diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 56ac4e9c0..d86cff228 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,39 +1,38 @@ - name: Docs # Controls when the workflow will run on: # Triggers the workflow on push or pull request push: - branches: [ dev, docs ] + branches: [dev, docs] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: - # Allow one concurrent deployment concurrency: group: "pages" cancel-in-progress: true - jobs: deploy-docs: # The type of runner that the job will run on runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 - - uses: actions/setup-python@v4 - + - uses: actions/setup-python@v5 + with: + python-version: '3.12.3' - run: | pip install --upgrade pip && pip install mkdocs mkdocs-gen-files pymdown-extensions \ mkdocs-git-revision-date-plugin mkdocs-autolinks-plugin \ - mkdocs-awesome-pages-plugin + mkdocs-awesome-pages-plugin + - run: git config user.name 'github-actions[bot]' && git config user.email 'github-actions[bot]@users.noreply.github.com' - name: Publish docs diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index f07c4ae1a..499270de5 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -1,27 +1,43 @@ name: CI -on: [push, pull_request] +on: + push: + pull_request: + branches: + - master + - dev + - main jobs: - - build: - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 container: - image: alpine:3.16 + image: alpine:3.21 strategy: matrix: - model: ["TS100", "TS80", "TS80P", "Pinecil", "MHP30", "Pinecilv2", "S60", "TS101"] + model: + [ + "TS100", + "TS80", + "TS80P", + "Pinecil", + "MHP30", + "Pinecilv2", + "S60", + "S60P", + "T55", + "TS101", + ] fail-fast: true steps: - name: Install dependencies (apk) - run: apk add --no-cache gcc-riscv-none-elf gcc-arm-none-eabi newlib-riscv-none-elf newlib-arm-none-eabi findutils python3 py3-pip make git bash + run: apk add --no-cache gcc-riscv-none-elf g++-riscv-none-elf gcc-arm-none-eabi g++-arm-none-eabi newlib-riscv-none-elf newlib-arm-none-eabi findutils python3 py3-pip make git bash - name: Install dependencies (python) - run: python3 -m pip install bdflib + run: python3 -m pip install --break-system-packages bdflib - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: true @@ -37,32 +53,26 @@ jobs: - name: Copy license files run: cp LICENSE scripts/LICENSE_RELEASE.md source/Hexfile/ + - name: Generate json index file + run: ./source/metadata.py ${{ matrix.model }}.json + - name: Archive ${{ matrix.model }} artifacts - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: ${{ matrix.model }} path: | source/Hexfile/${{ matrix.model }}_*.hex source/Hexfile/${{ matrix.model }}_*.dfu source/Hexfile/${{ matrix.model }}_*.bin + source/Hexfile/${{ matrix.model }}.json source/Hexfile/LICENSE source/Hexfile/LICENSE_RELEASE.md if-no-files-found: error - - name: Generate json index file - run: ./source/metadata.py ${{ matrix.model }}.json - - - name: Archive ${{ matrix.model }} index file - uses: actions/upload-artifact@v3 - with: - name: metadata - path: source/Hexfile/${{ matrix.model }}.json - - build_multi-lang: - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 container: - image: alpine:3.16 + image: alpine:3.21 strategy: matrix: model: ["Pinecil", "Pinecilv2"] @@ -70,11 +80,11 @@ jobs: steps: - name: Install dependencies (apk) - run: apk add --no-cache gcc-riscv-none-elf newlib-riscv-none-elf findutils python3 py3-pip make git bash musl-dev + run: apk add --no-cache gcc-riscv-none-elf g++-riscv-none-elf gcc-arm-none-eabi g++-arm-none-eabi newlib-riscv-none-elf newlib-arm-none-eabi findutils python3 py3-pip make git bash musl-dev - name: Install dependencies (python) - run: python3 -m pip install bdflib + run: python3 -m pip install --break-system-packages bdflib - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: true @@ -85,48 +95,61 @@ jobs: run: echo "GITHUB_CI_PR_SHA=${{github.event.pull_request.head.sha}}" >> "${GITHUB_ENV}" - name: Build ${{ matrix.model }} - run: make -C source/ -j$(nproc) model="${{ matrix.model }}" firmware-multi_compressed_European firmware-multi_compressed_Bulgarian+Russian+Serbian+Ukrainian firmware-multi_Chinese+Japanese + run: make -C source/ -j$(nproc) model="${{ matrix.model }}" firmware-multi_compressed_European firmware-multi_compressed_Belorussian+Bulgarian+Russian+Serbian+Ukrainian firmware-multi_Chinese+Japanese - name: Copy license files run: cp LICENSE scripts/LICENSE_RELEASE.md source/Hexfile/ + - name: Generate json index file + run: ./source/metadata.py ${{ matrix.model }}_multi-lang.json + - name: Archive ${{ matrix.model }} artifacts - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: ${{ matrix.model }}_multi-lang path: | source/Hexfile/${{ matrix.model }}_*.hex source/Hexfile/${{ matrix.model }}_*.dfu source/Hexfile/${{ matrix.model }}_*.bin + source/Hexfile/${{ matrix.model }}_multi-lang.json source/Hexfile/LICENSE source/Hexfile/LICENSE_RELEASE.md if-no-files-found: error - - name: Generate json index file - run: ./source/metadata.py ${{ matrix.model }}_multi-lang.json + upload_metadata: + needs: [build, build_multi-lang] + runs-on: ubuntu-24.04 - - name: Archive ${{ matrix.model }} index file - uses: actions/upload-artifact@v3 + steps: + - name: Download all prebuilts + uses: actions/download-artifact@v5 with: - name: metadata - path: source/Hexfile/${{ matrix.model }}_multi-lang.json + path: source/Hexfile/ + merge-multiple: true + - run: ls -R source/Hexfile + - name: Upload JSONs in bulk as metadata + uses: actions/upload-artifact@v4 + with: + name: metadata + path: source/Hexfile/*.json + if-no-files-found: error tests: - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 container: - image: alpine:3.16 + image: alpine:3.21 steps: - name: Install dependencies (apk) run: apk add --no-cache python3 py3-pip make git bash findutils gcc musl-dev - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: true - name: Install dependencies (python) - run: python3 -m pip install bdflib + run: python3 -m pip install --break-system-packages bdflib - name: Run python tests run: ./Translations/make_translation_test.py @@ -134,52 +157,58 @@ jobs: - name: Run BriefLZ tests run: make -C source/ Objects/host/brieflz/libbrieflz.so && ./Translations/brieflz_test.py - check_c-cpp: - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 container: - image: alpine:3.16 + image: alpine:3.21 steps: - name: Install dependencies (apk) run: apk add --no-cache make git diffutils findutils clang-extra-tools bash - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: true - name: Check format style with clang-format run: make clean check-style + check-settings-docs: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v5 + - name: Run the menu docs generator + run: python Translations/gen_menu_docs.py + - name: Check that Documentation/Settings.md didn't change + run: git diff --exit-code check_python: - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 container: - image: alpine:3.16 + image: alpine:3.21 steps: - name: Install dependencies (apk) run: apk add --no-cache python3 py3-pip make git black - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: true - name: Install dependencies (python) - run: python3 -m pip install bdflib flake8 + run: python3 -m pip install --break-system-packages bdflib flake8 - name: Check python formatting with black - run: black --check Translations + run: black --diff --check Translations - name: Check python with flake8 run: flake8 Translations - check_shell: name: check_shell - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: shellcheck uses: reviewdog/action-shellcheck@v1 with: @@ -188,19 +217,23 @@ jobs: exclude: "./.git/*" # Optional. check_all_files_with_shebangs: "false" # Optional. - - check_readme: - runs-on: ubuntu-20.04 + check_docs: + runs-on: ubuntu-24.04 container: - image: alpine:3.16 + image: alpine:3.21 steps: - name: Install dependencies (apk) - run: apk add --no-cache git + run: apk add --no-cache git bash grep - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: submodules: true + fetch-tags: true + fetch-depth: 0 + + - name: Git ownership exception + run: git config --global --add safe.directory /__w/IronOS/IronOS && git config --global safe.directory "$GITHUB_WORKSPACE" - - name: Check autogenerated Documentation/README.md - run: /bin/sh ./scripts/deploy.sh docs_readme + - name: Check and verify documentation + run: ./scripts/deploy.sh docs diff --git a/.gitignore b/.gitignore index c8e8df7fd..dac85f240 100644 --- a/.gitignore +++ b/.gitignore @@ -215,3 +215,4 @@ Logo GUI/TS100 Logo Editor/TS100 Logo Editor/bin/ # Tests/linters/sanitizers source/check-style.log +.ash_history diff --git a/Development Resources/Hex/DO NOT FLASH_Flash Backup.hex b/Development Resources/Hex/DO NOT FLASH_Flash Backup.hex deleted file mode 100644 index 6d09c53e2..000000000 --- a/Development Resources/Hex/DO NOT FLASH_Flash Backup.hex +++ /dev/null @@ -1,2113 +0,0 @@ -:020000040800F2 -:2000000028310020613300087D3300088133000885330008893300088D330008000000000B -:20002000000000000000000000000000913300089533000800000000993300089D33000878 -:2000400000F09ABF00F026B800F024B800F022B800F020B800F01EB800F01CB800F01AB8DF -:2000600000F018B800F016B800F014B800F012B800F010B800F0F2BF00F0D8BF00F083BF7A -:2000800000F091BF01F014B801F01CB8A1330008A5330008DFF800F000000000F8B500F07E -:2000A0006BFFDFF85C4A04F50A750146284600F03FFDDFF8506A4FF400520021304600F053 -:2000C000E7FF06F200474FF4B0720FF6AC41384600F0E8FF0B222946384600F0E3FF0FF262 -:2000E000600518222946304600F0DCFF1822294606F5007000F0D6FFDFF80C0AC6F8160413 -:20010000A022DFF8081A06F5C06000F0CBFF50220FF2FC1106F5006000F0C4FF40220FF25E -:20012000402106F5206000F0BDFFA0680021C171017241716068C1604161C1618161F1BD7A -:20014000F8FFFFFFFFFFFF6F0007800009A0000BC000FFFFFFFF0F0070B50D46B5F5805F37 -:2001600008D14FF400720146DFF89809BDE8704000F098BFB5F5205F08D14FF40072014698 -:20018000DFF88C09BDE8704000F08CBFB5F5804F08D14FF400720146DFF87809BDE8704068 -:2001A00000F080BFB5F51A4F3CD3DFF858694FF40072014606F5C06000F074FFDFF840497C -:2001C0004FF40072314604F1280000F06BFFA068017A002926D1C07900280FD1B5F52A4F75 -:2001E00004D300F04FFAA168087270BD2088002818D000F047FAA168087270BD012811D19B -:200200002088002807D0B5F51C4F04D300F093FBA168087270BDB5F52C4F03D300F08BFBAC -:20022000A168087270BD10B50446002907D14FF400720FF64411BDE8104000F033BFB1F572 -:20024000805F07D14FF40072DFF8B818BDE8104000F028BFB1F5205F07D14FF40072DFF836 -:20026000B018BDE8104000F01DBFB1F5804F07D14FF40072DFF89C18BDE8104000F012BFB2 -:20028000B1F5004F0CD14FF40072002100F000FFA0220FF644412046BDE8104000F002BF6F -:2002A000B1F5024F0CD14FF40072002100F0F0FE50220FF25C012046BDE8104000F0F2BEEB -:2002C0006FF40240401841F2FF7290420DD24FF400720021204600F0DBFE40220FF28001E3 -:2002E0002046BDE8104000F0DDBEB1F51A4F4FF4007206D3DFF820182046BDE8104000F021 -:20030000D1BE00212046BDE8104000F0C1BE00007B00380031004200320031003700330070 -:2003200033002D0036003800440039002D0034003000350039002D00410035003700330066 -:200340002D004500410030004400320033003200450039003300320031007D00000000004E -:200360002E202020202020202020203200478A5A7945794500008A5A794504000000000090 -:200380002E2E2020202020202020201000478A5A7945794500008A5A794500000000000088 -:2003A0002DE9F84F2024DFF85C672AE0522805D1697A442902D1A97A592921D0552805D19C -:2003C000697A532902D1A97A452919D0452805D1697A522902D1A97A522911D04E2805D132 -:2003E000687A4F2802D1A87A542809D04520287252206872A872DFF8080780680321017290 -:020000040800F2 -:200400002034B4F5007F80F21381A01900F20045002028732878E528F2D00028F0D0E87AF6 -:200420002028EDD1287A482836D1697A452933D1A97A582930D1DFF8C876A87EE97E00EB16 -:2004400001200005000D38804FF47A7000F03AFEB8680021C171017A002904D002290FD067 -:20046000042907D012E052212972442169725921A9720BE04521297252216972A97205E069 -:200480004E2129724F2169725421A972E97D491CE97503210172B3E741287BD1697A442918 -:2004A00078D1A97A522975D1DFF85476A87EE97E00EB01200005000D38804FF47A7000F0EE -:2004C00001FED7F80880002088F8070088F80800D7F80490C9F800004FF0020A07E098F8B1 -:2004E000080040F0040088F808000AF1010ABAF10A0F27DA96F800063028F0D196F801062B -:200500007828ECD10AEB060090F80016A1F13002D2B20A2A08D3A1F14102D2B2062A03D32F -:200520006139C9B20629DAD2D9F800100901C9F800108B4690F8000600F024FA5844C9F845 -:200540000000D2E798F8080000281AD1D9F80000DFF8C815884203D300F025FD002806D101 -:200560004E2028724F2068725420A8720EE0B8680121C17153202872452068725420A87260 -:2005800004E04520287252206872A872B8680321017235E7422830D1697A49292DD1A97A5E -:2005A0004E292AD1DFF85875A87EE97E00EB01200005000D38804FF47A7000F083FDB86805 -:2005C000C179002906D14E2129724F2169725421A97205E052212972442169725921A97234 -:2005E000C179022901D10021C171C179012901D10221C1710321017202E753287FF4D6AEF4 -:20060000697A45297FF4D2AEA97A54297FF4CEAEDFF8EC74B868C17900297FF4F1AE5521C5 -:200620002972532169724521A97203210172E7E6BDE8F18F10B5DFF8C844A068007A032871 -:200640001ED100F04AFE0028FBD1002000F047FD4FF4C87000F036FD012000F040FD00F04F -:2006600049FEA068002101724171616800224A61CA6011462180C179022901D11146C1716D -:2006800010BD00002DE9F843DFF8744460680021016106E0A0680021417160680169491C0A -:2006A000016166683069B0F5007F80F04181A56869790E29F1D8DFE801F0091221313E5376 -:2006C00060768299A7C5D3E0EA00E6E7DFF83414401890F800063A2840F02881D3E0DFF889 -:2006E0002414401890F8000600F04CF90001A870002070616879401C6871CEE7AE78DFF8D5 -:200700000414401890F8000600F03CF98019A870A878E8706879401C6871BEE7DFF8E41304 -:20072000401890F8000600F02DF9000170606879401C6871B1E77768DFF8C813401890F8CD -:20074000000600F01FF9C0197060E87871680818E8707068000270606879401C68719CE7EE -:20076000DFF8A013401890F8000600F00BF9000128716879401C68718FE72F79DFF88413D9 -:20078000401890F8000600F0FDF8C01928717068297908187060E87829790818E870687957 -:2007A000401C687179E7D749401890F8000600F0E9F8000168706879401C68716DE76E78A4 -:2007C000D049401890F8000600F0DCF880196870E87869780818E8706879401C6871A978F5 -:2007E00000297FF45AAF801C687156E7C549401890F8000600F0C6F800017169E2688854FF -:020000040800F2 -:200800006879401C687148E77769D4F80C8017F80890BC49401890F8000600F0B3F84844A2 -:2008200007F80800E878716911F808100818E8707069401C7061A978884224D26879401EB8 -:2008400068712AE7EE78AF49401890F8000600F099F806EB0010E8706879401C68711CE777 -:20086000EE78A849401890F8000600F08BF88019E870E878002859D105E0A249401890F875 -:2008800000060D2852D16879401C687105E79D49401890F800060A2848D10020E871687888 -:2008A000042809D1D4F80C8098F8000098F80110090401EB0060B0606878012838D0002807 -:2008C0007FF4E8AE7068B168081870609349884201D202202DE00020706103E06068416940 -:2008E000891C416160684169A26892789142BFF4D1AE4068081800F01EFD60684169E26897 -:200900008B5C406808184D1CA668B678B54204D143F47F4100F0FEFC06E08918497803EBA0 -:20092000012189B200F0F6FC0428D7D0042000E00020BDE8F28338B50024714D00E0A41CF8 -:20094000B4F5007F1CD268680168C068401800F0F2FC68686B49611891F8002691F801169E -:2009600002EB012189B20268C068801800F0D2FC6968CA68921CCA600428E0D0042032BD7B -:20098000002032BD10B585B0044600A80FF2D411112200F0F5FCA4F16100C0B21A2800D2E6 -:2009A000203C002000E0401CC0B2102805D200A9415CE4B2A142F6D100E0002005B010BDF6 -:2009C00038B54F4CA2681378002B05D1400260614802A061012010701078012833D12569C7 -:2009E0006068806900280FD161692846FFF71BFC40229821284600F0EEFC60684FF4E0713A -:200A000081614020E0610CE040229821E069401900F0E1FC6068816940398161E069403017 -:200A2000E0614021012000F09FFD3021012000F00BFD606940306061A0694038A061384801 -:200A4000816840398160A06900280BD16068002181610846E0616061324803210170A06814 -:200A60000021017031BD70B5254C6268D3694033A5682E78002E05D1400220624802606260 -:200A8000012028702878012827D1002007E02569254E865D4E55401CD169491CD161D169E7 -:200AA0009942F4D3214D2888216A41182162636A181A6062C00506D10020D061A1F500715A -:200AC0002069FFF749FB164881682A88891A81604FF44051022000F0CBFC606A002803D064 -:200AE00010480078042809D160680021C1610121002000F0B7FEA0680021017070BD000067 -:200B0000000000201C040020188DDD40D80E00081C0600201C0800201C0A002000400008B1 -:200B2000EC2C0020B82C0020582C0020BA2C002010B41C2203E0303300F8013B121F1346C9 -:200B40005BB2002B0AD421FA02F303F00F031C460A2CF0DB373300F8013BEFE70021017001 -:200B600010BC70473031323334353637383941424344454600000000EB3C904D53444F5313 -:200B8000352E3000020108000200020010F80C00010001000000000000000000000029A2D2 -:200BA00098E46C4E4F204E414D4520202020464154313220202033C98ED1BCF07B8ED9B8B0 -:200BC00000208EC0FCBD007C384E247D248BC199E83C01721C83EB3A66A11C7C26663B077A -:200BE000268A57FC750680CA0288560280C31073EB33C98A461098F7661603461C13561EC7 -:020000040800F2 -:200C000003460E13D18B7611608946FC8956FEB82000F7E68B5E0B03C348F7F30146FC118A -:200C20004EFE61BF0000E8E600723926382D741760B10BBEA17DF3A66174324E740983C70C -:200C4000203BFB72E6EBDCA0FB7DB47D8BF0AC9840740C487413B40EBB0700CD10EBEFA0AD -:200C6000FD7DEBE6A0FC7DEBE1CD16CD19268B551A52B001BB0000E83B0072E85B8A5624C1 -:200C8000BE0B7C8BFCC746F03D7DC746F4297D8CD9894EF2894EF6C606967DCBEA03000098 -:200CA000200FB6C8668B46F86603461C668BD066C1EA10EB5E0FB6C84A4A8A460D32E4F757 -:200CC000E20346FC1356FEEB4A525006536A016A10918B4618969233D2F7F691F7F6428796 -:200CE000CAF7761A8AF28AE8C0CC020ACCB80102807E020E7504B4428BF48A5624CD136155 -:200D000061720B40750142035E0B497506F8C341BB000060666A00EBB04E544C4452202087 -:200D2000202020200D0A52656D6F7665206469736B73206F72206F74686572206D6564696E -:200D4000612EFF0D0A4469736B206572726F72FF0D0A507265737320616E79206B65792005 -:200D6000746F20726573746172740D0A00000000000000ACCBD855AA4446552056335F34EB -:200D8000325F4408000000000000000000008A5A794500000000000042200049006E006655 -:200DA000006F000F007272006D006100740069006F0000006E000000015300790073007495 -:200DC0000065000F00726D00200056006F006C00750000006D00650053595354454D7E3194 -:200DE00020202016005E63705D455D45000064705D45020000000000412E005F002E005440 -:200E00000072000F007F6100730068006500730000000000FFFFFFFF7E3120202020202053 -:200E200054524122004A8A5A7945794500008A5A7945050000100000E552415348457E3141 -:200E400045464D1200478A5A7945794500008A5A7945040000000000412E005400720061C5 -:200E60000073000F00256800650073000000FFFFFFFF0000FFFFFFFF5452415348457E311D -:200E80002020201200478A5A7945794500008A5A7945040000000000412E006600730065E6 -:200EA0000076000F00DA65006E0074007300640000000000FFFFFFFF46534556454E7E3143 -:200EC00020202012004D8A5A7945794500008A5A79450D00000000002E2020202020202036 -:200EE00020202010005E63705D455D45000064705D450200000000002E2E20202020202079 -:200F000020202010005E63705D455D45000064705D450000000000004247007500690064AB -:200F20000000000F00FFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF0149006E0064006532 -:200F40000078000F00FF6500720056006F006C00750000006D006500494E444558457E3150 -:200F600020202020007263705D455D45000064705D4503004C00000041480168426851189E -:200F800080684018704710B50446FFF7F5FF0A233C4A01463C4800F017F8844201D101202B -:200FA00010BD002010BD10B5FFF7E6FF37490C680A23344A0146344800F006F8844201D1EF -:200FC000012010BD002010BDF0B403F11506C3F14304C3F151050A330FE0C0EB40104FEA1E -:200FE000670C07EB9C7C4FEAAC0CA7EB8C07FF0021FA07F7FFB238185B1C1BB21F46B742A3 -:020000040800F2 -:20100000EBDB0DE0C0EB40104B1001EB93739B10A1EB8301C90022FA01F1C9B20818641C28 -:2010200024B22146A942EDDBF0BC704770B504460D461646FFF7B7FF002801D1002070BD4C -:20104000FFF79AFF0023324601462046FFF7BCFF854201D1012070BD002070BD70B5044665 -:201060000D461646FFF79FFF002801D1002070BD0023324629462046BDE87040A4E7000096 -:20108000E8F7FF1F011020D502DEC0DEFC3F000810B5044610460A460146204600F03EFC00 -:2010A000204610BD10B5044600F05AF9204610BD0FF27C11082802D201EB0010704701F141 -:2010C0008000704700214FF6FF7302E04F4A1360491C40F2DC5242439142F7D370474C49E0 -:2010E0004FF400620A614FF480520A61002808680BD120F4404040F440500860086820F4A8 -:20110000402040F440300860704720F4804040F430400860086820F4802040F430200860BC -:201120007047000080F308887047704710B500F029FC4FF4803000F03DFC00F055FC102020 -:2011400000F0BCFC022000F0AFFC324C6068324908436060206840F080702060012000F025 -:201160005CFC012000F05CFC392000F076FC0028FAD0022000F057FC00F05CFC0828FBD158 -:201180001420606140F60D20A0614FF42000E0610120BDE8104000F052BC80B501464FF083 -:2011A000006000F05DFD4FF4C06000F013FD14208DF8000001208DF801008DF802008DF8B6 -:2011C000030000A800F00BFD13208DF8000001208DF8010000208DF8020001208DF80300BD -:2011E00000A800F0FCFC01BD0C484FF6FF71C1600B4901600B4941600B484FF6FE71C160A5 -:201200000A4901604FF08831416070470C10014004080140001002400A846800000801408F -:201220008888880883B8BB8B000C014003888344312E33300000000000000000000000002C -:2012400053544D3332463130335438000000000056474D393631360000000000000000000F -:201260004D4355277320414443000000000000004E6F6E6500000000000000000000000077 -:2012800056332E3432410000000000000000000030000000000000000000000000000000C0 -:2012A0005669727475616C204D534400000000002D2D2D2D2D2D0000000000000000000035 -:2012C0000A48012101600021016041604FF4E051074A1180016000207047044801210160B9 -:2012E000002141600321016000207047405C0040222D00200448C0610221017203490162D3 -:20130000034A426208680047C42C00200C0300206403002038B504460D46104800F03AFC57 -:20132000052802D0342000F014FC29462046BDE8344000F0F5BB10B50446A0050CD10748EC -:2013400000F028FC052802D0342000F002FC2046BDE8104000F0C5BB10BD0000A086010079 -:2013600062B38B0708D0521E11F8013B00F8013B00F024808B07F6D1830740F0208000BFFF -:20138000103A07D330B4B1E83810103AA0E83810F9D230BC530724BFB1E80810A0E8081005 -:2013A00044BF51F8043B40F8043BD20724BF31F8022B20F8022B44BF0B7803707047083AE2 -:2013C00007D3B1E80810083A40F8043B40F804CBF7D25307E4E710B4490001F1804101F51E -:2013E000C041521C521009E010F8013B10F8014B43EA042321F8023B891C521EF4D110BC4B -:020000040800F2 -:201400007047490001F1804101F5C041521C521004E051F8043B20F8023B521EF9D17047A0 -:201420004FF6F8710840DFF8A4110860704710B4DFF89C2152F8203048F68F142340194379 -:2014400042F8201010BC704710B4DFF8842152F8203048F6BF742340CC0601D583F01003C3 -:20146000890601D583F0200342F8203010BC704710B4DFF85C2152F820304BF68F7423400B -:20148000CC0401D583F48053890401D583F4005342F8203010BC7047DFF8341151F820207D -:2014A0004BF68F731A4082F4405241F820207047DFF81C1151F8202048F68F631A4041F807 -:2014C00020207047DFF8081151F82020520409D551F8202092B248F68F731A4042F4804209 -:2014E00041F820207047DFF8E81051F82020520609D551F8202092B248F68F731A4042F095 -:20150000400241F820207047DFF8C020126892B202EBC000DFF8BC204908490042F8101090 -:201520007047DFF8A820126892B202EBC000DFF8A8204908490042F810107047DFF88C102D -:20154000096889B201EBC000DFF8881051F8100080B270471D49096889B201EBC0001E495D -:2015600051F8100080B27047184A126892B202EBC0001A4A42F810107047144A126892B2CB -:2015800002EBC000164A02EB40003F290AD34A091F23194200D1521E92B2910241F400414E -:2015A000016070474A08C90700D5521C92B29102016070470549096889B201EBC0000849C8 -:2015C00051F810008005800D70470000505C0040005C004000600040086000400460004075 -:2015E0000C6000400146C9B2090241EA1020704780B5AC4890F8201002290FD022D3042953 -:2016000002D014D305291DD1002180F820104FF440510220BDE80440FFF72ABFC17B2829E1 -:2016200010D1816A406ABDE8044000F073BB0121002000F017F94FF440510220BDE804400C -:20164000FFF716BF01BD38B5964CE57B0220FFF7B1FF60840246D8219348FFF7D2FE94F8B8 -:201660002000002802D0012803D016E0BDE831401FE02A2D05D1A16A606ABDE8344000F03E -:2016800078BB012000F01AF92421052000F03AFB00210220BDE83440E4E0022000F00EF92B -:2016A0002421052000F02EFB00210220BDE83440D8E010B500207B4C03E07B49415C01554D -:2016C000401C618C8842F8D3784862684260A26882601F290DD0022000F0F0F80020206055 -:2016E0001A21052000F00EFB00210120BDE81040B8E0E07B282801D02A280FD1617CA27C19 -:20170000120442EA0161E27C41EA0221227D11436162A17DE27D42EA0121A1622168644ABE -:2017200091427AD163490968627B914204D3A17B491EC9B210290BD3022000F0BFF82421C4 -:20174000052000F0DFFA00210120BDE8104089E000284AD003282CD008285AD00A2858D0DE -:2017600012282AD0152854D01A282ED01B2828D01D284ED01E2824D023282ED0252830D026 -:20178000282836D02A283AD02F283ED0552840D05A281ED088283CD08A283AD08F2838D0FE -:2017A0009E2836D0A82834D0AA2832D0AF2830D033E0BDE8104000F09DBABDE8104000F0AA -:2017C00063BABDE8104000F0A1BABDE8104000F089BABDE8104000F089BABDE8104000F077 -:2017E00062BABDE8104000F06DBABDE8104000F008BBA16A606ABDE8104000F08BBAA16A0F -:020000040800F2 -:20180000606ABDE8104000F0B4BABDE8104000F0DDBABDE8104000F0F8BA022000F04EF840 -:201820002021052000F06EFA00210120BDE8104018E010B50C4622469821FFF7CCFD21465D -:201840000120FFF791FE30210120FFF7FDFD1548032180F8201015488168091B81600021EB -:20186000017310BD10B50C46104B1349196018730D2298211846FFF7AEFD0D210120FFF729 -:2018800073FE0848052180F82010002C08D0042180F8201030210120BDE81040FFF7D4BDFA -:2018A00010BD0000982C0020582C0020EC2C002055534243102D00205553425380B5002877 -:2018C00003D002280ED006D301BD10210120BDE80440FFF7B9BD4FF480510220BDE80440D0 -:2018E000FFF7C6BD10210120FFF7AEFD4FF480510220BDE80440FFF7BBBD50F8041B61B176 -:2019000050F8042BD30744BFA9F101039A18002342F8043B091FFAD1EFE7704762F30F2281 -:2019200062F31F42401810F0030308D0C91A1FD3DB0748BF00F8012D28BF20F8022D130096 -:2019400030B414461546103928BF20E93C00FAD8490728BF20E90C0048BF40F8042D890062 -:2019600028BF20F8022D48BF00F8012D30BC7047C91818BF00F8012DCB0728BF00F8012DAC -:20198000704700004048016841F00101016041683E4A1140416001683D4A114001600168DD -:2019A00021F480210160416821F4FE01416000218160704734490A6822F480320A600A6866 -:2019C00022F480220A60B0F5803F03D0B0F5802F05D07047086840F48030086070470868EB -:2019E00040F4A0200860704710B582B0002000900446312000F031F80099491C00910028C2 -:201A000003D10098B0F5A06FF3D1312000F025F8002800D00124204616BD1E4908607047A8 -:201A20001E49086070471C490A68920850EA8200086070471848006800F00C0070471849F8 -:201A400008607047174A0029116802D008431060704721EA000010607047002142090A4B2D -:201A6000012A01D11A6804E0022A01D11A6A00E05A6A012300F01F0003FA00F0024200D0A9 -:201A80001946084670470000001002400000FFF8FFFFF6FE000042420410024060004242E9 -:201AA000D800424218100240DFF8D0100A6802F038020A600A68104308607047DFF8BC101A -:201AC0000A6822F010020A600A68104308607047DFF8AC00DFF8AC100160DFF8AC100160B7 -:201AE000704770B5054640F6FF76304600F052F8042814D1DFF89440206840F0020020606E -:201B00006560206840F040002060304600F042F8012804D0216841F6FD721140216070BDBD -:201B200070B504460D460F2000F034F804280FD1164E306840F00100306025800F2000F00B -:201B400029F8012804D0316841F6FE721140316070BD0F490860704704200D490A68D207DC -:201B600001D5012070470A68520701D5022070470968C90600D503207047000000200240EC -:201B80000420024023016745AB89EFCD102002400C20024010B50446FFF7DEFF04E000F089 -:201BA0000BF8FFF7D9FF641E012801D1002CF6D1002C00D1052010BD81B000200090FF20F5 -:201BC000009002E00098401E009000980028F9D101B07047274908432749086070472DE9BB -:201BE000F04105782B460121C278002A2FD0224A126802F4E062C2F5E062120A23F00303F5 -:020000040800F2 -:201C00001B4C1F5905F00305ED00FF26AE40B74390F801C0C2F1040E0CFA0EFC90F802E066 -:201C20004FF00F0828FA02F202EA0E0242EA0C021201AA4032403A431A51007842110F4B86 -:201C400000F01F0001FA00F043F8220006E05811064A05F01F03994042F82010BDE8F0811E -:201C6000074A1140084307490860704780E100E000E400E00000FA050CED00E000E100E06A -:201C800080FFFF1F08ED00E08749087CC00702D58648052105E00FF23020C97C252900D350 -:201CA0002421FFF7C6BD824800218180022181710021C1714172022181720021C1720C21C8 -:201CC000FFF7B7BD7B48002101800F218170FF21C17000218180022181710021C171082110 -:201CE000FFF7A7BD04217448FFF7A3BD08217348FFF79FBD6C48C17C132900D31221704832 -:201D0000FFF797BD6E4A90701173704701210020FFF7A8BD70B504460D466A4E307800289F -:201D20001FD12A462146282000F08CF800281FD05D48007B000607D5022030702946204670 -:201D4000BDE87040FEF73CBE0220FFF7B7FD24210520FFF7D7FF01210846BDE87040FFF782 -:201D600081BD022804D12046BDE87040FEF728BE70BD10B5534C2278002A20D10A460146B3 -:201D80002A2000F05FF800281FD04748007B000608D4012020704FF440510220BDE8104013 -:201DA000FFF766BB0020FFF789FD24210520FFF7A9FF00210120BDE81040FFF753BD012A00 -:201DC00003D1BDE81040FEF74EBE10BD80B536488168002908D1007C400705D401210020F0 -:201DE000BDE80440FFF73EBD0220FFF767FD24210520FFF787FF00210120BDE80440FFF786 -:201E000031BD01210020FFF72DBD80B526488168002903D10020FFF751FD09E0007B00065B -:201E200003D50020FFF74AFD02E00220FFF746FD20210520FFF766FF00210120BDE8044044 -:201E4000FFF710BD80B55118B1F5805F11D92A2802D10220FFF732FD0020FFF72FFD2121C2 -:201E60000520FFF74FFF00210120FFF7FBFC002002BD0D498968B1EB422F12D02A2803D18F -:201E80000220FFF71BFD02E00020FFF717FD24210520FFF737FF00210120FFF7E3FC002039 -:201EA00002BD012002BD0000982C0020FC2C0020F0030020042D0020180400200C04002087 -:201EC000DC030020B82C002000800202200000005669727475616C20444655204469736BCA -:201EE00000000000000000000000000010B5DFF8C047002804D1206801210182002010BD28 -:201F0000DFF8B00700680068804720680A3010BD80B5DFF89C070068C178DFF89C27527859 -:201F20008A420DD38278002A0AD18288002A07D18172DFF88007006840688047002002BDE3 -:201F4000022002BD10B5DFF86847002804D1206801210182002010BDDFF8580700688068B8 -:201F6000804720680C3010BD10B5DFF844472068C1784079DFF84427126892699047216851 -:201F80008A7A002A14D0002812D1087900280FD1887800280CD1DFF81C070068C068804745 -:201FA00020684179C1722068C1780173002010BD022010BD10B5DFF8F8160968002803D184 -:201FC00002200882002010BDDFF8F4460020208008787F22104218D1487A0146890603D5CB -:201FE000002141F0020121702178400609D541F001002070DFF8BC060068006980472046E5 -:020000040800F2 -:2020000010BD01F0FE002070F4E700F07F02012A01D1204610BD00F07F0002281BD14879B2 -:2020200000F00F01DFF89C26000652F8210008D500F030001028DDD1002040F001002070D2 -:20204000D8E700F44050B0F5805FD3D1002040F001002070CEE7002010BD70B5DFF8500640 -:202060000068017811F07F0105D1417A01F0DF014172002070BD022954D14188002951D138 -:20208000017900294ED1417921F08005DFF834460A0654F8252002D502F0300201E002F46A -:2020A0004052DFF814361B789D423BD2002A39D0807A002836D0080654F825000BD500F044 -:2020C0003000102827D12846FFF70DFA30212846FFF7BAF91FE000F44050B0F5805F1AD1DB -:2020E0004BF68F76002D0CD1DFF8DC0590F82C100020FFF742FA2068304080F44050206046 -:2021000009E02846FFF7DEF954F82500304080F4405044F82500DFF89C0500684069804705 -:20212000002070BD022070BD38B5DFF884050268537923F08000DFF88C151C0651F82040AA -:2021400002D504F0300401E004F44054DFF868552D78A84207D25588002D04D1002C02D03A -:20216000927A002A01D1022032BD1A0651F8202007D548F6BF731A4082F0100241F82020FA -:2021800006E04BF68F731A4082F4805241F82020DFF82005006880698047002032BD80B5A3 -:2021A000DFF80C050068417A41F020014172DFF804050068C0698047002002BDDFF8F0240D -:2021C0001268538A002804D18888C01A108200207047086818187047F8B5DFF8D4442068DD -:2021E00000F110052E88A968080016D0002E14D0A888864200D906463046884707462888B3 -:20220000801B28806888301868800020FFF7A2F9324601463846FFF7F4F8288800280CD0D7 -:20222000DFF8A8044FF44051018000210846FFF79BF9DFF89C04302101802888A9888842D9 -:2022400003D3206803210172F1BD002803D0206805210172F1BD0FD1206806210172DFF838 -:202260007404006880B2DFF87014002241F81020DFF85C0430210180F1BD2DE9F041DFF891 -:202280003044206800F110052F88002F08D1007A042805D10726DFF838041021018027E008 -:2022A000A888B84201D3042600E00226874200D907463846A968884780460020FFF73EF98E -:2022C0003A4601464046FFF786F839460020FFF74BF92888C01B2880688838186880DFF832 -:2022E000F00330210180DFF8E4034FF44051018020680672BDE8F08138B50220DFF8B04317 -:2023000021684D780A787F231A4230D1092D02D1FFF7FEFD3FE0052D0FD1C878802808D201 -:202320008878002805D18888002802D1887A002801D008204AE000202DE0032D0BD1CA78CC -:20234000012A28D18A88002A25D1497A890622D5FFF725FF1FE0012D1DD1CA78012A1AD151 -:202360008A88002A17D1497A89060DD413E002F07F01012904D10B2D0DD1FFF7F5FD0AE0BA -:20238000022908D1012D02D1FFF767FE03E0032D01D1FFF7C9FE002809D02846DFF81C13C6 -:2023A000096849698847032801D109200EE0002801D008200AE00620C649096889B2C64A1B -:2023C000002342F81130C24930220A802168087231BD38B5B64C206841780025062916D11C -:2023E00001787F22114279D18078012803D1B3480068C56972E0022803D1B0480068056A81 -:020000040800F2 -:202400006CE003286AD1AD480068456A66E0002940D14288002A3DD1C288022A3AD1027980 -:20242000002A37D101787F22114204D18288002A01D1AA4D52E001F07F02012A0DD129460F -:2024400040799E4A126892699047002846D12068807A002842D0A14D40E001F07F010229EA -:202460003CD1407900F00F0100F07002954B000653F8210002D500F0300001E000F4405086 -:202480008D4B1B78994229D2002A27D1002825D0924D23E0082905D100787F2108421DD183 -:2024A0008F4D1BE00A2919D1017801F07F01012914D1817A002911D0418800290ED10179DF -:2024C00000290BD1C188012908D1294640797B4A126892699047002800D1824D20682900F9 -:2024E00007D000214182206885610846A847002006E040787149096809698847032805D04C -:2025000021680A8A4FF6FF739A4203D120680921017231BD022801D0002A02D1082008728A -:2025200031BD087800060CD5C888904200D2088220686249096891F82C108182BDE8314046 -:202540009BE60320087261484FF44051018031BD38B56048006880B2634931F8100040001D -:2025600000F1804505F5C045514C2068017A092917D015F8011B0170206815F8011B4170F1 -:20258000AD1C35F8020BFFF72DF821684880AD1C35F8020BFFF726F82168888020686988AB -:2025A000C1802068012101722068C088002802D1FFF7A2FE01E0FFF70CFFBDE8314042E042 -:2025C00010B53B4C2068017A022901D0042904D1FFF753FE2068007A16E0062913D14178A3 -:2025E00005290AD101787F22114206D1C07800F044F830480068006A804730480068806851 -:202600008047082000E0082021680872BDE8104019E010B5264C2068007A032801D0052870 -:2026200004D1FFF7D9FD2068007A08E0072805D122480068C0688047082000E00820216890 -:202640000872BDE8104080B51F4890F82C100020FEF793FF16480068017A082906D11B4957 -:202660004FF480520A801A4910220A80007A092801D1012002BD002002BD70B40E49097864 -:202680000022104C48F68F7609E01346DBB254F82350ADB235401D4344F82350521C8A42CE -:2026A000F3D340F080001149086070BC70470000E02C0020E82C002014040020E42C002037 -:2026C000182D0020005C00400C0300201C2D00201E2D0020505C004004600040B51F00088A -:2026E000ED1E0008451F0008086000404C5C004070470000F8B58478303CE4B20A2C00D261 -:202700002246C478303CE4B20A2C00D2234600783038C0B20A2800D20146002413E02018B6 -:202720000FF2C415182606FB01477F5D80F8607006FB02477F5D80F8907006FB0346755D5A -:2027400080F8A850641C5548182CE8DB002409E00C220146204600EB40039800C0B200F0D5 -:2027600004F8641C082CF3DBF1BD70B50C46154600F1200600213046C0B200F054F86D1C76 -:2027800021462846C0B200F03DF8044601213046C0B200F048F821462846C0B2BDE87040AD -:2027A00030E04049086040483C2202700968C9B23B4800F0D1B910B58CB000A80FF2F0013C -:2027C0003022FEF7DDFD0020354903E000AA825C4254401C2E28F9DB344C4FF48071204699 -:2027E00000F02BFA0220FEF76DFC4FF48071204600F021FA0220FEF765FC2E20FFF7D1FF13 -:020000040800F2 -:202800000CB010BD10B50C46254940220A70012203E014F8013B5354521C8242F9DBFFF7DD -:20282000C0FF204610BD30B583B000AA0FF2B00330CB30C28DF80500012902D1B1208DF866 -:2028400001000020164903E000AA825C4254401C0828F9DB0820FFF7A4FF37BD10B50021FC -:202860002020FFF7E0FF0E4C402020707F220021601CFEF70DFC8020FFF793FF0121202033 -:20288000FFF7D1FF402020707F220021601CFEF7FFFB8020BDE8104083E700003402002000 -:2028A0001C2400200C2D0020242D00200008014080AE80D5805280A8800F80C080D3800086 -:2028C000804080A0808D801480DA8002808180E080D980F180DB803080A480A680AF0000EC -:2028E00080B080218020807F00E010080810E00000000000000F102020100F0000000000FA -:20290000001010F800000000000000000020203F2020000000000000007008080888700060 -:20292000000000000030282422213000000000000030088888483000000000000018202090 -:2029400020110E00000000000000C02010F800000000000000070424243F2400000000009A -:2029600000F8088888080800000000000019212020110E000000000000E010888818000086 -:2029800000000000000F112020110E000000000000380808C8380800000000000000003F29 -:2029A0000000000000000000007088080888700000000000001C222121221C000000000059 -:2029C00000E010080810E000000000000000312222110F0000000000000000000000000072 -:2029E00000000000003030000000000000000000022000E0401EFDD1704738B504460D4608 -:202A0000012D03D12146534800F015F9002D05D121465048BDE8344000F00FB931BD80B5BE -:202A200001210820FFF70EF8C020ADF8000014208DF8030003208DF8020000A9454800F03F -:202A4000A3F800214020FFF7D8FF01218020FFF7D4FF01214020FFF7D0FF0520FFF7C8FFD9 -:202A600000218020FFF7C9FF0520FFF7C1FF00214020FFF7C2FF01BD80B500214020FFF75A -:202A8000BCFF00218020FFF7B8FF0520FFF7B0FF01214020FFF7B1FF0520FFF7A9FF012136 -:202AA0008020FFF7AAFF0520FFF7A2FF00214020FFF7A3FF0520BDE8024099E738B504463F -:202AC00008250EE000218020FFF797FF0520FFF78FFF01214020FFF790FF0520FFF788FF3C -:202AE00064002846451EC0B200280AD000214020FFF783FF2006E5D501218020FFF77DFF20 -:202B0000E4E700214020FFF778FF01218020FFF774FFFF2400E0641EE4B2002C18D005207D -:202B2000FFF766FF80210B4800F07EF80028F2D101214020FFF761FF0520FFF759FF002189 -:202B40004020FFF75AFF0520FFF752FF012032BD002032BD000C014070B504460D461646D0 -:202B6000FFF75DFF7000C0B2FFF7A8FF03E014F8010BFFF7A3FF2846451EC0B20028F6D1BF -:202B8000BDE8704078E70000F0B40023CC7804F00F02E40601D58C7822430C88E4B2002CF2 -:202BA0001CD0046803E0482D00D106615B1C082B13D2012505FA03F635460F882F40AF420E -:202BC000F4D19D000F27AF40BC4302FA05F52C43CD78282DE7D14661E8E704600B88B3F5A3 -:202BE000807F1FD34468002319E0012503F1080605FA06F635460F882F40AF420ED19D000B -:020000040800F2 -:202C00000F27AF40BC4302FA05F52C43CD78282D00D14661CD78482D00D106615B1C082B7D -:202C2000E3D34460F0BC704700228068084200D00122104670470161704741617047000011 -:202C400080B500F007F99348006800218172FEF737FB9148002141604FF404418F4A118044 -:202C600001608F480021016001BD10B58D4800218172884800688C49C97941720020FEF717 -:202C8000CFFB4FF400710020FEF7D1FB20210020FEF7DAFB18210020FEF743FC834C94F8C2 -:202CA0002C100020FEF769FC58210020FEF72CFC0020FEF7FDFB0020FEF7EEFB002101205B -:202CC000FEF7B5FB98210120FEF71EFC20210120FEF7BAFB00210120FEF7CAFB002102201B -:202CE000FEF7A5FBD8210220FEF71BFC94F82C100220FEF742FC4FF440510220FEF7B8FB5D -:202D000000210220FEF7A0FB94F82C100020FEF734FC0020FEF7C0FB0020FFF7AEFC60489B -:202D20000121016062486349016063480021017010BD58480068807A002800D1704780B568 -:202D40005748052101600120FEF7CDFB0220FEF7B9FB59480021017001BD55480068554910 -:202D6000884202D00220FEF7A9BD70474C480421016070477047704780B546490A68137883 -:202D800003F07F03212B10D1FE280ED1508800280BD19088002808D1D088012805D10FF23F -:202DA000A100030003D1022002BD022002BD9061086800214182084600F042F8002002BD3D -:202DC00080B5344909680A7802F07F02212A18D1FF2816D14888002813D18888002810D1A4 -:202DE000C88800280DD10120FEF77DFB0220FEF769FB2F482F4901602F48002101700846CD -:202E000002BD022002BD002901D002207047002801D002207047002070472849FFF7CEB9A8 -:202E20002749FFF7CBB91B490968C978062901DB00207047234A02EBC101FFF7BFB9000026 -:202E4000002805D11348006801210182002070471D4870471D48016842688068002900D1BF -:202E6000704710B41A4B99700C0A1C710C0C9C71090E19729A72110A1973110C9973110E04 -:202E800019749874010A1975010C9975000E187610BC7047E02C0020405C0040222D00204F -:202EA000142D0020C42C0020703100080C030020982C002055534243B82C0020FC03002095 -:202EC000040400203C030020102D0020E8F7FF1F880300202DE9F0416F4C48F6BF764BF6B0 -:202EE0008F7721E05FEA084006D5206840F68F7108402060FFF78DFB206838402988CA04DC -:202F000001D580F48050890401D580F400502060206830406988CA0601D580F01000890652 -:202F200001D580F020002060616C5C480180090478D547F6FF716164018811F00F01584DAE -:202F4000297046D1574D216801F440512980216801F0300169802168394081F40051216088 -:202F60002168314081F0200121600088C00616D4206880B248F60F7108402060FFF720FBBB -:202F8000D4F800801FFA88F818F4084FB4D0206840F68F7108402060FFF7DAFAACE7D4F8B6 -:202FA00000801FFA88F85FEA086007D5206880B248F60F7108402060FFF702FB5FEA085097 -:202FC00090D5206840F68F7108402060FFF7C0FA92E754F821801FFA88F85FEA08400DD5E4 -:202FE00054F8210040F68F72104044F8210028782D4901EB800050F8040C80475FEA08602E -:020000040800F2 -:2030000092D5287854F8201089B248F60F72114044F820102878254901EB800050F8040CA4 -:20302000804781E7BDE8F08170B51D4C1A4D2BE047F6FF720260088800F00F00207055F8CF -:203040002060B6B231040DD555F8201040F68F72114045F820102078134901EB800050F857 -:20306000040C804730060FD5207855F8201089B248F60F72114045F8201020780B4901EBBA -:20308000800050F8040C80470948026803490A801204CDD470BD0000005C0040202D002013 -:2030A000252D00201C2D0020C0030020A4030020445C00402DE9F04500F10801026801EB10 -:2030C0008202406800F001034008400002EB80000025AA460024A0460126374602E000270F -:2030E000F44511D1824201D1BDE8F08552F804CB03B1CC4452F804EBE644F1E70D686D18F3 -:20310000091D51F804ABAA445545F7D066B115F9014B0026012705E00D686D18091D51F835 -:2031200004ABAA445545F7D0002C12D50FB115F8018BF445D3D00CF8018B641CF9D40AE082 -:20314000F44518BF5545CBD015F8018B0CF8018B641E002CF4D50126C2E7000012010002A5 -:203160000000004083042057000201020301000009022000010100C03209040000020806CC -:2031800050040705810240000007050202400000040309042603530054004D0069006300BF -:2031A00072006F0065006C0065006300740072006F006E0069006300730000002603530017 -:2031C00054004D003300320020004D006100730073002000530074006F00720061006700A5 -:2031E0006500000010035300540020004D00610073007300FDF79AFFFDF7F6FF1A480068BC -:2032000080050ED5FDF7CFFE18480168184A1140B1F1005F04D144680068FDF783FFA047C2 -:20322000FEE70A20FDF74EFF0020FDF758FFC820FDF748FF0120FDF752FF0020FDF7ADFF8A -:20324000FEF758F8FCF72AFFFFF7B5FAFFF706FB0FF22000FFF74EFAFEF73AFCFDF7A0F85B -:20326000FDF7E8F9F8E7000008080140004000080000FF2F332E34330000000070B50D4C8D -:203280000D4D286820800D4E208831880840400505D50B48406880474FF6FF30286020881B -:2032A00031880840000403D5BDE87040FFF712BE70BD0000202D0020445C0040222D00202D -:2032C0000C030020FEF794B9FEF7BDB910B5074979441831064C7C44163404E0081D0A6820 -:2032E000511888470146A142F8D110BD080000003000000007E6FFFF0C2900001C0400203E -:2033000000000000B1FDFFFF02000000020000009800000096010000000000201C0400008E -:2033200000F009F8002801D0FFF7D0FF0020FFF761FF00F002F80120704700F001B80000FD -:203340000746384600F002F8FBE70000C046C046024A11001820ABBEFBE700BF2600020003 -:2033600001488047014800472D11000871330008C046C046C046C046FFF7D2FFFFF7FEBF29 -:20338000FFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBF95 -:2033A000FFF742BEFFF76ABFFC000F1C2C00203C2C0020452C00201C2A0020810081008183 -:2033C000008100DC000104FCFC04070C0810E00000407FFC40076020180F000004FCFB845C -:2033E00007E40C100000407F40FC000003FC000204FC04FB000604FC0400001F20FB400146 -:020000040800F2 -:20340000201FFA00016060F600016060F9000078FB04018878FC0007605048444241407018 -:20342000F000016060F60002E01808FD04020818E0FD00020F3020FD400220300FFB0002E7 -:203440000808FCF7000240407FFD40E50027412C00086B2C0008752D0008772D0008792D0F -:203460000008C12D0008072E00081B2E0008212E0008272E0008FC000040FD00049031000E -:203480000804FD00049431000826FD0004BC31000826FD0004880300201AFD0004E4310034 -:2034A0000810FD0032F1260008332D0008F1260008F1260008F12600085B2D0008F126003A -:2034C00008F12600086D2D00081A03530054004D0033003200310030F30038C5320008F131 -:2034E000260008F1260008F1260008F1260008F1260008F1260008F1260008C9320008F1F0 -:20350000260008F1260008F1260008F1260008F126000870FA00000AF1000008FC00000296 -:20352000FD00045C31000812FD00047031000820FC000006FA00040301000003FD00000015 -:20354000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8B -:20356000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6B -:20358000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4B -:2035A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2B -:2035C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0B -:2035E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEB -:20360000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFCA -:20362000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAA -:20364000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8A -:20366000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6A -:20368000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4A -:2036A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2A -:2036C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0A -:2036E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEA -:20370000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC9 -:20372000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA9 -:20374000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF89 -:20376000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF69 -:20378000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF49 -:2037A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF29 -:2037C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF09 -:2037E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9 -:020000040800F2 -:20380000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC8 -:20382000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA8 -:20384000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF88 -:20386000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF68 -:20388000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF48 -:2038A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF28 -:2038C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF08 -:2038E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8 -:20390000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7 -:20392000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA7 -:20394000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF87 -:20396000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF67 -:20398000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF47 -:2039A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF27 -:2039C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF07 -:2039E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE7 -:203A0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC6 -:203A2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA6 -:203A4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF86 -:203A6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF66 -:203A8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF46 -:203AA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF26 -:203AC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF06 -:203AE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE6 -:203B0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC5 -:203B2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA5 -:203B4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF85 -:203B6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF65 -:203B8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF45 -:203BA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF25 -:203BC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF05 -:203BE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5 -:020000040800F2 -:203C0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC4 -:203C2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA4 -:203C4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF84 -:203C6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF64 -:203C8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF44 -:203CA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF24 -:203CC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF04 -:203CE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE4 -:203D0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC3 -:203D2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA3 -:203D4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF83 -:203D6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF63 -:203D8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF43 -:203DA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF23 -:203DC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF03 -:203DE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE3 -:203E0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC2 -:203E2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA2 -:203E4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF82 -:203E6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF62 -:203E8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF42 -:203EA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF22 -:203EC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF02 -:203EE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE2 -:203F0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC1 -:203F2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA1 -:203F4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF81 -:203F6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF61 -:203F8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF41 -:203FA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF21 -:203FC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01 -:203FE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE1 -:020000040800F2 -:2040000098350020E1BA000881BA000883BA000885BA000887BA000889BA000800000000AD -:204020000000000000000000000000008BBA00088DBA0008000000008FBA000891BA000840 -:2040400021BB000825BB000829BB00082DBB000831BB000835BB000839BB00083DBB0008D0 -:2040600041BB000845BB000849BB00084DBB000851BB000855BB000859BB00085DBB0008B0 -:2040800061BB000865BB000869BB00086DBB000893BA000875BB000879BB00087DBB00086F -:2040A00081BB000885BB000889BB00088DBB000897BA00089BBA000899BB00089DBB000866 -:2040C000A1BB0008A5BB0008A9BB0008ADBB0008B1BB0008B5BB0008B9BB0008BDBB000850 -:2040E000C1BB0008C5BB0008C9BB0008CDBB0008D1BB0008D5BB0008D9BB0008DDBB000830 -:20410000E1BB0008E5BB0008E9BB0008EDBB0008F1BB0008F5BB0008F9BB0008FDBB00080F -:2041200001BC000805BC000809BC00080DBC0008DFF8240B40697047DFF81C1B486170477F -:20414000DFF8141B08707047DFF80C0B0078704738B901EBC100052190FBF1F000F5A070D8 -:2041600006E001EB8100A0F5C860092190FBF1F000B2704710B5DFF8E44A00206060A06185 -:2041800001F0BFFE08B9082005E0042807DB012001F0B1FE0620BDE8104002F02BB80120C3 -:2041A00002F028F8DFF87C0EC069606110BD30B583B004460D46062100A802F025FA2A46D0 -:2041C0003FA100A802F034FA05F1090100A8DFF8882A12786AB9642D07DA0A2D03DA002DA6 -:2041E00005D5002901D443210CE0432113E043210EE0642D09DA0A2D03DA002D07D5002934 -:2042000003D445218170202105E0452103E04521417020218170C17000A9204601F0AFF9DF -:20422000DFF8380A1421016037BD70B582B0DFF8F84D60780FF28C0120B9009110236022E3 -:2042400000210BE0012802D16068009002E0022808D10091102360220021002002F04EFA58 -:20426000606025E0032823D10025542616E01C200FF2F01100FB051060600E21F01D02F089 -:2042800064FA6068009010230E220021F0B202F035FA6060F61F0A2002F0E8FB20788642ED -:2042A000E5DA0E3020706D1C062DDEDB002020706078401CC0B2042808BF0020607073BD93 -:2042C000256400000000000000000000000000000000000000000000000000000000000055 -:2042E000000000000000000000000000000000000000008898BFBF98880000000080808080 -:2043000080808000000000000000000000000000000000000000000000000000000000001D -:204320000000000000206060606060609090909090909090909090909090909090909090DD -:204340009090909090606060606060606070F8888482828383838383838282828283838372 -:204360008383838282828282868484848484848484848484848484848484828282828282D4 -:204380008282FE00000000000000000000000000000000000000000000000000000000001B -:2043A0000000000000000000000000000000000000000090B0FEFEB0900000000080808001 -:2043C00080808000000000000000000000000000000000000000000000000000000000005D -:2043E00000000000002060606060606090909090909090909090909090909090909090901D -:020000040800F2 -:204400009090909090606060606060606070F88884828283838383838382828282838383B1 -:20442000838383828282828286848484848484848484848484848484848482828282828213 -:204440008282FE0000F0F00000F0F0F00000FCF8F0E0C080000F0F00000F0F0F00003F1FFD -:204460000F0703010000000000000000000000000000000000000000000000000000000022 -:204480000001FFFF01010101010181C67E380080FFFF818101010101000000000020202036 -:2044A000E0E0008040402060C04000808080FFFF81808080000000000000008040402020FD -:2044C00020404080000000003F7F448484848484844727000000008040402020204040C094 -:2044E0000000000020C3828684848C8C887830000000008040402020204040C000000000E1 -:2045000020C3828684848C8C88783000000000000000008080C0602010180C86E0E0E0ECDA -:20452000FCF2F3F1F0F8ECE4E4E2E30100000000000000000080C0402030180CC0C0C0D83B -:20454000F8E4E6E3E1F1D8C8C8C4C603FCFCFC00000000C0382625010101010101010102AE -:204560007F7F7F0609090909090939484848483010080804FCFC00000000C0382625010198 -:2045800001010101010102027F7F0609090909090939484848483010080804040000000026 -:2045A000000000008080C06030180C8600E0E0ECF4F6F6FBF5E8E8E4E2E2E100000000002C -:2045C00000000000000080C06030180C00C0C0D8E8ECECF6EBD1D1C8C4C4C201FEFEFE80BF -:2045E0004040605854020202020202843F3F3F00010101010107050506020100FEFE804007 -:204600004060585402020202020284843F3F0001010101010705050602010000F8B50C469E -:204620008578303DEDB20A2D38BF2A46C578303DEDB20A2D38BF2B4600783038C0B20A2867 -:2046400038BF01460026DFF8D45C18200FF2780700FB016C1CF807C006EB050E8EF860C04A -:2046600000FB026C1CF807C08EF890C000FB036C1CF807C08EF8A8C0761C182EE8DB10271B -:2046800044B902230C220821284600F0ABFD05F1D80000E028460026009010230C22002147 -:2046A0000C2000F095F8761C082EF5DB7F1EE7D14CB94FF47A7002F0D9F902F08DF8BDE852 -:2046C000F14001F08ABDF1BD00E010080810E00000000000000F102020100F000000000055 -:2046E000001010F800000000000000000020203F2020000000000000007008080888700063 -:20470000000000000030282422213000000000000030088888483000000000000018202092 -:2047200020110E00000000000000C02010F800000000000000070424243F2400000000009C -:2047400000F8088888080800000000000019212020110E000000000000E010888818000088 -:2047600000000000000F112020110E000000000000380808C8380800000000000000003F2B -:204780000000000000000000007088080888700000000000001C222121221C00000000005B -:2047A00000E010080810E000000000000000312222110F0000000000000000000000000074 -:2047C000000000000030300000000000000000007043C0B201F092BF10B582B00FF210000A -:2047E000002400F0F5F9641C062CFAD313BD0000000000C0F038080404040408081C00003C -:020000040800F2 -:204800000000000F1F3060404040402030080000000000C0F0180C0404040C18F0C00000CE -:20482000000000071F306040404060301F07000000000004FC1C38E0C0000004FC04000054 -:20484000000000407F40000001071E387F00000000000004FCFC84848484E4040C1000006C -:20486000000000407F7F400000000300000000000000000000040404FCFC040404000000A7 -:2048800000000000004040407F7F404040000000000000C0F03808040404040C1C00000072 -:2048A000000000071F3860404042423E3E0202002DE9F04184B004468846062101A801F062 -:2048C000A3FEE4A62246314601A801F0B1FEDFF85C7701AD387828B9642CA8BF432008DA60 -:2048E000432004E0642CA8BF452002DA4520A8702020E87001A9012000F06AFEB878411C74 -:20490000B9700FF2540100F0F3FD292001F0F6FEB878032804BF0020B870062101A801F0E3 -:2049200073FE4246314601A801F082FE387828B9642CA8BF432008DA432004E0642CA8BFE2 -:20494000452002DA4520A8702020E87001A9382000F03EFEBDE8FF8100003060C0800000DE -:2049600000000000000000000000180C06030100000000000000000000003060C0803060A9 -:20498000C0800000000000000000180C0603190C060301000000000000003060C08030601B -:2049A000C0803060C08000000000180C0603190C0603190C060301000000183060C0800075 -:2049C000000000000000000000000C060301000000000000000000000000183060C0983091 -:2049E00060C080000000000000000C0603010C0603010000000000000000183060C09830BB -:204A000060C0983060C0800000000C0603010C0603010C060301000010B582B0012808BFE5 -:204A20000FF22C0103D0022808BF0FF2E401009100F03EFA012400F0CBF8641C062CFAD38E -:204A40004FF47A7002F012F8BDE8134001F0C5BBE01864E282010101010182E26418E0003F -:204A6000030C1021274E5850584E2721100C0300F00C0201010101020F00000000000000B9 -:204A8000030C081010101008060000000000000000601010909090E00000000000000000A1 -:204AA000000E11111010081F101800000000000000010101FF000000000000000000000055 -:204AC000001010101F10101000000000000000000000000000000000000000000000000057 -:204AE0008080808080808080808000000000000001077980008079070100000000000000B4 -:204B0000000000071C0700000000000000000000E018040212214181814122120418E00086 -:204B2000030C10202844424141422428100C0300F00C0201010101020F0000000000000046 -:204B4000030C081010101008060000000000000000601010909090E00000000000000000E0 -:204B6000000E11111010081F101800000000000000010101FF000000000000000000000094 -:204B8000001010101F10101000000000000000000000000000000000000000000000000096 -:204BA0008080808080808080808000000000000000010719E0B00D03010000000000000033 -:204BC0000010181700011618100000000000000000901023102200212001C0B201F08EBD72 -:204BE00070B582B00FF2780501F088F9022808D00ED304280AD006D3052808BF0FF20C1497 -:020000040800F2 -:204C000006E02C4604E00FF2901401E00FF2142405F18C00009000F04BF9DFF8EC5B287895 -:204C200080B90226142000FB06402838009010230A2200210A20FFF7CBFD761C092EF1DBB1 -:204C4000012004E05021102001F07FFD0020287073BD00002564000028030020D83000205D -:204C600001FF00E11FE000FF010000011E0100011E010000006010109090E0000000000E86 -:204C8000111110081F1800001010F04020101030000010101F1010000000000010F0201054 -:204CA000101010E00000101F10000000101F100000001013F30000000000000010101F1001 -:204CC0001000000010F02010101010E00000101F10000000101F100000E010101010F010E6 -:204CE0000000007D8A8A8A8A9170000000000080E0F8FE0707FEF8E080000000101C1F1FEA -:204D00001F1F1F12121F1F1F1F1F1C1001FF0100000000000000101F1010101010180400AF -:204D200000C0201010101020C0000007081010101008070010F00010F01000F01000000302 -:204D40001C0300031C03000000202020202020202000000000000000000000000107798011 -:204D6000008079070100000000071C070000000000C0201010101020C000000708101010C9 -:204D80001008070000001010FE1010100000000000000F1010080000001C222141414182CB -:204DA0000700001E081010101008070000C0A090909090A0C000000708101010100804001C -:204DC00010F02010101010E00000101F10000000101F100000202020202020202000000015 -:204DE000000000000000000001FF21212121F9030400101F1010101010180400001010F084 -:204E00004020101030000010101F101000000000001010F04020101030000010101F101064 -:204E20000000000001FF4140404041FF0100101F10000000101F100000001013F30000009C -:204E40000000000010101F10100000000000E010101010F0100000609D8A8A8A8A917000AD -:204E600001FF2010101010E00000101F10000000101F100000202020202020202000000074 -:204E8000000000000000000001077980008079070100000000071C070000000000001010C6 -:204EA000FE1010100000000000000F1010080000102310220021084601F020BC38B50FF2FE -:204EC000701451EA000213D100250CE0012D05D1009400F048F801F011FC04466D1C022D54 -:204EE0003FDA002DF2D1009400F005FB0846F2E7C8B1002935D101280AD104F120000090AD -:204F000010231022502001F0F9FB04F1400015E0022826D1009410231022002001F0EEFB99 -:204F200004F1600019E0E1B101290DD104F1200000F018F801F0E2FB04F18000009010236E -:204F40001A46002108460AE002290AD1009400F0D2FA01F0D3FB04F1A00000F003F801F012 -:204F6000CDFB31BD00901023102200215020704770B582B0044650250E01F6B20EE0102152 -:204F800005F1100001F0E1FB009400F0B4FAE8B201F0B4FB103D192001F068FDB542EEDA37 -:204FA00073BD2DE9F0411F48B0F91280DFF8180B0078012803D1414600F053FB80460FF2DD -:204FC000700400212046FFF7D3FF4FF47A7798FBF7F6F6B20FF62835012105EB4610FFF7F2 -:204FE000C7FF07FB1688642798FBF7F6F6B2022105EB4610FFF7BCFF032107FB16800A2296 -:020000040800F2 -:2050000090FBF2F0C0B205EB4010FFF7B1FF042105F5D070FFF7ACFF052104F12000BDE8EB -:20502000F041A5E7800200206031002028030020808040402020101008080404FE0000001F -:205040000000010102020404080810103F0000000000FE04040808101020204040808000DD -:2050600000003F10100808040402020101000000008080C0C06060303018180C0CFE0000CD -:20508000000101030306060C0C181830307F00000000FE0C0C181830306060C0C0808000EF -:2050A00000007F303018180C0C060603030101008080C0C0E0E0F0F0F8F8FCFCFE000000AF -:2050C00000000101030307070F0F1F1F3F0000000000FEFCFCF8F8F0F0E0E0C0C080800019 -:2050E00000003F1F1F0F0F0707030301010000002DE9F0411318DFF82482DFF8D4198D7847 -:205100005DB90125CD7000250D7108254D7100250D704D7001258D7028E0CD7825BB0E7952 -:205120004F7906EB000EAE449EF833E005EB080484F8D8E002EB050EC644F4182C1994F8F6 -:2051400033408EF8D8406D1CEDB2AF42E9D27D1C4D71761E0E71EDB20B2D05D10A20487170 -:2051600000200871012025E00D7925BB0125CE784F7911E006EB050EC6442C1894F8334094 -:205180008EF8D84006EB020EAE44C644EC1894F833408EF8D8406D1CEDB2BD42EAD3781E59 -:2051A0004871721CCA70C0B228B901204871092008710020C870BDE8F08110B50021002229 -:2051C0000123934003405400042AB9BFC4F10704A340E41FE3405918C9B2521C082AEFDB7C -:2051E000084610BD2DE9F44F82B082465FEA0308DFF8DC580AD1287828B900260027012018 -:2052000028706E700CE0AE686F6910E0B8F1010F0BD1687830B90026002728700120687012 -:20522000AE7004E0EE68AF6901E02E69EF6900249DF80800484340000090DFF8E09008E0E3 -:2052400014F80A00FFF7B9FF04EB090181F8D800641C00988442F3D300229DF80800DFF806 -:20526000741803E09DF8083002EB4302009B9A422FD200240AE021F81EA031F81EE04FEA03 -:205280001E2A83F8D8A08CF8D8E0641C8442E9D21318E31803EB090C02EB040E0EEB090369 -:2052A00093F8D8A09CF8D8B04BEA0A2A21F81EA0B8F1010F06D1002E14BF2AFA06FA0AFAD6 -:2052C00007FAD8E7002F0CBF0AFA06FA2AFA07FAD1E7002408E004EB090A9AF8D800FFF7C5 -:2052E0006CFF8AF8D800641C00988442F3D31FB9102E08D1002610277F1EB8F1000F04D1CF -:20530000AE606F6108E0761CF7E7B8F1010F07BFEE60AF612E61EF61BDE8F78F0000002050 -:205320002DE9FD4E81B08946DFF8AC07B0F91210DFF894572878012802D100F092F9014697 -:205340000A2091FBF0F109B2642291FBF2F6F6B202FB161393FBF0FA5FFA8AFA02FB1611BA -:2053600000FB1A10C0B200906878012803D1E8610020286206E0022805D10020E8611020B7 -:205380002862002068700020A8610FF2747405E0FFF713FF8BF83801781CA861AF69DFF844 -:2053A0003CB7B7EB490F1FDABB4404EB4610385CFFF703FF8BF8D80004EB4A10385CFFF709 -:2053C000FCFE8BF8F800009804EB4010385CFFF7F4FE8BF818013819297801290CBF90F8FA -:2053E000E00190F8A001D3E79DF80400C0F1030009FB00F04300E869296ADFF8D82601E0CB -:020000040800F2 -:2054000003EB4903062606FB09F6B3422BDA002609E022F81E4032F81E703C0A8AF8D8400D -:205420008CF8D870761C4E45EADA03EB090AB2440AEB0B0C03EB060E0EEB0B0A9AF8D840FA -:205440009CF8D87047EA042422F81E409DF8087027B9002914BFCC408440DAE700280CBF32 -:205460008C40C440D5E700201AE006EB0B0494F8D800FFF7A2FE84F8D80094F8F800FFF7BE -:205480009CFE84F8F80094F81801FFF796FE84F8180194F83801FFF790FE84F83801701CB0 -:2054A000A861AE69B6EB490FDFDB0BF1D8000121A96100F01FF8A8690007000E01F01EF9E4 -:2054C000A969491CA9610529F3DBE869296A50EA010202D019B9102804D1002005E0481E12 -:2054E000286201E0401CE861012004B0BDE8F08E01EB401000901023102200217047F8B5EE -:2055000004460D46DFF8D8651421304601F07CF80FF6240724B900230A220121384606E0E8 -:20552000012C07D101230A22012107F12000FFF759FE06E0022C04D10A2201213846FFF7E4 -:20554000D7FD009610230A220021562001F0D6F80FF2CC7400F04AFE042803D104F10C00B2 -:20556000009005E0002D06BF07F1140000900094102306220021502001F0C0F8F1BD38B564 -:205580000C46451EEDB2082D0BD3002509E03638C0B20FF26C51FFF7ABFF2801FFF719F927 -:2055A0006D1C207898B114F8010B202808BF0A20EFD02D2808BF0C20EBD0A0F130010A2979 -:2055C00038BF3038E4D3A0F141010629DFD331BDF8B504460D4600260FF604070DE0142171 -:2055E00001FB0070009010230A220021F6B20A2000FB0640FFF7EDF8761C287888B115F8C9 -:20560000010B432808BF0B20E9D0452808BF0C20E5D0A0F130010A293ABF3038C0B20A2061 -:20562000DDE7F1BD38B50446DFF8AC04B0F91450B0F91210DFF89004007801280BD100F08A -:2056400010F8002C0CBF2918411B09B20120BDE83440FEF77DBD0CB9681832BD481B32BD04 -:2056600029460020FEF774BD70B504460D46DFF86804B0F91200DFF850140978012902D1FC -:205680000146FFF7EEFF4FF47A7190FBF1F2642390FBF3F6B6B24DB9201890FBF3F390FBA7 -:2056A000F1F080B292B2904209D10AE0001B90FBF3F390FBF1F080B292B2904201D00320C9 -:2056C00070BD9BB2B34201D0022070BD012070BDF8B5DFF8F443DFF80054B5F914000A2813 -:2056E00004BF0120A081DFF8FC63F068002800F08980606938B10020606100F0FCFB01F08B -:205700006BF8FFF74EFC00F0F0FB40282DD0B0F5807F58D16089B5F9121088421EDA01203D -:2057200060700121A88AFFF79FFF074600F06EF80028FBD10120FFF775FF68826089B5F90E -:2057400012108142B8BF68820220607000F05EF80028FBD100210120FFF7B0FBB5F9120034 -:20576000618988422FD101212AE0B5F91200218988421FDA012060700021A88AFFF774FF6F -:205780000746002200F043F80028FAD1FFF74AFF68822089B5F912108842B8BF688202208D -:2057A0006070002200F033F80028FAD100210220FFF784FBB5F912002189884203D1022106 -:2057C0000020FFF77BFB40F2051700F08EFB80B1A08940B1F168B94205D3322141430A31ED -:2057E000A982401CA0814FF49670F060002000F07FFBA08930B1F068B84203D20A20A88259 -:020000040800F2 -:205800000120A081F1BD00009031002001221021384685E52DE9F0474FF00A09B14EAA4CE7 -:20582000AD4F00F0E3FC401E072869D8DFE810F00800C5004400F700910094004901E700AA -:205840006069012801D100F057F9207940B900F0DAFF00213846FEF7E1FE0120207107E0DD -:20586000B06928B9706918B1FEF7DFFC3220B061706978B9608A401C608280B2322805D1C5 -:20588000208A411E2182C0B200F0ECFE208A08B900F0FCFE01F017FB012803D000F025FBAC -:2058A00000282DD0F86970613320208200F0DAFEBDE8F04700F0E4BE606928B901206061DA -:2058C00000F019FB00F088FF00F098FC8046E078B8F1010F06D008B100F07EFF0020E08175 -:2058E000E07023E0E1894B2908BF002804D100F073FF0120E07000E0C0B1B06908B1306825 -:20590000DFE000F07FFC0546B7F912A02078012806D1FFF7A5FE05465146FFF7A2FE82463F -:2059200051462846FEF7C4FF3220B0613068002804BFE0780028E3D100F064FC0546B7F945 -:205940001200A842B4BF291A411B122900DA0546A6E0BDE8F047BBE66069012801D100F022 -:20596000CBF800F0C2FA48F24001401A07D0C03802D0403806D007E0012060710BE002200E -:2059800060710DE0607101E0607910B9FEF724FF0AE0012802D100F036FF05E0022803D1EF -:2059A00001213846FEF73AFE6079032804D0002000F09EFA0320607183E0606910B9012090 -:2059C00000F09BF8484F387828B1FFF725F80020387000F001FFB069002872D100F088FB62 -:2059E00005462078012802D1FFF73AFE054600F07DF836A10620FFF7C2FD14200DE060694E -:205A000010B9012000F079F86069012804BFB069002856D1FFF7E4F83220B06151E000F0C8 -:205A2000F1FB0546B7F91000A842B4BF291A411B1329B8BF054600F0E1FB8046E078B8F1E2 -:205A4000010F06D008B100F0C7FE0020E081E07020E0E189322908BF002804D100F0BCFEEE -:205A60000120E07000E0A8B1B06900287FF447AFB7F910A02078012806D1FFF7F1FD0546AB -:205A80005146FFF7EEFD824651462846FEF710FF3220B0613068002804BFE078002810D176 -:205AA0002078012802D1FFF7DBFD054600F01EF801F006FA01464046FFF721FDE089401C9C -:205AC000E081BDE8F0870000280300204600000070030020A02E0020800200200000002075 -:205AE000D8000020D83000202804002095FBF9F109B20120FEF75BBB0020606100F06CBEDE -:205B0000000000F8FE0301010103FEFCF00000000000003F7FE0808080C07F3F07000000F9 -:205B200000000008040406FFFF0000000000000000000000808080FFFF8080800000000053 -:205B4000000000060701010181C37F3E00000000000000E0F0D8CCC6C3C0C0E000000000D7 -:205B60000000000607818181C1633F1E00000000000000E0C080808181C37F3E00000000F2 -:205B800000000000C060380CFFFF0000000000000000060705040484FFFFC48406000000B9 -:205BA000000000FFFF8383838383830300000000000000E0C080808080C17F3F08000000AB -:205BC000000000E0F89C8EC2C3C18181000000000000003F7FC080808080C17F3F0000007E -:205BE0000000000F0303030383E33B0F030000000000000080E0781E0701000000000000D9 -:020000040800F2 -:205C00000000187E7EC381818181677E3C00000000001C7EFFC180808081E37F3C0000008F -:205C2000000078FEC603010101039EFCF000000000000001018383C361713F0F01000000A9 -:205C4000000000000000000000000000000000000000000000000000000000000000000044 -:205C60000000000000000000F00000000000000000000101010101011F0101010101010009 -:205C80000000000000000000000000000000000000010101010101010101010101010100F6 -:205CA0000E11110EE0F80C060301010101021E00000000000F3F70C0808080808040200037 -:205CC000000000000000C0C0C0C00000000000000000000000003030303000000000000004 -:205CE00008142214080202FE06020202C202061E00000000008080FF81810101030000004E -:205D0000C03008040402FAAAFA0204040830C0000718204058A4DBDEDBA458402018070057 -:205D200000F0FEFFF000007F7F7F7F00FF0FE1E00FFFFF80BFBF80FF10188CC66363C68C9F -:205D40001810426331180C0C1831634200F01E1FF00000FF8080FF0042C68C183030188C5C -:205D6000C64208183163C6C6633118088C8CC6C68C8CC6C68C8C3131181831311818313141 -:205D8000008C8C8C8C8C8C8C8C8C8C8C8C8C8C0000313131313131313131313131313100AD -:205DA00080C0603098CC66333366CC983060C08088CC6633190C060303060C193366CC8813 -:205DC000113366CC983060C0C0603098CC6633110103060C193366CCCC6633190C060301DF -:205DE00000E0180404040418E000000F3040404040300F0000000808FC0000000000000019 -:205E000040407F4040000000007804040404048870000060504844424140700000380404D0 -:205E20008484C830000000384040404040211E00000080601008FE0000000007040444441E -:205E40007F4444000000FC0484848404040000384141404040211E0000C0308884848404E6 -:205E60001800000F3140404040211E00001C04048444340C04000000007E010000000000DC -:205E800000708804040404887000001C2241414141221C0000F0080404040418E000003052 -:205EA000414242422219070000000000000000000000000000000000000000001C1CC03071 -:205EC000080404040830000007182040404020101C120C0202FE8282E20200000000407F64 -:205EE00040000300AA4800787047AA4840687047A84948607047A74908707047A4484078DA -:205F0000704770B5044600250A26A34801F02CF94519761EF9D10A20B5FBF0F19C4A40F672 -:205F20006373994203D304205070002070BD48439021B0FBF1F100200FF2A82333F8105069 -:205F4000A942D56808D2401C042805D20228F5D1002CF3D0A942F6D3401C70BD00208F49CC -:205F60000A68D243920548BF4FF480700968C943490648BF40F0400090B186490A78012AC9 -:205F800004BFCA68824207D18A68521C8A60162A06D340F4004002E000228A60C8604860DB -:205FA000704770B57E494A68D3089CB2C5000E781EB94D600120087009E0844234BF041B3A -:205FC000241AA4B23D2C3CBF8018C51A4D60E80870BD38B5002000F03CFD72481021016006 -:205FE000192000F047FD704D0A2021E0002000F02BFD69684118AA68824238BF0246AA60CB -:020000040800F2 -:20600000EA68904288BF1046E860288801280CD1A868081AE968401AC008FFF7C2FF04461B -:20602000002141F28830E860A96069602888401E288028880028D9D1204632BD5B490A7887 -:2060400022B9C000486001220A7007E04A688018931002EB5372A0EBE2004860811000EB49 -:206060005170C010704738B500254F4C0A2026E0012000F0E9FC216941186269824238BF9C -:2060800002466261A269904288BF1046A0612088012811D16069081AA169401AC008FFF7BA -:2060A000CDFF40F6E4414843000BA0F5FA75002141F28830A061616121612088401E208028 -:2060C00020880028D4D1284632BD10B5FFF781FF0446FFF7C8FF2E49B4F5C87F05D2B0F5C9 -:2060E000967F02DA8C60012000E00220087010BD70B50446FFF76DFF0546FFF7B4FF244929 -:206100004A8840F6FF739D4202D18B885B1C07E00023A5F6D966B6F5937F34BF521C0022A5 -:206120004A808B808A884B883C2A02D353B9032207E01AB90A2B28BF022202D20A2B01D263 -:2061400001224A70A4F57A7296235A4340F6B83392FBF3F250328968B4F57A7F08BF0A3AD4 -:2061600000D01CB18B18AB42B8BFAD1AB0F5C87FC8BF4FF4C87040F22632691A4FF47A7389 -:20618000504303FB010090FBF2F000B270BD0000280400201C3100200028014008080140AE -:2061A00050310020140C0140900300205831002010B5044645F2555000F0E4FF032000F0B0 -:2061C000E4FF0A2060434003000C00F0E1FF00F0E2FF00F0E5FF012010BD80B500F0DBFF5E -:2061E000012002BD2C0196005A002800DFF8B00300787047DFF8A81308707047DFF8A00386 -:20620000808B7047DFF89803B0F91E00704720220FF2D431DFF88C0300F0CEBFDFF8800347 -:2062200000218180C180018141818161C1600F2101820221418201218182704730B5002238 -:20624000DFF85C13C880B1F904300446181B08818D6900B2B0F5FA7FBCBF01224519A34225 -:2062600005DAE31A1BB2152BA4BF002500228D611F28B4BF002301230C8A4D8A6A438D698C -:206280006A4300FB04228C8AB1F90A50451B6C4303FB04224881012AB8BF002205DB41F243 -:2062A00071708242A8BF41F27072CA6090B230BDBB4A9180884204DA091A122904DB002148 -:2062C00005E0411A132901DA022100E001219183B4E770B5B44CB24D287801280ED002289E -:2062E00000F0FC80032849D0042800F09880052800F0E380082800F0208170BDFFF7F5FD64 -:20630000402811D0B0F5807F18D16878012817D000F05DF9042811DA0320287000202884D3 -:206320002060A061606109E06878012808D0022028700020A0610120FFF7DDFD687820B1D4 -:20634000E06910B96870FFF7D3FD00F040F940B9FDF7EEFE012804BF0020FDF7EDFE082078 -:206360002870A878042818BF012806D0286C60610020FFF7BDFD0120A87070BDFFF7B5FD30 -:2063800048F24001401A04D0C03802D040380AD00FE000F016F905202870002060604FF46A -:2063A000FA70E06005E000F054FB00F00DF900F011F900F00CF9042805DB00F002F900F043 -:2063C00003F900F007F9B5F93660606848B93046FFF78EFE00F0F0F800B200F03AFB1E20DF -:2063E000606000F03AFB00B9606000F06CFD98B9288C18B901202884E86BA060A0680028C0 -:020000040800F2 -:206400004DD1A883A06100F024FB0020FFF770FD286C6061042041E0002028843FE0B5F96D -:206420003460B5F93610B142B8BF0E46606848B93046FFF75DFE00F0BFF800B200F009FB39 -:206440001E20606000F0C3F804280DDB00F0B9F800F0BAF801202870286C60610420A870F2 -:20646000012068703220E061606958B900F0F1FA00F0AAF801206870C820E0610420A870EB -:206480000120287000F01FFD012802D0FFF72DFD28B10020A0616061288403202870FFF704 -:2064A0002DFD02287BD3FDF743FE012804BF0020FDF742FE0820287070BDE06800286ED129 -:2064C0003A4E0120307001F044F801F095F800203070032028700020206070BDE06920B166 -:2064E0000020BDE87040FFF703BDFFF7FEFC48F24001401A12D0C03810D040380BD1FFF7A8 -:20650000E4FDFFF7EFFC012803D101F022F801F073F8C820E061E878002840D00020E8701C -:2065200000F097FA012028700220A8700120687000F04AF83220E06170BDFFF7DFFC801E8D -:20654000012803D9801E01280FD921E0B5F93600FFF7CEFDE883FFF7D1FC012818D103207E -:2065600028700020FDF7E8FD12E000F030F801280EDB00F02CF804280ADA00F022F800F050 -:2065800023F8012068700220A061A87001202870074820B100F015F806481021016070BDC9 -:2065A0005C02002080020020D8300020280400205B6A0008140C0140E8833146B5F91E006B -:2065C00076E6002000F045BA0020FFF794BC0120FFF797BC012028700320A8700120687093 -:2065E0003220E06170470000322E3132000000000000000000000000D007B80B6400000090 -:2066000050460000A08C0000002201F0BDBD50F8041B61B150F8042BD30744BFA9F10103C0 -:206620009A18002342F8043B091FFAD1EFE770470CB41CB5044604A80190009401AB0A46E4 -:2066400000A907487844183001F0B8FD009900220A7000285CBF0098001B16BC5DF80CFB3F -:20666000CF0B000080B500A90FF2F42213680B608DF803003C22042100A802F0F3FC01BD13 -:2066800000B583B000A80FF2DC2104E000B583B000A80FF2D8210CC90CC03C22062100A830 -:2066A00002F0E0FC07BD10B5A0B00C4640218DF80010411CC9B2012000AA03E014F8013B1D -:2066C0008354401C8842F9DB3C2200A802F0CAFC204620B010BD30B583B000AA0FF29423AE -:2066E00030CB30C220308DF8050000A84278891841703C22082102F0B5FC37BD2DE9F041BA -:20670000044690465818C0B2CE080722114218BF761C811000EB5171CA10B0EBC2011ABF6D -:20672000501CC5B2D5B2069F09E031462046FFF7D2FF39464046FFF7B6FF0746761CF6B286 -:20674000AE42F2DB3846BDE8F08130B5A1B004460D4601A8FFF758FF00F051F82A46002155 -:20676000E0B2FFF7CBFF00F04AF82A460821E0B2FFF7C4FF21B030BD80B54FF48070ADF8E6 -:20678000000003208DF8020010208DF8030000A90E4802F0A3FC01BD10B50D4C4FF48071F7 -:2067A000204602F002FD022000F060F94FF48071204602F0F8FC022000F058F93C222E2187 -:2067C0000448BDE8104002F04DBC0000000C014000080140A002002000B5A1B0802101A8D5 -:2067E000FFF712FF00F00BF8802200F0B5F800F006F88022194600F0B0F821B000BD01A8A2 -:020000040800F2 -:206800000090082370472DE9F041A2B00125002201A90FF2681000F0BCFE040000F07F8065 -:206820002078422804BF60784D2840F0878094F83600FF2804BF94F83700FF2804D194F818 -:206840003800FF2808BF002500F081F801260F27002000210C2202FB0712121992F83E208F -:2068600080234FF0080C03EA020E1DB1BEF1000F0CD102E0BEF1000F08D00DF1080E864466 -:206880009EF8018046EA08088EF8018000F059F8E9D1491C0C29DDD37606360E7F1E082FC1 -:2068A000D6DA02A800900823602200F055F8FFF794FC00F04CF801260027002000216FF05C -:2068C0000B0202FB0712121992F8922080234FF0080C03EA020E1DB1BEF1000F0CD102E0F0 -:2068E000BEF1000F08D00DF1080E86449EF8018046EA08088EF8018000F023F8E9D1491C9C -:206900000C29DCD37606360E7F1C082FD5DB02A8009008236022082100F01FF808E00FF251 -:20692000680000901023602200210020FFF7E6FE4FF47A7000F09AF8FFF74FFC22B0BDE828 -:20694000F081401CC0B25B08BCF1010C70477F210DF1090002F056BC00210020CEE6000084 -:2069600080818000808D801480AF0000808D801080AE000080B080218020807F4C4F474F5A -:20698000494E2020424D500000000000000000000000000000000000000000000000000041 -:2069A00080C0E0F0F8FCFEFEFCF8F0E0C080C0E0F0F8FCFEFEFEFC783080C0C000189CCE2F -:2069C000E6F0F8FCFEFEFCF8F0E0C0E0F0F87C000000000000000000000000000000000029 -:2069E000000000000000000000000000000000000000000000000000000000000000001F78 -:206A00000F07030103070F1F3F7F7F3F1F0F07030103070703191C0E6773391C0E070301D0 -:206A200003070F1F3F7F7F3F1F0F0703010000000000000000000000000000000000000069 -:206A40000000000000000000DFF8281431F810007047DFF82414C8607047DFF81C04C06826 -:206A600070472021DFF8140402F0CCBBDFF80814142202E0DFF800140A2250438860886829 -:206A80000028FCD17047DFF8F8134FF400620A614FF480520A61002808680AD120F44040D1 -:206AA00040F440500860086820F4402040F4403009E020F4804040F430400860086820F4D5 -:206AC000802040F430200860704780B502F09EFB102002F05FFC012002F056FCDFF8A40353 -:206AE0004168DFF8A42311434160016841F080710160012002F0A3FB012002F0A3FB3920B3 -:206B000002F011FC0028FAD0022002F09EFB02F0A3FB0828FBD10121172002F0E0FB012103 -:206B200040F20C6002F0E4FB0121032002F0E9FB0120BDE8024002F094BB80B501464FF0C7 -:206B4000006002F0DAFC4FF4A06002F0A5FC14208DF8000002208DF8010000208DF802002F -:206B600001208DF8030000A802F09BFC01BD38B5C64C4FF6FF70E060C5492160C54961602C -:206B8000C54DE860C54828604FF0883068608020ADF80000002000F01FF84FF4807000F0B8 -:206BA00021F80121BE4802F002FB102000F01AF80120ADF80000002000F01AF80220ADF8C4 -:206BC0000000002000F014F84FF41070ADF80000482000F001F831BD8DF8030000A920465B -:206BE00002F07CBAADF8000003208DF8020010208DF8030000A9284602F070BA2DE9F041EC -:020000040800F2 -:206C000090B04FF420442546A64E304602F08AFCA5480590974806900020079002200890D8 -:206C20000020099080200A904FF480700B904FF480600C9020200D904FF400500E900020A6 -:206C40000F9005A9304602F0BAFC0121304602F0D1FC964E304600F0DBF900F05FF84FF4CA -:206C6000602702970020039002208DF8100000A9304600F0F6F9DFF83882404600F0C8F9C4 -:206C800000F04CF802970020039001208DF8100000A9404600F0E5F90723022207213046D5 -:206CA00000F023FA072301220821304600F01DFA052301220921404600F017FA0121304640 -:206CC00000F0F6F90121304600F0E9F90121404600F0E5F9304600F0F4F9304600F0F6F94D -:206CE00020B12846451E0028F7D114E0404600F0E8F92546404600F0E9F920B12846451E52 -:206D00000028F7D107E00121304600F0E5F90121404600F0E1F910B0BDE8F081002000903E -:206D200001208DF804008DF80500704700B585B04FF4E06002F0B0FB2F20ADF8040042F232 -:206D40000F70ADF808000020ADF80A00ADF8060001A94FF0804002F073FC00F061F802F048 -:206D6000C5FC012200F05CF802F0B8FC00F058F802F0AAFC1C2000F02AF805B000BD1FB5D9 -:206D80004FF4E06002F088FB2F20ADF804003120ADF808004FF48070ADF80A000020ADF85E -:206DA0000600444C01A9204602F04AFC0121204602F09CFC01220121204602F08FFC012199 -:206DC000204602F081FC1D2000F001F81FBD8DF8000000208DF8010001208DF802008DF884 -:206DE000030000A802F05DBB80B500F019F802F087FC0020304901EB8002536813B15368F2 -:206E00005B1E5360401C0828F5DB0878401C08700321084204BFBDE80140FFF79FB801BD74 -:206E200001214FF08040704780B50121214802F067FC1148416811B14168491E4160816807 -:206E400011B18168491E8160C16802781B4B49B1C168491EC160002A19BF1021596010216E -:206E60001960D243C16811B9102159600022027001BD0000783100200C310020D830002007 -:206E800004080140001002400A846800000801408888880883B8BB8B000C01400088834457 -:206EA00000013000080002404C240140002401400028014000040040D4300020100C014013 -:206EC0005148C089704751480088704700B585B08DF800008DF801101D22022100A802F040 -:206EE000C1F80DE000B585B08DF8000003461D22012100A802F0CBF843489DF800100173D2 -:206F0000012005B000BD80B500212A20FFF7DEFF02210E20FFF7DAFF03212A20FFF7D6FF12 -:206F200000212B20FFF7D2FF01212A20BDE80440CCE770B51C460023002500F11006964268 -:206F4000A6BFA0F11006B242012301F11006A642A6BFA1F11006B442012300F12006964207 -:206F6000A6BF20388242012501F12000A042A6BFA1F120008442012524480580184670BDF7 -:206F800021480178407802E01F480179407940EA01200009802903D3C043401C0005000D97 -:206FA000704730B583B0184C06212046FFF72CFB0020FFF797FFE8B1207B00071AD50120FD -:206FC000FFF790FFB0B1207B8DF80000207000A8417861709DF8021021719DF80310617136 -:206FE0000179217240796072FFF7CAFF0546FFF7CBFF00E0258A00232A460021208AFFF74C -:020000040800F2 -:2070000098FFE081258237BDF83000200A31002080B55749884208D101214FF4007002F0FB -:2070200079F900214FF4007016E05249884208D101214FF4806002F06DF900214FF48060F5 -:207040000AE04D4988420BD101214FF4004002F061F900214FF40040BDE8044002F05AB987 -:2070600001BD4268454B1A400B681A430B7942EA032242608268424B1A40CB681A438B6823 -:207080001A434B7942EA43028260C26A22F47002097C491EC9B242EA0151C16270470029E0 -:2070A000816812BF41F0010149084900816070470029816814BF41F4807121F480718160BF -:2070C0007047816841F00801816070478068C008FFE700F0010070470029816814BF41F4E6 -:2070E000A00121F4A0018160704770B507240A290BD3A1F10A0505EB4505C668AC4026EA3B -:207100000404AB402343C36008E001EB41050669AC4026EA0404AB40234303611F23072A3E -:207120000AD2521E02EB8202446B934024EA030391401943416370BD0D2A0AD2D21F02EB0D -:207140008202046B934024EA030391401943016370BD0D3A02EB8202C46A934024EA0303CA -:2071600091401943C16270BDC06C80B2704700000024014000280140003C0140FFFEF0FF46 -:20718000FDF7F1FF09490860704709490860704708490860704705484AF6AA210160704749 -:2071A00002484CF6CC4101607047000000300040043000400830004062B38B0708D0521ED3 -:2071C00011F8013B00F8013B00F024808B07F6D1830740F0208000BF103A07D330B4B1E88F -:2071E0003810103AA0E83810F9D230BC530724BFB1E80810A0E8081044BF51F8043B40F825 -:20720000043BD20724BF31F8022B20F8022B44BF0B7803707047083A07D3B1E80810083A19 -:2072200040F8043B40F804CBF7D25307E4E70268531C03601170704770470000F8B5642482 -:20724000DFF8742C0A23072911D8DFE801F0041123588090C5CC017845785D4304FB015161 -:207260008078401841F2D041401A58431082F1BDDFF8481C09780029F9D1017845785D43C0 -:2072800004FB01518078401841F2D041401A58435082F1BDC17846788578A1F1300C5FFA79 -:2072A0008CFCBCF10A0F0CD200784FF47A77664307FB006003FB0500081800F53C57B03759 -:2072C00018E0A5F13001C9B20A2909D2007803FB06F104FB0010281841F2D041471A09E01C -:2072E000A6F13001C9B20A2904D2007803FB0060A0F504773FB204FB07F09061F1BDC1789D -:207300008578A1F13006F6B20A2E0DD206784FF47A774078604307FB060003FB05000818B1 -:2073200000F53C57B0370DE0A5F13001C9B20A2908D201784078584304FB0100281841F263 -:20734000D041471A3FB204FB07F0D061F1BD46780778A6F13000C0B20A283ABF03FB0760EF -:20736000A0F50477303F03FB07F09082F1BDC178467807788578A1F13000C0B20A280CD222 -:207380004FF47A7004FB06F200FB072003FB0500081800F53C57B03717E0A5F13000C0B2E6 -:2073A0000A2808D203FB06F004FB0700281841F2D041471A09E0A6F13000C0B20A283ABF95 -:2073C00003FB0760A0F50477303F3FB203FB07F0DFF8EC1A0860F1BD00783038C0B2BDE8F9 -:2073E000F240FCF7ADBE467807788578A5F13000C0B20A2808D203FB06F004FB0700281845 -:020000040800F2 -:2074000041F2D041471A09E0A6F13000C0B20A283ABF03FB0760A0F50477303FDFF89C0A19 -:20742000007818B9DFF89C0A3FB20760F1BD000030B507291DD8DFE801F004041E324151D4 -:2074400060658378A3F13001C9B20A293FBF4478A4F13001C9B20A2979D20178A1F1310044 -:20746000C0B2042873D2342903D1302C08BF302B6DD1012030BDC1783039C9B20A2921BFFE -:2074800081783039C9B20A29F3D341783039C9B20A295CD200783638C0B2042828E0C17853 -:2074A0003039C9B20A29E4D381783039C9B20A294DD200783338C0B2072819E00178407821 -:2074C0003038C0B2062804D2A1F13000C0B203280EE03529CDD2312939D1CAE7017840783E -:2074E0003038C0B2032805D2A1F13000C0B20A28BFD32CE03929BCD229E001783129B8D058 -:207500003029E9E74478017883780A20A3F13005EDB20A2D08D26425604305FB0100181812 -:2075200041F2D041401A0AE0A4F13003DBB20A2B3ABF00FB0140A0F50470A1F13000012A0E -:2075400097D180B2DFF87C190968884291D0002030BD10B54FF41852DFF86C19DFF86C0962 -:20756000FFF73AFEDFF86809002100220B460C461EC010BD10B5002208E0135CA3F16104CD -:20758000E4B21A2C3CBF203B1354521C8A42F4DB10BD2DE9FF4180460E46DFF8304904F2C6 -:2075A000004710250B22394601A8FFF705FE0B2101A8FFF7DFFF0B22414601A802F0B8F859 -:2075C00098B907F11C00017831704178717007F11A0000A902780A7042784A70BDF80000BA -:2075E00004EB402000F5007003E020376D1ED9D1002004B0BDE8F0812DE9F04FADF5097D01 -:207600000024ADF8004000260FF6E80700AA0DF102013846FFF7BDFF0190DFF8B09809F2C1 -:2076200000400290DFF8A8A80198002800F001814FF48C7143A8FEF7E7FFDFF898784FF4EE -:20764000007201993846FFF7B7FDA0460025232043A900FB081B05E0232D3CBF05F80B0066 -:207660006D1C761C384602F095F8864206D2F05D0D2802BFF11949780A29EDD105F80B400B -:20768000B61C08F10108B8F1080FDFD30027DFF828880AEB87056E69304602F07BF823217F -:2076A00043AA01FB072B02463146584602F040F800286CD1686902F06DF8064604E0202823 -:2076C00018BF3D285DD1761C00F0C3FA864258D216F80B00A0F13001C9B20A29EFD230286D -:2076E00001D1062F4DD15E440022F9B23046FFF79FFE002845D0F9B23046FFF79FFD2FB915 -:20770000B8F9100000F097FA43A837E0012F05D1B8F9120000F089FA4BA81DE0022F06D1F1 -:20772000D8F8180000F075FA0DF5A97026E0032F05D1D8F81C0000F066FA5DA81DE0042F68 -:2077400005D1B8F9140000F06AFA66A816E0052F04D100F076FA6EA8C01C0FE0062F07D1DF -:20776000FCF7F2FC02460FF2F0710DF5EF7005E0072F16D100F042FA80A8401CFEF758FF1F -:207780000FE000F066FA0146584601F03BFD6C6B204601F0FFFF024621465846FFF70CFD24 -:2077A00001247F1C082FFFF474AF002C02BFDFF80C07007800283BD0FE2103A8FEF724FF58 -:2077C0000027232043A900FB071103A801F0FDFF0AEB8700416D03A801F0F7FF7F1C082F1A -:2077E000EFD303A801F0D6FF0246BDF8000009EB4010FF2A80F81C2400F21C4094BF002172 -:020000040800F2 -:20780000110A417001980299401A00F50070411200EB91508012012100F80A1003A801F028 -:20782000B9FF024603A90198FFF7C6FC00F058FA5DE00FF2407500AA0DF102012846FFF707 -:20784000A8FE09F21644DFF89086D0B1FE22014603A8FFF7B1FC00F05CF809F584600ECD09 -:207860000EC0FE2203A909F50060FFF7B5FC6675C4F82080032089F83A04FE2089F83C0471 -:2078800001E000F046F802980ECF0EC00FF6F007062239464846FFF79FFC0622394609F52D -:2078A0000070FFF799FC00270AEB8705D5F834B000F0CFF900F032F8686B01F06BFF8619D5 -:2078C000D5F854B000F0C5F900F028F8686D01F061FF86197F1C082FE6D3002089F80B0419 -:2078E000C9F8168402202071A67100F022FA42F60C0000EB09010022CA760A774A7640F843 -:207900000920002088600861C8600DF5097DBDE8F08F4FF418514846FEF776BE02465946AF -:2079200006EB090000F5C060FFF746BC2DE9F04FADF50B7D06460F46DFF89455DFF88C9568 -:20794000B7F5805F0BD14FF40072494601F0F0FE002815D04FF40072314648460CE0B7F53E -:20796000205F0ED109F5007400F076F9002807D04FF4007231462046FFF71EFC012028707E -:2079800036E1B7F5804F22D109F2004400F064F90028F5D04FF4007231462046FFF70CFC59 -:2079A0000120687010240FF24C570C22314600A8FFF702FC0B22394600A801F0B9FE10B9F0 -:2079C000B07E288214E12036641EEED110E1A7F50044B4F5005FF9D807EB0900A0F5F448CD -:2079E0004FF400724146304601F0A2FE08B100F038F9A7F5FC4005EB902A600A801C298A2F -:207A0000884240F0EF8000244FF48C7145A8FEF7FBFDDFF8C08400F024F900260027232007 -:207A200045A900FB061B05E0232F3CBF07F80B007F1C641C404601F0ADFE844208D214F817 -:207A400008000D2802BF04EB080149780A29EBD1002007F80B00A41C761C082EDED30026F7 -:207A6000DFF8547405EB8604D4F814B000F0F1F80246232045A900FB06185946404601F0DC -:207A800057FE002840F09780606901F083FE044604E0202818BF3D2810D1641C404601F05D -:207AA00079FE844280F0A68014F80800A0F13001C9B20A29EDD2302802D1062E40F09A8007 -:207AC00044440122F1B22046FFF7B2FC00287BD0F1B22046FFF7B2FB404601F05BFE014618 -:207AE000404601F08FFB2EB9B7F9100000F0A3F845A835E0012E05D1B7F9120000F095F80D -:207B00004DA81BE0022E05D1B86900F082F80DF5AD7025E0032E04D1F86900F074F85FA8F6 -:207B20001DE0042E05D1B7F9140000F078F868A816E0052E04D100F084F870A8C01C0FE0BF -:207B4000062E07D1FCF700FB02460FF20C410DF5F37005E0072E05D100F050F882A8401C82 -:207B6000FEF766FD761C082EFFF47CAFFE2105A8FEF74AFD0026232045A900FB061105A8A9 -:207B800001F023FE05EB8600416D05A801F01DFE761C082EEFD305A801F0FCFD0446288AD9 -:207BA00009EB4010FF2C80F8DC4300F5777094BF0021210A09E0646B204601F0EBFD024605 -:207BC00021464046FFF7F8FA14E041704FF4007205A909F5C060FFF7FFFA012068708AF840 -:207BE000010005E0012068708AF8010000F078F800F076F80DF50B7DBDE8F08FB148026854 -:020000040800F2 -:207C00000FF2643170476421B0FBF1F20FF21C3170476421B0FBF1F20FF2003170470A21D8 -:207C200090FBF1F20FF2143170470A2190FBF1F20FF2DC2170470A2190FBF1F20FF2C02110 -:207C400070479F4800680A21B0FBF1F20FF2F8217047584601F09EBD4FF40072214601F09D -:207C600067BD4FF4007231464046FFF7A5BA38B504460D46FFF7E0FA25B94FF400720FF2EB -:207C8000003121E09149B5F5805F08BF4FF400721AD0B5F5205F04D14FF4007201F50071CF -:207CA00012E0B5F5804F04D14FF4007201F580610AE0A5F50040B0F5005F0AD84FF4007299 -:207CC00005F1006101F58C412046BDE83840FFF773BA4FF400712046BDE8344001F092BA74 -:207CE000F8B501F061FB00207949425CD2B1002242548402744D281901F087FD73482618D9 -:207D0000002736F8021B3819281801F06DFD042803D001F053FB0420F2BDBF1CB7F5806F7E -:207D2000EFD302E0401C1028DFD301F047FB0020F2BD70B5654C01F037FB0025624E06EB98 -:207D4000852001F062FD6D1C092DF8DB002534F8021B701901F048FD042801D0042070BD21 -:207D6000AD1CB5F5185FF2DB01F028FB002070BD2DE9F04142F61804544D6619574F327ADE -:207D80002AB9400238604802786001203072307A012831D1605978B905F5185839684046F1 -:207DA000FFF765FF40229821404601F043FD4FF4E070605140200CE040229821B868401973 -:207DC00000F5185001F036FD605940386051B8684030B8604021012001F0D7FD30210120DF -:207DE00001F05DFD3868403038607868403878603B48816840398160786838B96051B86000 -:207E0000386038480321017000203072BDE8F0812DE9F04142F61C042C4D62594032661919 -:207E2000314F33792BB9400238604802786001203071307901282FD100202C490AE05B19AF -:207E400003F5185310F801C083F800C0401C63595B1C635163599342F1D3DFF89480B8F888 -:207E600000003968411839607A68101A7860C00507D100206051A1F5007105F51850FFF7BE -:207E800055FD17488168B8F80020891A81604FF44051022001F014FD786800281EBF1148BE -:207EA0000078042806D100206051012101F0D4FE00203071BDE8F0818002002028040020CC -:207EC000340400203004002000C0000864040020E8010020A02C0020188DDD403C31002062 -:207EE0002C310020A03000204831002040300020A2300020434F4E46494720205458540004 -:207F0000545F5374616E6462793D256400000000545F576F726B3D25640000005761697462 -:207F20005F54696D653D25640000000049646C655F54696D653D256400000000545F5374E1 -:207F400065703D25640000005475726E5F4F66665F763D256400000054656D7053686F7791 -:207F6000466C61673D2564005A65726F505F41643D2564004C4F474F494E2020424D500020 -:207F8000EB3C904D53444F53352E3000020108000200025000F80C000100010000000000AC -:207FA00000000000000029A298E46C4E4F204E414D4520202020464154313220202033C916 -:207FC0008ED1BCF07B8ED9B800208EC0FCBD007C384E247D248BC199E83C01721C83EB3ACE -:207FE00066A11C7C26663B07268A57FC750680CA0288560280C31073EB33C98A461098F74E -:020000040800F2 -:20800000661603461C13561E03460E13D18B7611608946FC8956FEB82000F7E68B5E0B03F7 -:20802000C348F7F30146FC114EFE61BF0000E8E600723926382D741760B10BBEA17DF3A66B -:208040006174324E740983C7203BFB72E6EBDCA0FB7DB47D8BF0AC9840740C487413B40E36 -:20806000BB0700CD10EBEFA0FD7DEBE6A0FC7DEBE1CD16CD19268B551A52B001BB0000E828 -:208080003B0072E85B8A5624BE0B7C8BFCC746F03D7DC746F4297D8CD9894EF2894EF6C601 -:2080A00006967DCBEA030000200FB6C8668B46F86603461C668BD066C1EA10EB5E0FB6C890 -:2080C0004A4A8A460D32E4F7E20346FC1356FEEB4A525006536A016A10918B4618969233AA -:2080E000D2F7F691F7F64287CAF7761A8AF28AE8C0CC020ACCB80102807E020E7504B4429F -:208100008BF48A5624CD136161720B40750142035E0B497506F8C341BB000060666A00EBC3 -:20812000B04E544C44522020202020200D0A52656D6F7665206469736B73206F72206F7484 -:20814000686572206D656469612EFF0D0A4469736B206572726F72FF0D0A50726573732064 -:20816000616E79206B657920746F20726573746172740D0A00000000000000ACCBD855AAC1 -:20818000F8FFFFFFFFFF000000B500BF130096469446103928BFA0E80C50FAD85FEA417CC3 -:2081A00028BF0CC048BF40F8042BC90728BF20F8022B48BF00F8012B00BD00002DE9F04F65 -:2081C000A1B0804617461D46029102AE0020706211AC6FF000490AE017F8011B0298C04778 -:2081E0000290002800F06A82706A401C7062387808B9706A64E22528EED10020F060306143 -:208200007061B061F061306201E040F0010017F8011F2029F9D023290DD02B2904D02D299F -:2082200006D030290AD00CE040F0020080B2EEE740F00400FAE740F00800F7E740F01000A5 -:20824000F4E72A290DD129680A1D2A600968F162002904D54942F16240F0040080B27F1C2B -:2082600012E00021F16209E0F16A494505D001EB810302EB43013039F1627F1C3A78A2F1B4 -:208280003001C9B20A29EFD339782E2903D04FF0FF31B1621DE017F8011F2A2906D12968F9 -:2082A0000A1D2A600968B1627F1C12E00021B16209E0B16A494505D001EB810302EB4301C0 -:2082C0003039B1627F1C3A78A2F13001C9B20A29EFD3308639780FF6983001F0FFFC08B1C8 -:2082E00017F8010B8DF83A009DF83A00682804D1387868280AD1622005E06C2804BF3878E7 -:208300006C2803D171208DF83A007F1C11A8B0603978B1F1250023D01C3871D0001F0228F8 -:208320006ED9133800F09680093869D0801E00F02781401E00F0D180401E022860D9001F76 -:2083400000F0CB80401F30D0401E00F08380401E20D0C01E09D0801E7CD0C01E7AD017E123 -:20836000F068411CF16025211BE12868011D296000687060B26A002A02D501F00BFA07E04C -:20838000002101F0B7FC00281ABF7168401AB06A306107E12868011D296000680021CDE9DB -:2083A000000111A870607821E6E09DF83A00622818D0682806D06A280BD06C2819D07128AA -:2083C00007D016E02868011D2960716A00680180E8E02A68101D2860706AC1171268C2E9EF -:2083E0000001DFE02868011D2960716A00680170D8E02868011D2960716A00680160D1E08E -:020000040800F2 -:208400002868C01D20F00700286000F108022A60D0E90023CDE90023002B04D5F068421C5C -:20842000F2602D220DE0308E820704D5F068421CF2602B2205E0C00704D5F068421CF260AC -:2084400020220255F06811AA8018706000A800F0C5F9A7E09DF83A006C2808BF2A6811D08E -:20846000712808BF2A6802D06A282A680AD1D21D22F007022A6094460CF108022A60DCE975 -:20848000002303E0131D2B6012680023CDE90023682808BF92B207D0622808BFD2B203D08B -:2084A000742818BF7A2802D10023CDE9002396F8300000075CD5DDE90023002B08BF002ADD -:2084C00056D041F02000782852D1F06830220255401C421CF26001554AE09DF83A0062287C -:2084E0000CD0682810D06A281AD06C2823D0712816D074281FD07A280CD01CE02868021DFA -:208500002A6090F900201AE02868021D2A60B0F9002014E02868021D2A60026800230FE083 -:208520002868C01D20F00700286000F108022A60D0E9002304E02868021D2A600268D3175D -:20854000CDE90023002B04DAF068421CF2602D220DE0308E820704D5F068421CF2602B2280 -:2085600005E0C00704D5F068421CF26020220255F06811AA8018706000A800F0A4F811E035 -:20858000F068411CF16029680A1D2A60096808E0F068421CF2602522025519B1F068421C14 -:2085A000F26001557F1CF06AF168401AB169401A3169401AF169401A7169401A316AA0EBF5 -:2085C000010A96F83000400711D420208DF84000BAF1010F0BDBD346012310AA00A94046DA -:2085E00000F02FFC002869D1BBF1010BF4D1F36811AA00A9404600F024FC00285ED1302085 -:208600008DF84000D6F818B0BBF1010F0ADB012310AA00A9404600F014FC00284ED1BBF15E -:20862000010BF4D13369726800A9404600F009FC002843D130208DF84000D6F81CB0BBF138 -:20864000010F09DB012310AA00A9404600F0F9FBA0BBBBF1010BF5D17369306971684218B4 -:2086600000A9404600F0EDFB40BB30208DF84000D6F820B0BBF1010F09DB012310AA00A91E -:20868000404600F0DEFBC8B9BBF1010BF5D196F8300040077FF5ABAD20208DF84000BAF10B -:2086A000010FFFF6A4AD012310AA00A9404600F0C8FB18B9BAF1010AF5D198E54FF0FF306C -:2086C00021B0BDE8F08F2DE9FA4782B0064635696F2908BF082705D041F02000782814BF0B -:2086E0000A2710273C24D6E90001804689469DF80820642A18BF692A05D1002903DAD8F103 -:20870000000869EB4909B9F1000F08BFB8F1000F0CD1306B50B9082F3BD196F838000007E2 -:2087200037D53B24302085F83B0032E0A4F1010A5446FB17404649463A4601F007FBCDE92A -:208740000089B846A8FB0023DDE90089A8EB02023032D2B23A2A03D39DF80830513B9A18BB -:208760000AF8052080465FEA010908BFB8F1000F03D0F06861198842D8D3082F09D196F881 -:208780003800000705D5605D302802D0641E30206055C4F13C00B0616119F160316B88421F -:2087A00007DA081A3062308F4FF6EF710840308710E000290ED596F8381001F014011029B0 -:2087C00008D1716B7269891A326A891A081A0128A8BF306204B0BDE8F08700002DE9F24FBC -:2087E0008EB0044604AED4E90001CDE902019DF8380040F020008DF8000061280BD0206B37 -:020000040800F2 -:20880000002848BF062005D404BF9DF80000672801D1012020636168C1F30A5040F2FF7352 -:2088200098421ED1080304BF206800280AD10320A0619DF838006138C0B21A2838D30FF2CC -:20884000446109E00320A0619DF838006138C0B21A282AD30FF224610322E068FEF7ACFCBF -:20886000B9E1012817DA204601F0E7FA012812DB002700209DF80010612920D1E1683022F4 -:2088800001F8012B4A1CE2609DF83820612A0CBF782258220FE040F2FE31626861F31E52D6 -:2088A0006260471A4FF0FF30E4E70FF2CC51D3E70FF2CC51D0E70A706169891C616110B93B -:2088C000002500277EE19DF80000612840F09780206B00284CBF2125451C2DB26E1CD4E9FD -:2088E0000089DDE902010022002301F0C7FA3ABF89F00040CDE90280CDE902893F1F8DF821 -:2089000010200DF11108012E35DBDDE902010022002301F0CBFA2ED21C2102A801F0DEFA5D -:20892000DDE9020101F060FB8146F61F012E09DB01F086FB02460B46DDE9020101F098FBDB -:20894000CDE9020108F20700072105E009F00F0200F8012D4FEA2919B9F1010F01DB491EA8 -:20896000F4D5491E5CBF002200F8012DF9D500F20708012EC9DA0DF11100A8EB00010DF122 -:208980001106A942B8BF0D462DB2002D30D42846884206DA04A941184978082928BF0F21D4 -:2089A00000D2002104AA821800E06D1E401E12F801398B42F9D00F2904D104A941184A7804 -:2089C000521C4A70002802D504AE6D1C3F1D2DB2681E0DD481190A783032D2B23A2A03D357 -:2089E0009DF838303A3B9A1801F80129401EF2D5206B002840F1E680681E2063E2E0DDE930 -:208A000002010022002301F039FA3CBF81F00041CDE902013FB247F297507843474990FB9D -:208A2000F1F73FB2C7F107069246DFF814B1012E19DBDDE90289F00707D552465B4640461E -:208A4000494601F0D5FB8046894676105046594652465B4601F0CCFB82468B46002EEAD103 -:208A6000CDE9028921E076429046DFF8D89012E0F00707D552465B464046494601F0B8FB30 -:208A80008046894676105046594652465B4601F0AFFB82468B46002EEAD1DDE902014246DF -:208AA0004B4601F077FCCDE902019DF8000066280CBF07F10A000620216B4518142DA8BF61 -:208AC000132530208DF810000DF11106DFF87890012D3BDBDDE9020101F09CFA06F10801F1 -:208AE00004220A26B0FBF6F303EB830EA0EB4E00303001F8010DB3FBF6F000EB8006A3EB3A -:208B00004603303301F8013D521EEAD101F10806083D012DDCDBDDE9020101F07BFA01F0FD -:208B200099FA02460B46DDE9020101F0A1FA00224B4601F05DFBCDE90201CBE7A086010026 -:208B4000000024400000F03F84D797410DF11100301A0DF1110602E0401E7F1E761C3178C9 -:208B60003029F9D09DF80010662902D13FB2791C03E065290CBF01210021226B8D182DB2B6 -:208B8000A842B8BF05462DB2002D1BD42946814204DA885D352828BF392000D230208A19D7 -:208BA000521E00E06D1E491E12F801398342F9D0392802D1885D401C8855002902D5761EBB -:208BC0006D1C7F1C3FB200972BB232469DF83810204600F003F80FB0BDE8F08F2DE9F0433A -:208BE00085B00546894617461E46D5F83080012E02DA01260FF2902749F02000BDF930407F -:020000040800F2 -:208C0000662808BF641C18D0672840F082806FF003008442C0F28380444580F28080641C7E -:208C200095F83800000702D44645B8BFB04624B2B8EB040848BF4FF00008E868A96924B28F -:208C4000012C25DA4A1C30230B54B8F1010F03DA95F83810090702D52E211154521CAA6151 -:208C600018EB040FB8BFC8F1000424B261426962A044B045B8BF464636B2EE61324639465C -:208C8000AB691818FEF798FAA8EB0600A862C1E00818A64218DA32463946FEF78DFAA96946 -:208CA0007118A961A01B6862B8F1010F03DA95F83800000705D5E8682E220A54E869401CB5 -:208CC000E861C5F82880A5E022463946FEF774FAA8692018361BB8F1010F03DA95F8381012 -:208CE000090703D5E9682E224254401CA86136B2B045B8BF464636B23246E119EB68C0188B -:208D0000FEF75AFAA8693018A861A8EB0600686280E0B9F1610F16D14FF0700918E04645A9 -:208D200004DA95F83810090758BFB046B8F1010848BF4FF00008B9F1670F14BF4FF04509E3 -:208D40004FF0650904E0B9F1410F08BF4FF05009A9694A1CE86817F8013B0B54B8F1010FFE -:208D600005DA95F83810090758BFAA6117D52E211154531CAB61B8F1010F10DB761E36B2D2 -:208D8000B045B8BF464636B2324639461818FEF713FAA8693018A861A8EB06006862A869F4 -:208DA000E968471807F8019B002C03D42B2007F8010B03E02D2007F8010B644200260DF10A -:208DC000080809E00A22214600A801F006FC019808F8010B009C761C24B2012CF2DA022E9A -:208DE00006DA49F02000652804BF302007F8010B4EB9302007F8010B07E0761E02A8305C7C -:208E0000303007F8010B012EF7DAA869E9684018381AE86195F8380000F0140010280DD1B3 -:208E20006869A9690818696A0818E9690818A96A0818696B8842BCBF081A286205B0BDE878 -:208E4000F083F8B504460D4616461F46002077B116F8011BA868A047A86030B1E86A401C94 -:208E6000E86200207F1EF3D1F2BD4FF0FF30F2BD686A6C747A4C00006E616E004E414E00C9 -:208E8000696E6600494E460030000000002800E0401EFDD1704710B586B0FDF76DFCC02065 -:208EA000ADF8000003208DF802001C208DF8030000F04CF80020ADF808004BF6FF70ADF849 -:208EC0000A003C20ADF80C004FF48060ADF80E004FF48040ADF810005F4801905F4C01A960 -:208EE000204601F081FB0121204601F0DDFB06B010BD5B4A012903D10146104600F053B98F -:208F000019B90146104600F050B9704780B50121082000F0EDF9C020ADF8000014208DF89F -:208F2000030003208DF8020000F010F800F012F800F05BF800F05CF800F055F8002100F0BD -:208F400055F800F050F800F005F801BD00A9444800F0C4B800214020CBE780B5FFF7FAFFE9 -:208F6000002100F043F800F03EF800F041F800F03AF800F03AF800F036F8FFF7EBFF0220F2 -:208F8000BDE8024082E738B50446082508E000F02DF800F028F800F02BF800F024F864008D -:208FA0002846451EC0B230B1FFF7D4FF20064CBF01210021EBE7FFF7CDFF00F016F8FF249B -:208FC00000F011F800F043F848B900F011F800F00AF8FFF7BFFF00F006F8012032BD641E4D -:208FE000EED1002032BD022050E70121802080E7012140207DE770B5044608250026FFF783 -:020000040800F2 -:20900000F4FF0DE0FFF7A6FFFFF7EDFFFFF7F0FFFFF7E9FF760000F01AF808B146F00106C2 -:209020002846451EC0B20028ECD1FFF793FF002C0CBF01210021FFF7D9FFFFF7D4FFFFF7B9 -:20904000D7FFFFF7D0FFFFF785FFF0B270BD8021034800F0A1B80000A0860100005400403C -:20906000000C014070B504460D461646FFF74EFF7000C0B201E014F8010BFFF784FF284680 -:20908000451EC0B20028F6D1BDE8704065E7F8B504460D4616461F46FFF738FF7600F0B21B -:2090A000FFF771FF3846FFF76EFFFFF72FFF46F00100C0B2FFF767FF03E0FFF79CFF04F8D0 -:2090C000010B2846451E28B1EDB2002D0CBF00200120F2E7BDE8F1403FE700002DE9F041E6 -:2090E0000022CC7804F00F03E40644BF8C7823430C8801250F26E7B217B3D0F800C005FAD4 -:2091000002F7BE460EEA0408F04514D14FEA820E06FA0EF82CEA080C03FA0EFE4EEA0C0CE2 -:2091200091F803E0BEF1280F08BF476103D0BEF1480F08BF0761521C082AE0D3C0F800C09B -:20914000B4F5807F26D3D0F804C0002202F1080705FA07F7BE460EEA0408F04515D14FEA65 -:20916000820E06FA0EF82CEA080C03FA0EFE4EEA0C0C91F803E0BEF1280F08BF476191F88C -:2091800003E0BEF1480F08BF0761521C082ADDD3C0F804C0BDE8F08100228068084218BFAA -:2091A000012210467047016170474161704770B5134A00284CBF94691468C0F3034583B2AF -:2091C000460D3601B34000F44016B6F5401F06D124F07064156825F07065156008E0C60273 -:2091E00043BF032606FA05F5AC439C4344F0706401B11C43002801D5946170BD146070BDA2 -:2092000004000140002201F059BA00005048016841F00101016041684E4A114041600168B2 -:209220004D4A11400160016821F480210160416821F4FE0141604FF41F018160704747497C -:209240000860704747490860704745490A68920850EA8200086070474148006800F00C00DE -:20926000704741490860704730B53D490A683F4B02F00C02082A0ED10A680C68C2F38342B6 -:20928000921C3B4D5543E40302D50C68A40301D52B4600E0534303600B68364A0468C3F3F2 -:2092A00003139B5C24FA03F343600B684468C3F302239B5C24FA03F383600B684468C3F32D -:2092C000C2239B5C24FA03F3C3600968C368C1F381318918097CB3FBF1F1016130BD264A04 -:2092E0000029116814BF084321EA000010607047224A0029116814BF084321EA00001060D5 -:2093000070471F4A0029116814BF084321EA0000106070471B4A0029116814BF084321EA0B -:2093200000001060704700214209094B012A08BF1A6803D0022A0CBF1A6A5A6A012300F0AC -:209340001F0003FA00F0024218BF012108467047001002400000FFF8FFFFF6FE0000424200 -:209360000410024060004242D800424200127A0000093D001404002014100240181002407D -:209380001C1002400C100240DFF8D4100A6802F0380206E0DFF8C8100A6822F010020A6013 -:2093A0000A68104308607047FFE7DFF8B800DFF8B8100160DFF8B41001607047FFE7DFF8E4 -:2093C000B000016841F080010160704738B5054600F015F804280DD1DFF89440206840F008 -:2093E00002002060656000F006F8216841F6FD721140216032BD206840F0400020604FF48D -:020000040800F2 -:20940000302039E070B504460D4600F011F804280CD1174E306840F001003060258000F0CC -:2094200007F8316841F6FE721140316070BD08804FF4005020E00F490860704704200D49D2 -:209440000A68D20701D5012070470A68520701D5022070470968C90648BF03207047000078 -:20946000002002400420024023016745AB89EFCD102002400C20024010B5FFE70446FFF799 -:20948000DDFF03E02CB1FFF7D9FF641E0128F9D004B9052010BD00001B4908431B490860C4 -:2094A000704770B503781A460121C478ECB1174B1B6803F4E063C3F5E0631B0A4478C3F14B -:2094C0000405AC4085780F2626FA03F32B4023431B010F4C1355007842110E4B00F01F006C -:2094E00001FA00F043F8220070BD50110A4A03F01F03994042F8201070BD084A11400843CF -:2095000007490860704700000000FA050CED00E000E400E000E100E080E100E080FFFF1FA1 -:2095200008ED00E001684FF6FE72114001600021016041608160C1603349344A90421DD0A8 -:20954000334A904221D0334A904225D0324A904229D0324A90422DD0314A904203D1086864 -:2095600040F4700029E02F4A904203D1086840F0706022E02C492D4A904203D1086840F07B -:209580000F001AE02A4A904203D1086840F0F00013E0284A904203D1086840F470600CE0AD -:2095A000254A904203D1086840F4704005E0234A904203D1086840F470200860704702688D -:2095C0006FF30E128B681A430B6A1A430B691A434B691A438B691A43CB691A434B6A1A4311 -:2095E0008B6A1A430260CA6842600A6882604968C16070470029016812BF41F001014FF62B -:20960000FE7211400160704704000240080002401C000240300002404400024058000240F1 -:209620006C0002408000024004040240080402401C04024030040240440402405804024022 -:2096400030B50488DFF8D820DFF8BC30984218BF90420ED0B0F1804F1CBFDFF8B050A8429A -:2096600007D0DFF8AC50A8421CBFDFF8A850A84204D14FF68F752C404D882C43DFF8985035 -:20968000A8421CBFDFF89450A84204D04FF6FF452C40CD882C4304808C8884850C88048515 -:2096A000984218BF90420AD0DFF8782090421FBFDFF874209042DFF87420904201D1097A5F -:2096C00001860121818230BD0029018812BF41F001014FF6FE72114001807047002A8289C8 -:2096E00014BF114322EA0101818170470029018812BF41F080014FF67F7211400180704788 -:2097000000BFC94301827047002C01400004004000080040000C004000100040001400405B -:20972000003401400040014000440140004801400300002013F0030F09D0521E22BF13F8B8 -:20974000010B11F801CBB0EB0C00F3D07047121F22BF53F8040B51F804CB6045F7D0121DE8 -:209760000AD200BA9CFA8CFCB0EB0C0038BF6FF0000088BF01207047521E22BF13F8010BB1 -:2097800011F801CBB0EB0C00F6D0521C08BF10467047000000F10103810704D010F8011BD0 -:2097A00089B18107FAD10268B2F10131914311F0803F04BF50F8042FF6E710F8011B11B148 -:2097C00010F8011BFBE7C01A7047024600E0521C1378002BFBD111F8013B137012F8013BCC -:2097E000002BF8D17047000038B504460D461048FFF742FE05281CBF3420FFF71CFE2946CB -:020000040800F2 -:209800002046BDE83440FFF7FDBD10B50446A0050CD10748FFF730FE05281CBF3420FFF7C3 -:209820000AFE2046BDE81040FFF7D0BD10BD0000A086010010B5490001F1804101F5C04196 -:20984000521C521009E010F8013B10F8014B43EA042321F8023B891C521EF4D110BD49001D -:2098600001F1804101F5C041521C521004E051F8043B20F8023B521EF9D170474FF6F8710E -:209880000840DFF890110860704710B5DFF8882152F8203048F68F142340194324E010B5A1 -:2098A000DFF8742152F8203048F6BF742340CC0648BF83F01003890648BF83F020030FE054 -:2098C00010B5DFF8542152F820304BF68F742340CC0448BF83F48053890448BF83F40053B7 -:2098E00043F4004141F0800142F8201010BDDFF8281151F820204BF68F731A4082F44052C9 -:2099000042F4004209E0DFF8101151F8202048F68F631A4042F40042FFE742F0800241F890 -:2099200020207047DFF8F01051F8202052040AD551F8202048F68F731A4042F4404242F08E -:20994000800241F820207047334951F8202052060AD551F8202048F68F731A4042F400427E -:2099600042F0C00241F82020704738E0294A126892B202EBC000294A37E03BE02549096849 -:2099800089B201EBC00025493AE0224A126892B202EBC000224A2AE01E4A126892B202EBF8 -:2099A000C000204A02EB40003F2909D34A091F23194208BF521E1204910941F4004105E0DA -:2099C0004A08C90748BF521C12049109016070471049096889B201EBC000124914E00D4AD1 -:2099E000126892B202EBC0000F4A4908490042F8101070470749096889B201EBC0000A49FD -:209A000051F8100080B2704751F810008005800D70470000505C0040005C004008600040B2 -:209A2000046000400C600040006000400106090C41EA10207047000080B5964890F820103D -:209A4000022909D018D3042902D00ED3052913D1002180F820100CE0C17B28290CD1816A1B -:209A6000406ABDE8044000F09CBE0121002000F0F3F84FF440512BE101BD38B5854CE57B30 -:209A80000220FFF7A5FF60840246D8218248FFF7E6FE94F8200010B1012803D00AE0BDE849 -:209AA000314013E02A2D06D1A16A606ABDE8344000F0A1BE022000F0F9F82421052000F07A -:209AC0006BFE00210220BDE83440C5E010B5714C628C1AB170492046FDF77EFB6F486168D5 -:209AE0004160A1688160608C1F2806D0022000F0DDF8002020601A218DE0E27B282A18BF1D -:209B00002A2A0FD1607CA17C090441EA0060E17C40EA0120217D08436062A07DE17D41EA87 -:209B20000020A06220685E49884270D15D480068617B884204D3A07B401EC0B2102804D345 -:209B4000022000F0B3F8242165E0606AA16A002A49D0032A2BD0082A18BF0A2A53D0122AE2 -:209B600029D0152A4FD01A2A2DD01B2A27D01D2A49D01E2A23D0232A2DD0252A2FD0282A8C -:209B800035D02A2A37D02F2A39D0552A3BD05A2A1DD0882A18BF8A2A35D08F2A18BF9E2A6E -:209BA00031D0A82A1CBFAA2AAF2A2CD02FE0BDE8104000F0E9BDBDE8104000F0AFBDBDE8BE -:209BC000104000F0EDBDBDE8104000F0D5BDBDE8104000F0D5BDBDE8104000F0AEBDBDE8B8 -:209BE000104000F0B9BDBDE8104000F043BEBDE8104000F0D6BDBDE8104000F0FCBDBDE80E -:020000040800F2 -:209C0000104000F021BEBDE8104000F038BE022000F04CF82021052000F0BEFD00210120A1 -:209C2000BDE8104018E010B50C4622469821FFF701FE21460120FFF7A8FE30210120FFF77E -:209C40002EFE1448032180F8201014488168091B81600021017310BD10B50C460F4B124938 -:209C6000196018730D2298211846FFF7E3FD0D210120FFF78AFE0748052180F8201044B1E5 -:209C8000042180F8201030210120BDE81040FFF706BE10BD80300020403000202C3100202C -:209CA000555342437C3100205553425380B518B1022807D00AD301BD10210120BDE8044098 -:209CC000FFF7EDBD10210120FFF7E9FD4FF480510220BDE80440FFF7F3BD00000278C9B2FC -:209CE0008A421AB11CBF10F8012FF9E718BF002070470000C9B2830706D0521E22D310F8E4 -:209D0000013B9942F7D11FE0083A13D302F1040241EA012141EA014150F8043B121F21BFF2 -:209D20004B40A3F1013C2CEA030C1CF0803FF3D0C9B2001F083210F8013B521E28BF91EA2A -:209D4000030FF8D818BF0120401E70471B4213D1094236D12AB18446B0FBF2F002FB10C280 -:209D6000704700F0E7BDFCD30022002370470B000200002100207047904271EB030CF6D3C2 -:209D800070B5B1FA81F4B3FA83F52C1BA340C4F1200532FA05F63343A2405FF00046E6401B -:209DA00002E05B085FEA3202841A71EB030524BF204629467641F4D302000B00300000214B -:209DC00070BD012ACFD970B5140C20D0B1FA81F4B2FA82F5C4F120046419B4F12006D6D341 -:209DE000B2405FF00044F440002502E052085FEA3303C61A71EB020E24BF304671466441C9 -:209E00006D41F3D302000B002000290070BD0C46B1FBF2F102FB11452D0445EA1045B5FBB2 -:209E2000F2F402FB145580B240EA0545B5FBF2F002FB105240EA044070BD30B4436803F022 -:209E4000004201211B031B0B436004BF0368002B08D10DE00368DD0F45EA440444605B00CB -:209E60000360491E4468E302F4D523031B0B436043681A434260084630BC70474FF4001CD5 -:209E80001CEB410F94BF1CEB430F09E041EA030C50EA4C0C52EA0C0C03D2994208BF90426D -:209EA000704714BF8B428242704700004FF4001C1CEB410F94BF1CEB430F09E041EA030C4B -:209EC00050EA4C0C52EA0C0C03D28B4208BF8242704714BF994290427047000070B5044612 -:209EE0000D466068C0F30A5040F2FF72904207D16068000304BF2068002817D0022070BD79 -:209F000020B92046FFF799FF012867DA012D0FDB40F2FF71091A8D420AD36068002847BF8B -:209F200000202F4900202F49C4E90001012070BD4142A942616806DA6FF31E51401941EA89 -:209F40000050606041E001F000410122636862F31F536360401E451905F13500352803D30C -:209F600061600020206070BD002215F11F0F04DA20352268236000206060684213D0521EE0 -:209F80009241D243C0F1200325689D4055EAD2722568C540666806FA03F32B432360636806 -:209FA00023FA00F06060606808436060B2F1004F03D80DD12078C0070AD52068401C2060B4 -:209FC000206828B96068401C60604FF0FF3070BD6068884204BF20680028F6D1002070BD80 -:209FE0000000F0FF0000F07FF446400D40EAC120490006D200F014F8004248BF6FF000406C -:020000040800F2 -:20A00000604700F00DF84FF0004188428CBF084640426047400D40EAC120490080F00D80FA -:20A0200040F00040490DA1F58061491C05D4D1F11F0154BFC840C01770474FF00000704724 -:20A04000010040F10980F446404200F005F851F000416047010000BF09D0B0FA80F18840F7 -:20A06000C91CC1F58461090501EBD0214005704770B44FF0004591EA030F44BF6B4000F0A6 -:20A080005BBC00BF841A71EB030604D26E40001BB141121973414FF4001C1CEB410F34BFCE -:20A0A0007CEB430684E00C0DA4EB1356362E7DDC012E43DC45EAC32343EA525312BFD202E4 -:20A0C00092025B08240545EAC12141EA5051D2EBC020994125D407D1B0FA80F610FA06F11A -:20A0E00064D00020203608E0B1FA81F6B140C6F1200220FA02F21143B0404FEAF474B4EB50 -:20A10000465434F001064FEA74040AD8D6F50016760D04F00044F04061FA06F25040F14007 -:20A120004840C00A40EA415021F0004128BF5FEA500550F1000044EBD12137E045EAC323AD -:20A14000DB0A45EAC121C90AB6F120050EDD42EA0242120CC5F1200603FA06F6EB4042EAC5 -:20A1600006056D42984161F100010DE062FA06F5F240554063FA06FC82EA0C02F3405A4048 -:20A180006D42904161EB030111F4801F05D1641E620502D06D004041494121F48011430851 -:20A1A00075F1004350F1000041EB045170BC70471CEB410F15D223F0004352EA43060BD05D -:20A1C0004FEA4C0CBCEB410F04D80C0D661E342EB7DDEBE7801A994150EA410608BF0021D9 -:20A1E000E4E708BF1CEB430F28BF6FF00001DDE7B0B581EA030C0CF0004C40F2FF7515EA9D -:20A2000011541DBF15EA1357AC42AF4239E0E41923EA455343F48013C90241F0004141EAC8 -:20A22000505EC7021100A7FB020200284FF00000EEFB01204FF00001E3FB072118BF42F030 -:20A240000102401800214941E3FB0E01A4F580640F0302D252004041494154F101046CDDB8 -:20A26000470872F1004250F1000051EB0451A1F580115CBF41EA0C01B0BD4CEA0551002085 -:20A28000B0BD05EA1357AC4214BFAF4241E050EA410E1CBF52EA430E02E061460020B0BD1E -:20A2A00024423C441BD15FEA070EF6D0090302BF01460020AEF1140EB1FA81F7AEEB0704EC -:20A2C00001FA07FE0C37C7F1200100FA07F7C8404EEA000E23EA455343F48013A2E733F001 -:20A2E0000043B3FA83F704BFB2FA82FE77440B3FE41BB7F1200E2FBF02FA0EF3BB40C7F18D -:20A30000200E22FA0EFE38BF43EA0E03BA40641C82E750EA410E14BF52EA430E6FF0000186 -:20A320004FF4001717EB430F8ABF194617EB410FB5E74CEA05510020B0BDD4F10104B4F151 -:20A3400020070FDAC4F12007520828BF42F0010210FA07F501FA07F7E1BF2A43E0403843F4 -:20A36000E1400FE0352C98DCC7F1200452EA400220FA07F218BF42F0010231FA07F0A1407C -:20A380000A43002172F1004250F1000051EB0C01B0BD0000F0B540F2FF7581EA030C0CF0F2 -:20A3A000004C15EA11541DBF15EA1357AC42AF42E5E0BC41C1F31301C3F31303801A9941FF -:20A3C00043F4801304D2641E4000494180185941C90241EA5051B1FBF3F603FB1611A2FB71 -:20A3E0000675D7EBC020A94102D2761E80185941C90241EA5051B1FBF3FE03FB1E11A2FBBE -:020000040800F2 -:20A400000E75D7EBC020A94103D2AEF1010E80185941890241EA9051760546EA8E2EB1FBCE -:20A42000F3F603FB1611A2FB0675D7EB8020A94102D2761E80185941C90241EA50514EEA41 -:20A44000060EB1FBF3F603FB1611A2FB0675D7EBC020A94102D2761E80185941C90241EAFA -:20A460005051B1FBF3F703FB1711A2FB0735D3EBC020A94167F100070CBF004247F0010773 -:20A4800066F3D5274FEA1E31B80814F5806412DDBD0775F1004250EB0E5051EB045111F5A7 -:20A4A000801F5CBF41EA0C01F0BD4CF07F6141F0E0410020F0BDBD076D0840EA0E5041F4CC -:20A4C0008011D4F10104B4F120060ADAC4F120060200E04001FA06F3E1401843B2401543BB -:20A4E0000EE0342C13DCC6F1200445EA40056D0820FA06F2154321FA06F0A1400D4300218E -:20A5000075F1004250F1000051EB0C01F0BD00205FEA0C01F0BDCFB992185B41B3FA83F744 -:20A5200004BFB2FA82F6BF190B3FB7F120062FBF02FA06F3BB40C7F1200622FA06F638BF79 -:20A540003343BA401CB1E419641E33E77F4231F00041B1FA81F404BFB0FA80F6A4190B3CFB -:20A56000B4F120062FBF00FA06F1A140C4F1200620FA06F638BF3143A0403C1B1AE7AC42CE -:20A580001ABF05EA1357AF4212E050EA41061CBF52EA4306BFE750EA4107304661461CBFA5 -:20A5A00041EA0551F0BD52EA430C08BFC143F0BD00204FF4001616EB410F98BF16EB430FF6 -:20A5C00008BF16EB410F24BFC14305E016EB430F0CBF61464CEA0551F0BD91FBF2F303FB2A -:20A5E0001211C0E90031704770B586B004460D46A68800A8FEF738FE02992948B1FBF0F016 -:20A600004FF6C07232400243A28022884FF6FE731A4022802A68234B9A4208D25200B1FBDA -:20A62000F2F18AB2042A38BF042189B220E0EB884BF6FF76B34204D102EB4202B1FBF2F1C3 -:20A6400006E019235A43B1FBF2F141F4804189B20A0504BF41F0010189B241F4004189B28A -:20A6600080B24FF4967250434FF47A7290FBF2F0401C2084A183208840F0010020802088E9 -:20A680004FF6F5310840A9880843698908432080A88929890843208106B070BD00000000FC -:20A6A00040420F00A18601000029018812BF41F001014FF6FE72114001807047401810F095 -:20A6C000030308D0C91A1FD3DB0748BF00F8012D28BF20F8022D130030B414461546103995 -:20A6E00028BF20E93C00FAD8490728BF20E90C0048BF40F8042D890028BF20F8022D48BFE2 -:20A7000000F8012D30BC7047C91818BF00F8012DCB0728BF00F8012D704700007449087CBB -:20A72000C00702D57348052105E00FF2E410C97C252928BF2421FFF776BA6F480021818002 -:20A74000022181710021C1714172022181720021C1720C21FFF767BA6848002101800F21AE -:20A760008170FF21C17000218180022181710021C1710821FFF757BA04216148FFF753BA0C -:20A7800008216048FFF74FBA5948C17C132928BF12215D48FFF747BA5B4A90701173704739 -:20A7A00069E070B504460D46584E3078C0B92A462146282000F076F8C8B14D48007B0006BB -:20A7C00003D50220307029460CE00220FFF76EFA00F00EF801210120BDE87040FFF73CBA8A -:20A7E000022804D12046BDE87040FDF7C1BA70BD24210520D0E710B5444C2278EAB90A4600 -:020000040800F2 -:20A8000001462A2000F04EF8E8B13948007B000608D4012020704FF440510220BDE810405E -:20A82000FFF74EB80020FFF741FAFFF7E1FF00210120BDE81040FFF70FBA012A04BFBDE86C -:20A840001040FDF7E5BA10BD80B52948816829B9007C400702D40121002006E00220FFF7FE -:20A8600025FAFFF7C5FF00210120FFE7BDE80440FFF7F2B900BF01210020FFF7EDB980B57B -:20A880001B48816809B9002004E0007B00064CBF00200220FFF70AFA2021FFF7AAFF0021DD -:20A8A0000120E3E780B55118B1F5805F09D92A2804BF0220FFF7FAF90020FFF7F7F9212140 -:20A8C0000BE00B498968B1EB422F0ED02A280CBF02200020FFF7EAF92421FFF78AFF002140 -:20A8E0000120FFF7B9F9002002BD012002BD0000803000206831002038040020703100202A -:20A90000600400205404002000040020A030002000800202200000004D696E692044534FF0 -:20A920004469736B2020202020202020202020202020202070470000841A71EB030603D2FD -:20A94000001BB141121973414FF4001C1CEB410F34BF7CEB430443E00C0DA4EB1356352E1D -:20A9600050DC45EAC323DB0A45EAC121C912B6F120050DDD63FA05F6EB4086EA03051242C0 -:20A9800018BF45F00105C01851F100010CD213E062FA06F5F2405540F3415A40B340F340A7 -:20A9A0005A408018594107D349085FEA30005FEA350528BF45F0010501F58011420875F14B -:20A9C000004250F1000041EB045170BC4FF4001C1CEB410F38BF70470020090D09057047E8 -:20A9E0001CEB410F10D252EA43060BD0BCEB410F05D80C0DAB43661E342EB5DD02E0AB439B -:20AA00008018594170BC704770BC704710B5DFF8884700B92BE000F096F8006880472068DA -:20AA20000A3010BD80B5DFF870070068C178DFF86C2752788A420CD38278002A04BF82881B -:20AA4000002A06D1817200F07EF840688047002002BD022002BD10B5DFF83C4700B906E0AF -:20AA600000F071F88068804720680C3010BD206801210182002010BD10B5DFF81C4720689C -:20AA8000C1784079DFF8182712689269904721688A7A92B1002804BF087900280DD1887820 -:20AAA00058B900F050F8C068804720684179C1722068C1780173002010BD022010BD1CB507 -:20AAC000DFF8D416096810B90220088239E0DFF8D44600202080087800227F23184215D181 -:20AAE000487A81064CBF42F0020102F0FD0121702178400654BF01F0FE0041F001002070A9 -:20AB000000F021F800698047204616BD00F07F03012BF9D000F07F00022812D1487900F02F -:20AB20000F0142F0010200F088FA05D500F030001028E5D12270E3E700F44050B0F5805F12 -:20AB4000F7E7002016BDDFF8600600687047F8B5DFF844060068017811F07F0104D1417A08 -:20AB600001F0DF0141724FE0022901BF41880029017900294AD1417921F08005DFF82C46EE -:20AB80000A0654F825204CBF02F0300202F44052DFF808361B789D4238D2002A1CBF807ACD -:20ABA000002833D0080654F825000BD500F03000102825D12846FEF7C7FE30212846FEF7E1 -:20ABC0006EFE1DE000F44050B0F5805F18D148F280064BF68F7745B900F0BDFA206838406F -:20ABE00080F44050304320600AE02846FEF79AFE54F82500384080F44050304344F82500B8 -:020000040800F2 -:20AC0000FFF7A1FF406980470020F2BD0220F2BD38B5DFF884050268537923F08000DFF8A1 -:20AC20008C151C0651F820404CBF04F0300404F44054DFF868552D78A84206D2558825B933 -:20AC4000002C1CBF927A002A01D1022032BD48F280021B0651F8203005D548F6BF742340B0 -:20AC600083F0100304E04BF68F74234083F480531A4341F82020FFF766FF80698047002078 -:20AC800032BD80B5DFF810050068417A41F020014172FFF758FFC0698047002002BDDFF889 -:20ACA000F8241268538A20B98888C01A108200207047086818187047F8B5DFF8DC5428685A -:20ACC00000F110042688A168080018BF002E14D0A088864288BF064630468847074620880A -:20ACE000801B20806088301860800020FEF746FE324601463846FEF7B2FDDFF8B464208838 -:20AD000050B1DFF8B0044FF44051018000210020FEF73BFE3020308028682188A2889142AD -:20AD200028BF032101D211B105210172F1BD06210172DFF88404006880B2DFF8801400220C -:20AD400041F8102030203080F1BD2DE9F843DFF84844206800F110063188DFF85454002938 -:20AD600004BF007A042816D1DFF85404017801290DD1DFF84414096889B2DFF8402400239A -:20AD800042F8113030212980042703702CE007271020288028E0B6F80480884505D3042784 -:20ADA000414588BF4146884600E002274046B168884781460020FEF7E0FD424601464846E4 -:20ADC000FEF738FD41460020FEF7DFFD3088A0EB0800308070884044708030202880DFF89B -:20ADE000D4034FF44051018020680772BDE8F18338B5DFF8A4432068457801787F221142B0 -:20AE000038D1092D02D1FFF70DFE47E0052D1BD1C17880294FD28178002901BF81880029C3 -:20AE2000807A002847D10620DFF88C13096889B2DFF88823002342F81130DFF874133022C0 -:20AE40000A802168087231BD032D08D1C178012904BF8088002823D1FFF713FF1EE0012DF0 -:20AE600004BFC17801291BD18188C9B9407A80060DD415E001F07F00012804D10B2D0FD199 -:20AE8000FFF7FAFD0AE002280AD1012D02D1FFF75EFE03E0032D03D1FFF7BAFE0028C2D034 -:20AEA0002846BF49096849698847032808BF0920C7D00028B7D00820C3E738B5B64D286877 -:20AEC0004178B74C062913D101787F2211422AD18078012802D12068C16968E0022802D150 -:20AEE0002068016A63E003281DD12068416A5EE000293DD14188002904BFC188022912D14F -:20AF0000017981B901787F22114204BF8288002A2CD001F07F02012A10D100F089F810B965 -:20AF20002868807A10BB28684078216809698847032845D128680921017231BD01F07F01DD -:20AF40000229F0D1407900F00F0100F0700200F074F84CBF00F0300000F440508F4B1B7872 -:20AF60009942E0D2002ADED10028DCD095491EE0082905D100787F210842D4D1924916E0DC -:20AF80000A2902BF017801F07F010129CBD1817A0029C8D04188002901BF01790029C188B3 -:20AFA0000129C0D100F044F80028BCD187490800B9D028680022428281610020884700202D -:20AFC00029680A8A4FF6FF739A4208BF092004D0022818BF002A02D10820087231BD0878E7 -:20AFE00000061ED5C88800902368009C944202D2009808820FE082420DD293F82C00704C80 -:020000040800F2 -:20B00000824238BF002005D392FBF0F500FB152008B90120207093F82C008882BDE8314092 -:20B0200093E60320087263484FF44051018031BD002140792268926910475C4B000653F85E -:20B040002100704738B55C48006880B2604931F81000400000F1804000F5C0404E4C216802 -:20B060000A7A092A14D010F8012B0A70216810F8012B4A70851C35F8040BFEF7D7FC2168E2 -:20B0800048802888FEF7D2FC21688880A888C8802068012101722068C08810B9FFF7A8FE1A -:20B0A00001E0FFF70AFFBDE831403EE010B53A4C2068017A022918BF042904D1FFF745FEF1 -:20B0C0002068007A14E0062911D14178052902BF01787F22114206D1C07800F042F8FFF725 -:20B0E00032FD006A80472E48006880688047082017E010B5284C2068007A022818BF0428DC -:20B100000ED0032818BF052804D1FFF7D5FD2068007A06E0072803D121480068C0688047DA -:20B12000082021680872BDE8104080B500F013F819480068017A082906D11E494FF48052F7 -:20B140000A801B4910220A80007A092801D1012002BD002002BD1F4890F82C100020FEF7C9 -:20B160001BBC70B50D4909780022104B48F68F760BE0D4B253F824503540254345F40045B1 -:20B1800045F0800543F82450521C8A42F1D340F080001149086070BDC83000205C04002011 -:20B1A000CC30002084310020D0300020005C00408A31002088310020505C0040046000409E -:20B1C00091310020BFAA00080DAA000857AA000808600040D00200204C5C0040704700001B -:20B1E00080B500F0F8F88B4800680021817200F031F98948002141604FF40441874A118054 -:20B20000016087480021016001BD10B5854800218172804800688449C97941720020FEF711 -:20B220002DFB4FF400710020FEF72FFB20210020FEF735FB18210020FEF798FB7B4C00F0D5 -:20B2400042F858210020FEF790FB0020FEF75BFB0020FEF74CFB00210120FEF716FB9821D3 -:20B260000120FEF782FB20210120FEF718FB00210120FEF725FB00210220FEF706FBD82148 -:20B280000220FEF773FB94F82C100220FEF784FB4FF440510220FEF713FB00210220FEF79A -:20B2A000FEFA00F010F80020FEF721FB0020FFF758FF5B48012101605D485E4901605E4887 -:20B2C0000021017010BD94F82C100020FEF764BB50480068807A00B9704780B550480521B6 -:20B2E00001600120FEF730FB0220FEF71BFB52480021017001BD4E4800684E4988421CBF5B -:20B300000220FEF7D3BC704745480421016070477047704780B53F4909680A7802F07F0275 -:20B32000212A08BFFE280BD14888002801BF88880028C888012803D10FF28900020001D15E -:20B34000022002BD88610020488200F03BF8002002BD80B52F4909680A7802F07F02212AD9 -:20B3600008BFFF2815D14888002804BF888800280FD1C88868B90120FEF7E6FA0220FEF7A8 -:20B38000D1FA2B482B4901602B4800210170002002BD022002BD00290CBF002802207047E0 -:20B3A0002649FFF77CBC2649FFF779BC19490968C978062901DB00207047224A02EBC10145 -:20B3C000FFF76DBC28B91348006801210182002070471D4870471D4801684268806801B9F8 -:20B3E000704710B51A4B99700C0A1C710C0C9C71090E19729A72110A1973110C9973110EFE -:020000040800F2 -:20B4000019749874010A1975010C9975000E187610BD0000C8300020405C00408E310020A3 -:20B4200080310020AC300020A0B80008D00200208030002055534243A03000204404002098 -:20B440004C040020000300207C310020E8F7FF1FAC030020064801210160002101604160CC -:20B460004FF4E051034A1180FFE7016000207047405C00408E310020545F5374616E646292 -:20B4800079000000545F576F726B0000576169745F54696D6500000049646C655F54696D53 -:20B4A00065000000545F5374657000005475726E5F4F66665F76000054656D7053686F77A9 -:20B4C000466C6167000000005A65726F505F416400000000545F5374616E6462793D3230D7 -:20B4E00030000000545F576F726B3D3330300000576169745F54696D653D3138300000009D -:20B5000049646C655F54696D653D333630000000545F537465703D31300000005475726E53 -:20B520005F4F66665F763D313000000054656D7053686F77466C61673D3000005A65726F60 -:20B54000505F41643D3233390000000020202023283130307E343030290D0A0020202020AE -:20B56000202023283130307E343030290D0A0000202020232836307E39393939290D0A00AA -:20B5800020202023283330307E39393939290D0A00000000202020202020202328357E32BB -:20B5A00035290D0A000000002020202328397E3132290D0A0000000020202328302C3129D0 -:20B5C0000D0A00002020202023526561644F6E6C790D0A002DE9F84F0020ADF8000040F624 -:20B5E0008F7848F60F7B48F28006444F444CDFF81491DFF814A14BF6BF7525E054F820109B -:20B60000ADF80010BDF8001009040BD554F8201008EA010144F820103C4901EB800050F8AE -:20B62000040C8047BDF8000000060DD599F8000054F820100BEA010144F82010344901EBBD -:20B64000800050F8040C8047606CAAF80000000452D5BAF8000010F00F0089F80000CDD1D2 -:20B6600020683880388800F030007880388800F4405038802068284080F4005080F0200072 -:20B6800030432060BAF80000C006206805D40BEA00002060FFF70AFD16E0ADF80000BDF81C -:20B6A0000000000506D5206808EA00002060FFF7C9FC09E0BDF800000004C5D5206808EA3F -:20B6C00000002060FFF715FD206828403988C90448BF80F480503988890448BF80F4005000 -:20B6E0007988C90648BF80F010007988890648BF80F0200030432060BDE8F18F88310020DB -:20B70000005C0040923100208C310020E4030020C80300202E48016841F0010101604168BF -:20B720002C4A1140416001682B4A11400160016821F480210160416821F4FE0141604FF4F0 -:20B740001F0181600021026842F4803202600268491C920302D4B1F5A06FF8D10168890366 -:20B7600030D51E490A6842F010020A600A68920892000A600A6842F002020A6041684160D9 -:20B7800041684160416841F480614160416821F47C114160416841F4E8114160016841F001 -:20B7A0008071016001688901FCD54168890889004160416841F002014160416801F00C01EA -:20B7C0000829FAD106484FF00061016070470000001002400000FFF8FFFFF6FE00200240CA -:20B7E00008ED00E02DE9F04500F10801026801EB8202406800F001034008400002EB8000C4 -:020000040800F2 -:20B800000025AA460024A0460126374602E00027F44511D1824201D1BDE8F08552F804CB78 -:20B8200003B1CC4452F804EBE644F1E70D686D18091D51F804ABAA445545F7D066B115F97D -:20B84000014B0026012705E00D686D18091D51F804ABAA445545F7D0002C12D50FB115F822 -:20B86000018BF445D3D00CF8018B641CF9D40AE0F44518BF5545CBD015F8018B0CF8018B2B -:20B88000641E002CF4D50126C2E70000120100020000004083042057000201020301000005 -:20B8A00009022000010100C0320904000002080650040705810240000007050202400000D9 -:20B8C000040309042603530054004D006900630072006F0065006C0065006300740072000B -:20B8E0006F006E0069006300730000002603530054004D003300320020004D006100730069 -:20B9000073002000530074006F007200610067006500000010035300540020004D00610037 -:20B9200073007300FBF7D1F84FF48040FBF705F9FBF7FCF9FBF723FAFBF719F90020FBF767 -:20B94000A2F8C820FBF792F80120FBF79CF800F035F8FDF7A0FAFBF751F9FAF747FC0628F9 -:20B9600018BFFBF7D0FAFAF752FCFAF715FFFAF733FFFBF776F8F8F7FDFBFBF7EAFDFBF7BB -:20B980003BFEFAF74BFC0020FAF7B2FA40F6B830FAF70EFC084CFAF720FCFAF727FC0628BD -:20B9A00005D0206918B9FBF7FCFA32202061F9F731FFFAF78EFCEEE7D83000200448C06198 -:20B9C0000221017203490162034A426208680047AC300020D00200204C03002070B50D4C9F -:20B9E0000D4D286820800D4E208831880840400505D50B48406880474FF6FF302860208834 -:20BA000031880840000444BFBDE87040FFF7E2BD70BD00008C310020445C00408E3100206B -:20BA2000D0020020FEF708B8FEF727B810B5074979441831064C7C44163404E0081D0A6899 -:20BA4000511888470146A142F8D110BD0800000030000000BBABFFFF302D0000640400206D -:20BA60000000000081FDFFFF0200000002000000A0010000570200000000002064040000C4 -:20BA80007047FEE7FEE7FEE7FEE77047704770477047FFF7A3BFFBF7A7B9FBF7C5B9000065 -:20BAA00000F009F8002801D0FFF7C0FF0020FFF739FF00F002F80120704700F001B800002E -:20BAC0000746384600F002F8FBE70000C046C046024A11001820ABBEFBE700BF26000200FC -:20BAE000014880470148004715B70008F1BA0008C046C046C046C046FFF7D2FFFFF7C0BFCB -:20BB0000FFF7BFBFFFF7BEBFFFF7BDBFFFF7BCBFFFF7BBBFFFF7BABFFFF7B9BFFFF7B8BFA1 -:20BB2000FFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBF6D -:20BB4000FFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBF4D -:20BB6000FFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF78FBFFFF7FEBFFFF7FEBFFFF7FEBF9C -:20BB8000FFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF781BFFFF781BFFFF7FEBFFFF7FEBF07 -:20BBA000FFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFED -:20BBC000FFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFCD -:20BBE000FFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBFAD -:020000040800F2 -:20BC0000FFF7FEBFFFF7FEBFFFF7FEBFFFF7FEBF03040C7480FD000380740C04FC0004034A -:20BC20001C601C03FA000080FC400080FB00011F22FC42012213FC00044040C00080FD4085 -:20BC400000C0FD000540407F414040F700016060F600016060F9000078FB04018878FC0086 -:20BC6000076050484442414070F000016060F60002E01808FD04020818E0FD00020F302044 -:20BC8000FD400220300FFB00020808FCF7000240407FFD4081008100BF006278B4000884ED -:20BCA000B400088CB4000898B40008A4B40008ACB40008B8B40008C8B40008D4B40008E4F8 -:20BCC000B40008F0B4000800B5000810B500081CB500082CB500083CB500084CB500085C52 -:20BCE000B5000870B5000880B5000894B50008A8B50008B8B50008C4B50008010001E5008A -:20BD000000FADB005780AE80D5805280A8800F80C080D38000804080A0808D801480DA807D -:20BD2000028081803380D980F180DB803080A480A680AF0000E1B100080BB2000811B300DC -:20BD40000813B3000815B3000853B3000897B30008A1B30008A7B30008ADB30008FC0000BB -:20BD600040FD0004C0B8000804FD0004C4B8000826FD0004ECB8000826FD0004AC030020B0 -:20BD80001AFD000414B9000810F50003A00FE803FC000033F1000010FD0023DDB10008D15A -:20BDA000B20008DDB10008DDB10008DDB10008F7B20008DDB10008DDB1000809B30008FD69 -:20BDC000000201000AEA000010F100018813F60012881300001A03530054004D00330032B6 -:20BDE00000310030F3003825BA0008DDB10008DDB10008DDB10008DDB10008DDB10008DD05 -:20BE0000B10008DDB1000829BA0008DDB10008DDB10008DDB10008DDB10008DDB10008708A -:20BE2000FA00000AF00011010203040102030406070809020406080001FA0000EFFD0000D0 -:20BE400064FA000008FC000002FD00048CB8000812FD0004A0B8000820FC000006FA00049E -:20BE60000301000003FD0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD6 -:20BE8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC2 -:20BEA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA2 -:20BEC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF82 -:20BEE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF62 -:20BF0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF41 -:20BF2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF21 -:20BF4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01 -:20BF6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE1 -:20BF8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC1 -:20BFA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA1 -:20BFC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF81 -:20BFE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF61 -:020000040800F2 -:20C00000F8FFFFFFFFFF00000000000000000000000000000000000000000000000000002D -:20C02000000000000000000000000000000000000000000000000000000000000000000000 -:20C040000000000000000000000000000000000000000000000000000000000000000000E0 -:20C060000000000000000000000000000000000000000000000000000000000000000000C0 -:20C080000000000000000000000000000000000000000000000000000000000000000000A0 -:20C0A000000000000000000000000000000000000000000000000000000000000000000080 -:20C0C000000000000000000000000000000000000000000000000000000000000000000060 -:20C0E000000000000000000000000000000000000000000000000000000000000000000040 -:20C1000000000000000000000000000000000000000000000000000000000000000000001F -:20C120000000000000000000000000000000000000000000000000000000000000000000FF -:20C140000000000000000000000000000000000000000000000000000000000000000000DF -:20C160000000000000000000000000000000000000000000000000000000000000000000BF -:20C1800000000000000000000000000000000000000000000000000000000000000000009F -:20C1A00000000000000000000000000000000000000000000000000000000000000000007F -:20C1C00000000000000000000000000000000000000000000000000000000000000000005F -:20C1E00000000000000000000000000000000000000000000000000000000000000000003F -:20C20000F8FFFFFFFFFF00000000000000000000000000000000000000000000000000002B -:20C220000000000000000000000000000000000000000000000000000000000000000000FE -:20C240000000000000000000000000000000000000000000000000000000000000000000DE -:20C260000000000000000000000000000000000000000000000000000000000000000000BE -:20C2800000000000000000000000000000000000000000000000000000000000000000009E -:20C2A00000000000000000000000000000000000000000000000000000000000000000007E -:20C2C00000000000000000000000000000000000000000000000000000000000000000005E -:20C2E00000000000000000000000000000000000000000000000000000000000000000003E -:20C3000000000000000000000000000000000000000000000000000000000000000000001D -:20C320000000000000000000000000000000000000000000000000000000000000000000FD -:20C340000000000000000000000000000000000000000000000000000000000000000000DD -:20C360000000000000000000000000000000000000000000000000000000000000000000BD -:20C3800000000000000000000000000000000000000000000000000000000000000000009D -:20C3A00000000000000000000000000000000000000000000000000000000000000000007D -:20C3C00000000000000000000000000000000000000000000000000000000000000000005D -:20C3E00000000000000000000000000000000000000000000000000000000000000000003D -:020000040800F2 -:20C40000434F4E46494720205458540000000000000000000000188DDD400200D60000008C -:20C420000000000000000000000000000000000000000000000000000000000000000000FC -:20C440000000000000000000000000000000000000000000000000000000000000000000DC -:20C460000000000000000000000000000000000000000000000000000000000000000000BC -:20C4800000000000000000000000000000000000000000000000000000000000000000009C -:20C4A00000000000000000000000000000000000000000000000000000000000000000007C -:20C4C00000000000000000000000000000000000000000000000000000000000000000005C -:20C4E00000000000000000000000000000000000000000000000000000000000000000003C -:20C5000000000000000000000000000000000000000000000000000000000000000000001B -:20C520000000000000000000000000000000000000000000000000000000000000000000FB -:20C540000000000000000000000000000000000000000000000000000000000000000000DB -:20C560000000000000000000000000000000000000000000000000000000000000000000BB -:20C5800000000000000000000000000000000000000000000000000000000000000000009B -:20C5A00000000000000000000000000000000000000000000000000000000000000000007B -:20C5C00000000000000000000000000000000000000000000000000000000000000000005B -:20C5E00000000000000000000000000000000000000000000000000000000000000000003B -:20C60000545F5374616E6462793D32303020202023283130307E343030290D0A545F576FBC -:20C62000726B3D33303020202020202023283130307E343030290D0A576169745F54696D41 -:20C64000653D313830202020232836307E39393939290D0A49646C655F54696D653D3336DA -:20C660003020202023283330307E39393939290D0A545F537465703D3130202020202020FD -:20C68000202328357E3235290D0A5475726E5F4F66665F763D31302020202328397E31327A -:20C6A000290D0A54656D7053686F77466C61673D3020202328302C31290D0A5A65726F50D4 -:20C6C0005F41643D3233392020202023526561644F6E6C790D0A00000000000000000000A3 -:20C6E00000000000000000000000000000000000000000000000000000000000000000003A -:20C70000000000000000000000000000000000000000000000000000000000000000000019 -:20C720000000000000000000000000000000000000000000000000000000000000000000F9 -:20C740000000000000000000000000000000000000000000000000000000000000000000D9 -:20C760000000000000000000000000000000000000000000000000000000000000000000B9 -:20C78000000000000000000000000000000000000000000000000000000000000000000099 -:20C7A000000000000000000000000000000000000000000000000000000000000000000079 -:20C7C000000000000000000000000000000000000000000000000000000000000000000059 -:20C7E000000000000000000000000000000000000000000000000000000000000000000039 -:020000040800F2 -:20C80000000000000000000000000000000000000000000000000000000000000000000018 -:20C820000000000000000000000000000000000000000000000000000000000000000000F8 -:20C840000000000000000000000000000000000000000000000000000000000000000000D8 -:20C860000000000000000000000000000000000000000000000000000000000000000000B8 -:20C88000000000000000000000000000000000000000000000000000000000000000000098 -:20C8A000000000000000000000000000000000000000000000000000000000000000000078 -:20C8C000000000000000000000000000000000000000000000000000000000000000000058 -:20C8E000000000000000000000000000000000000000000000000000000000000000000038 -:20C90000000000000000000000000000000000000000000000000000000000000000000017 -:20C920000000000000000000000000000000000000000000000000000000000000000000F7 -:20C940000000000000000000000000000000000000000000000000000000000000000000D7 -:20C960000000000000000000000000000000000000000000000000000000000000000000B7 -:20C98000000000000000000000000000000000000000000000000000000000000000000097 -:20C9A000000000000000000000000000000000000000000000000000000000000000000077 -:20C9C000000000000000000000000000000000000000000000000000000000000000000057 -:20C9E000000000000000000000000000000000000000000000000000000000000000000037 -:20CA0000000000000000000000000000000000000000000000000000000000000000000016 -:20CA20000000000000000000000000000000000000000000000000000000000000000000F6 -:20CA40000000000000000000000000000000000000000000000000000000000000000000D6 -:20CA60000000000000000000000000000000000000000000000000000000000000000000B6 -:20CA8000000000000000000000000000000000000000000000000000000000000000000096 -:20CAA000000000000000000000000000000000000000000000000000000000000000000076 -:20CAC000000000000000000000000000000000000000000000000000000000000000000056 -:20CAE000000000000000000000000000000000000000000000000000000000000000000036 -:20CB0000000000000000000000000000000000000000000000000000000000000000000015 -:20CB20000000000000000000000000000000000000000000000000000000000000000000F5 -:20CB40000000000000000000000000000000000000000000000000000000000000000000D5 -:20CB60000000000000000000000000000000000000000000000000000000000000000000B5 -:20CB8000000000000000000000000000000000000000000000000000000000000000000095 -:20CBA000000000000000000000000000000000000000000000000000000000000000000075 -:20CBC000000000000000000000000000000000000000000000000000000000000000000055 -:20CBE000000000000000000000000000000000000000000000000000000000000000000035 -:020000040800F2 -:20CC0000000000000000000000000000000000000000000000000000000000000000000014 -:20CC20000000000000000000000000000000000000000000000000000000000000000000F4 -:20CC40000000000000000000000000000000000000000000000000000000000000000000D4 -:20CC60000000000000000000000000000000000000000000000000000000000000000000B4 -:20CC8000000000000000000000000000000000000000000000000000000000000000000094 -:20CCA000000000000000000000000000000000000000000000000000000000000000000074 -:20CCC000000000000000000000000000000000000000000000000000000000000000000054 -:20CCE000000000000000000000000000000000000000000000000000000000000000000034 -:20CD0000000000000000000000000000000000000000000000000000000000000000000013 -:20CD20000000000000000000000000000000000000000000000000000000000000000000F3 -:20CD40000000000000000000000000000000000000000000000000000000000000000000D3 -:20CD60000000000000000000000000000000000000000000000000000000000000000000B3 -:20CD8000000000000000000000000000000000000000000000000000000000000000000093 -:20CDA000000000000000000000000000000000000000000000000000000000000000000073 -:20CDC000000000000000000000000000000000000000000000000000000000000000000053 -:20CDE000000000000000000000000000000000000000000000000000000000000000000033 -:20CE0000000000000000000000000000000000000000000000000000000000000000000012 -:20CE20000000000000000000000000000000000000000000000000000000000000000000F2 -:20CE40000000000000000000000000000000000000000000000000000000000000000000D2 -:20CE60000000000000000000000000000000000000000000000000000000000000000000B2 -:20CE8000000000000000000000000000000000000000000000000000000000000000000092 -:20CEA000000000000000000000000000000000000000000000000000000000000000000072 -:20CEC000000000000000000000000000000000000000000000000000000000000000000052 -:20CEE000000000000000000000000000000000000000000000000000000000000000000032 -:20CF0000000000000000000000000000000000000000000000000000000000000000000011 -:20CF20000000000000000000000000000000000000000000000000000000000000000000F1 -:20CF40000000000000000000000000000000000000000000000000000000000000000000D1 -:20CF60000000000000000000000000000000000000000000000000000000000000000000B1 -:20CF8000000000000000000000000000000000000000000000000000000000000000000091 -:20CFA000000000000000000000000000000000000000000000000000000000000000000071 -:20CFC000000000000000000000000000000000000000000000000000000000000000000051 -:20CFE000000000000000000000000000000000000000000000000000000000000000000031 -:020000040800F2 -:20D00000000000000000000000000000000000000000000000000000000000000000000010 -:20D020000000000000000000000000000000000000000000000000000000000000000000F0 -:20D040000000000000000000000000000000000000000000000000000000000000000000D0 -:20D060000000000000000000000000000000000000000000000000000000000000000000B0 -:20D08000000000000000000000000000000000000000000000000000000000000000000090 -:20D0A000000000000000000000000000000000000000000000000000000000000000000070 -:20D0C000000000000000000000000000000000000000000000000000000000000000000050 -:20D0E000000000000000000000000000000000000000000000000000000000000000000030 -:20D1000000000000000000000000000000000000000000000000000000000000000000000F -:20D120000000000000000000000000000000000000000000000000000000000000000000EF -:20D140000000000000000000000000000000000000000000000000000000000000000000CF -:20D160000000000000000000000000000000000000000000000000000000000000000000AF -:20D1800000000000000000000000000000000000000000000000000000000000000000008F -:20D1A00000000000000000000000000000000000000000000000000000000000000000006F -:20D1C00000000000000000000000000000000000000000000000000000000000000000004F -:20D1E00000000000000000000000000000000000000000000000000000000000000000002F -:20D2000000000000000000000000000000000000000000000000000000000000000000000E -:20D220000000000000000000000000000000000000000000000000000000000000000000EE -:20D240000000000000000000000000000000000000000000000000000000000000000000CE -:20D260000000000000000000000000000000000000000000000000000000000000000000AE -:20D2800000000000000000000000000000000000000000000000000000000000000000008E -:20D2A00000000000000000000000000000000000000000000000000000000000000000006E -:20D2C00000000000000000000000000000000000000000000000000000000000000000004E -:20D2E00000000000000000000000000000000000000000000000000000000000000000002E -:20D3000000000000000000000000000000000000000000000000000000000000000000000D -:20D320000000000000000000000000000000000000000000000000000000000000000000ED -:20D340000000000000000000000000000000000000000000000000000000000000000000CD -:20D360000000000000000000000000000000000000000000000000000000000000000000AD -:20D3800000000000000000000000000000000000000000000000000000000000000000008D -:20D3A00000000000000000000000000000000000000000000000000000000000000000006D -:20D3C00000000000000000000000000000000000000000000000000000000000000000004D -:20D3E00000000000000000000000000000000000000000000000000000000000000000002D -:020000040800F2 -:20D4000000000000000000000000000000000000000000000000000000000000000000000C -:20D420000000000000000000000000000000000000000000000000000000000000000000EC -:20D440000000000000000000000000000000000000000000000000000000000000000000CC -:20D460000000000000000000000000000000000000000000000000000000000000000000AC -:20D4800000000000000000000000000000000000000000000000000000000000000000008C -:20D4A00000000000000000000000000000000000000000000000000000000000000000006C -:20D4C00000000000000000000000000000000000000000000000000000000000000000004C -:20D4E00000000000000000000000000000000000000000000000000000000000000000002C -:20D5000000000000000000000000000000000000000000000000000000000000000000000B -:20D520000000000000000000000000000000000000000000000000000000000000000000EB -:20D540000000000000000000000000000000000000000000000000000000000000000000CB -:20D560000000000000000000000000000000000000000000000000000000000000000000AB -:20D5800000000000000000000000000000000000000000000000000000000000000000008B -:20D5A00000000000000000000000000000000000000000000000000000000000000000006B -:20D5C00000000000000000000000000000000000000000000000000000000000000000004B -:20D5E00000000000000000000000000000000000000000000000000000000000000000002B -:20D6000000000000000000000000000000000000000000000000000000000000000000000A -:20D620000000000000000000000000000000000000000000000000000000000000000000EA -:20D640000000000000000000000000000000000000000000000000000000000000000000CA -:20D660000000000000000000000000000000000000000000000000000000000000000000AA -:20D6800000000000000000000000000000000000000000000000000000000000000000008A -:20D6A00000000000000000000000000000000000000000000000000000000000000000006A -:20D6C00000000000000000000000000000000000000000000000000000000000000000004A -:20D6E00000000000000000000000000000000000000000000000000000000000000000002A -:20D70000000000000000000000000000000000000000000000000000000000000000000009 -:20D720000000000000000000000000000000000000000000000000000000000000000000E9 -:20D740000000000000000000000000000000000000000000000000000000000000000000C9 -:20D760000000000000000000000000000000000000000000000000000000000000000000A9 -:20D78000000000000000000000000000000000000000000000000000000000000000000089 -:20D7A000000000000000000000000000000000000000000000000000000000000000000069 -:20D7C000000000000000000000000000000000000000000000000000000000000000000049 -:20D7E000000000000000000000000000000000000000000000000000000000000000000029 -:020000040800F2 -:20D80000000000000000000000000000000000000000000000000000000000000000000008 -:20D820000000000000000000000000000000000000000000000000000000000000000000E8 -:20D840000000000000000000000000000000000000000000000000000000000000000000C8 -:20D860000000000000000000000000000000000000000000000000000000000000000000A8 -:20D88000000000000000000000000000000000000000000000000000000000000000000088 -:20D8A000000000000000000000000000000000000000000000000000000000000000000068 -:20D8C000000000000000000000000000000000000000000000000000000000000000000048 -:20D8E000000000000000000000000000000000000000000000000000000000000000000028 -:20D90000000000000000000000000000000000000000000000000000000000000000000007 -:20D920000000000000000000000000000000000000000000000000000000000000000000E7 -:20D940000000000000000000000000000000000000000000000000000000000000000000C7 -:20D960000000000000000000000000000000000000000000000000000000000000000000A7 -:20D98000000000000000000000000000000000000000000000000000000000000000000087 -:20D9A000000000000000000000000000000000000000000000000000000000000000000067 -:20D9C000000000000000000000000000000000000000000000000000000000000000000047 -:20D9E000000000000000000000000000000000000000000000000000000000000000000027 -:20DA0000000000000000000000000000000000000000000000000000000000000000000006 -:20DA20000000000000000000000000000000000000000000000000000000000000000000E6 -:20DA40000000000000000000000000000000000000000000000000000000000000000000C6 -:20DA60000000000000000000000000000000000000000000000000000000000000000000A6 -:20DA8000000000000000000000000000000000000000000000000000000000000000000086 -:20DAA000000000000000000000000000000000000000000000000000000000000000000066 -:20DAC000000000000000000000000000000000000000000000000000000000000000000046 -:20DAE000000000000000000000000000000000000000000000000000000000000000000026 -:20DB0000000000000000000000000000000000000000000000000000000000000000000005 -:20DB20000000000000000000000000000000000000000000000000000000000000000000E5 -:20DB40000000000000000000000000000000000000000000000000000000000000000000C5 -:20DB60000000000000000000000000000000000000000000000000000000000000000000A5 -:20DB8000000000000000000000000000000000000000000000000000000000000000000085 -:20DBA000000000000000000000000000000000000000000000000000000000000000000065 -:20DBC000000000000000000000000000000000000000000000000000000000000000000045 -:20DBE000000000000000000000000000000000000000000000000000000000000000000025 -:020000040800F2 -:20DC0000000000000000000000000000000000000000000000000000000000000000000004 -:20DC20000000000000000000000000000000000000000000000000000000000000000000E4 -:20DC40000000000000000000000000000000000000000000000000000000000000000000C4 -:20DC60000000000000000000000000000000000000000000000000000000000000000000A4 -:20DC8000000000000000000000000000000000000000000000000000000000000000000084 -:20DCA000000000000000000000000000000000000000000000000000000000000000000064 -:20DCC000000000000000000000000000000000000000000000000000000000000000000044 -:20DCE000000000000000000000000000000000000000000000000000000000000000000024 -:20DD0000000000000000000000000000000000000000000000000000000000000000000003 -:20DD20000000000000000000000000000000000000000000000000000000000000000000E3 -:20DD40000000000000000000000000000000000000000000000000000000000000000000C3 -:20DD60000000000000000000000000000000000000000000000000000000000000000000A3 -:20DD8000000000000000000000000000000000000000000000000000000000000000000083 -:20DDA000000000000000000000000000000000000000000000000000000000000000000063 -:20DDC000000000000000000000000000000000000000000000000000000000000000000043 -:20DDE000000000000000000000000000000000000000000000000000000000000000000023 -:20DE0000000000000000000000000000000000000000000000000000000000000000000002 -:20DE20000000000000000000000000000000000000000000000000000000000000000000E2 -:20DE40000000000000000000000000000000000000000000000000000000000000000000C2 -:20DE60000000000000000000000000000000000000000000000000000000000000000000A2 -:20DE8000000000000000000000000000000000000000000000000000000000000000000082 -:20DEA000000000000000000000000000000000000000000000000000000000000000000062 -:20DEC000000000000000000000000000000000000000000000000000000000000000000042 -:20DEE000000000000000000000000000000000000000000000000000000000000000000022 -:20DF0000000000000000000000000000000000000000000000000000000000000000000001 -:20DF20000000000000000000000000000000000000000000000000000000000000000000E1 -:20DF40000000000000000000000000000000000000000000000000000000000000000000C1 -:20DF60000000000000000000000000000000000000000000000000000000000000000000A1 -:20DF8000000000000000000000000000000000000000000000000000000000000000000081 -:20DFA000000000000000000000000000000000000000000000000000000000000000000061 -:20DFC000000000000000000000000000000000000000000000000000000000000000000041 -:20DFE000000000000000000000000000000000000000000000000000000000000000000021 -:020000040800F2 -:20E00000000000000000000000000000000000000000000000000000000000000000000000 -:20E020000000000000000000000000000000000000000000000000000000000000000000E0 -:20E040000000000000000000000000000000000000000000000000000000000000000000C0 -:20E060000000000000000000000000000000000000000000000000000000000000000000A0 -:20E08000000000000000000000000000000000000000000000000000000000000000000080 -:20E0A000000000000000000000000000000000000000000000000000000000000000000060 -:20E0C000000000000000000000000000000000000000000000000000000000000000000040 -:20E0E000000000000000000000000000000000000000000000000000000000000000000020 -:20E100000000000000000000000000000000000000000000000000000000000000000000FF -:20E120000000000000000000000000000000000000000000000000000000000000000000DF -:20E140000000000000000000000000000000000000000000000000000000000000000000BF -:20E1600000000000000000000000000000000000000000000000000000000000000000009F -:20E1800000000000000000000000000000000000000000000000000000000000000000007F -:20E1A00000000000000000000000000000000000000000000000000000000000000000005F -:20E1C00000000000000000000000000000000000000000000000000000000000000000003F -:20E1E00000000000000000000000000000000000000000000000000000000000000000001F -:20E200000000000000000000000000000000000000000000000000000000000000000000FE -:20E220000000000000000000000000000000000000000000000000000000000000000000DE -:20E240000000000000000000000000000000000000000000000000000000000000000000BE -:20E2600000000000000000000000000000000000000000000000000000000000000000009E -:20E2800000000000000000000000000000000000000000000000000000000000000000007E -:20E2A00000000000000000000000000000000000000000000000000000000000000000005E -:20E2C00000000000000000000000000000000000000000000000000000000000000000003E -:20E2E00000000000000000000000000000000000000000000000000000000000000000001E -:20E300000000000000000000000000000000000000000000000000000000000000000000FD -:20E320000000000000000000000000000000000000000000000000000000000000000000DD -:20E340000000000000000000000000000000000000000000000000000000000000000000BD -:20E3600000000000000000000000000000000000000000000000000000000000000000009D -:20E3800000000000000000000000000000000000000000000000000000000000000000007D -:20E3A00000000000000000000000000000000000000000000000000000000000000000005D -:20E3C00000000000000000000000000000000000000000000000000000000000000000003D -:20E3E00000000000000000000000000000000000000000000000000000000000000000001D -:020000040800F2 -:20E400000000000000000000000000000000000000000000000000000000000000000000FC -:20E420000000000000000000000000000000000000000000000000000000000000000000DC -:20E440000000000000000000000000000000000000000000000000000000000000000000BC -:20E4600000000000000000000000000000000000000000000000000000000000000000009C -:20E4800000000000000000000000000000000000000000000000000000000000000000007C -:20E4A00000000000000000000000000000000000000000000000000000000000000000005C -:20E4C00000000000000000000000000000000000000000000000000000000000000000003C -:20E4E00000000000000000000000000000000000000000000000000000000000000000001C -:20E500000000000000000000000000000000000000000000000000000000000000000000FB -:20E520000000000000000000000000000000000000000000000000000000000000000000DB -:20E540000000000000000000000000000000000000000000000000000000000000000000BB -:20E5600000000000000000000000000000000000000000000000000000000000000000009B -:20E5800000000000000000000000000000000000000000000000000000000000000000007B -:20E5A00000000000000000000000000000000000000000000000000000000000000000005B -:20E5C00000000000000000000000000000000000000000000000000000000000000000003B -:20E5E00000000000000000000000000000000000000000000000000000000000000000001B -:20E60000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF1A -:20E62000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA -:20E64000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDA -:20E66000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBA -:20E68000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF9A -:20E6A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7A -:20E6C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5A -:20E6E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF3A -:20E70000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF19 -:20E72000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF9 -:20E74000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD9 -:20E76000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB9 -:20E78000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF99 -:20E7A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF79 -:20E7C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF59 -:20E7E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF39 -:020000040800F2 -:20E80000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF18 -:20E82000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8 -:20E84000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD8 -:20E86000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB8 -:20E88000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF98 -:20E8A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF78 -:20E8C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF58 -:20E8E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF38 -:20E90000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF17 -:20E92000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7 -:20E94000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD7 -:20E96000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB7 -:20E98000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF97 -:20E9A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF77 -:20E9C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF57 -:20E9E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF37 -:20EA0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF16 -:20EA2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6 -:20EA4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD6 -:20EA6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB6 -:20EA8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF96 -:20EAA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF76 -:20EAC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56 -:20EAE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF36 -:20EB0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF15 -:20EB2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5 -:20EB4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD5 -:20EB6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB5 -:20EB8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF95 -:20EBA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF75 -:20EBC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF55 -:20EBE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF35 -:020000040800F2 -:20EC0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF14 -:20EC2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4 -:20EC4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD4 -:20EC6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB4 -:20EC8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF94 -:20ECA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF74 -:20ECC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF54 -:20ECE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF34 -:20ED0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF13 -:20ED2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF3 -:20ED4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD3 -:20ED6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB3 -:20ED8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF93 -:20EDA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF73 -:20EDC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF53 -:20EDE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF33 -:20EE0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF12 -:20EE2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2 -:20EE4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD2 -:20EE6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB2 -:20EE8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF92 -:20EEA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF72 -:20EEC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF52 -:20EEE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF32 -:20EF0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF11 -:20EF2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF1 -:20EF4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD1 -:20EF6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB1 -:20EF8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF91 -:20EFA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF71 -:20EFC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF51 -:20EFE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF31 -:020000040800F2 -:20F00000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF10 -:20F02000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0 -:20F04000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD0 -:20F06000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB0 -:20F08000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF90 -:20F0A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF70 -:20F0C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF50 -:20F0E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF30 -:20F10000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0F -:20F12000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF -:20F14000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFCF -:20F16000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAF -:20F18000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8F -:20F1A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6F -:20F1C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4F -:20F1E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2F -:20F20000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0E -:20F22000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEE -:20F24000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFCE -:20F26000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAE -:20F28000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8E -:20F2A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6E -:20F2C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4E -:20F2E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2E -:20F30000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0D -:20F32000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED -:20F34000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFCD -:20F36000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAD -:20F38000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8D -:20F3A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6D -:20F3C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4D -:20F3E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2D -:020000040800F2 -:20F40000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0C -:20F42000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEC -:20F44000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFCC -:20F46000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAC -:20F48000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8C -:20F4A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6C -:20F4C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4C -:20F4E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2C -:20F50000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0B -:20F52000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEB -:20F54000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFCB -:20F56000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAB -:20F58000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8B -:20F5A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6B -:20F5C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4B -:20F5E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2B -:20F60000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0A -:20F62000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEA -:20F64000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFCA -:20F66000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAA -:20F68000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8A -:20F6A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6A -:20F6C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4A -:20F6E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2A -:20F70000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF09 -:20F72000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9 -:20F74000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC9 -:20F76000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA9 -:20F78000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF89 -:20F7A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF69 -:20F7C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF49 -:20F7E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF29 -:020000040800F2 -:20F80000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF08 -:20F82000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE8 -:20F84000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC8 -:20F86000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA8 -:20F88000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF88 -:20F8A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF68 -:20F8C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF48 -:20F8E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF28 -:20F90000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF07 -:20F92000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE7 -:20F94000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7 -:20F96000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA7 -:20F98000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF87 -:20F9A000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF67 -:20F9C000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF47 -:20F9E000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF27 -:20FA0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF06 -:20FA2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE6 -:20FA4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC6 -:20FA6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA6 -:20FA8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF86 -:20FAA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF66 -:20FAC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF46 -:20FAE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF26 -:20FB0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF05 -:20FB2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5 -:20FB4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC5 -:20FB6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA5 -:20FB8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF85 -:20FBA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF65 -:20FBC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF45 -:20FBE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF25 -:020000040800F2 -:20FC0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF04 -:20FC2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE4 -:20FC4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC4 -:20FC6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA4 -:20FC8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF84 -:20FCA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF64 -:20FCC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF44 -:20FCE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF24 -:20FD0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF03 -:20FD2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE3 -:20FD4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC3 -:20FD6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA3 -:20FD8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF83 -:20FDA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF63 -:20FDC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF43 -:20FDE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF23 -:20FE0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF02 -:20FE2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE2 -:20FE4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC2 -:20FE6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA2 -:20FE8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF82 -:20FEA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF62 -:20FEC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF42 -:20FEE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF22 -:20FF0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01 -:20FF2000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE1 -:20FF4000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC1 -:20FF6000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA1 -:20FF8000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF81 -:20FFA000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF61 -:20FFC000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF41 -:20FFE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF21 -:00000001FF diff --git a/Development Resources/Hex/force_blank_flash.hex b/Development Resources/Hex/force_blank_flash.hex deleted file mode 100644 index 57c56b1c4..000000000 --- a/Development Resources/Hex/force_blank_flash.hex +++ /dev/null @@ -1,3074 +0,0 @@ -:020000040800F2 -:1040000000000000000000000000000000000000B0 -:1040100000000000000000000000000000000000A0 -:104020000000000000000000000000000000000090 -:104030000000000000000000000000000000000080 -:104040000000000000000000000000000000000070 -:104050000000000000000000000000000000000060 -:104060000000000000000000000000000000000050 -:104070000000000000000000000000000000000040 -:104080000000000000000000000000000000000030 -:104090000000000000000000000000000000000020 -:1040A0000000000000000000000000000000000010 -:1040B0000000000000000000000000000000000000 -:1040C00000000000000000000000000000000000F0 -:1040D00000000000000000000000000000000000E0 -:1040E00000000000000000000000000000000000D0 -:1040F00000000000000000000000000000000000C0 -:1041000000000000000000000000000000000000AF -:10411000000000000000000000000000000000009F -:10412000000000000000000000000000000000008F -:10413000000000000000000000000000000000007F -:10414000000000000000000000000000000000006F -:10415000000000000000000000000000000000005F -:10416000000000000000000000000000000000004F -:10417000000000000000000000000000000000003F -:10418000000000000000000000000000000000002F -:10419000000000000000000000000000000000001F -:1041A000000000000000000000000000000000000F -:1041B00000000000000000000000000000000000FF -:1041C00000000000000000000000000000000000EF -:1041D00000000000000000000000000000000000DF -:1041E00000000000000000000000000000000000CF -:1041F00000000000000000000000000000000000BF -:1042000000000000000000000000000000000000AE -:10421000000000000000000000000000000000009E -:10422000000000000000000000000000000000008E -:10423000000000000000000000000000000000007E -:10424000000000000000000000000000000000006E -:10425000000000000000000000000000000000005E -:10426000000000000000000000000000000000004E -:10427000000000000000000000000000000000003E -:10428000000000000000000000000000000000002E -:10429000000000000000000000000000000000001E -:1042A000000000000000000000000000000000000E -:1042B00000000000000000000000000000000000FE -:1042C00000000000000000000000000000000000EE -:1042D00000000000000000000000000000000000DE -:1042E00000000000000000000000000000000000CE -:1042F00000000000000000000000000000000000BE -:1043000000000000000000000000000000000000AD -:10431000000000000000000000000000000000009D -:10432000000000000000000000000000000000008D -:10433000000000000000000000000000000000007D -:10434000000000000000000000000000000000006D -:10435000000000000000000000000000000000005D -:10436000000000000000000000000000000000004D -:10437000000000000000000000000000000000003D -:10438000000000000000000000000000000000002D -:10439000000000000000000000000000000000001D -:1043A000000000000000000000000000000000000D -:1043B00000000000000000000000000000000000FD -:1043C00000000000000000000000000000000000ED -:1043D00000000000000000000000000000000000DD -:1043E00000000000000000000000000000000000CD -:1043F00000000000000000000000000000000000BD -:1044000000000000000000000000000000000000AC -:10441000000000000000000000000000000000009C -:10442000000000000000000000000000000000008C -:10443000000000000000000000000000000000007C -:10444000000000000000000000000000000000006C -:10445000000000000000000000000000000000005C -:10446000000000000000000000000000000000004C -:10447000000000000000000000000000000000003C -:10448000000000000000000000000000000000002C -:10449000000000000000000000000000000000001C -:1044A000000000000000000000000000000000000C -:1044B00000000000000000000000000000000000FC -:1044C00000000000000000000000000000000000EC -:1044D00000000000000000000000000000000000DC -:1044E00000000000000000000000000000000000CC -:1044F00000000000000000000000000000000000BC -:1045000000000000000000000000000000000000AB -:10451000000000000000000000000000000000009B -:10452000000000000000000000000000000000008B -:10453000000000000000000000000000000000007B -:10454000000000000000000000000000000000006B -:10455000000000000000000000000000000000005B -:10456000000000000000000000000000000000004B -:10457000000000000000000000000000000000003B -:10458000000000000000000000000000000000002B -:10459000000000000000000000000000000000001B -:1045A000000000000000000000000000000000000B -:1045B00000000000000000000000000000000000FB -:1045C00000000000000000000000000000000000EB -:1045D00000000000000000000000000000000000DB -:1045E00000000000000000000000000000000000CB -:1045F00000000000000000000000000000000000BB -:1046000000000000000000000000000000000000AA -:10461000000000000000000000000000000000009A -:10462000000000000000000000000000000000008A -:10463000000000000000000000000000000000007A -:10464000000000000000000000000000000000006A -:10465000000000000000000000000000000000005A -:10466000000000000000000000000000000000004A -:10467000000000000000000000000000000000003A -:10468000000000000000000000000000000000002A -:10469000000000000000000000000000000000001A -:1046A000000000000000000000000000000000000A -:1046B00000000000000000000000000000000000FA -:1046C00000000000000000000000000000000000EA -:1046D00000000000000000000000000000000000DA -:1046E00000000000000000000000000000000000CA -:1046F00000000000000000000000000000000000BA -:1047000000000000000000000000000000000000A9 -:104710000000000000000000000000000000000099 -:104720000000000000000000000000000000000089 -:104730000000000000000000000000000000000079 -:104740000000000000000000000000000000000069 -:104750000000000000000000000000000000000059 -:104760000000000000000000000000000000000049 -:104770000000000000000000000000000000000039 -:104780000000000000000000000000000000000029 -:104790000000000000000000000000000000000019 -:1047A0000000000000000000000000000000000009 -:1047B00000000000000000000000000000000000F9 -:1047C00000000000000000000000000000000000E9 -:1047D00000000000000000000000000000000000D9 -:1047E00000000000000000000000000000000000C9 -:1047F00000000000000000000000000000000000B9 -:1048000000000000000000000000000000000000A8 -:104810000000000000000000000000000000000098 -:104820000000000000000000000000000000000088 -:104830000000000000000000000000000000000078 -:104840000000000000000000000000000000000068 -:104850000000000000000000000000000000000058 -:104860000000000000000000000000000000000048 -:104870000000000000000000000000000000000038 -:104880000000000000000000000000000000000028 -:104890000000000000000000000000000000000018 -:1048A0000000000000000000000000000000000008 -:1048B00000000000000000000000000000000000F8 -:1048C00000000000000000000000000000000000E8 -:1048D00000000000000000000000000000000000D8 -:1048E00000000000000000000000000000000000C8 -:1048F00000000000000000000000000000000000B8 -:1049000000000000000000000000000000000000A7 -:104910000000000000000000000000000000000097 -:104920000000000000000000000000000000000087 -:104930000000000000000000000000000000000077 -:104940000000000000000000000000000000000067 -:104950000000000000000000000000000000000057 -:104960000000000000000000000000000000000047 -:104970000000000000000000000000000000000037 -:104980000000000000000000000000000000000027 -:104990000000000000000000000000000000000017 -:1049A0000000000000000000000000000000000007 -:1049B00000000000000000000000000000000000F7 -:1049C00000000000000000000000000000000000E7 -:1049D00000000000000000000000000000000000D7 -:1049E00000000000000000000000000000000000C7 -:1049F00000000000000000000000000000000000B7 -:104A000000000000000000000000000000000000A6 -:104A10000000000000000000000000000000000096 -:104A20000000000000000000000000000000000086 -:104A30000000000000000000000000000000000076 -:104A40000000000000000000000000000000000066 -:104A50000000000000000000000000000000000056 -:104A60000000000000000000000000000000000046 -:104A70000000000000000000000000000000000036 -:104A80000000000000000000000000000000000026 -:104A90000000000000000000000000000000000016 -:104AA0000000000000000000000000000000000006 -:104AB00000000000000000000000000000000000F6 -:104AC00000000000000000000000000000000000E6 -:104AD00000000000000000000000000000000000D6 -:104AE00000000000000000000000000000000000C6 -:104AF00000000000000000000000000000000000B6 -:104B000000000000000000000000000000000000A5 -:104B10000000000000000000000000000000000095 -:104B20000000000000000000000000000000000085 -:104B30000000000000000000000000000000000075 -:104B40000000000000000000000000000000000065 -:104B50000000000000000000000000000000000055 -:104B60000000000000000000000000000000000045 -:104B70000000000000000000000000000000000035 -:104B80000000000000000000000000000000000025 -:104B90000000000000000000000000000000000015 -:104BA0000000000000000000000000000000000005 -:104BB00000000000000000000000000000000000F5 -:104BC00000000000000000000000000000000000E5 -:104BD00000000000000000000000000000000000D5 -:104BE00000000000000000000000000000000000C5 -:104BF00000000000000000000000000000000000B5 -:104C000000000000000000000000000000000000A4 -:104C10000000000000000000000000000000000094 -:104C20000000000000000000000000000000000084 -:104C30000000000000000000000000000000000074 -:104C40000000000000000000000000000000000064 -:104C50000000000000000000000000000000000054 -:104C60000000000000000000000000000000000044 -:104C70000000000000000000000000000000000034 -:104C80000000000000000000000000000000000024 -:104C90000000000000000000000000000000000014 -:104CA0000000000000000000000000000000000004 -:104CB00000000000000000000000000000000000F4 -:104CC00000000000000000000000000000000000E4 -:104CD00000000000000000000000000000000000D4 -:104CE00000000000000000000000000000000000C4 -:104CF00000000000000000000000000000000000B4 -:104D000000000000000000000000000000000000A3 -:104D10000000000000000000000000000000000093 -:104D20000000000000000000000000000000000083 -:104D30000000000000000000000000000000000073 -:104D40000000000000000000000000000000000063 -:104D50000000000000000000000000000000000053 -:104D60000000000000000000000000000000000043 -:104D70000000000000000000000000000000000033 -:104D80000000000000000000000000000000000023 -:104D90000000000000000000000000000000000013 -:104DA0000000000000000000000000000000000003 -:104DB00000000000000000000000000000000000F3 -:104DC00000000000000000000000000000000000E3 -:104DD00000000000000000000000000000000000D3 -:104DE00000000000000000000000000000000000C3 -:104DF00000000000000000000000000000000000B3 -:104E000000000000000000000000000000000000A2 -:104E10000000000000000000000000000000000092 -:104E20000000000000000000000000000000000082 -:104E30000000000000000000000000000000000072 -:104E40000000000000000000000000000000000062 -:104E50000000000000000000000000000000000052 -:104E60000000000000000000000000000000000042 -:104E70000000000000000000000000000000000032 -:104E80000000000000000000000000000000000022 -:104E90000000000000000000000000000000000012 -:104EA0000000000000000000000000000000000002 -:104EB00000000000000000000000000000000000F2 -:104EC00000000000000000000000000000000000E2 -:104ED00000000000000000000000000000000000D2 -:104EE00000000000000000000000000000000000C2 -:104EF00000000000000000000000000000000000B2 -:104F000000000000000000000000000000000000A1 -:104F10000000000000000000000000000000000091 -:104F20000000000000000000000000000000000081 -:104F30000000000000000000000000000000000071 -:104F40000000000000000000000000000000000061 -:104F50000000000000000000000000000000000051 -:104F60000000000000000000000000000000000041 -:104F70000000000000000000000000000000000031 -:104F80000000000000000000000000000000000021 -:104F90000000000000000000000000000000000011 -:104FA0000000000000000000000000000000000001 -:104FB00000000000000000000000000000000000F1 -:104FC00000000000000000000000000000000000E1 -:104FD00000000000000000000000000000000000D1 -:104FE00000000000000000000000000000000000C1 -:104FF00000000000000000000000000000000000B1 -:1050000000000000000000000000000000000000A0 -:105010000000000000000000000000000000000090 -:105020000000000000000000000000000000000080 -:105030000000000000000000000000000000000070 -:105040000000000000000000000000000000000060 -:105050000000000000000000000000000000000050 -:105060000000000000000000000000000000000040 -:105070000000000000000000000000000000000030 -:105080000000000000000000000000000000000020 -:105090000000000000000000000000000000000010 -:1050A0000000000000000000000000000000000000 -:1050B00000000000000000000000000000000000F0 -:1050C00000000000000000000000000000000000E0 -:1050D00000000000000000000000000000000000D0 -:1050E00000000000000000000000000000000000C0 -:1050F00000000000000000000000000000000000B0 -:10510000000000000000000000000000000000009F -:10511000000000000000000000000000000000008F -:10512000000000000000000000000000000000007F -:10513000000000000000000000000000000000006F -:10514000000000000000000000000000000000005F -:10515000000000000000000000000000000000004F -:10516000000000000000000000000000000000003F -:10517000000000000000000000000000000000002F -:10518000000000000000000000000000000000001F -:10519000000000000000000000000000000000000F -:1051A00000000000000000000000000000000000FF -:1051B00000000000000000000000000000000000EF -:1051C00000000000000000000000000000000000DF -:1051D00000000000000000000000000000000000CF -:1051E00000000000000000000000000000000000BF -:1051F00000000000000000000000000000000000AF -:10520000000000000000000000000000000000009E -:10521000000000000000000000000000000000008E -:10522000000000000000000000000000000000007E -:10523000000000000000000000000000000000006E -:10524000000000000000000000000000000000005E -:10525000000000000000000000000000000000004E -:10526000000000000000000000000000000000003E -:10527000000000000000000000000000000000002E -:10528000000000000000000000000000000000001E -:10529000000000000000000000000000000000000E -:1052A00000000000000000000000000000000000FE -:1052B00000000000000000000000000000000000EE -:1052C00000000000000000000000000000000000DE -:1052D00000000000000000000000000000000000CE -:1052E00000000000000000000000000000000000BE -:1052F00000000000000000000000000000000000AE -:10530000000000000000000000000000000000009D -:10531000000000000000000000000000000000008D -:10532000000000000000000000000000000000007D -:10533000000000000000000000000000000000006D -:10534000000000000000000000000000000000005D -:10535000000000000000000000000000000000004D -:10536000000000000000000000000000000000003D -:10537000000000000000000000000000000000002D -:10538000000000000000000000000000000000001D -:10539000000000000000000000000000000000000D -:1053A00000000000000000000000000000000000FD -:1053B00000000000000000000000000000000000ED -:1053C00000000000000000000000000000000000DD -:1053D00000000000000000000000000000000000CD -:1053E00000000000000000000000000000000000BD -:1053F00000000000000000000000000000000000AD -:10540000000000000000000000000000000000009C -:10541000000000000000000000000000000000008C -:10542000000000000000000000000000000000007C -:10543000000000000000000000000000000000006C -:10544000000000000000000000000000000000005C -:10545000000000000000000000000000000000004C -:10546000000000000000000000000000000000003C -:10547000000000000000000000000000000000002C -:10548000000000000000000000000000000000001C -:10549000000000000000000000000000000000000C -:1054A00000000000000000000000000000000000FC -:1054B00000000000000000000000000000000000EC -:1054C00000000000000000000000000000000000DC -:1054D00000000000000000000000000000000000CC -:1054E00000000000000000000000000000000000BC -:1054F00000000000000000000000000000000000AC -:10550000000000000000000000000000000000009B -:10551000000000000000000000000000000000008B -:10552000000000000000000000000000000000007B -:10553000000000000000000000000000000000006B -:10554000000000000000000000000000000000005B -:10555000000000000000000000000000000000004B -:10556000000000000000000000000000000000003B -:10557000000000000000000000000000000000002B -:10558000000000000000000000000000000000001B -:10559000000000000000000000000000000000000B -:1055A00000000000000000000000000000000000FB -:1055B00000000000000000000000000000000000EB -:1055C00000000000000000000000000000000000DB -:1055D00000000000000000000000000000000000CB -:1055E00000000000000000000000000000000000BB -:1055F00000000000000000000000000000000000AB -:10560000000000000000000000000000000000009A -:10561000000000000000000000000000000000008A -:10562000000000000000000000000000000000007A -:10563000000000000000000000000000000000006A -:10564000000000000000000000000000000000005A -:10565000000000000000000000000000000000004A -:10566000000000000000000000000000000000003A -:10567000000000000000000000000000000000002A -:10568000000000000000000000000000000000001A -:10569000000000000000000000000000000000000A -:1056A00000000000000000000000000000000000FA -:1056B00000000000000000000000000000000000EA -:1056C00000000000000000000000000000000000DA -:1056D00000000000000000000000000000000000CA -:1056E00000000000000000000000000000000000BA -:1056F00000000000000000000000000000000000AA -:105700000000000000000000000000000000000099 -:105710000000000000000000000000000000000089 -:105720000000000000000000000000000000000079 -:105730000000000000000000000000000000000069 -:105740000000000000000000000000000000000059 -:105750000000000000000000000000000000000049 -:105760000000000000000000000000000000000039 -:105770000000000000000000000000000000000029 -:105780000000000000000000000000000000000019 -:105790000000000000000000000000000000000009 -:1057A00000000000000000000000000000000000F9 -:1057B00000000000000000000000000000000000E9 -:1057C00000000000000000000000000000000000D9 -:1057D00000000000000000000000000000000000C9 -:1057E00000000000000000000000000000000000B9 -:1057F00000000000000000000000000000000000A9 -:105800000000000000000000000000000000000098 -:105810000000000000000000000000000000000088 -:105820000000000000000000000000000000000078 -:105830000000000000000000000000000000000068 -:105840000000000000000000000000000000000058 -:105850000000000000000000000000000000000048 -:105860000000000000000000000000000000000038 -:105870000000000000000000000000000000000028 -:105880000000000000000000000000000000000018 -:105890000000000000000000000000000000000008 -:1058A00000000000000000000000000000000000F8 -:1058B00000000000000000000000000000000000E8 -:1058C00000000000000000000000000000000000D8 -:1058D00000000000000000000000000000000000C8 -:1058E00000000000000000000000000000000000B8 -:1058F00000000000000000000000000000000000A8 -:105900000000000000000000000000000000000097 -:105910000000000000000000000000000000000087 -:105920000000000000000000000000000000000077 -:105930000000000000000000000000000000000067 -:105940000000000000000000000000000000000057 -:105950000000000000000000000000000000000047 -:105960000000000000000000000000000000000037 -:105970000000000000000000000000000000000027 -:105980000000000000000000000000000000000017 -:105990000000000000000000000000000000000007 -:1059A00000000000000000000000000000000000F7 -:1059B00000000000000000000000000000000000E7 -:1059C00000000000000000000000000000000000D7 -:1059D00000000000000000000000000000000000C7 -:1059E00000000000000000000000000000000000B7 -:1059F00000000000000000000000000000000000A7 -:105A00000000000000000000000000000000000096 -:105A10000000000000000000000000000000000086 -:105A20000000000000000000000000000000000076 -:105A30000000000000000000000000000000000066 -:105A40000000000000000000000000000000000056 -:105A50000000000000000000000000000000000046 -:105A60000000000000000000000000000000000036 -:105A70000000000000000000000000000000000026 -:105A80000000000000000000000000000000000016 -:105A90000000000000000000000000000000000006 -:105AA00000000000000000000000000000000000F6 -:105AB00000000000000000000000000000000000E6 -:105AC00000000000000000000000000000000000D6 -:105AD00000000000000000000000000000000000C6 -:105AE00000000000000000000000000000000000B6 -:105AF00000000000000000000000000000000000A6 -:105B00000000000000000000000000000000000095 -:105B10000000000000000000000000000000000085 -:105B20000000000000000000000000000000000075 -:105B30000000000000000000000000000000000065 -:105B40000000000000000000000000000000000055 -:105B50000000000000000000000000000000000045 -:105B60000000000000000000000000000000000035 -:105B70000000000000000000000000000000000025 -:105B80000000000000000000000000000000000015 -:105B90000000000000000000000000000000000005 -:105BA00000000000000000000000000000000000F5 -:105BB00000000000000000000000000000000000E5 -:105BC00000000000000000000000000000000000D5 -:105BD00000000000000000000000000000000000C5 -:105BE00000000000000000000000000000000000B5 -:105BF00000000000000000000000000000000000A5 -:105C00000000000000000000000000000000000094 -:105C10000000000000000000000000000000000084 -:105C20000000000000000000000000000000000074 -:105C30000000000000000000000000000000000064 -:105C40000000000000000000000000000000000054 -:105C50000000000000000000000000000000000044 -:105C60000000000000000000000000000000000034 -:105C70000000000000000000000000000000000024 -:105C80000000000000000000000000000000000014 -:105C90000000000000000000000000000000000004 -:105CA00000000000000000000000000000000000F4 -:105CB00000000000000000000000000000000000E4 -:105CC00000000000000000000000000000000000D4 -:105CD00000000000000000000000000000000000C4 -:105CE00000000000000000000000000000000000B4 -:105CF00000000000000000000000000000000000A4 -:105D00000000000000000000000000000000000093 -:105D10000000000000000000000000000000000083 -:105D20000000000000000000000000000000000073 -:105D30000000000000000000000000000000000063 -:105D40000000000000000000000000000000000053 -:105D50000000000000000000000000000000000043 -:105D60000000000000000000000000000000000033 -:105D70000000000000000000000000000000000023 -:105D80000000000000000000000000000000000013 -:105D90000000000000000000000000000000000003 -:105DA00000000000000000000000000000000000F3 -:105DB00000000000000000000000000000000000E3 -:105DC00000000000000000000000000000000000D3 -:105DD00000000000000000000000000000000000C3 -:105DE00000000000000000000000000000000000B3 -:105DF00000000000000000000000000000000000A3 -:105E00000000000000000000000000000000000092 -:105E10000000000000000000000000000000000082 -:105E20000000000000000000000000000000000072 -:105E30000000000000000000000000000000000062 -:105E40000000000000000000000000000000000052 -:105E50000000000000000000000000000000000042 -:105E60000000000000000000000000000000000032 -:105E70000000000000000000000000000000000022 -:105E80000000000000000000000000000000000012 -:105E90000000000000000000000000000000000002 -:105EA00000000000000000000000000000000000F2 -:105EB00000000000000000000000000000000000E2 -:105EC00000000000000000000000000000000000D2 -:105ED00000000000000000000000000000000000C2 -:105EE00000000000000000000000000000000000B2 -:105EF00000000000000000000000000000000000A2 -:105F00000000000000000000000000000000000091 -:105F10000000000000000000000000000000000081 -:105F20000000000000000000000000000000000071 -:105F30000000000000000000000000000000000061 -:105F40000000000000000000000000000000000051 -:105F50000000000000000000000000000000000041 -:105F60000000000000000000000000000000000031 -:105F70000000000000000000000000000000000021 -:105F80000000000000000000000000000000000011 -:105F90000000000000000000000000000000000001 -:105FA00000000000000000000000000000000000F1 -:105FB00000000000000000000000000000000000E1 -:105FC00000000000000000000000000000000000D1 -:105FD00000000000000000000000000000000000C1 -:105FE00000000000000000000000000000000000B1 -:105FF00000000000000000000000000000000000A1 -:106000000000000000000000000000000000000090 -:106010000000000000000000000000000000000080 -:106020000000000000000000000000000000000070 -:106030000000000000000000000000000000000060 -:106040000000000000000000000000000000000050 -:106050000000000000000000000000000000000040 -:106060000000000000000000000000000000000030 -:106070000000000000000000000000000000000020 -:106080000000000000000000000000000000000010 -:106090000000000000000000000000000000000000 -:1060A00000000000000000000000000000000000F0 -:1060B00000000000000000000000000000000000E0 -:1060C00000000000000000000000000000000000D0 -:1060D00000000000000000000000000000000000C0 -:1060E00000000000000000000000000000000000B0 -:1060F00000000000000000000000000000000000A0 -:10610000000000000000000000000000000000008F -:10611000000000000000000000000000000000007F -:10612000000000000000000000000000000000006F -:10613000000000000000000000000000000000005F -:10614000000000000000000000000000000000004F -:10615000000000000000000000000000000000003F -:10616000000000000000000000000000000000002F -:10617000000000000000000000000000000000001F -:10618000000000000000000000000000000000000F -:1061900000000000000000000000000000000000FF -:1061A00000000000000000000000000000000000EF -:1061B00000000000000000000000000000000000DF -:1061C00000000000000000000000000000000000CF -:1061D00000000000000000000000000000000000BF -:1061E00000000000000000000000000000000000AF -:1061F000000000000000000000000000000000009F -:10620000000000000000000000000000000000008E -:10621000000000000000000000000000000000007E -:10622000000000000000000000000000000000006E -:10623000000000000000000000000000000000005E -:10624000000000000000000000000000000000004E -:10625000000000000000000000000000000000003E -:10626000000000000000000000000000000000002E -:10627000000000000000000000000000000000001E -:10628000000000000000000000000000000000000E -:1062900000000000000000000000000000000000FE -:1062A00000000000000000000000000000000000EE -:1062B00000000000000000000000000000000000DE -:1062C00000000000000000000000000000000000CE -:1062D00000000000000000000000000000000000BE -:1062E00000000000000000000000000000000000AE -:1062F000000000000000000000000000000000009E -:10630000000000000000000000000000000000008D -:10631000000000000000000000000000000000007D -:10632000000000000000000000000000000000006D -:10633000000000000000000000000000000000005D -:10634000000000000000000000000000000000004D -:10635000000000000000000000000000000000003D -:10636000000000000000000000000000000000002D -:10637000000000000000000000000000000000001D -:10638000000000000000000000000000000000000D -:1063900000000000000000000000000000000000FD -:1063A00000000000000000000000000000000000ED -:1063B00000000000000000000000000000000000DD -:1063C00000000000000000000000000000000000CD -:1063D00000000000000000000000000000000000BD -:1063E00000000000000000000000000000000000AD -:1063F000000000000000000000000000000000009D -:10640000000000000000000000000000000000008C -:10641000000000000000000000000000000000007C -:10642000000000000000000000000000000000006C -:10643000000000000000000000000000000000005C -:10644000000000000000000000000000000000004C -:10645000000000000000000000000000000000003C -:10646000000000000000000000000000000000002C -:10647000000000000000000000000000000000001C -:10648000000000000000000000000000000000000C -:1064900000000000000000000000000000000000FC -:1064A00000000000000000000000000000000000EC -:1064B00000000000000000000000000000000000DC -:1064C00000000000000000000000000000000000CC -:1064D00000000000000000000000000000000000BC -:1064E00000000000000000000000000000000000AC -:1064F000000000000000000000000000000000009C -:10650000000000000000000000000000000000008B -:10651000000000000000000000000000000000007B -:10652000000000000000000000000000000000006B -:10653000000000000000000000000000000000005B -:10654000000000000000000000000000000000004B -:10655000000000000000000000000000000000003B -:10656000000000000000000000000000000000002B -:10657000000000000000000000000000000000001B -:10658000000000000000000000000000000000000B -:1065900000000000000000000000000000000000FB -:1065A00000000000000000000000000000000000EB -:1065B00000000000000000000000000000000000DB -:1065C00000000000000000000000000000000000CB -:1065D00000000000000000000000000000000000BB -:1065E00000000000000000000000000000000000AB -:1065F000000000000000000000000000000000009B -:10660000000000000000000000000000000000008A -:10661000000000000000000000000000000000007A -:10662000000000000000000000000000000000006A -:10663000000000000000000000000000000000005A -:10664000000000000000000000000000000000004A -:10665000000000000000000000000000000000003A -:10666000000000000000000000000000000000002A -:10667000000000000000000000000000000000001A -:10668000000000000000000000000000000000000A -:1066900000000000000000000000000000000000FA -:1066A00000000000000000000000000000000000EA -:1066B00000000000000000000000000000000000DA -:1066C00000000000000000000000000000000000CA -:1066D00000000000000000000000000000000000BA -:1066E00000000000000000000000000000000000AA -:1066F000000000000000000000000000000000009A -:106700000000000000000000000000000000000089 -:106710000000000000000000000000000000000079 -:106720000000000000000000000000000000000069 -:106730000000000000000000000000000000000059 -:106740000000000000000000000000000000000049 -:106750000000000000000000000000000000000039 -:106760000000000000000000000000000000000029 -:106770000000000000000000000000000000000019 -:106780000000000000000000000000000000000009 -:1067900000000000000000000000000000000000F9 -:1067A00000000000000000000000000000000000E9 -:1067B00000000000000000000000000000000000D9 -:1067C00000000000000000000000000000000000C9 -:1067D00000000000000000000000000000000000B9 -:1067E00000000000000000000000000000000000A9 -:1067F0000000000000000000000000000000000099 -:106800000000000000000000000000000000000088 -:106810000000000000000000000000000000000078 -:106820000000000000000000000000000000000068 -:106830000000000000000000000000000000000058 -:106840000000000000000000000000000000000048 -:106850000000000000000000000000000000000038 -:106860000000000000000000000000000000000028 -:106870000000000000000000000000000000000018 -:106880000000000000000000000000000000000008 -:1068900000000000000000000000000000000000F8 -:1068A00000000000000000000000000000000000E8 -:1068B00000000000000000000000000000000000D8 -:1068C00000000000000000000000000000000000C8 -:1068D00000000000000000000000000000000000B8 -:1068E00000000000000000000000000000000000A8 -:1068F0000000000000000000000000000000000098 -:106900000000000000000000000000000000000087 -:106910000000000000000000000000000000000077 -:106920000000000000000000000000000000000067 -:106930000000000000000000000000000000000057 -:106940000000000000000000000000000000000047 -:106950000000000000000000000000000000000037 -:106960000000000000000000000000000000000027 -:106970000000000000000000000000000000000017 -:106980000000000000000000000000000000000007 -:1069900000000000000000000000000000000000F7 -:1069A00000000000000000000000000000000000E7 -:1069B00000000000000000000000000000000000D7 -:1069C00000000000000000000000000000000000C7 -:1069D00000000000000000000000000000000000B7 -:1069E00000000000000000000000000000000000A7 -:1069F0000000000000000000000000000000000097 -:106A00000000000000000000000000000000000086 -:106A10000000000000000000000000000000000076 -:106A20000000000000000000000000000000000066 -:106A30000000000000000000000000000000000056 -:106A40000000000000000000000000000000000046 -:106A50000000000000000000000000000000000036 -:106A60000000000000000000000000000000000026 -:106A70000000000000000000000000000000000016 -:106A80000000000000000000000000000000000006 -:106A900000000000000000000000000000000000F6 -:106AA00000000000000000000000000000000000E6 -:106AB00000000000000000000000000000000000D6 -:106AC00000000000000000000000000000000000C6 -:106AD00000000000000000000000000000000000B6 -:106AE00000000000000000000000000000000000A6 -:106AF0000000000000000000000000000000000096 -:106B00000000000000000000000000000000000085 -:106B10000000000000000000000000000000000075 -:106B20000000000000000000000000000000000065 -:106B30000000000000000000000000000000000055 -:106B40000000000000000000000000000000000045 -:106B50000000000000000000000000000000000035 -:106B60000000000000000000000000000000000025 -:106B70000000000000000000000000000000000015 -:106B80000000000000000000000000000000000005 -:106B900000000000000000000000000000000000F5 -:106BA00000000000000000000000000000000000E5 -:106BB00000000000000000000000000000000000D5 -:106BC00000000000000000000000000000000000C5 -:106BD00000000000000000000000000000000000B5 -:106BE00000000000000000000000000000000000A5 -:106BF0000000000000000000000000000000000095 -:106C00000000000000000000000000000000000084 -:106C10000000000000000000000000000000000074 -:106C20000000000000000000000000000000000064 -:106C30000000000000000000000000000000000054 -:106C40000000000000000000000000000000000044 -:106C50000000000000000000000000000000000034 -:106C60000000000000000000000000000000000024 -:106C70000000000000000000000000000000000014 -:106C80000000000000000000000000000000000004 -:106C900000000000000000000000000000000000F4 -:106CA00000000000000000000000000000000000E4 -:106CB00000000000000000000000000000000000D4 -:106CC00000000000000000000000000000000000C4 -:106CD00000000000000000000000000000000000B4 -:106CE00000000000000000000000000000000000A4 -:106CF0000000000000000000000000000000000094 -:106D00000000000000000000000000000000000083 -:106D10000000000000000000000000000000000073 -:106D20000000000000000000000000000000000063 -:106D30000000000000000000000000000000000053 -:106D40000000000000000000000000000000000043 -:106D50000000000000000000000000000000000033 -:106D60000000000000000000000000000000000023 -:106D70000000000000000000000000000000000013 -:106D80000000000000000000000000000000000003 -:106D900000000000000000000000000000000000F3 -:106DA00000000000000000000000000000000000E3 -:106DB00000000000000000000000000000000000D3 -:106DC00000000000000000000000000000000000C3 -:106DD00000000000000000000000000000000000B3 -:106DE00000000000000000000000000000000000A3 -:106DF0000000000000000000000000000000000093 -:106E00000000000000000000000000000000000082 -:106E10000000000000000000000000000000000072 -:106E20000000000000000000000000000000000062 -:106E30000000000000000000000000000000000052 -:106E40000000000000000000000000000000000042 -:106E50000000000000000000000000000000000032 -:106E60000000000000000000000000000000000022 -:106E70000000000000000000000000000000000012 -:106E80000000000000000000000000000000000002 -:106E900000000000000000000000000000000000F2 -:106EA00000000000000000000000000000000000E2 -:106EB00000000000000000000000000000000000D2 -:106EC00000000000000000000000000000000000C2 -:106ED00000000000000000000000000000000000B2 -:106EE00000000000000000000000000000000000A2 -:106EF0000000000000000000000000000000000092 -:106F00000000000000000000000000000000000081 -:106F10000000000000000000000000000000000071 -:106F20000000000000000000000000000000000061 -:106F30000000000000000000000000000000000051 -:106F40000000000000000000000000000000000041 -:106F50000000000000000000000000000000000031 -:106F60000000000000000000000000000000000021 -:106F70000000000000000000000000000000000011 -:106F80000000000000000000000000000000000001 -:106F900000000000000000000000000000000000F1 -:106FA00000000000000000000000000000000000E1 -:106FB00000000000000000000000000000000000D1 -:106FC00000000000000000000000000000000000C1 -:106FD00000000000000000000000000000000000B1 -:106FE00000000000000000000000000000000000A1 -:106FF0000000000000000000000000000000000091 -:107000000000000000000000000000000000000080 -:107010000000000000000000000000000000000070 -:107020000000000000000000000000000000000060 -:107030000000000000000000000000000000000050 -:107040000000000000000000000000000000000040 -:107050000000000000000000000000000000000030 -:107060000000000000000000000000000000000020 -:107070000000000000000000000000000000000010 -:107080000000000000000000000000000000000000 -:1070900000000000000000000000000000000000F0 -:1070A00000000000000000000000000000000000E0 -:1070B00000000000000000000000000000000000D0 -:1070C00000000000000000000000000000000000C0 -:1070D00000000000000000000000000000000000B0 -:1070E00000000000000000000000000000000000A0 -:1070F0000000000000000000000000000000000090 -:10710000000000000000000000000000000000007F -:10711000000000000000000000000000000000006F -:10712000000000000000000000000000000000005F -:10713000000000000000000000000000000000004F -:10714000000000000000000000000000000000003F -:10715000000000000000000000000000000000002F -:10716000000000000000000000000000000000001F -:10717000000000000000000000000000000000000F -:1071800000000000000000000000000000000000FF -:1071900000000000000000000000000000000000EF -:1071A00000000000000000000000000000000000DF -:1071B00000000000000000000000000000000000CF -:1071C00000000000000000000000000000000000BF -:1071D00000000000000000000000000000000000AF -:1071E000000000000000000000000000000000009F -:1071F000000000000000000000000000000000008F -:10720000000000000000000000000000000000007E -:10721000000000000000000000000000000000006E -:10722000000000000000000000000000000000005E -:10723000000000000000000000000000000000004E -:10724000000000000000000000000000000000003E -:10725000000000000000000000000000000000002E -:10726000000000000000000000000000000000001E -:10727000000000000000000000000000000000000E -:1072800000000000000000000000000000000000FE -:1072900000000000000000000000000000000000EE -:1072A00000000000000000000000000000000000DE -:1072B00000000000000000000000000000000000CE -:1072C00000000000000000000000000000000000BE -:1072D00000000000000000000000000000000000AE -:1072E000000000000000000000000000000000009E -:1072F000000000000000000000000000000000008E -:10730000000000000000000000000000000000007D -:10731000000000000000000000000000000000006D -:10732000000000000000000000000000000000005D -:10733000000000000000000000000000000000004D -:10734000000000000000000000000000000000003D -:10735000000000000000000000000000000000002D -:10736000000000000000000000000000000000001D -:10737000000000000000000000000000000000000D -:1073800000000000000000000000000000000000FD -:1073900000000000000000000000000000000000ED -:1073A00000000000000000000000000000000000DD -:1073B00000000000000000000000000000000000CD -:1073C00000000000000000000000000000000000BD -:1073D00000000000000000000000000000000000AD -:1073E000000000000000000000000000000000009D -:1073F000000000000000000000000000000000008D -:10740000000000000000000000000000000000007C -:10741000000000000000000000000000000000006C -:10742000000000000000000000000000000000005C -:10743000000000000000000000000000000000004C -:10744000000000000000000000000000000000003C -:10745000000000000000000000000000000000002C -:10746000000000000000000000000000000000001C -:10747000000000000000000000000000000000000C -:1074800000000000000000000000000000000000FC -:1074900000000000000000000000000000000000EC -:1074A00000000000000000000000000000000000DC -:1074B00000000000000000000000000000000000CC -:1074C00000000000000000000000000000000000BC -:1074D00000000000000000000000000000000000AC -:1074E000000000000000000000000000000000009C -:1074F000000000000000000000000000000000008C -:10750000000000000000000000000000000000007B -:10751000000000000000000000000000000000006B -:10752000000000000000000000000000000000005B -:10753000000000000000000000000000000000004B -:10754000000000000000000000000000000000003B -:10755000000000000000000000000000000000002B -:10756000000000000000000000000000000000001B -:10757000000000000000000000000000000000000B -:1075800000000000000000000000000000000000FB -:1075900000000000000000000000000000000000EB -:1075A00000000000000000000000000000000000DB -:1075B00000000000000000000000000000000000CB -:1075C00000000000000000000000000000000000BB -:1075D00000000000000000000000000000000000AB -:1075E000000000000000000000000000000000009B -:1075F000000000000000000000000000000000008B -:10760000000000000000000000000000000000007A -:10761000000000000000000000000000000000006A -:10762000000000000000000000000000000000005A -:10763000000000000000000000000000000000004A -:10764000000000000000000000000000000000003A -:10765000000000000000000000000000000000002A -:10766000000000000000000000000000000000001A -:10767000000000000000000000000000000000000A -:1076800000000000000000000000000000000000FA -:1076900000000000000000000000000000000000EA -:1076A00000000000000000000000000000000000DA -:1076B00000000000000000000000000000000000CA -:1076C00000000000000000000000000000000000BA -:1076D00000000000000000000000000000000000AA -:1076E000000000000000000000000000000000009A -:1076F000000000000000000000000000000000008A -:107700000000000000000000000000000000000079 -:107710000000000000000000000000000000000069 -:107720000000000000000000000000000000000059 -:107730000000000000000000000000000000000049 -:107740000000000000000000000000000000000039 -:107750000000000000000000000000000000000029 -:107760000000000000000000000000000000000019 -:107770000000000000000000000000000000000009 -:1077800000000000000000000000000000000000F9 -:1077900000000000000000000000000000000000E9 -:1077A00000000000000000000000000000000000D9 -:1077B00000000000000000000000000000000000C9 -:1077C00000000000000000000000000000000000B9 -:1077D00000000000000000000000000000000000A9 -:1077E0000000000000000000000000000000000099 -:1077F0000000000000000000000000000000000089 -:107800000000000000000000000000000000000078 -:107810000000000000000000000000000000000068 -:107820000000000000000000000000000000000058 -:107830000000000000000000000000000000000048 -:107840000000000000000000000000000000000038 -:107850000000000000000000000000000000000028 -:107860000000000000000000000000000000000018 -:107870000000000000000000000000000000000008 -:1078800000000000000000000000000000000000F8 -:1078900000000000000000000000000000000000E8 -:1078A00000000000000000000000000000000000D8 -:1078B00000000000000000000000000000000000C8 -:1078C00000000000000000000000000000000000B8 -:1078D00000000000000000000000000000000000A8 -:1078E0000000000000000000000000000000000098 -:1078F0000000000000000000000000000000000088 -:107900000000000000000000000000000000000077 -:107910000000000000000000000000000000000067 -:107920000000000000000000000000000000000057 -:107930000000000000000000000000000000000047 -:107940000000000000000000000000000000000037 -:107950000000000000000000000000000000000027 -:107960000000000000000000000000000000000017 -:107970000000000000000000000000000000000007 -:1079800000000000000000000000000000000000F7 -:1079900000000000000000000000000000000000E7 -:1079A00000000000000000000000000000000000D7 -:1079B00000000000000000000000000000000000C7 -:1079C00000000000000000000000000000000000B7 -:1079D00000000000000000000000000000000000A7 -:1079E0000000000000000000000000000000000097 -:1079F0000000000000000000000000000000000087 -:107A00000000000000000000000000000000000076 -:107A10000000000000000000000000000000000066 -:107A20000000000000000000000000000000000056 -:107A30000000000000000000000000000000000046 -:107A40000000000000000000000000000000000036 -:107A50000000000000000000000000000000000026 -:107A60000000000000000000000000000000000016 -:107A70000000000000000000000000000000000006 -:107A800000000000000000000000000000000000F6 -:107A900000000000000000000000000000000000E6 -:107AA00000000000000000000000000000000000D6 -:107AB00000000000000000000000000000000000C6 -:107AC00000000000000000000000000000000000B6 -:107AD00000000000000000000000000000000000A6 -:107AE0000000000000000000000000000000000096 -:107AF0000000000000000000000000000000000086 -:107B00000000000000000000000000000000000075 -:107B10000000000000000000000000000000000065 -:107B20000000000000000000000000000000000055 -:107B30000000000000000000000000000000000045 -:107B40000000000000000000000000000000000035 -:107B50000000000000000000000000000000000025 -:107B60000000000000000000000000000000000015 -:107B70000000000000000000000000000000000005 -:107B800000000000000000000000000000000000F5 -:107B900000000000000000000000000000000000E5 -:107BA00000000000000000000000000000000000D5 -:107BB00000000000000000000000000000000000C5 -:107BC00000000000000000000000000000000000B5 -:107BD00000000000000000000000000000000000A5 -:107BE0000000000000000000000000000000000095 -:107BF0000000000000000000000000000000000085 -:107C00000000000000000000000000000000000074 -:107C10000000000000000000000000000000000064 -:107C20000000000000000000000000000000000054 -:107C30000000000000000000000000000000000044 -:107C40000000000000000000000000000000000034 -:107C50000000000000000000000000000000000024 -:107C60000000000000000000000000000000000014 -:107C70000000000000000000000000000000000004 -:107C800000000000000000000000000000000000F4 -:107C900000000000000000000000000000000000E4 -:107CA00000000000000000000000000000000000D4 -:107CB00000000000000000000000000000000000C4 -:107CC00000000000000000000000000000000000B4 -:107CD00000000000000000000000000000000000A4 -:107CE0000000000000000000000000000000000094 -:107CF0000000000000000000000000000000000084 -:107D00000000000000000000000000000000000073 -:107D10000000000000000000000000000000000063 -:107D20000000000000000000000000000000000053 -:107D30000000000000000000000000000000000043 -:107D40000000000000000000000000000000000033 -:107D50000000000000000000000000000000000023 -:107D60000000000000000000000000000000000013 -:107D70000000000000000000000000000000000003 -:107D800000000000000000000000000000000000F3 -:107D900000000000000000000000000000000000E3 -:107DA00000000000000000000000000000000000D3 -:107DB00000000000000000000000000000000000C3 -:107DC00000000000000000000000000000000000B3 -:107DD00000000000000000000000000000000000A3 -:107DE0000000000000000000000000000000000093 -:107DF0000000000000000000000000000000000083 -:107E00000000000000000000000000000000000072 -:107E10000000000000000000000000000000000062 -:107E20000000000000000000000000000000000052 -:107E30000000000000000000000000000000000042 -:107E40000000000000000000000000000000000032 -:107E50000000000000000000000000000000000022 -:107E60000000000000000000000000000000000012 -:107E70000000000000000000000000000000000002 -:107E800000000000000000000000000000000000F2 -:107E900000000000000000000000000000000000E2 -:107EA00000000000000000000000000000000000D2 -:107EB00000000000000000000000000000000000C2 -:107EC00000000000000000000000000000000000B2 -:107ED00000000000000000000000000000000000A2 -:107EE0000000000000000000000000000000000092 -:107EF0000000000000000000000000000000000082 -:107F00000000000000000000000000000000000071 -:107F10000000000000000000000000000000000061 -:107F20000000000000000000000000000000000051 -:107F30000000000000000000000000000000000041 -:107F40000000000000000000000000000000000031 -:107F50000000000000000000000000000000000021 -:107F60000000000000000000000000000000000011 -:107F70000000000000000000000000000000000001 -:107F800000000000000000000000000000000000F1 -:107F900000000000000000000000000000000000E1 -:107FA00000000000000000000000000000000000D1 -:107FB00000000000000000000000000000000000C1 -:107FC00000000000000000000000000000000000B1 -:107FD00000000000000000000000000000000000A1 -:107FE0000000000000000000000000000000000091 -:107FF0000000000000000000000000000000000081 -:108000000000000000000000000000000000000070 -:108010000000000000000000000000000000000060 -:108020000000000000000000000000000000000050 -:108030000000000000000000000000000000000040 -:108040000000000000000000000000000000000030 -:108050000000000000000000000000000000000020 -:108060000000000000000000000000000000000010 -:108070000000000000000000000000000000000000 -:1080800000000000000000000000000000000000F0 -:1080900000000000000000000000000000000000E0 -:1080A00000000000000000000000000000000000D0 -:1080B00000000000000000000000000000000000C0 -:1080C00000000000000000000000000000000000B0 -:1080D00000000000000000000000000000000000A0 -:1080E0000000000000000000000000000000000090 -:1080F0000000000000000000000000000000000080 -:10810000000000000000000000000000000000006F -:10811000000000000000000000000000000000005F -:10812000000000000000000000000000000000004F -:10813000000000000000000000000000000000003F -:10814000000000000000000000000000000000002F -:10815000000000000000000000000000000000001F -:10816000000000000000000000000000000000000F -:1081700000000000000000000000000000000000FF -:1081800000000000000000000000000000000000EF -:1081900000000000000000000000000000000000DF -:1081A00000000000000000000000000000000000CF -:1081B00000000000000000000000000000000000BF -:1081C00000000000000000000000000000000000AF -:1081D000000000000000000000000000000000009F -:1081E000000000000000000000000000000000008F -:1081F000000000000000000000000000000000007F -:10820000000000000000000000000000000000006E -:10821000000000000000000000000000000000005E -:10822000000000000000000000000000000000004E -:10823000000000000000000000000000000000003E -:10824000000000000000000000000000000000002E -:10825000000000000000000000000000000000001E -:10826000000000000000000000000000000000000E -:1082700000000000000000000000000000000000FE -:1082800000000000000000000000000000000000EE -:1082900000000000000000000000000000000000DE -:1082A00000000000000000000000000000000000CE -:1082B00000000000000000000000000000000000BE -:1082C00000000000000000000000000000000000AE -:1082D000000000000000000000000000000000009E -:1082E000000000000000000000000000000000008E -:1082F000000000000000000000000000000000007E -:10830000000000000000000000000000000000006D -:10831000000000000000000000000000000000005D -:10832000000000000000000000000000000000004D -:10833000000000000000000000000000000000003D -:10834000000000000000000000000000000000002D -:10835000000000000000000000000000000000001D -:10836000000000000000000000000000000000000D -:1083700000000000000000000000000000000000FD -:1083800000000000000000000000000000000000ED -:1083900000000000000000000000000000000000DD -:1083A00000000000000000000000000000000000CD -:1083B00000000000000000000000000000000000BD -:1083C00000000000000000000000000000000000AD -:1083D000000000000000000000000000000000009D -:1083E000000000000000000000000000000000008D -:1083F000000000000000000000000000000000007D -:10840000000000000000000000000000000000006C -:10841000000000000000000000000000000000005C -:10842000000000000000000000000000000000004C -:10843000000000000000000000000000000000003C -:10844000000000000000000000000000000000002C -:10845000000000000000000000000000000000001C -:10846000000000000000000000000000000000000C -:1084700000000000000000000000000000000000FC -:1084800000000000000000000000000000000000EC -:1084900000000000000000000000000000000000DC -:1084A00000000000000000000000000000000000CC -:1084B00000000000000000000000000000000000BC -:1084C00000000000000000000000000000000000AC -:1084D000000000000000000000000000000000009C -:1084E000000000000000000000000000000000008C -:1084F000000000000000000000000000000000007C -:10850000000000000000000000000000000000006B -:10851000000000000000000000000000000000005B -:10852000000000000000000000000000000000004B -:10853000000000000000000000000000000000003B -:10854000000000000000000000000000000000002B -:10855000000000000000000000000000000000001B -:10856000000000000000000000000000000000000B -:1085700000000000000000000000000000000000FB -:1085800000000000000000000000000000000000EB -:1085900000000000000000000000000000000000DB -:1085A00000000000000000000000000000000000CB -:1085B00000000000000000000000000000000000BB -:1085C00000000000000000000000000000000000AB -:1085D000000000000000000000000000000000009B -:1085E000000000000000000000000000000000008B -:1085F000000000000000000000000000000000007B -:10860000000000000000000000000000000000006A -:10861000000000000000000000000000000000005A -:10862000000000000000000000000000000000004A -:10863000000000000000000000000000000000003A -:10864000000000000000000000000000000000002A -:10865000000000000000000000000000000000001A -:10866000000000000000000000000000000000000A -:1086700000000000000000000000000000000000FA -:1086800000000000000000000000000000000000EA -:1086900000000000000000000000000000000000DA -:1086A00000000000000000000000000000000000CA -:1086B00000000000000000000000000000000000BA -:1086C00000000000000000000000000000000000AA -:1086D000000000000000000000000000000000009A -:1086E000000000000000000000000000000000008A -:1086F000000000000000000000000000000000007A -:108700000000000000000000000000000000000069 -:108710000000000000000000000000000000000059 -:108720000000000000000000000000000000000049 -:108730000000000000000000000000000000000039 -:108740000000000000000000000000000000000029 -:108750000000000000000000000000000000000019 -:108760000000000000000000000000000000000009 -:1087700000000000000000000000000000000000F9 -:1087800000000000000000000000000000000000E9 -:1087900000000000000000000000000000000000D9 -:1087A00000000000000000000000000000000000C9 -:1087B00000000000000000000000000000000000B9 -:1087C00000000000000000000000000000000000A9 -:1087D0000000000000000000000000000000000099 -:1087E0000000000000000000000000000000000089 -:1087F0000000000000000000000000000000000079 -:108800000000000000000000000000000000000068 -:108810000000000000000000000000000000000058 -:108820000000000000000000000000000000000048 -:108830000000000000000000000000000000000038 -:108840000000000000000000000000000000000028 -:108850000000000000000000000000000000000018 -:108860000000000000000000000000000000000008 -:1088700000000000000000000000000000000000F8 -:1088800000000000000000000000000000000000E8 -:1088900000000000000000000000000000000000D8 -:1088A00000000000000000000000000000000000C8 -:1088B00000000000000000000000000000000000B8 -:1088C00000000000000000000000000000000000A8 -:1088D0000000000000000000000000000000000098 -:1088E0000000000000000000000000000000000088 -:1088F0000000000000000000000000000000000078 -:108900000000000000000000000000000000000067 -:108910000000000000000000000000000000000057 -:108920000000000000000000000000000000000047 -:108930000000000000000000000000000000000037 -:108940000000000000000000000000000000000027 -:108950000000000000000000000000000000000017 -:108960000000000000000000000000000000000007 -:1089700000000000000000000000000000000000F7 -:1089800000000000000000000000000000000000E7 -:1089900000000000000000000000000000000000D7 -:1089A00000000000000000000000000000000000C7 -:1089B00000000000000000000000000000000000B7 -:1089C00000000000000000000000000000000000A7 -:1089D0000000000000000000000000000000000097 -:1089E0000000000000000000000000000000000087 -:1089F0000000000000000000000000000000000077 -:108A00000000000000000000000000000000000066 -:108A10000000000000000000000000000000000056 -:108A20000000000000000000000000000000000046 -:108A30000000000000000000000000000000000036 -:108A40000000000000000000000000000000000026 -:108A50000000000000000000000000000000000016 -:108A60000000000000000000000000000000000006 -:108A700000000000000000000000000000000000F6 -:108A800000000000000000000000000000000000E6 -:108A900000000000000000000000000000000000D6 -:108AA00000000000000000000000000000000000C6 -:108AB00000000000000000000000000000000000B6 -:108AC00000000000000000000000000000000000A6 -:108AD0000000000000000000000000000000000096 -:108AE0000000000000000000000000000000000086 -:108AF0000000000000000000000000000000000076 -:108B00000000000000000000000000000000000065 -:108B10000000000000000000000000000000000055 -:108B20000000000000000000000000000000000045 -:108B30000000000000000000000000000000000035 -:108B40000000000000000000000000000000000025 -:108B50000000000000000000000000000000000015 -:108B60000000000000000000000000000000000005 -:108B700000000000000000000000000000000000F5 -:108B800000000000000000000000000000000000E5 -:108B900000000000000000000000000000000000D5 -:108BA00000000000000000000000000000000000C5 -:108BB00000000000000000000000000000000000B5 -:108BC00000000000000000000000000000000000A5 -:108BD0000000000000000000000000000000000095 -:108BE0000000000000000000000000000000000085 -:108BF0000000000000000000000000000000000075 -:108C00000000000000000000000000000000000064 -:108C10000000000000000000000000000000000054 -:108C20000000000000000000000000000000000044 -:108C30000000000000000000000000000000000034 -:108C40000000000000000000000000000000000024 -:108C50000000000000000000000000000000000014 -:108C60000000000000000000000000000000000004 -:108C700000000000000000000000000000000000F4 -:108C800000000000000000000000000000000000E4 -:108C900000000000000000000000000000000000D4 -:108CA00000000000000000000000000000000000C4 -:108CB00000000000000000000000000000000000B4 -:108CC00000000000000000000000000000000000A4 -:108CD0000000000000000000000000000000000094 -:108CE0000000000000000000000000000000000084 -:108CF0000000000000000000000000000000000074 -:108D00000000000000000000000000000000000063 -:108D10000000000000000000000000000000000053 -:108D20000000000000000000000000000000000043 -:108D30000000000000000000000000000000000033 -:108D40000000000000000000000000000000000023 -:108D50000000000000000000000000000000000013 -:108D60000000000000000000000000000000000003 -:108D700000000000000000000000000000000000F3 -:108D800000000000000000000000000000000000E3 -:108D900000000000000000000000000000000000D3 -:108DA00000000000000000000000000000000000C3 -:108DB00000000000000000000000000000000000B3 -:108DC00000000000000000000000000000000000A3 -:108DD0000000000000000000000000000000000093 -:108DE0000000000000000000000000000000000083 -:108DF0000000000000000000000000000000000073 -:108E00000000000000000000000000000000000062 -:108E10000000000000000000000000000000000052 -:108E20000000000000000000000000000000000042 -:108E30000000000000000000000000000000000032 -:108E40000000000000000000000000000000000022 -:108E50000000000000000000000000000000000012 -:108E60000000000000000000000000000000000002 -:108E700000000000000000000000000000000000F2 -:108E800000000000000000000000000000000000E2 -:108E900000000000000000000000000000000000D2 -:108EA00000000000000000000000000000000000C2 -:108EB00000000000000000000000000000000000B2 -:108EC00000000000000000000000000000000000A2 -:108ED0000000000000000000000000000000000092 -:108EE0000000000000000000000000000000000082 -:108EF0000000000000000000000000000000000072 -:108F00000000000000000000000000000000000061 -:108F10000000000000000000000000000000000051 -:108F20000000000000000000000000000000000041 -:108F30000000000000000000000000000000000031 -:108F40000000000000000000000000000000000021 -:108F50000000000000000000000000000000000011 -:108F60000000000000000000000000000000000001 -:108F700000000000000000000000000000000000F1 -:108F800000000000000000000000000000000000E1 -:108F900000000000000000000000000000000000D1 -:108FA00000000000000000000000000000000000C1 -:108FB00000000000000000000000000000000000B1 -:108FC00000000000000000000000000000000000A1 -:108FD0000000000000000000000000000000000091 -:108FE0000000000000000000000000000000000081 -:108FF0000000000000000000000000000000000071 -:109000000000000000000000000000000000000060 -:109010000000000000000000000000000000000050 -:109020000000000000000000000000000000000040 -:109030000000000000000000000000000000000030 -:109040000000000000000000000000000000000020 -:109050000000000000000000000000000000000010 -:109060000000000000000000000000000000000000 -:1090700000000000000000000000000000000000F0 -:1090800000000000000000000000000000000000E0 -:1090900000000000000000000000000000000000D0 -:1090A00000000000000000000000000000000000C0 -:1090B00000000000000000000000000000000000B0 -:1090C00000000000000000000000000000000000A0 -:1090D0000000000000000000000000000000000090 -:1090E0000000000000000000000000000000000080 -:1090F0000000000000000000000000000000000070 -:10910000000000000000000000000000000000005F -:10911000000000000000000000000000000000004F -:10912000000000000000000000000000000000003F -:10913000000000000000000000000000000000002F -:10914000000000000000000000000000000000001F -:10915000000000000000000000000000000000000F -:1091600000000000000000000000000000000000FF -:1091700000000000000000000000000000000000EF -:1091800000000000000000000000000000000000DF -:1091900000000000000000000000000000000000CF -:1091A00000000000000000000000000000000000BF -:1091B00000000000000000000000000000000000AF -:1091C000000000000000000000000000000000009F -:1091D000000000000000000000000000000000008F -:1091E000000000000000000000000000000000007F -:1091F000000000000000000000000000000000006F -:10920000000000000000000000000000000000005E -:10921000000000000000000000000000000000004E -:10922000000000000000000000000000000000003E -:10923000000000000000000000000000000000002E -:10924000000000000000000000000000000000001E -:10925000000000000000000000000000000000000E -:1092600000000000000000000000000000000000FE -:1092700000000000000000000000000000000000EE -:1092800000000000000000000000000000000000DE -:1092900000000000000000000000000000000000CE -:1092A00000000000000000000000000000000000BE -:1092B00000000000000000000000000000000000AE -:1092C000000000000000000000000000000000009E -:1092D000000000000000000000000000000000008E -:1092E000000000000000000000000000000000007E -:1092F000000000000000000000000000000000006E -:10930000000000000000000000000000000000005D -:10931000000000000000000000000000000000004D -:10932000000000000000000000000000000000003D -:10933000000000000000000000000000000000002D -:10934000000000000000000000000000000000001D -:10935000000000000000000000000000000000000D -:1093600000000000000000000000000000000000FD -:1093700000000000000000000000000000000000ED -:1093800000000000000000000000000000000000DD -:1093900000000000000000000000000000000000CD -:1093A00000000000000000000000000000000000BD -:1093B00000000000000000000000000000000000AD -:1093C000000000000000000000000000000000009D -:1093D000000000000000000000000000000000008D -:1093E000000000000000000000000000000000007D -:1093F000000000000000000000000000000000006D -:10940000000000000000000000000000000000005C -:10941000000000000000000000000000000000004C -:10942000000000000000000000000000000000003C -:10943000000000000000000000000000000000002C -:10944000000000000000000000000000000000001C -:10945000000000000000000000000000000000000C -:1094600000000000000000000000000000000000FC -:1094700000000000000000000000000000000000EC -:1094800000000000000000000000000000000000DC -:1094900000000000000000000000000000000000CC -:1094A00000000000000000000000000000000000BC -:1094B00000000000000000000000000000000000AC -:1094C000000000000000000000000000000000009C -:1094D000000000000000000000000000000000008C -:1094E000000000000000000000000000000000007C -:1094F000000000000000000000000000000000006C -:10950000000000000000000000000000000000005B -:10951000000000000000000000000000000000004B -:10952000000000000000000000000000000000003B -:10953000000000000000000000000000000000002B -:10954000000000000000000000000000000000001B -:10955000000000000000000000000000000000000B -:1095600000000000000000000000000000000000FB -:1095700000000000000000000000000000000000EB -:1095800000000000000000000000000000000000DB -:1095900000000000000000000000000000000000CB -:1095A00000000000000000000000000000000000BB -:1095B00000000000000000000000000000000000AB -:1095C000000000000000000000000000000000009B -:1095D000000000000000000000000000000000008B -:1095E000000000000000000000000000000000007B -:1095F000000000000000000000000000000000006B -:10960000000000000000000000000000000000005A -:10961000000000000000000000000000000000004A -:10962000000000000000000000000000000000003A -:10963000000000000000000000000000000000002A -:10964000000000000000000000000000000000001A -:10965000000000000000000000000000000000000A -:1096600000000000000000000000000000000000FA -:1096700000000000000000000000000000000000EA -:1096800000000000000000000000000000000000DA -:1096900000000000000000000000000000000000CA -:1096A00000000000000000000000000000000000BA -:1096B00000000000000000000000000000000000AA -:1096C000000000000000000000000000000000009A -:1096D000000000000000000000000000000000008A -:1096E000000000000000000000000000000000007A -:1096F000000000000000000000000000000000006A -:109700000000000000000000000000000000000059 -:109710000000000000000000000000000000000049 -:109720000000000000000000000000000000000039 -:109730000000000000000000000000000000000029 -:109740000000000000000000000000000000000019 -:109750000000000000000000000000000000000009 -:1097600000000000000000000000000000000000F9 -:1097700000000000000000000000000000000000E9 -:1097800000000000000000000000000000000000D9 -:1097900000000000000000000000000000000000C9 -:1097A00000000000000000000000000000000000B9 -:1097B00000000000000000000000000000000000A9 -:1097C0000000000000000000000000000000000099 -:1097D0000000000000000000000000000000000089 -:1097E0000000000000000000000000000000000079 -:1097F0000000000000000000000000000000000069 -:109800000000000000000000000000000000000058 -:109810000000000000000000000000000000000048 -:109820000000000000000000000000000000000038 -:109830000000000000000000000000000000000028 -:109840000000000000000000000000000000000018 -:109850000000000000000000000000000000000008 -:1098600000000000000000000000000000000000F8 -:1098700000000000000000000000000000000000E8 -:1098800000000000000000000000000000000000D8 -:1098900000000000000000000000000000000000C8 -:1098A00000000000000000000000000000000000B8 -:1098B00000000000000000000000000000000000A8 -:1098C0000000000000000000000000000000000098 -:1098D0000000000000000000000000000000000088 -:1098E0000000000000000000000000000000000078 -:1098F0000000000000000000000000000000000068 -:109900000000000000000000000000000000000057 -:109910000000000000000000000000000000000047 -:109920000000000000000000000000000000000037 -:109930000000000000000000000000000000000027 -:109940000000000000000000000000000000000017 -:109950000000000000000000000000000000000007 -:1099600000000000000000000000000000000000F7 -:1099700000000000000000000000000000000000E7 -:1099800000000000000000000000000000000000D7 -:1099900000000000000000000000000000000000C7 -:1099A00000000000000000000000000000000000B7 -:1099B00000000000000000000000000000000000A7 -:1099C0000000000000000000000000000000000097 -:1099D0000000000000000000000000000000000087 -:1099E0000000000000000000000000000000000077 -:1099F0000000000000000000000000000000000067 -:109A00000000000000000000000000000000000056 -:109A10000000000000000000000000000000000046 -:109A20000000000000000000000000000000000036 -:109A30000000000000000000000000000000000026 -:109A40000000000000000000000000000000000016 -:109A50000000000000000000000000000000000006 -:109A600000000000000000000000000000000000F6 -:109A700000000000000000000000000000000000E6 -:109A800000000000000000000000000000000000D6 -:109A900000000000000000000000000000000000C6 -:109AA00000000000000000000000000000000000B6 -:109AB00000000000000000000000000000000000A6 -:109AC0000000000000000000000000000000000096 -:109AD0000000000000000000000000000000000086 -:109AE0000000000000000000000000000000000076 -:109AF0000000000000000000000000000000000066 -:109B00000000000000000000000000000000000055 -:109B10000000000000000000000000000000000045 -:109B20000000000000000000000000000000000035 -:109B30000000000000000000000000000000000025 -:109B40000000000000000000000000000000000015 -:109B50000000000000000000000000000000000005 -:109B600000000000000000000000000000000000F5 -:109B700000000000000000000000000000000000E5 -:109B800000000000000000000000000000000000D5 -:109B900000000000000000000000000000000000C5 -:109BA00000000000000000000000000000000000B5 -:109BB00000000000000000000000000000000000A5 -:109BC0000000000000000000000000000000000095 -:109BD0000000000000000000000000000000000085 -:109BE0000000000000000000000000000000000075 -:109BF0000000000000000000000000000000000065 -:109C00000000000000000000000000000000000054 -:109C10000000000000000000000000000000000044 -:109C20000000000000000000000000000000000034 -:109C30000000000000000000000000000000000024 -:109C40000000000000000000000000000000000014 -:109C50000000000000000000000000000000000004 -:109C600000000000000000000000000000000000F4 -:109C700000000000000000000000000000000000E4 -:109C800000000000000000000000000000000000D4 -:109C900000000000000000000000000000000000C4 -:109CA00000000000000000000000000000000000B4 -:109CB00000000000000000000000000000000000A4 -:109CC0000000000000000000000000000000000094 -:109CD0000000000000000000000000000000000084 -:109CE0000000000000000000000000000000000074 -:109CF0000000000000000000000000000000000064 -:109D00000000000000000000000000000000000053 -:109D10000000000000000000000000000000000043 -:109D20000000000000000000000000000000000033 -:109D30000000000000000000000000000000000023 -:109D40000000000000000000000000000000000013 -:109D50000000000000000000000000000000000003 -:109D600000000000000000000000000000000000F3 -:109D700000000000000000000000000000000000E3 -:109D800000000000000000000000000000000000D3 -:109D900000000000000000000000000000000000C3 -:109DA00000000000000000000000000000000000B3 -:109DB00000000000000000000000000000000000A3 -:109DC0000000000000000000000000000000000093 -:109DD0000000000000000000000000000000000083 -:109DE0000000000000000000000000000000000073 -:109DF0000000000000000000000000000000000063 -:109E00000000000000000000000000000000000052 -:109E10000000000000000000000000000000000042 -:109E20000000000000000000000000000000000032 -:109E30000000000000000000000000000000000022 -:109E40000000000000000000000000000000000012 -:109E50000000000000000000000000000000000002 -:109E600000000000000000000000000000000000F2 -:109E700000000000000000000000000000000000E2 -:109E800000000000000000000000000000000000D2 -:109E900000000000000000000000000000000000C2 -:109EA00000000000000000000000000000000000B2 -:109EB00000000000000000000000000000000000A2 -:109EC0000000000000000000000000000000000092 -:109ED0000000000000000000000000000000000082 -:109EE0000000000000000000000000000000000072 -:109EF0000000000000000000000000000000000062 -:109F00000000000000000000000000000000000051 -:109F10000000000000000000000000000000000041 -:109F20000000000000000000000000000000000031 -:109F30000000000000000000000000000000000021 -:109F40000000000000000000000000000000000011 -:109F50000000000000000000000000000000000001 -:109F600000000000000000000000000000000000F1 -:109F700000000000000000000000000000000000E1 -:109F800000000000000000000000000000000000D1 -:109F900000000000000000000000000000000000C1 -:109FA00000000000000000000000000000000000B1 -:109FB00000000000000000000000000000000000A1 -:109FC0000000000000000000000000000000000091 -:109FD0000000000000000000000000000000000081 -:109FE0000000000000000000000000000000000071 -:109FF0000000000000000000000000000000000061 -:10A000000000000000000000000000000000000050 -:10A010000000000000000000000000000000000040 -:10A020000000000000000000000000000000000030 -:10A030000000000000000000000000000000000020 -:10A040000000000000000000000000000000000010 -:10A050000000000000000000000000000000000000 -:10A0600000000000000000000000000000000000F0 -:10A0700000000000000000000000000000000000E0 -:10A0800000000000000000000000000000000000D0 -:10A0900000000000000000000000000000000000C0 -:10A0A00000000000000000000000000000000000B0 -:10A0B00000000000000000000000000000000000A0 -:10A0C0000000000000000000000000000000000090 -:10A0D0000000000000000000000000000000000080 -:10A0E0000000000000000000000000000000000070 -:10A0F0000000000000000000000000000000000060 -:10A10000000000000000000000000000000000004F -:10A11000000000000000000000000000000000003F -:10A12000000000000000000000000000000000002F -:10A13000000000000000000000000000000000001F -:10A14000000000000000000000000000000000000F -:10A1500000000000000000000000000000000000FF -:10A1600000000000000000000000000000000000EF -:10A1700000000000000000000000000000000000DF -:10A1800000000000000000000000000000000000CF -:10A1900000000000000000000000000000000000BF -:10A1A00000000000000000000000000000000000AF -:10A1B000000000000000000000000000000000009F -:10A1C000000000000000000000000000000000008F -:10A1D000000000000000000000000000000000007F -:10A1E000000000000000000000000000000000006F -:10A1F000000000000000000000000000000000005F -:10A20000000000000000000000000000000000004E -:10A21000000000000000000000000000000000003E -:10A22000000000000000000000000000000000002E -:10A23000000000000000000000000000000000001E -:10A24000000000000000000000000000000000000E -:10A2500000000000000000000000000000000000FE -:10A2600000000000000000000000000000000000EE -:10A2700000000000000000000000000000000000DE -:10A2800000000000000000000000000000000000CE -:10A2900000000000000000000000000000000000BE -:10A2A00000000000000000000000000000000000AE -:10A2B000000000000000000000000000000000009E -:10A2C000000000000000000000000000000000008E -:10A2D000000000000000000000000000000000007E -:10A2E000000000000000000000000000000000006E -:10A2F000000000000000000000000000000000005E -:10A30000000000000000000000000000000000004D -:10A31000000000000000000000000000000000003D -:10A32000000000000000000000000000000000002D -:10A33000000000000000000000000000000000001D -:10A34000000000000000000000000000000000000D -:10A3500000000000000000000000000000000000FD -:10A3600000000000000000000000000000000000ED -:10A3700000000000000000000000000000000000DD -:10A3800000000000000000000000000000000000CD -:10A3900000000000000000000000000000000000BD -:10A3A00000000000000000000000000000000000AD -:10A3B000000000000000000000000000000000009D -:10A3C000000000000000000000000000000000008D -:10A3D000000000000000000000000000000000007D -:10A3E000000000000000000000000000000000006D -:10A3F000000000000000000000000000000000005D -:10A40000000000000000000000000000000000004C -:10A41000000000000000000000000000000000003C -:10A42000000000000000000000000000000000002C -:10A43000000000000000000000000000000000001C -:10A44000000000000000000000000000000000000C -:10A4500000000000000000000000000000000000FC -:10A4600000000000000000000000000000000000EC -:10A4700000000000000000000000000000000000DC -:10A4800000000000000000000000000000000000CC -:10A4900000000000000000000000000000000000BC -:10A4A00000000000000000000000000000000000AC -:10A4B000000000000000000000000000000000009C -:10A4C000000000000000000000000000000000008C -:10A4D000000000000000000000000000000000007C -:10A4E000000000000000000000000000000000006C -:10A4F000000000000000000000000000000000005C -:10A50000000000000000000000000000000000004B -:10A51000000000000000000000000000000000003B -:10A52000000000000000000000000000000000002B -:10A53000000000000000000000000000000000001B -:10A54000000000000000000000000000000000000B -:10A5500000000000000000000000000000000000FB -:10A5600000000000000000000000000000000000EB -:10A5700000000000000000000000000000000000DB -:10A5800000000000000000000000000000000000CB -:10A5900000000000000000000000000000000000BB -:10A5A00000000000000000000000000000000000AB -:10A5B000000000000000000000000000000000009B -:10A5C000000000000000000000000000000000008B -:10A5D000000000000000000000000000000000007B -:10A5E000000000000000000000000000000000006B -:10A5F000000000000000000000000000000000005B -:10A60000000000000000000000000000000000004A -:10A61000000000000000000000000000000000003A -:10A62000000000000000000000000000000000002A -:10A63000000000000000000000000000000000001A -:10A64000000000000000000000000000000000000A -:10A6500000000000000000000000000000000000FA -:10A6600000000000000000000000000000000000EA -:10A6700000000000000000000000000000000000DA -:10A6800000000000000000000000000000000000CA -:10A6900000000000000000000000000000000000BA -:10A6A00000000000000000000000000000000000AA -:10A6B000000000000000000000000000000000009A -:10A6C000000000000000000000000000000000008A -:10A6D000000000000000000000000000000000007A -:10A6E000000000000000000000000000000000006A -:10A6F000000000000000000000000000000000005A -:10A700000000000000000000000000000000000049 -:10A710000000000000000000000000000000000039 -:10A720000000000000000000000000000000000029 -:10A730000000000000000000000000000000000019 -:10A740000000000000000000000000000000000009 -:10A7500000000000000000000000000000000000F9 -:10A7600000000000000000000000000000000000E9 -:10A7700000000000000000000000000000000000D9 -:10A7800000000000000000000000000000000000C9 -:10A7900000000000000000000000000000000000B9 -:10A7A00000000000000000000000000000000000A9 -:10A7B0000000000000000000000000000000000099 -:10A7C0000000000000000000000000000000000089 -:10A7D0000000000000000000000000000000000079 -:10A7E0000000000000000000000000000000000069 -:10A7F0000000000000000000000000000000000059 -:10A800000000000000000000000000000000000048 -:10A810000000000000000000000000000000000038 -:10A820000000000000000000000000000000000028 -:10A830000000000000000000000000000000000018 -:10A840000000000000000000000000000000000008 -:10A8500000000000000000000000000000000000F8 -:10A8600000000000000000000000000000000000E8 -:10A8700000000000000000000000000000000000D8 -:10A8800000000000000000000000000000000000C8 -:10A8900000000000000000000000000000000000B8 -:10A8A00000000000000000000000000000000000A8 -:10A8B0000000000000000000000000000000000098 -:10A8C0000000000000000000000000000000000088 -:10A8D0000000000000000000000000000000000078 -:10A8E0000000000000000000000000000000000068 -:10A8F0000000000000000000000000000000000058 -:10A900000000000000000000000000000000000047 -:10A910000000000000000000000000000000000037 -:10A920000000000000000000000000000000000027 -:10A930000000000000000000000000000000000017 -:10A940000000000000000000000000000000000007 -:10A9500000000000000000000000000000000000F7 -:10A9600000000000000000000000000000000000E7 -:10A9700000000000000000000000000000000000D7 -:10A9800000000000000000000000000000000000C7 -:10A9900000000000000000000000000000000000B7 -:10A9A00000000000000000000000000000000000A7 -:10A9B0000000000000000000000000000000000097 -:10A9C0000000000000000000000000000000000087 -:10A9D0000000000000000000000000000000000077 -:10A9E0000000000000000000000000000000000067 -:10A9F0000000000000000000000000000000000057 -:10AA00000000000000000000000000000000000046 -:10AA10000000000000000000000000000000000036 -:10AA20000000000000000000000000000000000026 -:10AA30000000000000000000000000000000000016 -:10AA40000000000000000000000000000000000006 -:10AA500000000000000000000000000000000000F6 -:10AA600000000000000000000000000000000000E6 -:10AA700000000000000000000000000000000000D6 -:10AA800000000000000000000000000000000000C6 -:10AA900000000000000000000000000000000000B6 -:10AAA00000000000000000000000000000000000A6 -:10AAB0000000000000000000000000000000000096 -:10AAC0000000000000000000000000000000000086 -:10AAD0000000000000000000000000000000000076 -:10AAE0000000000000000000000000000000000066 -:10AAF0000000000000000000000000000000000056 -:10AB00000000000000000000000000000000000045 -:10AB10000000000000000000000000000000000035 -:10AB20000000000000000000000000000000000025 -:10AB30000000000000000000000000000000000015 -:10AB40000000000000000000000000000000000005 -:10AB500000000000000000000000000000000000F5 -:10AB600000000000000000000000000000000000E5 -:10AB700000000000000000000000000000000000D5 -:10AB800000000000000000000000000000000000C5 -:10AB900000000000000000000000000000000000B5 -:10ABA00000000000000000000000000000000000A5 -:10ABB0000000000000000000000000000000000095 -:10ABC0000000000000000000000000000000000085 -:10ABD0000000000000000000000000000000000075 -:10ABE0000000000000000000000000000000000065 -:10ABF0000000000000000000000000000000000055 -:10AC00000000000000000000000000000000000044 -:10AC10000000000000000000000000000000000034 -:10AC20000000000000000000000000000000000024 -:10AC30000000000000000000000000000000000014 -:10AC40000000000000000000000000000000000004 -:10AC500000000000000000000000000000000000F4 -:10AC600000000000000000000000000000000000E4 -:10AC700000000000000000000000000000000000D4 -:10AC800000000000000000000000000000000000C4 -:10AC900000000000000000000000000000000000B4 -:10ACA00000000000000000000000000000000000A4 -:10ACB0000000000000000000000000000000000094 -:10ACC0000000000000000000000000000000000084 -:10ACD0000000000000000000000000000000000074 -:10ACE0000000000000000000000000000000000064 -:10ACF0000000000000000000000000000000000054 -:10AD00000000000000000000000000000000000043 -:10AD10000000000000000000000000000000000033 -:10AD20000000000000000000000000000000000023 -:10AD30000000000000000000000000000000000013 -:10AD40000000000000000000000000000000000003 -:10AD500000000000000000000000000000000000F3 -:10AD600000000000000000000000000000000000E3 -:10AD700000000000000000000000000000000000D3 -:10AD800000000000000000000000000000000000C3 -:10AD900000000000000000000000000000000000B3 -:10ADA00000000000000000000000000000000000A3 -:10ADB0000000000000000000000000000000000093 -:10ADC0000000000000000000000000000000000083 -:10ADD0000000000000000000000000000000000073 -:10ADE0000000000000000000000000000000000063 -:10ADF0000000000000000000000000000000000053 -:10AE00000000000000000000000000000000000042 -:10AE10000000000000000000000000000000000032 -:10AE20000000000000000000000000000000000022 -:10AE30000000000000000000000000000000000012 -:10AE40000000000000000000000000000000000002 -:10AE500000000000000000000000000000000000F2 -:10AE600000000000000000000000000000000000E2 -:10AE700000000000000000000000000000000000D2 -:10AE800000000000000000000000000000000000C2 -:10AE900000000000000000000000000000000000B2 -:10AEA00000000000000000000000000000000000A2 -:10AEB0000000000000000000000000000000000092 -:10AEC0000000000000000000000000000000000082 -:10AED0000000000000000000000000000000000072 -:10AEE0000000000000000000000000000000000062 -:10AEF0000000000000000000000000000000000052 -:10AF00000000000000000000000000000000000041 -:10AF10000000000000000000000000000000000031 -:10AF20000000000000000000000000000000000021 -:10AF30000000000000000000000000000000000011 -:10AF40000000000000000000000000000000000001 -:10AF500000000000000000000000000000000000F1 -:10AF600000000000000000000000000000000000E1 -:10AF700000000000000000000000000000000000D1 -:10AF800000000000000000000000000000000000C1 -:10AF900000000000000000000000000000000000B1 -:10AFA00000000000000000000000000000000000A1 -:10AFB0000000000000000000000000000000000091 -:10AFC0000000000000000000000000000000000081 -:10AFD0000000000000000000000000000000000071 -:10AFE0000000000000000000000000000000000061 -:10AFF0000000000000000000000000000000000051 -:10B000000000000000000000000000000000000040 -:10B010000000000000000000000000000000000030 -:10B020000000000000000000000000000000000020 -:10B030000000000000000000000000000000000010 -:10B040000000000000000000000000000000000000 -:10B0500000000000000000000000000000000000F0 -:10B0600000000000000000000000000000000000E0 -:10B0700000000000000000000000000000000000D0 -:10B0800000000000000000000000000000000000C0 -:10B0900000000000000000000000000000000000B0 -:10B0A00000000000000000000000000000000000A0 -:10B0B0000000000000000000000000000000000090 -:10B0C0000000000000000000000000000000000080 -:10B0D0000000000000000000000000000000000070 -:10B0E0000000000000000000000000000000000060 -:10B0F0000000000000000000000000000000000050 -:10B10000000000000000000000000000000000003F -:10B11000000000000000000000000000000000002F -:10B12000000000000000000000000000000000001F -:10B13000000000000000000000000000000000000F -:10B1400000000000000000000000000000000000FF -:10B1500000000000000000000000000000000000EF -:10B1600000000000000000000000000000000000DF -:10B1700000000000000000000000000000000000CF -:10B1800000000000000000000000000000000000BF -:10B1900000000000000000000000000000000000AF -:10B1A000000000000000000000000000000000009F -:10B1B000000000000000000000000000000000008F -:10B1C000000000000000000000000000000000007F -:10B1D000000000000000000000000000000000006F -:10B1E000000000000000000000000000000000005F -:10B1F000000000000000000000000000000000004F -:10B20000000000000000000000000000000000003E -:10B21000000000000000000000000000000000002E -:10B22000000000000000000000000000000000001E -:10B23000000000000000000000000000000000000E -:10B2400000000000000000000000000000000000FE -:10B2500000000000000000000000000000000000EE -:10B2600000000000000000000000000000000000DE -:10B2700000000000000000000000000000000000CE -:10B2800000000000000000000000000000000000BE -:10B2900000000000000000000000000000000000AE -:10B2A000000000000000000000000000000000009E -:10B2B000000000000000000000000000000000008E -:10B2C000000000000000000000000000000000007E -:10B2D000000000000000000000000000000000006E -:10B2E000000000000000000000000000000000005E -:10B2F000000000000000000000000000000000004E -:10B30000000000000000000000000000000000003D -:10B31000000000000000000000000000000000002D -:10B32000000000000000000000000000000000001D -:10B33000000000000000000000000000000000000D -:10B3400000000000000000000000000000000000FD -:10B3500000000000000000000000000000000000ED -:10B3600000000000000000000000000000000000DD -:10B3700000000000000000000000000000000000CD -:10B3800000000000000000000000000000000000BD -:10B3900000000000000000000000000000000000AD -:10B3A000000000000000000000000000000000009D -:10B3B000000000000000000000000000000000008D -:10B3C000000000000000000000000000000000007D -:10B3D000000000000000000000000000000000006D -:10B3E000000000000000000000000000000000005D -:10B3F000000000000000000000000000000000004D -:10B40000000000000000000000000000000000003C -:10B41000000000000000000000000000000000002C -:10B42000000000000000000000000000000000001C -:10B43000000000000000000000000000000000000C -:10B4400000000000000000000000000000000000FC -:10B4500000000000000000000000000000000000EC -:10B4600000000000000000000000000000000000DC -:10B4700000000000000000000000000000000000CC -:10B4800000000000000000000000000000000000BC -:10B4900000000000000000000000000000000000AC -:10B4A000000000000000000000000000000000009C -:10B4B000000000000000000000000000000000008C -:10B4C000000000000000000000000000000000007C -:10B4D000000000000000000000000000000000006C -:10B4E000000000000000000000000000000000005C -:10B4F000000000000000000000000000000000004C -:10B50000000000000000000000000000000000003B -:10B51000000000000000000000000000000000002B -:10B52000000000000000000000000000000000001B -:10B53000000000000000000000000000000000000B -:10B5400000000000000000000000000000000000FB -:10B5500000000000000000000000000000000000EB -:10B5600000000000000000000000000000000000DB -:10B5700000000000000000000000000000000000CB -:10B5800000000000000000000000000000000000BB -:10B5900000000000000000000000000000000000AB -:10B5A000000000000000000000000000000000009B -:10B5B000000000000000000000000000000000008B -:10B5C000000000000000000000000000000000007B -:10B5D000000000000000000000000000000000006B -:10B5E000000000000000000000000000000000005B -:10B5F000000000000000000000000000000000004B -:10B60000000000000000000000000000000000003A -:10B61000000000000000000000000000000000002A -:10B62000000000000000000000000000000000001A -:10B63000000000000000000000000000000000000A -:10B6400000000000000000000000000000000000FA -:10B6500000000000000000000000000000000000EA -:10B6600000000000000000000000000000000000DA -:10B6700000000000000000000000000000000000CA -:10B6800000000000000000000000000000000000BA -:10B6900000000000000000000000000000000000AA -:10B6A000000000000000000000000000000000009A -:10B6B000000000000000000000000000000000008A -:10B6C000000000000000000000000000000000007A -:10B6D000000000000000000000000000000000006A -:10B6E000000000000000000000000000000000005A -:10B6F000000000000000000000000000000000004A -:10B700000000000000000000000000000000000039 -:10B710000000000000000000000000000000000029 -:10B720000000000000000000000000000000000019 -:10B730000000000000000000000000000000000009 -:10B7400000000000000000000000000000000000F9 -:10B7500000000000000000000000000000000000E9 -:10B7600000000000000000000000000000000000D9 -:10B7700000000000000000000000000000000000C9 -:10B7800000000000000000000000000000000000B9 -:10B7900000000000000000000000000000000000A9 -:10B7A0000000000000000000000000000000000099 -:10B7B0000000000000000000000000000000000089 -:10B7C0000000000000000000000000000000000079 -:10B7D0000000000000000000000000000000000069 -:10B7E0000000000000000000000000000000000059 -:10B7F0000000000000000000000000000000000049 -:10B800000000000000000000000000000000000038 -:10B810000000000000000000000000000000000028 -:10B820000000000000000000000000000000000018 -:10B830000000000000000000000000000000000008 -:10B8400000000000000000000000000000000000F8 -:10B8500000000000000000000000000000000000E8 -:10B8600000000000000000000000000000000000D8 -:10B8700000000000000000000000000000000000C8 -:10B8800000000000000000000000000000000000B8 -:10B8900000000000000000000000000000000000A8 -:10B8A0000000000000000000000000000000000098 -:10B8B0000000000000000000000000000000000088 -:10B8C0000000000000000000000000000000000078 -:10B8D0000000000000000000000000000000000068 -:10B8E0000000000000000000000000000000000058 -:10B8F0000000000000000000000000000000000048 -:10B900000000000000000000000000000000000037 -:10B910000000000000000000000000000000000027 -:10B920000000000000000000000000000000000017 -:10B930000000000000000000000000000000000007 -:10B9400000000000000000000000000000000000F7 -:10B9500000000000000000000000000000000000E7 -:10B9600000000000000000000000000000000000D7 -:10B9700000000000000000000000000000000000C7 -:10B9800000000000000000000000000000000000B7 -:10B9900000000000000000000000000000000000A7 -:10B9A0000000000000000000000000000000000097 -:10B9B0000000000000000000000000000000000087 -:10B9C0000000000000000000000000000000000077 -:10B9D0000000000000000000000000000000000067 -:10B9E0000000000000000000000000000000000057 -:10B9F0000000000000000000000000000000000047 -:10BA00000000000000000000000000000000000036 -:10BA10000000000000000000000000000000000026 -:10BA20000000000000000000000000000000000016 -:10BA30000000000000000000000000000000000006 -:10BA400000000000000000000000000000000000F6 -:10BA500000000000000000000000000000000000E6 -:10BA600000000000000000000000000000000000D6 -:10BA700000000000000000000000000000000000C6 -:10BA800000000000000000000000000000000000B6 -:10BA900000000000000000000000000000000000A6 -:10BAA0000000000000000000000000000000000096 -:10BAB0000000000000000000000000000000000086 -:10BAC0000000000000000000000000000000000076 -:10BAD0000000000000000000000000000000000066 -:10BAE0000000000000000000000000000000000056 -:10BAF0000000000000000000000000000000000046 -:10BB00000000000000000000000000000000000035 -:10BB10000000000000000000000000000000000025 -:10BB20000000000000000000000000000000000015 -:10BB30000000000000000000000000000000000005 -:10BB400000000000000000000000000000000000F5 -:10BB500000000000000000000000000000000000E5 -:10BB600000000000000000000000000000000000D5 -:10BB700000000000000000000000000000000000C5 -:10BB800000000000000000000000000000000000B5 -:10BB900000000000000000000000000000000000A5 -:10BBA0000000000000000000000000000000000095 -:10BBB0000000000000000000000000000000000085 -:10BBC0000000000000000000000000000000000075 -:10BBD0000000000000000000000000000000000065 -:10BBE0000000000000000000000000000000000055 -:10BBF0000000000000000000000000000000000045 -:10BC00000000000000000000000000000000000034 -:10BC10000000000000000000000000000000000024 -:10BC20000000000000000000000000000000000014 -:10BC30000000000000000000000000000000000004 -:10BC400000000000000000000000000000000000F4 -:10BC500000000000000000000000000000000000E4 -:10BC600000000000000000000000000000000000D4 -:10BC700000000000000000000000000000000000C4 -:10BC800000000000000000000000000000000000B4 -:10BC900000000000000000000000000000000000A4 -:10BCA0000000000000000000000000000000000094 -:10BCB0000000000000000000000000000000000084 -:10BCC0000000000000000000000000000000000074 -:10BCD0000000000000000000000000000000000064 -:10BCE0000000000000000000000000000000000054 -:10BCF0000000000000000000000000000000000044 -:10BD00000000000000000000000000000000000033 -:10BD10000000000000000000000000000000000023 -:10BD20000000000000000000000000000000000013 -:10BD30000000000000000000000000000000000003 -:10BD400000000000000000000000000000000000F3 -:10BD500000000000000000000000000000000000E3 -:10BD600000000000000000000000000000000000D3 -:10BD700000000000000000000000000000000000C3 -:10BD800000000000000000000000000000000000B3 -:10BD900000000000000000000000000000000000A3 -:10BDA0000000000000000000000000000000000093 -:10BDB0000000000000000000000000000000000083 -:10BDC0000000000000000000000000000000000073 -:10BDD0000000000000000000000000000000000063 -:10BDE0000000000000000000000000000000000053 -:10BDF0000000000000000000000000000000000043 -:10BE00000000000000000000000000000000000032 -:10BE10000000000000000000000000000000000022 -:10BE20000000000000000000000000000000000012 -:10BE30000000000000000000000000000000000002 -:10BE400000000000000000000000000000000000F2 -:10BE500000000000000000000000000000000000E2 -:10BE600000000000000000000000000000000000D2 -:10BE700000000000000000000000000000000000C2 -:10BE800000000000000000000000000000000000B2 -:10BE900000000000000000000000000000000000A2 -:10BEA0000000000000000000000000000000000092 -:10BEB0000000000000000000000000000000000082 -:10BEC0000000000000000000000000000000000072 -:10BED0000000000000000000000000000000000062 -:10BEE0000000000000000000000000000000000052 -:10BEF0000000000000000000000000000000000042 -:10BF00000000000000000000000000000000000031 -:10BF10000000000000000000000000000000000021 -:10BF20000000000000000000000000000000000011 -:10BF30000000000000000000000000000000000001 -:10BF400000000000000000000000000000000000F1 -:10BF500000000000000000000000000000000000E1 -:10BF600000000000000000000000000000000000D1 -:10BF700000000000000000000000000000000000C1 -:10BF800000000000000000000000000000000000B1 -:10BF900000000000000000000000000000000000A1 -:10BFA0000000000000000000000000000000000091 -:10BFB0000000000000000000000000000000000081 -:10BFC0000000000000000000000000000000000071 -:10BFD0000000000000000000000000000000000061 -:10BFE0000000000000000000000000000000000051 -:10BFF0000000000000000000000000000000000041 -:10C000000000000000000000000000000000000030 -:10C010000000000000000000000000000000000020 -:10C020000000000000000000000000000000000010 -:10C030000000000000000000000000000000000000 -:10C0400000000000000000000000000000000000F0 -:10C0500000000000000000000000000000000000E0 -:10C0600000000000000000000000000000000000D0 -:10C0700000000000000000000000000000000000C0 -:10C0800000000000000000000000000000000000B0 -:10C0900000000000000000000000000000000000A0 -:10C0A0000000000000000000000000000000000090 -:10C0B0000000000000000000000000000000000080 -:10C0C0000000000000000000000000000000000070 -:10C0D0000000000000000000000000000000000060 -:10C0E0000000000000000000000000000000000050 -:10C0F0000000000000000000000000000000000040 -:10C10000000000000000000000000000000000002F -:10C11000000000000000000000000000000000001F -:10C12000000000000000000000000000000000000F -:10C1300000000000000000000000000000000000FF -:10C1400000000000000000000000000000000000EF -:10C1500000000000000000000000000000000000DF -:10C1600000000000000000000000000000000000CF -:10C1700000000000000000000000000000000000BF -:10C1800000000000000000000000000000000000AF -:10C19000000000000000000000000000000000009F -:10C1A000000000000000000000000000000000008F -:10C1B000000000000000000000000000000000007F -:10C1C000000000000000000000000000000000006F -:10C1D000000000000000000000000000000000005F -:10C1E000000000000000000000000000000000004F -:10C1F000000000000000000000000000000000003F -:10C20000000000000000000000000000000000002E -:10C21000000000000000000000000000000000001E -:10C22000000000000000000000000000000000000E -:10C2300000000000000000000000000000000000FE -:10C2400000000000000000000000000000000000EE -:10C2500000000000000000000000000000000000DE -:10C2600000000000000000000000000000000000CE -:10C2700000000000000000000000000000000000BE -:10C2800000000000000000000000000000000000AE -:10C29000000000000000000000000000000000009E -:10C2A000000000000000000000000000000000008E -:10C2B000000000000000000000000000000000007E -:10C2C000000000000000000000000000000000006E -:10C2D000000000000000000000000000000000005E -:10C2E000000000000000000000000000000000004E -:10C2F000000000000000000000000000000000003E -:10C30000000000000000000000000000000000002D -:10C31000000000000000000000000000000000001D -:10C32000000000000000000000000000000000000D -:10C3300000000000000000000000000000000000FD -:10C3400000000000000000000000000000000000ED -:10C3500000000000000000000000000000000000DD -:10C3600000000000000000000000000000000000CD -:10C3700000000000000000000000000000000000BD -:10C3800000000000000000000000000000000000AD -:10C39000000000000000000000000000000000009D -:10C3A000000000000000000000000000000000008D -:10C3B000000000000000000000000000000000007D -:10C3C000000000000000000000000000000000006D -:10C3D000000000000000000000000000000000005D -:10C3E000000000000000000000000000000000004D -:10C3F000000000000000000000000000000000003D -:10C40000000000000000000000000000000000002C -:10C41000000000000000000000000000000000001C -:10C42000000000000000000000000000000000000C -:10C4300000000000000000000000000000000000FC -:10C4400000000000000000000000000000000000EC -:10C4500000000000000000000000000000000000DC -:10C4600000000000000000000000000000000000CC -:10C4700000000000000000000000000000000000BC -:10C4800000000000000000000000000000000000AC -:10C49000000000000000000000000000000000009C -:10C4A000000000000000000000000000000000008C -:10C4B000000000000000000000000000000000007C -:10C4C000000000000000000000000000000000006C -:10C4D000000000000000000000000000000000005C -:10C4E000000000000000000000000000000000004C -:10C4F000000000000000000000000000000000003C -:10C50000000000000000000000000000000000002B -:10C51000000000000000000000000000000000001B -:10C52000000000000000000000000000000000000B -:10C5300000000000000000000000000000000000FB -:10C5400000000000000000000000000000000000EB -:10C5500000000000000000000000000000000000DB -:10C5600000000000000000000000000000000000CB -:10C5700000000000000000000000000000000000BB -:10C5800000000000000000000000000000000000AB -:10C59000000000000000000000000000000000009B -:10C5A000000000000000000000000000000000008B -:10C5B000000000000000000000000000000000007B -:10C5C000000000000000000000000000000000006B -:10C5D000000000000000000000000000000000005B -:10C5E000000000000000000000000000000000004B -:10C5F000000000000000000000000000000000003B -:10C60000000000000000000000000000000000002A -:10C61000000000000000000000000000000000001A -:10C62000000000000000000000000000000000000A -:10C6300000000000000000000000000000000000FA -:10C6400000000000000000000000000000000000EA -:10C6500000000000000000000000000000000000DA -:10C6600000000000000000000000000000000000CA -:10C6700000000000000000000000000000000000BA -:10C6800000000000000000000000000000000000AA -:10C69000000000000000000000000000000000009A -:10C6A000000000000000000000000000000000008A -:10C6B000000000000000000000000000000000007A -:10C6C000000000000000000000000000000000006A -:10C6D000000000000000000000000000000000005A -:10C6E000000000000000000000000000000000004A -:10C6F000000000000000000000000000000000003A -:10C700000000000000000000000000000000000029 -:10C710000000000000000000000000000000000019 -:10C720000000000000000000000000000000000009 -:10C7300000000000000000000000000000000000F9 -:10C7400000000000000000000000000000000000E9 -:10C7500000000000000000000000000000000000D9 -:10C7600000000000000000000000000000000000C9 -:10C7700000000000000000000000000000000000B9 -:10C7800000000000000000000000000000000000A9 -:10C790000000000000000000000000000000000099 -:10C7A0000000000000000000000000000000000089 -:10C7B0000000000000000000000000000000000079 -:10C7C0000000000000000000000000000000000069 -:10C7D0000000000000000000000000000000000059 -:10C7E0000000000000000000000000000000000049 -:10C7F0000000000000000000000000000000000039 -:10C800000000000000000000000000000000000028 -:10C810000000000000000000000000000000000018 -:10C820000000000000000000000000000000000008 -:10C8300000000000000000000000000000000000F8 -:10C8400000000000000000000000000000000000E8 -:10C8500000000000000000000000000000000000D8 -:10C8600000000000000000000000000000000000C8 -:10C8700000000000000000000000000000000000B8 -:10C8800000000000000000000000000000000000A8 -:10C890000000000000000000000000000000000098 -:10C8A0000000000000000000000000000000000088 -:10C8B0000000000000000000000000000000000078 -:10C8C0000000000000000000000000000000000068 -:10C8D0000000000000000000000000000000000058 -:10C8E0000000000000000000000000000000000048 -:10C8F0000000000000000000000000000000000038 -:10C900000000000000000000000000000000000027 -:10C910000000000000000000000000000000000017 -:10C920000000000000000000000000000000000007 -:10C9300000000000000000000000000000000000F7 -:10C9400000000000000000000000000000000000E7 -:10C9500000000000000000000000000000000000D7 -:10C9600000000000000000000000000000000000C7 -:10C9700000000000000000000000000000000000B7 -:10C9800000000000000000000000000000000000A7 -:10C990000000000000000000000000000000000097 -:10C9A0000000000000000000000000000000000087 -:10C9B0000000000000000000000000000000000077 -:10C9C0000000000000000000000000000000000067 -:10C9D0000000000000000000000000000000000057 -:10C9E0000000000000000000000000000000000047 -:10C9F0000000000000000000000000000000000037 -:10CA00000000000000000000000000000000000026 -:10CA10000000000000000000000000000000000016 -:10CA20000000000000000000000000000000000006 -:10CA300000000000000000000000000000000000F6 -:10CA400000000000000000000000000000000000E6 -:10CA500000000000000000000000000000000000D6 -:10CA600000000000000000000000000000000000C6 -:10CA700000000000000000000000000000000000B6 -:10CA800000000000000000000000000000000000A6 -:10CA90000000000000000000000000000000000096 -:10CAA0000000000000000000000000000000000086 -:10CAB0000000000000000000000000000000000076 -:10CAC0000000000000000000000000000000000066 -:10CAD0000000000000000000000000000000000056 -:10CAE0000000000000000000000000000000000046 -:10CAF0000000000000000000000000000000000036 -:10CB00000000000000000000000000000000000025 -:10CB10000000000000000000000000000000000015 -:10CB20000000000000000000000000000000000005 -:10CB300000000000000000000000000000000000F5 -:10CB400000000000000000000000000000000000E5 -:10CB500000000000000000000000000000000000D5 -:10CB600000000000000000000000000000000000C5 -:10CB700000000000000000000000000000000000B5 -:10CB800000000000000000000000000000000000A5 -:10CB90000000000000000000000000000000000095 -:10CBA0000000000000000000000000000000000085 -:10CBB0000000000000000000000000000000000075 -:10CBC0000000000000000000000000000000000065 -:10CBD0000000000000000000000000000000000055 -:10CBE0000000000000000000000000000000000045 -:10CBF0000000000000000000000000000000000035 -:10CC00000000000000000000000000000000000024 -:10CC10000000000000000000000000000000000014 -:10CC20000000000000000000000000000000000004 -:10CC300000000000000000000000000000000000F4 -:10CC400000000000000000000000000000000000E4 -:10CC500000000000000000000000000000000000D4 -:10CC600000000000000000000000000000000000C4 -:10CC700000000000000000000000000000000000B4 -:10CC800000000000000000000000000000000000A4 -:10CC90000000000000000000000000000000000094 -:10CCA0000000000000000000000000000000000084 -:10CCB0000000000000000000000000000000000074 -:10CCC0000000000000000000000000000000000064 -:10CCD0000000000000000000000000000000000054 -:10CCE0000000000000000000000000000000000044 -:10CCF0000000000000000000000000000000000034 -:10CD00000000000000000000000000000000000023 -:10CD10000000000000000000000000000000000013 -:10CD20000000000000000000000000000000000003 -:10CD300000000000000000000000000000000000F3 -:10CD400000000000000000000000000000000000E3 -:10CD500000000000000000000000000000000000D3 -:10CD600000000000000000000000000000000000C3 -:10CD700000000000000000000000000000000000B3 -:10CD800000000000000000000000000000000000A3 -:10CD90000000000000000000000000000000000093 -:10CDA0000000000000000000000000000000000083 -:10CDB0000000000000000000000000000000000073 -:10CDC0000000000000000000000000000000000063 -:10CDD0000000000000000000000000000000000053 -:10CDE0000000000000000000000000000000000043 -:10CDF0000000000000000000000000000000000033 -:10CE00000000000000000000000000000000000022 -:10CE10000000000000000000000000000000000012 -:10CE20000000000000000000000000000000000002 -:10CE300000000000000000000000000000000000F2 -:10CE400000000000000000000000000000000000E2 -:10CE500000000000000000000000000000000000D2 -:10CE600000000000000000000000000000000000C2 -:10CE700000000000000000000000000000000000B2 -:10CE800000000000000000000000000000000000A2 -:10CE90000000000000000000000000000000000092 -:10CEA0000000000000000000000000000000000082 -:10CEB0000000000000000000000000000000000072 -:10CEC0000000000000000000000000000000000062 -:10CED0000000000000000000000000000000000052 -:10CEE0000000000000000000000000000000000042 -:10CEF0000000000000000000000000000000000032 -:10CF00000000000000000000000000000000000021 -:10CF10000000000000000000000000000000000011 -:10CF20000000000000000000000000000000000001 -:10CF300000000000000000000000000000000000F1 -:10CF400000000000000000000000000000000000E1 -:10CF500000000000000000000000000000000000D1 -:10CF600000000000000000000000000000000000C1 -:10CF700000000000000000000000000000000000B1 -:10CF800000000000000000000000000000000000A1 -:10CF90000000000000000000000000000000000091 -:10CFA0000000000000000000000000000000000081 -:10CFB0000000000000000000000000000000000071 -:10CFC0000000000000000000000000000000000061 -:10CFD0000000000000000000000000000000000051 -:10CFE0000000000000000000000000000000000041 -:10CFF0000000000000000000000000000000000031 -:10D000000000000000000000000000000000000020 -:10D010000000000000000000000000000000000010 -:10D020000000000000000000000000000000000000 -:10D0300000000000000000000000000000000000F0 -:10D0400000000000000000000000000000000000E0 -:10D0500000000000000000000000000000000000D0 -:10D0600000000000000000000000000000000000C0 -:10D0700000000000000000000000000000000000B0 -:10D0800000000000000000000000000000000000A0 -:10D090000000000000000000000000000000000090 -:10D0A0000000000000000000000000000000000080 -:10D0B0000000000000000000000000000000000070 -:10D0C0000000000000000000000000000000000060 -:10D0D0000000000000000000000000000000000050 -:10D0E0000000000000000000000000000000000040 -:10D0F0000000000000000000000000000000000030 -:10D10000000000000000000000000000000000001F -:10D11000000000000000000000000000000000000F -:10D1200000000000000000000000000000000000FF -:10D1300000000000000000000000000000000000EF -:10D1400000000000000000000000000000000000DF -:10D1500000000000000000000000000000000000CF -:10D1600000000000000000000000000000000000BF -:10D1700000000000000000000000000000000000AF -:10D18000000000000000000000000000000000009F -:10D19000000000000000000000000000000000008F -:10D1A000000000000000000000000000000000007F -:10D1B000000000000000000000000000000000006F -:10D1C000000000000000000000000000000000005F -:10D1D000000000000000000000000000000000004F -:10D1E000000000000000000000000000000000003F -:10D1F000000000000000000000000000000000002F -:10D20000000000000000000000000000000000001E -:10D21000000000000000000000000000000000000E -:10D2200000000000000000000000000000000000FE -:10D2300000000000000000000000000000000000EE -:10D2400000000000000000000000000000000000DE -:10D2500000000000000000000000000000000000CE -:10D2600000000000000000000000000000000000BE -:10D2700000000000000000000000000000000000AE -:10D28000000000000000000000000000000000009E -:10D29000000000000000000000000000000000008E -:10D2A000000000000000000000000000000000007E -:10D2B000000000000000000000000000000000006E -:10D2C000000000000000000000000000000000005E -:10D2D000000000000000000000000000000000004E -:10D2E000000000000000000000000000000000003E -:10D2F000000000000000000000000000000000002E -:10D30000000000000000000000000000000000001D -:10D31000000000000000000000000000000000000D -:10D3200000000000000000000000000000000000FD -:10D3300000000000000000000000000000000000ED -:10D3400000000000000000000000000000000000DD -:10D3500000000000000000000000000000000000CD -:10D3600000000000000000000000000000000000BD -:10D3700000000000000000000000000000000000AD -:10D38000000000000000000000000000000000009D -:10D39000000000000000000000000000000000008D -:10D3A000000000000000000000000000000000007D -:10D3B000000000000000000000000000000000006D -:10D3C000000000000000000000000000000000005D -:10D3D000000000000000000000000000000000004D -:10D3E000000000000000000000000000000000003D -:10D3F000000000000000000000000000000000002D -:10D40000000000000000000000000000000000001C -:10D41000000000000000000000000000000000000C -:10D4200000000000000000000000000000000000FC -:10D4300000000000000000000000000000000000EC -:10D4400000000000000000000000000000000000DC -:10D4500000000000000000000000000000000000CC -:10D4600000000000000000000000000000000000BC -:10D4700000000000000000000000000000000000AC -:10D48000000000000000000000000000000000009C -:10D49000000000000000000000000000000000008C -:10D4A000000000000000000000000000000000007C -:10D4B000000000000000000000000000000000006C -:10D4C000000000000000000000000000000000005C -:10D4D000000000000000000000000000000000004C -:10D4E000000000000000000000000000000000003C -:10D4F000000000000000000000000000000000002C -:10D50000000000000000000000000000000000001B -:10D51000000000000000000000000000000000000B -:10D5200000000000000000000000000000000000FB -:10D5300000000000000000000000000000000000EB -:10D5400000000000000000000000000000000000DB -:10D5500000000000000000000000000000000000CB -:10D5600000000000000000000000000000000000BB -:10D5700000000000000000000000000000000000AB -:10D58000000000000000000000000000000000009B -:10D59000000000000000000000000000000000008B -:10D5A000000000000000000000000000000000007B -:10D5B000000000000000000000000000000000006B -:10D5C000000000000000000000000000000000005B -:10D5D000000000000000000000000000000000004B -:10D5E000000000000000000000000000000000003B -:10D5F000000000000000000000000000000000002B -:10D60000000000000000000000000000000000001A -:10D61000000000000000000000000000000000000A -:10D6200000000000000000000000000000000000FA -:10D6300000000000000000000000000000000000EA -:10D6400000000000000000000000000000000000DA -:10D6500000000000000000000000000000000000CA -:10D6600000000000000000000000000000000000BA -:10D6700000000000000000000000000000000000AA -:10D68000000000000000000000000000000000009A -:10D69000000000000000000000000000000000008A -:10D6A000000000000000000000000000000000007A -:10D6B000000000000000000000000000000000006A -:10D6C000000000000000000000000000000000005A -:10D6D000000000000000000000000000000000004A -:10D6E000000000000000000000000000000000003A -:10D6F000000000000000000000000000000000002A -:10D700000000000000000000000000000000000019 -:10D710000000000000000000000000000000000009 -:10D7200000000000000000000000000000000000F9 -:10D7300000000000000000000000000000000000E9 -:10D7400000000000000000000000000000000000D9 -:10D7500000000000000000000000000000000000C9 -:10D7600000000000000000000000000000000000B9 -:10D7700000000000000000000000000000000000A9 -:10D780000000000000000000000000000000000099 -:10D790000000000000000000000000000000000089 -:10D7A0000000000000000000000000000000000079 -:10D7B0000000000000000000000000000000000069 -:10D7C0000000000000000000000000000000000059 -:10D7D0000000000000000000000000000000000049 -:10D7E0000000000000000000000000000000000039 -:10D7F0000000000000000000000000000000000029 -:10D800000000000000000000000000000000000018 -:10D810000000000000000000000000000000000008 -:10D8200000000000000000000000000000000000F8 -:10D8300000000000000000000000000000000000E8 -:10D8400000000000000000000000000000000000D8 -:10D8500000000000000000000000000000000000C8 -:10D8600000000000000000000000000000000000B8 -:10D8700000000000000000000000000000000000A8 -:10D880000000000000000000000000000000000098 -:10D890000000000000000000000000000000000088 -:10D8A0000000000000000000000000000000000078 -:10D8B0000000000000000000000000000000000068 -:10D8C0000000000000000000000000000000000058 -:10D8D0000000000000000000000000000000000048 -:10D8E0000000000000000000000000000000000038 -:10D8F0000000000000000000000000000000000028 -:10D900000000000000000000000000000000000017 -:10D910000000000000000000000000000000000007 -:10D9200000000000000000000000000000000000F7 -:10D9300000000000000000000000000000000000E7 -:10D9400000000000000000000000000000000000D7 -:10D9500000000000000000000000000000000000C7 -:10D9600000000000000000000000000000000000B7 -:10D9700000000000000000000000000000000000A7 -:10D980000000000000000000000000000000000097 -:10D990000000000000000000000000000000000087 -:10D9A0000000000000000000000000000000000077 -:10D9B0000000000000000000000000000000000067 -:10D9C0000000000000000000000000000000000057 -:10D9D0000000000000000000000000000000000047 -:10D9E0000000000000000000000000000000000037 -:10D9F0000000000000000000000000000000000027 -:10DA00000000000000000000000000000000000016 -:10DA10000000000000000000000000000000000006 -:10DA200000000000000000000000000000000000F6 -:10DA300000000000000000000000000000000000E6 -:10DA400000000000000000000000000000000000D6 -:10DA500000000000000000000000000000000000C6 -:10DA600000000000000000000000000000000000B6 -:10DA700000000000000000000000000000000000A6 -:10DA80000000000000000000000000000000000096 -:10DA90000000000000000000000000000000000086 -:10DAA0000000000000000000000000000000000076 -:10DAB0000000000000000000000000000000000066 -:10DAC0000000000000000000000000000000000056 -:10DAD0000000000000000000000000000000000046 -:10DAE0000000000000000000000000000000000036 -:10DAF0000000000000000000000000000000000026 -:10DB00000000000000000000000000000000000015 -:10DB10000000000000000000000000000000000005 -:10DB200000000000000000000000000000000000F5 -:10DB300000000000000000000000000000000000E5 -:10DB400000000000000000000000000000000000D5 -:10DB500000000000000000000000000000000000C5 -:10DB600000000000000000000000000000000000B5 -:10DB700000000000000000000000000000000000A5 -:10DB80000000000000000000000000000000000095 -:10DB90000000000000000000000000000000000085 -:10DBA0000000000000000000000000000000000075 -:10DBB0000000000000000000000000000000000065 -:10DBC0000000000000000000000000000000000055 -:10DBD0000000000000000000000000000000000045 -:10DBE0000000000000000000000000000000000035 -:10DBF0000000000000000000000000000000000025 -:10DC00000000000000000000000000000000000014 -:10DC10000000000000000000000000000000000004 -:10DC200000000000000000000000000000000000F4 -:10DC300000000000000000000000000000000000E4 -:10DC400000000000000000000000000000000000D4 -:10DC500000000000000000000000000000000000C4 -:10DC600000000000000000000000000000000000B4 -:10DC700000000000000000000000000000000000A4 -:10DC80000000000000000000000000000000000094 -:10DC90000000000000000000000000000000000084 -:10DCA0000000000000000000000000000000000074 -:10DCB0000000000000000000000000000000000064 -:10DCC0000000000000000000000000000000000054 -:10DCD0000000000000000000000000000000000044 -:10DCE0000000000000000000000000000000000034 -:10DCF0000000000000000000000000000000000024 -:10DD00000000000000000000000000000000000013 -:10DD10000000000000000000000000000000000003 -:10DD200000000000000000000000000000000000F3 -:10DD300000000000000000000000000000000000E3 -:10DD400000000000000000000000000000000000D3 -:10DD500000000000000000000000000000000000C3 -:10DD600000000000000000000000000000000000B3 -:10DD700000000000000000000000000000000000A3 -:10DD80000000000000000000000000000000000093 -:10DD90000000000000000000000000000000000083 -:10DDA0000000000000000000000000000000000073 -:10DDB0000000000000000000000000000000000063 -:10DDC0000000000000000000000000000000000053 -:10DDD0000000000000000000000000000000000043 -:10DDE0000000000000000000000000000000000033 -:10DDF0000000000000000000000000000000000023 -:10DE00000000000000000000000000000000000012 -:10DE10000000000000000000000000000000000002 -:10DE200000000000000000000000000000000000F2 -:10DE300000000000000000000000000000000000E2 -:10DE400000000000000000000000000000000000D2 -:10DE500000000000000000000000000000000000C2 -:10DE600000000000000000000000000000000000B2 -:10DE700000000000000000000000000000000000A2 -:10DE80000000000000000000000000000000000092 -:10DE90000000000000000000000000000000000082 -:10DEA0000000000000000000000000000000000072 -:10DEB0000000000000000000000000000000000062 -:10DEC0000000000000000000000000000000000052 -:10DED0000000000000000000000000000000000042 -:10DEE0000000000000000000000000000000000032 -:10DEF0000000000000000000000000000000000022 -:10DF00000000000000000000000000000000000011 -:10DF10000000000000000000000000000000000001 -:10DF200000000000000000000000000000000000F1 -:10DF300000000000000000000000000000000000E1 -:10DF400000000000000000000000000000000000D1 -:10DF500000000000000000000000000000000000C1 -:10DF600000000000000000000000000000000000B1 -:10DF700000000000000000000000000000000000A1 -:10DF80000000000000000000000000000000000091 -:10DF90000000000000000000000000000000000081 -:10DFA0000000000000000000000000000000000071 -:10DFB0000000000000000000000000000000000061 -:10DFC0000000000000000000000000000000000051 -:10DFD0000000000000000000000000000000000041 -:10DFE0000000000000000000000000000000000031 -:10DFF0000000000000000000000000000000000021 -:10E000000000000000000000000000000000000010 -:10E010000000000000000000000000000000000000 -:10E0200000000000000000000000000000000000F0 -:10E0300000000000000000000000000000000000E0 -:10E0400000000000000000000000000000000000D0 -:10E0500000000000000000000000000000000000C0 -:10E0600000000000000000000000000000000000B0 -:10E0700000000000000000000000000000000000A0 -:10E080000000000000000000000000000000000090 -:10E090000000000000000000000000000000000080 -:10E0A0000000000000000000000000000000000070 -:10E0B0000000000000000000000000000000000060 -:10E0C0000000000000000000000000000000000050 -:10E0D0000000000000000000000000000000000040 -:10E0E0000000000000000000000000000000000030 -:10E0F0000000000000000000000000000000000020 -:10E10000000000000000000000000000000000000F -:10E1100000000000000000000000000000000000FF -:10E1200000000000000000000000000000000000EF -:10E1300000000000000000000000000000000000DF -:10E1400000000000000000000000000000000000CF -:10E1500000000000000000000000000000000000BF -:10E1600000000000000000000000000000000000AF -:10E17000000000000000000000000000000000009F -:10E18000000000000000000000000000000000008F -:10E19000000000000000000000000000000000007F -:10E1A000000000000000000000000000000000006F -:10E1B000000000000000000000000000000000005F -:10E1C000000000000000000000000000000000004F -:10E1D000000000000000000000000000000000003F -:10E1E000000000000000000000000000000000002F -:10E1F000000000000000000000000000000000001F -:10E20000000000000000000000000000000000000E -:10E2100000000000000000000000000000000000FE -:10E2200000000000000000000000000000000000EE -:10E2300000000000000000000000000000000000DE -:10E2400000000000000000000000000000000000CE -:10E2500000000000000000000000000000000000BE -:10E2600000000000000000000000000000000000AE -:10E27000000000000000000000000000000000009E -:10E28000000000000000000000000000000000008E -:10E29000000000000000000000000000000000007E -:10E2A000000000000000000000000000000000006E -:10E2B000000000000000000000000000000000005E -:10E2C000000000000000000000000000000000004E -:10E2D000000000000000000000000000000000003E -:10E2E000000000000000000000000000000000002E -:10E2F000000000000000000000000000000000001E -:10E30000000000000000000000000000000000000D -:10E3100000000000000000000000000000000000FD -:10E3200000000000000000000000000000000000ED -:10E3300000000000000000000000000000000000DD -:10E3400000000000000000000000000000000000CD -:10E3500000000000000000000000000000000000BD -:10E3600000000000000000000000000000000000AD -:10E37000000000000000000000000000000000009D -:10E38000000000000000000000000000000000008D -:10E39000000000000000000000000000000000007D -:10E3A000000000000000000000000000000000006D -:10E3B000000000000000000000000000000000005D -:10E3C000000000000000000000000000000000004D -:10E3D000000000000000000000000000000000003D -:10E3E000000000000000000000000000000000002D -:10E3F000000000000000000000000000000000001D -:10E40000000000000000000000000000000000000C -:10E4100000000000000000000000000000000000FC -:10E4200000000000000000000000000000000000EC -:10E4300000000000000000000000000000000000DC -:10E4400000000000000000000000000000000000CC -:10E4500000000000000000000000000000000000BC -:10E4600000000000000000000000000000000000AC -:10E47000000000000000000000000000000000009C -:10E48000000000000000000000000000000000008C -:10E49000000000000000000000000000000000007C -:10E4A000000000000000000000000000000000006C -:10E4B000000000000000000000000000000000005C -:10E4C000000000000000000000000000000000004C -:10E4D000000000000000000000000000000000003C -:10E4E000000000000000000000000000000000002C -:10E4F000000000000000000000000000000000001C -:10E50000000000000000000000000000000000000B -:10E5100000000000000000000000000000000000FB -:10E5200000000000000000000000000000000000EB -:10E5300000000000000000000000000000000000DB -:10E5400000000000000000000000000000000000CB -:10E5500000000000000000000000000000000000BB -:10E5600000000000000000000000000000000000AB -:10E57000000000000000000000000000000000009B -:10E58000000000000000000000000000000000008B -:10E59000000000000000000000000000000000007B -:10E5A000000000000000000000000000000000006B -:10E5B000000000000000000000000000000000005B -:10E5C000000000000000000000000000000000004B -:10E5D000000000000000000000000000000000003B -:10E5E000000000000000000000000000000000002B -:10E5F000000000000000000000000000000000001B -:10E60000000000000000000000000000000000000A -:10E6100000000000000000000000000000000000FA -:10E6200000000000000000000000000000000000EA -:10E6300000000000000000000000000000000000DA -:10E6400000000000000000000000000000000000CA -:10E6500000000000000000000000000000000000BA -:10E6600000000000000000000000000000000000AA -:10E67000000000000000000000000000000000009A -:10E68000000000000000000000000000000000008A -:10E69000000000000000000000000000000000007A -:10E6A000000000000000000000000000000000006A -:10E6B000000000000000000000000000000000005A -:10E6C000000000000000000000000000000000004A -:10E6D000000000000000000000000000000000003A -:10E6E000000000000000000000000000000000002A -:10E6F000000000000000000000000000000000001A -:10E700000000000000000000000000000000000009 -:10E7100000000000000000000000000000000000F9 -:10E7200000000000000000000000000000000000E9 -:10E7300000000000000000000000000000000000D9 -:10E7400000000000000000000000000000000000C9 -:10E7500000000000000000000000000000000000B9 -:10E7600000000000000000000000000000000000A9 -:10E770000000000000000000000000000000000099 -:10E780000000000000000000000000000000000089 -:10E790000000000000000000000000000000000079 -:10E7A0000000000000000000000000000000000069 -:10E7B0000000000000000000000000000000000059 -:10E7C0000000000000000000000000000000000049 -:10E7D0000000000000000000000000000000000039 -:10E7E0000000000000000000000000000000000029 -:10E7F0000000000000000000000000000000000019 -:10E800000000000000000000000000000000000008 -:10E8100000000000000000000000000000000000F8 -:10E8200000000000000000000000000000000000E8 -:10E8300000000000000000000000000000000000D8 -:10E8400000000000000000000000000000000000C8 -:10E8500000000000000000000000000000000000B8 -:10E8600000000000000000000000000000000000A8 -:10E870000000000000000000000000000000000098 -:10E880000000000000000000000000000000000088 -:10E890000000000000000000000000000000000078 -:10E8A0000000000000000000000000000000000068 -:10E8B0000000000000000000000000000000000058 -:10E8C0000000000000000000000000000000000048 -:10E8D0000000000000000000000000000000000038 -:10E8E0000000000000000000000000000000000028 -:10E8F0000000000000000000000000000000000018 -:10E900000000000000000000000000000000000007 -:10E9100000000000000000000000000000000000F7 -:10E9200000000000000000000000000000000000E7 -:10E9300000000000000000000000000000000000D7 -:10E9400000000000000000000000000000000000C7 -:10E9500000000000000000000000000000000000B7 -:10E9600000000000000000000000000000000000A7 -:10E970000000000000000000000000000000000097 -:10E980000000000000000000000000000000000087 -:10E990000000000000000000000000000000000077 -:10E9A0000000000000000000000000000000000067 -:10E9B0000000000000000000000000000000000057 -:10E9C0000000000000000000000000000000000047 -:10E9D0000000000000000000000000000000000037 -:10E9E0000000000000000000000000000000000027 -:10E9F0000000000000000000000000000000000017 -:10EA00000000000000000000000000000000000006 -:10EA100000000000000000000000000000000000F6 -:10EA200000000000000000000000000000000000E6 -:10EA300000000000000000000000000000000000D6 -:10EA400000000000000000000000000000000000C6 -:10EA500000000000000000000000000000000000B6 -:10EA600000000000000000000000000000000000A6 -:10EA70000000000000000000000000000000000096 -:10EA80000000000000000000000000000000000086 -:10EA90000000000000000000000000000000000076 -:10EAA0000000000000000000000000000000000066 -:10EAB0000000000000000000000000000000000056 -:10EAC0000000000000000000000000000000000046 -:10EAD0000000000000000000000000000000000036 -:10EAE0000000000000000000000000000000000026 -:10EAF0000000000000000000000000000000000016 -:10EB00000000000000000000000000000000000005 -:10EB100000000000000000000000000000000000F5 -:10EB200000000000000000000000000000000000E5 -:10EB300000000000000000000000000000000000D5 -:10EB400000000000000000000000000000000000C5 -:10EB500000000000000000000000000000000000B5 -:10EB600000000000000000000000000000000000A5 -:10EB70000000000000000000000000000000000095 -:10EB80000000000000000000000000000000000085 -:10EB90000000000000000000000000000000000075 -:10EBA0000000000000000000000000000000000065 -:10EBB0000000000000000000000000000000000055 -:10EBC0000000000000000000000000000000000045 -:10EBD0000000000000000000000000000000000035 -:10EBE0000000000000000000000000000000000025 -:10EBF0000000000000000000000000000000000015 -:10EC00000000000000000000000000000000000004 -:10EC100000000000000000000000000000000000F4 -:10EC200000000000000000000000000000000000E4 -:10EC300000000000000000000000000000000000D4 -:10EC400000000000000000000000000000000000C4 -:10EC500000000000000000000000000000000000B4 -:10EC600000000000000000000000000000000000A4 -:10EC70000000000000000000000000000000000094 -:10EC80000000000000000000000000000000000084 -:10EC90000000000000000000000000000000000074 -:10ECA0000000000000000000000000000000000064 -:10ECB0000000000000000000000000000000000054 -:10ECC0000000000000000000000000000000000044 -:10ECD0000000000000000000000000000000000034 -:10ECE0000000000000000000000000000000000024 -:10ECF0000000000000000000000000000000000014 -:10ED00000000000000000000000000000000000003 -:10ED100000000000000000000000000000000000F3 -:10ED200000000000000000000000000000000000E3 -:10ED300000000000000000000000000000000000D3 -:10ED400000000000000000000000000000000000C3 -:10ED500000000000000000000000000000000000B3 -:10ED600000000000000000000000000000000000A3 -:10ED70000000000000000000000000000000000093 -:10ED80000000000000000000000000000000000083 -:10ED90000000000000000000000000000000000073 -:10EDA0000000000000000000000000000000000063 -:10EDB0000000000000000000000000000000000053 -:10EDC0000000000000000000000000000000000043 -:10EDD0000000000000000000000000000000000033 -:10EDE0000000000000000000000000000000000023 -:10EDF0000000000000000000000000000000000013 -:10EE00000000000000000000000000000000000002 -:10EE100000000000000000000000000000000000F2 -:10EE200000000000000000000000000000000000E2 -:10EE300000000000000000000000000000000000D2 -:10EE400000000000000000000000000000000000C2 -:10EE500000000000000000000000000000000000B2 -:10EE600000000000000000000000000000000000A2 -:10EE70000000000000000000000000000000000092 -:10EE80000000000000000000000000000000000082 -:10EE90000000000000000000000000000000000072 -:10EEA0000000000000000000000000000000000062 -:10EEB0000000000000000000000000000000000052 -:10EEC0000000000000000000000000000000000042 -:10EED0000000000000000000000000000000000032 -:10EEE0000000000000000000000000000000000022 -:10EEF0000000000000000000000000000000000012 -:10EF00000000000000000000000000000000000001 -:10EF100000000000000000000000000000000000F1 -:10EF200000000000000000000000000000000000E1 -:10EF300000000000000000000000000000000000D1 -:10EF400000000000000000000000000000000000C1 -:10EF500000000000000000000000000000000000B1 -:10EF600000000000000000000000000000000000A1 -:10EF70000000000000000000000000000000000091 -:10EF80000000000000000000000000000000000081 -:10EF90000000000000000000000000000000000071 -:10EFA0000000000000000000000000000000000061 -:10EFB0000000000000000000000000000000000051 -:10EFC0000000000000000000000000000000000041 -:10EFD0000000000000000000000000000000000031 -:10EFE0000000000000000000000000000000000021 -:10EFF0000000000000000000000000000000000011 -:10F000000000000000000000000000000000000000 -:10F0100000000000000000000000000000000000F0 -:10F0200000000000000000000000000000000000E0 -:10F0300000000000000000000000000000000000D0 -:10F0400000000000000000000000000000000000C0 -:10F0500000000000000000000000000000000000B0 -:10F0600000000000000000000000000000000000A0 -:10F070000000000000000000000000000000000090 -:10F080000000000000000000000000000000000080 -:10F090000000000000000000000000000000000070 -:10F0A0000000000000000000000000000000000060 -:10F0B0000000000000000000000000000000000050 -:10F0C0000000000000000000000000000000000040 -:10F0D0000000000000000000000000000000000030 -:10F0E0000000000000000000000000000000000020 -:10F0F0000000000000000000000000000000000010 -:10F1000000000000000000000000000000000000FF -:10F1100000000000000000000000000000000000EF -:10F1200000000000000000000000000000000000DF -:10F1300000000000000000000000000000000000CF -:10F1400000000000000000000000000000000000BF -:10F1500000000000000000000000000000000000AF -:10F16000000000000000000000000000000000009F -:10F17000000000000000000000000000000000008F -:10F18000000000000000000000000000000000007F -:10F19000000000000000000000000000000000006F -:10F1A000000000000000000000000000000000005F -:10F1B000000000000000000000000000000000004F -:10F1C000000000000000000000000000000000003F -:10F1D000000000000000000000000000000000002F -:10F1E000000000000000000000000000000000001F -:10F1F000000000000000000000000000000000000F -:10F2000000000000000000000000000000000000FE -:10F2100000000000000000000000000000000000EE -:10F2200000000000000000000000000000000000DE -:10F2300000000000000000000000000000000000CE -:10F2400000000000000000000000000000000000BE -:10F2500000000000000000000000000000000000AE -:10F26000000000000000000000000000000000009E -:10F27000000000000000000000000000000000008E -:10F28000000000000000000000000000000000007E -:10F29000000000000000000000000000000000006E -:10F2A000000000000000000000000000000000005E -:10F2B000000000000000000000000000000000004E -:10F2C000000000000000000000000000000000003E -:10F2D000000000000000000000000000000000002E -:10F2E000000000000000000000000000000000001E -:10F2F000000000000000000000000000000000000E -:10F3000000000000000000000000000000000000FD -:10F3100000000000000000000000000000000000ED -:10F3200000000000000000000000000000000000DD -:10F3300000000000000000000000000000000000CD -:10F3400000000000000000000000000000000000BD -:10F3500000000000000000000000000000000000AD -:10F36000000000000000000000000000000000009D -:10F37000000000000000000000000000000000008D -:10F38000000000000000000000000000000000007D -:10F39000000000000000000000000000000000006D -:10F3A000000000000000000000000000000000005D -:10F3B000000000000000000000000000000000004D -:10F3C000000000000000000000000000000000003D -:10F3D000000000000000000000000000000000002D -:10F3E000000000000000000000000000000000001D -:10F3F000000000000000000000000000000000000D -:10F4000000000000000000000000000000000000FC -:10F4100000000000000000000000000000000000EC -:10F4200000000000000000000000000000000000DC -:10F4300000000000000000000000000000000000CC -:10F4400000000000000000000000000000000000BC -:10F4500000000000000000000000000000000000AC -:10F46000000000000000000000000000000000009C -:10F47000000000000000000000000000000000008C -:10F48000000000000000000000000000000000007C -:10F49000000000000000000000000000000000006C -:10F4A000000000000000000000000000000000005C -:10F4B000000000000000000000000000000000004C -:10F4C000000000000000000000000000000000003C -:10F4D000000000000000000000000000000000002C -:10F4E000000000000000000000000000000000001C -:10F4F000000000000000000000000000000000000C -:10F5000000000000000000000000000000000000FB -:10F5100000000000000000000000000000000000EB -:10F5200000000000000000000000000000000000DB -:10F5300000000000000000000000000000000000CB -:10F5400000000000000000000000000000000000BB -:10F5500000000000000000000000000000000000AB -:10F56000000000000000000000000000000000009B -:10F57000000000000000000000000000000000008B -:10F58000000000000000000000000000000000007B -:10F59000000000000000000000000000000000006B -:10F5A000000000000000000000000000000000005B -:10F5B000000000000000000000000000000000004B -:10F5C000000000000000000000000000000000003B -:10F5D000000000000000000000000000000000002B -:10F5E000000000000000000000000000000000001B -:10F5F000000000000000000000000000000000000B -:10F6000000000000000000000000000000000000FA -:10F6100000000000000000000000000000000000EA -:10F6200000000000000000000000000000000000DA -:10F6300000000000000000000000000000000000CA -:10F6400000000000000000000000000000000000BA -:10F6500000000000000000000000000000000000AA -:10F66000000000000000000000000000000000009A -:10F67000000000000000000000000000000000008A -:10F68000000000000000000000000000000000007A -:10F69000000000000000000000000000000000006A -:10F6A000000000000000000000000000000000005A -:10F6B000000000000000000000000000000000004A -:10F6C000000000000000000000000000000000003A -:10F6D000000000000000000000000000000000002A -:10F6E000000000000000000000000000000000001A -:10F6F000000000000000000000000000000000000A -:10F7000000000000000000000000000000000000F9 -:10F7100000000000000000000000000000000000E9 -:10F7200000000000000000000000000000000000D9 -:10F7300000000000000000000000000000000000C9 -:10F7400000000000000000000000000000000000B9 -:10F7500000000000000000000000000000000000A9 -:10F760000000000000000000000000000000000099 -:10F770000000000000000000000000000000000089 -:10F780000000000000000000000000000000000079 -:10F790000000000000000000000000000000000069 -:10F7A0000000000000000000000000000000000059 -:10F7B0000000000000000000000000000000000049 -:10F7C0000000000000000000000000000000000039 -:10F7D0000000000000000000000000000000000029 -:10F7E0000000000000000000000000000000000019 -:10F7F0000000000000000000000000000000000009 -:10F8000000000000000000000000000000000000F8 -:10F8100000000000000000000000000000000000E8 -:10F8200000000000000000000000000000000000D8 -:10F8300000000000000000000000000000000000C8 -:10F8400000000000000000000000000000000000B8 -:10F8500000000000000000000000000000000000A8 -:10F860000000000000000000000000000000000098 -:10F870000000000000000000000000000000000088 -:10F880000000000000000000000000000000000078 -:10F890000000000000000000000000000000000068 -:10F8A0000000000000000000000000000000000058 -:10F8B0000000000000000000000000000000000048 -:10F8C0000000000000000000000000000000000038 -:10F8D0000000000000000000000000000000000028 -:10F8E0000000000000000000000000000000000018 -:10F8F0000000000000000000000000000000000008 -:10F9000000000000000000000000000000000000F7 -:10F9100000000000000000000000000000000000E7 -:10F9200000000000000000000000000000000000D7 -:10F9300000000000000000000000000000000000C7 -:10F9400000000000000000000000000000000000B7 -:10F9500000000000000000000000000000000000A7 -:10F960000000000000000000000000000000000097 -:10F970000000000000000000000000000000000087 -:10F980000000000000000000000000000000000077 -:10F990000000000000000000000000000000000067 -:10F9A0000000000000000000000000000000000057 -:10F9B0000000000000000000000000000000000047 -:10F9C0000000000000000000000000000000000037 -:10F9D0000000000000000000000000000000000027 -:10F9E0000000000000000000000000000000000017 -:10F9F0000000000000000000000000000000000007 -:10FA000000000000000000000000000000000000F6 -:10FA100000000000000000000000000000000000E6 -:10FA200000000000000000000000000000000000D6 -:10FA300000000000000000000000000000000000C6 -:10FA400000000000000000000000000000000000B6 -:10FA500000000000000000000000000000000000A6 -:10FA60000000000000000000000000000000000096 -:10FA70000000000000000000000000000000000086 -:10FA80000000000000000000000000000000000076 -:10FA90000000000000000000000000000000000066 -:10FAA0000000000000000000000000000000000056 -:10FAB0000000000000000000000000000000000046 -:10FAC0000000000000000000000000000000000036 -:10FAD0000000000000000000000000000000000026 -:10FAE0000000000000000000000000000000000016 -:10FAF0000000000000000000000000000000000006 -:10FB000000000000000000000000000000000000F5 -:10FB100000000000000000000000000000000000E5 -:10FB200000000000000000000000000000000000D5 -:10FB300000000000000000000000000000000000C5 -:10FB400000000000000000000000000000000000B5 -:10FB500000000000000000000000000000000000A5 -:10FB60000000000000000000000000000000000095 -:10FB70000000000000000000000000000000000085 -:10FB80000000000000000000000000000000000075 -:10FB90000000000000000000000000000000000065 -:10FBA0000000000000000000000000000000000055 -:10FBB0000000000000000000000000000000000045 -:10FBC0000000000000000000000000000000000035 -:10FBD0000000000000000000000000000000000025 -:10FBE0000000000000000000000000000000000015 -:10FBF0000000000000000000000000000000000005 -:10FC000000000000000000000000000000000000F4 -:10FC100000000000000000000000000000000000E4 -:10FC200000000000000000000000000000000000D4 -:10FC300000000000000000000000000000000000C4 -:10FC400000000000000000000000000000000000B4 -:10FC500000000000000000000000000000000000A4 -:10FC60000000000000000000000000000000000094 -:10FC70000000000000000000000000000000000084 -:10FC80000000000000000000000000000000000074 -:10FC90000000000000000000000000000000000064 -:10FCA0000000000000000000000000000000000054 -:10FCB0000000000000000000000000000000000044 -:10FCC0000000000000000000000000000000000034 -:10FCD0000000000000000000000000000000000024 -:10FCE0000000000000000000000000000000000014 -:10FCF0000000000000000000000000000000000004 -:10FD000000000000000000000000000000000000F3 -:10FD100000000000000000000000000000000000E3 -:10FD200000000000000000000000000000000000D3 -:10FD300000000000000000000000000000000000C3 -:10FD400000000000000000000000000000000000B3 -:10FD500000000000000000000000000000000000A3 -:10FD60000000000000000000000000000000000093 -:10FD70000000000000000000000000000000000083 -:10FD80000000000000000000000000000000000073 -:10FD90000000000000000000000000000000000063 -:10FDA0000000000000000000000000000000000053 -:10FDB0000000000000000000000000000000000043 -:10FDC0000000000000000000000000000000000033 -:10FDD0000000000000000000000000000000000023 -:10FDE0000000000000000000000000000000000013 -:10FDF0000000000000000000000000000000000003 -:10FE000000000000000000000000000000000000F2 -:10FE100000000000000000000000000000000000E2 -:10FE200000000000000000000000000000000000D2 -:10FE300000000000000000000000000000000000C2 -:10FE400000000000000000000000000000000000B2 -:10FE500000000000000000000000000000000000A2 -:10FE60000000000000000000000000000000000092 -:10FE70000000000000000000000000000000000082 -:10FE80000000000000000000000000000000000072 -:10FE90000000000000000000000000000000000062 -:10FEA0000000000000000000000000000000000052 -:10FEB0000000000000000000000000000000000042 -:10FEC0000000000000000000000000000000000032 -:10FED0000000000000000000000000000000000022 -:10FEE0000000000000000000000000000000000012 -:10FEF0000000000000000000000000000000000002 -:10FF000000000000000000000000000000000000F1 -:10FF100000000000000000000000000000000000E1 -:10FF200000000000000000000000000000000000D1 -:10FF300000000000000000000000000000000000C1 -:10FF400000000000000000000000000000000000B1 -:10FF500000000000000000000000000000000000A1 -:10FF60000000000000000000000000000000000091 -:10FF70000000000000000000000000000000000081 -:10FF80000000000000000000000000000000000071 -:10FF90000000000000000000000000000000000061 -:10FFA0000000000000000000000000000000000051 -:10FFB0000000000000000000000000000000000041 -:10FFC0000000000000000000000000000000000031 -:10FFD0000000000000000000000000000000000021 -:10FFE0000000000000000000000000000000000011 -:10FFF0000000000000000000000000000000000001 -:00000001FF diff --git a/Documentation/DebugMenu.md b/Documentation/DebugMenu.md index 1b40ad784..c18018a94 100644 --- a/Documentation/DebugMenu.md +++ b/Documentation/DebugMenu.md @@ -40,9 +40,9 @@ I.e.: **Additional scroll-able items appear in this order**: -### Date +### Timestamp -- This is a date of firmware compilation and it has the following format: `DD-MM-YY` (i.e., `01-07-23` means it has been built in July, 1st, 2023) +- This is a timestamp of firmware compilation and it has the following format: `YYYYMMDD HHMMSS` (i.e., `20230701 213456` means it has been built in July, 1st, 2023 at 9:34:56 pm) ### ID diff --git a/Documentation/DebuggingPD.md b/Documentation/DebuggingPD.md new file mode 100644 index 000000000..94050c830 --- /dev/null +++ b/Documentation/DebuggingPD.md @@ -0,0 +1,61 @@ +# Debugging PD + +When using many of these soldering irons, the recommended power source is to use a USB-PD power supply. + +Occasionally, issues are run into where the iron reboots or appears to not boot when connected to this supply. + +There are generally a few different reasons for this to occur, the first is of course a bug or incompatibility in the IronOS PD-stack / firmware, but there are also power adapters that either have issues or try to be _smart_ to the detriment of compatibility. + +It also helps to remember that driving a soldering iron is not like a normal load that these power supplies are designed for. Normally a laptop or phone will gently ramp the power draw up and down. Where as the soldering iron will rapidly go from 0 to full power, and then back to 0 again. This can cause issues with some power supplies tripping out. + +In general, a normal, boring 60-100W PD supply is recommended. Watch out for adapters with multiple ports that are used by marketing to advertise a higher number. It's somewhat common to see 65W adapters being pushed that have two ports, one of which is 45W and one that is 20W. These cannot support 65W output on one typically. + +Smarter chargers that try to implement every known protocol can come with quirks. Often slight shortcuts are taken in the PD implementation that can cause hard to debug issues. + + +## If the unit doesn't power up at all + +This can be the most frustrating one to diagnose. + +First, test the device powers up when powered by a USB-A -> USB-C cable. Or a DC power supply. This can rule out other issues that cause the device to appear off (bad flashing). + +### No power +If your device won't power up on any other supply type, look into if you can boot into the bootloader. This is usually done by holding down a button while connecting it to a computer and then checking if it's detected. + +If the device shows up to a computer, but doesn't operate when powered up normally, the two most likely causes are a bad flash/firmware OR a non-functioning display. + +Testing alternative firmware builds or trying to heat the unit (pressing the front button) can be ways to test this. + +### Powers up on other supplies + +If the device powers up on other supplies, but not on the USB-PD supply, it could be a problem with the USB-PD supply itself. Try using a different USB-PD supply to see if the issue persists. + +If the unit does not power on any PD supplies it could be damage to the PD PHY or the USB connector. USB-PD uses the CC pins on the connector, which are not used for normal data so a USB-A adapter for example doesn't use these at all. + +## If the unit powers up but keeps rebooting + +There are two causes of this: +1. If the reboot occurs when the unit starts to heat up, then it is the power supply being unable to supply the power requested. +2. The unit reboots frequently even without any buttons being pressed. + +If this is the issue that you are seeing, then the problem is that something during the PD initialisation is failing. + +The _best_ way to resolve this is to be able to capture the USB PD traffic. This is the only way to know what is **really** going on and why the two devices can't negotiate. + +To capture PD traffic requires a device that can capture this data. A logic analyser can be used on the CC pins, though note that the signalling voltage is < 3.3V so it will require a logic analyser that can handle this or buffering. + +Alternatively, a lot of the higher-end USB power meter units can capture the packets. It doesn't matter if it only shows these on screen or if it can save these out to a file (ideally a file though). + +**Without a traffic capture, all debugging is guessing** + +On firmwares 2.23+ there is a toggle in advanced settings to change the PD mode. This will adjust how the firmware negotiates with the PD supply slightly. This can enable/disable the PPS and EPR modes (dynamic voltage negotiation). + +PPS is known to be incorrectly implemented on some supplies, so turning off these features can improve compatibility. + +If the device is _sometimes_ stable, you can on Pinecil devices boot while holding the front button to enter the PD debug menu. This will show what voltages & power levels are being advertised by the device. This can be used to cross-check with what is printed on the adapter. Take into consideration that non e-marked cables will be limited to 3A and that EPR requires specifically marked cables. + +If you take the tip out of the iron, it will result in most devices not negotiating a PD profile (the irons wait to know what kind of tip is installed). This can be used to stop the failing negotiations in some situations to allow viewing this menu. + + +Before filing a support request, please try testing other power adapters & cables to try and narrow down the possibilities of the issue being a one-off. +If you have the capability to capture the PD traffic, that makes the problem exponentially easier to rectify. diff --git a/Documentation/Development.md b/Documentation/Development.md index ef47bcaaf..9cc3995c7 100644 --- a/Documentation/Development.md +++ b/Documentation/Development.md @@ -14,6 +14,42 @@ You will need to update the build settings for include paths and point to the ne In the `source` folder there is a `Makefile` that can be used to build the repository using command line tools. When running the `make` command, specify which model of the device and the language(s) you would like to use. +### Windows (MSYS2 environment) + +1. Download `msys2` install package from the [official website](https://msys2.org) and install it according to the instruction there; +2. Install requried packages (here and for the future commands use **`mingw64.exe`** terminal): +``` +$ pacman -S mingw-w64-x86_64-arm-none-eabi-gcc mingw-w64-x86_64-libwinpthread-git python3 python3-pip make unzip git +``` +3. Download _3rd party RISC-V toolchain_ `xpack-riscv-none-elf-gcc-...-win32-x64.zip` from [this repository](https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack/releases); +4. Move downloaded `xpack-riscv-none-elf-gcc-...-win32-x64.zip` to `msys64` _Windows_ directory (e.g., `C:\msys64\`); +5. Extract files from `xpack-riscv-none-elf-gcc-...-win32-x64.zip` and go back to _home_ directory: +``` +$ cd / +$ unzip xpack-riscv-none-elf-gcc-...-win32-x64.zip +$ cd ~ +``` +6. Permanently set `PATH` environment variable, so all required toolchains could be available for `make` and for other build scripts: +``` +$ echo 'export PATH=/xpack-riscv-none-elf-gcc-.../bin:${PATH}' >> ~/.bashrc +$ source ~/.bashrc +``` +7. Additionally, `OpenOCD` and/or `ST-Link` can be installed as well to help with flashing: +``` +$ pacman -S mingw-w64-x86_64-openocd +$ pacman -S mingw-w64-x86_64-stlink +``` +8. Clone _IronOS_ repo: +``` +$ git clone --recursive https://github.com/Ralim/IronOS.git +$ cd IronOS +``` +9. Follow steps _4-8_ from [macOS section](#macos); +10. `pip` can be updated inside `venv` only: +``` +$ python3 -m pip install --upgrade pip +``` + ### macOS Use the following steps to set up a build environment for IronOS on the command line (in Terminal). @@ -74,7 +110,7 @@ make -j$(nproc) model=Pinecil firmware-multi_European To build a Cyrillic compressed multi-language firmware for the Pinecil with as many simultaneous jobs as there are logical processors on macOS: ``` -make -j$(sysctl -n hw.logicalcpu) model=Pinecil firmware-multi_compressed_Bulgarian+Russian+Serbian+Ukrainian +make -j$(sysctl -n hw.logicalcpu) model=Pinecil firmware-multi_compressed_Belorussian+Bulgarian+Russian+Serbian+Ukrainian ``` To build a custom multi-language firmware including English and Simplified Chinese for the TS80: diff --git a/Documentation/Flashing/MHP30.md b/Documentation/Flashing/MHP30.md index 4ac4c5d1d..afc13313b 100644 --- a/Documentation/Flashing/MHP30.md +++ b/Documentation/Flashing/MHP30.md @@ -26,9 +26,9 @@ Then this works the same as a production release (use the correct file). # MHP30 -This is completely safe, but if it goes wrong just put the `.hex` file from the official website ([MHP30](https://www.minidso.com/forum.php?mod=viewthread&tid=4385&extra=page%3D1) onto the unit and you're back to the old firmware. Downloads for the `.hex` files to flash are available on the [releases page.](https://github.com/Ralim/IronOS/releases) The file you want is called MHP30.zip. Inside the zip file (make sure to extract the file before flashing with it) will be a file called `MHP30_{Language-Code}.hex`. +This is completely safe, but if it goes wrong just put the corresponding `.hex` file from [the official website](https://e-design.com.cn/en/NewsDetail/4203645.html) ([mirror backup](https://github.com/Ralim/IronOS-Meta/tree/main/Firmware/Miniware)) onto the unit and you're back to the old firmware. Downloads for the `.hex` files to flash are available on the [releases page.](https://github.com/Ralim/IronOS/releases) The file you want is called MHP30.zip. Inside the zip file (make sure to extract the file before flashing with it) will be a file called `MHP30_{Language-Code}.hex`. -Officially the bootloader on the devices only works under Windows (use the built-in File Explorer, as alternative file managers or copy handlers like Teracopy will fail). However, users have reported that it does work under Mac, and can be made to work under Linux _sometimes_. Details over on the [wiki page](https://github.com/Ralim/IronOS/wiki/Upgrading-Firmware). +Officially the bootloader on the devices only works under Windows (use the built-in File Explorer, as alternative file managers or copy handlers like Teracopy will fail). However, users have reported that it does work under [Mac](#mac), and can be made to work under [Linux](#linux) _sometimes_ (look for details below). 1. Hold the button closest to the tip (MHP30 the left button on the back), and plug in the USB to the computer. 2. The unit will appear as a USB drive. (Screen will say `DFU` on it.) diff --git a/Documentation/Flashing/Pinecil V2.md b/Documentation/Flashing/Pinecil V2.md index ac74a0d97..bf2c5203b 100644 --- a/Documentation/Flashing/Pinecil V2.md +++ b/Documentation/Flashing/Pinecil V2.md @@ -24,7 +24,7 @@ In general you probably want `master`. Once you click on a run, scroll down to the "Artifacts" section and then click on your device model name to download a zip file. Then this works the same as a production release (use the correct file). -# Pinecil V2 +## Pinecil V2 - The MCU in Pinecil V2 is Bouffalo BL706 and does _not_ use usb-dfu for flashing as the previous Pinecil V1 MCU did. - See the Pinecil Wiki page [here](https://wiki.pine64.org/wiki/Pinecil#Firmware_&_Updates) for instructions. @@ -34,3 +34,16 @@ Then this works the same as a production release (use the correct file). - One advantage of Pinecil is that you cannot permanently damage it doing a firmware update (because BIN is in ROM); an update could render Pinecil temporarily inoperable if you flash an invalid firmware. But no worries, simply re-flashing with a working firmware copy will fix everything. - USB-C cable is required to do an update. Generally, all USB controllers work, but some hubs have issues, so it is preferred to avoid USB hubs for updates. - Background on the [BL706 chipset](https://lupyuen.github.io/articles/bl706) + +### Troubleshooting + +If you are running into issues such as timeouts during the programming or bootloader errors, the BL702 has a not-amazing USB PHY built in. This can cause problems on cheap cables (especially "thin" ones that tend not to have shielding). One of the authors (Ralim) has found this especially common on the cables supplied with Apple chargers when used with newer Ryzen processor ports. + +It is _strongly_ reccomended to use a good quality cable, ideally _short_. +Also try other USB ports, as on some devices they can use different hub's or lengths of signalling, and this can fix the issue. + +By the PinecilV2's design, by default some of the internal buses are exposed on the USB3 pins, to enable hacking/debugging/mods. This is suspected it _may_ play poorly on some chipsets. Try using a USB2.0 cable. Others have had luck with chaining USB-C->USB-A->USB-C. This may be due to this, as a lot of these adaptors are USB2 or only USB3 5gbps (half USB3 pins). + +Another workaround is to put a USB hub somewhere in the chain, as these will re-form the signal and can work around the issue. + +_Finally_, some users have reported issues under Windows that were fixed by changing OS (Typically to a Linux live cd). diff --git a/Documentation/Flashing/TS100.md b/Documentation/Flashing/TS100.md index 787164e10..0d5ff257e 100644 --- a/Documentation/Flashing/TS100.md +++ b/Documentation/Flashing/TS100.md @@ -26,9 +26,9 @@ Then this works the same as a production release (use the correct file). # TS100 -This is completely safe, but if it goes wrong just put the `.hex` file from the official website ([TS100](https://www.minidso.com/forum.php?mod=viewthread&tid=868&extra=page%3D1) onto the unit and you're back to the old firmware. Downloads for the `.hex` files to flash are available on the [releases page.](https://github.com/Ralim/IronOS/releases) The file you want is called TS100.zip. Inside the zip file (make sure to extract the file before flashing with it) will be a file called `TS100_{Language-Code}.hex`. +This is completely safe, but if it goes wrong just put the corresponding `.hex` file from [the official website](https://e-design.com.cn/en/NewsDetail/4203645.html) ([mirror backup](https://github.com/Ralim/IronOS-Meta/tree/main/Firmware/Miniware)) onto the unit and you're back to the old firmware. Downloads for the `.hex` files to flash are available on the [releases page.](https://github.com/Ralim/IronOS/releases) The file you want is called TS100.zip. Inside the zip file (make sure to extract the file before flashing with it) will be a file called `TS100_{Language-Code}.hex`. -Officially the bootloader on the devices only works under Windows (use the built-in File Explorer, as alternative file managers or copy handlers like Teracopy will fail). However, users have reported that it does work under Mac, and can be made to work under Linux _sometimes_. Details over on the [wiki page](https://github.com/Ralim/IronOS/wiki/Upgrading-Firmware). +Officially the bootloader on the devices only works under Windows (use the built-in File Explorer, as alternative file managers or copy handlers like Teracopy will fail). However, users have reported that it does work under [Mac](#mac), and can be made to work under [Linux](#linux) _sometimes_ (look for details below). 1. Hold the button closest to the tip (MHP30 the left button on the back), and plug in the USB to the computer. 2. The unit will appear as a USB drive. (Screen will say `DFU` on it.) diff --git a/Documentation/Flashing/TS80(P).md b/Documentation/Flashing/TS80(P).md index deaa6b98b..d108ca3d1 100644 --- a/Documentation/Flashing/TS80(P).md +++ b/Documentation/Flashing/TS80(P).md @@ -26,9 +26,9 @@ Then this works the same as a production release (use the correct file). # TS80 / TS80P -This is completely safe, but if it goes wrong just put the `.hex` file from the official website ([TS80](https://www.minidso.com/forum.php?mod=viewthread&tid=868&extra=page%3D1)/[TS80P](https://www.minidso.com/forum.php?mod=viewthread&tid=4070&extra=page%3D1) onto the unit and you're back to the old firmware. Downloads for the `.hex` files to flash are available on the [releases page.](https://github.com/Ralim/IronOS/releases) The file you want is called TS80.zip or TS80P.zip. Inside the zip file (make sure to extract the file before flashing with it) will be a file called `TS80_{Language-Code}.hex`/`TS80P_{Language-Code}.hex`. +This is completely safe, but if it goes wrong just put the corresponding `.hex` file from [the official website](https://e-design.com.cn/en/NewsDetail/4203645.html) ([mirror backup](https://github.com/Ralim/IronOS-Meta/tree/main/Firmware/Miniware)) onto the unit and you're back to the old firmware. Downloads for the `.hex` files to flash are available on the [releases page.](https://github.com/Ralim/IronOS/releases) The file you want is called TS80.zip or TS80P.zip. Inside the zip file (make sure to extract the file before flashing with it) will be a file called `TS80_{Language-Code}.hex`/`TS80P_{Language-Code}.hex`. -Officially the bootloader on the devices only works under Windows (use the built-in File Explorer, as alternative file managers or copy handlers like Teracopy will fail). However, users have reported that it does work under Mac, and can be made to work under Linux _sometimes_. Details over on the [wiki page](https://github.com/Ralim/TS80/wiki/Upgrading-Firmware). +Officially the bootloader on the devices only works under Windows (use the built-in File Explorer, as alternative file managers or copy handlers like Teracopy will fail). However, users have reported that it does work under [Mac](#mac), and can be made to work under [Linux](#linux) _sometimes_ (look for details below). 1. Hold the button closest to the tip (MHP30 the left button on the back), and plug in the USB to the computer. 2. The unit will appear as a USB drive. (Screen will say `DFU` on it.) @@ -39,6 +39,8 @@ Officially the bootloader on the devices only works under Windows (use the built 7. If it didn't work the first time, try copying the file again without disconnecting the device, often it will work on the second shot. 8. Disconnect the USB and power up the device. You're good to go. +If you get a message when copying: "Are you sure you want to move this file without its properties?" then this can cause an issue where the iron thinks that the file has finished copying before it actually has and can cause a .ERR file. Since this dialog prompt is caused by copying a file from NTFS to FAT (the iron's filesystem) in windows, you can fix this by formatting a thumbdrive as FAT32 and then storing the hex file on that before copying the file to the iron. As there will be no NTFS properties on the file when stored on a FAT32 filesystem, there will be no prompt, and the copy will then proceed normally. + For the more adventurous out there, you can also load this firmware onto the device using an SWD programmer, for easier installation follow the guide at the end of this document. On the USB port, `USB_D+` is shorted to `SWDIO` and `USB_D-` is shorted to `SWCLK` so debugging works without disassembly (attach while staying in the bootloader). Installing [IronOS-dfu](https://github.com/Ralim/IronOS-dfu) is recommended as it allows reliable flashing of binary files with [dfu-util](http://dfu-util.sourceforge.net/). diff --git a/Documentation/GettingStarted.md b/Documentation/GettingStarted.md index e269a8819..e13f35950 100644 --- a/Documentation/GettingStarted.md +++ b/Documentation/GettingStarted.md @@ -9,7 +9,7 @@ If your device did not come with IronOS already installed, or if you need to upd - [TS80 / TS80P](https://ralim.github.io/IronOS/Flashing/TS80%28P%29/) - [TS100](https://ralim.github.io/IronOS/Flashing/TS100) -It is recommended to update to the newest stable release. +It is recommended to update to the newest stable release when you first receive your device to ensure you are up to date. Once your Iron has been flashed, on first power on it _may_ warn you about the system settings being reset. _Do not panic_; this is 100% completely normal. This is here to note to you that they have been reset to handle the internal structure changing. diff --git a/Documentation/HallSensor.md b/Documentation/HallSensor.md index cca5e2afd..081266ff2 100644 --- a/Documentation/HallSensor.md +++ b/Documentation/HallSensor.md @@ -2,11 +2,11 @@ ## Sleep Mode Menu -In Sleep mode, the iron automatically lowers the temperature to 150 °C (default). This default was chosen as it is just below the melting point of many solders. A stand-by lower temperature helps reduce the rate of oxidation and prevents damage to iron tips. In general, when not using the iron, unplug it or let it sleep to increase the longevity of replaceable tips. The default sleep temperature can be customized. +In sleep mode, the iron automatically lowers the temperature to 150°C (default). This default setting was chosen as it is just below the melting point of a wide range of solders. A lower standby temperature helps reduce the oxidation rate and prevent damage to the soldering tips. As a general rule, when not in use, unplug the unit or let it go into sleep mode to extend the life of the replaceable tips. The default sleep temperature can be adjusted to your preference. -Simply moving the iron or pressing any button will wake it back up into soldering mode. +Simply moving the iron or pressing any button will wake it back up into soldering mode. The sensitivity is adjustable. It is recommended to adjust this to suit your environment so that it reliably stays in sleep mode when not in use, but does not go into sleep mode when in use. (This may vary depending on the amount of movement during soldering.) -### Optional Hall Effect Feature (Pinecil only): +### Optional Hall Effect Feature (Pinecil (v1/v2) only): Inside the [Sleep Menu](https://ralim.github.io/IronOS/Settings/#setting-sleep-temp) is an additional type of sleep setting. Pinecil has an unpopulated footprint (**U14**) for a hall effect sensor, Silicon Labs **Si7210-B-00-IV**. After installing the hall effect sensor (HES), it is possible to auto-trigger Pinecil to enter sleep mode when it enters the stand, and _Zzzz_ will appear (or text in detailed mode). This could be a fun enhancement for any Pinecil and adds a feature typically only found in more expensive high-end irons. The HES is available at many electronic stores for ~$2-$6. diff --git a/Documentation/Hardware.md b/Documentation/Hardware.md index 4734a5529..8a1830b00 100644 --- a/Documentation/Hardware.md +++ b/Documentation/Hardware.md @@ -1,36 +1,66 @@ ## Notes on the various supported hardware +Below are short summaries / notes around the hardware. This is not an in-depth comparison of the features of the units. Please do your own research before purchasing. + +Due to descisions out of our control, Miniware no longer provides source-code/schematics/support for any open source firmware on their devices. This does mean that only (TS100/TS80/TS80P) are "open" to any extent. TS80P is pushing that as it was never open at all but just happens to be very close to the TS80. While this generally shouldn't affect the performance of the device, it does mean that their newer products can be slow to be supported or some issues are harder to resolve. + +Sequre has so far been supportive of the S60 by providing schematics. + +The Pine64 units (Pinecil) are schematics-available (i.e you can download them on the Pine64 Wiki). They are currently the only vendor that has provided financial support of the project. They are also the only vendor that allows contact directly to the engineering teams for hardware issues. This results in generally better support for these devices. It does **not** mean that this firmware is designed around them, but it does help however that they are designed with this firmware in mind as Ralim talks to them. Where possible features are designed to work across all devices but the time for support may vary depending on the hardware and its quirks. + + +## A quick note on power supplies + +For all devices listed **except** the MHP30: + +These soldering irons do *NOT* contain DC/DC converters. +This means that your power at the tip is a function of the supplied voltage. Just because the iron "supports" running at a wide range of voltages, you should always use a voltage near the upper limit where possible. +It is highly recommended to use a PD adapter where possible as this allows the iron to _know_ the limitations of your supply. +The marked irons can only turn the tip on and off in software, this means that they can't control the maximum power drawn from the supply. This is why when using PD the iron may select a lower voltage than your power supplies maximum. This is to prevent your power supply failing from over current. For more information about power management underhood, please, [see the related documentation section](https://ralim.github.io/IronOS/Power/). + +For the MHP30, it contains a buck DC/DC, which means it can utilise most power supplies fairly well, but you should still aim for highest voltage that is reasonable to use. + ### TS100 -TS100\* is a neat soldering iron: +The TS100 was the first supported soldering iron, and is generally a very capable device. +Its now generally not reccomended to buy new as other devices have all of its features and more, and can often be the same price or cheaper. It's still fully supported though, nothing will be taken away from it. - can run from 9-25V DC; - provides a power range that is determined by the input voltage; - voltages below 12V don't overly work well for any substantial mass; -- the default firmware can be found [here](https://www.minidso.com/forum.php?mod=viewthread&tid=892&extra=page%3D1). +- the original firmware can be found [here](https://e-design.com.cn/en/NewsDetail/4203645.html)([mirror backup](https://github.com/Ralim/IronOS-Meta/tree/main/Firmware/Miniware)). ![](https://brushlesswhoop.com/images/ts100-og.jpg) +### TS101 + +The TS101 is the direct replacement of the TS100 with the same tip compatibility. +It adds a spring pressure tip holding mechanism instead of using a screw so tips are easier to swap on the fly (But are held less securely and can pull out depending on the use case). It adds USB-C PD support and the hardware is compatible with 28V EPR power supplies (under both IronOS and official firmware). + +It unfortunately uses an STM32 clone MCU with quirks, so performance of the screen isn't as good as it could be but its perfectly usable. The bootloader for programming is the biggest weakness of this device and programming can be a pain. Fortunately, IronOS is relatively stable feature wise, so you shouldn't need to update the device often. + +The Miniware bootup logo is burned into their bootloader, so IronOS cant remove this. IronOS can show your own logo when it starts however. There are quirks to loading a logo on this device, so be sure to read the documentation if you are coming from other devices. ### TS80 -TS80\* is a successor to TS100: +TS80 is a successor to TS100, it moves to custom smaller tips that perform better at lower wattages. It is optimised for a 9V/2A Quick Charge 3.0 power supply. This is commonly found on older power banks on the USB-A port. +It does **not** support USB-PD and will not work when powered from a USB-C power supply in most cases. - uses _Quick Charge 3.0_ / _QC3_ capable charger only (18W max); - doesn't support PD as it is not designed on the hardware level; -- the default firmware can be found [here](https://www.minidso.com/forum.php?mod=viewthread&tid=3208&extra=page%3D1). +- the original firmware can be found [here](https://e-design.com.cn/en/NewsDetail/4203645.html)([mirror backup](https://github.com/Ralim/IronOS-Meta/tree/main/Firmware/Miniware)). -![](https://core-electronics.com.au/media/catalog/product/4/2/4244-01.jpg) +![Image of TS80](https://core-electronics.com.au/media/catalog/product/4/2/4244-01.jpg) ### TS80P -TS80P\* is a successor to TS80: +The TS80P is the direct successor to the TS80 and essentially what the TS80 should have been from its debut. It is nearly identical except it adds USB-PD support for far better compatibility with modern power banks as well as a faster tip removal method. -- supports _Quick Charge 3.0_ (_QC3_: 9V/3A, 18W max); +- supports _Quick Charge 3.0_ (_QC3_: 9V/2A,12V/1.5A 18W max); - supports _Power Delivery_ (_PD_: 9V/3A & 12V/3A, 30W max)\*\*; -- the default firmware can be found [here](https://www.minidso.com/forum.php?mod=viewthread&tid=4085&extra=page%3D1). +- the original firmware can be found [here](https://e-design.com.cn/en/NewsDetail/4203645.html)([mirror backup](https://github.com/Ralim/IronOS-Meta/tree/main/Firmware/Miniware)). \*\*: use valid PD device that supports 12V/3A as power source to get full 30W potential, otherwise the iron will fall back to 9V/18W power mode. @@ -44,12 +74,13 @@ MHP30 is a **M**ini **H**ot **P**late: - accelerometer is the MSA301, this is mounted roughly in the middle of the unit; - USB-PD is using the FUSB302; - the hardware I2C bus on PB6/7 is used for the MSA301 and FUSB302; -- the OLED is the same SSD1306 as everything else, but it’s on a bit-banged bus. +- the OLED is the same SSD1306 as everything else, but it’s on a bit-banged bus; +- the original firmware can be found [here](https://e-design.com.cn/en/NewsDetail/4203645.html)([mirror backup](https://github.com/Ralim/IronOS-Meta/tree/main/Firmware/Miniware)). ### Pinecil -Pincecil\*: +Pincecil: - first model of soldering iron from PINE64; - the default firmware can be found [here](https://files.pine64.org/os/Pinecil/Pinecil_firmware_20201115.zip). @@ -57,6 +88,3 @@ Pincecil\*: ![](https://pine64.com/wp-content/uploads/2020/11/pinecil-bb2-04.jpg?v=0446c16e2e66) -\*: Please note: these soldering irons do *NOT* contain DC/DC converters. This means that your power at the tip is a function of the supplied voltage. Just because the iron "supports" running at a wide range of voltages, you should always use a voltage near the upper limit where possible. It is highly recommended to use a PD adapter where possible as this allows the iron to _know_ the limitations of your supply. The marked irons can only turn the tip on and off in software, this means that they can't control the maximum power drawn from the supply. This is why when using PD the iron may select a lower voltage than your power supplies maximum. This is to prevent your power supply failing from over current. For more information about power management underhood, please, [see the related documentation section](https://ralim.github.io/IronOS/Power/). - - diff --git a/Documentation/History.md b/Documentation/History.md index 21672326a..11d69c574 100644 --- a/Documentation/History.md +++ b/Documentation/History.md @@ -1,7 +1,51 @@ # Version Changes -# V2.21 +## v2.22 + +### New Hardware Support + +#### Sequre S60 + +The [Sequre S60](https://sequremall.com/products/sequre-s60-nano-electric-soldering-iron-support-pd-qc-power-supply-compatible-with-c210-soldering-iron-tips-precision-electronic-mobile-phone-repair-tool-anti-static-soldering-pen?variant=42361945096380) uses JBC tips, which makes it quite useful for the smaller tip types and extra options available. + +#### TS101 + +The TS101 is the evolution of the TS100, picking up USB-PD. +It has otherwise similar tip support to the TS100/Pinecil/PinecilV2. + +Absolutely massive kudos goes to @VioletEternity for her work on the reverse engineering of this. If you at all are helped by IronOS running on this device more credit goes to her than to I. Also big thanks to @whitequark for organising + supporting + magic. + +### Features & changes + +#### PinecilV2 notes + +1. BLE is fixed on all devices. +2. Bootup Logo support is finalised and working. +3. Improved the tip control, improving accuracy and remove most oscillations. + +#### Profile heating mode for MHP30 + +This lets you define a heat profile and run this profile akin to a proper reflow device. +This can be used on the MHP30 by long-holding the A button (aka start button). +Profile can be edited in settings. + +#### Note on newer OLED's + +To prevent this release being held up forever, the TS101 and S60 are being released with a limitation on the OLED screen. +The current code will only draw to the upper left corner of the screen. +Assets have been made for rendering this at full size, but the code is not complete yet. + +#### Smaller updates + +- Filtering added to MHP tilt-exit to make it less sensitive +- Warning if a tip is detected to be shorted (TS101 + PinecilV2) +- Translation updates ❤️ +- Documentation updates +- Lots of tooling and code cleanups + + +## v2.21 ### Features & changes @@ -20,7 +64,7 @@ Alternatively you can use Spagett1's PineFlash tool that should provide a GUI in For a small number of V2 Pinecil devices there appears to be an interference issue between the Bluetooth Low Energy and some devices; more information here. If this occurs to you, please let us know in the issue and rollback to 2.20 for now. -# V2.20 +## v2.20 - First "full" release for PinecilV2 - Loots of documentation updates @@ -29,7 +73,7 @@ For a small number of V2 Pinecil devices there appears to be an interference iss - Cold Junction Calibration was reworked and now occurs _at next boot_ to make it easier to perform when the device is cold -# V2.19 +## v2.19 - Bug-fix Infinite Boot Logo - Shutdown settings for MHP30 @@ -40,7 +84,7 @@ For a small number of V2 Pinecil devices there appears to be an interference iss - Improved documents, added features table -# V2.18 +## v2.18 - Support for animated bootup logo's - Bootup logo's moved to their own IronOS-Meta repo @@ -50,7 +94,7 @@ For a small number of V2 Pinecil devices there appears to be an interference iss - Better Instructions/documents -# V2.17 +## v2.17 ### Features & changes @@ -78,7 +122,7 @@ For a small number of V2 Pinecil devices there appears to be an interference iss - -> Release has been updated to build `e065be3` after one bug with the BMA223 was found. -# V2.16 +## v2.16 - Overhaul of the Timer+ADC setup with help from @sandmanRO - Overhaul of the PID with help from @sandmanRO @@ -96,7 +140,7 @@ For a small number of V2 Pinecil devices there appears to be an interference iss - Romanian language added -# V2.15 +## v2.15 ### Features & changes @@ -121,7 +165,7 @@ Programs the same as any one Miniware unit using drag and drop. The flood doors are now open for feature requests for this unit :) -# V2.14 +## v2.14 - Fixing auto rotation bug in the LIS accelerometer in the TS80/TS80P - Adds support for two new accelerometers @@ -139,7 +183,7 @@ The flood doors are now open for feature requests for this unit :) - clang-format spec setup #801 -# V2.13 +## v2.13 - First _official_ Pinecil release - All of the wire for Pinecil releases added @@ -157,7 +201,7 @@ The flood doors are now open for feature requests for this unit :) - Rework of all of the temperature curves for better accuracy -# V2.12 +## v2.12 - Only released as pre-release - [TS80P] Improvements to the PD negotiation to handle a few more adapters cleanly @@ -166,21 +210,21 @@ The flood doors are now open for feature requests for this unit :) - Removing the very old single line menu style. -# V2.11 +## v2.11 - First TS80P support - Added in a USB-PD driver stack for the FUSB302 - Fixed some graphical glitches -# V2.10 +## v2.10 - GUI polish (animations and scroll bars) - Power pulse to keep power supplies alive - Adjustable tip response gain -# V2.09 +## v2.09 - Adjustable steps in temperature adjustment - Git hash now in build string @@ -188,19 +232,19 @@ The flood doors are now open for feature requests for this unit :) - Some minor QC3 improvements -# V2.08 +## v2.08 - Fixes auto start in sleep mode - Power limiters -# V2.07 +## v2.07 - QC fixes - Cosmetic fixes for leading 0's -# V2.06 +## v2.06 - Warning on settings reset - Temp temp re-write @@ -209,32 +253,32 @@ The flood doors are now open for feature requests for this unit :) - Menu timeouts -# V2.05 +## v2.05 - Language updates -# V2.04 +## v2.04 - GUI updates -# V2.03 +## v2.03 - Support for new accelerometers -# V2.02 +## v2.02 - Adds small font -# V2.01 +## v2.01 - Newer settings menu -# V2.00 +## v2.00 - Complete re-write of the low layer system to use the STM32 HAL for easier development - This allowed easier setup for the new ADC auto measuring system @@ -245,7 +289,7 @@ The flood doors are now open for feature requests for this unit :) - Added smaller font for said screen views -# V1.17 +## v1.17 - Added blinking cooldown display - Allowed smaller sleep timeout values @@ -253,72 +297,72 @@ The flood doors are now open for feature requests for this unit :) - Automatic startup option -# V1.16 +## v1.16 - Added automatic rotation support - Added power display graph -# V1.15 +## v1.15 - Added support for a custom bootup logo to be programmed via the DFU bootloader -# V1.14 +## v1.14 - Changed input voltage cutoff to be based on cell count rather than voltage -# V1.13 +## v1.13 - Swapped buttons for menu to prevent accidentally changing first menu item - Added auto key repeat -# V1.12 +## v1.12 - Increases sensitivity options to be 1\*9 with 0 off state - Fixes issue where going from COOL \*> soldering can leave screen off -# V1.11 +## v1.11 - Boost mode - Change sensitivity options to be 1\*8 -# V1.10 +## v1.10 - Adds help text to settings - Improves settings for the display update rate -# V1.09 +## v1.09 - Adds display modes, for slowing down or simplifying the display -# V1.08 +## v1.08 - Fix settings menu not showing flip display -# V1.07 +## v1.07 - Adds shutdown time to automatically shutdown the iron after inactivity -# V1.06 +## v1.06 - Changes H and C when the iron is heating to the minidso chevron like images -# V1.05 +## v1.05 - Adds ability to calibrate the input voltage measurement -# V1.04 +## v1.04 - Increased accuracy of the temperature control - Improved PID response slightly @@ -326,14 +370,14 @@ The flood doors are now open for feature requests for this unit :) - Nicer idle screen -# V1.03 +## v1.03 - Improved Button handling - Ability to set motion sensitivity - DC voltmeter page shows input voltage -# V1.02 +## v1.02 - Adds hold both buttons on IDLE to access the therometer mode - Changes the exit soldering mode to be holding both buttons (Like original firmware) diff --git a/Documentation/Logo.md b/Documentation/Logo.md index 9734fda33..a7d25628d 100644 --- a/Documentation/Logo.md +++ b/Documentation/Logo.md @@ -26,11 +26,13 @@ It is easiest if you copy your logo file to be converted into this folder too, i The image can be in color and any size, but it will be resized and converted to 1-bit color. However, it looks best if you create a 96x16 image (`png` or `bmp`) in any image editor and color the pixels black & white manually. The thresholding used for converting colour to B&W may not always work as well as one would hope. -The converter requires at least Python3 and Pillow apps. Follow online instructions for installing Python and Pillow on your machine. Any reasonably recent version should work well. +The converter requires at least Python3 and Pillow apps as well as the IntelHex library for Python. Follow online instructions for installing Python, Pillow, and IntelHex on your machine. Any reasonably recent version should work well. -When running the script on the Windows operating system; it is recommended to use `Powershell` rather than the old `Command Prompt`. +When running the script on the Windows operating system it is recommended to use `Powershell` rather than the old `Command Prompt`. -For installing pillow; you can install it via your package manager (Debian and similar distros) or via pip. To install via pip the command should be `python -m pip install pillow`. +For installing pillow, you can install it via your package manager (Debian and similar distros) or via pip. To install via pip the command should be `python -m pip install pillow`. + +For installing IntelHex you can use the same pip command as above but replace `pillow` with `intelhex` so that it becomes `python -m pip install intelhex`. In your shell you can now execute `python img2logo.py input.png out -m ${model}` to convert the file `input.png` and create output files in the folder `out`. The model should be replaced by one of the following options: @@ -38,8 +40,8 @@ The model should be replaced by one of the following options: - `miniware` for older Miniware Irons -> TS100, TS80, TS80P - `pinecilv1` for the Pinecil V1 - `pinecilv2` for the Pinecil V2 -- `ts101` for the Miniware TS101 [^1] -- `s60` for the Squire S60 [^1] +- `ts101` for the Miniware TS101 [^1] [^2] +- `s60` for the Sequre S60 [^1] - `mhp30` for the Miniware MHP30 Different models are used for different flash locations for the image storage. @@ -50,6 +52,28 @@ After processing its expected to have a `.hex` and `.dfu` file created to be use Note: make sure your image file is in the same folder as script files (img2logo.py, output_dfu.py, output_hex.py). [^1] Note that these devices have larger resolution screens that the logo system supports right now. Fixes are coming for this soon, roughly scheduled for 2.23. +[^2] The TS101 requires extra steps, see below. + +### TS101 Quirks + +When Miniware designed the TS101 they cut cost by using an STM32 clone with some odd quirks. They also re-wrote their USB bootloader, which has introduced new bugs for us to deal with. +Their bootloader appears to have kept the existing limit of not being able to flash small hex files, but they no longer fall for the older "just repeat the content" trick and instead reject the file. +Additionally, while the MCU in use has 128K of flash, their bootloader (at least for me) fails to write to anything above 99K. It _looks_ like a watchdog reset or hard crash. Unsure. + +This has flow on effects, where the settings can still be located in the upper ~28K of flash, but it cant be used for anything we flash over USB. +Of that 100K we can use, they waste 32K of it for their bootloader (Old bootloaders were 16K). +This means the main "app" of IronOS is limited to around 67K (100K-32K for bootloader, -1K for logo). + +For this device the Logo is not located at the end of flash but instead at the last writable page (99K). + +Additionally, as we need to do a large write, to avoid having to waste more flash space; the logo is merged with the normal firmware. This means that the firmware and logo are flashed together once. +Future updates can be done without merging as it will leave the logo data there as normal firmware doesnt touch that area of flash. + +To do this, download the latest version of IronOS and merge it with the logo using the `--merge` command line argument. + +To create the logo file for a TS101 the full command looks like `python3 img2logo.py -m ts101 --merge `. + +For this reason, there are no TS101 logo's generated by the IronOS-Meta repo. ## Flashing the Logo @@ -76,4 +100,4 @@ For these flash as per usual using the `.dfu` file. Afterwards power cycle and t ### Upload via blisp (PinecilV2) -For the PinecilV2 we suggest `blisp` as the command line tool to use if you are not using a GUI tool. `blsip` has been updated to accept `.dfu` files as well as the `.bin` files it historically used. As such you use the `.dfu` file for the logo and flash as per normal otherwise and it will work and reboot at the end. It should show you your new logo after flashing. +For the PinecilV2 we suggest `blisp` as the command line tool to use if you are not using a GUI tool. `blisp` has been updated to accept `.dfu` files as well as the `.bin` files it historically used. As such you use the `.dfu` file for the logo and flash as per normal otherwise and it will work and reboot at the end. It should show you your new logo after flashing. diff --git a/Documentation/PortingToNewDevice.md b/Documentation/PortingToNewDevice.md new file mode 100644 index 000000000..b0479f64d --- /dev/null +++ b/Documentation/PortingToNewDevice.md @@ -0,0 +1,72 @@ +# Requesting support for a new device + +IronOS is largely designed to run on devices that are using _fairly_ modern microcontrollers at their core. Generally this means an ARM Cortex or RISC-V processor. +At this point in time it is not planned to support 8051 or similar cored devices. This is largely due to the reliance on FreeRTOS at the moment. + +When requesting a port for a new device, please try and find out if the hardware meets the below requirements. + +The feature list's below are organised into three categories; Hard requirements that as of current must be met, soft requirements that _should_ be met for full featured performance and the final category of planned _but not yet implemented_ features; which can be implemented but can result in delays as these are not yet implemented. + +Aside from the below, keep in mind IronOS is really designed for soldering irons. This has expanded out into hot-plates as they are exceptionally similar devices. + +## Hard requirements + +1. Supported processor (Arm Cortex or RISC-V). (Though generally anything that has an existing FreeRTOS port is possible). +2. 64K of flash or larger (See note A) +3. 16K of ram or larger +4. Device has one or more heating elements that can be controlled by a main temperature sensor +5. If the main temperature sensor is a thermocouple, a reference temperature sensor for cold junction compensation must exist and be close to the sensor contacts +6. Means of the user updating the device without opening +7. Known pinmap for the microcontroller. (see note B) + +## Soft requirements + +1. USB-PD is strongly preferred over Quick Charge; Quick Charge only devices are considered legacy and will likely not be prioritiesd. +2. Open source or at the least schematics available is **strongly** preferred and will prioritise the device. +3. Likewise friendly vendors will help dramatically with support, due to both questions and also appearances to help the community. +4. Hardware PWM wired up to the tip control is nice to have but not essential +5. Very strong preference against devices that use the endless sea of STM32 clones. + +## Planned features + +These features are planned for eventual support, but will likely not be done until devices need them. + +- Colour screens +- More than 2 buttons for input, or encoder inputs +- WiFi/Zigbee/ any other networking + +## Notes + +### Note A - Flash storage space + +64KB is generally the minimum recommended size for the hardware to have. +Larger is _definitely_ preferred as it enables more features or the multi-pack language firmwares. +Keep in mind that on some devices we loose space to a USB DFU bootloader (Older STM32F1's) so the firmware _can_ work with less. But it can come at the cost of features. +128KB or larger is **great**. +For devices that have BLE or WiFi or other features, often code requirements are significantly larger. These are considered non essential features so will be ignored if we run into size issues. + +### Note B - Pinmap for the microcontroller + +In order to be able to write the interfacing code to communicate with the hardware, we need to know what pins on the microcontroller go to what hardware. +It is also loosely required to have an understanding of the rest of the device, we do not need details on a lot of the boring aspects,but if for example a USB-PD interface IC is used we would want to know which one. + +## Example request for adding a new device + +Device Name: +Device Type: +Approximate Price: +Example purchase locations: + +### Hardware details + +Microcontroller version: `STM32F103C8Tx` +Flash size (If external to the MCU):`N/A` +Microcontroller Pinout: +Device type: +Device meets hard requirements list [] +Device meets soft requirements list [] + +Device features USB-PD [] +Device features USB-QC [] +Device features DC Input [] +Device features BLE [] diff --git a/Documentation/Power.md b/Documentation/Power.md index a6532adf3..3152d13db 100644 --- a/Documentation/Power.md +++ b/Documentation/Power.md @@ -6,13 +6,14 @@ This *means* that the power provided in the tip is 100% controlled by the supply Irons at their simplest are just a resistor (Ω) connected to your power source via a switch. -- When the switch is on, the power in the resistor is: $P(watts) = V(volts) \times\ I(current=amps)$ -- Current through the resistor is: $I(amps) = V(volts) ÷ Ω (resistance)$ +- When the switch is on, the power in the resistor is: *`P(watts) = V(volts) \times\ I(current=amps)`* +- Current through the resistor is: *`I(amps) = V(volts) ÷ Ω (resistance)`* - Combining these gives some common equations for Power - $P(watts) = V(volts) * I(amps)$ or $P = V^2 ÷ Ω$ + *`P(watts) = V(volts) * I(amps)`* or *`P = V^2 ÷ Ω`* The resistance of the tip is a fixed constant in ohms (Ω): + - 6.2 Ω Pine64 short tip - 8.0 Ω TS100/Pinecil long tip - 4.5 Ω TS80(P) diff --git a/Documentation/README.md b/Documentation/README.md index 85f51d439..3b4dc6956 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -21,12 +21,15 @@ - [Temperature](../Documentation/Temperature.md) - [Startup Logo](../Documentation/Logo.md) - Hardware - - [Hall Sensor (Pinecil)](../Documentation/HallSensor.md) - [Bluetooth (Pinecil V2)](../Documentation/Bluetooth.md) + - [Debugging USB-PD](../Documentation/DebuggingPD.md) + - [Hall Sensor (Pinecil)](../Documentation/HallSensor.md) - [Hardware Notes](../Documentation/Hardware.md) - - [Troubleshooting](../Documentation/Troubleshooting.md) - [Known Hardware Issues](../Documentation/HardwareIssues.md) + - [New Hardware Requirements](../Documentation/PortingToNewDevice.md) - [Power sources](../Documentation/PowerSources.md) + - [Troubleshooting](../Documentation/Troubleshooting.md) + - [WS2812B RGB Modding (Pinecil V2)](../Documentation/WS2812BModding.md) - [Translations](../Documentation/Translation.md) - [Development](../Documentation/Development.md) - [Changelog](../Documentation/History.md) diff --git a/Documentation/Settings.md b/Documentation/Settings.md index 7b85506e1..ebe5bda4e 100644 --- a/Documentation/Settings.md +++ b/Documentation/Settings.md @@ -43,194 +43,223 @@ When the device is powered by a battery, this adjusts the low voltage threshold On device help text: -Set cutoff voltage to prevent battery over-drain. (DC 10V) (S=3.3V per cell, disable PWR limit) +Set cutoff voltage to prevent battery overdischarge (DC=10V) (S=3.3V per cell, disable PWR limit) -### Setting: Sleep temp +### Setting: Minimum voltage -Temperature the device will drop down to while asleep. Typically around halfway between off and soldering temperature. +When powered by a battery, this adjusts the minimum voltage per cell before shutdown. (This is multiplied by the cell count.) On device help text: -Tip temperature while in "sleep mode" +Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V) -### Setting: Sleep timeout +### Setting: QC voltage -How long of a period without movement / button-pressing is required before the device drops down to the sleep temperature. +This adjusts the maximum voltage the QC negotiation will adjust to. Does NOT affect USB-PD. Should be set safely based on the current rating of your power supply. On device help text: -Interval before "sleep mode" starts (s=seconds | m=minutes) +Max QC voltage the iron should negotiate for -### Setting: Shutdown timeout +### Setting: PD timeout -How long of a period without movement / button-pressing is required before the device turns off the tip heater completely and returns to the main idle screen. +How long until firmware stops trying to negotiate for USB-PD and tries QC instead. Longer times may help dodgy / old PD adapters, faster times move onto PD quickly. Units of 100ms. Recommended to keep small values. On device help text: -Interval before the iron shuts down (m=minutes) +PD negotiation timeout in 100ms steps for compatibility with some QC chargers -### Setting: Motion sensitivity +### Setting: PD Mode -Scale of how sensitive the device is to movement. Higher numbers == more sensitive. 0 == motion detection turned off. +Adjusts how the USB-PD Logic selects the voltage. No Dynamic disables EPR & PPS protocols, Safe mode does not use padding resistance (will select a slightly lower voltage). On device help text: -0=off | 1=least sensitive | ... | 9=most sensitive +No Dynamic disables EPR & PPS, Safe mode does not use padding resistance -### Setting: Temperature unit +### Setting: Boost temp -If the device shows temperatures in °C or °F. +When the unit is in soldering mode. You can hold down the button at the front of the device to temporarily override the soldering temperature to this value. This SETS the temperature, it does not ADD to it. On device help text: -C=Celsius | F=Fahrenheit +Tip temperature used in "boost mode" -### Setting: Detailed idle screen +### Setting: Start-up behavior -Should the device show an 'advanced' view on the idle screen. The advanced view uses text to show more details than the typical icons. +When the device powers up, should it enter into a special mode. These settings set it to either start into soldering mode, sleeping mode or auto mode (Enters into soldering mode on the first movement). On device help text: -Display detailed info in a smaller font on idle screen +S=heat to soldering temp | Z=standby at sleep temp until moved | R=standby without heating until moved -### Setting: Display orientation +### Setting: Temp change short -If the display should rotate automatically or if it should be fixed for left- or right-handed mode. +Factor by which the temperature is changed with a quick press of the buttons. On device help text: -R=right-handed | L=left-handed | A=automatic +Temperature-change-increment on short button press -### Setting: Boost temp +### Setting: Temp change long -When the unit is in soldering mode. You can hold down the button at the front of the device to temporarily override the soldering temperature to this value. This SETS the temperature, it does not ADD to it. +Factor by which the temperature is changed with a hold of the buttons. On device help text: -Tip temperature used in "boost mode" +Temperature-change-increment on long button press -### Setting: Start-up behavior +### Setting: Allow locking buttons -When the device powers up, should it enter into a special mode. These settings set it to either start into soldering mode, sleeping mode or auto mode (Enters into soldering mode on the first movement). +If locking the buttons against accidental presses is enabled. On device help text: -O=off | S=heat to soldering temp | Z=standby at sleep temp until moved | R=standby, heat-off until moved +While soldering, hold down both buttons to toggle locking them (B=boost mode only | F=full locking) -### Setting: Cooldown flashing +### Setting: Profile Phases -If the idle screen should blink the tip temperature for attention while the tip is over 50°C. Intended as a 'tip is still hot' warning. +set the number of phases for profile mode. On device help text: -Flash temperature reading at idle if tip is hot +Number of phases in profile mode -### Setting: Calibrate CJC at next boot +### Setting: Preheat Temp -Note: -If the difference between the target temperature and the measured temperature is less than 5°C, **calibration is NOT required at all**. +Preheat to this temperature at the start of profile mode. -This is used to calibrate the offset between ADC and Op-amp of the tip **at next boot** (Ideally it has to be done at boot, before internal components get warm.). If the checkbox is set, the calibration will only be performed at the next boot. After a successful calibration the checkbox will be unchecked again! If you need to repeat the calibration however, you have to set the checkbox *again*, unplug your device and let it cool down to room/ambient temperature & power it up, ideally while it sits on the desk. +On device help text: -Also, the calibration will only take place if both of the following conditions are met: -- The tip must be installed. -- The temperature difference between tip and handle must be less than 10°C. (~ ambient / room temperature) +Preheat to this temperature at the start of profile mode -Otherwise, the calibration will be performed the next time the device is started and both conditions are met, unless the corresponding checkbox is unchecked. +### Setting: Preheat Speed -Hence, never repeat the calibration in quick succession! +How fast the temperature is allowed to rise during the preheat phase at the start of profile mode. On device help text: -Calibrate tip Cold Junction Compensation at the next boot (not required if Delta T is < 5°C) +Preheat at this rate (degrees per second) -### Setting: Restore default settings +### Setting: Phase 1 Temp -Resets all settings and calibrations to factory defaults. Does NOT erase custom user boot up logo's. +Target temperature for the end of phase 1 of profile mode. On device help text: -Reset default settings for this firmware ver. +Target temperature for the end of this phase -### Setting: Calibrate input voltage +### Setting: Phase 1 Duration -Enters an adjustment mode where you can gradually adjust the measured voltage to compensate for any unit-to-unit variance in the voltage sense resistors. +Duration of phase 1 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature. On device help text: -Start VIN calibration (long press to exit) +Target duration of this phase (seconds) -### Setting: Detailed solder screen +### Setting: Phase 2 Temp -Should the device show an 'advanced' soldering view. This is a text-based view that shows more information at the cost of no nice graphics. +Target temperature for the end of phase 2 of profile mode. On device help text: -Display detailed info in a smaller font on soldering screen -### Setting: Scrolling speed -How fast the description text scrolls when hovering on a menu. Faster speeds may induce tearing, but allow reading the whole description faster. +### Setting: Phase 2 Duration + +Duration of phase 2 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature. On device help text: -Speed info text scrolls past at (S=slow | F=fast) -### Setting: QC voltage -This adjusts the maximum voltage the QC negotiation will adjust to. Does NOT affect USB-PD. Should be set safely based on the current rating of your power supply. +### Setting: Phase 3 Temp + +Target temperature for the end of phase 3 of profile mode. On device help text: -Max QC voltage the iron should negotiate for -### Setting: PD timeout -How long until firmware stops trying to negotiate for USB-PD and tries QC instead. Longer times may help dodgy / old PD adapters, faster times move onto PD quickly. Units of 100ms. Recommended to keep small values. +### Setting: Phase 3 Duration + +Duration of phase 3 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature. On device help text: -PD negotiation timeout in 100ms steps for compatibility with some QC chargers -### Setting: Power limit -Allows setting a custom wattage for the device to aim to keep the AVERAGE power below. The unit can't control its peak power no matter how you set this. (Except for MHP30 which will regulate nicely to this). If USB-PD is in use, the limit will be set to the lower of this and the supplies advertised wattage. +### Setting: Phase 4 Temp + +Target temperature for the end of phase 5 of profile mode. On device help text: -Maximum power the iron can use (W=watt) -### Setting: Swap + - keys -Swaps which button increments and decrements on temperature change screens. +### Setting: Phase 4 Duration + +Duration of phase 5 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature. On device help text: -Reverse assignment of buttons for temperature adjustment -### Setting: Temp change short -Factor by which the temperature is changed with a quick press of the buttons. +### Setting: Phase 5 Temp + +Target temperature for the end of phase 5 of profile mode. On device help text: -Temperature-change-increment on short button press -### Setting: Temp change long -Factor by which the temperature is changed with a hold of the buttons. +### Setting: Phase 5 Duration + +Duration of phase 5 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature. On device help text: -Temperature-change-increment on long button press -### Setting: Power pulse -Enables and sets the wattage of the power pulse. Power pulse causes the device to briefly turn on the heater to draw power to avoid power banks going to sleep. +### Setting: Cooldown Speed + +How fast the temperature is allowed to drop during the cooldown phase at the end of profile mode. + +On device help text: + +Cooldown at this rate at the end of profile mode (degrees per second) + +### Setting: Motion sensitivity + +Scale of how sensitive the device is to movement. Higher numbers == more sensitive. 0 == motion detection turned off. + +On device help text: + +1=least sensitive | ... | 9=most sensitive + +### Setting: Sleep temp + +Temperature the device will drop down to while asleep. Typically around halfway between off and soldering temperature. On device help text: -Intensity of power of keep-awake-pulse (watt) +Tip temperature while in "sleep mode" + +### Setting: Sleep timeout + +How long of a period without movement / button-pressing is required before the device drops down to the sleep temperature. + +On device help text: + +Interval before "sleep mode" starts (s=seconds | m=minutes) + +### Setting: Shutdown timeout + +How long of a period without movement / button-pressing is required before the device turns off the tip heater completely and returns to the main idle screen. + +On device help text: + +Interval before the iron shuts down (m=minutes) ### Setting: Hall sensor sensitivity @@ -238,63 +267,79 @@ If the unit has a hall effect sensor (Pinecil), this adjusts how sensitive it is On device help text: -Sensitivity to magnets (0=off | 1=least sensitive | ... | 9=most sensitive) +Sensitivity to magnets (1=least sensitive | ... | 9=most sensitive) -### Setting: Allow locking buttons +### Setting: HallSensor SleepTime -If locking the buttons against accidental presses is enabled. +If the unit has a hall effect sensor (Pinecil), this adjusts how long the device takes before it drops down to the sleep temperature when hall sensor is over threshold. On device help text: -While soldering, hold down both buttons to toggle locking them (D=disable | B=boost mode only | F=full locking) +Interval before "sleep mode" starts when hall effect is above threshold -### Setting: Minimum voltage +### Setting: Temperature unit -When powered by a battery, this adjusts the minimum voltage per cell before shutdown. (This is multiplied by the cell count.) +If the device shows temperatures in °C or °F. On device help text: -Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V) +C=°Celsius | F=°Fahrenheit -### Setting: Anim. loop +### Setting: Display orientation -Should the menu animations loop. Only visible if the animation speed is not set to "Off" +If the display should rotate automatically or if it should be fixed for left- or right-handed mode. On device help text: -Loop icon animations in main menu +R=right-handed | L=left-handed | A=automatic -### Setting: Anim. speed +### Setting: Cooldown flashing -How fast should the menu animations loop, or if they should not loop at all. +If the idle screen should blink the tip temperature for attention while the tip is over 50°C. Intended as a 'tip is still hot' warning. On device help text: -Pace of icon animations in menu (O=off | S=slow | M=medium | F=fast) +Flash temp reading at idle while tip is hot -### Setting: Power pulse delay +### Setting: Scrolling speed -Adjusts the time interval between power pulses. Longer gaps reduce undesired heating of the tip, but needs to be fast enough to keep your power bank awake. +How fast the description text scrolls when hovering on a menu. Faster speeds may induce tearing, but allow reading the whole description faster. On device help text: -Delay before keep-awake-pulse is triggered (x 2.5s) +Scrolling speed of info text (S=slow | F=fast) -### Setting: Power pulse duration +### Setting: Swap + - keys -How long should the power pulse go for. Some power banks require seeing the power draw be sustained for a certain duration to keep awake. Should be kept as short as possible to avoid wasting power / undesired heating of the tip. +Swaps which button increments and decrements on temperature change screens. On device help text: -Keep-awake-pulse duration (x 250ms) +Reverse assignment of buttons for temperature adjustment -### Setting: Language: EN English +### Setting: Swap A B keys -Changes the device language on multi-lingual builds. +Swaps which button is used as Enter/Change and as Scroll/Back in Settings menu. On device help text: -Current firmware language +Reverse assignment of buttons for Settings menu + +### Setting: Anim. speed + +How fast should the menu animations loop, or if they should not loop at all. + +On device help text: + +Pace of icon animations in menu (S=slow | M=medium | F=fast) + +### Setting: Anim. loop + +Should the menu animations loop. Only visible if the animation speed is not set to "Off" + +On device help text: + +Loop icon animations in main menu ### Setting: Screen brightness @@ -318,4 +363,111 @@ Sets the duration for the boot logo (s=seconds). On device help text: -Set Boot logo duration (off | s=seconds | infinity) +Set boot logo duration (s=seconds) + +### Setting: Detailed idle screen + +Should the device show an 'advanced' view on the idle screen. The advanced view uses text to show more details than the typical icons. + +On device help text: + +Display detailed info in a smaller font on idle screen + +### Setting: Detailed solder screen + +Should the device show an 'advanced' soldering view. This is a text-based view that shows more information at the cost of no nice graphics. + +On device help text: + +Display detailed info in a smaller font on soldering screen + +### Setting: Bluetooth + +Should BLE be enabled at boot time. + +On device help text: + +Enables BLE + +### Setting: Power limit + +Allows setting a custom wattage for the device to aim to keep the AVERAGE power below. The unit can't control its peak power no matter how you set this. (Except for MHP30 which will regulate nicely to this). If USB-PD is in use, the limit will be set to the lower of this and the supplies advertised wattage. + +On device help text: + +Average maximum power the iron can use (W=watt) + +### Setting: Calibrate CJC at next boot + +Note: +If the difference between the target temperature and the measured temperature is less than 5°C, **calibration is NOT required at all**. + +This is used to calibrate the offset between ADC and Op-amp of the tip **at next boot** (Ideally it has to be done at boot, before internal components get warm.). If the checkbox is set, the calibration will only be performed at the next boot. After a successful calibration the checkbox will be unchecked again! If you need to repeat the calibration however, you have to set the checkbox *again*, unplug your device and let it cool down to room/ambient temperature & power it up, ideally while it sits on the desk. + + +Also, the calibration will only take place if both of the following conditions are met: +- The tip must be installed. +- The temperature difference between tip and handle must be less than 10°C. (~ ambient / room temperature) + +Otherwise, the calibration will be performed the next time the device is started and both conditions are met, unless the corresponding checkbox is unchecked. +Hence, never repeat the calibration in quick succession! + +On device help text: + +Calibrate Cold Junction Compensation at next boot (not required if Delta T is < 5°C) + +### Setting: Calibrate input voltage + +Enters an adjustment mode where you can gradually adjust the measured voltage to compensate for any unit-to-unit variance in the voltage sense resistors. + +On device help text: + +Start VIN calibration (long press to exit) + +### Setting: Power pulse + +Enables and sets the wattage of the power pulse. Power pulse causes the device to briefly turn on the heater to draw power to avoid power banks going to sleep. + +On device help text: + +Intensity of power of keep-awake-pulse (W=watt) + +### Setting: Power pulse delay + +Adjusts the time interval between power pulses. Longer gaps reduce undesired heating of the tip, but needs to be fast enough to keep your power bank awake. + +On device help text: + +Delay before keep-awake-pulse is triggered (x 2.5s) + +### Setting: Power pulse duration + +How long should the power pulse go for. Some power banks require seeing the power draw be sustained for a certain duration to keep awake. Should be kept as short as possible to avoid wasting power / undesired heating of the tip. + +On device help text: + +Keep-awake-pulse duration (x 250ms) + +### Setting: Restore default settings + +Resets all settings and calibrations to factory defaults. Does NOT erase custom user boot up logo's. + +On device help text: + +Reset all settings to default + +### Setting: Language: EN English + +Changes the device language on multi-lingual builds. + +On device help text: + + + +### Setting: Soldering Tip Type + +For manually selecting the type of tip fitted + +On device help text: + +Select the tip type fitted diff --git a/Documentation/WS2812BModding.md b/Documentation/WS2812BModding.md new file mode 100644 index 000000000..90ac7b297 --- /dev/null +++ b/Documentation/WS2812BModding.md @@ -0,0 +1,33 @@ +# WS2812B RGB Modding (Pinecil V2) + +## What is it? + +The idea of this mod is to bring the RGB feature of the MHP30 to the Pinecil V2. +Use a transparent shell for a better effect. + +Pinecil V2 has a free GPIO_12 accessible through TP10, which is along the screen, cf [Pinecil PCB placement v2.0](https://files.pine64.org/doc/Pinecil/Pinecil_PCB_placement_v2.0_20220608.pdf) page 3. (TP9 (GPIO_14) is also available but hidden below the screen. If you want to use it, change `WS2812B_Pin` in `source/Core/BSP/Pinecilv2/Pins.h`.) + +We'll using it to drive a WS2812B and let the color logic already present for the MHP30 do its magic: + +- green when temperature is safe (< 55°C) +- pulsing red when heating +- solid red when desired temperature is reached +- orange when cooling down + +## Electrical considerations + +WS2812B requires a Vdd between 3.5 and 5.3V and Vih (high level of input signal) must be at least 0.7*Vdd. +Pinecil V2 GPIO levels are 3.3V and the 5V rail is actually max 4.6V. +So we can directly power the WS2812B on the 5V rail and command it with the GPIO without need for a level shifter, or for a Zener diode to clamp Vdd. + +## How to wire it? + +- WS2812B pin 1 (Vdd) is connected to the "5V" rail, e.g. on the C8 capacitor as illustrated [here](https://github.com/Ralim/IronOS/issues/1410#issuecomment-1296064392). +- WS2812B pin 3 (Vss) is connected to the Pinecil GND, e.g. on the U10 pad at the back of the PCB, below R35, as illustrated [here](https://github.com/Ralim/IronOS/issues/1410#issuecomment-1296064392). +- WS2812B pin 4 (Din) is connected to TP10. + +You can use e.g. 0.1-mm enameled wire and isolate connections with UV glue to avoid any shortcut. + +## How to enable it in the code? + +`make firmware-EN model=Pinecilv2 ws2812b_enable=1` diff --git a/Documentation/index.md b/Documentation/index.md index f301f2ec4..a394b6645 100644 --- a/Documentation/index.md +++ b/Documentation/index.md @@ -15,7 +15,7 @@ _This firmware does **NOT** support the USB port while running for changing sett | Device | DC | QC | PD | EPR | BLE | Battery | Recommended | | :--------: | :-: | :-: | :-: | :-: | :-: | :-----: | :---------: | | MHP30 | ❌ | ❌ | ✔️ | ❌ | ❌ | ❌ | ✔️ | -| Pinecil V1 | ✔️ | ✔️ | ✔️ | ❌ | ❌ | ✔️ | ✔️ | +| Pinecil V1 | ✔️ | ✔️ | ✔️ | ❌ | ❌ | ✔️ | ❌ | | Pinecil V2 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | | TS80P | ❌ | ✔️ | ✔️ | ❌ | ❌ | ✔️ | ✔️ | | TS100 | ✔️ | ❌ | ❌ | ❌ | ❌ | ✔️ | ❌ | diff --git a/Env.yml b/Env.yml index 695cd122e..16db291d3 100644 --- a/Env.yml +++ b/Env.yml @@ -1,4 +1,3 @@ -version: "3" name: "ironos" services: builder: diff --git a/Makefile b/Makefile index 042f18367..db08ee493 100644 --- a/Makefile +++ b/Makefile @@ -52,7 +52,7 @@ DOCKER_CMD=$(DOCKER_BIN) -f $(DOCKER_YML) run --rm builder MKDOCS_YML=$(CURDIR)/scripts/IronOS-mkdocs.yml # supported models -MODELS=TS100 TS80 TS80P Pinecil MHP30 Pinecilv2 S60 TS101 # target names & dir names +MODELS=TS100 TS80 TS80P Pinecil MHP30 Pinecilv2 S60 TS101 S60P T55 # target names & dir names MODELS_ML=Pinecil Pinecilv2 # target names MODELS_MULTILANG=Pinecil_multi-lang Pinecilv2_multi-lang # dir names @@ -144,12 +144,12 @@ docs: $(MKDOCS_YML) Documentation/* Documentation/Flashing/* Documentation/im docs-deploy: $(MKDOCS_YML) Documentation/* Documentation/Flashing/* Documentation/images/* $(MKDOCS) gh-deploy -f $(MKDOCS_YML) -d ../site -# routine check for autogenerated Documentation/README.md +# routine check to verify documentation test-md: @echo "" - @echo "---- Checking REAMDE.md... ----" + @echo "---- Checking documentation... ----" @echo "" - @/bin/sh ./scripts/deploy.sh docs_readme + @./scripts/deploy.sh docs # shell style & linter check (github CI version of shellcheck is more recent than alpine one so the latter may not catch some policies) test-sh: @@ -164,7 +164,7 @@ test-py: @echo "---- Checking python code... ----" @echo "" flake8 Translations - black --check Translations + black --diff --check Translations @$(MAKE) -C source/ Objects/host/brieflz/libbrieflz.so ./Translations/brieflz_test.py ./Translations/make_translation_test.py @@ -199,7 +199,7 @@ build-all: # target to build multilang supported builds for Pinecil & PinecilV2 build-multilang: @for modelml in $(MODELS_ML); do \ - $(MAKE) -C source/ -j2 model=$${modelml} firmware-multi_compressed_European firmware-multi_compressed_Bulgarian+Russian+Serbian+Ukrainian firmware-multi_Chinese+Japanese ; \ + $(MAKE) -C source/ -j2 model=$${modelml} firmware-multi_compressed_European firmware-multi_compressed_Belorussian+Bulgarian+Russian+Serbian+Ukrainian firmware-multi_Chinese+Japanese ; \ mkdir -p $(OUT_DIR)/$${modelml}_multi-lang ; \ cp $(OUT_HEX)/$${modelml}_multi_*.bin $(OUT_DIR)/$${modelml}_multi-lang ; \ cp $(OUT_HEX)/$${modelml}_multi_*.hex $(OUT_DIR)/$${modelml}_multi-lang ; \ diff --git a/README.md b/README.md index 4053e3f21..8d582b336 100644 --- a/README.md +++ b/README.md @@ -3,52 +3,59 @@ [![Contributors](https://img.shields.io/github/contributors-anon/ralim/ironos?color=blue&style=flat)](https://github.com/Ralim/IronOS/graphs/contributors) [![Latest Release](https://img.shields.io/github/v/release/ralim/IronOS)](https://github.com/Ralim/IronOS/releases/latest) -# IronOS - Flexible Soldering iron control Firmware +# IronOS - Open Source Flexible Firmware for Soldering Hardware _This repository was formerly known as TS100, it's the same great code. Just with more supported devices._ -Originally conceived as an alternative firmware for the TS100, this firmware has evolved into a complex soldering iron control firmware. +Originally conceived as an alternative firmware for the _TS100_, this firmware has evolved into a complex soldering hardware control firmware. -The firmware implements all of the standard features of a 'smart' soldering iron, with lots of little extras and tweaks. -I highly recommend reading the installation guide fully when installing on your iron. And after install just explore the settings menu. +The firmware implements all of the standard features of a _smart_ soldering hardware, with lots of little extras and tweaks. +I highly recommend reading the installation guide fully when installing on your device. And after install just explore the settings menu. -For soldering irons that are designed to be powered by 'smart' power sources (PD and QC), the firmware supports settings around the negotiated power and voltage. -For soldering irons that are designed to be powered by batteries (TS100 & Pinecil), settings for a cutoff voltage for battery protection are supported. +For soldering hardware that is designed to be powered by _smart_ power sources such as _PD_ or _QC_, the firmware supports settings around the negotiated power and voltage. +For soldering hardware that is designed to be powered by batteries (_TS100_ & _Pinecil_), settings for a cutoff voltage for battery protection are supported. -Currently **31** languages are supported. When downloading the firmware for your soldering iron, take note of the language code in the file name. +Currently **31** languages are supported. When downloading the firmware for your soldering hardware, take note of the _language code_ in the file name. -This project is considered feature complete for use as a soldering iron, _so please suggest any feature improvements you would like!_ +This project is considered feature complete for use on a daily basis, _so please suggest any feature improvements you would like!_ -_This firmware does **NOT** support the USB port while running for changing settings. This is done through the onscreen menu only. Logos are edited on a computer and flashed like firmware._ +_This firmware does **NOT** support the USB port while running for changing settings (this is done through the onscreen menu only). Custom logos are edited on a computer and flashed in the same manner as firmware._ -| Device | DC | QC | PD | EPR | BLE | Tip Sense | Recommended Purchase | Notes | -| :------------: | :-: | :-: | :-: | :-: | :-: | :-----: | :------------------: | :-------------------------------------------:| -| Miniware MHP30 | ❌ | ❌ | ✔️ | ❌ | ❌ | ✔️ | ✔️ | | -| Pinecil V1 | ✔️ | ✔️ | ✔️ | ❌ | ❌ | ❌ | ❌ * | | -| Pinecil V2 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | | -| Miniware TS101 | ✔️ | ❌ | ✔️ | ✔️ | ❌ | ✔️ | ✔️ | Full OLED resolution not yet supported. | -| Sequre S60 | ❌ | ❌ | ✔️ | ❌ | ❌ | ❌ | ✔️ | Full OLED resolution not yet supported. | -| Miniware TS80P | ❌ | ✔️ | ✔️ | ❌ | ❌ | N/A | ✔️ | | -| Miniware TS100 | ✔️ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌** | | -| Miniware TS80 | ❌ | ✔️ | ❌ | ❌ | ❌ | N/A | ❌*** | | +## Supported Hardware -_Tip Sense_ refers to the device being able to choose between the 'usual' TS100 or Hakko T12 style tips and Pine64's custom shorter tips which have lower resistance and allow for more power. This is N/A for TS80/TS80P as there is only one model of tip for them. +| Device | DC | QC | PD | EPR\*\*\*\* | BLE | Tip Sense | Recommended Purchase | Notes | +| :------------: | :-: | :-: | :-: | :-: | :-: | :-------: | :------------------: | :-------------------------------------: | +| Miniware MHP30 | ❌ | ❌ | ✔️ | ❌ | ❌ | ✔️ | ✔️ | | +| Pinecil V1 | ✔️ | ✔️ | ✔️ | ❌ | ❌ | ❌ | ❌ \* | | +| Pinecil V2 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | | +| Miniware TS101 | ✔️ | ❌ | ✔️ | ✔️ | ❌ | ✔️ | ✔️ \*\*\*\*\* | Full OLED resolution not yet supported. | +| Sequre S60 | ❌ | ❌ | ✔️ | ❌ | ❌ | ❌ | ✔️ | Full OLED resolution not yet supported. | +| Sequre S60P | ❌ | ❌ | ✔️ | ❌ | ❌ | ❌ | ✔️ | Full OLED resolution not yet supported. | +| Sequre T55 | ❌ | ❌ | ✔️ | ❌ | ❌ | N/A | ✔️ | Full OLED resolution not yet supported. | +| Miniware TS80P | ❌ | ✔️ | ✔️ | ❌ | ❌ | N/A | ✔️ | | +| Miniware TS100 | ✔️ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌\*\* | | +| Miniware TS80 | ❌ | ✔️ | ❌ | ❌ | ❌ | N/A | ❌\*\*\* | | + +_Tip Sense_ refers to the device being able to choose between the _"regular"_ _TS100_ or _Hakko T12 style_ tips and _Pine64_'s custom shorter tips which have lower resistance and allow for more power. This is N/A for _TS80(P)_ as there is only one model of tip for them. _Recommended Purchase_ is only referring to if you are buying a **new** device. Of course all the devices listed are supported and will work excellently for years to come. -The TS101 and S60 feature a higher resolution OLED than other devices. Work is ongoing to support this fully, for now a cropped view is usable. +The _TS101_ & _S60(P)_ irons and _MHP30_ & _T55_ plates feature a higher resolution OLED than other devices. Work is ongoing to support this fully, for now a cropped view is usable. + +\* _PinecilV1_ stopped being manufactured a long time ago now, all models for sale online are generally clones (or old stock). Vendors are trying to sell these for more than _Pine64_ sells the _V2_ for now. Thus the _V1_ is **_no longer recommended_**. -\*PinecilV1 stopped being manufactured a long time ago now, all models for sale online are generally clones (or old stock). Vendors are trying to sell these for more than Pine64 sells the V2 for now. Thus the V1 is **_no longer recommended_**. +\*\* Please note that _Miniware_ started shipping _TS100_'s using **cloned STM32 chips**. While these do work with _IronOS_, their **DFU bootloader** works terribly, and it is hard to get it to successfully flash larger firmware images like _IronOS_ without timing out. This is the main reason why the _TS100_ is **_no longer recommended_**. -\**Please note that Miniware started shipping TS100's using cloned STM32 Chips. While these do work with IronOS, their DFU bootloader works terribly, and it is hard to get it to successfully flash larger firmware images like IronOS without timing out. This is the main reason why the TS100 is **_no longer recommended_**. +\*\*\* _TS80_ is replaced by _TS80P_. Production ramped down a long time ago and it's just existing stock clearing the system. It's marked not recommended being optimistic that people might pause and buy the far superior _TS80P_ instead. This is the main reason why the _TS80_ is **_no longer recommended_**. -\**\*TS80 is replaced by TS80P. Production ramped down a long time ago and it's just existing stock clearing the system. It's marked not recommended being optimistic that people might pause and buy the far superior TS80P instead. This is the main reason why the TS80 is **_no longer recommended_**. +\*\*\*\* **EPR/PPS with 28V support** is _**disabled by default**_ due to [safety concerns](https://github.com/Ralim/IronOS/pull/2073), but to turn it back on set +_PD Mode_ option in _Power settings_ submenu to _Safe_ or _Default_. + +\*\*\*\*\* Some users confirm that there is a version of newer _TS101_ revision with another OLED screen model, which is not supported yet at all by _IronOS_ unfortunately. See [this bug report](https://github.com/Ralim/IronOS/issues/2063) for more information. ## Getting Started -To get started with IronOS firmware, please jump to [Getting Started Guide](https://ralim.github.io/IronOS/GettingStarted/). -But the [TL;DR](https://www.merriam-webster.com/dictionary/TL%3BDR) is to press the button near the front of the iron to heat up. Use the button near the back of the iron to enter the settings menu. -Long hold the rear button in soldering mode to exit back to the start screen. +To get started with _IronOS firmware_, please jump to [Getting Started Guide](https://ralim.github.io/IronOS/GettingStarted/). ## Installation @@ -60,49 +67,104 @@ For notes on installation for your device, please refer to the flashing guide fo - [TS80 / TS80P](https://ralim.github.io/IronOS/Flashing/TS80%28P%29/) - [TS100](https://ralim.github.io/IronOS/Flashing/TS100) +## Builds + +The links in the table below allow to download available builds directly: +- current _Stable Release_ is **`v2.22`**; +- _Development Build_ **dynamically** provides _**the latest successful build**_ from **`dev`** branch. + +| Device | Stable Release | Development Build | +|:---------------------:|:--------------:|:-----------------:| +| Pinecil V1 | [Pinecil.zip](https://github.com/Ralim/IronOS/releases/download/v2.22/Pinecil.zip) | [Pinecil.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/Pinecil.zip) | +| Pinecil V1/multilang | [Pinecil_multi-lang.zip](https://github.com/Ralim/IronOS/releases/download/v2.22/Pinecil_multi-lang.zip) | [Pinecil_multi-lang.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/Pinecil_multi-lang.zip) | +| Pinecil V2 | [PinecilV2.zip](https://github.com/Ralim/IronOS/releases/download/v2.22/PinecilV2.zip) | [PinecilV2.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/Pinecilv2.zip) | +| Pinecil V2/multilang | [PinecilV2_multi-lang.zip](https://github.com/Ralim/IronOS/releases/download/v2.22/PinecilV2_multi-lang.zip) | [PinecilV2_multi-lang.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/Pinecilv2_multi-lang.zip) | +| Miniware TS100 | [TS100.zip](https://github.com/Ralim/IronOS/releases/download/v2.22/TS100.zip) | [TS100.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/TS100.zip) | +| Miniware TS101 | [TS101.zip](https://github.com/Ralim/IronOS/releases/download/v2.22/TS101.zip) | [TS101.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/TS101.zip) | +| Miniware TS80 | [TS80.zip](https://github.com/Ralim/IronOS/releases/download/v2.22/TS80.zip) | [TS80.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/TS80.zip) | +| Miniware TS80P | [TS80P.zip](https://github.com/Ralim/IronOS/releases/download/v2.22/TS80P.zip) | [TS80P.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/TS80P.zip) | +| Miniware MHP30 | [MHP30.zip](https://github.com/Ralim/IronOS/releases/download/v2.22/MHP30.zip) | [MHP30.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/MHP30.zip) | +| Sequre S60 | [S60.zip](https://github.com/Ralim/IronOS/releases/download/v2.22/S60.zip) | [S60.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/S60.zip) | +| Sequre S60P | Not Released | [S60P.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/S60P.zip) | +| Sequre T55 | Not Released | [T55.zip](https://nightly.link/Ralim/IronOS/workflows/push/dev/T55.zip) | + ## Key Features -- PID style iron temperature control -- Automatic sleep with selectable sensitivity -- Motion wake support -- All settings exposed in the intuitive menu -- (TS100) Set a voltage lower limit for Lithium batteries so you don't kill your battery pack -- (TS80) Set 18 W or 24 W settings for your power bank -- (TS80P) Automatically negotiates appropriate PD and falls back to QC mode like TS80 -- (Pinecil) Supports all 3 power modes (PD, QC, DC In). -- (Pinecilv2) Supports USB-PD EPR for 28V operation. -- Improved readability Fonts, supporting multiple languages -- Use hardware features to improve reliability -- Can disable movement detection if desired -- Boost mode lets you temporarily change the temperature when soldering (i.e. raise the temperature for short periods) -- (TS100/Pinecil) Battery charge level indicator if power source set to a lipo cell count -- (TS80/TS80P/Pinecil) Power bank operating voltage is displayed -- [Custom boot up logo support](https://ralim.github.io/IronOS/Logo/)[^bootlogo] -- Automatic LCD rotation based on the orientation - - -[^bootlogo]: **BOOTUP LOGO NOTICE**: - IronOS supports both a bootup logo _AND_ bootup animations. - However, _**they are no longer included in this repo**_. - **Please, [read the docs](https://ralim.github.io/IronOS/Logo/) for more information**. - -## Menu System - -This new firmware uses a new menu system to allow access to the settings on the device. -When on the main screen and having the tip plugged in, the unit shows a pair of prompts for the two most common operations. - -- Pressing the button near the tip enters the _soldering mode_ -- Pressing the button near the USB end enters the _settings menu_ -- When not in _soldering mode_, holding down the button near the tip will enter _soldering temperature adjust mode_ (This is the same as the one in the _soldering mode_, but allows to adjust the temperature before heating up), in _soldering mode_ however this will activate _boost mode_ as long as you hold down the button. -- Holding down the button near the USB end will show the _[debug menu](https://ralim.github.io/IronOS/DebugMenu/)._ In _soldering mode_ this ends the heating. - -Operation details are over in the [Menu information.](https://ralim.github.io/IronOS/Menu/) +- PID style iron temperature control; +- automatic sleep with selectable sensitivity; +- adjustable & tweakable motion wake support; +- all settings exposed in the intuitive menu; +- (_TS100_) set a voltage lower limit for Lithium batteries so you don't kill your battery pack; +- (_TS80_) set 18W or 24W settings for your power bank; +- (_TS80P_) automatically negotiates appropriate PD and falls back to QC mode like _TS80_; +- (_Pinecil_) supports all 3 power modes (PD, QC, DC In); +- (_Pinecilv2_) supports _USB-PD EPR_ for **28V** operation; +- improved readability Fonts, supporting multiple languages; +- use hardware features to improve reliability; +- boost mode lets you temporarily change the temperature when soldering (i.e. raise the temperature for short periods); +- (_TS100_/_Pinecil_) battery charge level indicator if power source set to a LiPo cell count; +- (_TS80_/_TS80P_/_Pinecil_) power bank operating voltage is displayed; +- [custom boot up logo support](https://ralim.github.io/IronOS/Logo/)[^bootlogo]; +- automatic LCD rotation based on the orientation; +- ... and many many other cool & hackable features![^changelog] + +[^bootlogo]: + **BOOTUP LOGO NOTICE**: + IronOS supports both a bootup logo _AND_ bootup animations. + However, _**they are no longer included in this repo**_. + **Please, [read the docs](https://ralim.github.io/IronOS/Logo/) for more information**. + +[^changelog]: + [See the full changelog here](https://ralim.github.io/IronOS/History). + +## Basic Control + +Supported device is controlled by two buttons which can be pressed in the following ways: + - short: ~1 second or so; + - long: more than 1 second; + - both (press & hold both of them together). + +Available buttons are: + - `+/A` button: near the front closer to the tip (for irons) or on the left side of the device (for plates); + - `-/B` button: near the back far from the tip (for irons) or on the right side of the device (for plates). + +After powering on the device for the first time with _IronOS_ installed and having the tip/plate plugged in, on the main menu in _standby mode_ the unit shows a pair of prompts for the two most common operations: +- pressing the `+/A` button enters the _soldering mode_; +- pressing the `-/B` button enters the _settings menu_; +- in _soldering mode_: + - short press of `+/A` / `-/B` buttons changes the soldering temperature; + - long press of the `+/A` button enables _boost mode_ (increasing soldering temperature to the adjustable setting as long as the button is pressed); + - long press of the `-/B` button enters _standby mode_ and stops heating; +- in _standby mode_: + - long press of the `+/A` button enters _soldering temperature adjust mode_ (the same as the one in the _soldering mode_, but allows to adjust the temperature before heating up); + - long hold of the `-/B` button enters the [_debug menu_](https://ralim.github.io/IronOS/DebugMenu/); +- in _menu mode_ (to make it short here): + - `-/B` scrolls & cycles through menus and submenus; + - `+/A` enters to menu & submenu settings or changes their values if they are activated already. + +Additional details are described in the [menu information](https://ralim.github.io/IronOS/Menu/). + +## Remote Control + +### Pinecil V2 only + +Pinecil V2 has [_Bluetooth Low Energy_ module](https://ralim.github.io/IronOS/Bluetooth), which is supported by _IronOS_ since `2.21` release to control some of the settings using additional tools like [PineSAM](https://github.com/builder555/PineSAM) or [PineTool](https://github.com/lachlanbell/PineTool). In `2.21` and `2.22` releases the module was _on_ by default. However, **_Bluetooth_ is turned off in the settings by default in current `dev` builds and for the next releases** [due to security concerns](#1856).[^ble] + +To enable _Bluetooth_ back: +- go to _Settings_ menu; +- press `-/B` button four times to scroll the menu for `Advanced settings`; +- press `+/A` button to open submenu; +- press `+/A` button to toggle/enable _Bluetooth_ feature; +- press `-/B` **and hold it** for just more than five seconds to exit from the _Settings_ menu. + +[^ble]: + This is related only to situations when a user restores default settings using menu, or when _IronOS_ update is taking place on a new device or on a device with a previous firmware version. ## Translations Is your preferred language missing localisation of some of the text? -Translations are stored as `json` files in the Translations folder. -PR's are loved and accepted to enhance the firmware. +Translations are stored as `json` files in the `Translations` folder. +_Pull requests_ are loved and accepted to enhance the firmware. ## Thanks @@ -127,13 +189,13 @@ Especially to the following users, who have helped in various ways that are mass Plus the huge number of people who have contributed translations, your effort is massively appreciated. -## Licence +## License -The code created by the community is GNU GPLv3. Unless noted elsewhere. -Other components such as FreeRTOS/USB-PD have their own licence. +The code created by the community is covered by the [GNU GPLv3](https://www.gnu.org/licenses/gpl-3.0.html#license-text) license **unless noted elsewhere**. +Other components such as _FreeRTOS_ and _USB-PD_ have their own licenses. ## Commercial Use -This software is provided as-is, so I cannot provide any commercial support for the firmware. -However, you are more than welcome to distribute links to the firmware or provide irons with this software on them. -Please do not re-host the files, but rather link to this page, so that there are no old versions of the firmware scattered around. +This software is provided _**"AS IS"**_, so I cannot provide any commercial support for the firmware. +However, you are more than welcome to distribute links to the firmware or provide hardware with this firmware. +**Please do not re-host the files, but rather link to this page, so that there are no old versions of the firmware scattered around**. diff --git a/Translations/gen_menu_docs.py b/Translations/gen_menu_docs.py index 5bc8222e7..aa705bfe9 100755 --- a/Translations/gen_menu_docs.py +++ b/Translations/gen_menu_docs.py @@ -51,7 +51,7 @@ def write_menu_categories(filep, defs, translation_data): for menu in defs.get("menuGroups", {}): menu_id = menu.get("id", "") entry = translation_data.get("menuGroups", {}).get(menu_id, "") - name = " ".join(entry.get("text2", [])) + name = " ".join(entry.get("displayText").split("\n")) desc = menu.get("description", "") section = f""" ### Category: {name} @@ -80,9 +80,9 @@ def write_menu_entries(filep, defs, translation_data): for menu in defs.get("menuOptions", {}): menu_id = menu.get("id", "") entry = translation_data.get("menuOptions", {}).get(menu_id, "") - name = " ".join(entry.get("text2", [])) + name = " ".join(entry.get("displayText").split("\n")) desc = menu.get("description", "") - on_device_desc = entry.get("desc", "") + on_device_desc = entry.get("description", "") section = f""" ### Setting: {name} @@ -99,8 +99,8 @@ def main() -> None: json_dir = HERE print(json_dir) logging.info("Loading translation definitions") - defs = load_json(TRANSLATION_DEFS_PATH) - eng_translation = load_json(ENGLISH_TRANSLATION_PATH) + defs = load_json(TRANSLATION_DEFS_PATH, False) + eng_translation = load_json(ENGLISH_TRANSLATION_PATH, False) with open(MENU_DOCS_FILE_PATH, "w") as outputf: write_header(outputf) write_menu_categories(outputf, defs, eng_translation) diff --git a/Translations/make_translation.py b/Translations/make_translation.py index 752deaf62..55045c95a 100755 --- a/Translations/make_translation.py +++ b/Translations/make_translation.py @@ -10,7 +10,7 @@ import re import subprocess import sys -from datetime import datetime +import time from pathlib import Path from typing import Dict, List, Optional, TextIO, Tuple, Union from dataclasses import dataclass @@ -76,13 +76,13 @@ def check_excluded(record): return False - for category in ("menuOptions", "menuGroups"): - for index, record in enumerate(defs[category]): + for category in ("menuOptions", "menuGroups", "menuValues"): + for _, record in enumerate(defs[category]): if check_excluded(record): lang[category][record["id"]]["displayText"] = "" lang[category][record["id"]]["description"] = "" - for index, record in enumerate(defs["messagesWarn"]): + for _, record in enumerate(defs["messagesWarn"]): if check_excluded(record): lang["messagesWarn"][record["id"]]["message"] = "" @@ -146,12 +146,16 @@ def get_constants() -> List[Tuple[str, str]]: ("SmallSymbolState", "State"), ("SmallSymbolNoVBus", "No VBus"), ("SmallSymbolVBus", "VBus"), + ("LargeSymbolSleep", "Zzz "), ] def get_debug_menu() -> List[str]: return [ - datetime.today().strftime("%d-%m-%y"), + time.strftime( + "%Y%m%d %H%M%S", + time.gmtime(int(os.environ.get("SOURCE_DATE_EPOCH", time.time()))), + ), "ID ", "ACC ", "PWR ", @@ -202,9 +206,9 @@ def get_letter_counts(defs: dict, lang: dict, build_version: str) -> Dict: """From the source definitions, language file and build version; calculates the ranked symbol list Args: - defs (dict): _description_ - lang (dict): _description_ - build_version (str): _description_ + defs (dict): Definitions + lang (dict): Language lookup + build_version (str): The build version id to ensure its letters are included Returns: Dict: _description_ @@ -248,6 +252,15 @@ def get_letter_counts(defs: dict, lang: dict, build_version: str) -> Dict: msg = obj[eid]["description"] big_font_messages.append(msg) + obj = lang["menuValues"] + for mod in defs["menuValues"]: + eid = mod["id"] + msg = obj[eid]["displayText"] + if test_is_small_font(msg): + small_font_messages.append(msg) + else: + big_font_messages.append(msg) + obj = lang["menuGroups"] for mod in defs["menuGroups"]: eid = mod["id"] @@ -619,7 +632,7 @@ def make_font_table_named_cpp( if name: output_table = f"const uint8_t {name}[] = {{\n" for i, sym in enumerate(sym_list): - output_table += f"{bytes_to_c_hex(font_map[sym])}//0x{i+2:X} -> {sym}\n" + output_table += f"{bytes_to_c_hex(font_map[sym])}//0x{i + 2:X} -> {sym}\n" if name: output_table += f"}}; // {name}\n" return output_table @@ -633,7 +646,7 @@ def make_font_table_06_cpp(sym_list: List[str], font_map: FontMapsPerFont) -> st font_line = bytes_to_c_hex(font_bytes) else: font_line = "// " # placeholder - output_table += f"{font_line}//0x{i+2:X} -> {sym}\n" + output_table += f"{font_line}//0x{i + 2:X} -> {sym}\n" output_table += "};\n" return output_table @@ -985,7 +998,7 @@ def write_languages( f.write("};\n") f.write( "const uint8_t LanguageCount = sizeof(LanguageMetas) / sizeof(LanguageMetas[0]);\n\n" - f"alignas(TranslationData) uint8_t translation_data_out_buffer[{max_decompressed_translation_size }];\n" + f"alignas(TranslationData) uint8_t translation_data_out_buffer[{max_decompressed_translation_size}];\n" "const uint16_t translation_data_out_buffer_size = sizeof(translation_data_out_buffer);\n\n" ) @@ -1113,6 +1126,12 @@ def encode_string_and_add( encode_string_and_add( lang_data["displayText"], "menuOptions" + record["id"] + "displayText" ) + for index, record in enumerate(defs["menuValues"]): + lang_data = lang["menuValues"][record["id"]] + # Add to translations the menu text and the description + encode_string_and_add( + lang_data["displayText"], "menuValues" + record["id"] + "displayText" + ) for index, record in enumerate(defs["menuGroups"]): lang_data = lang["menuGroups"][record["id"]] @@ -1200,6 +1219,21 @@ def encode_string_and_add( f" .{record['id']} = {start_index}, // {escape(lang_data)}\n" ) + for _, record in enumerate(defs["menuValues"]): + # Add to translations the menu text and the description + lang_data = lang["menuValues"][record["id"]] + key = "menuValues" + record["id"] + "displayText" + translated_index = translated_string_lookups[key] + string_index = translated_index.byte_encoded_translation_index + start_index = ( + string_index_commulative_lengths[string_index] + + translated_index.str_start_offset + ) + + translation_indices_text += ( + f" .{record['id']} = {start_index}, // {escape(lang_data)}\n" + ) + translation_indices_text += "\n" # Now for the fun ones, where they are nested and ordered @@ -1229,6 +1263,7 @@ def write_grouped_indexes(output_text: str, name: str, mainKey: str, subKey: str translation_indices_text = write_grouped_indexes( translation_indices_text, "SettingsShortNames", "menuOptions", "displayText" ) + translation_indices_text = write_grouped_indexes( translation_indices_text, "SettingsMenuEntriesDescriptions", diff --git a/Translations/translation_BE.json b/Translations/translation_BE.json index 300390093..8868ad4a4 100644 --- a/Translations/translation_BE.json +++ b/Translations/translation_BE.json @@ -1,319 +1,351 @@ { - "languageCode": "BE", - "languageLocalName": "Беларуская", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Каліброўка\nзроблена!" - }, - "ResetOKMessage": { - "message": "Скід OK" - }, - "SettingsResetMessage": { - "message": "Налады\nзкінуты!" - }, - "NoAccelerometerMessage": { - "message": "Ня вызначаны\nакселерометр!" - }, - "NoPowerDeliveryMessage": { - "message": "Няма USB-PD IC\nвыяўлены!" - }, - "LockingKeysString": { - "message": "ЗАМКНУТЫ" - }, - "UnlockingKeysString": { - "message": "АДЫМКНУТЫ" - }, - "WarningKeysLockedString": { - "message": "!ЗАМКНУТЫ!" - }, - "WarningThermalRunaway": { - "message": "Некантралюемае\nразаграванне" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Пераканайцеся, што пры наступнай загрузцы наканечнік і ручка маюць пакаёвую тэмпературу!" - }, - "CJCCalibrating": { - "message": "каліброўка\n" - }, - "SettingsResetWarning": { - "message": "Вы ўпэннены, што жадаеце зкінуць налады да першапачатковых значэнняў?" - }, - "UVLOWarningString": { - "message": "НАПРУГА--" - }, - "UndervoltageString": { - "message": "Нізкая напруга\n" - }, - "InputVoltageString": { - "message": "Сілкаванне В: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Чаканне...\n" - }, - "SleepingTipAdvancedString": { - "message": "Джала: \n" - }, - "OffString": { - "message": "Выкл." - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Ваша прылада, хутчэй за ўсё, падробка!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "П", - "SettingLeftChar": "Л", - "SettingAutoChar": "А", - "SettingOffChar": "O", - "SettingSlowChar": "М", - "SettingMediumChar": "С", - "SettingFastChar": "Х", - "SettingStartNoneChar": "В", - "SettingStartSolderingChar": "П", - "SettingStartSleepChar": "Ч", - "SettingStartSleepOffChar": "К", - "SettingLockDisableChar": "А", - "SettingLockBoostChar": "Т", - "SettingLockFullChar": "П" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Налады\nсілкавання", - "description": "" - }, - "SolderingMenu": { - "displayText": "Налады\nпайкі", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Рэжымы\nсну", - "description": "" - }, - "UIMenu": { - "displayText": "Налады\nінтэрфейсу", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Дадатковыя\nналады", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Крыніца\nсілкавання", - "description": "Крыніца сілкавання. Усталюе напругу адсечкі. (DC 10В) (S 3,3В на ячэйку, без абмежавання магутнасці)" - }, - "MinVolCell": { - "displayText": "Мін.\nнапр.", - "description": "Мінімальная дазволеная напруга на ячэйку (3S: 3 - 3,7V | 4S: 2,4 - 3,7V)" - }, - "QCMaxVoltage": { - "displayText": "Магутнасць\nсілкавання", - "description": "Магутнасць выкарыстоўваемай крыніцы сілкавання" - }, - "PDNegTimeout": { - "displayText": "PD\nпрыпынак", - "description": "Час чакання ўзгаднення PD з крокам 100 мс для сумяшчальнасці з некаторымі зараднымі зараднымі прыладамі QC (0: адключана)" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Уключае рэжымы PPS & EPR." - }, - "BoostTemperature": { - "displayText": "t° турба\nрэжыму", - "description": "Тэмпература джала ў турба-рэжыме" - }, - "AutoStart": { - "displayText": "Аўта\nстарт", - "description": "Рэжым, у якім запускаецца паяльнік пры падачы сілкавання (В=Выкл. | П=Пайка | Ч=Чаканне | К=Чаканне пры комн. тэмп.)" - }, - "TempChangeShortStep": { - "displayText": "Крок тэмп.\nкар. нац.", - "description": "Крок вымярэння тэмпературы пры кароткім націску кнопак" - }, - "TempChangeLongStep": { - "displayText": "Крок тэмп.\nпад. нац.", - "description": "Крок вымярэння тэмпературы пры падоўжаным націску кнопак" - }, - "LockingMode": { - "displayText": "Дазволіць\nблок. кнопак", - "description": "Пры рабоце падоўжаны націск дзьвух кнопак блакуе іх (А=Адключана | Т=Толькі турба | П=Поўная блакіроўка)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Адчувальнасць\nакселерометра", - "description": "Адчувальнасць акселерометра (0=Выкл. | 1=Мін. | ... | 9=Макс.)" - }, - "SleepTemperature": { - "displayText": "Тэмп.\nчакання", - "description": "Тэмпература рэжыму чакання" - }, - "SleepTimeout": { - "displayText": "Таймаўт\nчакання", - "description": "Час да пераходу ў рэжым чакання (Хвіліны | Секунды)" - }, - "ShutdownTimeout": { - "displayText": "Таймаут\nвыключэння", - "description": "Час да адключэння паяльніка (Хвіліны)" - }, - "HallEffSensitivity": { - "displayText": "Эфект Хола\nадчувальнасць", - "description": "Узровень адчувальнасці датчыка хола ў рэжыме сну (0=Выкл. | 1=Мін. | ... | 9=Макс.)" - }, - "TemperatureUnit": { - "displayText": "Адзінкі\nтэмпературы", - "description": "Адзінкі вымярэння тэмпературы (C=Цэльcія | F=Фарэнгейта)" - }, - "DisplayRotation": { - "displayText": "Арыентацыя\nэкрану", - "description": "Арыентацыя экрану (П=Правая рука | Л=Левая рука | А=Аўта)" - }, - "CooldownBlink": { - "displayText": "Мігценне t°\nпры астуджэнні", - "description": "Міргаць тэмпературай на экране астуджэння, пакуль джала яшчэ гарачае" - }, - "ScrollingSpeed": { - "displayText": "Хуткацсь\nтексту", - "description": "Хуткасць гартання тэксту (М=марудна | Х=хутка)" - }, - "ReverseButtonTempChange": { - "displayText": "Інвертаваць\nкнопкі", - "description": "Інвертаваць кнопкі вымярэння тэмпературы" - }, - "AnimSpeed": { - "displayText": "Хуткасць\nанімацыі", - "description": "Хуткасць анімацыі гузікаў у галоўным меню (Мілісекунды) (А=Адключана | Н=Нізкая | С=Сярэдняя | В=Высокая)" - }, - "AnimLoop": { - "displayText": "Зацыкленая\nанімацыя", - "description": "Зацыкленая анімацыя гузікаў у галоўным меню" - }, - "Brightness": { - "displayText": "Экран\nЯркасць", - "description": "Адрэгулюйце кантраснасць / яркасць OLED-экрана" - }, - "ColourInversion": { - "displayText": "Экран\nІнвертаваць", - "description": "Інвертаваць колеры OLED-экрана" - }, - "LOGOTime": { - "displayText": "Лагатып загрузкі\nпрацягласць", - "description": "Усталяваць працягласць лагатыпа загрузкі (s=Секунды)" - }, - "AdvancedIdle": { - "displayText": "Падрабязны\nрэжым чакання", - "description": "Адлюстроўваць дэталёвую инфармацыю паменьшаным шрыфтом на экране чакання" - }, - "AdvancedSoldering": { - "displayText": "Падрабязны\nэкран пайкі", - "description": "Паказваць дэталёвую інформацыю на экране пайкі" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Межы\nмагутнасці", - "description": "Максімальная магутнасць, якую можа выкарыстоўваць паяльнік (Ватт)" - }, - "CalibrateCJC": { - "displayText": "Каліброўка тэмпературы\nпры наступнай загрузцы", - "description": "Каліброўка тэмпературы пры наступным уключэнні (не патрабуецца, калі розніца тэмператур меньш за 5°C)" - }, - "VoltageCalibration": { - "displayText": "Каліброўка\nнапругі", - "description": "Каліброўка ўваходнай напругі (падоўжаны націск для выхаду)" - }, - "PowerPulsePower": { - "displayText": "Сіла імп.\nсілкав. Вт", - "description": "Моц імпульса ўтрымливаючага ад сну павербанку ці іншай крыніцы сілкавання" - }, - "PowerPulseWait": { - "displayText": "Імпульс магутнасці\nчас чакання", - "description": "Час чакання перад запускам кожнага імпульсу няспання (x 2.5 с)" - }, - "PowerPulseDuration": { - "displayText": "Імпульс магутнасці\nпрацягласць", - "description": "Працягласць імпульсу няспання (x 250 мс)" - }, - "SettingsReset": { - "displayText": "Скід\nналадаў", - "description": "Скід наладаў да першапачатковых значэнняў" - }, - "LanguageSwitch": { - "displayText": "Мова:\n BY Беларуская", - "description": "" - } + "languageCode": "BE", + "languageLocalName": "Беларуская", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Каліброўка\nзроблена!" + }, + "ResetOKMessage": { + "message": "Скід OK" + }, + "SettingsResetMessage": { + "message": "Налады\nзкінуты!" + }, + "NoAccelerometerMessage": { + "message": "Ня вызначаны\nакселерометр!" + }, + "NoPowerDeliveryMessage": { + "message": "Няма USB-PD IC\nвыяўлены!" + }, + "LockingKeysString": { + "message": "ЗАМКНУТЫ" + }, + "UnlockingKeysString": { + "message": "АДЫМКНУТЫ" + }, + "WarningKeysLockedString": { + "message": "!ЗАМКНУТЫ!" + }, + "WarningThermalRunaway": { + "message": "Некантралюемае\nразаграванне" + }, + "WarningTipShorted": { + "message": "!Кароткае замыканне на джале!" + }, + "SettingsCalibrationWarning": { + "message": "Пераканайцеся, што пры наступнай загрузцы наканечнік і ручка маюць пакаёвую тэмпературу!" + }, + "CJCCalibrating": { + "message": "каліброўка\n" + }, + "SettingsResetWarning": { + "message": "Вы ўпэннены, што жадаеце зкінуць налады да першапачатковых значэнняў?" + }, + "UVLOWarningString": { + "message": "НАПРУГА--" + }, + "UndervoltageString": { + "message": "Нізкая напруга\n" + }, + "InputVoltageString": { + "message": "Сілкаванне В: \n" + }, + "SleepingAdvancedString": { + "message": "Чаканне...\n" + }, + "SleepingTipAdvancedString": { + "message": "Джала: \n" + }, + "ProfilePreheatString": { + "message": "Разагрэць\n" + }, + "ProfileCooldownString": { + "message": "Астудзіць\n" + }, + "DeviceFailedValidationWarning": { + "message": "Ваша прылада, хутчэй за ўсё, падробка!" + }, + "TooHotToStartProfileWarning": { + "message": "Занадта горача\nкаб запусціць профіль" + } + }, + "characters": { + "SettingRightChar": "П", + "SettingLeftChar": "Л", + "SettingAutoChar": "А", + "SettingSlowChar": "М", + "SettingMediumChar": "С", + "SettingFastChar": "Х", + "SettingStartSolderingChar": "П", + "SettingStartSleepChar": "Ч", + "SettingStartSleepOffChar": "К", + "SettingLockBoostChar": "Т", + "SettingLockFullChar": "П" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Налады\nсілкавання", + "description": "" + }, + "SolderingMenu": { + "displayText": "Налады\nпайкі", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Рэжымы\nсну", + "description": "" + }, + "UIMenu": { + "displayText": "Налады\nінтэрфейсу", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Дадатковыя\nналады", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "\nРэжым" + }, + "USBPDModeNoDynamic": { + "displayText": "Няма\nдынамікі" + }, + "USBPDModeSafe": { + "displayText": "Бяспечны\nрэжым" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Крыніца\nсілкавання", + "description": "Крыніца сілкавання. Усталюе напругу адсечкі. (DC 10В) (S 3,3В на ячэйку, без абмежавання магутнасці)" + }, + "MinVolCell": { + "displayText": "Мін.\nнапр.", + "description": "Мінімальная дазволеная напруга на ячэйку (3S: 3 - 3,7V | 4S: 2,4 - 3,7V)" + }, + "QCMaxVoltage": { + "displayText": "Магутнасць\nсілкавання", + "description": "Магутнасць выкарыстоўваемай крыніцы сілкавання" + }, + "PDNegTimeout": { + "displayText": "PD\nпрыпынак", + "description": "Час чакання ўзгаднення PD з крокам 100 мс для сумяшчальнасці з некаторымі зараднымі зараднымі прыладамі QC (0: адключана)" + }, + "USBPDMode": { + "displayText": "PD\nРэжым", + "description": "Уключае рэжымы PPS & EPR." + }, + "BoostTemperature": { + "displayText": "t° турба\nрэжыму", + "description": "Тэмпература джала ў турба-рэжыме" + }, + "AutoStart": { + "displayText": "Аўта\nстарт", + "description": "Рэжым, у якім запускаецца паяльнік пры падачы сілкавання (П=Пайка | Ч=Чаканне | К=Чаканне пры комн. тэмп.)" + }, + "TempChangeShortStep": { + "displayText": "Крок тэмп.\nкар. нац.", + "description": "Крок вымярэння тэмпературы пры кароткім націску кнопак" + }, + "TempChangeLongStep": { + "displayText": "Крок тэмп.\nпад. нац.", + "description": "Крок вымярэння тэмпературы пры падоўжаным націску кнопак" + }, + "LockingMode": { + "displayText": "Дазволіць\nблок. кнопак", + "description": "Пры рабоце падоўжаны націск дзьвух кнопак блакуе іх (Т=Толькі турба | П=Поўная блакіроўка)" + }, + "ProfilePhases": { + "displayText": "Фазы\nпрофілю", + "description": "Колькасць фаз у рэжыме профілю" + }, + "ProfilePreheatTemp": { + "displayText": "Тэмпература\nразагравання", + "description": "Разагрэйце да гэтай тэмпературы ў пачатку профільнага рэжыму" + }, + "ProfilePreheatSpeed": { + "displayText": "Хуткасть\nразагравання", + "description": "Разагрэйце з гэтай хуткасцю (градусы ў секунду)" + }, + "ProfilePhase1Temp": { + "displayText": "Фаза 1\nтэмпература", + "description": "Мэтавая тэмпература ў канцы гэтай фазы" + }, + "ProfilePhase1Duration": { + "displayText": "Фаза 1\nпрацягласць", + "description": "Мэтавая працягласць гэтай фазы (секунды)" + }, + "ProfilePhase2Temp": { + "displayText": "Фаза 2\nтэмпература", + "description": "Мэтавая тэмпература ў канцы гэтай фазы" + }, + "ProfilePhase2Duration": { + "displayText": "Фаза 2\nпрацягласць", + "description": "Мэтавая працягласць гэтай фазы (секунды)" + }, + "ProfilePhase3Temp": { + "displayText": "Фаза 3\nтэмпература", + "description": "Мэтавая тэмпература ў канцы гэтай фазы" + }, + "ProfilePhase3Duration": { + "displayText": "Фаза 3\nпрацягласць", + "description": "Мэтавая працягласць гэтай фазы (секунды)" + }, + "ProfilePhase4Temp": { + "displayText": "Фаза 4\nтэмпература", + "description": "Мэтавая тэмпература ў канцы гэтай фазы" + }, + "ProfilePhase4Duration": { + "displayText": "Фаза 4\nпрацягласць", + "description": "Мэтавая працягласць гэтай фазы (секунды)" + }, + "ProfilePhase5Temp": { + "displayText": "Фаза 5\nтэмпература", + "description": "Мэтавая тэмпература ў канцы гэтай фазы" + }, + "ProfilePhase5Duration": { + "displayText": "Фаза 5\nпрацягласць", + "description": "Мэтавая працягласць гэтай фазы (секунды)" + }, + "ProfileCooldownSpeed": { + "displayText": "Хуткасць\nастывання", + "description": "Астуджаць з гэтай хуткасцю ў канцы профільнага рэжыму (градусы ў секунду)" + }, + "MotionSensitivity": { + "displayText": "Адчувальнасць\nакселерометра", + "description": "Адчувальнасць акселерометра (1=Мін. | ... | 9=Макс.)" + }, + "SleepTemperature": { + "displayText": "Тэмп.\nчакання", + "description": "Тэмпература рэжыму чакання" + }, + "SleepTimeout": { + "displayText": "Таймаўт\nчакання", + "description": "Час да пераходу ў рэжым чакання (Хвіліны | Секунды)" + }, + "ShutdownTimeout": { + "displayText": "Таймаут\nвыключэння", + "description": "Час да адключэння паяльніка (Хвіліны)" + }, + "HallEffSensitivity": { + "displayText": "Эфект Хола\nадчувальнасць", + "description": "Узровень адчувальнасці датчыка хола ў рэжыме сну (1=Мін. | ... | 9=Макс.)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Інтэрвал перад пачаткам \"рэжыму сну\", калі эфект Хола перавышае парог" + }, + "TemperatureUnit": { + "displayText": "Адзінкі\nтэмпературы", + "description": "Адзінкі вымярэння тэмпературы (C=Цэльcія | F=Фарэнгейта)" + }, + "DisplayRotation": { + "displayText": "Арыентацыя\nэкрану", + "description": "Арыентацыя экрану (П=Правая рука | Л=Левая рука | А=Аўта)" + }, + "CooldownBlink": { + "displayText": "Мігценне t°\nпры астуджэнні", + "description": "Міргаць тэмпературай на экране астуджэння, пакуль джала яшчэ гарачае" + }, + "ScrollingSpeed": { + "displayText": "Хуткацсь\nтексту", + "description": "Хуткасць гартання тэксту (М=марудна | Х=хутка)" + }, + "ReverseButtonTempChange": { + "displayText": "Інвертаваць\nкнопкі", + "description": "Інвертаваць кнопкі вымярэння тэмпературы" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Хуткасць\nанімацыі", + "description": "Хуткасць анімацыі гузікаў у галоўным меню (Мілісекунды) (Н=Нізкая | С=Сярэдняя | В=Высокая)" + }, + "AnimLoop": { + "displayText": "Зацыкленая\nанімацыя", + "description": "Зацыкленая анімацыя гузікаў у галоўным меню" + }, + "Brightness": { + "displayText": "Экран\nЯркасць", + "description": "Адрэгулюйце кантраснасць / яркасць OLED-экрана" + }, + "ColourInversion": { + "displayText": "Экран\nІнвертаваць", + "description": "Інвертаваць колеры OLED-экрана" + }, + "LOGOTime": { + "displayText": "Лагатып загрузкі\nпрацягласць", + "description": "Усталяваць працягласць лагатыпа загрузкі (s=Секунды)" + }, + "AdvancedIdle": { + "displayText": "Падрабязны\nрэжым чакання", + "description": "Адлюстроўваць дэталёвую инфармацыю паменьшаным шрыфтом на экране чакання" + }, + "AdvancedSoldering": { + "displayText": "Падрабязны\nэкран пайкі", + "description": "Паказваць дэталёвую інформацыю на экране пайкі" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Уключыць BLE" + }, + "PowerLimit": { + "displayText": "Межы\nмагутнасці", + "description": "Максімальная магутнасць, якую можа выкарыстоўваць паяльнік (Ватт)" + }, + "CalibrateCJC": { + "displayText": "Каліброўка тэмпературы\nпры наступнай загрузцы", + "description": "Каліброўка тэмпературы пры наступным уключэнні (не патрабуецца, калі розніца тэмператур меньш за 5°C)" + }, + "VoltageCalibration": { + "displayText": "Каліброўка\nнапругі", + "description": "Каліброўка ўваходнай напругі (падоўжаны націск для выхаду)" + }, + "PowerPulsePower": { + "displayText": "Сіла імп.\nсілкав. Вт", + "description": "Моц імпульса ўтрымливаючага ад сну павербанку ці іншай крыніцы сілкавання" + }, + "PowerPulseWait": { + "displayText": "Імпульс магутнасці\nчас чакання", + "description": "Час чакання перад запускам кожнага імпульсу няспання (x 2.5 с)" + }, + "PowerPulseDuration": { + "displayText": "Імпульс магутнасці\nпрацягласць", + "description": "Працягласць імпульсу няспання (x 250 мс)" + }, + "SettingsReset": { + "displayText": "Скід\nналадаў", + "description": "Скід наладаў да першапачатковых значэнняў" + }, + "LanguageSwitch": { + "displayText": "Мова:\n BY Беларуская", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } -} \ No newline at end of file + } +} diff --git a/Translations/translation_BG.json b/Translations/translation_BG.json index 498847b8c..e734ac908 100644 --- a/Translations/translation_BG.json +++ b/Translations/translation_BG.json @@ -1,319 +1,351 @@ { - "languageCode": "BG", - "languageLocalName": "Български", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Калибрирането\nе завършено!" - }, - "ResetOKMessage": { - "message": "Нулиране" - }, - "SettingsResetMessage": { - "message": "Настройките бяха\nнулирани!" - }, - "NoAccelerometerMessage": { - "message": "Не е открит\nакселерометър!" - }, - "NoPowerDeliveryMessage": { - "message": "Не е открито\nUSB-PD захранване!" - }, - "LockingKeysString": { - "message": "ЗАКЛЮЧ" - }, - "UnlockingKeysString": { - "message": "ОТКЛЮЧ" - }, - "WarningKeysLockedString": { - "message": "!ЗАКЛЮЧ!" - }, - "WarningThermalRunaway": { - "message": "Неконтролируемо\nпрегряване" - }, - "WarningTipShorted": { - "message": "!КС на човка!" - }, - "SettingsCalibrationWarning": { - "message": "Преди рестартиране се уверете, че човка и дръжката са на стайна температурата!" - }, - "CJCCalibrating": { - "message": "калибриране\n" - }, - "SettingsResetWarning": { - "message": "Сигурни ли сте, че искате да върнете фабричните настройки?" - }, - "UVLOWarningString": { - "message": "НИС.НАПР." - }, - "UndervoltageString": { - "message": "Ниско напрежение\n" - }, - "InputVoltageString": { - "message": "Входно V: \n" - }, - "SleepingSimpleString": { - "message": "Хъррр" - }, - "SleepingAdvancedString": { - "message": "Сън...\n" - }, - "SleepingTipAdvancedString": { - "message": "Човка:\n" - }, - "OffString": { - "message": "Изкл." - }, - "ProfilePreheatString": { - "message": "Загряване\n" - }, - "ProfileCooldownString": { - "message": "Охлаждане\n" - }, - "DeviceFailedValidationWarning": { - "message": "Вероятно, устройство е фалшификат!" - }, - "TooHotToStartProfileWarning": { - "message": "Твърде горещо за\nстартиране на профила" - } - }, - "characters": { - "SettingRightChar": "Д", - "SettingLeftChar": "Л", - "SettingAutoChar": "А", - "SettingOffChar": "И", - "SettingSlowChar": "Н", - "SettingMediumChar": "С", - "SettingFastChar": "В", - "SettingStartNoneChar": "И", - "SettingStartSolderingChar": "З", - "SettingStartSleepChar": "С", - "SettingStartSleepOffChar": "П", - "SettingLockDisableChar": "И", - "SettingLockBoostChar": "Т", - "SettingLockFullChar": "П" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Настройки на\nзахранването", - "description": "" - }, - "SolderingMenu": { - "displayText": "Настройки на\nзапояване", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Авто\nизключване", - "description": "" - }, - "UIMenu": { - "displayText": "Интерфейс\n", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Допълнителни\nнастройки", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Гранично\nнапрежение", - "description": "Минимално напрежение, за да не се изтощи батерията (DC 10V) (S 3,3V за клетка)" - }, - "MinVolCell": { - "displayText": "Мин.\nнапрежение", - "description": "Минимално допустимо напрежение на акумулаторна клетка (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" - }, - "QCMaxVoltage": { - "displayText": "Напреж.\nна QC", - "description": "Максимална напрежение с QC захранвания" - }, - "PDNegTimeout": { - "displayText": "PD\nинтервал", - "description": "PD интервал за договаряне на захранването на стъпки от 100 мс за съвместимост с някои QC захранвания (0=Изкл.)" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Включи PPS & EPR" - }, - "BoostTemperature": { - "displayText": "Турбо\nтемп.", - "description": "Температурата за \"турбо\" режим" - }, - "AutoStart": { - "displayText": "Автоматичен\nработен режим", - "description": "Режим на поялника при включване на захранването (И=Изкл. | З=Запояване | С=Сън | П=Покой на стайна температурата)" - }, - "TempChangeShortStep": { - "displayText": "Промяна T\nбързо", - "description": "Промяна на температурата при бързо натискане на бутон" - }, - "TempChangeLongStep": { - "displayText": "Промяна Т\nзадържане", - "description": "Промяна на температурата при задържане на бутон" - }, - "LockingMode": { - "displayText": "Бутони за\nзаключване", - "description": "Докато запоявате, задръжте двата бутона, за да превключите заключването им (И=Изкл. | Т=Турбо режим | П=Пълно)" - }, - "ProfilePhases": { - "displayText": "Брой\nетапи", - "description": "Броят на етапите в режим на термичен профил" - }, - "ProfilePreheatTemp": { - "displayText": "Температурата\nна загряване", - "description": "Температурата на загряване в началото на режим на термичен профил" - }, - "ProfilePreheatSpeed": { - "displayText": "Скорост на\nзагряване", - "description": "Скорост на предварително загряване (градуси в секунда)" - }, - "ProfilePhase1Temp": { - "displayText": "Етап 1\nТемпературата", - "description": "Температурата в края на този етап" - }, - "ProfilePhase1Duration": { - "displayText": "Етап 1\nПродължителност", - "description": "Продължителност на този етап (в секунди)" - }, - "ProfilePhase2Temp": { - "displayText": "Етап 2\nТемпературата", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Етап 2\nПродължителност", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Етап 3\nТемпературата", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Етап 3\nПродължителност", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Етап 4\nТемпературата", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Етап 4\nПродължителност", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Етап 5\nТемпературата", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Етап 5\nПродължителност", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Скорост на\nохлаждане", - "description": "Скорост на охлаждане в края на режим на термичен профил (градуси в секунда)" - }, - "MotionSensitivity": { - "displayText": "Чувствител.\nна движение", - "description": "Чувствителност на движение на акселерометър (0=Изкл. | 1=Слабо | ... | 9=Силно)" - }, - "SleepTemperature": { - "displayText": "Темп.\nсън", - "description": "Температурата при режим \"сън\"" - }, - "SleepTimeout": { - "displayText": "Време\nсън", - "description": "Включване в режим \"сън\" (секунди | минути)" - }, - "ShutdownTimeout": { - "displayText": "Време\nизкл.", - "description": "Изключване след (минути)" - }, - "HallEffSensitivity": { - "displayText": "Датчик\nна Хол", - "description": "Чувствителност на сензора към магнитно поле (0=Изкл. | 1=Слабо | ... | 9=Силно)" - }, - "TemperatureUnit": { - "displayText": "Единици за\nтемпературата", - "description": "Единици за температурата (C=Целзии | F=Фаренхайт)" - }, - "DisplayRotation": { - "displayText": "Ориентация\nна дисплея", - "description": "Ориентация на дисплея (Д=Дясна ръка | Л=Лява ръка | А=Авто)" - }, - "CooldownBlink": { - "displayText": "Мигай при\nтопъл поялник", - "description": "След изключване от работен режим, индикатора за температурата да мига докато човката на поялника все още е топла" - }, - "ScrollingSpeed": { - "displayText": "Скорост\nна текста", - "description": "Скорост на движение на този текст (Н=Ниска | B=Висока)" - }, - "ReverseButtonTempChange": { - "displayText": "Размяна\nбутони +/-", - "description": "Обръщане на бутоните + и - за промяна на температурата на човка на поялника" - }, - "AnimSpeed": { - "displayText": "Скорост на\nанимацията", - "description": "Скорост на анимация на иконата в главното меню (И=Изкл. | Н=Ниска | C=Средна | B=Висока)" - }, - "AnimLoop": { - "displayText": "Анимац.\nцикъл", - "description": "Зациклена анимация на иконите в главното меню" - }, - "Brightness": { - "displayText": "Яркост\nна екрана", - "description": "Регулирайте яркостта на екрана" - }, - "ColourInversion": { - "displayText": "Инвертиране\nна екрана", - "description": "Инверсия на пикселите на екрана" - }, - "LOGOTime": { - "displayText": "Продължит.\nлогото", - "description": "Продължителност на логото за стартиране (в секунди)" - }, - "AdvancedIdle": { - "displayText": "Детайлен\nекран в покой", - "description": "Покажи детайлна информация със ситен шрифт на екрана в режим на покой" - }, - "AdvancedSoldering": { - "displayText": "Детайлен\nработен екран", - "description": "Детайлна информация в работен режим при запояване" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Включи BLE" - }, - "PowerLimit": { - "displayText": "Лимит на\nмощност", - "description": "Максимална мощност на поялника (вати)" - }, - "CalibrateCJC": { - "displayText": "Калибриране\nна темп.", - "description": "Калибриране на температурата (CJC) при следващо включване (не се изисква, ако разликата е по-малка от 5 °С)" - }, - "VoltageCalibration": { - "displayText": "Калибриране\nнапрежение", - "description": "Калибриране на входното напрежение (задръжте бутонa за изход)" - }, - "PowerPulsePower": { - "displayText": "Захранващ\nимпулс", - "description": "Поддържане на интензивност на захранващия импулс (вати)" - }, - "PowerPulseWait": { - "displayText": "Закъснение\nна импулса", - "description": "Пауза между импулсите, които предпазват захранването от автоматично изключване (x 2,5 с)" - }, - "PowerPulseDuration": { - "displayText": "Продължит.\nна импулса", - "description": "Дължината на импулса, който предпазва захранването от автоматично изключване (x 250 мс)" - }, - "SettingsReset": { - "displayText": "Фабрични\nнастройки", - "description": "Връщане на фабрични настройки" - }, - "LanguageSwitch": { - "displayText": "Език:\n BG Български", - "description": "" - } + "languageCode": "BG", + "languageLocalName": "Български", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Калибрирането\nе завършено!" + }, + "ResetOKMessage": { + "message": "Нулиране" + }, + "SettingsResetMessage": { + "message": "Настройките бяха\nнулирани!" + }, + "NoAccelerometerMessage": { + "message": "Не е открит\nакселерометър!" + }, + "NoPowerDeliveryMessage": { + "message": "Не е открито\nUSB-PD захранване!" + }, + "LockingKeysString": { + "message": "ЗАКЛЮЧ" + }, + "UnlockingKeysString": { + "message": "ОТКЛЮЧ" + }, + "WarningKeysLockedString": { + "message": "!ЗАКЛЮЧ!" + }, + "WarningThermalRunaway": { + "message": "Неконтролируемо\nпрегряване" + }, + "WarningTipShorted": { + "message": "!КС на човка!" + }, + "SettingsCalibrationWarning": { + "message": "Преди рестартиране се уверете, че човка и дръжката са на стайна температурата!" + }, + "CJCCalibrating": { + "message": "калибриране\n" + }, + "SettingsResetWarning": { + "message": "Сигурни ли сте, че искате да върнете фабричните настройки?" + }, + "UVLOWarningString": { + "message": "НИС.НАПР." + }, + "UndervoltageString": { + "message": "Ниско напрежение\n" + }, + "InputVoltageString": { + "message": "Входно V: \n" + }, + "SleepingAdvancedString": { + "message": "Сън...\n" + }, + "SleepingTipAdvancedString": { + "message": "Човка:\n" + }, + "ProfilePreheatString": { + "message": "Загряване\n" + }, + "ProfileCooldownString": { + "message": "Охлаждане\n" + }, + "DeviceFailedValidationWarning": { + "message": "Вероятно, устройство е фалшификат!" + }, + "TooHotToStartProfileWarning": { + "message": "Твърде горещо за\nстартиране на профила" + } + }, + "characters": { + "SettingRightChar": "Д", + "SettingLeftChar": "Л", + "SettingAutoChar": "А", + "SettingSlowChar": "Н", + "SettingMediumChar": "С", + "SettingFastChar": "В", + "SettingStartSolderingChar": "З", + "SettingStartSleepChar": "С", + "SettingStartSleepOffChar": "П", + "SettingLockBoostChar": "Т", + "SettingLockFullChar": "П" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Настройки на\nзахранването", + "description": "" + }, + "SolderingMenu": { + "displayText": "Настройки на\nзапояване", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Авто\nизключване", + "description": "" + }, + "UIMenu": { + "displayText": "Интерфейс\n", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Допълнителни\nнастройки", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Вкл.\nPPSиERP" + }, + "USBPDModeNoDynamic": { + "displayText": "Изкл.\n" + }, + "USBPDModeSafe": { + "displayText": "Вкл.без\nискане" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Гранично\nнапрежение", + "description": "Минимално напрежение, за да не се изтощи батерията (DC 10V) (S 3,3V за клетка)" + }, + "MinVolCell": { + "displayText": "Мин.\nнапрежение", + "description": "Минимално допустимо напрежение на акумулаторна клетка (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" + }, + "QCMaxVoltage": { + "displayText": "Напреж.\nна QC", + "description": "Максимална напрежение с QC захранвания" + }, + "PDNegTimeout": { + "displayText": "PD\nинтервал", + "description": "PD интервал за договаряне на захранването на стъпки от 100 мс за съвместимост с някои QC захранвания (0=Изкл.)" + }, + "USBPDMode": { + "displayText": "PD\nрежим", + "description": "Вкл.без искане: включи PPS и EPR без да искате повече мощност" + }, + "BoostTemperature": { + "displayText": "Турбо\nтемп.", + "description": "Температурата за \"турбо\" режим" + }, + "AutoStart": { + "displayText": "Автоматичен\nработен режим", + "description": "Режим на поялника при включване на захранването (З=Запояване | С=Сън | П=Покой на стайна температурата)" + }, + "TempChangeShortStep": { + "displayText": "Промяна T\nбързо", + "description": "Промяна на температурата при бързо натискане на бутон" + }, + "TempChangeLongStep": { + "displayText": "Промяна Т\nзадържане", + "description": "Промяна на температурата при задържане на бутон" + }, + "LockingMode": { + "displayText": "Бутони за\nзаключване", + "description": "Докато запоявате, задръжте двата бутона, за да превключите заключването им (Т=Турбо режим | П=Пълно)" + }, + "ProfilePhases": { + "displayText": "Брой\nетапи", + "description": "Броят на етапите в режим на термичен профил" + }, + "ProfilePreheatTemp": { + "displayText": "Температурата\nна загряване", + "description": "Температурата на загряване в началото на режим на термичен профил" + }, + "ProfilePreheatSpeed": { + "displayText": "Скорост на\nзагряване", + "description": "Скорост на предварително загряване (градуси в секунда)" + }, + "ProfilePhase1Temp": { + "displayText": "Етап 1\nТемпературата", + "description": "Температурата в края на този етап" + }, + "ProfilePhase1Duration": { + "displayText": "Етап 1\nПродължителност", + "description": "Продължителност на този етап (в секунди)" + }, + "ProfilePhase2Temp": { + "displayText": "Етап 2\nТемпературата", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Етап 2\nПродължителност", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Етап 3\nТемпературата", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Етап 3\nПродължителност", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Етап 4\nТемпературата", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Етап 4\nПродължителност", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Етап 5\nТемпературата", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Етап 5\nПродължителност", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Скорост на\nохлаждане", + "description": "Скорост на охлаждане в края на режим на термичен профил (градуси в секунда)" + }, + "MotionSensitivity": { + "displayText": "Чувствител.\nна движение", + "description": "Чувствителност на движение на акселерометър (1=Слабо | ... | 9=Силно)" + }, + "SleepTemperature": { + "displayText": "Темп.\nсън", + "description": "Температурата при режим \"сън\"" + }, + "SleepTimeout": { + "displayText": "Време\nсън", + "description": "Включване в режим \"сън\" (секунди | минути)" + }, + "ShutdownTimeout": { + "displayText": "Време\nизкл.", + "description": "Изключване след (минути)" + }, + "HallEffSensitivity": { + "displayText": "Датчик\nна Хол", + "description": "Чувствителност на сензора към магнитно поле (1=Слабо | ... | 9=Силно)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Интервалът преди началото на \"режим на заспиване\", когато ефектът на Хол надвиши прага" + }, + "TemperatureUnit": { + "displayText": "Единици за\nтемпературата", + "description": "Единици за температурата (C=Целзии | F=Фаренхайт)" + }, + "DisplayRotation": { + "displayText": "Ориентация\nна дисплея", + "description": "Ориентация на дисплея (Д=Дясна ръка | Л=Лява ръка | А=Авто)" + }, + "CooldownBlink": { + "displayText": "Мигай при\nтопъл поялник", + "description": "След изключване от работен режим, индикатора за температурата да мига докато човката на поялника все още е топла" + }, + "ScrollingSpeed": { + "displayText": "Скорост\nна текста", + "description": "Скорост на движение на този текст (Н=Ниска | B=Висока)" + }, + "ReverseButtonTempChange": { + "displayText": "Размяна\nбутони +/-", + "description": "Обръщане на бутоните + и - за промяна на температурата на човка на поялника" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Скорост на\nанимацията", + "description": "Скорост на анимация на иконата в главното меню (Н=Ниска | C=Средна | B=Висока)" + }, + "AnimLoop": { + "displayText": "Анимац.\nцикъл", + "description": "Зациклена анимация на иконите в главното меню" + }, + "Brightness": { + "displayText": "Яркост\nна екрана", + "description": "Регулирайте яркостта на екрана" + }, + "ColourInversion": { + "displayText": "Инвертиране\nна екрана", + "description": "Инверсия на пикселите на екрана" + }, + "LOGOTime": { + "displayText": "Продължит.\nлогото", + "description": "Продължителност на логото за стартиране (в секунди)" + }, + "AdvancedIdle": { + "displayText": "Детайлен\nекран в покой", + "description": "Покажи детайлна информация със ситен шрифт на екрана в режим на покой" + }, + "AdvancedSoldering": { + "displayText": "Детайлен\nработен екран", + "description": "Детайлна информация в работен режим при запояване" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Включи BLE" + }, + "PowerLimit": { + "displayText": "Лимит на\nмощност", + "description": "Максимална мощност на поялника (вати)" + }, + "CalibrateCJC": { + "displayText": "Калибриране\nна темп.", + "description": "Калибриране на температурата (CJC) при следващо включване (не се изисква, ако разликата е по-малка от 5 °С)" + }, + "VoltageCalibration": { + "displayText": "Калибриране\nнапрежение", + "description": "Калибриране на входното напрежение (задръжте бутонa за изход)" + }, + "PowerPulsePower": { + "displayText": "Захранващ\nимпулс", + "description": "Поддържане на интензивност на захранващия импулс (вати)" + }, + "PowerPulseWait": { + "displayText": "Закъснение\nна импулса", + "description": "Пауза между импулсите, които предпазват захранването от автоматично изключване (x 2,5 с)" + }, + "PowerPulseDuration": { + "displayText": "Продължит.\nна импулса", + "description": "Дължината на импулса, който предпазва захранването от автоматично изключване (x 250 мс)" + }, + "SettingsReset": { + "displayText": "Фабрични\nнастройки", + "description": "Връщане на фабрични настройки" + }, + "LanguageSwitch": { + "displayText": "Език:\n BG Български", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_CS.json b/Translations/translation_CS.json index ac4d50c96..a581179b9 100644 --- a/Translations/translation_CS.json +++ b/Translations/translation_CS.json @@ -1,319 +1,351 @@ { - "languageCode": "CS", - "languageLocalName": "Český", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Kalibrace\ndokončena!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Nějaká nastavení\nbyla změněna!" - }, - "NoAccelerometerMessage": { - "message": "Akcelerometr\nnebyl detekován!" - }, - "NoPowerDeliveryMessage": { - "message": "Žádný IO USB-PD\nnebyl detekován!" - }, - "LockingKeysString": { - "message": "ZAMČENO" - }, - "UnlockingKeysString": { - "message": "ODEMČENO" - }, - "WarningKeysLockedString": { - "message": "ZAMČENO!" - }, - "WarningThermalRunaway": { - "message": "Teplotní\nOchrana" - }, - "WarningTipShorted": { - "message": "!Zkrat na hrotu!" - }, - "SettingsCalibrationWarning": { - "message": "Před restartem se ujistěte, že hrot a držák mají pokojovou teplotu!" - }, - "CJCCalibrating": { - "message": "kalibrování\n" - }, - "SettingsResetWarning": { - "message": "Opravdu chcete resetovat zařízení do továrního nastavení?" - }, - "UVLOWarningString": { - "message": "Nízké DC" - }, - "UndervoltageString": { - "message": "Nízké napětí\n" - }, - "InputVoltageString": { - "message": "Napětí: \n" - }, - "SleepingSimpleString": { - "message": "Zzz " - }, - "SleepingAdvancedString": { - "message": "Režim spánku...\n" - }, - "SleepingTipAdvancedString": { - "message": "Hrot: \n" - }, - "OffString": { - "message": "Vyp" - }, - "ProfilePreheatString": { - "message": "Předehřívání\n" - }, - "ProfileCooldownString": { - "message": "Zchlazování\n" - }, - "DeviceFailedValidationWarning": { - "message": "Vaše zařízení je pravěpodobně padělek!" - }, - "TooHotToStartProfileWarning": { - "message": "Teplota příliš vysoká pro start profilu" - } - }, - "characters": { - "SettingRightChar": "P", - "SettingLeftChar": "L", - "SettingAutoChar": "A", - "SettingOffChar": "D", - "SettingSlowChar": "P", - "SettingMediumChar": "S", - "SettingFastChar": "R", - "SettingStartNoneChar": "V", - "SettingStartSolderingChar": "P", - "SettingStartSleepChar": "S", - "SettingStartSleepOffChar": "M", - "SettingLockDisableChar": "Z", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "U" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Napájecí\nnastavení", - "description": "" - }, - "SolderingMenu": { - "displayText": "Pájecí\nnastavení", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Režim\nspánku", - "description": "" - }, - "UIMenu": { - "displayText": "Uživatelské\nrozhraní", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Pokročilá\nnastavení", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Zdroj\nnapájení", - "description": "Při nižším napětí ukončit pájení (DC 10V) (S 3,3V na článek, zakázat omezení napájení)." - }, - "MinVolCell": { - "displayText": "Minimální\nnapětí", - "description": "Minimální dovolené napětí po článku (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" - }, - "QCMaxVoltage": { - "displayText": "Napětí\nQC", - "description": "Maximální napětí QC pro jednání páječkou" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "Maximální prodleva při jednání PD ve 100ms krocích pro kompatibilitu s některými QC nabíječkami" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Povoluje režimy PPS & EPR" - }, - "BoostTemperature": { - "displayText": "Teplota\nboostu", - "description": "Teplota hrotu v \"režimu boost\"" - }, - "AutoStart": { - "displayText": "Chování\npři startu", - "description": "V=vypnuto | P=pájecí teplota | S=spánková teplota | M=zahřát hrot po pohybu" - }, - "TempChangeShortStep": { - "displayText": "Krok teploty\nkrátký?", - "description": "Velikost přídavku při změně teploty krátkým stiskem tlačítka" - }, - "TempChangeLongStep": { - "displayText": "Krok teploty\ndlouhý?", - "description": "Velikost přídavku při změně teploty dlouhým stiskem tlačítka" - }, - "LockingMode": { - "displayText": "Povolit zamč.\ntlačítek", - "description": "Při pájení podržte obě tlačítka pro jejich zamčení (Z=zakázáno | B=pouze v režimu boost | U=úplné zamčení)" - }, - "ProfilePhases": { - "displayText": "Profilové\nFáze", - "description": "Počet fází v profilovém režimu" - }, - "ProfilePreheatTemp": { - "displayText": "Teplota\nPředehřátí", - "description": "Teplota na kterou předehřát na začátku profilového režimu" - }, - "ProfilePreheatSpeed": { - "displayText": "Rychlost\nPředehřívání", - "description": "Rychlost předehřívání (stupně za sekundu)" - }, - "ProfilePhase1Temp": { - "displayText": "Teplota\nFáze 1", - "description": "Cílová teplota na konci této fáze" - }, - "ProfilePhase1Duration": { - "displayText": "Trvání\nFáze 1", - "description": "Doba trvání této fáze (sekundy)" - }, - "ProfilePhase2Temp": { - "displayText": "Teplota\nFáze 2", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Trvání\nFáze 2", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Teplota\nFáze 3", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Trvání\nFáze 3", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Teplota\nFáze 4", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Trvání\nFáze 4", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Teplota\nFáze 5", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Trvání\nFáze 5", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Rychlost\nochlazování", - "description": "Rychlost ochlazování na konci profilového režimu (stupně za sekundu)" - }, - "MotionSensitivity": { - "displayText": "Citlivost\nna pohyb", - "description": "0=vyp | 1=nejméně citlivé | ... | 9=nejvíce citlivé" - }, - "SleepTemperature": { - "displayText": "Teplota\nve spánku", - "description": "Teplota hrotu v režimu spánku." - }, - "SleepTimeout": { - "displayText": "Čas\ndo spánku", - "description": "\"Režim spánku\" naběhne v (s=sekundách | m=minutách)" - }, - "ShutdownTimeout": { - "displayText": "Čas do\nvypnutí", - "description": "Interval automatického vypnutí (m=minut)" - }, - "HallEffSensitivity": { - "displayText": "Citlivost\nHall. čidla", - "description": "Citlivost Hallova čidla pro detekci spánku (0=vypnuto | 1=nejméně citlivé | ... | 9=nejvíce citlivé)" - }, - "TemperatureUnit": { - "displayText": "Jednotka\nteploty", - "description": "C=Celsius | F=Fahrenheit" - }, - "DisplayRotation": { - "displayText": "Orientace\nobrazovky", - "description": "P=pravák | L=levák | A=automaticky" - }, - "CooldownBlink": { - "displayText": "Blikáni při\nchladnutí", - "description": "Blikat teplotou při chladnutí dokud je hrot horký" - }, - "ScrollingSpeed": { - "displayText": "Rychlost\nposouvání", - "description": "Rychlost posouvání popisků podobných tomuto (P=pomalu | R=rychle)" - }, - "ReverseButtonTempChange": { - "displayText": "Prohodit\ntl. +-?", - "description": "Prohodit tlačítka pro změnu teploty" - }, - "AnimSpeed": { - "displayText": "Anim.\nrychlost", - "description": "Tempo animace ikon v menu (O=vypnuto | P=pomalu | S=středně | R=rychle)" - }, - "AnimLoop": { - "displayText": "Anim.\nsmyčka", - "description": "Animovat ikony hlavního menu ve smyčce" - }, - "Brightness": { - "displayText": "Jas\nobrazovky", - "description": "Upravit jas OLED" - }, - "ColourInversion": { - "displayText": "Invertovat\nobrazovku", - "description": "Invertovat barvy na OLED" - }, - "LOGOTime": { - "displayText": "Trvání\nboot loga", - "description": "Nastavení doby trvání boot loga (s=sekundy)" - }, - "AdvancedIdle": { - "displayText": "Podrobná obr.\nnečinnosti", - "description": "Zobrazit detailní informace malým fontem na obrazovce nečinnosti" - }, - "AdvancedSoldering": { - "displayText": "Podrobná obr.\npájení", - "description": "Zobrazit detailní informace malým fontem na obrazovce pájení" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Povoluje BLE" - }, - "PowerLimit": { - "displayText": "Omezení\nVýkonu", - "description": "Maximální příkon páječky (W=watt)" - }, - "CalibrateCJC": { - "displayText": "Kalibrovat CJC\npři příštím startu", - "description": "Při příštím startu bude kalibrována kompenzace studeného spoje (není třeba pokud Delta T je < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Kalibrovat\nvstupní napětí?", - "description": "Začít kalibraci vstupního napětí (dlouhý stisk pro ukončení)" - }, - "PowerPulsePower": { - "displayText": "Napájecí\npulz", - "description": "Intenzita výkonu pulzu pro udržení páječky vzhůru (watt)" - }, - "PowerPulseWait": { - "displayText": "Prodleva\nnapáj. pulzu", - "description": "Prodleva než je spuštěn pulz pro udržení páječky vzhůru pulzu pro udržení páječky vzhůru (x 2,5s)" - }, - "PowerPulseDuration": { - "displayText": "Délka\nnapáj. pulzu", - "description": "Délka pulzu pro udržení páječky vzhůru (x 250ms)" - }, - "SettingsReset": { - "displayText": "Obnovit tovární\nnastavení?", - "description": "Obnovit všechna nastavení na výchozí" - }, - "LanguageSwitch": { - "displayText": "Jazyk:\n CS Český", - "description": "" - } + "languageCode": "CS", + "languageLocalName": "Český", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibrace\ndokončena!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Nějaká nastavení\nbyla změněna!" + }, + "NoAccelerometerMessage": { + "message": "Akcelerometr\nnebyl detekován!" + }, + "NoPowerDeliveryMessage": { + "message": "Žádný IO USB-PD\nnebyl detekován!" + }, + "LockingKeysString": { + "message": "ZAMČENO" + }, + "UnlockingKeysString": { + "message": "ODEMČENO" + }, + "WarningKeysLockedString": { + "message": "ZAMČENO!" + }, + "WarningThermalRunaway": { + "message": "Teplotní\nOchrana" + }, + "WarningTipShorted": { + "message": "!Zkrat na hrotu!" + }, + "SettingsCalibrationWarning": { + "message": "Před restartem se ujistěte, že hrot a držák mají pokojovou teplotu!" + }, + "CJCCalibrating": { + "message": "kalibrování\n" + }, + "SettingsResetWarning": { + "message": "Opravdu chcete resetovat zařízení do továrního nastavení?" + }, + "UVLOWarningString": { + "message": "Nízké DC" + }, + "UndervoltageString": { + "message": "Nízké napětí\n" + }, + "InputVoltageString": { + "message": "Napětí: \n" + }, + "SleepingAdvancedString": { + "message": "Režim spánku...\n" + }, + "SleepingTipAdvancedString": { + "message": "Hrot: \n" + }, + "ProfilePreheatString": { + "message": "Předehřívání\n" + }, + "ProfileCooldownString": { + "message": "Zchlazování\n" + }, + "DeviceFailedValidationWarning": { + "message": "Vaše zařízení je pravěpodobně padělek!" + }, + "TooHotToStartProfileWarning": { + "message": "Teplota příliš vysoká pro start profilu" + } + }, + "characters": { + "SettingRightChar": "P", + "SettingLeftChar": "L", + "SettingAutoChar": "A", + "SettingSlowChar": "P", + "SettingMediumChar": "S", + "SettingFastChar": "R", + "SettingStartSolderingChar": "P", + "SettingStartSleepChar": "S", + "SettingStartSleepOffChar": "M", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "U" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Napájecí\nnastavení", + "description": "" + }, + "SolderingMenu": { + "displayText": "Pájecí\nnastavení", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Režim\nspánku", + "description": "" + }, + "UIMenu": { + "displayText": "Uživatelské\nrozhraní", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Pokročilá\nnastavení", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Zdroj\nnapájení", + "description": "Při nižším napětí ukončit pájení (DC 10V) (S 3,3V na článek, zakázat omezení napájení)." + }, + "MinVolCell": { + "displayText": "Minimální\nnapětí", + "description": "Minimální dovolené napětí po článku (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" + }, + "QCMaxVoltage": { + "displayText": "Napětí\nQC", + "description": "Maximální napětí QC pro jednání páječkou" + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "Maximální prodleva při jednání PD ve 100ms krocích pro kompatibilitu s některými QC nabíječkami" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "Povoluje režimy PPS & EPR" + }, + "BoostTemperature": { + "displayText": "Teplota\nboostu", + "description": "Teplota hrotu v \"režimu boost\"" + }, + "AutoStart": { + "displayText": "Chování\npři startu", + "description": "P=pájecí teplota | S=spánková teplota | M=zahřát hrot po pohybu" + }, + "TempChangeShortStep": { + "displayText": "Krok teploty\nkrátký?", + "description": "Velikost přídavku při změně teploty krátkým stiskem tlačítka" + }, + "TempChangeLongStep": { + "displayText": "Krok teploty\ndlouhý?", + "description": "Velikost přídavku při změně teploty dlouhým stiskem tlačítka" + }, + "LockingMode": { + "displayText": "Povolit zamč.\ntlačítek", + "description": "Při pájení podržte obě tlačítka pro jejich zamčení (B=pouze v režimu boost | U=úplné zamčení)" + }, + "ProfilePhases": { + "displayText": "Profilové\nFáze", + "description": "Počet fází v profilovém režimu" + }, + "ProfilePreheatTemp": { + "displayText": "Teplota\nPředehřátí", + "description": "Teplota na kterou předehřát na začátku profilového režimu" + }, + "ProfilePreheatSpeed": { + "displayText": "Rychlost\nPředehřívání", + "description": "Rychlost předehřívání (stupně za sekundu)" + }, + "ProfilePhase1Temp": { + "displayText": "Teplota\nFáze 1", + "description": "Cílová teplota na konci této fáze" + }, + "ProfilePhase1Duration": { + "displayText": "Trvání\nFáze 1", + "description": "Doba trvání této fáze (sekundy)" + }, + "ProfilePhase2Temp": { + "displayText": "Teplota\nFáze 2", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Trvání\nFáze 2", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Teplota\nFáze 3", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Trvání\nFáze 3", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Teplota\nFáze 4", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Trvání\nFáze 4", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Teplota\nFáze 5", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Trvání\nFáze 5", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Rychlost\nochlazování", + "description": "Rychlost ochlazování na konci profilového režimu (stupně za sekundu)" + }, + "MotionSensitivity": { + "displayText": "Citlivost\nna pohyb", + "description": "1=nejméně citlivé | ... | 9=nejvíce citlivé" + }, + "SleepTemperature": { + "displayText": "Teplota\nve spánku", + "description": "Teplota hrotu v režimu spánku." + }, + "SleepTimeout": { + "displayText": "Čas\ndo spánku", + "description": "\"Režim spánku\" naběhne v (s=sekundách | m=minutách)" + }, + "ShutdownTimeout": { + "displayText": "Čas do\nvypnutí", + "description": "Interval automatického vypnutí (m=minut)" + }, + "HallEffSensitivity": { + "displayText": "Citlivost\nHall. čidla", + "description": "Citlivost Hallova čidla pro detekci spánku (1=nejméně citlivé | ... | 9=nejvíce citlivé)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval před začátkem \"režimu spánku\", kdy Hallův efekt překročí práh" + }, + "TemperatureUnit": { + "displayText": "Jednotka\nteploty", + "description": "C=Celsius | F=Fahrenheit" + }, + "DisplayRotation": { + "displayText": "Orientace\nobrazovky", + "description": "P=pravák | L=levák | A=automaticky" + }, + "CooldownBlink": { + "displayText": "Blikáni při\nchladnutí", + "description": "Blikat teplotou při chladnutí dokud je hrot horký" + }, + "ScrollingSpeed": { + "displayText": "Rychlost\nposouvání", + "description": "Rychlost posouvání popisků podobných tomuto (P=pomalu | R=rychle)" + }, + "ReverseButtonTempChange": { + "displayText": "Prohodit\ntl. +-?", + "description": "Prohodit tlačítka pro změnu teploty" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\nrychlost", + "description": "Tempo animace ikon v menu (P=pomalu | S=středně | R=rychle)" + }, + "AnimLoop": { + "displayText": "Anim.\nsmyčka", + "description": "Animovat ikony hlavního menu ve smyčce" + }, + "Brightness": { + "displayText": "Jas\nobrazovky", + "description": "Upravit jas OLED" + }, + "ColourInversion": { + "displayText": "Invertovat\nobrazovku", + "description": "Invertovat barvy na OLED" + }, + "LOGOTime": { + "displayText": "Trvání\nboot loga", + "description": "Nastavení doby trvání boot loga (s=sekundy)" + }, + "AdvancedIdle": { + "displayText": "Podrobná obr.\nnečinnosti", + "description": "Zobrazit detailní informace malým fontem na obrazovce nečinnosti" + }, + "AdvancedSoldering": { + "displayText": "Podrobná obr.\npájení", + "description": "Zobrazit detailní informace malým fontem na obrazovce pájení" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Povoluje BLE" + }, + "PowerLimit": { + "displayText": "Omezení\nVýkonu", + "description": "Maximální příkon páječky (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Kalibrovat CJC\npři příštím startu", + "description": "Při příštím startu bude kalibrována kompenzace studeného spoje (není třeba pokud Delta T je < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibrovat\nvstupní napětí?", + "description": "Začít kalibraci vstupního napětí (dlouhý stisk pro ukončení)" + }, + "PowerPulsePower": { + "displayText": "Napájecí\npulz", + "description": "Intenzita výkonu pulzu pro udržení páječky vzhůru (watt)" + }, + "PowerPulseWait": { + "displayText": "Prodleva\nnapáj. pulzu", + "description": "Prodleva než je spuštěn pulz pro udržení páječky vzhůru pulzu pro udržení páječky vzhůru (x 2,5s)" + }, + "PowerPulseDuration": { + "displayText": "Délka\nnapáj. pulzu", + "description": "Délka pulzu pro udržení páječky vzhůru (x 250ms)" + }, + "SettingsReset": { + "displayText": "Obnovit tovární\nnastavení?", + "description": "Obnovit všechna nastavení na výchozí" + }, + "LanguageSwitch": { + "displayText": "Jazyk:\n CS Český", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_DA.json b/Translations/translation_DA.json index 2e0971c0f..b3b59fde7 100644 --- a/Translations/translation_DA.json +++ b/Translations/translation_DA.json @@ -1,319 +1,351 @@ { - "languageCode": "DA", - "languageLocalName": "Dansk", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Visse indstillinger\nEr blevet ændret!" - }, - "NoAccelerometerMessage": { - "message": "ingen accelerometer\nfundet!" - }, - "NoPowerDeliveryMessage": { - "message": "ingen USB-PD IC\nFundet!" - }, - "LockingKeysString": { - "message": "LÅST" - }, - "UnlockingKeysString": { - "message": "ULÅST" - }, - "WarningKeysLockedString": { - "message": "!LÅST!" - }, - "WarningThermalRunaway": { - "message": "Thermal\nRunaway" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Er du sikker du vil resette indstillingerne til standard?" - }, - "UVLOWarningString": { - "message": "Lav Volt" - }, - "UndervoltageString": { - "message": "Undervolt\n" - }, - "InputVoltageString": { - "message": "Input V: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Dvale...\n" - }, - "SleepingTipAdvancedString": { - "message": "Tip: \n" - }, - "OffString": { - "message": "Off" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Din enhed er højst sandsyneligt en Kopivare!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "H", - "SettingLeftChar": "V", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "S", - "SettingMediumChar": "M", - "SettingFastChar": "F", - "SettingStartNoneChar": "S", - "SettingStartSolderingChar": "L", - "SettingStartSleepChar": "D", - "SettingStartSleepOffChar": "R", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Strøm\nIndstillinger", - "description": "" - }, - "SolderingMenu": { - "displayText": "Lodde\nIndstillinger", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Dvale\nmode", - "description": "" - }, - "UIMenu": { - "displayText": "Bruger\nGrændseflade", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Advancerede\nIndstillinger", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Strøm\nKilde", - "description": "Strømforsyning. Indstil Cutoff Spændingen. (DC 10V) (S 3,3V per celle)" - }, - "MinVolCell": { - "displayText": "Minimum\nSpænding", - "description": "Minimum tilladt spænding pr. celle (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" - }, - "QCMaxVoltage": { - "displayText": "QC\nSpænding", - "description": "Max QC spænding Loddekolben skal forhandle sig til" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "PD-forhandlingstimeout i trin på 100 ms for kompatibilitet med nogle QC-opladere" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Boost\ntemp", - "description": "Temperatur i \"boost mode\"" - }, - "AutoStart": { - "displayText": "Start-up\nOpførsel", - "description": "Start automatisk med lodning når strøm sættes til. (S=Slukket | L=Lodning | D=Dvale tilstand | R=Dvale tilstand rumtemperatur)" - }, - "TempChangeShortStep": { - "displayText": "Temp ændring\nkort", - "description": "Temperatur-ændring-stigning ved kort tryk på knappen" - }, - "TempChangeLongStep": { - "displayText": "Temp ændring\nlang", - "description": "Temperatur-ændring-stigning ved lang tryk på knappen" - }, - "LockingMode": { - "displayText": "Tillad låsning\naf knapperne", - "description": "Hold begge knapper nede under lodning for at låse dem (D=deaktiver | B=kun boost-tilstand | F=fuld låsning)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Bevægelses\nfølsomhed", - "description": "Bevægelsesfølsomhed (0=Slukket | 1=Mindst følsom | ... | 9=Mest følsom)" - }, - "SleepTemperature": { - "displayText": "Dvale\ntemp", - "description": "Dvale Temperatur (C)" - }, - "SleepTimeout": { - "displayText": "Dvale\ntimeout", - "description": "Dvale Timeout (Minutter | Sekunder)" - }, - "ShutdownTimeout": { - "displayText": "Sluknings\ntimeout", - "description": "sluknings Timeout (Minutter)" - }, - "HallEffSensitivity": { - "displayText": "Hall sensor\nfølsomhed", - "description": "følsomhed overfor magneten (0=Slukket | 1=Mindst følsom | ... | 9=Mest følsom)" - }, - "TemperatureUnit": { - "displayText": "Temperatur\nEnhed", - "description": "Temperatur Enhed (C=Celsius | F=Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "Skærm\nOrientering", - "description": "Skærm Orientering (H=Højre Håndet | V=Venstre Håndet | A=Automatisk)" - }, - "CooldownBlink": { - "displayText": "Køl ned\nBlinkning", - "description": "Blink temperaturen på skærmen, mens spidsen stadig er varm." - }, - "ScrollingSpeed": { - "displayText": "Scrolling\nHastighed", - "description": "Hastigheden infotekst ruller forbi med (S=Langsom | F=Hurtigt)" - }, - "ReverseButtonTempChange": { - "displayText": "Skift\n+ - tasterne", - "description": "Skift tildeling af knapper til temperaturjustering" - }, - "AnimSpeed": { - "displayText": "Anim.\nHastighed", - "description": "Hastigheden for ikonanimationer i menuen (O=fra | S=langsomt | M=medium | F=hurtigt)" - }, - "AnimLoop": { - "displayText": "Anim.\nsløfe", - "description": "ikonanimation sløfe i hovedmenuen" - }, - "Brightness": { - "displayText": "Skærm\nlysstyrke", - "description": "Juster lysstyrken på OLED-skærmen" - }, - "ColourInversion": { - "displayText": "spejlvende\nskærm", - "description": "spejlvende farverne på OLED-skærmen" - }, - "LOGOTime": { - "displayText": "opstartslogo\nvarighed", - "description": "Indstiller varigheden for opstartslogoet (s=sekunder)" - }, - "AdvancedIdle": { - "displayText": "Detaljeret\nStandby skærm", - "description": "Vis detialieret information med en mindre skriftstørrelse på standby skærmen." - }, - "AdvancedSoldering": { - "displayText": "Detaljeret\nloddeskærm", - "description": "Vis detaljeret information mens der loddes" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Strøm\nbegrænsning", - "description": "Maksimal effekt Loddekolben kan bruge (W=watt)" - }, - "CalibrateCJC": { - "displayText": "kalibrere CJK\nunder næste opstart", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Kalibrere\ninput spændingen?", - "description": "VIN kalibrering. Knapperne justere, Lang tryk for at gå ud" - }, - "PowerPulsePower": { - "displayText": "Strøm\npuls", - "description": "Intensiteten af strøm for hold-vågen-puls (watt)" - }, - "PowerPulseWait": { - "displayText": "Strøm puls\nForsinkelse", - "description": "Forsinkelse før hold-vågen-puls udløses (x 2,5s)" - }, - "PowerPulseDuration": { - "displayText": "Strøm puls\nvarighed", - "description": "Hold-vågen-pulsvarighed (x 250ms)" - }, - "SettingsReset": { - "displayText": "Gendan fabriks\nIndstillinger", - "description": "Gendan alle indstillinger" - }, - "LanguageSwitch": { - "displayText": "Sprog:\n DA Dansk", - "description": "" - } + "languageCode": "DA", + "languageLocalName": "Dansk", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibration\ndone!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Visse indstillinger\nEr blevet ændret!" + }, + "NoAccelerometerMessage": { + "message": "ingen accelerometer\nfundet!" + }, + "NoPowerDeliveryMessage": { + "message": "ingen USB-PD IC\nFundet!" + }, + "LockingKeysString": { + "message": "LÅST" + }, + "UnlockingKeysString": { + "message": "ULÅST" + }, + "WarningKeysLockedString": { + "message": "!LÅST!" + }, + "WarningThermalRunaway": { + "message": "Thermal\nRunaway" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Before rebooting, make sure tip & handle are at room temperature!" + }, + "CJCCalibrating": { + "message": "calibrating\n" + }, + "SettingsResetWarning": { + "message": "Er du sikker du vil resette indstillingerne til standard?" + }, + "UVLOWarningString": { + "message": "Lav Volt" + }, + "UndervoltageString": { + "message": "Undervolt\n" + }, + "InputVoltageString": { + "message": "Input V: \n" + }, + "SleepingAdvancedString": { + "message": "Dvale...\n" + }, + "SleepingTipAdvancedString": { + "message": "Tip: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Din enhed er højst sandsyneligt en Kopivare!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "H", + "SettingLeftChar": "V", + "SettingAutoChar": "A", + "SettingSlowChar": "S", + "SettingMediumChar": "M", + "SettingFastChar": "F", + "SettingStartSolderingChar": "L", + "SettingStartSleepChar": "D", + "SettingStartSleepOffChar": "R", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Strøm\nIndstillinger", + "description": "" + }, + "SolderingMenu": { + "displayText": "Lodde\nIndstillinger", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Dvale\nmode", + "description": "" + }, + "UIMenu": { + "displayText": "Bruger\nGrændseflade", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Advancerede\nIndstillinger", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Strøm\nKilde", + "description": "Strømforsyning. Indstil Cutoff Spændingen. (DC 10V) (S 3,3V per celle)" + }, + "MinVolCell": { + "displayText": "Minimum\nSpænding", + "description": "Minimum tilladt spænding pr. celle (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\nSpænding", + "description": "Max QC spænding Loddekolben skal forhandle sig til" + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "PD-forhandlingstimeout i trin på 100 ms for kompatibilitet med nogle QC-opladere" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Boost\ntemp", + "description": "Temperatur i \"boost mode\"" + }, + "AutoStart": { + "displayText": "Start-up\nOpførsel", + "description": "Start automatisk med lodning når strøm sættes til. (L=Lodning | D=Dvale tilstand | R=Dvale tilstand rumtemperatur)" + }, + "TempChangeShortStep": { + "displayText": "Temp ændring\nkort", + "description": "Temperatur-ændring-stigning ved kort tryk på knappen" + }, + "TempChangeLongStep": { + "displayText": "Temp ændring\nlang", + "description": "Temperatur-ændring-stigning ved lang tryk på knappen" + }, + "LockingMode": { + "displayText": "Tillad låsning\naf knapperne", + "description": "Hold begge knapper nede under lodning for at låse dem (B=kun boost-tilstand | F=fuld låsning)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Bevægelses\nfølsomhed", + "description": "Bevægelsesfølsomhed (1=Mindst følsom | ... | 9=Mest følsom)" + }, + "SleepTemperature": { + "displayText": "Dvale\ntemp", + "description": "Dvale Temperatur (C)" + }, + "SleepTimeout": { + "displayText": "Dvale\ntimeout", + "description": "Dvale Timeout (Minutter | Sekunder)" + }, + "ShutdownTimeout": { + "displayText": "Sluknings\ntimeout", + "description": "sluknings Timeout (Minutter)" + }, + "HallEffSensitivity": { + "displayText": "Hall sensor\nfølsomhed", + "description": "følsomhed overfor magneten (1=Mindst følsom | ... | 9=Mest følsom)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Intervallet før starten af \"dvaletilstand\", når Hall-effekten overskrider tærsklen" + }, + "TemperatureUnit": { + "displayText": "Temperatur\nEnhed", + "description": "Temperatur Enhed (C=Celsius | F=Fahrenheit)" + }, + "DisplayRotation": { + "displayText": "Skærm\nOrientering", + "description": "Skærm Orientering (H=Højre Håndet | V=Venstre Håndet | A=Automatisk)" + }, + "CooldownBlink": { + "displayText": "Køl ned\nBlinkning", + "description": "Blink temperaturen på skærmen, mens spidsen stadig er varm." + }, + "ScrollingSpeed": { + "displayText": "Scrolling\nHastighed", + "description": "Hastigheden infotekst ruller forbi med (S=Langsom | F=Hurtigt)" + }, + "ReverseButtonTempChange": { + "displayText": "Skift\n+ - tasterne", + "description": "Skift tildeling af knapper til temperaturjustering" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\nHastighed", + "description": "Hastigheden for ikonanimationer i menuen (S=langsomt | M=medium | F=hurtigt)" + }, + "AnimLoop": { + "displayText": "Anim.\nsløfe", + "description": "ikonanimation sløfe i hovedmenuen" + }, + "Brightness": { + "displayText": "Skærm\nlysstyrke", + "description": "Juster lysstyrken på OLED-skærmen" + }, + "ColourInversion": { + "displayText": "spejlvende\nskærm", + "description": "spejlvende farverne på OLED-skærmen" + }, + "LOGOTime": { + "displayText": "opstartslogo\nvarighed", + "description": "Indstiller varigheden for opstartslogoet (s=sekunder)" + }, + "AdvancedIdle": { + "displayText": "Detaljeret\nStandby skærm", + "description": "Vis detialieret information med en mindre skriftstørrelse på standby skærmen." + }, + "AdvancedSoldering": { + "displayText": "Detaljeret\nloddeskærm", + "description": "Vis detaljeret information mens der loddes" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Strøm\nbegrænsning", + "description": "Maksimal effekt Loddekolben kan bruge (W=watt)" + }, + "CalibrateCJC": { + "displayText": "kalibrere CJK\nunder næste opstart", + "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibrere\ninput spændingen?", + "description": "VIN kalibrering. Knapperne justere, Lang tryk for at gå ud" + }, + "PowerPulsePower": { + "displayText": "Strøm\npuls", + "description": "Intensiteten af strøm for hold-vågen-puls (watt)" + }, + "PowerPulseWait": { + "displayText": "Strøm puls\nForsinkelse", + "description": "Forsinkelse før hold-vågen-puls udløses (x 2,5s)" + }, + "PowerPulseDuration": { + "displayText": "Strøm puls\nvarighed", + "description": "Hold-vågen-pulsvarighed (x 250ms)" + }, + "SettingsReset": { + "displayText": "Gendan fabriks\nIndstillinger", + "description": "Gendan alle indstillinger" + }, + "LanguageSwitch": { + "displayText": "Sprog:\n DA Dansk", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_DE.json b/Translations/translation_DE.json index 527c2e18e..80533d3a7 100644 --- a/Translations/translation_DE.json +++ b/Translations/translation_DE.json @@ -1,319 +1,351 @@ { - "languageCode": "DE", - "languageLocalName": "Deutsch", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Erfolgreich\nkalibriert!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Einstellungen\nzurückgesetzt!" - }, - "NoAccelerometerMessage": { - "message": "Bewegungssensor\nnicht erkannt!" - }, - "NoPowerDeliveryMessage": { - "message": "USB-PD IC\nnicht erkannt!" - }, - "LockingKeysString": { - "message": "GESPERRT" - }, - "UnlockingKeysString": { - "message": "ENTSPERRT" - }, - "WarningKeysLockedString": { - "message": "!GESPERRT!" - }, - "WarningThermalRunaway": { - "message": "Thermal\nRunaway" - }, - "WarningTipShorted": { - "message": "!Lötspitze\nkurzgeschlossen!" - }, - "SettingsCalibrationWarning": { - "message": "Vor dem Neustart bitte sicherstellen, dass Lötspitze & Gerät Raumtemperatur haben!" - }, - "CJCCalibrating": { - "message": "kalibriere\n" - }, - "SettingsResetWarning": { - "message": "Sicher, dass alle Werte zurückgesetzt werden sollen?" - }, - "UVLOWarningString": { - "message": "V niedr." - }, - "UndervoltageString": { - "message": "Unterspannung\n" - }, - "InputVoltageString": { - "message": "V Eingang: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Ruhemodus...\n" - }, - "SleepingTipAdvancedString": { - "message": "Temp: \n" - }, - "OffString": { - "message": "aus" - }, - "ProfilePreheatString": { - "message": "Vorwärmen\n" - }, - "ProfileCooldownString": { - "message": "Abkühlen\n" - }, - "DeviceFailedValidationWarning": { - "message": "Höchstwahrscheinlich ist das Gerät eine Fälschung!" - }, - "TooHotToStartProfileWarning": { - "message": "Zu heiß für\nProfilstart!" - } - }, - "characters": { - "SettingRightChar": "R", - "SettingLeftChar": "L", - "SettingAutoChar": "A", - "SettingOffChar": "A", - "SettingSlowChar": "L", - "SettingMediumChar": "M", - "SettingFastChar": "S", - "SettingStartNoneChar": "A", - "SettingStartSolderingChar": "L", - "SettingStartSleepChar": "R", - "SettingStartSleepOffChar": "K", - "SettingLockDisableChar": "A", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "V" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Energie-\neinstellungen", - "description": "" - }, - "SolderingMenu": { - "displayText": "Löt-\neinstellungen", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Ruhe-\nmodus", - "description": "" - }, - "UIMenu": { - "displayText": "Anzeige-\neinstellungen", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Erweiterte\nEinstellungen", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Spannungs-\nquelle", - "description": "Spannungsquelle (Abschaltspannung) (DC=10V | nS=n*3.3V für n LiIon-Zellen)" - }, - "MinVolCell": { - "displayText": "Minimale\nSpannung", - "description": "Minimal zulässige Spannung pro Zelle (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" - }, - "QCMaxVoltage": { - "displayText": "Spannungs-\nmaximum", - "description": "Maximal zulässige Spannung der verwendeten Spannungsversorgung (V=Volt)" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "PD Abfragedauer in 100ms Schritten (Kompatibilität mit best. QC-Ladegeräten)" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Aktiviert PPS & EPR" - }, - "BoostTemperature": { - "displayText": "Boost-\ntemperatur", - "description": "Temperatur der Lötspitze im Boostmodus" - }, - "AutoStart": { - "displayText": "Start im\nLötmodus", - "description": "Heizverhalten beim Einschalten der Spannungsversorgung (A=aus | L=Lötmodus | R=Ruhemodus | K=Ruhemodus mit kalter Spitze)" - }, - "TempChangeShortStep": { - "displayText": "Temp-Schritt\nDruck kurz", - "description": "Schrittweite für Temperaturänderung bei kurzem Tastendruck" - }, - "TempChangeLongStep": { - "displayText": "Temp-Schritt\nDruck lang", - "description": "Schrittweite für Temperaturänderung bei langem Tastendruck" - }, - "LockingMode": { - "displayText": "Tasten-\nsperre", - "description": "Langes Drücken beider Tasten im Lötmodus sperrt diese (A=aus | B=nur Boost | V=vollständig)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhasen", - "description": "Anzahl an Phasen im Profilmodus" - }, - "ProfilePreheatTemp": { - "displayText": "Vorheiz-\ntemperatur", - "description": "Zu Beginn des Profilmodus auf diese Temperatur vorheizen" - }, - "ProfilePreheatSpeed": { - "displayText": "Vorheiz-\nrate", - "description": "Mit dieser Geschwindigkeit vorheizen (Grad pro Sekunde)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemperatur", - "description": "Zieltemperatur zum Ende dieser Phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDauer", - "description": "Dauer dieser Phase (Sekunden)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemperatur", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDauer", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemperatur", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDauer", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemperatur", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDauer", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemperatur", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDauer", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Abkühl-\nrate", - "description": "Am Ende des Profilmodus mit dieser Geschwindigkeit abkühlen (Grad pro Sekunde)" - }, - "MotionSensitivity": { - "displayText": "Bewegungs-\nempfindlichk.", - "description": "0=aus | 1=minimal | ... | 9=maximal" - }, - "SleepTemperature": { - "displayText": "Ruhe-\ntemperatur", - "description": "Ruhetemperatur der Lötspitze" - }, - "SleepTimeout": { - "displayText": "Ruhever-\nzögerung", - "description": "Dauer vor Übergang in den Ruhemodus (s=Sekunden | m=Minuten)" - }, - "ShutdownTimeout": { - "displayText": "Abschalt-\nverzög.", - "description": "Dauer vor automatischer Abschaltung (m=Minuten)" - }, - "HallEffSensitivity": { - "displayText": "Empfindlichkeit\nder Hall-Sonde", - "description": "Empfindlichkeit der Hall-Sonde um den Ruhemodus auszulösen (0=aus | 1=minimal | ... | 9=maximal)" - }, - "TemperatureUnit": { - "displayText": "Temperatur-\neinheit", - "description": "C=°Celsius | F=°Fahrenheit" - }, - "DisplayRotation": { - "displayText": "Anzeige-\nausrichtung", - "description": "R=rechtshändig | L=linkshändig | A=automatisch" - }, - "CooldownBlink": { - "displayText": "Abkühl-\nblinken", - "description": "Temperaturanzeige blinkt beim Abkühlen, solange Spitze heiß ist" - }, - "ScrollingSpeed": { - "displayText": "Scroll-\ngeschw.", - "description": "Scrollgeschwindigkeit der Erläuterungen (L=langsam | S=schnell)" - }, - "ReverseButtonTempChange": { - "displayText": "+- Tasten\numkehren", - "description": "Tastenbelegung zur Temperaturänderung umkehren" - }, - "AnimSpeed": { - "displayText": "Anim.\nGeschw.", - "description": "Geschwindigkeit der Icon-Animationen im Menü (A=aus | L=langsam | M=mittel | S=schnell)" - }, - "AnimLoop": { - "displayText": "Anim.\nSchleife", - "description": "Icon-Animationen im Hauptmenü wiederholen" - }, - "Brightness": { - "displayText": "Bildschirm-\nhelligkeit", - "description": "Verändert die Helligkeit des OLED-Displays" - }, - "ColourInversion": { - "displayText": "Farben\numkehren", - "description": "Invertiert die Farben des OLED-Displays" - }, - "LOGOTime": { - "displayText": "Startlogo-\ndauer", - "description": "Legt die Dauer der Anzeige des Startlogos fest (s=Sekunden)" - }, - "AdvancedIdle": { - "displayText": "Detaillierte\nRuheansicht", - "description": "Detaillierte Anzeige im Ruhemodus" - }, - "AdvancedSoldering": { - "displayText": "Detaillierte\nLötansicht", - "description": "Detaillierte Anzeige im Lötmodus" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Aktiviert Bluetooth LE" - }, - "PowerLimit": { - "displayText": "Leistungs-\nmaximum", - "description": "Durchschnittliche maximal zulässige Leistungsaufnahme des Lötkolbens (W=Watt)" - }, - "CalibrateCJC": { - "displayText": "Temperatur\nkalibrieren", - "description": "Beim nächsten Start wird die Kaltstellenkompensation kalibriert (nicht nötig wenn Delta T < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Eingangsspannung\nkalibrieren", - "description": "Kalibrierung der Eingangsspannung (Langer Tastendruck zum Verlassen)" - }, - "PowerPulsePower": { - "displayText": "Leistungs-\nimpuls", - "description": "Powerbank mit einem Impuls wach halten (Watt)" - }, - "PowerPulseWait": { - "displayText": "Impuls-\nverzögerung", - "description": "Dauer vor Abgabe von Wachhalteimpulsen (x 2,5s)" - }, - "PowerPulseDuration": { - "displayText": "Impuls-\ndauer", - "description": "Dauer des Wachhalteimpulses (x 250ms)" - }, - "SettingsReset": { - "displayText": "Einstellungen\nzurücksetzen", - "description": "Werte auf Werkseinstellungen zurücksetzen" - }, - "LanguageSwitch": { - "displayText": "Sprache:\n DE Deutsch", - "description": "" - } + "languageCode": "DE", + "languageLocalName": "Deutsch", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Erfolgreich\nkalibriert!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Einstellungen\nzurückgesetzt!" + }, + "NoAccelerometerMessage": { + "message": "Bewegungssensor\nnicht erkannt!" + }, + "NoPowerDeliveryMessage": { + "message": "USB-PD IC\nnicht erkannt!" + }, + "LockingKeysString": { + "message": "GESPERRT" + }, + "UnlockingKeysString": { + "message": "ENTSPERRT" + }, + "WarningKeysLockedString": { + "message": "!GESPERRT!" + }, + "WarningThermalRunaway": { + "message": "Thermal\nRunaway" + }, + "WarningTipShorted": { + "message": "!Lötspitze\nkurzgeschlossen!" + }, + "SettingsCalibrationWarning": { + "message": "Vor dem Neustart bitte sicherstellen, dass Lötspitze & Gerät Raumtemperatur haben!" + }, + "CJCCalibrating": { + "message": "kalibriere\n" + }, + "SettingsResetWarning": { + "message": "Sicher, dass alle Werte zurückgesetzt werden sollen?" + }, + "UVLOWarningString": { + "message": "V niedr." + }, + "UndervoltageString": { + "message": "Unterspannung\n" + }, + "InputVoltageString": { + "message": "V Eingang: \n" + }, + "SleepingAdvancedString": { + "message": "Ruhemodus...\n" + }, + "SleepingTipAdvancedString": { + "message": "Temp: \n" + }, + "ProfilePreheatString": { + "message": "Vorwärmen\n" + }, + "ProfileCooldownString": { + "message": "Abkühlen\n" + }, + "DeviceFailedValidationWarning": { + "message": "Höchstwahrscheinlich ist das Gerät eine Fälschung!" + }, + "TooHotToStartProfileWarning": { + "message": "Zu heiß für\nProfilstart!" + } + }, + "characters": { + "SettingRightChar": "R", + "SettingLeftChar": "L", + "SettingAutoChar": "A", + "SettingSlowChar": "L", + "SettingMediumChar": "M", + "SettingFastChar": "S", + "SettingStartSolderingChar": "L", + "SettingStartSleepChar": "R", + "SettingStartSleepOffChar": "K", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "V" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Energie-\neinstellungen", + "description": "" + }, + "SolderingMenu": { + "displayText": "Löt-\neinstellungen", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Ruhe-\nmodus", + "description": "" + }, + "UIMenu": { + "displayText": "Anzeige-\neinstellungen", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Erweiterte\nEinstellungen", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Spannungs-\nquelle", + "description": "Spannungsquelle (Abschaltspannung) (DC=10V | nS=n*3.3V für n LiIon-Zellen)" + }, + "MinVolCell": { + "displayText": "Minimale\nSpannung", + "description": "Minimal zulässige Spannung pro Zelle (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" + }, + "QCMaxVoltage": { + "displayText": "Spannungs-\nmaximum", + "description": "Maximal zulässige Spannung der verwendeten Spannungsversorgung (V=Volt)" + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "PD Abfragedauer in 100ms Schritten (Kompatibilität mit best. QC-Ladegeräten)" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "Aktiviert PPS & EPR" + }, + "BoostTemperature": { + "displayText": "Boost-\ntemperatur", + "description": "Temperatur der Lötspitze im Boostmodus" + }, + "AutoStart": { + "displayText": "Start im\nLötmodus", + "description": "Heizverhalten beim Einschalten der Spannungsversorgung (L=Lötmodus | R=Ruhemodus | K=Ruhemodus mit kalter Spitze)" + }, + "TempChangeShortStep": { + "displayText": "Temp-Schritt\nDruck kurz", + "description": "Schrittweite für Temperaturänderung bei kurzem Tastendruck" + }, + "TempChangeLongStep": { + "displayText": "Temp-Schritt\nDruck lang", + "description": "Schrittweite für Temperaturänderung bei langem Tastendruck" + }, + "LockingMode": { + "displayText": "Tasten-\nsperre", + "description": "Langes Drücken beider Tasten im Lötmodus sperrt diese (B=nur Boost | V=vollständig)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhasen", + "description": "Anzahl an Phasen im Profilmodus" + }, + "ProfilePreheatTemp": { + "displayText": "Vorheiz-\ntemperatur", + "description": "Zu Beginn des Profilmodus auf diese Temperatur vorheizen" + }, + "ProfilePreheatSpeed": { + "displayText": "Vorheiz-\nrate", + "description": "Mit dieser Geschwindigkeit vorheizen (Grad pro Sekunde)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemperatur", + "description": "Zieltemperatur zum Ende dieser Phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDauer", + "description": "Dauer dieser Phase (Sekunden)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemperatur", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDauer", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemperatur", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDauer", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemperatur", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDauer", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemperatur", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDauer", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Abkühl-\nrate", + "description": "Am Ende des Profilmodus mit dieser Geschwindigkeit abkühlen (Grad pro Sekunde)" + }, + "MotionSensitivity": { + "displayText": "Bewegungs-\nempfindlichk.", + "description": "1=minimal | ... | 9=maximal" + }, + "SleepTemperature": { + "displayText": "Ruhe-\ntemperatur", + "description": "Ruhetemperatur der Lötspitze" + }, + "SleepTimeout": { + "displayText": "Ruhever-\nzögerung", + "description": "Dauer vor Übergang in den Ruhemodus (s=Sekunden | m=Minuten)" + }, + "ShutdownTimeout": { + "displayText": "Abschalt-\nverzög.", + "description": "Dauer vor automatischer Abschaltung (m=Minuten)" + }, + "HallEffSensitivity": { + "displayText": "Empfindlichkeit\nder Hall-Sonde", + "description": "Empfindlichkeit der Hall-Sonde um den Ruhemodus auszulösen (1=minimal | ... | 9=maximal)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Dauer vor dem Wechsel in den \"Ruhemodus\", nachdem die Hall-Sonde auslöst" + }, + "TemperatureUnit": { + "displayText": "Temperatur-\neinheit", + "description": "C=°Celsius | F=°Fahrenheit" + }, + "DisplayRotation": { + "displayText": "Anzeige-\nausrichtung", + "description": "R=rechtshändig | L=linkshändig | A=automatisch" + }, + "CooldownBlink": { + "displayText": "Abkühl-\nblinken", + "description": "Temperaturanzeige blinkt beim Abkühlen, solange Spitze heiß ist" + }, + "ScrollingSpeed": { + "displayText": "Scroll-\ngeschw.", + "description": "Scrollgeschwindigkeit der Erläuterungen (L=langsam | S=schnell)" + }, + "ReverseButtonTempChange": { + "displayText": "+- Tasten\numkehren", + "description": "Tastenbelegung zur Temperaturänderung umkehren" + }, + "ReverseButtonSettings": { + "displayText": "A B Tasten\nvertauschen", + "description": "Umgekehrte Belegung der Tasten für das Einstellungsmenü" + }, + "AnimSpeed": { + "displayText": "Anim.\nGeschw.", + "description": "Geschwindigkeit der Icon-Animationen im Menü (L=langsam | M=mittel | S=schnell)" + }, + "AnimLoop": { + "displayText": "Anim.\nSchleife", + "description": "Icon-Animationen im Hauptmenü wiederholen" + }, + "Brightness": { + "displayText": "Bildschirm-\nhelligkeit", + "description": "Verändert die Helligkeit des OLED-Displays" + }, + "ColourInversion": { + "displayText": "Farben\numkehren", + "description": "Invertiert die Farben des OLED-Displays" + }, + "LOGOTime": { + "displayText": "Startlogo-\ndauer", + "description": "Legt die Dauer der Anzeige des Startlogos fest (s=Sekunden)" + }, + "AdvancedIdle": { + "displayText": "Detaillierte\nRuheansicht", + "description": "Detaillierte Anzeige im Ruhemodus" + }, + "AdvancedSoldering": { + "displayText": "Detaillierte\nLötansicht", + "description": "Detaillierte Anzeige im Lötmodus" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Aktiviert Bluetooth LE" + }, + "PowerLimit": { + "displayText": "Leistungs-\nmaximum", + "description": "Durchschnittliche maximal zulässige Leistungsaufnahme des Lötkolbens (W=Watt)" + }, + "CalibrateCJC": { + "displayText": "Temperatur\nkalibrieren", + "description": "Beim nächsten Start wird die Kaltstellenkompensation kalibriert (nicht nötig wenn Delta T < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Eingangsspannung\nkalibrieren", + "description": "Kalibrierung der Eingangsspannung (Langer Tastendruck zum Verlassen)" + }, + "PowerPulsePower": { + "displayText": "Leistungs-\nimpuls", + "description": "Powerbank mit einem Impuls wach halten (Watt)" + }, + "PowerPulseWait": { + "displayText": "Impuls-\nverzögerung", + "description": "Dauer vor Abgabe von Wachhalteimpulsen (x 2,5s)" + }, + "PowerPulseDuration": { + "displayText": "Impuls-\ndauer", + "description": "Dauer des Wachhalteimpulses (x 250ms)" + }, + "SettingsReset": { + "displayText": "Einstellungen\nzurücksetzen", + "description": "Werte auf Werkseinstellungen zurücksetzen" + }, + "LanguageSwitch": { + "displayText": "Sprache:\n DE Deutsch", + "description": "" + }, + "SolderingTipType": { + "displayText": "Löt-\nspitzentyp", + "description": "Wählen Sie den Typ der eingesetzten Spitze" } + } } diff --git a/Translations/translation_EL.json b/Translations/translation_EL.json index 75ca856f9..2bb084493 100644 --- a/Translations/translation_EL.json +++ b/Translations/translation_EL.json @@ -1,319 +1,351 @@ { - "languageCode": "EL", - "languageLocalName": "Greek", - "tempUnitFahrenheit": true, - "messagesWarn": { - "CalibrationDone": { - "message": "Βαθμονόμηση\nολοκληρώθηκε!" - }, - "ResetOKMessage": { - "message": "Επαν. OK" - }, - "SettingsResetMessage": { - "message": "Κάποιες ρυθμ.\nάλλαξαν" - }, - "NoAccelerometerMessage": { - "message": "Δεν εντοπίστηκε\nεπιταχυνσιόμετρο" - }, - "NoPowerDeliveryMessage": { - "message": "Δεν εντοπίστηκε\nκύκλωμα USB-PD" - }, - "LockingKeysString": { - "message": "ΚΛΕΙΔ." - }, - "UnlockingKeysString": { - "message": "ΞΕΚΛΕΙΔ." - }, - "WarningKeysLockedString": { - "message": "ΚΛΕΙΔΩΜΕΝΑ\nΠΛΗΚΤΡΑ!" - }, - "WarningThermalRunaway": { - "message": "Θερμική\nΦυγή" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Πριν την επανεκκίνηση, βεβαιωθείτε ότι η μύτη και η συσκ. είναι σε θερμ. δωματίου!" - }, - "CJCCalibrating": { - "message": "βαθμονόμηση\n" - }, - "SettingsResetWarning": { - "message": "Σίγουρα θέλετε επαναφορά αρχικών ρυθμίσεων;" - }, - "UVLOWarningString": { - "message": "Χαμηλ DC" - }, - "UndervoltageString": { - "message": "Υπόταση\n" - }, - "InputVoltageString": { - "message": "Είσοδος V: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Υπνος...\n" - }, - "SleepingTipAdvancedString": { - "message": "Μύτη: \n" - }, - "OffString": { - "message": "Απ." - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Η συσκευή σας ίσως να μην είναι αυθεντική!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "R", - "SettingLeftChar": "L", - "SettingAutoChar": "Α", - "SettingOffChar": "0", - "SettingSlowChar": "Α", - "SettingMediumChar": "Μ", - "SettingFastChar": "Γ", - "SettingStartNoneChar": "0", - "SettingStartSolderingChar": "Κ", - "SettingStartSleepChar": "Ζ", - "SettingStartSleepOffChar": "Υ", - "SettingLockDisableChar": "Α", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "Π" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Ρυθμίσεις\nενέργειας", - "description": "" - }, - "SolderingMenu": { - "displayText": "Ρυθμίσεις\nκόλλησης", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Λειτουργία\nύπνου", - "description": "" - }, - "UIMenu": { - "displayText": "Διεπαφή\nχρήστη", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Προηγμένες\nρυθμίσεις", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Πηγή\nενέργειας", - "description": "Πηγή ενέργειας. Oρισμός τάσης απενεργοποίησης. (DC 10V) (S 3.3V ανα μπαταρία, απενεργοποίηση ενεργειακού ορίου)" - }, - "MinVolCell": { - "displayText": "Ελάχιστη\nτάση", - "description": "Ελάχιστη επιτρεπτή τάση ανα μπαταρία (3 σε σειρά: 3 - 3.7V | 4-6 σε σειρά: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "Τάση\nQC", - "description": "Μέγιστη τάση QC που να ζητείται από το τροφοδοτικό" - }, - "PDNegTimeout": { - "displayText": "χρονικό όριο\nPD", - "description": "Χρονικό όριο διαπραγμάτευσης PD σε βήματα 100ms για συμβατότητα με κάποιους φορτιστές QC" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Ενεργοποιεί λειτουργίες PPS & EPR." - }, - "BoostTemperature": { - "displayText": "Θερμοκ.\nboost", - "description": "Θερμοκρασία στη \"λειτουργία boost\"" - }, - "AutoStart": { - "displayText": "Ζέσταμα\nκατά την εν.", - "description": "0=off | Κ=θερμ. κόλλησης | Z=αναμονή σε θερμοκρασία ύπνου μέχρι την κίνηση | Υ=αναμονή χωρίς ζέσταμα μέχρι την κίνηση" - }, - "TempChangeShortStep": { - "displayText": "Αλλαγή θερμοκ.\nστιγμιαίο", - "description": "Βήμα αλλαγής θερμοκρασίας σε στιγμιαίο πάτημα πλήκτρου" - }, - "TempChangeLongStep": { - "displayText": "Αλλαγή θερμοκ.\nπαρατεταμένο", - "description": "Βήμα αλλαγής θερμοκρασίας σε παρατεταμένο πάτημα πλήκτρου" - }, - "LockingMode": { - "displayText": "Κλείδωμα\nπλήκτρων", - "description": "Κατά την κόλληση, κρατήστε και τα δύο πλήκτρα για κλείδωμα (A=απενεργοποίηση | B=μόνο λειτ. boost | Π=πλήρες κλείδωμα)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Ευαισθησία\nκίνησης", - "description": "0=off | 1=λιγότερο ευαίσθητο | ... | 9=περισσότερο ευαίσθητο" - }, - "SleepTemperature": { - "displayText": "Θερμοκρ.\nύπνου", - "description": "Θερμοκρασία μύτης σε λειτ. ύπνου" - }, - "SleepTimeout": { - "displayText": "Έναρξη\nύπνου", - "description": "Χρονικό διάστημα πρίν την ενεργοποίηση λειτουργίας ύπνου (Δ=δευτ. | Λ=λεπτά)" - }, - "ShutdownTimeout": { - "displayText": "Έναρξη\nαπενεργ.", - "description": "Χρονικό διάστημα πρίν την απενεργοποίηση του κολλητηριού (Λ=λεπτά)" - }, - "HallEffSensitivity": { - "displayText": "Ευαισθ. αισθ. \nφαιν. Hall", - "description": "Ευαισθησία του αισθητήρα φαινομένου Hall για εντοπισμό αδράνειας (0=off | 1=λιγότερο ευαίσθητο | ... | 9=περισσότερο ευαίσθητο)" - }, - "TemperatureUnit": { - "displayText": "Μονάδες\nθερμοκρασίας", - "description": "C=Κελσίου | F=Φαρενάιτ" - }, - "DisplayRotation": { - "displayText": "Διάταξη\nοθόνης", - "description": "R=δεξιόχειρες | L=αριστερόχειρες | Α=αυτόματο" - }, - "CooldownBlink": { - "displayText": "Αναβοσβήσιμο\nψύξης", - "description": "Αναβοσβήσιμο της ενδειξης θερμοκρασίας κατά την παύση θέρμανσης όταν η μύτη είναι ακόμα καυτή" - }, - "ScrollingSpeed": { - "displayText": "Ταχύτητα\nκύλισης", - "description": "Ταχύτητα κύλισης κειμένου (Α=αργά | Γ=γρήγορα)" - }, - "ReverseButtonTempChange": { - "displayText": "Αντιστροφή\nπλήκτρων + -", - "description": "Αντιστροφή διάταξης πλήκτρων στη ρύθμιση θερμοκρασίας" - }, - "AnimSpeed": { - "displayText": "Ταχύτητα\nκιν. εικονιδ.", - "description": "Ρυθμός κίνησης εικονιδίων στο μενού (0=off | Α=αργός | Μ=μέτριος | Γ=γρήγορος)" - }, - "AnimLoop": { - "displayText": "Επανάληψη\nκιν. εικονιδ.", - "description": "Επανάληψη κίνησης εικονιδίων στο αρχικό μενού" - }, - "Brightness": { - "displayText": "Αντίθεση\nοθόνης", - "description": "Ρύθμιση φωτεινότητας οθόνης OLED" - }, - "ColourInversion": { - "displayText": "Αντιστροφή\nχρωμάτων", - "description": "Αντιστροφή χρωμάτων οθόνης OLED" - }, - "LOGOTime": { - "displayText": "Διάρκεια\nlogo εκκίνησης", - "description": "Διάρκεια εμφάνισης της εικόνας εκκίνησης (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Λεπτομερής\nοθ. αδράνειας", - "description": "Προβολή λεπτομερών πληροφοριών σε μικρότερη γραμματοσειρά στην οθόνη αδράνειας" - }, - "AdvancedSoldering": { - "displayText": "Λεπτομερής\nοθ. κόλλησης", - "description": "Προβολή λεπτομερών πληροφοριών σε μικρότερη γραμματοσειρά στην οθόνη κόλλησης" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Ενεργειακό\nόριο", - "description": "Μέγιστη ενέργεια που μπορεί να χρησιμοποιεί το κολλητήρι (W=watt)" - }, - "CalibrateCJC": { - "displayText": "Βαθμονόμηση CJC\nσε επόμενη έναρξη", - "description": "Στην επόμενη εκκίνηση θα γίνει βαθμονόμηση θερμοκρασίας (δεν απαιτείται αν Δθερμ < 5 C)" - }, - "VoltageCalibration": { - "displayText": "Βαθμονόμηση\nτάσης εισόδου;", - "description": "Έναρξη βαθμονόμησης τάσης εισόδου (κράτημα για έξοδο)" - }, - "PowerPulsePower": { - "displayText": "Παλμός\nενέργειας", - "description": "Ένταση ενέργειας παλμού διατήρησης λειτουργίας (W=watt)" - }, - "PowerPulseWait": { - "displayText": "Καθυστέρηση\nπαλμού ενέργ.", - "description": "Καθυστέρηση πριν την ενεργοποίση παλμού διατήρησης λειτουργίας (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Διάρκεια\nπαλμού ενέργ.", - "description": "Διάρκεια παλμού διατήρησης ενέργειας (x 250ms)" - }, - "SettingsReset": { - "displayText": "Επαναφορά\nεργ. ρυθμίσεων;", - "description": "Επαναφορά στις προεπιλεγμένες ρυθμίσεις" - }, - "LanguageSwitch": { - "displayText": "Γλώσσα:\n EL Ελληνικά", - "description": "" - } + "languageCode": "EL", + "languageLocalName": "Greek", + "tempUnitFahrenheit": true, + "messagesWarn": { + "CalibrationDone": { + "message": "Βαθμονόμηση\nολοκληρώθηκε!" + }, + "ResetOKMessage": { + "message": "Επαν. OK" + }, + "SettingsResetMessage": { + "message": "Κάποιες ρυθμ.\nάλλαξαν" + }, + "NoAccelerometerMessage": { + "message": "Δεν εντοπίστηκε\nεπιταχυνσιόμετρο" + }, + "NoPowerDeliveryMessage": { + "message": "Δεν εντοπίστηκε\nκύκλωμα USB-PD" + }, + "LockingKeysString": { + "message": "ΚΛΕΙΔ." + }, + "UnlockingKeysString": { + "message": "ΞΕΚΛΕΙΔ." + }, + "WarningKeysLockedString": { + "message": "ΚΛΕΙΔΩΜΕΝΑ\nΠΛΗΚΤΡΑ!" + }, + "WarningThermalRunaway": { + "message": "Θερμική\nΦυγή" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Πριν την επανεκκίνηση, βεβαιωθείτε ότι η μύτη και η συσκ. είναι σε θερμ. δωματίου!" + }, + "CJCCalibrating": { + "message": "βαθμονόμηση\n" + }, + "SettingsResetWarning": { + "message": "Σίγουρα θέλετε επαναφορά αρχικών ρυθμίσεων;" + }, + "UVLOWarningString": { + "message": "Χαμηλ DC" + }, + "UndervoltageString": { + "message": "Υπόταση\n" + }, + "InputVoltageString": { + "message": "Είσοδος V: \n" + }, + "SleepingAdvancedString": { + "message": "Υπνος...\n" + }, + "SleepingTipAdvancedString": { + "message": "Μύτη: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Η συσκευή σας ίσως να μην είναι αυθεντική!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "R", + "SettingLeftChar": "L", + "SettingAutoChar": "Α", + "SettingSlowChar": "Α", + "SettingMediumChar": "Μ", + "SettingFastChar": "Γ", + "SettingStartSolderingChar": "Κ", + "SettingStartSleepChar": "Ζ", + "SettingStartSleepOffChar": "Υ", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "Π" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Ρυθμίσεις\nενέργειας", + "description": "" + }, + "SolderingMenu": { + "displayText": "Ρυθμίσεις\nκόλλησης", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Λειτουργία\nύπνου", + "description": "" + }, + "UIMenu": { + "displayText": "Διεπαφή\nχρήστη", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Προηγμένες\nρυθμίσεις", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Πηγή\nενέργειας", + "description": "Πηγή ενέργειας. Oρισμός τάσης απενεργοποίησης. (DC 10V) (S 3.3V ανα μπαταρία, απενεργοποίηση ενεργειακού ορίου)" + }, + "MinVolCell": { + "displayText": "Ελάχιστη\nτάση", + "description": "Ελάχιστη επιτρεπτή τάση ανα μπαταρία (3 σε σειρά: 3 - 3.7V | 4-6 σε σειρά: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "Τάση\nQC", + "description": "Μέγιστη τάση QC που να ζητείται από το τροφοδοτικό" + }, + "PDNegTimeout": { + "displayText": "χρονικό όριο\nPD", + "description": "Χρονικό όριο διαπραγμάτευσης PD σε βήματα 100ms για συμβατότητα με κάποιους φορτιστές QC" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "Ενεργοποιεί λειτουργίες PPS & EPR." + }, + "BoostTemperature": { + "displayText": "Θερμοκ.\nboost", + "description": "Θερμοκρασία στη \"λειτουργία boost\"" + }, + "AutoStart": { + "displayText": "Ζέσταμα\nκατά την εν.", + "description": "Κ=θερμ. κόλλησης | Z=αναμονή σε θερμοκρασία ύπνου μέχρι την κίνηση | Υ=αναμονή χωρίς ζέσταμα μέχρι την κίνηση" + }, + "TempChangeShortStep": { + "displayText": "Αλλαγή θερμοκ.\nστιγμιαίο", + "description": "Βήμα αλλαγής θερμοκρασίας σε στιγμιαίο πάτημα πλήκτρου" + }, + "TempChangeLongStep": { + "displayText": "Αλλαγή θερμοκ.\nπαρατεταμένο", + "description": "Βήμα αλλαγής θερμοκρασίας σε παρατεταμένο πάτημα πλήκτρου" + }, + "LockingMode": { + "displayText": "Κλείδωμα\nπλήκτρων", + "description": "Κατά την κόλληση, κρατήστε και τα δύο πλήκτρα για κλείδωμα (B=μόνο λειτ. boost | Π=πλήρες κλείδωμα)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Ευαισθησία\nκίνησης", + "description": "1=λιγότερο ευαίσθητο | ... | 9=περισσότερο ευαίσθητο" + }, + "SleepTemperature": { + "displayText": "Θερμοκρ.\nύπνου", + "description": "Θερμοκρασία μύτης σε λειτ. ύπνου" + }, + "SleepTimeout": { + "displayText": "Έναρξη\nύπνου", + "description": "Χρονικό διάστημα πρίν την ενεργοποίηση λειτουργίας ύπνου (Δ=δευτ. | Λ=λεπτά)" + }, + "ShutdownTimeout": { + "displayText": "Έναρξη\nαπενεργ.", + "description": "Χρονικό διάστημα πρίν την απενεργοποίηση του κολλητηριού (Λ=λεπτά)" + }, + "HallEffSensitivity": { + "displayText": "Ευαισθ. αισθ. \nφαιν. Hall", + "description": "Ευαισθησία του αισθητήρα φαινομένου Hall για εντοπισμό αδράνειας (1=λιγότερο ευαίσθητο | ... | 9=περισσότερο ευαίσθητο)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Το διάστημα πριν από την \"λειτουργία ύπνου\" ξεκινά όταν το εφέ αίθουσας είναι πάνω από το όριο" + }, + "TemperatureUnit": { + "displayText": "Μονάδες\nθερμοκρασίας", + "description": "C=Κελσίου | F=Φαρενάιτ" + }, + "DisplayRotation": { + "displayText": "Διάταξη\nοθόνης", + "description": "R=δεξιόχειρες | L=αριστερόχειρες | Α=αυτόματο" + }, + "CooldownBlink": { + "displayText": "Αναβοσβήσιμο\nψύξης", + "description": "Αναβοσβήσιμο της ενδειξης θερμοκρασίας κατά την παύση θέρμανσης όταν η μύτη είναι ακόμα καυτή" + }, + "ScrollingSpeed": { + "displayText": "Ταχύτητα\nκύλισης", + "description": "Ταχύτητα κύλισης κειμένου (Α=αργά | Γ=γρήγορα)" + }, + "ReverseButtonTempChange": { + "displayText": "Αντιστροφή\nπλήκτρων + -", + "description": "Αντιστροφή διάταξης πλήκτρων στη ρύθμιση θερμοκρασίας" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Ταχύτητα\nκιν. εικονιδ.", + "description": "Ρυθμός κίνησης εικονιδίων στο μενού (Α=αργός | Μ=μέτριος | Γ=γρήγορος)" + }, + "AnimLoop": { + "displayText": "Επανάληψη\nκιν. εικονιδ.", + "description": "Επανάληψη κίνησης εικονιδίων στο αρχικό μενού" + }, + "Brightness": { + "displayText": "Αντίθεση\nοθόνης", + "description": "Ρύθμιση φωτεινότητας οθόνης OLED" + }, + "ColourInversion": { + "displayText": "Αντιστροφή\nχρωμάτων", + "description": "Αντιστροφή χρωμάτων οθόνης OLED" + }, + "LOGOTime": { + "displayText": "Διάρκεια\nlogo εκκίνησης", + "description": "Διάρκεια εμφάνισης της εικόνας εκκίνησης (s=seconds)" + }, + "AdvancedIdle": { + "displayText": "Λεπτομερής\nοθ. αδράνειας", + "description": "Προβολή λεπτομερών πληροφοριών σε μικρότερη γραμματοσειρά στην οθόνη αδράνειας" + }, + "AdvancedSoldering": { + "displayText": "Λεπτομερής\nοθ. κόλλησης", + "description": "Προβολή λεπτομερών πληροφοριών σε μικρότερη γραμματοσειρά στην οθόνη κόλλησης" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Ενεργειακό\nόριο", + "description": "Μέγιστη ενέργεια που μπορεί να χρησιμοποιεί το κολλητήρι (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Βαθμονόμηση CJC\nσε επόμενη έναρξη", + "description": "Στην επόμενη εκκίνηση θα γίνει βαθμονόμηση θερμοκρασίας (δεν απαιτείται αν Δθερμ < 5 C)" + }, + "VoltageCalibration": { + "displayText": "Βαθμονόμηση\nτάσης εισόδου;", + "description": "Έναρξη βαθμονόμησης τάσης εισόδου (κράτημα για έξοδο)" + }, + "PowerPulsePower": { + "displayText": "Παλμός\nενέργειας", + "description": "Ένταση ενέργειας παλμού διατήρησης λειτουργίας (W=watt)" + }, + "PowerPulseWait": { + "displayText": "Καθυστέρηση\nπαλμού ενέργ.", + "description": "Καθυστέρηση πριν την ενεργοποίση παλμού διατήρησης λειτουργίας (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Διάρκεια\nπαλμού ενέργ.", + "description": "Διάρκεια παλμού διατήρησης ενέργειας (x 250ms)" + }, + "SettingsReset": { + "displayText": "Επαναφορά\nεργ. ρυθμίσεων;", + "description": "Επαναφορά στις προεπιλεγμένες ρυθμίσεις" + }, + "LanguageSwitch": { + "displayText": "Γλώσσα:\n EL Ελληνικά", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_EN.json b/Translations/translation_EN.json index 2ed38eaad..4bd33631c 100644 --- a/Translations/translation_EN.json +++ b/Translations/translation_EN.json @@ -1,319 +1,351 @@ { - "languageCode": "EN", - "languageLocalName": "English", - "tempUnitFahrenheit": true, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Certain settings\nchanged!" - }, - "NoAccelerometerMessage": { - "message": "No accelerometer\ndetected!" - }, - "NoPowerDeliveryMessage": { - "message": "No USB-PD IC\ndetected!" - }, - "LockingKeysString": { - "message": "LOCKED" - }, - "UnlockingKeysString": { - "message": "UNLOCKED" - }, - "WarningKeysLockedString": { - "message": "!LOCKED!" - }, - "WarningThermalRunaway": { - "message": "Thermal\nRunaway" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Are you sure you want to restore default settings?" - }, - "UVLOWarningString": { - "message": "DC LOW" - }, - "UndervoltageString": { - "message": "Undervoltage\n" - }, - "InputVoltageString": { - "message": "Input V: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Sleeping...\n" - }, - "SleepingTipAdvancedString": { - "message": "Tip: \n" - }, - "OffString": { - "message": "Off" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Your device is most likely a counterfeit!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "R", - "SettingLeftChar": "L", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "S", - "SettingMediumChar": "M", - "SettingFastChar": "F", - "SettingStartNoneChar": "O", - "SettingStartSolderingChar": "S", - "SettingStartSleepChar": "Z", - "SettingStartSleepOffChar": "R", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Power\nsettings", - "description": "" - }, - "SolderingMenu": { - "displayText": "Soldering\nsettings", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Sleep\nmode", - "description": "" - }, - "UIMenu": { - "displayText": "User\ninterface", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Advanced\nsettings", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Power\nsource", - "description": "Set cutoff voltage to prevent battery overdrainage (DC 10V) (S=3.3V per cell, disable PWR limit)" - }, - "MinVolCell": { - "displayText": "Minimum\nvoltage", - "description": "Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "QC\nvoltage", - "description": "Max QC voltage the iron should negotiate for" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Boost\ntemp", - "description": "Tip temperature used in \"boost mode\"" - }, - "AutoStart": { - "displayText": "Start-up\nbehavior", - "description": "O=off | S=heat to soldering temp | Z=standby at sleep temp until moved | R=standby without heating until moved" - }, - "TempChangeShortStep": { - "displayText": "Temp change\nshort", - "description": "Temperature-change-increment on short button press" - }, - "TempChangeLongStep": { - "displayText": "Temp change\nlong", - "description": "Temperature-change-increment on long button press" - }, - "LockingMode": { - "displayText": "Allow locking\nbuttons", - "description": "While soldering, hold down both buttons to toggle locking them (D=disable | B=boost mode only | F=full locking)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Motion\nsensitivity", - "description": "0=off | 1=least sensitive | ... | 9=most sensitive" - }, - "SleepTemperature": { - "displayText": "Sleep\ntemp", - "description": "Tip temperature while in \"sleep mode\"" - }, - "SleepTimeout": { - "displayText": "Sleep\ntimeout", - "description": "Interval before \"sleep mode\" starts (s=seconds | m=minutes)" - }, - "ShutdownTimeout": { - "displayText": "Shutdown\ntimeout", - "description": "Interval before the iron shuts down (m=minutes)" - }, - "HallEffSensitivity": { - "displayText": "Hall sensor\nsensitivity", - "description": "Sensitivity to magnets (0=off | 1=least sensitive | ... | 9=most sensitive)" - }, - "TemperatureUnit": { - "displayText": "Temperature\nunit", - "description": "C=°Celsius | F=°Fahrenheit" - }, - "DisplayRotation": { - "displayText": "Display\norientation", - "description": "R=right-handed | L=left-handed | A=automatic" - }, - "CooldownBlink": { - "displayText": "Cooldown\nflashing", - "description": "Flash temp reading at idle while tip is hot" - }, - "ScrollingSpeed": { - "displayText": "Scrolling\nspeed", - "description": "Scrolling speed of info text (S=slow | F=fast)" - }, - "ReverseButtonTempChange": { - "displayText": "Swap\n+ - keys", - "description": "Reverse assignment of buttons for temperature adjustment" - }, - "AnimSpeed": { - "displayText": "Anim.\nspeed", - "description": "Pace of icon animations in menu (O=off | S=slow | M=medium | F=fast)" - }, - "AnimLoop": { - "displayText": "Anim.\nloop", - "description": "Loop icon animations in main menu" - }, - "Brightness": { - "displayText": "Screen\nbrightness", - "description": "Adjust the OLED screen brightness" - }, - "ColourInversion": { - "displayText": "Invert\nscreen", - "description": "Invert the OLED screen colors" - }, - "LOGOTime": { - "displayText": "Boot logo\nduration", - "description": "Set boot logo duration (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Detailed\nidle screen", - "description": "Display detailed info in a smaller font on idle screen" - }, - "AdvancedSoldering": { - "displayText": "Detailed\nsolder screen", - "description": "Display detailed info in a smaller font on soldering screen" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Power\nlimit", - "description": "Average maximum power the iron can use (W=watt)" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nat next boot", - "description": "Calibrate Cold Junction Compensation at next boot (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Calibrate\ninput voltage", - "description": "Start VIN calibration (long press to exit)" - }, - "PowerPulsePower": { - "displayText": "Power\npulse", - "description": "Intensity of power of keep-awake-pulse (W=watt)" - }, - "PowerPulseWait": { - "displayText": "Power pulse\ndelay", - "description": "Delay before keep-awake-pulse is triggered (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Power pulse\nduration", - "description": "Keep-awake-pulse duration (x 250ms)" - }, - "SettingsReset": { - "displayText": "Restore default\nsettings", - "description": "Reset all settings to default" - }, - "LanguageSwitch": { - "displayText": "Language:\n EN English", - "description": "" - } + "languageCode": "EN", + "languageLocalName": "English", + "tempUnitFahrenheit": true, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibration\ndone!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Certain settings\nchanged!" + }, + "NoAccelerometerMessage": { + "message": "No accelerometer\ndetected!" + }, + "NoPowerDeliveryMessage": { + "message": "No USB-PD IC\ndetected!" + }, + "LockingKeysString": { + "message": "LOCKED" + }, + "UnlockingKeysString": { + "message": "UNLOCKED" + }, + "WarningKeysLockedString": { + "message": "!LOCKED!" + }, + "WarningThermalRunaway": { + "message": "Thermal\nRunaway" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Before rebooting, make sure tip & handle are at room temperature!" + }, + "CJCCalibrating": { + "message": "calibrating\n" + }, + "SettingsResetWarning": { + "message": "Are you sure you want to restore default settings?" + }, + "UVLOWarningString": { + "message": "DC LOW" + }, + "UndervoltageString": { + "message": "Undervoltage\n" + }, + "InputVoltageString": { + "message": "Input V: \n" + }, + "SleepingAdvancedString": { + "message": "Sleeping...\n" + }, + "SleepingTipAdvancedString": { + "message": "Tip: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Your device is most likely a counterfeit!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "R", + "SettingLeftChar": "L", + "SettingAutoChar": "A", + "SettingSlowChar": "S", + "SettingMediumChar": "M", + "SettingFastChar": "F", + "SettingStartSolderingChar": "S", + "SettingStartSleepChar": "Z", + "SettingStartSleepOffChar": "R", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Power\nsettings", + "description": "" + }, + "SolderingMenu": { + "displayText": "Soldering\nsettings", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Sleep\nmode", + "description": "" + }, + "UIMenu": { + "displayText": "User\ninterface", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Advanced\nsettings", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Power\nsource", + "description": "Set cutoff voltage to prevent battery overdischarge (DC=10V) (S=3.3V per cell, disable PWR limit)" + }, + "MinVolCell": { + "displayText": "Minimum\nvoltage", + "description": "Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\nvoltage", + "description": "Max QC voltage the iron should negotiate for" + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Boost\ntemp", + "description": "Tip temperature used in \"boost mode\"" + }, + "AutoStart": { + "displayText": "Start-up\nbehavior", + "description": "S=heat to soldering temp | Z=standby at sleep temp until moved | R=standby without heating until moved" + }, + "TempChangeShortStep": { + "displayText": "Temp change\nshort", + "description": "Temperature-change-increment on short button press" + }, + "TempChangeLongStep": { + "displayText": "Temp change\nlong", + "description": "Temperature-change-increment on long button press" + }, + "LockingMode": { + "displayText": "Allow locking\nbuttons", + "description": "While soldering, hold down both buttons to toggle locking them (B=boost mode only | F=full locking)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Motion\nsensitivity", + "description": "1=least sensitive | ... | 9=most sensitive" + }, + "SleepTemperature": { + "displayText": "Sleep\ntemp", + "description": "Tip temperature while in \"sleep mode\"" + }, + "SleepTimeout": { + "displayText": "Sleep\ntimeout", + "description": "Interval before \"sleep mode\" starts (s=seconds | m=minutes)" + }, + "ShutdownTimeout": { + "displayText": "Shutdown\ntimeout", + "description": "Interval before the iron shuts down (m=minutes)" + }, + "HallEffSensitivity": { + "displayText": "Hall sensor\nsensitivity", + "description": "Sensitivity to magnets (1=least sensitive | ... | 9=most sensitive)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval before \"sleep mode\" starts when hall effect is above threshold" + }, + "TemperatureUnit": { + "displayText": "Temperature\nunit", + "description": "C=°Celsius | F=°Fahrenheit" + }, + "DisplayRotation": { + "displayText": "Display\norientation", + "description": "R=right-handed | L=left-handed | A=automatic" + }, + "CooldownBlink": { + "displayText": "Cooldown\nflashing", + "description": "Flash temp reading at idle while tip is hot" + }, + "ScrollingSpeed": { + "displayText": "Scrolling\nspeed", + "description": "Scrolling speed of info text (S=slow | F=fast)" + }, + "ReverseButtonTempChange": { + "displayText": "Swap\n+ - keys", + "description": "Reverse assignment of buttons for temperature adjustment" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\nspeed", + "description": "Pace of icon animations in menu (S=slow | M=medium | F=fast)" + }, + "AnimLoop": { + "displayText": "Anim.\nloop", + "description": "Loop icon animations in main menu" + }, + "Brightness": { + "displayText": "Screen\nbrightness", + "description": "Adjust the OLED screen brightness" + }, + "ColourInversion": { + "displayText": "Invert\nscreen", + "description": "Invert the OLED screen colors" + }, + "LOGOTime": { + "displayText": "Boot logo\nduration", + "description": "Set boot logo duration (s=seconds)" + }, + "AdvancedIdle": { + "displayText": "Detailed\nidle screen", + "description": "Display detailed info in a smaller font on idle screen" + }, + "AdvancedSoldering": { + "displayText": "Detailed\nsolder screen", + "description": "Display detailed info in a smaller font on soldering screen" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Power\nlimit", + "description": "Average maximum power the iron can use (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Calibrate CJC\nat next boot", + "description": "Calibrate Cold Junction Compensation at next boot (not required if Delta T is < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Calibrate\ninput voltage", + "description": "Start VIN calibration (long press to exit)" + }, + "PowerPulsePower": { + "displayText": "Power\npulse", + "description": "Intensity of power of keep-awake-pulse (W=watt)" + }, + "PowerPulseWait": { + "displayText": "Power pulse\ndelay", + "description": "Delay before keep-awake-pulse is triggered (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Power pulse\nduration", + "description": "Keep-awake-pulse duration (x 250ms)" + }, + "SettingsReset": { + "displayText": "Restore default\nsettings", + "description": "Reset all settings to default" + }, + "LanguageSwitch": { + "displayText": "Language:\n EN English", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_ES.json b/Translations/translation_ES.json index 34c4125da..62d0a78a2 100644 --- a/Translations/translation_ES.json +++ b/Translations/translation_ES.json @@ -1,320 +1,351 @@ { - "languageCode": "ES", - "languageLocalName": "Castellano", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "¡Calibracion\nlista!" - }, - "ResetOKMessage": { - "message": "Listo" - }, - "SettingsResetMessage": { - "message": "¡Ajustes\nReiniciados!" - }, - "NoAccelerometerMessage": { - "message": "¡Sin acelerómetro\nDetectado!" - }, - "NoPowerDeliveryMessage": { - "message": "¡Sin USB-PD IC\nDetectado!" - }, - "LockingKeysString": { - "message": "BLOQUEADO" - }, - "UnlockingKeysString": { - "message": "DESBLOQUEADO" - }, - "WarningKeysLockedString": { - "message": "¡BLOQUEADO!" - }, - "WarningThermalRunaway": { - "message": "Térmico\nFuera de control" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "¡Antes de reiniciar, asegúrese de que la punta y el mango estén a temperatura ambiente!" - }, - "CJCCalibrating": { - "message": "Calibrando\n" - }, - "SettingsResetWarning": { - "message": "¿Quieres restablecer los ajustes?" - }, - "UVLOWarningString": { - "message": "CC BAJA" - }, - "UndervoltageString": { - "message": "Voltaje bajo\n" - }, - "InputVoltageString": { - "message": "Voltaje: \n" - }, - "SleepingSimpleString": { - "message": "Reposo" - }, - "SleepingAdvancedString": { - "message": "En reposo...\n" - }, - "SleepingTipAdvancedString": { - "message": "Punta: \n" - }, - "OffString": { - "message": "Apagado" - }, - "ProfilePreheatString": { - "message": "Precalentado\n" - }, - "ProfileCooldownString": { - "message": "Enfriado\n" - }, - "DeviceFailedValidationWarning": { - "message": "¡Es probable es que su dispositivo sea falso!" - }, - "TooHotToStartProfileWarning": { - "message": "Muy caliente para \nempezar perfil" - } - }, - "characters": { - "SettingRightChar": "D", - "SettingLeftChar": "I", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "L", - "SettingMediumChar": "M", - "SettingFastChar": "R", - "SettingStartNoneChar": "N", - "SettingStartSolderingChar": "S", - "SettingStartSleepChar": "R", - "SettingStartSleepOffChar": "F", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Potencia\najustes", - "description": "" - }, - "SolderingMenu": { - "displayText": "Soldadura\najustes", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Modos de\nreposo", - "description": "" - }, - "UIMenu": { - "displayText": "Interfaz\nde usuario", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Ajustes\navanzados", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Fuente\nde energía", - "description": "Elige el tipo de fuente para limitar el voltaje (DC 10V) (S 3,3V por pila, ilimitado)" - }, - "MinVolCell": { - "displayText": "Mínimo\nvoltaje", - "description": "Voltaje mínimo permitido por célula (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" - }, - "QCMaxVoltage": { - "displayText": "Potencia de\nentrada", - "description": "Potencia en Watts del adaptador de corriente utilizado" - }, - "PDNegTimeout": { - "displayText": "PD\ntiempo de espera", - "description": "Timeout de negociación de PD en pasos de 100ms para compatibilidad con algunos cargadores QC (0: apagado)" - - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Permite modos PPS & EPR" - }, - "BoostTemperature": { - "displayText": "Ajustar la\ntemp. extra", - "description": "Temperatura de la punta de \"modo boost\"" - }, - "AutoStart": { - "displayText": "Calentar\nal enchufar", - "description": "Calentado automático al iniciar (N=no | S=entrar en modo soldar | R=solo entrar en reposo | F=en reposo pero mantiene la punta fría)" - }, - "TempChangeShortStep": { - "displayText": "Cambio temp.\npuls. cortas", - "description": "Aumento de la temperatura al pulsar brevemente un botón" - }, - "TempChangeLongStep": { - "displayText": "Cambio temp.\npuls. largas", - "description": "Aumento de la temperatura al pulsar prolongadamente un botón" - }, - "LockingMode": { - "displayText": "Permitir botones\nbloqueo", - "description": "Mientras suelda, mantenga pulsados ambos botones para alternar su bloqueo (D=desactivar | B=sólo modo boost | F=bloqueo total)" - }, - "ProfilePhases": { - "displayText": "Fases de\nPerfil", - "description": "Numero de fases en modo perfil" - }, - "ProfilePreheatTemp": { - "displayText": "Temp de \n precalentado", - "description": "Precalentar a esta temperatura al inicio del modo perfil" - }, - "ProfilePreheatSpeed": { - "displayText": "Velocidad de \nPrecalentado", - "description": "Precalentar a esta velocidad (grados por segundo)" - }, - "ProfilePhase1Temp": { - "displayText": "Fase 1\nTemp", - "description": "Temperatura objetivo al final de esta fase" - }, - "ProfilePhase1Duration": { - "displayText": "Fase 1\nDuración", - "description": "Duración objetivo de esta fase (segundos)" - }, - "ProfilePhase2Temp": { - "displayText": "Fase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Fase 2\nDuración", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Fase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Fase 3\nDuración", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Fase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Fase 4\nDuración", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Fase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Fase 5\nDuración", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Velocidad de\nEnfriamineto", - "description": "Enfriar a esta velocidad al final del modo perfil (grados por segundo)" - }, - "MotionSensitivity": { - "displayText": "Detección de\nmovimiento", - "description": "Tiempo de reacción al agarrar (0=no | 1=menos sensible | ... | 9=más sensible)" - }, - "SleepTemperature": { - "displayText": "Temperatura\nen reposo", - "description": "Temperatura de la punta en \"reposo\"" - }, - "SleepTimeout": { - "displayText": "Entrar\nen reposo", - "description": "Tiempo de inactividad para entrar en reposo (min | seg)" - }, - "ShutdownTimeout": { - "displayText": "Tiempo de\napagado", - "description": "Tiempo de inactividad para apagarse (en minutos)" - }, - "HallEffSensitivity": { - "displayText": "Hall Eff\nSensibilidad", - "description": "Sensibilidad del sensor de efecto Hall en la detección de reposo (0=no | 1=menos sensible | ... | 9=más sensible)" - }, - "TemperatureUnit": { - "displayText": "Unidad de\ntemperatura", - "description": "Unidad de temperatura (C=entígrados | F=Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "Orientación\nde pantalla", - "description": "Orientación de la pantalla (D=diestro | I=zurdo | A=automático)" - }, - "CooldownBlink": { - "displayText": "Parpadear\nal enfriar", - "description": "Parpadear texto en inactivo cuando la punta este caliente" - }, - "ScrollingSpeed": { - "displayText": "Velocidad\ndel texto", - "description": "Velocidad de desplazamiento del texto (R=rápida | L=lenta)" - }, - "ReverseButtonTempChange": { - "displayText": "Invertir\nbotones +/-", - "description": "Invertir botones de ajuste de temperatura" - }, - "AnimSpeed": { - "displayText": "Anim.\nvelocidad", - "description": "Velocidad de animaciones de iconos en el menú (O=apagado | L=baja | M=media | R=alta)" - }, - "AnimLoop": { - "displayText": "Anim.\nbucle", - "description": "Bucle de animaciones del menú principal" - }, - "Brightness": { - "displayText": "Pantalla\nbrillo", - "description": "Ajusta el brillo de la pantalla OLED" - }, - "ColourInversion": { - "displayText": "Invertir\npantalla", - "description": "Invertir la pantalla OLED" - }, - "LOGOTime": { - "displayText": "Logo inicial\nduración", - "description": "Duración de la animación del logo inicial (s=segundos)" - }, - "AdvancedIdle": { - "displayText": "Info extra en\nmodo reposo", - "description": "Mostrar información detallada en tamaño pequeño en la pantalla de reposo" - }, - "AdvancedSoldering": { - "displayText": "Info extra\nal soldar", - "description": "Mostrar información detallada en tamaño pequeño en la pantalla de soldadura" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Habilitar BLE" - }, - "PowerLimit": { - "displayText": "Potencia\nlímite", - "description": "Elige el límite de potencia máxima del soldador (en Watts)" - }, - "CalibrateCJC": { - "displayText": "Calibrar CJC\nen el próximo inicio", - "description": "Al siguinte inicio el Cold Junction Compensation sera calibrado (no requerido si el Delta T es < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Calibrar voltaje\nde entrada", - "description": "Iniciar calibración VIN (pulsación larga para salir)" - }, - "PowerPulsePower": { - "displayText": "Pulsos bat.\nconstantes", - "description": "Intensidad de la potencia del pulso para mantener encendido (W=Watt)" - }, - "PowerPulseWait": { - "displayText": "Tiempor entre\n pulso de energia", - "description": "Tiempo de espera del pulso para mantener encendido (x 2,5s)" - }, - "PowerPulseDuration": { - "displayText": "Duración de\n pulso de energia", - "description": "Duración del pulso para mantener encendido (x 250ms)" - }, - "SettingsReset": { - "displayText": "Volver a ajustes\nde fábrica", - "description": "Restablecer todos los ajustes por defecto" - }, - "LanguageSwitch": { - "displayText": "Idioma:\n ES Castellano", - "description": "" - } + "languageCode": "ES", + "languageLocalName": "Castellano", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "¡Calibracion\nlista!" + }, + "ResetOKMessage": { + "message": "Listo" + }, + "SettingsResetMessage": { + "message": "¡Ajustes\nReiniciados!" + }, + "NoAccelerometerMessage": { + "message": "¡Sin acelerómetro\nDetectado!" + }, + "NoPowerDeliveryMessage": { + "message": "¡Sin USB-PD IC\nDetectado!" + }, + "LockingKeysString": { + "message": "BLOQUEADO" + }, + "UnlockingKeysString": { + "message": "DESBLOQUEADO" + }, + "WarningKeysLockedString": { + "message": "¡BLOQUEADO!" + }, + "WarningThermalRunaway": { + "message": "Térmico\nFuera de control" + }, + "WarningTipShorted": { + "message": "¡Punta en cortocircuito!" + }, + "SettingsCalibrationWarning": { + "message": "¡Antes de reiniciar, asegúrese de que la punta y el mango estén a temperatura ambiente!" + }, + "CJCCalibrating": { + "message": "Calibrando\n" + }, + "SettingsResetWarning": { + "message": "¿Quieres restablecer los ajustes?" + }, + "UVLOWarningString": { + "message": "CC BAJA" + }, + "UndervoltageString": { + "message": "Voltaje bajo\n" + }, + "InputVoltageString": { + "message": "Voltaje: \n" + }, + "SleepingAdvancedString": { + "message": "En reposo...\n" + }, + "SleepingTipAdvancedString": { + "message": "Punta: \n" + }, + "ProfilePreheatString": { + "message": "Precalentado\n" + }, + "ProfileCooldownString": { + "message": "Enfriado\n" + }, + "DeviceFailedValidationWarning": { + "message": "¡Es probable es que su dispositivo sea falso!" + }, + "TooHotToStartProfileWarning": { + "message": "Muy caliente para \nempezar perfil" + } + }, + "characters": { + "SettingRightChar": "D", + "SettingLeftChar": "I", + "SettingAutoChar": "A", + "SettingSlowChar": "L", + "SettingMediumChar": "M", + "SettingFastChar": "R", + "SettingStartSolderingChar": "S", + "SettingStartSleepChar": "R", + "SettingStartSleepOffChar": "F", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Potencia\najustes", + "description": "" + }, + "SolderingMenu": { + "displayText": "Soldadura\najustes", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Modos de\nreposo", + "description": "" + }, + "UIMenu": { + "displayText": "Interfaz\nde usuario", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Ajustes\navanzados", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Modo por\nDefecto" + }, + "USBPDModeNoDynamic": { + "displayText": "Dinámico\nNo" + }, + "USBPDModeSafe": { + "displayText": "Modo\nSeguro" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Fuente\nde energía", + "description": "Elige el tipo de fuente para limitar el voltaje (DC 10V) (S 3,3V por pila, ilimitado)" + }, + "MinVolCell": { + "displayText": "Mínimo\nvoltaje", + "description": "Voltaje mínimo permitido por célula (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" + }, + "QCMaxVoltage": { + "displayText": "Potencia de\nentrada", + "description": "Potencia en vatios del adaptador de corriente utilizado" + }, + "PDNegTimeout": { + "displayText": "PD\ntiempo de espera", + "description": "Tiempo de espera de negociación de PD en pasos de 100ms para compatibilidad con algunos cargadores QC (0: apagado)" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "Permite modos PPS & EPR" + }, + "BoostTemperature": { + "displayText": "Ajustar la\ntemp. extra", + "description": "Temperatura de la punta de \"modo boost\"" + }, + "AutoStart": { + "displayText": "Calentar\nal enchufar", + "description": "Calentado automático al iniciar (S=entrar en modo soldar | R=solo entrar en reposo | F=en reposo pero mantiene la punta fría)" + }, + "TempChangeShortStep": { + "displayText": "Cambio temp.\npuls. cortas", + "description": "Aumento de la temperatura al pulsar brevemente un botón" + }, + "TempChangeLongStep": { + "displayText": "Cambio temp.\npuls. largas", + "description": "Aumento de la temperatura al pulsar prolongadamente un botón" + }, + "LockingMode": { + "displayText": "Permitir botones\nbloqueo", + "description": "Mientras suelda, mantenga pulsados ambos botones para alternar su bloqueo (B=sólo modo boost | F=bloqueo total)" + }, + "ProfilePhases": { + "displayText": "Fases de\nPerfil", + "description": "Numero de fases en modo perfil" + }, + "ProfilePreheatTemp": { + "displayText": "Temp de \n precalentado", + "description": "Precalentar a esta temperatura al inicio del modo perfil" + }, + "ProfilePreheatSpeed": { + "displayText": "Velocidad de \nPrecalentado", + "description": "Precalentar a esta velocidad (grados por segundo)" + }, + "ProfilePhase1Temp": { + "displayText": "Fase 1\nTemp", + "description": "Temperatura objetivo al final de esta fase" + }, + "ProfilePhase1Duration": { + "displayText": "Fase 1\nDuración", + "description": "Duración objetivo de esta fase (segundos)" + }, + "ProfilePhase2Temp": { + "displayText": "Fase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Fase 2\nDuración", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Fase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Fase 3\nDuración", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Fase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Fase 4\nDuración", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Fase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Fase 5\nDuración", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Velocidad de\nEnfriamineto", + "description": "Enfriar a esta velocidad al final del modo perfil (grados por segundo)" + }, + "MotionSensitivity": { + "displayText": "Detección de\nmovimiento", + "description": "Tiempo de reacción al agarrar (1=menos sensible | ... | 9=más sensible)" + }, + "SleepTemperature": { + "displayText": "Temperatura\nen reposo", + "description": "Temperatura de la punta en \"reposo\"" + }, + "SleepTimeout": { + "displayText": "Entrar\nen reposo", + "description": "Tiempo de inactividad para entrar en reposo (min | seg)" + }, + "ShutdownTimeout": { + "displayText": "Tiempo de\napagado", + "description": "Tiempo de inactividad para apagarse (en minutos)" + }, + "HallEffSensitivity": { + "displayText": "Hall Eff\nSensibilidad", + "description": "Sensibilidad del sensor de efecto Hall en la detección de reposo (1=menos sensible | ... | 9=más sensible)" + }, + "HallEffSleepTimeout": { + "displayText": "Tiempo reposo\nSensor Hall", + "description": "Intervalo antes de que \"modo resposo\" empiece cuando sensorhall supera límite" + }, + "TemperatureUnit": { + "displayText": "Unidad de\ntemperatura", + "description": "Unidad de temperatura (C=entígrados | F=Fahrenheit)" + }, + "DisplayRotation": { + "displayText": "Orientación\nde pantalla", + "description": "Orientación de la pantalla (D=diestro | I=zurdo | A=automático)" + }, + "CooldownBlink": { + "displayText": "Parpadear\nal enfriar", + "description": "Parpadear texto en inactivo cuando la punta este caliente" + }, + "ScrollingSpeed": { + "displayText": "Velocidad\ndel texto", + "description": "Velocidad de desplazamiento del texto (R=rápida | L=lenta)" + }, + "ReverseButtonTempChange": { + "displayText": "Invertir\nbotones +/-", + "description": "Invertir botones de ajuste de temperatura" + }, + "ReverseButtonSettings": { + "displayText": "Cambiar\nteclas A B", + "description": "Asignación inversa de botonos para el menú de configuración" + }, + "AnimSpeed": { + "displayText": "Anim.\nvelocidad", + "description": "Velocidad de animaciones de iconos en el menú (L=baja | M=media | R=alta)" + }, + "AnimLoop": { + "displayText": "Anim.\nbucle", + "description": "Bucle de animaciones del menú principal" + }, + "Brightness": { + "displayText": "Pantalla\nbrillo", + "description": "Ajusta el brillo de la pantalla OLED" + }, + "ColourInversion": { + "displayText": "Invertir\npantalla", + "description": "Invertir la pantalla OLED" + }, + "LOGOTime": { + "displayText": "Logo inicial\nduración", + "description": "Duración de la animación del logo inicial (s=segundos)" + }, + "AdvancedIdle": { + "displayText": "Info extra en\nmodo reposo", + "description": "Mostrar información detallada en tamaño pequeño en la pantalla de reposo" + }, + "AdvancedSoldering": { + "displayText": "Info extra\nal soldar", + "description": "Mostrar información detallada en tamaño pequeño en la pantalla de soldadura" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Habilitar BLE" + }, + "PowerLimit": { + "displayText": "Potencia\nlímite", + "description": "Elige el límite de potencia máxima del soldador (en vatios)" + }, + "CalibrateCJC": { + "displayText": "Calibrar CJC\nen el próximo inicio", + "description": "Al siguinte inicio la compensación de referencia será calibrada (no requerido si el Delta T es < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Calibrar voltaje\nde entrada", + "description": "Iniciar calibración VIN (pulsación larga para salir)" + }, + "PowerPulsePower": { + "displayText": "Pulsos bat.\nconstantes", + "description": "Intensidad de la potencia del pulso para mantener encendido (W=Vatio)" + }, + "PowerPulseWait": { + "displayText": "Tiempor entre\n pulso de energia", + "description": "Tiempo de espera del pulso para mantener encendido (x 2,5s)" + }, + "PowerPulseDuration": { + "displayText": "Duración de\n pulso de energia", + "description": "Duración del pulso para mantener encendido (x 250ms)" + }, + "SettingsReset": { + "displayText": "Volver a ajustes\nde fábrica", + "description": "Restablecer todos los ajustes por defecto" + }, + "LanguageSwitch": { + "displayText": "Idioma:\n ES Castellano", + "description": "" + }, + "SolderingTipType": { + "displayText": "Tipo de\nTpunta", + "description": "Selecciona la punta montada" } + } } diff --git a/Translations/translation_ET.json b/Translations/translation_ET.json new file mode 100644 index 000000000..6dedbc42c --- /dev/null +++ b/Translations/translation_ET.json @@ -0,0 +1,351 @@ +{ + "languageCode": "ET", + "languageLocalName": "Eesti", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibreerimine\ntehtud!" + }, + "ResetOKMessage": { + "message": "Vaikesätted\ntaastatud" + }, + "SettingsResetMessage": { + "message": "Osad seadistused\non muutunud!" + }, + "NoAccelerometerMessage": { + "message": "Kiirendusandurit\nei tuvastatud!" + }, + "NoPowerDeliveryMessage": { + "message": "USB-PD IC\nei tuvastatud!" + }, + "LockingKeysString": { + "message": "LUKUS" + }, + "UnlockingKeysString": { + "message": "AVATUD" + }, + "WarningKeysLockedString": { + "message": "!LUKUS!" + }, + "WarningThermalRunaway": { + "message": "Termiline\närajooks" + }, + "WarningTipShorted": { + "message": "!Otsik lühises!" + }, + "SettingsCalibrationWarning": { + "message": "Enne taaskäivitamist veenduge, et otsik ja käepide on toatemperatuuril!" + }, + "CJCCalibrating": { + "message": "kalibreerimine\n" + }, + "SettingsResetWarning": { + "message": "Kas olete kindel, et soovite taastada vaikesätted?" + }, + "UVLOWarningString": { + "message": "DC MADAL" + }, + "UndervoltageString": { + "message": "Alapinge\n" + }, + "InputVoltageString": { + "message": "Sisend V: \n" + }, + "SleepingAdvancedString": { + "message": "Unerežiim...\n" + }, + "SleepingTipAdvancedString": { + "message": "Otsik: \n" + }, + "ProfilePreheatString": { + "message": "Eelkuumutus\n" + }, + "ProfileCooldownString": { + "message": "Jahtumine\n" + }, + "DeviceFailedValidationWarning": { + "message": "Teie seade on tõenäoliselt võltsing!" + }, + "TooHotToStartProfileWarning": { + "message": "Liiga kuum,\net alustada profiili" + } + }, + "characters": { + "SettingRightChar": "P", + "SettingLeftChar": "V", + "SettingAutoChar": "A", + "SettingSlowChar": "A", + "SettingMediumChar": "K", + "SettingFastChar": "T", + "SettingStartSolderingChar": "J", + "SettingStartSleepChar": "Z", + "SettingStartSleepOffChar": "P", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "T" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Toiteseaded\n", + "description": "" + }, + "SolderingMenu": { + "displayText": "Jootmise\nseaded", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Unerežiimi\nseaded", + "description": "" + }, + "UIMenu": { + "displayText": "Kasutaja-\nliides", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Täpsemad\nseaded", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Toiteallikas\nDC", + "description": "Määrab katkestuspinge, et vältida aku liigset tühjenemist. (DC 10V) (S=3,3V elemendi kohta, eemaldab voolupiirangud)" + }, + "MinVolCell": { + "displayText": "Minimaalne\npinge", + "description": "Minimaalne lubatud pinge akuelemendi kohta (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\npinge", + "description": "Maks. QC pinge, mida jootekolb läbirääkima peaks" + }, + "PDNegTimeout": { + "displayText": "PD\naegumine", + "description": "PD läbirääkimise aegumine 100ms sammudena, et tagada ühilduvus osade QC laadijatega" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "Võimaldab PPS- ja EPR-režiimi" + }, + "BoostTemperature": { + "displayText": "Boost\ntemp", + "description": "Kolviotsiku temperatuur \"boost režiimis\"" + }, + "AutoStart": { + "displayText": "Käitumine\nkäivitusel", + "description": "J=kuumuta jootmistemperatuurini | Z=unerežiim, kuni seadet liigutatakse | P=unerežiim toatemperatuuril, kuni seadet liigutatakse" + }, + "TempChangeShortStep": { + "displayText": "Temp. muut\nlühike", + "description": "Temperatuuri muutmine lühikese vajutusega" + }, + "TempChangeLongStep": { + "displayText": "Temp. muut\npikk", + "description": "Temperatuuri muutmine pika vajutusega" + }, + "LockingMode": { + "displayText": "Luba nuppude\nlukustamine", + "description": "Hoidke jootmise ajal mõlemad nupud all, et lülitada nende lukustamist (B=ainult boostrežiimis | T=täielik lukustamine)." + }, + "ProfilePhases": { + "displayText": "Profiil\nfaasid", + "description": "Faaside arv profiilirežiimis" + }, + "ProfilePreheatTemp": { + "displayText": "Eelkuumutus\ntemp.", + "description": "Eelkuumuta sellele temperatuurile profiilirežiimi alguses" + }, + "ProfilePreheatSpeed": { + "displayText": "Eelkuumutus\nkiirus", + "description": "Eelkuumuta sellise kiirusega (kraadi sekundis)." + }, + "ProfilePhase1Temp": { + "displayText": "Faas 1\ntemp.", + "description": "Selle faasi lõpu sihttemperatuur" + }, + "ProfilePhase1Duration": { + "displayText": "Faas 1\nkestus", + "description": "Selle faasi sihtkestus (sekundites)" + }, + "ProfilePhase2Temp": { + "displayText": "Faas 2\ntemp.", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Faas 2\nkestus", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Faas 3\ntemp.", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Faas 3\nkestus", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Faas 4\ntemp.", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Faas 4\nkestus", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Faas 5\ntemp.", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Faas 5\nkestus", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Jahtumise\nkiirus", + "description": "Jahtumine selle kiirusega profiilirežiimi lõpus (kraadi sekundis)" + }, + "MotionSensitivity": { + "displayText": "Liikumise\ntundlikkus", + "description": "1=vähetundlikuim | ... | 9=kõige tundlikum" + }, + "SleepTemperature": { + "displayText": "Unerežiimi\ntemp", + "description": "Kolviotsiku temperatuur \"unerežiimis\"" + }, + "SleepTimeout": { + "displayText": "Unerežiimi\nviide", + "description": "Aeg enne \"unerežiimi\" algust (s=sekundid | m=minutid)" + }, + "ShutdownTimeout": { + "displayText": "Seiskumise\nviide", + "description": "Aeg enne jootekolvi välja lülitamist (m=minutid)" + }, + "HallEffSensitivity": { + "displayText": "Halli anduri\ntundlikkus", + "description": "Tundlikkus magnetite suhtes (1=vähetundlikum | ... | 9=kõige tundlikum)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Intervall enne \"unerežiimi\" käivitub, kui saaliefekt on üle läve" + }, + "TemperatureUnit": { + "displayText": "Temperatuuri\nühik", + "description": "C=°Celsius | F=°Fahrenheit" + }, + "DisplayRotation": { + "displayText": "Ekraani\norienteeritus", + "description": "P=paremakäeline | V=vasakukäeline | A=automaatne" + }, + "CooldownBlink": { + "displayText": "Jahtumisel\nvilkumine", + "description": "Vilguta otsiku temperatuuri, kui see jahtub ja on veel ohtlikult kuum" + }, + "ScrollingSpeed": { + "displayText": "Kerimise\nkiirus", + "description": "Infoteksti kerimise kiirus (A = aeglane | K = kiire)" + }, + "ReverseButtonTempChange": { + "displayText": "Vaheta\n+ - nupud", + "description": "Temperatuurinuppude asukohtade vahetus" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\nkiirus", + "description": "Menüüikoonide animatsiooni kiirus (A=aeglane | K=keskmine | T=tempokas)" + }, + "AnimLoop": { + "displayText": "Pidevad\nanim.", + "description": "Esitage menüüs pidevalt animatsioone" + }, + "Brightness": { + "displayText": "Ekraani\nheledus", + "description": "Seadista OLED ekraani heledust" + }, + "ColourInversion": { + "displayText": "Ekraani\ninverteerimine", + "description": "Inverteeri OLED ekraani värvid" + }, + "LOGOTime": { + "displayText": "Alguslogo\nkestus", + "description": "Aeg, mille jooksul näidatakse logo peale kolvi käivitamist (s=sekundites)" + }, + "AdvancedIdle": { + "displayText": "Andmed\npuhkeolekus", + "description": "Näita unerežiimis üksikasjalikumat teavet väiksemas kirjas" + }, + "AdvancedSoldering": { + "displayText": "Andmed\njootmisel", + "description": "Näita jootmisel üksikasjalikumat teavet väiksemas kirjas" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Luba BLE" + }, + "PowerLimit": { + "displayText": "Võimsus-\npiirang", + "description": "Suurim lubatud võimsus mida kolb võib kasutada (W=vatti)" + }, + "CalibrateCJC": { + "displayText": "Kalibr. CJC\ntuleval käivit.", + "description": "Kalibreeri külmaühenduse kompensatsioon (CJC) järgmisel käivitamisel (ei ole vajalik, kui Delta T on < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibreeri\nsisendpinge", + "description": "Sisendpinge (VIN) kalibreerimine (väljumiseks vajutage pikalt)" + }, + "PowerPulsePower": { + "displayText": "Impulsi\ntugevus", + "description": "Ärkvelolekuimpulsi tugevus (vattides). Vajalik, vältimaks akupanga uinumist." + }, + "PowerPulseWait": { + "displayText": "Impulsi\nviivitus", + "description": "Viivitus enne ärkvelolekuimpulsi käivitumist (x 2,5s)" + }, + "PowerPulseDuration": { + "displayText": "Impulsi\nkestus", + "description": "Ärkvelolekuimpulsi kestus (x 250ms)" + }, + "SettingsReset": { + "displayText": "Taasta\nvaikesätted", + "description": "Nulli kõik seadistused vaikesätetele" + }, + "LanguageSwitch": { + "displayText": "Keel:\n ET Eesti", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" + } + } +} diff --git a/Translations/translation_FI.json b/Translations/translation_FI.json index 9c89a8558..f35fbf327 100644 --- a/Translations/translation_FI.json +++ b/Translations/translation_FI.json @@ -1,319 +1,351 @@ { - "languageCode": "FI", - "languageLocalName": "Suomi", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Palautus" - }, - "SettingsResetMessage": { - "message": "Asetukset\npalautettu!" - }, - "NoAccelerometerMessage": { - "message": "Kiihtyvyysanturi\npuuttuu!" - }, - "NoPowerDeliveryMessage": { - "message": "USB-PD IC\npuuttuu!" - }, - "LockingKeysString": { - "message": " LUKITTU" - }, - "UnlockingKeysString": { - "message": "AUKI" - }, - "WarningKeysLockedString": { - "message": "!LUKKO!" - }, - "WarningThermalRunaway": { - "message": "Thermal\nRunaway" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Haluatko varmasti palauttaa oletusarvot?" - }, - "UVLOWarningString": { - "message": "DC ALH." - }, - "UndervoltageString": { - "message": "Alijännite\n" - }, - "InputVoltageString": { - "message": "Jännite: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Lepotila...\n" - }, - "SleepingTipAdvancedString": { - "message": "Kärki: \n" - }, - "OffString": { - "message": "Off" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Your device is most likely a counterfeit!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "O", - "SettingLeftChar": "V", - "SettingAutoChar": "A", - "SettingOffChar": "P", - "SettingSlowChar": "A", - "SettingMediumChar": "M", - "SettingFastChar": "S", - "SettingStartNoneChar": "E", - "SettingStartSolderingChar": "J", - "SettingStartSleepChar": "L", - "SettingStartSleepOffChar": "H", - "SettingLockDisableChar": "P", - "SettingLockBoostChar": "V", - "SettingLockFullChar": "K" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Virta-\nasetukset", - "description": "" - }, - "SolderingMenu": { - "displayText": "Juotos-\nasetukset", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Lepotilan\nasetukset", - "description": "" - }, - "UIMenu": { - "displayText": "Käyttö-\nliittymä", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Lisä-\nasetukset", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Virtalähde\nDC", - "description": "Virtalähde. Asettaa katkaisujännitteen. (DC 10V) (S 3.3V per kenno, poistaa virtarajoitukset)" - }, - "MinVolCell": { - "displayText": "Pienin\njännite", - "description": "Pienin sallittu jännite per kenno (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "QC\njännite", - "description": "Ensisijainen maksimi QC jännite" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Tehostus-\nlämpötila", - "description": "Tehostustilan lämpötila" - }, - "AutoStart": { - "displayText": "Autom.\nkäynnistys", - "description": "Käynnistää virrat kytkettäessä juotostilan automaattisesti. (E=Ei käytössä | J=juotostila | L=Lepotila | H=Lepotila huoneenlämpö)" - }, - "TempChangeShortStep": { - "displayText": "Lämmön muutos\nlyhyt painal.", - "description": "Lämpötilan muutos lyhyellä painalluksella" - }, - "TempChangeLongStep": { - "displayText": "Lämmön muutos\npitkä painal.", - "description": "Lämpötilan muutos pitkällä painalluksella" - }, - "LockingMode": { - "displayText": "Salli nappien\nlukitus", - "description": "Kolvatessa paina molempia näppäimiä lukitaksesi ne (P=pois | V=vain tehostus | K=kaikki)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Liikkeen\nherkkyys", - "description": "0=pois päältä | 1=vähäinen herkkyys | ... | 9=suurin herkkyys" - }, - "SleepTemperature": { - "displayText": "Lepotilan\nlämpötila", - "description": "Kärjen lämpötila \"lepotilassa\"" - }, - "SleepTimeout": { - "displayText": "Lepotilan\nviive", - "description": "\"Lepotilan\" ajastus (s=sekuntia | m=minuuttia)" - }, - "ShutdownTimeout": { - "displayText": "Sammutus\nviive", - "description": "Automaattisen sammutuksen ajastus (m=minuuttia)" - }, - "HallEffSensitivity": { - "displayText": "Hall-\nherk.", - "description": "Hall-efektianturin herkkyys lepotilan tunnistuksessa (0=pois päältä | 1=vähäinen herkkyys | ... | 9=suurin herkkyys)" - }, - "TemperatureUnit": { - "displayText": "Lämpötilan\nyksikkö", - "description": "C=celsius, F=fahrenheit" - }, - "DisplayRotation": { - "displayText": "Näytön\nkierto", - "description": "O=oikeakätinen | V=vasenkätinen | A=automaattinen" - }, - "CooldownBlink": { - "displayText": "Jäähdytyksen\nvilkutus", - "description": "Vilkuttaa jäähtyessä juotoskärjen lämpötilaa sen ollessa vielä vaarallisen kuuma" - }, - "ScrollingSpeed": { - "displayText": "Selityksien\nnopeus", - "description": "Selityksien vieritysnopeus (H=hidas | N=nopea)" - }, - "ReverseButtonTempChange": { - "displayText": "Suunnanvaihto\n+ - näppäimille", - "description": "Lämpötilapainikkeiden suunnan vaihtaminen" - }, - "AnimSpeed": { - "displayText": "Animaation\nnopeus", - "description": "Animaatioiden nopeus valikossa (P=pois | A=alhainen | K=keskiverto | S=suuri)" - }, - "AnimLoop": { - "displayText": "Animaation\ntoistaminen", - "description": "Toista animaatiot valikossa" - }, - "Brightness": { - "displayText": "Screen\nbrightness", - "description": "Adjust the OLED screen brightness" - }, - "ColourInversion": { - "displayText": "Invert\nscreen", - "description": "Invert the OLED screen colors" - }, - "LOGOTime": { - "displayText": "Boot logo\nduration", - "description": "Set boot logo duration (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Tiedot\nlepotilassa", - "description": "Näyttää yksityiskohtaisemmat pienemmällä fontilla tiedot lepotilassa." - }, - "AdvancedSoldering": { - "displayText": "Tarkempi\njuotosnäyttö", - "description": "Näyttää yksityiskohtaisemmat tiedot pienellä fontilla juotostilassa" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Tehon-\nrajoitus", - "description": "Suurin sallittu teho (Watti)" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nat next boot", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Kalibroi\ntulojännite?", - "description": "Tulojännitten kalibrointi (VIN) (paina pitkään poistuaksesi)" - }, - "PowerPulsePower": { - "displayText": "Herätyspulssin\nvoimakkuus", - "description": "Herätyspulssin voimakkuus (Watti)" - }, - "PowerPulseWait": { - "displayText": "Pulssin\nodotusaika", - "description": "Odotusaika herätyspulssin lähetykseen (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Pulssin\nkesto", - "description": "Herätyspulssin kesto (x 250ms)" - }, - "SettingsReset": { - "displayText": "Palauta\ntehdasasetukset?", - "description": "Palauta kaikki asetukset oletusarvoihin" - }, - "LanguageSwitch": { - "displayText": "Kieli:\n FI Suomi", - "description": "" - } + "languageCode": "FI", + "languageLocalName": "Suomi", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibrointi\nvalmis!" + }, + "ResetOKMessage": { + "message": "Tehdasasetukset\npalautettu!" + }, + "SettingsResetMessage": { + "message": "Tehdasasetukset\npalautettu!" + }, + "NoAccelerometerMessage": { + "message": "Kiihtyvyysanturi\npuuttuu!" + }, + "NoPowerDeliveryMessage": { + "message": "USB-PD IC\npuuttuu!" + }, + "LockingKeysString": { + "message": "Näppäinlukko\nkäytössä." + }, + "UnlockingKeysString": { + "message": "Näppäimet\nkäytössä." + }, + "WarningKeysLockedString": { + "message": "!Näppäimet\nlukittu!" + }, + "WarningThermalRunaway": { + "message": "!Lämmönsäätelyn\nhäiriö!" + }, + "WarningTipShorted": { + "message": "!Kärki\noikosulussa!" + }, + "SettingsCalibrationWarning": { + "message": "Varmista laitteen ja kärjen huoneenlämpöisyys ennen uudelleenkäynnistystä!" + }, + "CJCCalibrating": { + "message": "Kalibroidaan\n" + }, + "SettingsResetWarning": { + "message": "Haluatko varmasti palauttaa oletusarvot?" + }, + "UVLOWarningString": { + "message": "DC jännite alhainen." + }, + "UndervoltageString": { + "message": "Alijännite.\n" + }, + "InputVoltageString": { + "message": "Jännite: \n" + }, + "SleepingAdvancedString": { + "message": "Lepotila...\n" + }, + "SleepingTipAdvancedString": { + "message": "Kärki: \n" + }, + "ProfilePreheatString": { + "message": "Esilämmitetään\n" + }, + "ProfileCooldownString": { + "message": "Jäähtyy\n" + }, + "DeviceFailedValidationWarning": { + "message": "Laite saattaa olla väärennös!" + }, + "TooHotToStartProfileWarning": { + "message": "Lämpötila liian korkea\nprofiilin aloitukseen!" + } + }, + "characters": { + "SettingRightChar": "O", + "SettingLeftChar": "V", + "SettingAutoChar": "A", + "SettingSlowChar": "A", + "SettingMediumChar": "M", + "SettingFastChar": "S", + "SettingStartSolderingChar": "J", + "SettingStartSleepChar": "L", + "SettingStartSleepOffChar": "H", + "SettingLockBoostChar": "V", + "SettingLockFullChar": "K" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Virta-\nasetukset", + "description": "" + }, + "SolderingMenu": { + "displayText": "Juotos-\nasetukset", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Lepotilan\nasetukset", + "description": "" + }, + "UIMenu": { + "displayText": "Käyttö-\nliittymä", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Lisä-\nasetukset", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "USB-PD\noletus-t" + }, + "USBPDModeNoDynamic": { + "displayText": "USB-PD\nvakaa-ti" + }, + "USBPDModeSafe": { + "displayText": "USB-PD\nturva-ti" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Virtalähde\nDC", + "description": "Virtalähde. Asettaa katkaisujännitteen. (DC 10V) (S 3.3V per kenno, poistaa virtarajoitukset)" + }, + "MinVolCell": { + "displayText": "Pienin\njännite", + "description": "Pienin sallittu jännite per kenno (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\njännite", + "description": "Ensisijainen maksimi QC jännite." + }, + "PDNegTimeout": { + "displayText": "PD\naikakatkais", + "description": "PD neuvottelun aikakatkaisu 100ms askelin joitakin QC-latureita varten." + }, + "USBPDMode": { + "displayText": "PD\ntila", + "description": "Vakaa tila ei käytä EPR & PPS, turva-tila ei käytä vastuksen pehmustusta." + }, + "BoostTemperature": { + "displayText": "Tehostus-\nlämpötila", + "description": "Tehostustilan lämpötila." + }, + "AutoStart": { + "displayText": "Autom.\nkäynnistys", + "description": "Käynnistää virrat kytkettäessä juotostilan automaattisesti. (J=juotostila | L=Lepotila | H=Lepotila huoneenlämpö)" + }, + "TempChangeShortStep": { + "displayText": "Lämmön muutos\nlyhyt painal.", + "description": "Lämpötilan muutos lyhyellä painalluksella." + }, + "TempChangeLongStep": { + "displayText": "Lämmön muutos\npitkä painal.", + "description": "Lämpötilan muutos pitkällä painalluksella." + }, + "LockingMode": { + "displayText": "Salli nappien\nlukitus", + "description": "Kolvatessa paina molempia näppäimiä lukitaksesi ne (V=vain tehostus | K=kaikki)" + }, + "ProfilePhases": { + "displayText": "Profiili\nvaiheet", + "description": "Vaiheiden määrä profiilitilassa." + }, + "ProfilePreheatTemp": { + "displayText": "Esilämmityksen\nlämpötila", + "description": "Esilämmittää tähän lämpötilaan profiilitilan alussa." + }, + "ProfilePreheatSpeed": { + "displayText": "Esilämmityksen\nnopeus", + "description": "Esilämmityksen nopeus (asteita/sekunti)" + }, + "ProfilePhase1Temp": { + "displayText": "Vaiheen 1\nTemp", + "description": "Kohdelämpötila tämän vaiheen lopussa." + }, + "ProfilePhase1Duration": { + "displayText": "Vaiheen 1\nkesto", + "description": "Tämän vaiheen ajankäyttö (sekunteina) Saattaa kestää kauemmin jos lämmitys hitaampaa." + }, + "ProfilePhase2Temp": { + "displayText": "Vaiheen 2\nlämpötila", + "description": "Kohdelämpötila tämän vaiheen lopussa." + }, + "ProfilePhase2Duration": { + "displayText": "Vaiheen 2\nkesto", + "description": "Tämän vaiheen ajankäyttö (sekunteina) Saattaa kestää kauemmin jos lämmitys hitaampaa." + }, + "ProfilePhase3Temp": { + "displayText": "Vaiheen 3\nlämpötila", + "description": "Kohdelämpötila tämän vaiheen lopussa." + }, + "ProfilePhase3Duration": { + "displayText": "Vaiheen 3\nkesto", + "description": "Tämän vaiheen ajankäyttö (sekunteina) Saattaa kestää kauemmin jos lämmitys hitaampaa." + }, + "ProfilePhase4Temp": { + "displayText": "Vaiheen 4\nlämpötila", + "description": "Kohdelämpötila tämän vaiheen lopussa." + }, + "ProfilePhase4Duration": { + "displayText": "Vaiheen 4\nkesto", + "description": "Tämän vaiheen ajankäyttö (sekunteina) Saattaa kestää kauemmin jos lämmitys hitaampaa." + }, + "ProfilePhase5Temp": { + "displayText": "Vaiheen 5\nlämpötila", + "description": "Kohdelämpötila tämän vaiheen lopussa." + }, + "ProfilePhase5Duration": { + "displayText": "Vaiheen 5\nkesto", + "description": "Tämän vaiheen ajankäyttö (sekunteina) Saattaa kestää kauemmin jos lämmitys hitaampaa." + }, + "ProfileCooldownSpeed": { + "displayText": "Jäähtymis\nnopeus", + "description": "Jäähtymisnopeus profiilitilan lopussa (asteita sekunnissa)" + }, + "MotionSensitivity": { + "displayText": "Liikkeen\nherkkyys", + "description": "1=vähäinen herkkyys | ... | 9=suurin herkkyys" + }, + "SleepTemperature": { + "displayText": "Lepotilan\nlämpötila", + "description": "Kärjen lämpötila \"lepotilassa\"" + }, + "SleepTimeout": { + "displayText": "Lepotilan\nviive", + "description": "\"Lepotilan\" ajastus (s=sekuntia | m=minuuttia)" + }, + "ShutdownTimeout": { + "displayText": "Sammutus\nviive", + "description": "Automaattisen sammutuksen ajastus (m=minuuttia)" + }, + "HallEffSensitivity": { + "displayText": "Hall-\nherk.", + "description": "Hall-efektianturin herkkyys lepotilan tunnistuksessa (1=vähäinen herkkyys | ... | 9=suurin herkkyys)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Aikaväli ennen \"lepotilaa\" alkaa, kun hall-efekti ylittää kynnyksen" + }, + "TemperatureUnit": { + "displayText": "Lämpötilan\nyksikkö", + "description": "C=celsius, F=fahrenheit" + }, + "DisplayRotation": { + "displayText": "Näytön\nkierto", + "description": "O=oikeakätinen | V=vasenkätinen | A=automaattinen" + }, + "CooldownBlink": { + "displayText": "Jäähdytyksen\nvilkutus", + "description": "Vilkuttaa jäähtyessä juotoskärjen lämpötilaa sen ollessa vielä vaarallisen kuuma" + }, + "ScrollingSpeed": { + "displayText": "Selityksien\nnopeus", + "description": "Selityksien vieritysnopeus (H=hidas | N=nopea)" + }, + "ReverseButtonTempChange": { + "displayText": "Suunnanvaihto\n+ - näppäimille", + "description": "Lämpötilapainikkeiden suunnan vaihtaminen" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Animaation\nnopeus", + "description": "Animaatioiden nopeus valikossa (A=alhainen | K=keskiverto | S=suuri)" + }, + "AnimLoop": { + "displayText": "Animaation\ntoistaminen", + "description": "Toista animaatiot valikossa." + }, + "Brightness": { + "displayText": "Näytön\nkirkkaus", + "description": "Säädä OLED-näytön kirkkautta." + }, + "ColourInversion": { + "displayText": "Käänteiset\nvärit", + "description": "Asettaa käänteiset värit OLED-näyttöön." + }, + "LOGOTime": { + "displayText": "Käynnistysl\naika näytöllä", + "description": "Aseta käynnistyslogon aika näytöllä (s=sekunteja)" + }, + "AdvancedIdle": { + "displayText": "Tiedot\nlepotilassa", + "description": "Näyttää yksityiskohtaisemmat tiedot pienellä fontilla lepotilassa." + }, + "AdvancedSoldering": { + "displayText": "Tarkempi\njuotosnäyttö", + "description": "Näyttää yksityiskohtaisemmat tiedot pienellä fontilla juotostilassa" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "BLE käyttöön." + }, + "PowerLimit": { + "displayText": "Tehon-\nrajoitus", + "description": "Suurin sallittu teho (Watti)" + }, + "CalibrateCJC": { + "displayText": "Kalibroi CJC\nensi käynnist", + "description": "Ensi käynnistyksessä kärjen Cold Junction Compensation kalibroidaan (ei tarpeellista jos Delta T on < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibroi\ntulojännite?", + "description": "Tulojännitteen kalibrointi (VIN) (paina pitkään poistuaksesi)" + }, + "PowerPulsePower": { + "displayText": "Herätyspulssin\nvoimakkuus", + "description": "Herätyspulssin voimakkuus (Watteina)" + }, + "PowerPulseWait": { + "displayText": "Pulssin\nodotusaika", + "description": "Odotusaika herätyspulssin lähetykseen (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Pulssin\nkesto", + "description": "Herätyspulssin kesto (x 250ms)" + }, + "SettingsReset": { + "displayText": "Palauta\ntehdasasetukset?", + "description": "Palauta kaikki asetukset oletusarvoihin" + }, + "LanguageSwitch": { + "displayText": "Kieli:\n FI Suomi", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_FR.json b/Translations/translation_FR.json index 56bae3024..3bd561894 100644 --- a/Translations/translation_FR.json +++ b/Translations/translation_FR.json @@ -1,319 +1,351 @@ { - "languageCode": "FR", - "languageLocalName": "Français", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Étalonnage\nterminé!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Réglages\nréinitialisés !" - }, - "NoAccelerometerMessage": { - "message": "Accéléromètre\nnon détecté !" - }, - "NoPowerDeliveryMessage": { - "message": "USB-PD\nnon détecté !" - }, - "LockingKeysString": { - "message": "VERROUIL" - }, - "UnlockingKeysString": { - "message": "DEVERROU" - }, - "WarningKeysLockedString": { - "message": "! VERR. !" - }, - "WarningThermalRunaway": { - "message": "Emballement\nthermique" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Avant de redémarrer, assurez-vous que la panne et la poignée sont à température ambiante !" - }, - "CJCCalibrating": { - "message": "Etalonnage\n" - }, - "SettingsResetWarning": { - "message": "Voulez-vous vraiment réinitialiser les paramètres aux valeurs par défaut ?" - }, - "UVLOWarningString": { - "message": "DC FAIBL" - }, - "UndervoltageString": { - "message": "Sous-tension\n" - }, - "InputVoltageString": { - "message": "V d'entrée: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "En veille...\n" - }, - "SleepingTipAdvancedString": { - "message": "Panne: \n" - }, - "OffString": { - "message": "Off" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Votre appareil semble être une contrefaçon !" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "D", - "SettingLeftChar": "G", - "SettingAutoChar": "A", - "SettingOffChar": "D", - "SettingSlowChar": "L", - "SettingMediumChar": "M", - "SettingFastChar": "R", - "SettingStartNoneChar": "D", - "SettingStartSolderingChar": "A", - "SettingStartSleepChar": "V", - "SettingStartSleepOffChar": "O", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "V" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Paramètres\nd'alim.", - "description": "" - }, - "SolderingMenu": { - "displayText": "Paramètres\nde soudure", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Mode\nveille", - "description": "" - }, - "UIMenu": { - "displayText": "Interface\nutilisateur", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Options\navancées", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Source\nd'alim.", - "description": "Source d'alimentation. Règle la tension de coupure (DC 10V) (S 3.3V par cellules, désactive la limite de puissance)" - }, - "MinVolCell": { - "displayText": "Tension\nminimale", - "description": "Tension minimale autorisée par cellule (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "Tension\nQC", - "description": "Tension maximale désirée avec une alimentation QC" - }, - "PDNegTimeout": { - "displayText": "Délai\nexpir. PD", - "description": "Délai de la negociation PD par étapes de 100ms pour la compatiblité avec certains chargeurs QC" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Temp.\nboost", - "description": "Température utilisée en \"mode boost\"" - }, - "AutoStart": { - "displayText": "Chauffer au\ndémarrage", - "description": "D=désactivé | A=activé | V=mode veille | O=mode veille à température ambiante" - }, - "TempChangeShortStep": { - "displayText": "Incrément\nappui court", - "description": "Incrément de changement de température sur appui court" - }, - "TempChangeLongStep": { - "displayText": "Incrément\nappui long", - "description": "Incrément de changement de température sur appui long" - }, - "LockingMode": { - "displayText": "Verrouiller\nles boutons", - "description": "Pendant la soudure, appuyer sur les deux boutons pour les verrouiller (D=désactivé | B=boost seulement | V=verr. total)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Sensibilité\nau mouvement", - "description": "0=désactivé | 1=peu sensible | ... | 9=très sensible" - }, - "SleepTemperature": { - "displayText": "Temp.\nveille", - "description": "Température de la panne en \"mode veille\"" - }, - "SleepTimeout": { - "displayText": "Délai\nveille", - "description": "Délai avant mise en veille (s=secondes | m=minutes)" - }, - "ShutdownTimeout": { - "displayText": "Délai\narrêt", - "description": "Délai avant l'arrêt du fer à souder (m=minutes)" - }, - "HallEffSensitivity": { - "displayText": "Sensibilité\ncapteur effet hall", - "description": "Sensibilité du capteur à effet Hall pour la mise en veille (0=désactivé | 1=peu sensible | ... | 9=très sensible)" - }, - "TemperatureUnit": { - "displayText": "Unité de\ntempérature", - "description": "C=Celsius | F=Fahrenheit" - }, - "DisplayRotation": { - "displayText": "Orientation\nde l'écran", - "description": "D=droitier | G=gaucher | A=automatique" - }, - "CooldownBlink": { - "displayText": "Refroidir en\nclignotant", - "description": "Faire clignoter la température lors du refroidissement tant que la panne est chaude" - }, - "ScrollingSpeed": { - "displayText": "Vitesse de\ndéfilement", - "description": "Vitesse de défilement du texte (R=rapide | L=lent)" - }, - "ReverseButtonTempChange": { - "displayText": "Inverser les\ntouches + -", - "description": "Inverser les boutons d'ajustement de température" - }, - "AnimSpeed": { - "displayText": "Vitesse\nanim. icônes", - "description": "Vitesse des animations des icônes dans le menu (D=désactivé | L=lente | M=moyenne | R=rapide)" - }, - "AnimLoop": { - "displayText": "Rejouer\nanim. icônes", - "description": "Rejouer en boucle les animations des icônes dans le menu principal" - }, - "Brightness": { - "displayText": "Luminosité\nde l'écran", - "description": "Ajuster la luminosité de l'écran OLED" - }, - "ColourInversion": { - "displayText": "Inverser\nles couleurs", - "description": "Inverser les couleurs de l'écran OLED" - }, - "LOGOTime": { - "displayText": "Durée logo\ndémarrage", - "description": "Définit la durée d'affichage du logo au démarrage (s=secondes)" - }, - "AdvancedIdle": { - "displayText": "Écran veille\ndétaillé", - "description": "Afficher les informations détaillées sur l'écran de veille" - }, - "AdvancedSoldering": { - "displayText": "Écran soudure\ndétaillé", - "description": "Afficher les informations détaillées sur l'écran de soudure" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Activer le bluetooth basse consommation" - }, - "PowerLimit": { - "displayText": "Limite de\npuissance", - "description": "Puissance maximale utilisable (W=watts)" - }, - "CalibrateCJC": { - "displayText": "Étalonner CJC\nau prochain démarrage", - "description": "Au prochain démarrage, la compensation de soudure froide sera calibrée (non nécessaire si Delta T est < 5°C)." - }, - "VoltageCalibration": { - "displayText": "Étalonner\ntension d'entrée", - "description": "Étalonner tension d'entrée (appui long pour quitter)" - }, - "PowerPulsePower": { - "displayText": "Puissance\nimpulsions", - "description": "Puissance des impulsions pour éviter la mise en veille des batteries (watts)" - }, - "PowerPulseWait": { - "displayText": "Délai entre\nles impulsions", - "description": "Délai entre chaque impulsion pour empêcher la mise en veille (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Durée des\nimpulsions", - "description": "Durée des impulsions pour empêcher la mise en veille (x 250ms)" - }, - "SettingsReset": { - "displayText": "Réinitialisation\nd'usine", - "description": "Réinitialiser tous les réglages" - }, - "LanguageSwitch": { - "displayText": "Langue:\n FR Français", - "description": "" - } + "languageCode": "FR", + "languageLocalName": "Français", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Étalonnage\nterminé !" + }, + "ResetOKMessage": { + "message": "Réin. OK" + }, + "SettingsResetMessage": { + "message": "Réglages\nréinitialisés !" + }, + "NoAccelerometerMessage": { + "message": "Accéléromètre\nnon détecté !" + }, + "NoPowerDeliveryMessage": { + "message": "USB-PD\nnon détecté !" + }, + "LockingKeysString": { + "message": "Verr." + }, + "UnlockingKeysString": { + "message": "Déverr." + }, + "WarningKeysLockedString": { + "message": "! VERR. !" + }, + "WarningThermalRunaway": { + "message": "Surchauffe\ncritique" + }, + "WarningTipShorted": { + "message": "!Court-circuit Panne!" + }, + "SettingsCalibrationWarning": { + "message": "Avant de redémarrer, assurez-vous que la panne et la poignée sont à température ambiante !" + }, + "CJCCalibrating": { + "message": "Étalonnage\n" + }, + "SettingsResetWarning": { + "message": "Voulez-vous vraiment réinitialiser les paramètres aux valeurs par défaut ?" + }, + "UVLOWarningString": { + "message": "DC FAIBLE" + }, + "UndervoltageString": { + "message": "Sous-tension\n" + }, + "InputVoltageString": { + "message": "Tension:\n" + }, + "SleepingAdvancedString": { + "message": "En veille...\n" + }, + "SleepingTipAdvancedString": { + "message": "Panne:\n" + }, + "ProfilePreheatString": { + "message": "Préchauffage\n" + }, + "ProfileCooldownString": { + "message": "Refroidissement\n" + }, + "DeviceFailedValidationWarning": { + "message": "Votre appareil semble être une contrefaçon !" + }, + "TooHotToStartProfileWarning": { + "message": "Trop chaud pour\nactiver le profile" + } + }, + "characters": { + "SettingRightChar": "D", + "SettingLeftChar": "G", + "SettingAutoChar": "A", + "SettingSlowChar": "L", + "SettingMediumChar": "M", + "SettingFastChar": "R", + "SettingStartSolderingChar": "A", + "SettingStartSleepChar": "V", + "SettingStartSleepOffChar": "O", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "V" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Paramètres\nd'alim.", + "description": "" + }, + "SolderingMenu": { + "displayText": "Paramètres\nde soudure", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Mode\nveille", + "description": "" + }, + "UIMenu": { + "displayText": "Interface\nutilisateur", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Options\navancées", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Mode\npar Défaut" + }, + "USBPDModeNoDynamic": { + "displayText": "Non\nDynamique" + }, + "USBPDModeSafe": { + "displayText": "Mode\nSécurisé" + }, + "TipTypeAuto": { + "displayText": "Détéction\nAuto." + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nCourt" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Source\nd'alim.", + "description": "Source d'alimentation. Définit la tension de coupure (DC 10V) (S 3.3V par cellule, désactive la limite de puissance)" + }, + "MinVolCell": { + "displayText": "Tension\nminimale", + "description": "Tension minimale autorisée par cellule (3S : 3 - 3.7V | 4-6S : 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "Tension\nQC", + "description": "Tension maximale désirée avec une alimentation QC" + }, + "PDNegTimeout": { + "displayText": "Délai\nexpir. PD", + "description": "Délai de négociation PD par paliers de 100ms pour la compatibilité avec certains chargeurs QC" + }, + "USBPDMode": { + "displayText": "Mode\nPD", + "description": "Le mode Non Dynamique désactive EPR & PPS, le mode Sécurisé n'utilise pas de résistance à la protection" + }, + "BoostTemperature": { + "displayText": "Temp.\nboost", + "description": "Température utilisée en \"mode boost\"" + }, + "AutoStart": { + "displayText": "Chauffer\nau démarrage", + "description": "A=activé | V=mode veille | O=mode veille à température ambiante" + }, + "TempChangeShortStep": { + "displayText": "Incrément\nappui court", + "description": "Incrément de changement de température sur appui court" + }, + "TempChangeLongStep": { + "displayText": "Incrément\nappui long", + "description": "Incrément de changement de température sur appui long" + }, + "LockingMode": { + "displayText": "Verrouiller\nles boutons", + "description": "Pendant la soudure, appuyer sur les deux boutons pour les verrouiller (B=boost seulement | V=verr. total)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Nombre de phases dans le mode de profile" + }, + "ProfilePreheatTemp": { + "displayText": "Temp.\nPréchauffage", + "description": "Préchauffer à cette température au début du mode de profile" + }, + "ProfilePreheatSpeed": { + "displayText": "Vitesse\nPréchauffage", + "description": "Préchauffer à cette vitesse (degrés par seconde)" + }, + "ProfilePhase1Temp": { + "displayText": "Temp.\nPhase 1", + "description": "Température séléctionnée pour la fin de cette phase" + }, + "ProfilePhase1Duration": { + "displayText": "Durée\nPhase 1", + "description": "Durée séléctionnée pour cette phase (secondes)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Vitesse de\nRefroidissement", + "description": "Refroidissement à ce rythme à la fin du mode profil (degrés par seconde)" + }, + "MotionSensitivity": { + "displayText": "Sensibilité\nau mouvement", + "description": "1=très peu sensible | ... | 9=extrêmement sensible" + }, + "SleepTemperature": { + "displayText": "Temp.\nveille", + "description": "Température de la panne en \"mode veille\"" + }, + "SleepTimeout": { + "displayText": "Délai\nveille", + "description": "Délai avant mise en veille (s=secondes | m=minutes)" + }, + "ShutdownTimeout": { + "displayText": "Délai\narrêt", + "description": "Délai avant l'arrêt du fer à souder (m=minutes)" + }, + "HallEffSensitivity": { + "displayText": "Sensibilité capteur\neffet hall", + "description": "Sensibilité du capteur à effet Hall pour la mise en veille (1=peu sensible | ... | 9=très sensible)" + }, + "HallEffSleepTimeout": { + "displayText": "Temps de veille\ncapteur effet hall", + "description": "Intervalle avant le démarrage du \"mode veille\" lorsque l'effet Hall est supérieur au seuil" + }, + "TemperatureUnit": { + "displayText": "Unité de\ntempérature", + "description": "C=Celsius | F=Fahrenheit" + }, + "DisplayRotation": { + "displayText": "Orientation\nde l'écran", + "description": "D=droitier | G=gaucher | A=automatique" + }, + "CooldownBlink": { + "displayText": "Refroidir en\nclignotant", + "description": "Faire clignoter la température lors du refroidissement tant que la panne est chaude" + }, + "ScrollingSpeed": { + "displayText": "Vitesse\nde défilement", + "description": "Vitesse de défilement du texte (R=rapide | L=lent)" + }, + "ReverseButtonTempChange": { + "displayText": "Inverser les\ntouches + -", + "description": "Inverser les boutons d'ajustement de température" + }, + "ReverseButtonSettings": { + "displayText": "Inverser les\ntouches A B", + "description": "Inverser les boutons pour le menu Paramètres" + }, + "AnimSpeed": { + "displayText": "Vitesse\nanim. icônes", + "description": "Vitesse des animations des icônes dans le menu (L=lente | M=moyenne | R=rapide)" + }, + "AnimLoop": { + "displayText": "Rejouer\nanim. icônes", + "description": "Rejouer en boucle les animations des icônes dans le menu principal" + }, + "Brightness": { + "displayText": "Luminosité\nde l'écran", + "description": "Ajuster la luminosité de l'écran OLED" + }, + "ColourInversion": { + "displayText": "Inverser\nles couleurs", + "description": "Inverser les couleurs de l'écran OLED" + }, + "LOGOTime": { + "displayText": "Durée logo\ndémarrage", + "description": "Définit la durée d'affichage du logo au démarrage (s=secondes)" + }, + "AdvancedIdle": { + "displayText": "Écran veille\ndétaillé", + "description": "Afficher les informations détaillées sur l'écran de veille" + }, + "AdvancedSoldering": { + "displayText": "Écran soudure\ndétaillé", + "description": "Afficher les informations détaillées sur l'écran de soudure" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Activer le bluetooth basse consommation" + }, + "PowerLimit": { + "displayText": "Limite de\npuissance", + "description": "Puissance maximale utilisable (W=watts)" + }, + "CalibrateCJC": { + "displayText": "Étalonner CJC\nau reboot", + "description": "Au prochain démarrage, la compensation de soudure froide (CJC) sera calibrée (non nécessaire si Delta T est < 5°C)." + }, + "VoltageCalibration": { + "displayText": "Étalonner\ntension d'entrée", + "description": "Étalonner tension d'entrée (appui long pour quitter)" + }, + "PowerPulsePower": { + "displayText": "Puissance\nimpulsions", + "description": "Puissance des impulsions pour éviter la mise en veille des batteries (watts)" + }, + "PowerPulseWait": { + "displayText": "Délai entre\nles impulsions", + "description": "Délai entre chaque impulsion pour empêcher la mise en veille (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Durée des\nimpulsions", + "description": "Durée des impulsions pour empêcher la mise en veille (x 250ms)" + }, + "SettingsReset": { + "displayText": "Réinitialisation\nd'usine", + "description": "Réinitialiser tous les réglages" + }, + "LanguageSwitch": { + "displayText": "Langue:\n FR Français", + "description": "" + }, + "SolderingTipType": { + "displayText": "Type\nde panne", + "description": "Séléctionner le type de panne utilisé" } + } } diff --git a/Translations/translation_HR.json b/Translations/translation_HR.json index a25f0e2e3..4360cdbfc 100644 --- a/Translations/translation_HR.json +++ b/Translations/translation_HR.json @@ -1,319 +1,351 @@ { - "languageCode": "HR", - "languageLocalName": "Hrvatski", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Kalibracija\ndovršena!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Neke postavke\nsu izmijenjene!" - }, - "NoAccelerometerMessage": { - "message": "Akcelerometar\nnije pronađen!" - }, - "NoPowerDeliveryMessage": { - "message": "USB-PD IC\nnije pronađen!" - }, - "LockingKeysString": { - "message": "ZAKLJUČ" - }, - "UnlockingKeysString": { - "message": "OTKLJUČ" - }, - "WarningKeysLockedString": { - "message": "ZAKLJUČ!" - }, - "WarningThermalRunaway": { - "message": "Neispravan\ngrijač" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Prije restarta provjerite da su vrh i ručka na sobnoj temperaturi!" - }, - "CJCCalibrating": { - "message": "kalibriram\n" - }, - "SettingsResetWarning": { - "message": "Jeste li sigurni da želite sve postavke vratiti na tvorničke vrijednosti?" - }, - "UVLOWarningString": { - "message": "BAT!!!" - }, - "UndervoltageString": { - "message": "PRENIZAK NAPON\n" - }, - "InputVoltageString": { - "message": "Napon V: \n" - }, - "SleepingSimpleString": { - "message": "Zzz " - }, - "SleepingAdvancedString": { - "message": "SPAVAM...\n" - }, - "SleepingTipAdvancedString": { - "message": "Vrh: \n" - }, - "OffString": { - "message": "Off" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Vaš uređaj je najvjerojatnije krivotvoren!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "D", - "SettingLeftChar": "L", - "SettingAutoChar": "A", - "SettingOffChar": "U", - "SettingSlowChar": "S", - "SettingMediumChar": "M", - "SettingFastChar": "B", - "SettingStartNoneChar": "U", - "SettingStartSolderingChar": "L", - "SettingStartSleepChar": "T", - "SettingStartSleepOffChar": "H", - "SettingLockDisableChar": "O", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "Z" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Postavke\nnapajanja", - "description": "" - }, - "SolderingMenu": { - "displayText": "Postavke\nlemljenja", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Ušteda\nenergije", - "description": "" - }, - "UIMenu": { - "displayText": "Korisničko\nsučelje", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Napredne\nopcije", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Izvor\nnapajanja", - "description": "Izvor napajanja. Postavlja napon isključivanja. (DC 10V) (S 3.3V po ćeliji)" - }, - "MinVolCell": { - "displayText": "Najniži\nnapon", - "description": "Najniži dozvoljeni napon po ćeliji baterije (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "Snaga\nnapajanja", - "description": "Snaga modula za napajanje" - }, - "PDNegTimeout": { - "displayText": "USB-PD\ntimeout", - "description": "Timeout za USB-Power Delivery u koracima od 100ms za kompatibilnost s nekim QC punjačima" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Boost\ntemp", - "description": "Temperatura u pojačanom (Boost) načinu." - }, - "AutoStart": { - "displayText": "Auto\nstart", - "description": "Ako je aktivno, lemilica po uključivanju napajanja odmah počinje grijati. (U=ugašeno | L=lemljenje | T=spavanje toplo | H=spavanje hladno)" - }, - "TempChangeShortStep": { - "displayText": "Korak temp\nkratki pritisak", - "description": "Korak temperature pri kratkom pritisku tipke" - }, - "TempChangeLongStep": { - "displayText": "Korak temp\ndugi pritisak", - "description": "Korak temperature pri dugačkom pritisku tipke" - }, - "LockingMode": { - "displayText": "Zaključavanje\ntipki", - "description": "Tokom lemljenja, držite obje tipke kako biste ih zaključali ili otključali (O=otključano | B=zaključan boost | Z=zaključano sve)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Osjetljivost\npokreta", - "description": "Osjetljivost prepoznavanja pokreta. (0=ugašeno | 1=najmanje osjetljivo | ... | 9=najosjetljivije)" - }, - "SleepTemperature": { - "displayText": "Temp\nspavanja", - "description": "Temperatura na koju se spušta lemilica nakon određenog vremena mirovanja (C | F)" - }, - "SleepTimeout": { - "displayText": "Vrijeme\nspavanja", - "description": "Vrijeme mirovanja nakon kojega lemilica spušta temperaturu. (Minute | Sekunde)" - }, - "ShutdownTimeout": { - "displayText": "Vrijeme\ngašenja", - "description": "Vrijeme mirovanja nakon kojega će se lemilica ugasiti (Minute)" - }, - "HallEffSensitivity": { - "displayText": "Osjetljivost\nHall senzora", - "description": "Osjetljivost senzora magnetskog polja za detekciju spavanja (U=Ugašeno | N=Najmanja | S=Srednja | V=Visoka)" - }, - "TemperatureUnit": { - "displayText": "Jedinica\ntemperature", - "description": "Jedinica temperature (C=Celzij | F=Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "Rotacija\nekrana", - "description": "Orijentacija ekrana (D=desnoruki | L=ljevoruki | A=automatski)" - }, - "CooldownBlink": { - "displayText": "Upozorenje\npri hlađenju", - "description": "Bljeskanje temperature prilikom hlađenja, ako je lemilica vruća" - }, - "ScrollingSpeed": { - "displayText": "Brzina\nporuka", - "description": "Brzina kretanja dugačkih poruka (B=brzo | S=sporo)" - }, - "ReverseButtonTempChange": { - "displayText": "Zamjena\n+ - tipki", - "description": "Zamjenjuje funkciju gornje i donje tipke za podešavanje temperature" - }, - "AnimSpeed": { - "displayText": "Brzina\nanimacije", - "description": "Brzina animacije ikona u menijima (U=ugašeno | S=sporo | M=srednje | B=brzo)" - }, - "AnimLoop": { - "displayText": "Ponavljanje\nanimacije", - "description": "Hoće li se animacije menija vrtiti u petlji - samo ako brzina animacije nije na \"Ugašeno\"" - }, - "Brightness": { - "displayText": "Svjetlina\nekrana", - "description": "Podešavanje svjetline OLED ekrana. Veća svjetlina može dugotrajno dovesti do pojave duhova na ekranu." - }, - "ColourInversion": { - "displayText": "Inverzija\nekrana", - "description": "Inverzan prikaz slike na ekranu" - }, - "LOGOTime": { - "displayText": "Trajanje\nboot logotipa", - "description": "Trajanje prikaza boot logotipa (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Detalji\npri čekanju", - "description": "Prikazivanje detaljnih informacija tijekom čekanja" - }, - "AdvancedSoldering": { - "displayText": "Detalji\npri lemljenju", - "description": "Prikazivanje detaljnih informacija tijekom lemljenja" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Ograničenje\nsnage", - "description": "Najveća snaga koju lemilica smije vući iz napajanja (W=watt)" - }, - "CalibrateCJC": { - "displayText": "Kalibracija kod\nsljed. starta", - "description": "Kod sljedećeg starta izvršit će se kalibracija (nije potrebno ako je pogreška manja od 5°C)" - }, - "VoltageCalibration": { - "displayText": "Kalibracija\nnapajanja", - "description": "Kalibracija ulaznog napona napajanja (Podešavanje tipkama, dugački pritisak za kraj)" - }, - "PowerPulsePower": { - "displayText": "Snaga period.\npulsa napajanja", - "description": "Intenzitet periodičkog pulsa kojega lemilica povlači kako se USB napajanje ne bi ugasilo (W=watt)" - }, - "PowerPulseWait": { - "displayText": "Interval per.\npulsa nap.", - "description": "Razmak periodičkih pulseva koje lemilica povlači kako se USB napajanje ne bi ugasilo (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Trajanje per.\npulsa nap.", - "description": "Trajanje periodičkog pulsa kojega lemilica povlači kako se USB napajanje ne bi ugasilo (x 250ms)" - }, - "SettingsReset": { - "displayText": "Tvorničke\npostavke", - "description": "Vraćanje svih postavki na tvorničke vrijednosti" - }, - "LanguageSwitch": { - "displayText": "Jezik:\n HR Hrvatski", - "description": "" - } + "languageCode": "HR", + "languageLocalName": "Hrvatski", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibracija\ndovršena!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Neke postavke\nsu izmijenjene!" + }, + "NoAccelerometerMessage": { + "message": "Akcelerometar\nnije pronađen!" + }, + "NoPowerDeliveryMessage": { + "message": "USB-PD IC\nnije pronađen!" + }, + "LockingKeysString": { + "message": "ZAKLJUČ" + }, + "UnlockingKeysString": { + "message": "OTKLJUČ" + }, + "WarningKeysLockedString": { + "message": "ZAKLJUČ!" + }, + "WarningThermalRunaway": { + "message": "Neispravan\ngrijač" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Prije restarta provjerite da su vrh i ručka na sobnoj temperaturi!" + }, + "CJCCalibrating": { + "message": "kalibriram\n" + }, + "SettingsResetWarning": { + "message": "Jeste li sigurni da želite sve postavke vratiti na tvorničke vrijednosti?" + }, + "UVLOWarningString": { + "message": "BAT!!!" + }, + "UndervoltageString": { + "message": "PRENIZAK NAPON\n" + }, + "InputVoltageString": { + "message": "Napon V: \n" + }, + "SleepingAdvancedString": { + "message": "SPAVAM...\n" + }, + "SleepingTipAdvancedString": { + "message": "Vrh: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Vaš uređaj je najvjerojatnije krivotvoren!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "D", + "SettingLeftChar": "L", + "SettingAutoChar": "A", + "SettingSlowChar": "S", + "SettingMediumChar": "M", + "SettingFastChar": "B", + "SettingStartSolderingChar": "L", + "SettingStartSleepChar": "T", + "SettingStartSleepOffChar": "H", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "Z" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Postavke\nnapajanja", + "description": "" + }, + "SolderingMenu": { + "displayText": "Postavke\nlemljenja", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Ušteda\nenergije", + "description": "" + }, + "UIMenu": { + "displayText": "Korisničko\nsučelje", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Napredne\nopcije", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Izvor\nnapajanja", + "description": "Izvor napajanja. Postavlja napon isključivanja. (DC 10V) (S 3.3V po ćeliji)" + }, + "MinVolCell": { + "displayText": "Najniži\nnapon", + "description": "Najniži dozvoljeni napon po ćeliji baterije (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "Snaga\nnapajanja", + "description": "Snaga modula za napajanje" + }, + "PDNegTimeout": { + "displayText": "USB-PD\ntimeout", + "description": "Timeout za USB-Power Delivery u koracima od 100ms za kompatibilnost s nekim QC punjačima" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Boost\ntemp", + "description": "Temperatura u pojačanom (Boost) načinu." + }, + "AutoStart": { + "displayText": "Auto\nstart", + "description": "Ako je aktivno, lemilica po uključivanju napajanja odmah počinje grijati. (L=lemljenje | T=spavanje toplo | H=spavanje hladno)" + }, + "TempChangeShortStep": { + "displayText": "Korak temp\nkratki pritisak", + "description": "Korak temperature pri kratkom pritisku tipke" + }, + "TempChangeLongStep": { + "displayText": "Korak temp\ndugi pritisak", + "description": "Korak temperature pri dugačkom pritisku tipke" + }, + "LockingMode": { + "displayText": "Zaključavanje\ntipki", + "description": "Tokom lemljenja, držite obje tipke kako biste ih zaključali ili otključali (B=zaključan boost | Z=zaključano sve)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Osjetljivost\npokreta", + "description": "Osjetljivost prepoznavanja pokreta. (1=najmanje osjetljivo | ... | 9=najosjetljivije)" + }, + "SleepTemperature": { + "displayText": "Temp\nspavanja", + "description": "Temperatura na koju se spušta lemilica nakon određenog vremena mirovanja (C | F)" + }, + "SleepTimeout": { + "displayText": "Vrijeme\nspavanja", + "description": "Vrijeme mirovanja nakon kojega lemilica spušta temperaturu. (Minute | Sekunde)" + }, + "ShutdownTimeout": { + "displayText": "Vrijeme\ngašenja", + "description": "Vrijeme mirovanja nakon kojega će se lemilica ugasiti (Minute)" + }, + "HallEffSensitivity": { + "displayText": "Osjetljivost\nHall senzora", + "description": "Osjetljivost senzora magnetskog polja za detekciju spavanja (N=Najmanja | S=Srednja | V=Visoka)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval prije pokretanja \"načina mirovanja\" kada je Hall efekt iznad praga" + }, + "TemperatureUnit": { + "displayText": "Jedinica\ntemperature", + "description": "Jedinica temperature (C=Celzij | F=Fahrenheit)" + }, + "DisplayRotation": { + "displayText": "Rotacija\nekrana", + "description": "Orijentacija ekrana (D=desnoruki | L=ljevoruki | A=automatski)" + }, + "CooldownBlink": { + "displayText": "Upozorenje\npri hlađenju", + "description": "Bljeskanje temperature prilikom hlađenja, ako je lemilica vruća" + }, + "ScrollingSpeed": { + "displayText": "Brzina\nporuka", + "description": "Brzina kretanja dugačkih poruka (B=brzo | S=sporo)" + }, + "ReverseButtonTempChange": { + "displayText": "Zamjena\n+ - tipki", + "description": "Zamjenjuje funkciju gornje i donje tipke za podešavanje temperature" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Brzina\nanimacije", + "description": "Brzina animacije ikona u menijima (S=sporo | M=srednje | B=brzo)" + }, + "AnimLoop": { + "displayText": "Ponavljanje\nanimacije", + "description": "Hoće li se animacije menija vrtiti u petlji - samo ako brzina animacije nije na \"Ugašeno\"" + }, + "Brightness": { + "displayText": "Svjetlina\nekrana", + "description": "Podešavanje svjetline OLED ekrana. Veća svjetlina može dugotrajno dovesti do pojave duhova na ekranu." + }, + "ColourInversion": { + "displayText": "Inverzija\nekrana", + "description": "Inverzan prikaz slike na ekranu" + }, + "LOGOTime": { + "displayText": "Trajanje\nboot logotipa", + "description": "Trajanje prikaza boot logotipa (s=seconds)" + }, + "AdvancedIdle": { + "displayText": "Detalji\npri čekanju", + "description": "Prikazivanje detaljnih informacija tijekom čekanja" + }, + "AdvancedSoldering": { + "displayText": "Detalji\npri lemljenju", + "description": "Prikazivanje detaljnih informacija tijekom lemljenja" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Ograničenje\nsnage", + "description": "Najveća snaga koju lemilica smije vući iz napajanja (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Kalibracija kod\nsljed. starta", + "description": "Kod sljedećeg starta izvršit će se kalibracija (nije potrebno ako je pogreška manja od 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibracija\nnapajanja", + "description": "Kalibracija ulaznog napona napajanja (Podešavanje tipkama, dugački pritisak za kraj)" + }, + "PowerPulsePower": { + "displayText": "Snaga period.\npulsa napajanja", + "description": "Intenzitet periodičkog pulsa kojega lemilica povlači kako se USB napajanje ne bi ugasilo (W=watt)" + }, + "PowerPulseWait": { + "displayText": "Interval per.\npulsa nap.", + "description": "Razmak periodičkih pulseva koje lemilica povlači kako se USB napajanje ne bi ugasilo (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Trajanje per.\npulsa nap.", + "description": "Trajanje periodičkog pulsa kojega lemilica povlači kako se USB napajanje ne bi ugasilo (x 250ms)" + }, + "SettingsReset": { + "displayText": "Tvorničke\npostavke", + "description": "Vraćanje svih postavki na tvorničke vrijednosti" + }, + "LanguageSwitch": { + "displayText": "Jezik:\n HR Hrvatski", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_HU.json b/Translations/translation_HU.json index b218dd047..096cebbd0 100644 --- a/Translations/translation_HU.json +++ b/Translations/translation_HU.json @@ -1,319 +1,351 @@ { - "languageCode": "HU", - "languageLocalName": "Magyar", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Kalibráció\nkész!" - }, - "ResetOKMessage": { - "message": "Törlés OK" - }, - "SettingsResetMessage": { - "message": "Beállítások\nvisszaállítva!" - }, - "NoAccelerometerMessage": { - "message": "Nincs\ngyorsulásmérő!" - }, - "NoPowerDeliveryMessage": { - "message": "Nincs\nUSB-PD IC!" - }, - "LockingKeysString": { - "message": "LEZÁRVA" - }, - "UnlockingKeysString": { - "message": "FELOLDVA" - }, - "WarningKeysLockedString": { - "message": "!LEZÁRVA!" - }, - "WarningThermalRunaway": { - "message": "Kontrollálatlan\nhőmérséklet!" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Újraindítás előtt a hegy és az eszköz legyen szobahőmérsékletű!" - }, - "CJCCalibrating": { - "message": "Kalibrálás\n" - }, - "SettingsResetWarning": { - "message": "Biztos visszaállítja a beállításokat alapértékekre?" - }, - "UVLOWarningString": { - "message": "DC túl alacsony" - }, - "UndervoltageString": { - "message": "Alulfeszültség\n" - }, - "InputVoltageString": { - "message": "Bemenet V: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Alvás...\n" - }, - "SleepingTipAdvancedString": { - "message": "Hegy: \n" - }, - "OffString": { - "message": "Ki" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Az eszköz valószínűleg nem eredeti!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "J", - "SettingLeftChar": "B", - "SettingAutoChar": "A", - "SettingOffChar": "0", - "SettingSlowChar": "L", - "SettingMediumChar": "K", - "SettingFastChar": "Gy", - "SettingStartNoneChar": "K", - "SettingStartSolderingChar": "F", - "SettingStartSleepChar": "A", - "SettingStartSleepOffChar": "Sz", - "SettingLockDisableChar": "K", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "T" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Táp\nbeállítások", - "description": "" - }, - "SolderingMenu": { - "displayText": "Forrasztási\nbeállítások", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Alvási\nmódok", - "description": "" - }, - "UIMenu": { - "displayText": "Felhasználói\nfelület", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Haladó\nbeállítások", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Áram\nforrás", - "description": "Kikapcsolási feszültség beállítása (DC:10V | S:3.3V/LiPo cella | ki)" - }, - "MinVolCell": { - "displayText": "Minimum\nfeszültség", - "description": "Minimális engedélyezett cellafeszültség (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "Max. USB\nfeszültség", - "description": "Maximális USB feszültség (QuickCharge)" - }, - "PDNegTimeout": { - "displayText": "PD\nidőtúllépés", - "description": "PD egyeztetés időkerete (kompatibilitás QC töltőkkel) (x 100ms)" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Boost\nhőmérséklet", - "description": "Hőmérséklet \"boost\" módban" - }, - "AutoStart": { - "displayText": "Automatikus\nindítás", - "description": "Bekapcsolás után automatikusan lépjen forrasztás módba (K=ki | F=forrasztás | A=alvó mód | Sz=szobahőmérséklet)" - }, - "TempChangeShortStep": { - "displayText": "Hőm. állítás\nrövid", - "description": "Hőmérséklet állítás rövid gombnyomásra (C | F)" - }, - "TempChangeLongStep": { - "displayText": "Hőm. állítás\nhosszú", - "description": "Hőmérséklet állítás hosszú gombnyomásra (C | F)" - }, - "LockingMode": { - "displayText": "Lezárás\nengedélyezés", - "description": "Forrasztás közben mindkét gombot hosszan lenyomva lezárja a kezelést (K=ki | B=csak \"boost\" módban | T=teljes lezárás)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Mozgás\nérzékenység", - "description": "Mozgás érzékenység beállítása (0=kikapcsolva | 1=legkevésbé érzékeny | ... | 9=legérzékenyebb)" - }, - "SleepTemperature": { - "displayText": "Alvási\nhőmérséklet", - "description": "Hőmérséklet alvó módban (C | F)" - }, - "SleepTimeout": { - "displayText": "Alvás\nidőzítő", - "description": "Alvási időzítő (perc | másodperc)" - }, - "ShutdownTimeout": { - "displayText": "Kikapcsolás\nidőzítő", - "description": "Kikapcsolási időzítő (perc)" - }, - "HallEffSensitivity": { - "displayText": "Alvásérzékelő\nérzékenység", - "description": "Alvásérzékelő gyorsulásmérő érzékenysége (0=kikapcsolva | 1=legkevésbé érzékeny | ... | 9=legérzékenyebb)" - }, - "TemperatureUnit": { - "displayText": "Hőmérséklet\nmértékegysége", - "description": "Hőmérséklet mértékegysége (C=Celsius | F=Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "Kijelző\ntájolása", - "description": "Kijelző tájolása (J=jobbkezes | B=balkezes | A=automatikus)" - }, - "CooldownBlink": { - "displayText": "Villogás\nhűléskor", - "description": "Villogjon a hőmérséklet kijelzése hűlés közben, amíg a forrasztó hegy forró" - }, - "ScrollingSpeed": { - "displayText": "Görgetés\nsebessége", - "description": "Szöveggörgetés sebessége" - }, - "ReverseButtonTempChange": { - "displayText": "+/- gomb\nmegfordítása", - "description": "Forrasztó hegy hőmérsékletállító gombok felcserélése" - }, - "AnimSpeed": { - "displayText": "Animáció\nsebessége", - "description": "Menüikonok animációjának sebessége (0=ki | L=lassú | K=közepes | Gy=gyors)" - }, - "AnimLoop": { - "displayText": "Folytonos\nanimáció", - "description": "Főmenü ikonjainak folytonos animációja" - }, - "Brightness": { - "displayText": "Képernyő\nkontraszt", - "description": "Képernyő kontrasztjának állítása" - }, - "ColourInversion": { - "displayText": "Képernyő\ninvertálás", - "description": "Képernyő színeinek invertálása" - }, - "LOGOTime": { - "displayText": "Boot logo\nmegjelenítés", - "description": "Boot logo megjelenítési idejének beállítása (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Részletes\nkészenlét", - "description": "Részletes információk megjelenítése kisebb betűméretben a készenléti képernyőn" - }, - "AdvancedSoldering": { - "displayText": "Részletes\nforrasztás infó", - "description": "Részletes információk megjelenítése forrasztás közben" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Teljesítmény\nmaximum", - "description": "Maximális felvett teljesitmény beállitása" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nköv. indításnál", - "description": "Következő indításnál a hegy Cold Junction Compensation kalibrálása (nem szükséges ha Delta T kisebb mint 5°C)" - }, - "VoltageCalibration": { - "displayText": "Bemeneti fesz.\nkalibrálása?", - "description": "Bemeneti feszültség kalibrálása (hosszan nyomva kilép)" - }, - "PowerPulsePower": { - "displayText": "Ébr. pulzus\nnagysága", - "description": "Powerbankot ébrentartó áramfelvételi pulzusok nagysága (W)" - }, - "PowerPulseWait": { - "displayText": "Ébr. pulzus\nidőköze", - "description": "Powerbankot ébrentartó áramfelvételi pulzusok időköze (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Ébr. pulzus\nidőtartama", - "description": "Powerbankot ébrentartó áramfelvételi pulzusok időtartama (x 250ms)" - }, - "SettingsReset": { - "displayText": "Gyári\nbeállítások?", - "description": "Beállítások alaphelyzetbe állítása" - }, - "LanguageSwitch": { - "displayText": "Nyelv:\n HU Magyar", - "description": "" - } + "languageCode": "HU", + "languageLocalName": "Magyar", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibráció\nkész!" + }, + "ResetOKMessage": { + "message": "Törlés OK" + }, + "SettingsResetMessage": { + "message": "Beállítások\nvisszaállítva!" + }, + "NoAccelerometerMessage": { + "message": "Nincs\ngyorsulásmérő!" + }, + "NoPowerDeliveryMessage": { + "message": "Nincs\nUSB-PD IC!" + }, + "LockingKeysString": { + "message": "LEZÁRVA" + }, + "UnlockingKeysString": { + "message": "FELOLDVA" + }, + "WarningKeysLockedString": { + "message": "!LEZÁRVA!" + }, + "WarningThermalRunaway": { + "message": "Kontrollálatlan\nhőmérséklet!" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Újraindítás előtt a hegy és az eszköz legyen szobahőmérsékletű!" + }, + "CJCCalibrating": { + "message": "Kalibrálás\n" + }, + "SettingsResetWarning": { + "message": "Biztos visszaállítja a beállításokat alapértékekre?" + }, + "UVLOWarningString": { + "message": "DC túl alacsony" + }, + "UndervoltageString": { + "message": "Alulfeszültség\n" + }, + "InputVoltageString": { + "message": "Bemenet V: \n" + }, + "SleepingAdvancedString": { + "message": "Alvás...\n" + }, + "SleepingTipAdvancedString": { + "message": "Hegy: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Az eszköz valószínűleg nem eredeti!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "J", + "SettingLeftChar": "B", + "SettingAutoChar": "A", + "SettingSlowChar": "L", + "SettingMediumChar": "K", + "SettingFastChar": "Gy", + "SettingStartSolderingChar": "F", + "SettingStartSleepChar": "A", + "SettingStartSleepOffChar": "Sz", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "T" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Táp\nbeállítások", + "description": "" + }, + "SolderingMenu": { + "displayText": "Forrasztási\nbeállítások", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Alvási\nmódok", + "description": "" + }, + "UIMenu": { + "displayText": "Felhasználói\nfelület", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Haladó\nbeállítások", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Áram\nforrás", + "description": "Kikapcsolási feszültség beállítása (DC:10V | S:3.3V/LiPo cella | ki)" + }, + "MinVolCell": { + "displayText": "Minimum\nfeszültség", + "description": "Minimális engedélyezett cellafeszültség (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "Max. USB\nfeszültség", + "description": "Maximális USB feszültség (QuickCharge)" + }, + "PDNegTimeout": { + "displayText": "PD\nidőtúllépés", + "description": "PD egyeztetés időkerete (kompatibilitás QC töltőkkel) (x 100ms)" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Boost\nhőmérséklet", + "description": "Hőmérséklet \"boost\" módban" + }, + "AutoStart": { + "displayText": "Automatikus\nindítás", + "description": "Bekapcsolás után automatikusan lépjen forrasztás módba (F=forrasztás | A=alvó mód | Sz=szobahőmérséklet)" + }, + "TempChangeShortStep": { + "displayText": "Hőm. állítás\nrövid", + "description": "Hőmérséklet állítás rövid gombnyomásra (C | F)" + }, + "TempChangeLongStep": { + "displayText": "Hőm. állítás\nhosszú", + "description": "Hőmérséklet állítás hosszú gombnyomásra (C | F)" + }, + "LockingMode": { + "displayText": "Lezárás\nengedélyezés", + "description": "Forrasztás közben mindkét gombot hosszan lenyomva lezárja a kezelést (B=csak \"boost\" módban | T=teljes lezárás)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Mozgás\nérzékenység", + "description": "Mozgás érzékenység beállítása (1=legkevésbé érzékeny | ... | 9=legérzékenyebb)" + }, + "SleepTemperature": { + "displayText": "Alvási\nhőmérséklet", + "description": "Hőmérséklet alvó módban (C | F)" + }, + "SleepTimeout": { + "displayText": "Alvás\nidőzítő", + "description": "Alvási időzítő (perc | másodperc)" + }, + "ShutdownTimeout": { + "displayText": "Kikapcsolás\nidőzítő", + "description": "Kikapcsolási időzítő (perc)" + }, + "HallEffSensitivity": { + "displayText": "Alvásérzékelő\nérzékenység", + "description": "Alvásérzékelő gyorsulásmérő érzékenysége (1=legkevésbé érzékeny | ... | 9=legérzékenyebb)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Az \"alvó üzemmód\" előtti intervallum akkor kezdődik, amikor a hall-effektus meghaladja a küszöbértéket" + }, + "TemperatureUnit": { + "displayText": "Hőmérséklet\nmértékegysége", + "description": "Hőmérséklet mértékegysége (C=Celsius | F=Fahrenheit)" + }, + "DisplayRotation": { + "displayText": "Kijelző\ntájolása", + "description": "Kijelző tájolása (J=jobbkezes | B=balkezes | A=automatikus)" + }, + "CooldownBlink": { + "displayText": "Villogás\nhűléskor", + "description": "Villogjon a hőmérséklet kijelzése hűlés közben, amíg a forrasztó hegy forró" + }, + "ScrollingSpeed": { + "displayText": "Görgetés\nsebessége", + "description": "Szöveggörgetés sebessége" + }, + "ReverseButtonTempChange": { + "displayText": "+/- gomb\nmegfordítása", + "description": "Forrasztó hegy hőmérsékletállító gombok felcserélése" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Animáció\nsebessége", + "description": "Menüikonok animációjának sebessége (L=lassú | K=közepes | Gy=gyors)" + }, + "AnimLoop": { + "displayText": "Folytonos\nanimáció", + "description": "Főmenü ikonjainak folytonos animációja" + }, + "Brightness": { + "displayText": "Képernyő\nkontraszt", + "description": "Képernyő kontrasztjának állítása" + }, + "ColourInversion": { + "displayText": "Képernyő\ninvertálás", + "description": "Képernyő színeinek invertálása" + }, + "LOGOTime": { + "displayText": "Boot logo\nmegjelenítés", + "description": "Boot logo megjelenítési idejének beállítása (s=seconds)" + }, + "AdvancedIdle": { + "displayText": "Részletes\nkészenlét", + "description": "Részletes információk megjelenítése kisebb betűméretben a készenléti képernyőn" + }, + "AdvancedSoldering": { + "displayText": "Részletes\nforrasztás infó", + "description": "Részletes információk megjelenítése forrasztás közben" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Teljesítmény\nmaximum", + "description": "Maximális felvett teljesitmény beállitása" + }, + "CalibrateCJC": { + "displayText": "Calibrate CJC\nköv. indításnál", + "description": "Következő indításnál a hegy Cold Junction Compensation kalibrálása (nem szükséges ha Delta T kisebb mint 5°C)" + }, + "VoltageCalibration": { + "displayText": "Bemeneti fesz.\nkalibrálása?", + "description": "Bemeneti feszültség kalibrálása (hosszan nyomva kilép)" + }, + "PowerPulsePower": { + "displayText": "Ébr. pulzus\nnagysága", + "description": "Powerbankot ébrentartó áramfelvételi pulzusok nagysága (W)" + }, + "PowerPulseWait": { + "displayText": "Ébr. pulzus\nidőköze", + "description": "Powerbankot ébrentartó áramfelvételi pulzusok időköze (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Ébr. pulzus\nidőtartama", + "description": "Powerbankot ébrentartó áramfelvételi pulzusok időtartama (x 250ms)" + }, + "SettingsReset": { + "displayText": "Gyári\nbeállítások?", + "description": "Beállítások alaphelyzetbe állítása" + }, + "LanguageSwitch": { + "displayText": "Nyelv:\n HU Magyar", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_IT.json b/Translations/translation_IT.json index a4250403f..0b479784a 100644 --- a/Translations/translation_IT.json +++ b/Translations/translation_IT.json @@ -1,319 +1,351 @@ { - "languageCode": "IT", - "languageLocalName": "Italiano", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibrazione\ncompletata!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Impostazioni\nripristinate" - }, - "NoAccelerometerMessage": { - "message": "Accelerometro\nnon rilevato" - }, - "NoPowerDeliveryMessage": { - "message": "USB PD\nnon rilevato" - }, - "LockingKeysString": { - "message": "Blocc." - }, - "UnlockingKeysString": { - "message": "Sblocc." - }, - "WarningKeysLockedString": { - "message": "BLOCCATO" - }, - "WarningThermalRunaway": { - "message": "Temperatura\nfuori controllo" - }, - "WarningTipShorted": { - "message": "Punta in cortocircuito!" - }, - "SettingsCalibrationWarning": { - "message": "Prima di riavviare assicurati che la punta e l'impugnatura siano a temperatura ambiente!" - }, - "CJCCalibrating": { - "message": "Calibrazione in corso\n" - }, - "SettingsResetWarning": { - "message": "Ripristinare le impostazioni predefinite?" - }, - "UVLOWarningString": { - "message": "DC BASSA" - }, - "UndervoltageString": { - "message": "DC INSUFFICIENTE\n" - }, - "InputVoltageString": { - "message": "V in: \n" - }, - "SleepingSimpleString": { - "message": "Zzz " - }, - "SleepingAdvancedString": { - "message": "Riposo\n" - }, - "SleepingTipAdvancedString": { - "message": "Punta: \n" - }, - "OffString": { - "message": "OFF" - }, - "ProfilePreheatString": { - "message": "Preriscaldamento\n" - }, - "ProfileCooldownString": { - "message": "Raffreddamento\n" - }, - "DeviceFailedValidationWarning": { - "message": "È probabile che questo dispositivo sia contraffatto!" - }, - "TooHotToStartProfileWarning": { - "message": "Troppo caldo\nper il profilo" - } - }, - "characters": { - "SettingRightChar": "D", - "SettingLeftChar": "S", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "L", - "SettingMediumChar": "M", - "SettingFastChar": "V", - "SettingStartNoneChar": "D", - "SettingStartSolderingChar": "S", - "SettingStartSleepChar": "R", - "SettingStartSleepOffChar": "A", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "T", - "SettingLockFullChar": "C" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Opzioni\nalimentaz", - "description": "" - }, - "SolderingMenu": { - "displayText": "Opzioni\nsaldatura", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Risparmio\nenergetico", - "description": "" - }, - "UIMenu": { - "displayText": "Interfaccia\nutente", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Opzioni\navanzate", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Sorgente\nalimentaz", - "description": "Imposta una tensione minima di alimentazione attraverso la selezione di una sorgente [DC: 10 V; 3S/4S/5S/6S: 3,3 V per cella]" - }, - "MinVolCell": { - "displayText": "Tensione\nmin celle", - "description": "Modifica la tensione di minima carica delle celle di una batteria Li-Po [3S: 3,0-3,7 V; 4S/5S/6S: 2,4-3,7 V]" - }, - "QCMaxVoltage": { - "displayText": "Tensione\nQC", - "description": "Imposta la massima tensione negoziabile con un alimentatore Quick Charge [volt]" - }, - "PDNegTimeout": { - "displayText": "Abilitazione\nUSB PD", - "description": "Regola il massimo tempo utile per la negoziazione del protocollo USB Power Delivery con alimentatori compatibili [0: disattiva; multipli di 100 ms]" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Abilita le modalità Power Delivery PPS ed EPR" - }, - "BoostTemperature": { - "displayText": "Temp\nTurbo", - "description": "Imposta la temperatura della funzione turbo [°C/°F]" - }, - "AutoStart": { - "displayText": "Avvio\nautomatico", - "description": "Attiva automaticamente il saldatore quando viene alimentato [D: disattiva; S: saldatura; R: riposo; A: temperatura ambiente]" - }, - "TempChangeShortStep": { - "displayText": "Temp passo\nbreve", - "description": "Imposta il passo dei valori di temperatura per una breve pressione dei tasti" - }, - "TempChangeLongStep": { - "displayText": "Temp passo\nlungo", - "description": "Imposta il passo dei valori di temperatura per una lunga pressione dei tasti" - }, - "LockingMode": { - "displayText": "Blocco\ntasti", - "description": "Blocca i tasti durante la modalità saldatura; tieni premuto entrambi per bloccare o sbloccare [D: disattiva; T: consenti Turbo; C: blocco completo]" - }, - "ProfilePhases": { - "displayText": "Fasi modalità\nprofilo", - "description": "Imposta il numero di fasi da attuare per un profilo di riscaldamento personalizzato" - }, - "ProfilePreheatTemp": { - "displayText": "Temperatura\npreriscaldamento", - "description": "Imposta la temperatura di preriscaldamento da raggiungere all'inizio del profilo di riscaldamento" - }, - "ProfilePreheatSpeed": { - "displayText": "Velocità\npreriscaldamento", - "description": "Imposta la velocità di preriscaldamento [°C/s]" - }, - "ProfilePhase1Temp": { - "displayText": "Temperatura\nfase 1", - "description": "Imposta la temperatura da raggiungere alla fine di questa fase" - }, - "ProfilePhase1Duration": { - "displayText": "Durata\nfase 1", - "description": "Imposta la durata di questa fase [secondi]" - }, - "ProfilePhase2Temp": { - "displayText": "Temperatura\nfase 2", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Durata\nfase 2", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Temperatura\nfase 3", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Durata\nfase 3", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Temperatura\nfase 4", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Durata\nfase 4", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Temperatura\nfase 5", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Durata\nfase 5", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Velocità\nraffreddamento", - "description": "Imposta la velocità di raffreddamento al termine del profilo di riscaldamento [°C/s]" - }, - "MotionSensitivity": { - "displayText": "Sensibilità\nal movimento", - "description": "Imposta la sensibilità al movimento per uscire dalla modalità riposo [0: nessuna; 1: minima; 9: massima]" - }, - "SleepTemperature": { - "displayText": "Temperatura\nriposo", - "description": "Imposta la temperatura da mantenere in modalità riposo [°C/°F]" - }, - "SleepTimeout": { - "displayText": "Timer\nriposo", - "description": "Imposta il timer per entrare in modalità riposo [secondi/minuti]" - }, - "ShutdownTimeout": { - "displayText": "Timer\nspegnimento", - "description": "Imposta il timer per lo spegnimento [minuti]" - }, - "HallEffSensitivity": { - "displayText": "Sensore\nHall", - "description": "Regola la sensibilità del sensore ad effetto Hall per entrare in modalità riposo [0: nessuna; 1: minima; 9: massima]" - }, - "TemperatureUnit": { - "displayText": "Unità di\ntemperatura", - "description": "Scegli l'unità di misura per la temperatura [C: grado Celsius; F: grado Farenheit]" - }, - "DisplayRotation": { - "displayText": "Orientamento\nschermo", - "description": "Imposta l'orientamento dello schermo [D: mano destra; S: mano sinistra; A: automatico]" - }, - "CooldownBlink": { - "displayText": "Avviso\npunta calda", - "description": "Evidenzia il valore di temperatura durante il raffreddamento se la punta è ancora calda" - }, - "ScrollingSpeed": { - "displayText": "Velocità\ntesto", - "description": "Imposta la velocità di scorrimento del testo [L: lenta; V: veloce]" - }, - "ReverseButtonTempChange": { - "displayText": "Inversione\ntasti", - "description": "Inverti i tasti per aumentare o diminuire la temperatura della punta" - }, - "AnimSpeed": { - "displayText": "Velocità\nanimazioni", - "description": "Imposta la velocità di riproduzione delle animazioni del menù principale [O: OFF; L: lenta; M: media; V: veloce]" - }, - "AnimLoop": { - "displayText": "Ciclo\nanimazioni", - "description": "Abilita la riproduzione ciclica delle animazioni del menù principale" - }, - "Brightness": { - "displayText": "Luminosità\nschermo", - "description": "Regola la luminosità dello schermo [1: minimo; 10: massimo]" - }, - "ColourInversion": { - "displayText": "Inverti\ncolori", - "description": "Inverti i colori dello schermo" - }, - "LOGOTime": { - "displayText": "Durata\nlogo", - "description": "Imposta la permanenza sullo schermo del logo iniziale [secondi]" - }, - "AdvancedIdle": { - "displayText": "Interfaccia\ntestuale", - "description": "Mostra informazioni dettagliate all'interno della schermata principale" - }, - "AdvancedSoldering": { - "displayText": "Dettagli\nsaldatura", - "description": "Mostra informazioni dettagliate durante la modalità saldatura" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Abilita BLE" - }, - "PowerLimit": { - "displayText": "Limite\npotenza", - "description": "Imposta il valore di potenza massima erogabile al saldatore [watt]" - }, - "CalibrateCJC": { - "displayText": "Calibra T\nall'avvio", - "description": "Calibra le rilevazioni di temperatura al prossimo riavvio (non necessario se lo scarto di temperatura è minore di 5 °C)" - }, - "VoltageCalibration": { - "displayText": "Calibrazione\ntensione", - "description": "Calibra la tensione in ingresso; regola con entrambi i tasti, tieni premuto il tasto superiore per uscire" - }, - "PowerPulsePower": { - "displayText": "Potenza\nimpulso", - "description": "Regola la potenza di un \"impulso sveglia\" atto a prevenire lo standby eventuale dell'alimentatore [watt]" - }, - "PowerPulseWait": { - "displayText": "Distanza\nimpulsi", - "description": "Imposta il tempo che deve intercorrere tra due \"impulsi sveglia\" [multipli di 2,5 s]" - }, - "PowerPulseDuration": { - "displayText": "Durata\nimpulso", - "description": "Regola la durata dell'«impulso sveglia» [multipli di 250 ms]" - }, - "SettingsReset": { - "displayText": "Ripristino\nimpostazioni", - "description": "Ripristina le impostazioni predefinite" - }, - "LanguageSwitch": { - "displayText": "Lingua:\n IT Italiano", - "description": "" - } + "languageCode": "IT", + "languageLocalName": "Italiano", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibrazione\ncompletata!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Impostazioni\nripristinate" + }, + "NoAccelerometerMessage": { + "message": "Accelerometro\nnon rilevato" + }, + "NoPowerDeliveryMessage": { + "message": "USB PD\nnon rilevato" + }, + "LockingKeysString": { + "message": "Blocc." + }, + "UnlockingKeysString": { + "message": "Sblocc." + }, + "WarningKeysLockedString": { + "message": "BLOCCATO" + }, + "WarningThermalRunaway": { + "message": "Temperatura\nfuori controllo" + }, + "WarningTipShorted": { + "message": "Punta in cortocircuito!" + }, + "SettingsCalibrationWarning": { + "message": "Prima di riavviare assicurati che la punta e l'impugnatura siano a temperatura ambiente!" + }, + "CJCCalibrating": { + "message": "Calibrazione in corso\n" + }, + "SettingsResetWarning": { + "message": "Ripristinare le impostazioni predefinite?" + }, + "UVLOWarningString": { + "message": "DC BASSA" + }, + "UndervoltageString": { + "message": "DC INSUFFICIENTE\n" + }, + "InputVoltageString": { + "message": "V in: \n" + }, + "SleepingAdvancedString": { + "message": "Riposo\n" + }, + "SleepingTipAdvancedString": { + "message": "Punta: \n" + }, + "ProfilePreheatString": { + "message": "Preriscaldamento\n" + }, + "ProfileCooldownString": { + "message": "Raffreddamento\n" + }, + "DeviceFailedValidationWarning": { + "message": "È probabile che questo dispositivo sia contraffatto!" + }, + "TooHotToStartProfileWarning": { + "message": "Troppo caldo\nper il profilo" + } + }, + "characters": { + "SettingRightChar": "D", + "SettingLeftChar": "S", + "SettingAutoChar": "A", + "SettingSlowChar": "L", + "SettingMediumChar": "M", + "SettingFastChar": "V", + "SettingStartSolderingChar": "S", + "SettingStartSleepChar": "R", + "SettingStartSleepOffChar": "A", + "SettingLockBoostChar": "T", + "SettingLockFullChar": "C" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Opzioni\nalimentaz", + "description": "" + }, + "SolderingMenu": { + "displayText": "Opzioni\nsaldatura", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Risparmio\nenergetico", + "description": "" + }, + "UIMenu": { + "displayText": "Interfaccia\nutente", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Opzioni\navanzate", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Modalità\npredefinita" + }, + "USBPDModeNoDynamic": { + "displayText": "Modalità\nstatica" + }, + "USBPDModeSafe": { + "displayText": "Modalità\nsicura" + }, + "TipTypeAuto": { + "displayText": "Rilevaz.\nauto" + }, + "TipTypeT12Long": { + "displayText": "TS100\nlunga" + }, + "TipTypeT12Short": { + "displayText": "Pine\ncorta" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Sorgente\nalimentaz", + "description": "Imposta una tensione minima di alimentazione attraverso la selezione di una sorgente [DC: 10 V; 3S/4S/5S/6S: 3,3 V per cella]" + }, + "MinVolCell": { + "displayText": "Tensione\nmin celle", + "description": "Modifica la tensione di minima carica delle celle di una batteria Li-Po [3S: 3,0-3,7 V; 4S/5S/6S: 2,4-3,7 V]" + }, + "QCMaxVoltage": { + "displayText": "Tensione\nQC", + "description": "Imposta la massima tensione negoziabile con un alimentatore Quick Charge [volt]" + }, + "PDNegTimeout": { + "displayText": "Abilitazione\nUSB PD", + "description": "Imposta il tempo di negoziazione del protocollo USB Power Delivery con alimentatori compatibili [0: disattiva; multipli di 100 ms]" + }, + "USBPDMode": { + "displayText": "Modalità\nUSB PD", + "description": "Abilita le modalità Power Delivery PPS ed EPR" + }, + "BoostTemperature": { + "displayText": "Temp\nturbo", + "description": "Imposta la temperatura della funzione turbo [°C/°F]" + }, + "AutoStart": { + "displayText": "Avvio\nautomatico", + "description": "Attiva automaticamente il saldatore quando viene alimentato [S: saldatura; R: riposo; A: temperatura ambiente]" + }, + "TempChangeShortStep": { + "displayText": "Temp passo\nbreve", + "description": "Imposta il passo dei valori di temperatura per una breve pressione dei tasti" + }, + "TempChangeLongStep": { + "displayText": "Temp passo\nlungo", + "description": "Imposta il passo dei valori di temperatura per una lunga pressione dei tasti" + }, + "LockingMode": { + "displayText": "Blocco\ntasti", + "description": "Blocca i tasti durante la modalità saldatura; tieni premuto entrambi per bloccare o sbloccare [T: consenti Turbo; C: blocco completo]" + }, + "ProfilePhases": { + "displayText": "Fasi modalità\nprofilo", + "description": "Imposta il numero di fasi da implementare per un profilo di riscaldamento personalizzato" + }, + "ProfilePreheatTemp": { + "displayText": "Temperatura\npreriscaldamento", + "description": "Imposta la temperatura di preriscaldamento da raggiungere all'inizio del profilo di riscaldamento" + }, + "ProfilePreheatSpeed": { + "displayText": "Velocità\npreriscaldamento", + "description": "Imposta la velocità di preriscaldamento [°C/s]" + }, + "ProfilePhase1Temp": { + "displayText": "Temperatura\nfase 1", + "description": "Imposta la temperatura da raggiungere alla fine di questa fase" + }, + "ProfilePhase1Duration": { + "displayText": "Durata\nfase 1", + "description": "Imposta la durata di questa fase [secondi]" + }, + "ProfilePhase2Temp": { + "displayText": "Temperatura\nfase 2", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Durata\nfase 2", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Temperatura\nfase 3", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Durata\nfase 3", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Temperatura\nfase 4", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Durata\nfase 4", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Temperatura\nfase 5", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Durata\nfase 5", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Velocità\nraffreddamento", + "description": "Imposta la velocità di raffreddamento al termine del profilo di riscaldamento [°C/s]" + }, + "MotionSensitivity": { + "displayText": "Sensibilità\nal movimento", + "description": "Imposta la sensibilità al movimento per uscire dalla modalità riposo [1: minima; 9: massima]" + }, + "SleepTemperature": { + "displayText": "Temperatura\nriposo", + "description": "Imposta la temperatura da mantenere in modalità riposo [°C/°F]" + }, + "SleepTimeout": { + "displayText": "Timer\nriposo", + "description": "Imposta un timer per entrare in modalità riposo [secondi/minuti]" + }, + "ShutdownTimeout": { + "displayText": "Timer\nspegnimento", + "description": "Imposta un timer per lo spegnimento [minuti]" + }, + "HallEffSensitivity": { + "displayText": "Sensore\nHall", + "description": "Regola la sensibilità del sensore ad effetto Hall per entrare in modalità riposo [1: minima; 9: massima]" + }, + "HallEffSleepTimeout": { + "displayText": "Timer\nHall", + "description": "Imposta un timer per entrare in modalità riposo quando il sensore ad effetto Hall è al di sopra della soglia di attivazione [secondi]" + }, + "TemperatureUnit": { + "displayText": "Unità di\ntemperatura", + "description": "Scegli l'unità di misura per la temperatura [C: grado Celsius; F: grado Farenheit]" + }, + "DisplayRotation": { + "displayText": "Orientamento\nschermo", + "description": "Imposta l'orientamento dello schermo [D: mano destra; S: mano sinistra; A: automatico]" + }, + "CooldownBlink": { + "displayText": "Avviso\npunta calda", + "description": "Evidenzia il valore di temperatura durante il raffreddamento se la punta è ancora calda" + }, + "ScrollingSpeed": { + "displayText": "Velocità\ntesto", + "description": "Imposta la velocità di scorrimento del testo [L: lenta; V: veloce]" + }, + "ReverseButtonTempChange": { + "displayText": "Inversione\ntasti", + "description": "Inverti i tasti per aumentare o diminuire la temperatura della punta" + }, + "ReverseButtonSettings": { + "displayText": "Inversione\ntasti A/B", + "description": "Inverti il funzionamento dei tasti del saldatore all'interno del menù principale" + }, + "AnimSpeed": { + "displayText": "Velocità\nanimazioni", + "description": "Imposta la velocità di riproduzione delle animazioni del menù principale [L: lenta; M: media; V: veloce]" + }, + "AnimLoop": { + "displayText": "Ciclo\nanimazioni", + "description": "Abilita la riproduzione ciclica delle animazioni del menù principale" + }, + "Brightness": { + "displayText": "Luminosità\nschermo", + "description": "Regola la luminosità dello schermo [1: minimo; 10: massimo]" + }, + "ColourInversion": { + "displayText": "Inverti\ncolori", + "description": "Inverti i colori dello schermo" + }, + "LOGOTime": { + "displayText": "Durata\nlogo", + "description": "Imposta la permanenza sullo schermo del logo iniziale [secondi]" + }, + "AdvancedIdle": { + "displayText": "Interfaccia\ntestuale", + "description": "Mostra informazioni dettagliate all'interno della schermata principale" + }, + "AdvancedSoldering": { + "displayText": "Dettagli\nsaldatura", + "description": "Mostra informazioni dettagliate durante la modalità saldatura" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Abilita BLE" + }, + "PowerLimit": { + "displayText": "Limite\npotenza", + "description": "Imposta il valore di potenza massima erogabile al saldatore [watt]" + }, + "CalibrateCJC": { + "displayText": "Calibra T\nall'avvio", + "description": "Calibra le rilevazioni di temperatura al prossimo riavvio (non necessario se lo scarto di temperatura è minore di 5 °C)" + }, + "VoltageCalibration": { + "displayText": "Calibrazione\ntensione", + "description": "Calibra la tensione in ingresso; regola con entrambi i tasti, tieni premuto il tasto superiore per uscire" + }, + "PowerPulsePower": { + "displayText": "Potenza\nimpulso", + "description": "Regola la potenza di un segnale di attività per prevenire lo standby eventuale dell'alimentatore [watt]" + }, + "PowerPulseWait": { + "displayText": "Distanza\nimpulsi", + "description": "Imposta il tempo che deve intercorrere tra un segnale di attività e il successivo [multipli di 2,5 s]" + }, + "PowerPulseDuration": { + "displayText": "Durata\nimpulso", + "description": "Regola la durata del segnale di attività [multipli di 250 ms]" + }, + "SettingsReset": { + "displayText": "Ripristino\nimpostazioni", + "description": "Ripristina le impostazioni predefinite" + }, + "LanguageSwitch": { + "displayText": "Lingua:\n IT Italiano", + "description": "" + }, + "SolderingTipType": { + "displayText": "Tipo di\npunta", + "description": "Seleziona il modello della punta in uso" } + } } diff --git a/Translations/translation_JA_JP.json b/Translations/translation_JA_JP.json index 5d669bb49..589aa08a4 100644 --- a/Translations/translation_JA_JP.json +++ b/Translations/translation_JA_JP.json @@ -1,319 +1,351 @@ { - "languageCode": "JA_JP", - "languageLocalName": "日本語", - "tempUnitFahrenheit": true, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration done!" - }, - "ResetOKMessage": { - "message": "リセットOK" - }, - "SettingsResetMessage": { - "message": "初期化されました" - }, - "NoAccelerometerMessage": { - "message": "加速度計未検出" - }, - "NoPowerDeliveryMessage": { - "message": "PD IC未検出" - }, - "LockingKeysString": { - "message": "ボタンロック" - }, - "UnlockingKeysString": { - "message": "ロックを解除" - }, - "WarningKeysLockedString": { - "message": "!入力ロック中!" - }, - "WarningThermalRunaway": { - "message": "過熱" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating" - }, - "SettingsResetWarning": { - "message": "設定をリセットしますか?" - }, - "UVLOWarningString": { - "message": "電圧が低すぎます" - }, - "UndervoltageString": { - "message": "Undervoltage" - }, - "InputVoltageString": { - "message": "Input V: " - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Sleeping..." - }, - "SleepingTipAdvancedString": { - "message": "Tip: " - }, - "OffString": { - "message": "オフ" - }, - "ProfilePreheatString": { - "message": "Preheat" - }, - "ProfileCooldownString": { - "message": "Cooldown" - }, - "DeviceFailedValidationWarning": { - "message": "このデバイスはおそらく偽造品です" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to start profile" - } - }, - "characters": { - "SettingRightChar": "右", - "SettingLeftChar": "左", - "SettingAutoChar": "自", - "SettingOffChar": "×", - "SettingSlowChar": "遅", - "SettingMediumChar": "中", - "SettingFastChar": "速", - "SettingStartNoneChar": "×", - "SettingStartSolderingChar": "熱", - "SettingStartSleepChar": "待", - "SettingStartSleepOffChar": "室", - "SettingLockDisableChar": "×", - "SettingLockBoostChar": "ブ", - "SettingLockFullChar": "全" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "電源設定", - "description": "" - }, - "SolderingMenu": { - "displayText": "半田付け設定", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "待機設定", - "description": "" - }, - "UIMenu": { - "displayText": "UI設定", - "description": "" - }, - "AdvancedMenu": { - "displayText": "高度な設定", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "下限電圧", - "description": "下限電圧を指定する " - }, - "MinVolCell": { - "displayText": "最低電圧", - "description": "セルあたりの最低電圧 <ボルト> <3S: 3.0V - 3.7V, 4/5/6S: 2.4V - 3.7V>" - }, - "QCMaxVoltage": { - "displayText": "QC電圧", - "description": "QC電源使用時に要求する目標電圧" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "一部のQC電源との互換性のため、PDネゴシエーションをタイムアウトする時間 " - }, - "PDVpdo": { - "displayText": "PD VPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "ブースト温度", - "description": "ブーストモードで使用される温度" - }, - "AutoStart": { - "displayText": "自動加熱", - "description": "電源投入時に自動的に加熱する <×=オフ | 熱=半田付けモード | 待=スタンバイモード | 室=室温スタンバイモード>" - }, - "TempChangeShortStep": { - "displayText": "温度変化 短", - "description": "ボタンを短く押した時の温度変化値" - }, - "TempChangeLongStep": { - "displayText": "温度変化 長", - "description": "ボタンを長押しした時の温度変化値" - }, - "LockingMode": { - "displayText": "ボタンロック", - "description": "半田付けモード時に両方のボタンを長押しし、ボタンロックする <×=オフ | ブ=ブーストのみ許可 | 全=すべてをロック>" - }, - "ProfilePhases": { - "displayText": "Profile Phases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat Temp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat Speed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1 Temp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1 Duration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2 Temp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2 Duration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3 Temp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3 Duration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4 Temp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4 Duration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5 Temp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5 Duration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown Speed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "動きの感度", - "description": "0=オフ | 1=最低感度 | ... | 9=最高感度" - }, - "SleepTemperature": { - "displayText": "待機温度", - "description": "スタンバイ時のコテ先温度" - }, - "SleepTimeout": { - "displayText": "待機遅延", - "description": "スタンバイモードに入るまでの待機時間 " - }, - "ShutdownTimeout": { - "displayText": "自動オフ", - "description": "自動電源オフまでの待機時間 " - }, - "HallEffSensitivity": { - "displayText": "磁界感度", - "description": "スタンバイモードに入るのに使用される磁場センサーの感度 <0=オフ | 1=最低感度 | ... | 9=最高感度>" - }, - "TemperatureUnit": { - "displayText": "温度単位", - "description": "C=摂氏 | F=華氏" - }, - "DisplayRotation": { - "displayText": "画面の向き", - "description": "右=右利き | 左=左利き | 自=自動" - }, - "CooldownBlink": { - "displayText": "冷却中に点滅", - "description": "加熱の停止後、コテ先が熱い間は温度表示を点滅する" - }, - "ScrollingSpeed": { - "displayText": "スクロール速度", - "description": "テキストをスクロールする速さ <遅=遅い | 速=速い>" - }, - "ReverseButtonTempChange": { - "displayText": "キー入れ替え", - "description": "温度設定時に+ボタンと-ボタンを入れ替える" - }, - "AnimSpeed": { - "displayText": "動画の速度", - "description": "メニューアイコンのアニメーションの速さ <×=再生しない | 遅=低速 | 中=中速 | 速=高速>" - }, - "AnimLoop": { - "displayText": "動画をループ", - "description": "メニューアイコンのアニメーションをループする" - }, - "Brightness": { - "displayText": "画面輝度", - "description": "画面の明るさ・コントラストを変更する" - }, - "ColourInversion": { - "displayText": "色反転", - "description": "画面の色を反転する" - }, - "LOGOTime": { - "displayText": "起動画面", - "description": "起動画面の表示時間を設定する" - }, - "AdvancedIdle": { - "displayText": "詳細な待受画面", - "description": "待ち受け画面に詳細情報を表示する" - }, - "AdvancedSoldering": { - "displayText": "詳細な作業画面", - "description": "半田付け画面に詳細情報を表示する" - }, - "BluetoothLE": { - "displayText": "Bluetooth", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "電力制限", - "description": "最大電力を制限する " - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5 C)" - }, - "VoltageCalibration": { - "displayText": "電圧校正", - "description": "入力電圧(VIN)の校正を開始する <長押しで終了>" - }, - "PowerPulsePower": { - "displayText": "電力パルス", - "description": "電源をオンに保つための電力パルス <ワット>" - }, - "PowerPulseWait": { - "displayText": "パルス間隔", - "description": "電源をオンに保つための電力パルスの時間間隔 " - }, - "PowerPulseDuration": { - "displayText": "パルス時間長", - "description": "電源をオンに保つための電力パルスの時間長 " - }, - "SettingsReset": { - "displayText": "設定をリセット", - "description": "すべての設定を初期化する" - }, - "LanguageSwitch": { - "displayText": "言語: 日本語", - "description": "" - } + "languageCode": "JA_JP", + "languageLocalName": "日本語", + "tempUnitFahrenheit": true, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibration done!" + }, + "ResetOKMessage": { + "message": "リセットOK" + }, + "SettingsResetMessage": { + "message": "初期化されました" + }, + "NoAccelerometerMessage": { + "message": "加速度計未検出" + }, + "NoPowerDeliveryMessage": { + "message": "PD IC未検出" + }, + "LockingKeysString": { + "message": "ボタンロック" + }, + "UnlockingKeysString": { + "message": "ロックを解除" + }, + "WarningKeysLockedString": { + "message": "!入力ロック中!" + }, + "WarningThermalRunaway": { + "message": "過熱" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Before rebooting, make sure tip & handle are at room temperature!" + }, + "CJCCalibrating": { + "message": "calibrating" + }, + "SettingsResetWarning": { + "message": "設定をリセットしますか?" + }, + "UVLOWarningString": { + "message": "電圧が低すぎます" + }, + "UndervoltageString": { + "message": "Undervoltage" + }, + "InputVoltageString": { + "message": "Input V: " + }, + "SleepingAdvancedString": { + "message": "Sleeping..." + }, + "SleepingTipAdvancedString": { + "message": "Tip: " + }, + "ProfilePreheatString": { + "message": "Preheat" + }, + "ProfileCooldownString": { + "message": "Cooldown" + }, + "DeviceFailedValidationWarning": { + "message": "このデバイスはおそらく偽造品です" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to start profile" + } + }, + "characters": { + "SettingRightChar": "右", + "SettingLeftChar": "左", + "SettingAutoChar": "自", + "SettingSlowChar": "遅", + "SettingMediumChar": "中", + "SettingFastChar": "速", + "SettingStartSolderingChar": "熱", + "SettingStartSleepChar": "待", + "SettingStartSleepOffChar": "室", + "SettingLockBoostChar": "ブ", + "SettingLockFullChar": "全" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "電源設定", + "description": "" + }, + "SolderingMenu": { + "displayText": "半田付け設定", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "待機設定", + "description": "" + }, + "UIMenu": { + "displayText": "UI設定", + "description": "" + }, + "AdvancedMenu": { + "displayText": "高度な設定", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "下限電圧", + "description": "下限電圧を指定する " + }, + "MinVolCell": { + "displayText": "最低電圧", + "description": "セルあたりの最低電圧 <ボルト> <3S: 3.0V - 3.7V, 4/5/6S: 2.4V - 3.7V>" + }, + "QCMaxVoltage": { + "displayText": "QC電圧", + "description": "QC電源使用時に要求する目標電圧" + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "一部のQC電源との互換性のため、PDネゴシエーションをタイムアウトする時間 " + }, + "USBPDMode": { + "displayText": "PD VPDO", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "ブースト温度", + "description": "ブーストモードで使用される温度" + }, + "AutoStart": { + "displayText": "自動加熱", + "description": "電源投入時に自動的に加熱する <熱=半田付けモード | 待=スタンバイモード | 室=室温スタンバイモード>" + }, + "TempChangeShortStep": { + "displayText": "温度変化 短", + "description": "ボタンを短く押した時の温度変化値" + }, + "TempChangeLongStep": { + "displayText": "温度変化 長", + "description": "ボタンを長押しした時の温度変化値" + }, + "LockingMode": { + "displayText": "ボタンロック", + "description": "半田付けモード時に両方のボタンを長押しし、ボタンロックする <ブ=ブーストのみ許可 | 全=すべてをロック>" + }, + "ProfilePhases": { + "displayText": "Profile Phases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat Temp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat Speed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1 Temp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1 Duration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2 Temp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2 Duration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3 Temp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3 Duration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4 Temp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4 Duration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5 Temp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5 Duration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown Speed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "動きの感度", + "description": "1=最低感度 | ... | 9=最高感度" + }, + "SleepTemperature": { + "displayText": "待機温度", + "description": "スタンバイ時のコテ先温度" + }, + "SleepTimeout": { + "displayText": "待機遅延", + "description": "スタンバイモードに入るまでの待機時間 " + }, + "ShutdownTimeout": { + "displayText": "自動オフ", + "description": "自動電源オフまでの待機時間 " + }, + "HallEffSensitivity": { + "displayText": "磁界感度", + "description": "スタンバイモードに入るのに使用される磁場センサーの感度 <1=最低感度 | ... | 9=最高感度>" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "ホール効果が閾値を超えたときに\"「スリープモード」\"が開始されるまでの間隔" + }, + "TemperatureUnit": { + "displayText": "温度単位", + "description": "C=摂氏 | F=華氏" + }, + "DisplayRotation": { + "displayText": "画面の向き", + "description": "右=右利き | 左=左利き | 自=自動" + }, + "CooldownBlink": { + "displayText": "冷却中に点滅", + "description": "加熱の停止後、コテ先が熱い間は温度表示を点滅する" + }, + "ScrollingSpeed": { + "displayText": "スクロール速度", + "description": "テキストをスクロールする速さ <遅=遅い | 速=速い>" + }, + "ReverseButtonTempChange": { + "displayText": "キー入れ替え", + "description": "温度設定時に+ボタンと-ボタンを入れ替える" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "動画の速度", + "description": "メニューアイコンのアニメーションの速さ <遅=低速 | 中=中速 | 速=高速>" + }, + "AnimLoop": { + "displayText": "動画をループ", + "description": "メニューアイコンのアニメーションをループする" + }, + "Brightness": { + "displayText": "画面輝度", + "description": "画面の明るさ・コントラストを変更する" + }, + "ColourInversion": { + "displayText": "色反転", + "description": "画面の色を反転する" + }, + "LOGOTime": { + "displayText": "起動画面", + "description": "起動画面の表示時間を設定する" + }, + "AdvancedIdle": { + "displayText": "詳細な待受画面", + "description": "待ち受け画面に詳細情報を表示する" + }, + "AdvancedSoldering": { + "displayText": "詳細な作業画面", + "description": "半田付け画面に詳細情報を表示する" + }, + "BluetoothLE": { + "displayText": "Bluetooth", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "電力制限", + "description": "最大電力を制限する " + }, + "CalibrateCJC": { + "displayText": "Calibrate CJC", + "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5 C)" + }, + "VoltageCalibration": { + "displayText": "電圧校正", + "description": "入力電圧(VIN)の校正を開始する <長押しで終了>" + }, + "PowerPulsePower": { + "displayText": "電力パルス", + "description": "電源をオンに保つための電力パルス <ワット>" + }, + "PowerPulseWait": { + "displayText": "パルス間隔", + "description": "電源をオンに保つための電力パルスの時間間隔 " + }, + "PowerPulseDuration": { + "displayText": "パルス時間長", + "description": "電源をオンに保つための電力パルスの時間長 " + }, + "SettingsReset": { + "displayText": "設定をリセット", + "description": "すべての設定を初期化する" + }, + "LanguageSwitch": { + "displayText": "言語: 日本語", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_LT.json b/Translations/translation_LT.json index cbdb8f275..036d4b29a 100644 --- a/Translations/translation_LT.json +++ b/Translations/translation_LT.json @@ -1,319 +1,351 @@ { - "languageCode": "LT", - "languageLocalName": "Lietuvių", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Atstatyta" - }, - "SettingsResetMessage": { - "message": "Nust. \natstatyti!" - }, - "NoAccelerometerMessage": { - "message": "Nerastas\nakselerometras!" - }, - "NoPowerDeliveryMessage": { - "message": "Nerastas\nUSB-PD IC!" - }, - "LockingKeysString": { - "message": "UŽRAKIN" - }, - "UnlockingKeysString": { - "message": "ATRAKIN" - }, - "WarningKeysLockedString": { - "message": "!UŽRAK!" - }, - "WarningThermalRunaway": { - "message": "Perkaitimo\npavojus" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Ar norite atstatyti nustatymus į numatytas reikšmes?" - }, - "UVLOWarningString": { - "message": "MAŽ VOLT" - }, - "UndervoltageString": { - "message": "Žema įtampa\n" - }, - "InputVoltageString": { - "message": "Įvestis V: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Miegu...\n" - }, - "SleepingTipAdvancedString": { - "message": "Antg: \n" - }, - "OffString": { - "message": "Išj" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Your device is most likely a counterfeit!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "D", - "SettingLeftChar": "K", - "SettingAutoChar": "A", - "SettingOffChar": "I", - "SettingSlowChar": "L", - "SettingMediumChar": "V", - "SettingFastChar": "G", - "SettingStartNoneChar": "N", - "SettingStartSolderingChar": "T", - "SettingStartSleepChar": "M", - "SettingStartSleepOffChar": "K", - "SettingLockDisableChar": "I", - "SettingLockBoostChar": "T", - "SettingLockFullChar": "V" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Maitinimo\nnustatymai", - "description": "" - }, - "SolderingMenu": { - "displayText": "Litavimo\nnustatymai", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Miego\nrežimai", - "description": "" - }, - "UIMenu": { - "displayText": "Naudotojo\nsąsaja", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Išplėsti.\nnustatymai", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Maitinimo\nšaltinis", - "description": "Išjungimo įtampa. (DC 10V) (arba celių [S] kiekis [3.3V per celę])" - }, - "MinVolCell": { - "displayText": "Minimalus\nvoltažas", - "description": "Minimalus voltažas, kuris yra leidžiamas kiekvienam baterijos elementui (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "QC mait.\nįtampa", - "description": "Maksimali QC maitinimo bloko įtampa" - }, - "PDNegTimeout": { - "displayText": "PD\nlaikas", - "description": "PD suderinimo laikas žingsniais po 100ms suderinamumui su kai kuriais QC įkrovikliais" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Turbo\ntemperat.", - "description": "Temperatūra turbo režimu" - }, - "AutoStart": { - "displayText": "Automatinis\npaleidimas", - "description": "Ar pradėti kaitininti iš karto įjungus lituoklį (N=Ne | T=Taip | M=Miegas | K=Miegoti kambario temperatūroje)" - }, - "TempChangeShortStep": { - "displayText": "Temp.keitim.\ntrump.spust.", - "description": "Temperatūros keitimo žingsnis trumpai spustėlėjus mygtuką" - }, - "TempChangeLongStep": { - "displayText": "Temp.keitim.\nilgas pasp.", - "description": "Temperatūros keitimo žingsnis ilgai paspaudus mygtuką" - }, - "LockingMode": { - "displayText": "Mygtukų\nužraktas", - "description": "Lituodami, ilgai paspauskite abu mygtukus, kad juos užrakintumėte (I=Išjungta | T=leidžiamas tik Turbo režimas | V=Visiškas užrakinimas)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Judesio\njautrumas", - "description": "Judesio jautrumas (0=Išjungta | 1=Mažiausias | ... | 9=Didžiausias)" - }, - "SleepTemperature": { - "displayText": "Miego\ntemperat.", - "description": "Antgalio temperatūra miego režimu" - }, - "SleepTimeout": { - "displayText": "Miego\nlaikas", - "description": "Užmigimo laikas (sekundės | minutės)" - }, - "ShutdownTimeout": { - "displayText": "Išjungimo\nlaikas", - "description": "Išjungimo laikas (minutės)" - }, - "HallEffSensitivity": { - "displayText": "Holo\njutiklis", - "description": "Holo jutiklio jautrumas nustatant miegą (0=Išjungta | 1=Mažiausias | ... | 9=Didžiausias)" - }, - "TemperatureUnit": { - "displayText": "Temperatūros\nvienetai", - "description": "Temperatūros vienetai (C=Celsijus | F=Farenheitas)" - }, - "DisplayRotation": { - "displayText": "Ekrano\norientacija", - "description": "Ekrano orientacija (D=Dešiniarankiams | K=Kairiarankiams | A=Automatinė)" - }, - "CooldownBlink": { - "displayText": "Atvėsimo\nmirksėjimas", - "description": "Ar mirksėti temperatūrą ekrane kol vėstantis antgalis vis dar karštas?" - }, - "ScrollingSpeed": { - "displayText": "Aprašymo\ngreitis", - "description": "Greitis, kuriuo šis tekstas slenka" - }, - "ReverseButtonTempChange": { - "displayText": "Sukeisti + -\nmygtukus?", - "description": "Sukeisti + - temperatūros keitimo mygtukus vietomis" - }, - "AnimSpeed": { - "displayText": "Animacijų\ngreitis", - "description": "Paveiksliukų animacijų greitis meniu punktuose (I=Išjungtas | L=Lėtas | V=Vidutinis | G=Greitas)" - }, - "AnimLoop": { - "displayText": "Animacijų\npakartojimas", - "description": "Leidžia kartoti animacijas be sustojimo pagrindiniame meniu" - }, - "Brightness": { - "displayText": "Ekrano\nšviesumas", - "description": "Nustato OLED ekrano kontrastą/šviesumą." - }, - "ColourInversion": { - "displayText": "Ekrano\ninvertavimas", - "description": "Invertuoja OLED ekrano spalvas" - }, - "LOGOTime": { - "displayText": "Boot logo\nduration", - "description": "Set boot logo duration (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Detalus lau-\nkimo ekranas", - "description": "Ar rodyti papildomą informaciją mažesniu šriftu laukimo ekrane" - }, - "AdvancedSoldering": { - "displayText": "Detalus lita-\nvimo ekranas", - "description": "Ar rodyti išsamią informaciją lituojant" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Galios\nriba", - "description": "Didžiausia galia, kurią gali naudoti lituoklis (Vatai)" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nat next boot", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Kalibruoti\nįvesties įtampą?", - "description": "Įvesties įtampos kalibravimas. Trumpai paspauskite, norėdami nustatyti, ilgai paspauskite, kad išeitumėte." - }, - "PowerPulsePower": { - "displayText": "Galios\npulso W", - "description": "Periodinis galios pulso intensyvumas maitinblokiui, neleidžiantis jam užmigti." - }, - "PowerPulseWait": { - "displayText": "Galios pulso\ndažnumas", - "description": "Pasikartojantis laiko intervalas (x 2.5s), ties kuriuo kartojamas galios pulsas maitinblokiui, neleidžiantis jam užmigti" - }, - "PowerPulseDuration": { - "displayText": "Galios pulso\ntrukmė", - "description": "Galios pulso aktyvioji trukmė (x 250ms)" - }, - "SettingsReset": { - "displayText": "Atstatyti\nnustatymus?", - "description": "Nustato nustatymus į numatytuosius" - }, - "LanguageSwitch": { - "displayText": "Kalba:\n LT Lietuvių", - "description": "" - } + "languageCode": "LT", + "languageLocalName": "Lietuvių", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibravimas\natliktas!" + }, + "ResetOKMessage": { + "message": "Atstatyta" + }, + "SettingsResetMessage": { + "message": "Nust. \natstatyti!" + }, + "NoAccelerometerMessage": { + "message": "Nerastas\nakselerometras!" + }, + "NoPowerDeliveryMessage": { + "message": "Nerastas\nUSB-PD IC!" + }, + "LockingKeysString": { + "message": "UŽRAKIN" + }, + "UnlockingKeysString": { + "message": "ATRAKIN" + }, + "WarningKeysLockedString": { + "message": "!UŽRAK!" + }, + "WarningThermalRunaway": { + "message": "Perkaitimo\npavojus" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Before rebooting, make sure tip & handle are at room temperature!" + }, + "CJCCalibrating": { + "message": "Kalibruojama\n" + }, + "SettingsResetWarning": { + "message": "Ar norite atstatyti nustatymus į numatytas reikšmes?" + }, + "UVLOWarningString": { + "message": "MAŽ VOLT" + }, + "UndervoltageString": { + "message": "Žema įtampa\n" + }, + "InputVoltageString": { + "message": "Įvestis V: \n" + }, + "SleepingAdvancedString": { + "message": "Miegu...\n" + }, + "SleepingTipAdvancedString": { + "message": "Antg: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Your device is most likely a counterfeit!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "D", + "SettingLeftChar": "K", + "SettingAutoChar": "A", + "SettingSlowChar": "L", + "SettingMediumChar": "V", + "SettingFastChar": "G", + "SettingStartSolderingChar": "T", + "SettingStartSleepChar": "M", + "SettingStartSleepOffChar": "K", + "SettingLockBoostChar": "T", + "SettingLockFullChar": "V" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Maitinimo\nnustatymai", + "description": "" + }, + "SolderingMenu": { + "displayText": "Litavimo\nnustatymai", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Miego\nrežimai", + "description": "" + }, + "UIMenu": { + "displayText": "Naudotojo\nsąsaja", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Išplėsti.\nnustatymai", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Maitinimo\nšaltinis", + "description": "Išjungimo įtampa. (DC 10V) (arba celių [S] kiekis [3.3V per celę])" + }, + "MinVolCell": { + "displayText": "Minimalus\nvoltažas", + "description": "Minimalus voltažas, kuris yra leidžiamas kiekvienam baterijos elementui (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "QC mait.\nįtampa", + "description": "Maksimali QC maitinimo bloko įtampa" + }, + "PDNegTimeout": { + "displayText": "PD\nlaikas", + "description": "PD suderinimo laikas žingsniais po 100ms suderinamumui su kai kuriais QC įkrovikliais" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Turbo\ntemperat.", + "description": "Temperatūra turbo režimu" + }, + "AutoStart": { + "displayText": "Automatinis\npaleidimas", + "description": "Ar pradėti kaitininti iš karto įjungus lituoklį (T=Taip | M=Miegas | K=Miegoti kambario temperatūroje)" + }, + "TempChangeShortStep": { + "displayText": "Temp.keitim.\ntrump.spust.", + "description": "Temperatūros keitimo žingsnis trumpai spustėlėjus mygtuką" + }, + "TempChangeLongStep": { + "displayText": "Temp.keitim.\nilgas pasp.", + "description": "Temperatūros keitimo žingsnis ilgai paspaudus mygtuką" + }, + "LockingMode": { + "displayText": "Mygtukų\nužraktas", + "description": "Lituodami, ilgai paspauskite abu mygtukus, kad juos užrakintumėte (T=leidžiamas tik Turbo režimas | V=Visiškas užrakinimas)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Judesio\njautrumas", + "description": "Judesio jautrumas (1=Mažiausias | ... | 9=Didžiausias)" + }, + "SleepTemperature": { + "displayText": "Miego\ntemperat.", + "description": "Antgalio temperatūra miego režimu" + }, + "SleepTimeout": { + "displayText": "Miego\nlaikas", + "description": "Užmigimo laikas (sekundės | minutės)" + }, + "ShutdownTimeout": { + "displayText": "Išjungimo\nlaikas", + "description": "Išjungimo laikas (minutės)" + }, + "HallEffSensitivity": { + "displayText": "Holo\njutiklis", + "description": "Holo jutiklio jautrumas nustatant miegą (1=Mažiausias | ... | 9=Didžiausias)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Intervalas prieš \"miego režimą\" prasideda, kai salės efektas viršija slenkstį" + }, + "TemperatureUnit": { + "displayText": "Temperatūros\nvienetai", + "description": "Temperatūros vienetai (C=Celsijus | F=Farenheitas)" + }, + "DisplayRotation": { + "displayText": "Ekrano\norientacija", + "description": "Ekrano orientacija (D=Dešiniarankiams | K=Kairiarankiams | A=Automatinė)" + }, + "CooldownBlink": { + "displayText": "Atvėsimo\nmirksėjimas", + "description": "Ar mirksėti temperatūrą ekrane kol vėstantis antgalis vis dar karštas?" + }, + "ScrollingSpeed": { + "displayText": "Aprašymo\ngreitis", + "description": "Greitis, kuriuo šis tekstas slenka" + }, + "ReverseButtonTempChange": { + "displayText": "Sukeisti + -\nmygtukus?", + "description": "Sukeisti + - temperatūros keitimo mygtukus vietomis" + }, + "ReverseButtonSettings": { + "displayText": "Sukeisti A B\nmygtukus?", + "description": "Sukeisti nustatymų meniu mygtukus vietomis" + }, + "AnimSpeed": { + "displayText": "Animacijų\ngreitis", + "description": "Paveiksliukų animacijų greitis meniu punktuose (L=Lėtas | V=Vidutinis | G=Greitas)" + }, + "AnimLoop": { + "displayText": "Animacijų\npakartojimas", + "description": "Leidžia kartoti animacijas be sustojimo pagrindiniame meniu" + }, + "Brightness": { + "displayText": "Ekrano\nšviesumas", + "description": "Nustato OLED ekrano kontrastą/šviesumą." + }, + "ColourInversion": { + "displayText": "Ekrano\ninvertavimas", + "description": "Invertuoja OLED ekrano spalvas" + }, + "LOGOTime": { + "displayText": "Įkrovos logotipo\ntrukmė", + "description": "Nustatykite įkrovos logotipo trukmę (s=sekundės)" + }, + "AdvancedIdle": { + "displayText": "Detalus lau-\nkimo ekranas", + "description": "Ar rodyti papildomą informaciją mažesniu šriftu laukimo ekrane" + }, + "AdvancedSoldering": { + "displayText": "Detalus lita-\nvimo ekranas", + "description": "Ar rodyti išsamią informaciją lituojant" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Galios\nriba", + "description": "Didžiausia galia, kurią gali naudoti lituoklis (Vatai)" + }, + "CalibrateCJC": { + "displayText": "Calibrate CJC\nat next boot", + "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibruoti\nįvesties įtampą?", + "description": "Įvesties įtampos kalibravimas. Trumpai paspauskite, norėdami nustatyti, ilgai paspauskite, kad išeitumėte." + }, + "PowerPulsePower": { + "displayText": "Galios\npulso W", + "description": "Periodinis galios pulso intensyvumas maitinblokiui, neleidžiantis jam užmigti." + }, + "PowerPulseWait": { + "displayText": "Galios pulso\ndažnumas", + "description": "Pasikartojantis laiko intervalas (x 2.5s), ties kuriuo kartojamas galios pulsas maitinblokiui, neleidžiantis jam užmigti" + }, + "PowerPulseDuration": { + "displayText": "Galios pulso\ntrukmė", + "description": "Galios pulso aktyvioji trukmė (x 250ms)" + }, + "SettingsReset": { + "displayText": "Atstatyti\nnustatymus?", + "description": "Nustato nustatymus į numatytuosius" + }, + "LanguageSwitch": { + "displayText": "Kalba:\n LT Lietuvių", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_NB.json b/Translations/translation_NB.json index b18fc0a18..188e8473e 100644 --- a/Translations/translation_NB.json +++ b/Translations/translation_NB.json @@ -1,319 +1,351 @@ { - "languageCode": "NB", - "languageLocalName": "Norsk bokmål", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Tilbakestilling OK" - }, - "SettingsResetMessage": { - "message": "Noen innstillinger\nble endret!" - }, - "NoAccelerometerMessage": { - "message": "Ingen akselerometer\nfunnet!" - }, - "NoPowerDeliveryMessage": { - "message": "Ingen USB-PD IC\nfunnet!" - }, - "LockingKeysString": { - "message": "LÅST" - }, - "UnlockingKeysString": { - "message": "ÅPNET" - }, - "WarningKeysLockedString": { - "message": "!LÅST!" - }, - "WarningThermalRunaway": { - "message": "Termisk\nrømling" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Er du sikker på at du vil tilbakestille til standardinnstillinger?" - }, - "UVLOWarningString": { - "message": "Lavspenn" - }, - "UndervoltageString": { - "message": "Underspenning\n" - }, - "InputVoltageString": { - "message": "Innspenn.: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Dvale...\n" - }, - "SleepingTipAdvancedString": { - "message": "Spiss: \n" - }, - "OffString": { - "message": "Av" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Enheten din er sannsynligvis en forfalskning!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "H", - "SettingLeftChar": "V", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "S", - "SettingMediumChar": "M", - "SettingFastChar": "F", - "SettingStartNoneChar": "I", - "SettingStartSolderingChar": "L", - "SettingStartSleepChar": "D", - "SettingStartSleepOffChar": "R", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Effekt-\ninnst.", - "description": "" - }, - "SolderingMenu": { - "displayText": "Lodde-\ninnst.", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Dvale-\ninnst.", - "description": "" - }, - "UIMenu": { - "displayText": "Bruker-\ngrensesn.", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Avanserte\nvalg", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Kilde\n", - "description": "Strømforsyning. Sett nedre spenning for automatisk nedstenging. (DC 10V) (S 3.3V per celle)" - }, - "MinVolCell": { - "displayText": "Minimum\nspenning", - "description": "Minimum tillatt spenning per celle (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "QC-\nspenning", - "description": "Maks QC-spenning bolten skal forhandle om" - }, - "PDNegTimeout": { - "displayText": "PD-\ntidsavb.", - "description": "PD-forhandlingstidsavbrudd i steg på 100 ms for kompatibilitet med noen QC-ladere" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "KTmp\n", - "description": "Temperatur i \"kraft-modus\"" - }, - "AutoStart": { - "displayText": "AStart\n", - "description": "Start automatisk med lodding når strøm kobles til. (I=Inaktiv | L=Lodding | D=Dvale | R=Dvale romtemperatur)" - }, - "TempChangeShortStep": { - "displayText": "Temp-endring\nkort", - "description": "Hvor mye temperaturen skal endres ved kort trykk på knapp" - }, - "TempChangeLongStep": { - "displayText": "Temp-endring\nlang", - "description": "Hvor mye temperaturen skal endres ved langt trykk på knapp" - }, - "LockingMode": { - "displayText": "Tillat å låse\nknapper", - "description": "Mens du lodder, hold nede begge knapper for å bytte mellom låsemodus (D=deaktiver | B=kun boost | F=full lås)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "BSensr\n", - "description": "Bevegelsesfølsomhet (0=Inaktiv | 1=Minst følsom | ... | 9=Mest følsom)" - }, - "SleepTemperature": { - "displayText": "DTmp\n", - "description": "Dvaletemperatur (C)" - }, - "SleepTimeout": { - "displayText": "DTid\n", - "description": "Tid før dvale (Minutter | Sekunder)" - }, - "ShutdownTimeout": { - "displayText": "AvTid\n", - "description": "Tid før automatisk nedstenging (Minutter)" - }, - "HallEffSensitivity": { - "displayText": "Hall-sensor\nfølsomhet", - "description": "Sensitiviteten til Hall-effekt-sensoren for å detektere inaktivitet (0=Inaktiv | 1=Minst følsom | ... | 9=Mest følsom)" - }, - "TemperatureUnit": { - "displayText": "TmpEnh\n", - "description": "Temperaturskala (C=Celsius | F=Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "SkRetn\n", - "description": "Skjermretning (H=Høyrehendt | V=Venstrehendt | A=Automatisk)" - }, - "CooldownBlink": { - "displayText": "KjBlnk\n", - "description": "Blink temperaturen på skjermen mens spissen fortsatt er varm." - }, - "ScrollingSpeed": { - "displayText": "RullHa\n", - "description": "Hastigheten på rulletekst" - }, - "ReverseButtonTempChange": { - "displayText": "Bytt\n+ - kn.", - "description": "Bytt om på knappene for å stille temperatur" - }, - "AnimSpeed": { - "displayText": "Anim.\nhastighet", - "description": "Hastigheten til animasjonene i menyen (O=off | S=slow | M=medium | F=fast)" - }, - "AnimLoop": { - "displayText": "Anim.\nloop", - "description": "Loop ikon-animasjoner i hovedmenyen" - }, - "Brightness": { - "displayText": "Skjerm-\nlysstyrke", - "description": "Juster lysstyrken til OLED-skjermen" - }, - "ColourInversion": { - "displayText": "Inverter\nskjerm", - "description": "Inverter fargene på OLED-skjermen" - }, - "LOGOTime": { - "displayText": "Oppstartlogo\nvarighet", - "description": "Setter varigheten til oppstartlogoen (s=sekunder)" - }, - "AdvancedIdle": { - "displayText": "AvDvSk\n", - "description": "Vis detaljert informasjon med liten skrift på dvaleskjermen." - }, - "AdvancedSoldering": { - "displayText": "AvLdSk\n", - "description": "Vis detaljert informasjon ved lodding" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Effekt-\ngrense", - "description": "Maks effekt jernet kan bruke (W=watt)" - }, - "CalibrateCJC": { - "displayText": "TempKal?\n", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "KalSpIn?\n", - "description": "Kalibrer spenning. Knappene justerer. Langt trykk for å gå ut" - }, - "PowerPulsePower": { - "displayText": "Effekt-\npuls", - "description": "Hvor høy effekt pulsen for å holde laderen våken skal ha (watt)" - }, - "PowerPulseWait": { - "displayText": "Effektpuls\nforsink.", - "description": "Forsinkelse før effektpulsen utløses (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Effektpuls\nvarighet", - "description": "Hvor lenge holde-våken-pulsen varer (x 250ms)" - }, - "SettingsReset": { - "displayText": "TilbStl?\n", - "description": "Tilbakestill alle innstillinger" - }, - "LanguageSwitch": { - "displayText": "Språk:\n NB Norsk bm", - "description": "" - } + "languageCode": "NB", + "languageLocalName": "Norsk bokmål", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibration\ndone!" + }, + "ResetOKMessage": { + "message": "Tilbakestilling OK" + }, + "SettingsResetMessage": { + "message": "Noen innstillinger\nble endret!" + }, + "NoAccelerometerMessage": { + "message": "Ingen akselerometer\nfunnet!" + }, + "NoPowerDeliveryMessage": { + "message": "Ingen USB-PD IC\nfunnet!" + }, + "LockingKeysString": { + "message": "LÅST" + }, + "UnlockingKeysString": { + "message": "ÅPNET" + }, + "WarningKeysLockedString": { + "message": "!LÅST!" + }, + "WarningThermalRunaway": { + "message": "Termisk\nrømling" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Before rebooting, make sure tip & handle are at room temperature!" + }, + "CJCCalibrating": { + "message": "calibrating\n" + }, + "SettingsResetWarning": { + "message": "Er du sikker på at du vil tilbakestille til standardinnstillinger?" + }, + "UVLOWarningString": { + "message": "Lavspenn" + }, + "UndervoltageString": { + "message": "Underspenning\n" + }, + "InputVoltageString": { + "message": "Innspenn.: \n" + }, + "SleepingAdvancedString": { + "message": "Dvale...\n" + }, + "SleepingTipAdvancedString": { + "message": "Spiss: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Enheten din er sannsynligvis en forfalskning!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "H", + "SettingLeftChar": "V", + "SettingAutoChar": "A", + "SettingSlowChar": "S", + "SettingMediumChar": "M", + "SettingFastChar": "F", + "SettingStartSolderingChar": "L", + "SettingStartSleepChar": "D", + "SettingStartSleepOffChar": "R", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Effekt-\ninnst.", + "description": "" + }, + "SolderingMenu": { + "displayText": "Lodde-\ninnst.", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Dvale-\ninnst.", + "description": "" + }, + "UIMenu": { + "displayText": "Bruker-\ngrensesn.", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Avanserte\nvalg", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Kilde\n", + "description": "Strømforsyning. Sett nedre spenning for automatisk nedstenging. (DC 10V) (S 3.3V per celle)" + }, + "MinVolCell": { + "displayText": "Minimum\nspenning", + "description": "Minimum tillatt spenning per celle (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "QC-\nspenning", + "description": "Maks QC-spenning bolten skal forhandle om" + }, + "PDNegTimeout": { + "displayText": "PD-\ntidsavb.", + "description": "PD-forhandlingstidsavbrudd i steg på 100 ms for kompatibilitet med noen QC-ladere" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "KTmp\n", + "description": "Temperatur i \"kraft-modus\"" + }, + "AutoStart": { + "displayText": "AStart\n", + "description": "Start automatisk med lodding når strøm kobles til. (L=Lodding | D=Dvale | R=Dvale romtemperatur)" + }, + "TempChangeShortStep": { + "displayText": "Temp-endring\nkort", + "description": "Hvor mye temperaturen skal endres ved kort trykk på knapp" + }, + "TempChangeLongStep": { + "displayText": "Temp-endring\nlang", + "description": "Hvor mye temperaturen skal endres ved langt trykk på knapp" + }, + "LockingMode": { + "displayText": "Tillat å låse\nknapper", + "description": "Mens du lodder, hold nede begge knapper for å bytte mellom låsemodus (B=kun boost | F=full lås)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "BSensr\n", + "description": "Bevegelsesfølsomhet (1=Minst følsom | ... | 9=Mest følsom)" + }, + "SleepTemperature": { + "displayText": "DTmp\n", + "description": "Dvaletemperatur (C)" + }, + "SleepTimeout": { + "displayText": "DTid\n", + "description": "Tid før dvale (Minutter | Sekunder)" + }, + "ShutdownTimeout": { + "displayText": "AvTid\n", + "description": "Tid før automatisk nedstenging (Minutter)" + }, + "HallEffSensitivity": { + "displayText": "Hall-sensor\nfølsomhet", + "description": "Sensitiviteten til Hall-effekt-sensoren for å detektere inaktivitet (1=Minst følsom | ... | 9=Mest følsom)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Intervall før \"dvalemodus\" starter når halleffekten er over terskelen" + }, + "TemperatureUnit": { + "displayText": "TmpEnh\n", + "description": "Temperaturskala (C=Celsius | F=Fahrenheit)" + }, + "DisplayRotation": { + "displayText": "SkRetn\n", + "description": "Skjermretning (H=Høyrehendt | V=Venstrehendt | A=Automatisk)" + }, + "CooldownBlink": { + "displayText": "KjBlnk\n", + "description": "Blink temperaturen på skjermen mens spissen fortsatt er varm." + }, + "ScrollingSpeed": { + "displayText": "RullHa\n", + "description": "Hastigheten på rulletekst" + }, + "ReverseButtonTempChange": { + "displayText": "Bytt\n+ - kn.", + "description": "Bytt om på knappene for å stille temperatur" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\nhastighet", + "description": "Hastigheten til animasjonene i menyen (S=slow | M=medium | F=fast)" + }, + "AnimLoop": { + "displayText": "Anim.\nloop", + "description": "Loop ikon-animasjoner i hovedmenyen" + }, + "Brightness": { + "displayText": "Skjerm-\nlysstyrke", + "description": "Juster lysstyrken til OLED-skjermen" + }, + "ColourInversion": { + "displayText": "Inverter\nskjerm", + "description": "Inverter fargene på OLED-skjermen" + }, + "LOGOTime": { + "displayText": "Oppstartlogo\nvarighet", + "description": "Setter varigheten til oppstartlogoen (s=sekunder)" + }, + "AdvancedIdle": { + "displayText": "AvDvSk\n", + "description": "Vis detaljert informasjon med liten skrift på dvaleskjermen." + }, + "AdvancedSoldering": { + "displayText": "AvLdSk\n", + "description": "Vis detaljert informasjon ved lodding" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Effekt-\ngrense", + "description": "Maks effekt jernet kan bruke (W=watt)" + }, + "CalibrateCJC": { + "displayText": "TempKal?\n", + "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" + }, + "VoltageCalibration": { + "displayText": "KalSpIn?\n", + "description": "Kalibrer spenning. Knappene justerer. Langt trykk for å gå ut" + }, + "PowerPulsePower": { + "displayText": "Effekt-\npuls", + "description": "Hvor høy effekt pulsen for å holde laderen våken skal ha (watt)" + }, + "PowerPulseWait": { + "displayText": "Effektpuls\nforsink.", + "description": "Forsinkelse før effektpulsen utløses (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Effektpuls\nvarighet", + "description": "Hvor lenge holde-våken-pulsen varer (x 250ms)" + }, + "SettingsReset": { + "displayText": "TilbStl?\n", + "description": "Tilbakestill alle innstillinger" + }, + "LanguageSwitch": { + "displayText": "Språk:\n NB Norsk bm", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_NL.json b/Translations/translation_NL.json index 06e9075f2..cd8250287 100644 --- a/Translations/translation_NL.json +++ b/Translations/translation_NL.json @@ -1,319 +1,351 @@ { - "languageCode": "NL", - "languageLocalName": "Nederlands", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Instellingen\nzijn gereset!" - }, - "NoAccelerometerMessage": { - "message": "Geen accelerometer\ngedetecteerd!" - }, - "NoPowerDeliveryMessage": { - "message": "Geen USB-PD IC \ngedetecteerd!" - }, - "LockingKeysString": { - "message": "GEBLOKKEERD" - }, - "UnlockingKeysString": { - "message": "GEDEBLOKKEERD" - }, - "WarningKeysLockedString": { - "message": "!GEBLOKKEERD!" - }, - "WarningThermalRunaway": { - "message": "Verwarming\nOncontroleerbaar" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Weet je zeker dat je de fabrieksinstellingen terug wilt zetten?" - }, - "UVLOWarningString": { - "message": "DC Laag" - }, - "UndervoltageString": { - "message": "Onderspanning\n" - }, - "InputVoltageString": { - "message": "Voeding V: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Slaapstand...\n" - }, - "SleepingTipAdvancedString": { - "message": "Punt: \n" - }, - "OffString": { - "message": "Uit" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Jouw toestel is wellicht een namaak-versie!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "R", - "SettingLeftChar": "L", - "SettingAutoChar": "A", - "SettingOffChar": "U", - "SettingSlowChar": "L", - "SettingMediumChar": "G", - "SettingFastChar": "S", - "SettingStartNoneChar": "U", - "SettingStartSolderingChar": "G", - "SettingStartSleepChar": "S", - "SettingStartSleepOffChar": "B", - "SettingLockDisableChar": "U", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "V" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Voeding\ninstellingen", - "description": "" - }, - "SolderingMenu": { - "displayText": "Soldeer\ninstellingen", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Slaap\nModes", - "description": "" - }, - "UIMenu": { - "displayText": "Weergave\ninstellingen", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Geavanceerde\ninstellingen", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Spannings-\nbron", - "description": "Spanningsbron. Stelt drempelspanning in. (DC 10V) (S 3.3V per cel)" - }, - "MinVolCell": { - "displayText": "Minimum\nvoltage", - "description": "Minimum toegestaan voltage per cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "QC\nvoltage", - "description": "Maximaal QC voltage dat gevraagd mag worden" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "PD afstemmingsduur in stappen van 100ms (voor compatibiliteit met sommige QC laders)" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Boost\ntemp", - "description": "Punt temperatuur in boostmode" - }, - "AutoStart": { - "displayText": "Opstart\ngedrag", - "description": "Gedrag bij opstarten (U=Uit | G=Gebruiks-temperatuur | S=Slaapstand-temperatuur tot beweging | B=Uit tot beweging)" - }, - "TempChangeShortStep": { - "displayText": "Temp veranderen\nkort", - "description": "Temperatuur verandering bij kort drukken" - }, - "TempChangeLongStep": { - "displayText": "Temp veranderen\nlang", - "description": "Temperatuur verandering bij lang drukken" - }, - "LockingMode": { - "displayText": "Knopblokkering\ninschakelen", - "description": "Tijdens solderen lang op beide knoppen drukken blokkeert de knoppen (U=Uit | B=Alleen boost mode | V=Volledig blokkeren)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Bewegings-\ngevoeligheid", - "description": "Bewegingsgevoeligheid (0=uit | 1=minst gevoelig | ... | 9=meest gevoelig)" - }, - "SleepTemperature": { - "displayText": "Slaap\ntemp", - "description": "Punt temperatuur in slaapstand" - }, - "SleepTimeout": { - "displayText": "Slaap\ntime-out", - "description": "Tijd voordat slaapmodus wordt geactiveerd (S=seconden | M=minuten)" - }, - "ShutdownTimeout": { - "displayText": "Uitschakel\ntime-out", - "description": "Tijd voordat soldeerbout automatisch uitschakelt (M=minuten)" - }, - "HallEffSensitivity": { - "displayText": "Hall sensor\ngevoeligheid", - "description": "Gevoeligheid van de Hall effect sensor om naar slaapmodus te gaan (0=uit | 1=minst gevoelig | ... | 9=meest gevoelig)" - }, - "TemperatureUnit": { - "displayText": "Temperatuur\neenheid", - "description": "Temperatuureenheid (C=Celsius | F=Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "Scherm-\noriëntatie", - "description": "Schermoriëntatie (R=Rechtshandig | L=Linkshandig | A=Automatisch)" - }, - "CooldownBlink": { - "displayText": "Afkoel\nflitsen", - "description": "Temperatuur laten flitsen in het hoofdmenu zo lang de punt nog warm is" - }, - "ScrollingSpeed": { - "displayText": "Scroll\nsnelheid", - "description": "Snelheid waarmee de tekst scrolt (S=Snel | L=Langzaam)" - }, - "ReverseButtonTempChange": { - "displayText": "Draai\n+ - knoppen om", - "description": "Keer de +- knoppen van de temperatuurregeling om" - }, - "AnimSpeed": { - "displayText": "Animatie\nsnelheid", - "description": "Tempo van de icoon animaties in het hoofdmenu (U=uit | L=langzaam | G=gemiddeld | S=snel)" - }, - "AnimLoop": { - "displayText": "Animatie\nherhaling", - "description": "Herhaal icoon animaties in hoofdmenu" - }, - "Brightness": { - "displayText": "Scherm\nhelderheid", - "description": "Pas helderheid van het OLED scherm aan" - }, - "ColourInversion": { - "displayText": "Inverteer\nscherm", - "description": "Inverteer de kleuren van het OLED scherm" - }, - "LOGOTime": { - "displayText": "Opstart logo\nduur", - "description": "Stelt de weergaveduur van het opstartlogo in (s=seconden)" - }, - "AdvancedIdle": { - "displayText": "Gedetailleerd\nstartscherm", - "description": "Gedetailleerde informatie weergeven in een kleine letters op het startscherm." - }, - "AdvancedSoldering": { - "displayText": "Gedetailleerd\nsoldeerscherm", - "description": "Gedetailleerde informatie weergeven in een kleiner lettertype op het soldeerscherm" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Vermogen\nlimiet", - "description": "Maximaal vermogen (W=Watt)" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nat next boot", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Kalibreer\ninput-voltage?", - "description": "Start VIN Kalibratie (druk lang om te sluiten)" - }, - "PowerPulsePower": { - "displayText": "Stroom\nPuls", - "description": "Intensiteit van stroompuls om voeding aan te houden (watt)" - }, - "PowerPulseWait": { - "displayText": "Stroompuls\ninterval", - "description": "Tijdsduur tussen voeding wakker-blijf-pulsen (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Power pulse\nduur", - "description": "Duur van voeding-wakker-blijf-pulsen (x 250ms)" - }, - "SettingsReset": { - "displayText": "Instellingen\nresetten?", - "description": "Alle instellingen terugzetten naar fabrieksinstellingen" - }, - "LanguageSwitch": { - "displayText": "Taal:\n NL Nederlands", - "description": "" - } + "languageCode": "NL", + "languageLocalName": "Nederlands", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibratie\nklaar!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Sommige instellingen\nzijn veranderd!" + }, + "NoAccelerometerMessage": { + "message": "Geen accelerometer\ngedetecteerd!" + }, + "NoPowerDeliveryMessage": { + "message": "Geen USB-PD IC\ngedetecteerd!" + }, + "LockingKeysString": { + "message": "GEBLOKKEERD" + }, + "UnlockingKeysString": { + "message": "VRIJ" + }, + "WarningKeysLockedString": { + "message": "!GEBLOKKEERD!" + }, + "WarningThermalRunaway": { + "message": "Thermisch\nop hol geslagen" + }, + "WarningTipShorted": { + "message": "!Kortgesloten Soldeerpunt!" + }, + "SettingsCalibrationWarning": { + "message": "Voordat je opnieuw opstart: zorg dat de soldeerpunt op kamertemperatuur is!" + }, + "CJCCalibrating": { + "message": "Kalibreren\n" + }, + "SettingsResetWarning": { + "message": "Weet je zeker dat je de fabrieksinstellingen terug wilt zetten?" + }, + "UVLOWarningString": { + "message": "DC Laag" + }, + "UndervoltageString": { + "message": "Te lage spanning\n" + }, + "InputVoltageString": { + "message": "Ingangs spanning: \n" + }, + "SleepingAdvancedString": { + "message": "Slaapt...\n" + }, + "SleepingTipAdvancedString": { + "message": "Punt: \n" + }, + "ProfilePreheatString": { + "message": "Voorverwarmen\n" + }, + "ProfileCooldownString": { + "message": "Afkoelen\n" + }, + "DeviceFailedValidationWarning": { + "message": "Jou apparaat is waarschijnlijk een namaak!" + }, + "TooHotToStartProfileWarning": { + "message": "Te warm om\nprofiel te starten" + } + }, + "characters": { + "SettingRightChar": "R", + "SettingLeftChar": "L", + "SettingAutoChar": "A", + "SettingSlowChar": "L", + "SettingMediumChar": "M", + "SettingFastChar": "S", + "SettingStartSolderingChar": "T", + "SettingStartSleepChar": "S", + "SettingStartSleepOffChar": "Z", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "V" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Energie-\ninstellingen", + "description": "" + }, + "SolderingMenu": { + "displayText": "Soldeer\ninstellingen", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Slaap-\nstand", + "description": "" + }, + "UIMenu": { + "displayText": "Gebruiker-\nsomgeving", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Geavanceerde\ninstellingen", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Vermogens\nbron", + "description": "Minimale spanning om de batterij te beschermen tegen te ver ontladen (DC 10V) (S=3,3V per cell, zet PWR limiet uit)" + }, + "MinVolCell": { + "displayText": "Minimum\nspanning", + "description": "Minimale toegelaten voltage per cel (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\nspanning", + "description": "Maximale QC spanning de soldeerbout zou moeten aanvragen" + }, + "PDNegTimeout": { + "displayText": "PD ver-\nloop tijd", + "description": "PD onderhandelings verlooptijd, afstemmingsduur in stappen van 100 ms (voor compatibiliteit met sommige QC laders)" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "Zet PPS & EPR modes aan" + }, + "BoostTemperature": { + "displayText": "Boost\ntemp", + "description": "Tip temperatuur tijdens \"boost-modus\"" + }, + "AutoStart": { + "displayText": "start-\ngedrag", + "description": "T=verwarm naar soldeer temp | S=standby op slaap temp tot bewogen | Z=standby zonder verwarmen tot bewogen" + }, + "TempChangeShortStep": { + "displayText": "temp veran-\ndering kort", + "description": "Temperatuur veranderings stap bij korte druk op de knop" + }, + "TempChangeLongStep": { + "displayText": "temp veran-\ndering lang", + "description": "Temperatuur veranderings stap bij lange druk op de knop" + }, + "LockingMode": { + "displayText": "Vergrendel-\nings knoppen", + "description": "Houd tijdens het solderen beide knoppen ingedrukt om de vergrendeling in of uit te schakelen (B=alleen boost-modus | V=volledige vergrendeling)" + }, + "ProfilePhases": { + "displayText": "Profiel\nfases", + "description": "Nummer van fases in profiel modus" + }, + "ProfilePreheatTemp": { + "displayText": "Voorverwarm\ntemperatuur", + "description": "Voorverwarm naar deze temperatuur op de start van profiel modus" + }, + "ProfilePreheatSpeed": { + "displayText": "Voorverwarm\nsnelheid", + "description": "Voorverwarm op deze snelheid (graden per seconden)" + }, + "ProfilePhase1Temp": { + "displayText": "Fase 1\ntemperatuur", + "description": "Doel temperatuur op het einde van deze fase" + }, + "ProfilePhase1Duration": { + "displayText": "Fase\nduur", + "description": "Doel tijdsduur van deze fase (in seconden)" + }, + "ProfilePhase2Temp": { + "displayText": "Fase 2\ntemperatuur", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Fase 2\nduur", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Fase 3\ntemperatuur", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Fase 3\nduur", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Fase 4\ntemperatuur", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Fase 4\nduur", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Fase 5\ntemperatuur", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Fase 5\nduur", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Afkoel\nsnelheid", + "description": "De snelheid van afkoelen op het eind van profiel modus (graden per seconden)" + }, + "MotionSensitivity": { + "displayText": "Bewegings-\ngevoeligheid", + "description": "Bewegingsgevoeligheid (1=minst gevoelig | ... | 9=meest gevoelig)" + }, + "SleepTemperature": { + "displayText": "Slaap\ntemp", + "description": "Temperatuur in slaapstand (°C)" + }, + "SleepTimeout": { + "displayText": "Slaap ver-\ntraging", + "description": "Interval voor \"slaap stand\" start (Minuten | Seconden)" + }, + "ShutdownTimeout": { + "displayText": "Uitschakel\nna", + "description": "Automatisch afsluiten na (Minuten)" + }, + "HallEffSensitivity": { + "displayText": "Hall sensor\ngevoeligheid", + "description": "Gevoeligheid naar de magneten (1=minst gevoelig | ... | 9=meest gevoelig)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval voordat de \"slaapmodus\" start wanneer het Hall-effect boven de drempelwaarde komt" + }, + "TemperatureUnit": { + "displayText": "Temperatuur\neenheid", + "description": "C=°Celsius | F=°Fahrenheit" + }, + "DisplayRotation": { + "displayText": "Scherm-\noriëntatie", + "description": "R=Rechtshandig | L=Linkshandig | A=Automatisch" + }, + "CooldownBlink": { + "displayText": "Afkoel\nknipper", + "description": "Temperatuur knippert in hoofdmenu tijdens afkoeling" + }, + "ScrollingSpeed": { + "displayText": "Scroll\nsnelheid", + "description": "Scrollsnelheid van de tekst. (Langzaam | Snel)" + }, + "ReverseButtonTempChange": { + "displayText": "Wissel\n+ - knoppen", + "description": "Wissel de knoppen voor temperatuur controle om" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\nsnelheid", + "description": "Snelheid van de icoon animaties in het menu (Langzaam | Middel | Snel)" + }, + "AnimLoop": { + "displayText": "Anim.\nherhaling", + "description": "Herhaal icoon animaties in hoofdmenu" + }, + "Brightness": { + "displayText": "Scherm\nhelderheid", + "description": "Verander de helderheid van het OLED scherm" + }, + "ColourInversion": { + "displayText": "Inverteer\nscherm", + "description": "Keer de kleuren van het OLED scherm om" + }, + "LOGOTime": { + "displayText": "Opstart\nlogo duur", + "description": "Zet het duur van het opstart logo (s=seconden)" + }, + "AdvancedIdle": { + "displayText": "Detail\nslaapscherm", + "description": "Gedetailleerde informatie in een kleiner lettertype in het slaapscherm" + }, + "AdvancedSoldering": { + "displayText": "Detail\nsoldeerscherm", + "description": "Gedetailleerde informatie in kleiner lettertype in soldeerscherm" + }, + "BluetoothLE": { + "displayText": "Blue-\ntooth", + "description": "Zet Bluetooth aan" + }, + "PowerLimit": { + "displayText": "P\nlimiet", + "description": "Gemiddelde maximale vermogen dat de soldeerbout mag gebruiken (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Kalibreer CJC\nbij opstart", + "description": "Bij de volgende opstart tip \"Cold Junction Compensation\" wordt gekalibreerd (niet nodig als Delta T < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibreer vo-\nedingsspanning", + "description": "VIN Kalibreren (lang in te drukken om te annuleren)" + }, + "PowerPulsePower": { + "displayText": "Power\npuls", + "description": "Power van de aanhoud puls (W=watt)" + }, + "PowerPulseWait": { + "displayText": "Energie pulse\nvertraging", + "description": "Vertraging voordat de aanhoud puls wordt geactiveerd (x 2,5s)" + }, + "PowerPulseDuration": { + "displayText": "Power pulse\nduur", + "description": "Aanhoud pulse duur (x 250 ms)" + }, + "SettingsReset": { + "displayText": "Instellingen\nresetten?", + "description": "Alle instellingen terug zetten naar fabrieksinstellingen" + }, + "LanguageSwitch": { + "displayText": "Taal:\n NL Nederlands", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_NL_BE.json b/Translations/translation_NL_BE.json index 6a684fce2..cae333b59 100644 --- a/Translations/translation_NL_BE.json +++ b/Translations/translation_NL_BE.json @@ -1,319 +1,351 @@ { - "languageCode": "NL_BE", - "languageLocalName": "Vlaams", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Certain settings\nwere changed!" - }, - "NoAccelerometerMessage": { - "message": "No accelerometer\ndetected!" - }, - "NoPowerDeliveryMessage": { - "message": "No USB-PD IC\ndetected!" - }, - "LockingKeysString": { - "message": "LOCKED" - }, - "UnlockingKeysString": { - "message": "UNLOCKED" - }, - "WarningKeysLockedString": { - "message": "!LOCKED!" - }, - "WarningThermalRunaway": { - "message": "Thermal\nRunaway" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Ben je zeker dat je alle standaardwaarden wil resetten?" - }, - "UVLOWarningString": { - "message": "Voedingsspanning LAAG" - }, - "UndervoltageString": { - "message": "Onderspanning\n" - }, - "InputVoltageString": { - "message": "Voedingsspanning: \n" - }, - "SleepingSimpleString": { - "message": "Zzz " - }, - "SleepingAdvancedString": { - "message": "Slaapstand...\n" - }, - "SleepingTipAdvancedString": { - "message": "Punt: \n" - }, - "OffString": { - "message": "Uit" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Your device is most likely a counterfeit!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "R", - "SettingLeftChar": "L", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "T", - "SettingMediumChar": "M", - "SettingFastChar": "S", - "SettingStartNoneChar": "F", - "SettingStartSolderingChar": "T", - "SettingStartSleepChar": "S", - "SettingStartSleepOffChar": "K", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Power\nsettings", - "description": "" - }, - "SolderingMenu": { - "displayText": "Soldeer\nInstellingen", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Slaap\nstanden", - "description": "" - }, - "UIMenu": { - "displayText": "Gebruikers-\nInterface", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Gevorderde\nInstellingen", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Spannings-\nbron", - "description": "Spanningsbron. Stelt minimumspanning in. (DC 10V) (S 3.3V per cel)" - }, - "MinVolCell": { - "displayText": "Minimum\nvoltage", - "description": "Minimum allowed voltage per cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "Vermogen\nWatt", - "description": "Vermogen van de adapter" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Verhogings\ntemp", - "description": "Verhogingstemperatuur" - }, - "AutoStart": { - "displayText": "Auto\nstart", - "description": "Breng de soldeerbout op temperatuur bij het opstarten. (F=Uit | T=Soldeertemperatuur | S=Slaapstand-temperatuur | K=Slaapstand kamertemperatuur)" - }, - "TempChangeShortStep": { - "displayText": "Temp change\nshort", - "description": "Temperature-change-increment on short button press" - }, - "TempChangeLongStep": { - "displayText": "Temp change\nlong", - "description": "Temperature-change-increment on long button press" - }, - "LockingMode": { - "displayText": "Allow locking\nbuttons", - "description": "While soldering, hold down both buttons to toggle locking them (D=disable | B=boost mode only | F=full locking)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Bewegings-\ngevoeligheid", - "description": "Bewegingsgevoeligheid (0=uit | 1=minst gevoelig | ... | 9=meest gevoelig)" - }, - "SleepTemperature": { - "displayText": "Slaap\ntemp", - "description": "Temperatuur in slaapstand (°C)" - }, - "SleepTimeout": { - "displayText": "Slaap\ntime-out", - "description": "Slaapstand time-out (Minuten | Seconden)" - }, - "ShutdownTimeout": { - "displayText": "Uitschakel\ntime-out", - "description": "Automatisch afsluiten time-out (Minuten)" - }, - "HallEffSensitivity": { - "displayText": "Hall sensor\nsensitivity", - "description": "Sensitivity to magnets (0=uit | 1=minst gevoelig | ... | 9=meest gevoelig)" - }, - "TemperatureUnit": { - "displayText": "Temperatuur\nschaal", - "description": "Temperatuurschaal (°C=Celsius | °F=Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "Scherm-\noriëntatie", - "description": "Schermoriëntatie (R=Rechtshandig | L=Linkshandig | A=Automatisch)" - }, - "CooldownBlink": { - "displayText": "Afkoel\nknipper", - "description": "Temperatuur knippert in hoofdmenu tijdens afkoeling." - }, - "ScrollingSpeed": { - "displayText": "Scrol\nsnelheid", - "description": "Scrolsnelheid van de tekst." - }, - "ReverseButtonTempChange": { - "displayText": "Swap\n+ - keys", - "description": "Reverse assignment of buttons for temperature adjustment" - }, - "AnimSpeed": { - "displayText": "Anim.\nspeed", - "description": "Pace of icon animations in menu (O=off | T=slow | M=medium | S=fast)" - }, - "AnimLoop": { - "displayText": "Anim.\nloop", - "description": "Loop icon animations in main menu" - }, - "Brightness": { - "displayText": "Screen\nbrightness", - "description": "Adjust the OLED screen brightness" - }, - "ColourInversion": { - "displayText": "Invert\nscreen", - "description": "Invert the OLED screen colors" - }, - "LOGOTime": { - "displayText": "Boot logo\nduration", - "description": "Set boot logo duration (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Gedetailleerd\nslaapscherm", - "description": "Gedetailleerde informatie in een kleiner lettertype in het slaapscherm." - }, - "AdvancedSoldering": { - "displayText": "Gedetailleerd\nsoldeerscherm", - "description": "Gedetailleerde informatie in kleiner lettertype in soldeerscherm." - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Power\nlimit", - "description": "Average maximum power the iron can use (W=watt)" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nat next boot", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Calibreer\nvoedingsspanning?", - "description": "VIN Calibreren. Bevestigen door knoppen lang in te drukken." - }, - "PowerPulsePower": { - "displayText": "Power\npulse", - "description": "Intensity of power of keep-awake-pulse (W=watt)" - }, - "PowerPulseWait": { - "displayText": "Power pulse\ndelay", - "description": "Delay before keep-awake-pulse is triggered (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Power pulse\nduration", - "description": "Keep-awake-pulse duration (x 250ms)" - }, - "SettingsReset": { - "displayText": "Instellingen\nresetten?", - "description": "Alle instellingen resetten." - }, - "LanguageSwitch": { - "displayText": "Spraak:\n NL_BE Vlaams", - "description": "" - } + "languageCode": "NL_BE", + "languageLocalName": "Vlaams", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibratie\ngedaan!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Sommige settings\nzijn veranderd!" + }, + "NoAccelerometerMessage": { + "message": "Geen accelerometer\ngedectecteerd!" + }, + "NoPowerDeliveryMessage": { + "message": "Geen USB-PD IC\ngedetecteerd!" + }, + "LockingKeysString": { + "message": "LOCKED" + }, + "UnlockingKeysString": { + "message": "UNLOCKED" + }, + "WarningKeysLockedString": { + "message": "!LOCKED!" + }, + "WarningThermalRunaway": { + "message": "Thermisch\nop hol geslagen" + }, + "WarningTipShorted": { + "message": "!Soldeerpunt kortgesloten!" + }, + "SettingsCalibrationWarning": { + "message": "Voordat je opnieuw opstart: stel zeker dat de soldeerpunt op kamertemperatuur is!" + }, + "CJCCalibrating": { + "message": "Calibreren\n" + }, + "SettingsResetWarning": { + "message": "Weet je zeker dat je de fabrieksinstellingen terug wilt zetten?" + }, + "UVLOWarningString": { + "message": "Onderspanning" + }, + "UndervoltageString": { + "message": "Onderspanning\n" + }, + "InputVoltageString": { + "message": "Voedingsspanning: \n" + }, + "SleepingAdvancedString": { + "message": "Slaapstand...\n" + }, + "SleepingTipAdvancedString": { + "message": "Punt: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Jou apparaat is waarschijnlijk namaak!" + }, + "TooHotToStartProfileWarning": { + "message": "Te warm om\nprofiel te starten!" + } + }, + "characters": { + "SettingRightChar": "R", + "SettingLeftChar": "L", + "SettingAutoChar": "A", + "SettingSlowChar": "T", + "SettingMediumChar": "M", + "SettingFastChar": "S", + "SettingStartSolderingChar": "T", + "SettingStartSleepChar": "S", + "SettingStartSleepOffChar": "K", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Vermogens-\ninstellingen", + "description": "" + }, + "SolderingMenu": { + "displayText": "Soldeer\ninstellingen", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Slaap-\nstanden", + "description": "" + }, + "UIMenu": { + "displayText": "Gebruikers-\ninterface", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Geavanceerde\ninstellingen", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Spannings-\nbron", + "description": "Minimale toegelate voltage" + }, + "MinVolCell": { + "displayText": "Minimum\nvoltage", + "description": "Minimale toegelaten voltage per cel (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "Vermogen\nwatt", + "description": "Vermogen van de adapter" + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "PD afstemmingsduur in stappen van 100ms (voor compatibiliteit met sommige QC laders)" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "Zet PPS & EPR modes aan" + }, + "BoostTemperature": { + "displayText": "Verhog\nings temp", + "description": "Verhogingstemperatuur" + }, + "AutoStart": { + "displayText": "start-\ntemperatuur", + "description": "Breng de soldeerbout op temperatuur bij het opstarten. (T=Soldeertemperatuur | S=Slaapstand-temperatuur | K=Slaapstand kamertemperatuur)" + }, + "TempChangeShortStep": { + "displayText": "temp veran\ndering kort", + "description": "Temperatuurveranderingsstap bij korte druk op de knop" + }, + "TempChangeLongStep": { + "displayText": "temp veran\ndering lang", + "description": "Temperatuurveranderingsstap bij lange druk op de knop" + }, + "LockingMode": { + "displayText": "Vergrendel-\ning knoppen", + "description": "Houd tijdens het solderen beide knoppen ingedrukt om de vergrendeling in of uit te schakelen (B=alleen boost-modus | F=volledige vergrendeling)" + }, + "ProfilePhases": { + "displayText": "Profiel\nfases", + "description": "Nummer van fases in profiel modus" + }, + "ProfilePreheatTemp": { + "displayText": "Voorverwarm\ntemperatuur", + "description": "Voorverwarm naar deze temperatuur op de start van profiel modus" + }, + "ProfilePreheatSpeed": { + "displayText": "Voorverwarm\nsnelheid", + "description": "Voorverwarm op deze snelheid (graden per seconden)" + }, + "ProfilePhase1Temp": { + "displayText": "Fase 1\ntemperatuur", + "description": "Doel temperatuur op het einde van deze fase" + }, + "ProfilePhase1Duration": { + "displayText": "Fase\nduur", + "description": "Doel tijdsduur van deze fase (in seconden)" + }, + "ProfilePhase2Temp": { + "displayText": "Fase 2\ntemperatuur", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Fase 2\nduur", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Fase 3\ntemperatuur", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Fase 3\nduur", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Fase 4\ntemperatuur", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Fase 4\nduur", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Fase 5\ntemperatuur", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Fase 5\nduur", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Afkoel\nsnelheid", + "description": "De snelheid van afkoelen op het eind van profiel modus (graden per seconden)" + }, + "MotionSensitivity": { + "displayText": "Bewegings-\ngevoeligheid", + "description": "Bewegingsgevoeligheid (1=minst gevoelig | ... | 9=meest gevoelig)" + }, + "SleepTemperature": { + "displayText": "Slaap\ntemp", + "description": "Temperatuur in slaapstand (°C)" + }, + "SleepTimeout": { + "displayText": "Slaap\ntime-out", + "description": "Slaapstand time-out (Minuten | Seconden)" + }, + "ShutdownTimeout": { + "displayText": "Uitschakel\ntime-out", + "description": "Automatisch afsluiten time-out (Minuten)" + }, + "HallEffSensitivity": { + "displayText": "Hall sensor\ngevoeligheid", + "description": "Gevoeligheid naar de magneten (1=minst gevoelig | ... | 9=meest gevoelig)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval voordat de \"slaapmodus\" start wanneer het Hall-effect boven de drempelwaarde komt" + }, + "TemperatureUnit": { + "displayText": "Temperatuur\nschaal", + "description": "Temperatuurschaal (°C=Celsius | °F=Fahrenheit)" + }, + "DisplayRotation": { + "displayText": "Scherm-\noriëntatie", + "description": "Schermoriëntatie (R=Rechtshandig | L=Linkshandig | A=Automatisch)" + }, + "CooldownBlink": { + "displayText": "Afkoel\nknipper", + "description": "Temperatuur knippert in hoofdmenu tijdens afkoeling." + }, + "ScrollingSpeed": { + "displayText": "Scroll\nsnelheid", + "description": "Scrollsnelheid van de tekst." + }, + "ReverseButtonTempChange": { + "displayText": "Wissel\n+ - knoppen", + "description": "Wissel de knoppen voor temperatuur controle" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\nsnelheid", + "description": "Snelheid van de icoon animaties in het menu (T=sloom | M=middel | S=snel)" + }, + "AnimLoop": { + "displayText": "Anim.\nherhaling", + "description": "Herhaal icoon animaties in hoofdmenu" + }, + "Brightness": { + "displayText": "Scherm\nhelderheid", + "description": "Verander de helderheid van het OLED scherm" + }, + "ColourInversion": { + "displayText": "Omkeer\nscherm", + "description": "Omkeer de kleuren van het OLED scherm" + }, + "LOGOTime": { + "displayText": "Opstart\nlogo lengte", + "description": "Zet het lengte van het opstart logo (s=seconden)" + }, + "AdvancedIdle": { + "displayText": "Gedetailleerd\nslaapscherm", + "description": "Gedetailleerde informatie in een kleiner lettertype in het slaapscherm" + }, + "AdvancedSoldering": { + "displayText": "Gedetailleerd\nsoldeerscherm", + "description": "Gedetailleerde informatie in kleiner lettertype in soldeerscherm" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Zet Bluetooth aan" + }, + "PowerLimit": { + "displayText": "Power\nlimit", + "description": "Gemiddelde maximale power dat de soldeerbout mag gebruiken (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Calibreer CJC\nbij opstart", + "description": "Bij de volgende opstart tip Cold Junction Compensation wordt gecalibreerd (niet nodig als Delta T < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Calibreervo-\nedingsspanning?", + "description": "VIN Calibreren. Bevestigen door knoppen lang in te drukken." + }, + "PowerPulsePower": { + "displayText": "Power\npuls", + "description": "Power van de wakker-houd-puls (W=watt)" + }, + "PowerPulseWait": { + "displayText": "Power pulse\nvertraging", + "description": "Vertraging voordat de wakker-houd-puls wordt geactiveerd (x 2,5s)" + }, + "PowerPulseDuration": { + "displayText": "Power pulse\nduur", + "description": "Keep-awake-pulse duration (x 250ms)" + }, + "SettingsReset": { + "displayText": "Instellingen\nresetten?", + "description": "Alle instellingen resetten" + }, + "LanguageSwitch": { + "displayText": "Spraak:\n NL_BE Vlaams", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_PL.json b/Translations/translation_PL.json index c4237c10d..95a90bd8b 100644 --- a/Translations/translation_PL.json +++ b/Translations/translation_PL.json @@ -1,319 +1,351 @@ { - "languageCode": "PL", - "languageLocalName": "Polski", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Kalibracja\nwykonana!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Ust. \nzresetowane" - }, - "NoAccelerometerMessage": { - "message": "Nie rozpoznano\nakcelerometru!" - }, - "NoPowerDeliveryMessage": { - "message": "Nie rozpoznano\nkont. USB-PD IC!" - }, - "LockingKeysString": { - "message": " ZABLOK." - }, - "UnlockingKeysString": { - "message": "ODBLOK." - }, - "WarningKeysLockedString": { - "message": "!ZABLOK!" - }, - "WarningThermalRunaway": { - "message": "Ucieczka\ntermiczna" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Upewnij się, że końcówka i uchwyt mają temperaturę pokojową podczas następnego rozruchu!" - }, - "CJCCalibrating": { - "message": "kalibracja\n" - }, - "SettingsResetWarning": { - "message": "Czy na pewno chcesz przywrócić ustawienia fabryczne?" - }, - "UVLOWarningString": { - "message": "NIS. NAP" - }, - "UndervoltageString": { - "message": "Zbyt niskie nap.\n" - }, - "InputVoltageString": { - "message": "Nap. wej.: \n" - }, - "SleepingSimpleString": { - "message": "Zzz!" - }, - "SleepingAdvancedString": { - "message": "Tr. uśpienia\n" - }, - "SleepingTipAdvancedString": { - "message": "Grot: \n" - }, - "OffString": { - "message": "Wył" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Twoje urządzenie jest najprawdopodobniej podróbką!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "P", - "SettingLeftChar": "L", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "W", - "SettingMediumChar": "M", - "SettingFastChar": "S", - "SettingStartNoneChar": "B", - "SettingStartSolderingChar": "T", - "SettingStartSleepChar": "Z", - "SettingStartSleepOffChar": "O", - "SettingLockDisableChar": "W", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "P" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Ustawienia\nzasilania", - "description": "" - }, - "SolderingMenu": { - "displayText": "Lutowanie\n", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Oszcz.\nenergii", - "description": "" - }, - "UIMenu": { - "displayText": "Interfejs\nużytkownika", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Ustawienia\nzaawans.", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Źródło\nzasilania", - "description": "Źródło zasilania. Ustaw napięcie odcięcia. (DC 10V) (S 3.3V dla ogniw Li, wyłącz limit mocy)" - }, - "MinVolCell": { - "displayText": "Minimalne\nnapięcie", - "description": "Minimalne dozwolone napięcie na komórkę (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" - }, - "QCMaxVoltage": { - "displayText": "QC\nnapięcie", - "description": "Maksymalne napięcie, które lutownica będzie próbowała wynegocjować z ładowarką Quick Charge (V)" - }, - "PDNegTimeout": { - "displayText": "Limit czasu\nPD", - "description": "Limit czasu negocjacji PD w krokach co 100 ms dla zgodności z niektórymi ładowarkami QC (0: wyłączone)" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Włącza tryby PPS & EPR." - }, - "BoostTemperature": { - "displayText": "Temp.\nboost", - "description": "Temperatura w trybie \"boost\" " - }, - "AutoStart": { - "displayText": "Aut. uruch.\ntr. lutowania", - "description": "Automatyczne uruchamianie trybu lutowania po włączeniu zasilania. (B: wyłączone | T: lutowanie | Z: uśpienie | O: uśpienie w temp. pokojowej)" - }, - "TempChangeShortStep": { - "displayText": "Zm. temp.\nkr. przyc.", - "description": "Wartość zmiany temperatury, po krótkim przyciśnięciu (°C)" - }, - "TempChangeLongStep": { - "displayText": "Zm. temp.\ndł. przyc.", - "description": "Wartość zmiany temperatury, po długim przyciśnięciu (°C)" - }, - "LockingMode": { - "displayText": "Blokada\nprzycisków", - "description": "W trybie lutowania, wciśnij oba przyciski aby je zablokować (O=Wyłączona | B=tylko Boost | P=pełna blokada)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Czułość\nwykr. ruchu", - "description": "Czułość wykrywania ruchu (0: Wyłączona | 1: Minimalna | ... | 9: Maksymalna)" - }, - "SleepTemperature": { - "displayText": "Temp.\nuśpienia", - "description": "Temperatura w trybie uśpienia (°C)" - }, - "SleepTimeout": { - "displayText": "Czas do\nuśpienia", - "description": "Czas do przejścia w tryb uśpienia (minuty | sekundy)" - }, - "ShutdownTimeout": { - "displayText": "Czas do\nwyłączenia", - "description": "Czas do wyłączenia (minuty)" - }, - "HallEffSensitivity": { - "displayText": "Czułość\ncz. Halla", - "description": "Czułość czujnika Halla, używanego do przechodznia w tryb uśpienia (0: Wyłączona | 1: Minimalna | ... | 9: Maksymalna)" - }, - "TemperatureUnit": { - "displayText": "Jednostka\ntemperatury", - "description": "Jednostka temperatury (C: Celciusz | F: Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "Obrót\nekranu", - "description": "Obrót ekranu (P: dla praworęcznych | L: dla leworęcznych | A: automatycznie)" - }, - "CooldownBlink": { - "displayText": "Mig. podczas\nwychładzania", - "description": "Temperatura miga podczas wychładzania, gdy grot jest wciąż gorący" - }, - "ScrollingSpeed": { - "displayText": "Sz. przew.\ntekstu", - "description": "Szybkość przewijania tekstu" - }, - "ReverseButtonTempChange": { - "displayText": "Zamień przyc.\n+ -", - "description": "Zamienia działanie przycisków zmiany temperatury grotu" - }, - "AnimSpeed": { - "displayText": "Prędkosć\nanimacji", - "description": "Prędkość animacji ikon w menu (O: wył. | W: mała | M: średnia | S: duża)" - }, - "AnimLoop": { - "displayText": "Zapętlona\nanimacja", - "description": "Zapętla animację ikon w menu głównym" - }, - "Brightness": { - "displayText": "Jasność\nwyświetlacza", - "description": "Regulacja kontrastu/jasności wyświetlacza OLED" - }, - "ColourInversion": { - "displayText": "Odwrócenie\nkolorów", - "description": "Odwrócenie kolorów wyświetlacza OLED" - }, - "LOGOTime": { - "displayText": "Długość wyś.\nloga", - "description": "Ustawia czas wyświetlania loga podczas uruchamiania (s=sekund)" - }, - "AdvancedIdle": { - "displayText": "Szeczegółowy\nekran bezczy.", - "description": "Wyświetla szczegółowe informacje za pomocą mniejszej czcionki na ekranie bezczynności" - }, - "AdvancedSoldering": { - "displayText": "Sz. inf. w\ntr. lutowania", - "description": "Wyświetl szczegółowe informacje w trybie lutowania" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Ogr.\nmocy", - "description": "Maksymalna moc (W), jakiej może użyć lutownica" - }, - "CalibrateCJC": { - "displayText": "Kalibracja temperatury\nprzy następnym uruchomieniu", - "description": "Kalibracja temperatury przy następnym włączeniu (nie jest wymagana, jeśli różnica temperatur jest mniejsza niż 5°C" - }, - "VoltageCalibration": { - "displayText": "Kalibracja\nnapięcia", - "description": "Kalibracja napięcia wejściowego. Krótkie naciśnięcie, aby ustawić, długie naciśnięcie, aby wyjść." - }, - "PowerPulsePower": { - "displayText": "Moc\nimpulsu", - "description": "W przypadku używania powerbanku, utrzymuj moc na poziomie (W) aby nie uśpić powerbanku" - }, - "PowerPulseWait": { - "displayText": "Czas między\nimp. mocy", - "description": "Czas między kolejnymi impulsami mocy zapobiegającymi usypianiu powerbanku (x2,5 s)" - }, - "PowerPulseDuration": { - "displayText": "Długość\nimpulsu mocy", - "description": "Długość impulsu mocy zapobiegającego usypianiu powerbanku (x250 ms)" - }, - "SettingsReset": { - "displayText": "Ustawienia\nfabryczne", - "description": "Resetuje wszystkie ustawienia" - }, - "LanguageSwitch": { - "displayText": "Język:\n PL Polski", - "description": "" - } + "languageCode": "PL", + "languageLocalName": "Polski", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Skalibrowano!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Ust. \nzresetowane" + }, + "NoAccelerometerMessage": { + "message": "Nie rozpoznano\nakcelerometru!" + }, + "NoPowerDeliveryMessage": { + "message": "Nie rozpoznano\nkont. USB-PD IC!" + }, + "LockingKeysString": { + "message": "ZABLOK." + }, + "UnlockingKeysString": { + "message": "ODBLOK." + }, + "WarningKeysLockedString": { + "message": "!ZABLOK!" + }, + "WarningThermalRunaway": { + "message": "Ucieczka\ntermiczna" + }, + "WarningTipShorted": { + "message": "!Zwarty grot!" + }, + "SettingsCalibrationWarning": { + "message": "Upewnij się, że końcówka i uchwyt mają temperaturę pokojową podczas następnego rozruchu!" + }, + "CJCCalibrating": { + "message": "kalibracja\n" + }, + "SettingsResetWarning": { + "message": "Czy na pewno chcesz przywrócić ustawienia fabryczne?" + }, + "UVLOWarningString": { + "message": "NIS. NAP" + }, + "UndervoltageString": { + "message": "Zbyt niskie nap.\n" + }, + "InputVoltageString": { + "message": "Nap. wej.: \n" + }, + "SleepingAdvancedString": { + "message": "Tr. uśpienia\n" + }, + "SleepingTipAdvancedString": { + "message": "Grot: \n" + }, + "ProfilePreheatString": { + "message": "Rozgrzewanie\n" + }, + "ProfileCooldownString": { + "message": "Schładzanie\n" + }, + "DeviceFailedValidationWarning": { + "message": "Twoje urządzenie jest najprawdopodobniej podróbką!" + }, + "TooHotToStartProfileWarning": { + "message": "Zbyt gorące, aby\nuruchomić profil" + } + }, + "characters": { + "SettingRightChar": "P", + "SettingLeftChar": "L", + "SettingAutoChar": "A", + "SettingSlowChar": "W", + "SettingMediumChar": "M", + "SettingFastChar": "S", + "SettingStartSolderingChar": "T", + "SettingStartSleepChar": "Z", + "SettingStartSleepOffChar": "O", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "P" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Ustawienia\nzasilania", + "description": "" + }, + "SolderingMenu": { + "displayText": "Lutowanie\n", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Oszcz.\nenergii", + "description": "" + }, + "UIMenu": { + "displayText": "Interfejs\nużytkownika", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Ustawienia\nzaawans.", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Tryb\ndomyślny" + }, + "USBPDModeNoDynamic": { + "displayText": "Nie\ndynamiczny" + }, + "USBPDModeSafe": { + "displayText": "Tryb\nbezpieczny" + }, + "TipTypeAuto": { + "displayText": "Auto\nwykrycie" + }, + "TipTypeT12Long": { + "displayText": "Długi\nTS100" + }, + "TipTypeT12Short": { + "displayText": "Krótki\nPine" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Źródło\nzasilania", + "description": "Źródło zasilania. Ustaw napięcie odcięcia. (DC 10V) (S=3.3V dla ogniw Li, wyłącz limit mocy)" + }, + "MinVolCell": { + "displayText": "Minimalne\nnapięcie", + "description": "Minimalne dozwolone napięcie na komórkę (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" + }, + "QCMaxVoltage": { + "displayText": "Napięcie QC", + "description": "Maksymalne napięcie, które lutownica będzie próbowała wynegocjować z ładowarką Quick Charge (V)" + }, + "PDNegTimeout": { + "displayText": "Limit czasu\nPD", + "description": "Limit czasu negocjacji PD w krokach co 100ms dla zgodności z niektórymi ładowarkami QC (0: wyłączone)" + }, + "USBPDMode": { + "displayText": "Tryb PD", + "description": "Włącza tryby PPS & EPR." + }, + "BoostTemperature": { + "displayText": "Temp.\nboost", + "description": "Temp. w trybie \"boost\" " + }, + "AutoStart": { + "displayText": "Aut. uruch.\ntr. lutowania", + "description": "Automatyczne uruchamianie trybu lutowania po włączeniu zasilania. (T: lutowanie | Z: uśpienie | O: uśpienie w temp. pokojowej)" + }, + "TempChangeShortStep": { + "displayText": "Zm. temp.\nkr. przyc.", + "description": "Wartość zmiany temperatury, po krótkim przyciśnięciu (°C)" + }, + "TempChangeLongStep": { + "displayText": "Zm. temp.\ndł. przyc.", + "description": "Wartość zmiany temperatury, po długim przyciśnięciu (°C)" + }, + "LockingMode": { + "displayText": "Blokada\nprzycisków", + "description": "W trybie lutowania, wciśnij oba przyciski aby je zablokować (B=tylko Boost | P=pełna blokada)" + }, + "ProfilePhases": { + "displayText": "Fazy\nprofilu", + "description": "Liczba faz w trybie profilu" + }, + "ProfilePreheatTemp": { + "displayText": "Temp.\nrozgrzewania", + "description": "Rozgrzanie do tej temp. na początku trybu profilu" + }, + "ProfilePreheatSpeed": { + "displayText": "Prędk.\nrozgrzewania", + "description": "Tempo rozgrzewania (stopnie na sekundę)" + }, + "ProfilePhase1Temp": { + "displayText": "Temp.\nfazy 1", + "description": "Docelowa temp. na koniec tej fazy" + }, + "ProfilePhase1Duration": { + "displayText": "Dług.\nfazy 1", + "description": "Docelowy czas trwania tej fazy (sekundy)" + }, + "ProfilePhase2Temp": { + "displayText": "Temp.\nfazy 2", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Dług.\nfazy 2", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Temp.\nfazy 3", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Dług.\nfazy 3", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Temp.\nfazy 4", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Dług.\nfazy 4", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Temp.\nfazy 5", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Dług.\nfazy 5", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Prędk.\nschładzania", + "description": "Tempo schładzania na koniec trybu profilu (stopnie na sekundę)" + }, + "MotionSensitivity": { + "displayText": "Czułość\nwykr. ruchu", + "description": "Czułość wykrywania ruchu (1: Minimalna | ... | 9: Maksymalna)" + }, + "SleepTemperature": { + "displayText": "Temp.\nuśpienia", + "description": "Temperatura w trybie uśpienia (°C)" + }, + "SleepTimeout": { + "displayText": "Czas do\nuśpienia", + "description": "Czas do przejścia w tryb uśpienia (minuty | sekundy)" + }, + "ShutdownTimeout": { + "displayText": "Czas do\nwyłączenia", + "description": "Czas do wyłączenia (minuty)" + }, + "HallEffSensitivity": { + "displayText": "Czułość\ncz. Halla", + "description": "Czułość czujnika Halla, używanego do przechodznia w tryb uśpienia (1: Minimalna | ... | 9: Maksymalna)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Odstęp przed rozpoczęciem \"trybu uśpienia\", gdy efekt Halla przekracza próg" + }, + "TemperatureUnit": { + "displayText": "Jednostka\ntemperatury", + "description": "Jednostka temperatury (C: Celciusz | F: Fahrenheit)" + }, + "DisplayRotation": { + "displayText": "Obrót\nekranu", + "description": "Obrót ekranu (P: dla praworęcznych | L: dla leworęcznych | A: automatycznie)" + }, + "CooldownBlink": { + "displayText": "Mig. podczas\nschładzania", + "description": "Temperatura miga podczas schładzania, gdy grot jest wciąż gorący" + }, + "ScrollingSpeed": { + "displayText": "Sz. przew.\ntekstu", + "description": "Szybkość przewijania tekstu" + }, + "ReverseButtonTempChange": { + "displayText": "Zamień przyc.\n+ -", + "description": "Zamienia działanie przycisków zmiany temperatury grotu" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Prędkosć\nanimacji", + "description": "Prędkość animacji ikon w menu (W: mała | M: średnia | S: duża)" + }, + "AnimLoop": { + "displayText": "Zapętlona\nanimacja", + "description": "Zapętla animację ikon w menu głównym" + }, + "Brightness": { + "displayText": "Jasność\nwyświetlacza", + "description": "Regulacja kontrastu/jasności wyświetlacza OLED" + }, + "ColourInversion": { + "displayText": "Odwrócenie\nkolorów", + "description": "Odwrócenie kolorów wyświetlacza OLED" + }, + "LOGOTime": { + "displayText": "Długość wyś.\nloga", + "description": "Ustawia czas wyświetlania loga podczas uruchamiania (s=sekund)" + }, + "AdvancedIdle": { + "displayText": "Szczegółowy\nekran bezczyn.", + "description": "Wyświetla szczegółowe informacje za pomocą mniejszej czcionki na ekranie bezczynności" + }, + "AdvancedSoldering": { + "displayText": "Sz. inf. w\ntr. lutowania", + "description": "Wyświetl szczegółowe informacje w trybie lutowania" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Włącza Bluetooth Low Energy" + }, + "PowerLimit": { + "displayText": "Ogr.\nmocy", + "description": "Maksymalna moc (W), jakiej może użyć lutownica" + }, + "CalibrateCJC": { + "displayText": "Kalibracja temperatury\nprzy następnym uruchomieniu", + "description": "Kalibracja temperatury przy następnym włączeniu (nie jest wymagana, jeśli różnica temperatur jest mniejsza niż 5°C" + }, + "VoltageCalibration": { + "displayText": "Kalibracja\nnapięcia", + "description": "Kalibracja napięcia wejściowego. Krótkie naciśnięcie, aby ustawić, długie naciśnięcie, aby wyjść." + }, + "PowerPulsePower": { + "displayText": "Moc\nimpulsu", + "description": "W przypadku używania powerbanku, utrzymuj moc na poziomie (W) aby nie uśpić powerbanku" + }, + "PowerPulseWait": { + "displayText": "Czas między\nimp. mocy", + "description": "Czas między kolejnymi impulsami mocy zapobiegającymi usypianiu powerbanku (x2,5 s)" + }, + "PowerPulseDuration": { + "displayText": "Długość\nimpulsu mocy", + "description": "Długość impulsu mocy zapobiegającego usypianiu powerbanku (x250 ms)" + }, + "SettingsReset": { + "displayText": "Ustawienia\nfabryczne", + "description": "Resetuje wszystkie ustawienia" + }, + "LanguageSwitch": { + "displayText": "Język:\n PL Polski", + "description": "" + }, + "SolderingTipType": { + "displayText": "Typ grotu", + "description": "Wybierz typ zamontowanego grotu" } + } } diff --git a/Translations/translation_PT.json b/Translations/translation_PT.json index 65a85a47f..381ae84e0 100644 --- a/Translations/translation_PT.json +++ b/Translations/translation_PT.json @@ -1,319 +1,351 @@ { - "languageCode": "PT", - "languageLocalName": "Português", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibração\nefetuada!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Algumas configurações\nforam alteradas!" - }, - "NoAccelerometerMessage": { - "message": "Acelerómetro não\ndetetado!" - }, - "NoPowerDeliveryMessage": { - "message": "USB-PD IC não\ndetetado!" - }, - "LockingKeysString": { - "message": "Bloqueado" - }, - "UnlockingKeysString": { - "message": "Desbloqueado" - }, - "WarningKeysLockedString": { - "message": "!Bloqueado!" - }, - "WarningThermalRunaway": { - "message": "Thermal\nRunaway" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Antes de reiniciar certifique-se que o ferro está à temperatura ambiente!" - }, - "CJCCalibrating": { - "message": "calibrar\n" - }, - "SettingsResetWarning": { - "message": "Definições de fábrica?" - }, - "UVLOWarningString": { - "message": "DC BAIXO" - }, - "UndervoltageString": { - "message": "Subtensão\n" - }, - "InputVoltageString": { - "message": "Tensão: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Repouso...\n" - }, - "SleepingTipAdvancedString": { - "message": "Ponta: \n" - }, - "OffString": { - "message": "Off" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "O seu dispositivo provavelmente é falsificado!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "D", - "SettingLeftChar": "C", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "S", - "SettingMediumChar": "M", - "SettingFastChar": "F", - "SettingStartNoneChar": "D", - "SettingStartSolderingChar": "S", - "SettingStartSleepChar": "H", - "SettingStartSleepOffChar": "A", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Configurações de\nenergia", - "description": "" - }, - "SolderingMenu": { - "displayText": "Configurações\nSolda", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Modos\nRepouso", - "description": "" - }, - "UIMenu": { - "displayText": "Interface\nUtilizador", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Menu\nAvançado", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Fonte\nalimentação", - "description": "Fonte de alimentação. Define a tensão de corte. (DC=10V) (S=3.3V/célula)" - }, - "MinVolCell": { - "displayText": "Tensão\nmínima", - "description": "Tensão mínima permitida por célula de bateria (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "Potência\nFonte", - "description": "Potência da fonte usada (Watt)" - }, - "PDNegTimeout": { - "displayText": "PD tempo\nlimite", - "description": "Tempo limite de negoiciação de PD de 100ms para compatibilidade com alguns carregadores é (0: disabled)" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Activa o modo PPS & EPR" - }, - "BoostTemperature": { - "displayText": "Temp.\nModo turbo", - "description": "Ajuste de temperatura do \"modo turbo\"" - }, - "AutoStart": { - "displayText": "Aquecimento\nautomático", - "description": "Aquece a ponta automaticamente ao ligar (D=desligar | S=soldagem | H=hibernar | A=hibernar temp. ambiente)" - }, - "TempChangeShortStep": { - "displayText": "Mudança temp.\ncurta", - "description": "A temperatura será aumentada com um click curto" - }, - "TempChangeLongStep": { - "displayText": "Mudança temp.\nlonga", - "description": "A temperatura será aumentada com um click longo" - }, - "LockingMode": { - "displayText": "Permitir bloquear\nbotões", - "description": "Durante a solda premir os dois botões para alternar entre (D=desativados | B=modo turbo | F=bloqueio total)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Sensibilidade\nmovimento", - "description": "Sensibilidade ao movimento (0=Desligado | 1=Menor | ... | 9=Maior)" - }, - "SleepTemperature": { - "displayText": "Temperatura\nrepouso", - "description": "Temperatura de repouso (C)" - }, - "SleepTimeout": { - "displayText": "Tempo\nrepouso", - "description": "Tempo para repouso (Minutos | Segundos)" - }, - "ShutdownTimeout": { - "displayText": "Tempo\ndesligar", - "description": "Tempo para desligar (Minutos)" - }, - "HallEffSensitivity": { - "displayText": "Sensibilidade de\nmagnetismo", - "description": "Sensibilidade de magnetismo (0=Desligado | 1=Menor | ... | 9=Maior)" - }, - "TemperatureUnit": { - "displayText": "Unidade\ntemperatura", - "description": "Unidade de temperatura (C=Celsius | F=Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "Orientação\necrã", - "description": "Orientação do ecrã (D=estro | C=anhoto | A=utomática)" - }, - "CooldownBlink": { - "displayText": "Piscar ao\narrefecer", - "description": "Faz o valor da temperatura piscar durante o arrefecimento" - }, - "ScrollingSpeed": { - "displayText": "Velocidade\ntexto ajuda", - "description": "Velocidade a que o texto de ajuda é apresentado" - }, - "ReverseButtonTempChange": { - "displayText": "Trocar\nbotões + -", - "description": "Inverte o funcionamento dos botões de ajuste da temperatura" - }, - "AnimSpeed": { - "displayText": "Velocidade de\nanimação", - "description": "Velocidade das animações no menu (O=off | S=lenta | M=média | F=rápida)" - }, - "AnimLoop": { - "displayText": "Repetir\nanimações", - "description": "Repete animações de ícones no menu principal" - }, - "Brightness": { - "displayText": "Brilho\ndo ecrã", - "description": "Ajusta o brilho do ecrã OLED" - }, - "ColourInversion": { - "displayText": "Inverter\necrã", - "description": "Inverte as cores do ecrã OLED" - }, - "LOGOTime": { - "displayText": "Duração do\nlogo no arranque", - "description": "Define a duração do logotipo no arranque em (s=segundos)" - }, - "AdvancedIdle": { - "displayText": "Ecrã repouso\navançado", - "description": "Mostra informações avançadas quando em repouso" - }, - "AdvancedSoldering": { - "displayText": "Ecrã solda\navançado", - "description": "Mostra informações avançadas durante a solda" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Ativa o Bluetooth Low Energy (BLE)" - }, - "PowerLimit": { - "displayText": "Limite de\npotência", - "description": "Potência máxima a usar (W=watt)" - }, - "CalibrateCJC": { - "displayText": "Calibrar CJC\nno próximo arranque", - "description": "No próximo arranque CJC será calibrada (não será necessário caso o Delta T seja < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Calibrar\ntensão", - "description": "Calibra a tensão de alimentação. Use os botões para ajustar o valor. Mantenha pressionado para sair" - }, - "PowerPulsePower": { - "displayText": "Potência\ndo pulso", - "description": "Intensidade de potência de arranque (W=watt)" - }, - "PowerPulseWait": { - "displayText": "Espera do\npulso", - "description": "Espera entre o acordar e o envio da rectivação (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Duração\npulso", - "description": "Manter os inplosus de rectivação em (x 250ms)" - }, - "SettingsReset": { - "displayText": "Reset de\nfábrica?", - "description": "Repôe todos os ajustes" - }, - "LanguageSwitch": { - "displayText": "Idioma:\n PT Português", - "description": "" - } + "languageCode": "PT", + "languageLocalName": "Português", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibração\nfeita!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Algumas configurações\nforam alteradas!" + }, + "NoAccelerometerMessage": { + "message": "Acelerómetro não\ndetetado!" + }, + "NoPowerDeliveryMessage": { + "message": "USB-PD IC não\ndetetado!" + }, + "LockingKeysString": { + "message": "Bloqueado" + }, + "UnlockingKeysString": { + "message": "Desbloqueado" + }, + "WarningKeysLockedString": { + "message": "!Bloqueado!" + }, + "WarningThermalRunaway": { + "message": "Avalanche\nTérmica" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Antes de reiniciar certifique-se que o ferro está à temperatura ambiente!" + }, + "CJCCalibrating": { + "message": "a calibrar\n" + }, + "SettingsResetWarning": { + "message": "Definições de fábrica?" + }, + "UVLOWarningString": { + "message": "DC BAIXO" + }, + "UndervoltageString": { + "message": "Subtensão\n" + }, + "InputVoltageString": { + "message": "Tensão: \n" + }, + "SleepingAdvancedString": { + "message": "Repouso...\n" + }, + "SleepingTipAdvancedString": { + "message": "Ponta: \n" + }, + "ProfilePreheatString": { + "message": "Pré-Aquecer\n" + }, + "ProfileCooldownString": { + "message": "Arrefecer\n" + }, + "DeviceFailedValidationWarning": { + "message": "O seu dispositivo provavelmente é falsificado!" + }, + "TooHotToStartProfileWarning": { + "message": "Demasiado quente para\niniciar perfil" + } + }, + "characters": { + "SettingRightChar": "D", + "SettingLeftChar": "C", + "SettingAutoChar": "A", + "SettingSlowChar": "S", + "SettingMediumChar": "M", + "SettingFastChar": "F", + "SettingStartSolderingChar": "S", + "SettingStartSleepChar": "H", + "SettingStartSleepOffChar": "A", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Opções de\nEnergia", + "description": "" + }, + "SolderingMenu": { + "displayText": "Opções de\nSolda", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Modo de\nRepouso", + "description": "" + }, + "UIMenu": { + "displayText": "Interface\nUtilizador", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Opções\nAvançadas", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Fonte\nalimentação", + "description": "Fonte de alimentação. Define a tensão de corte. (DC=10V) (S=3.3V/célula)" + }, + "MinVolCell": { + "displayText": "Tensão\nmínima", + "description": "Tensão mínima permitida por célula de bateria (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "Potência\nFonte", + "description": "Potência da fonte usada (Watt)" + }, + "PDNegTimeout": { + "displayText": "PD tempo\nlimite", + "description": "Tempo limite de negoiciação de PD de 100ms para compatibilidade com alguns carregadores é (0: disabled)" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "Activa o modo PPS & EPR" + }, + "BoostTemperature": { + "displayText": "Temp.\nModo Turbo", + "description": "Ajuste de temperatura do \"modo turbo\"" + }, + "AutoStart": { + "displayText": "Aquecimento\nautomático", + "description": "Aquece a ponta automaticamente ao ligar (S=soldagem | H=hibernar | A=hibernar temp. ambiente)" + }, + "TempChangeShortStep": { + "displayText": "Mudança temp.\ncurta", + "description": "A temperatura será aumentada com um click curto" + }, + "TempChangeLongStep": { + "displayText": "Mudança temp.\nlonga", + "description": "A temperatura será aumentada com um click longo" + }, + "LockingMode": { + "displayText": "Permitir bloq.\nbotões", + "description": "Durante a solda premir os dois botões para alternar entre (B=modo turbo | F=bloqueio total)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Temperatura\nPré-aquecimento", + "description": "Pré-aquecer a esta temperatura quando o perfil é selecionado" + }, + "ProfilePreheatSpeed": { + "displayText": "Velocidade\nPré-aquecimento", + "description": "Ritmo de pré-aquecimento (graus por segundo)" + }, + "ProfilePhase1Temp": { + "displayText": "Temp.\nFase 1", + "description": "Temperatura alvo no final desta fase" + }, + "ProfilePhase1Duration": { + "displayText": "Duração\nFase 1", + "description": "Duração alvo desta fase (segundos)" + }, + "ProfilePhase2Temp": { + "displayText": "Temp.\nFase 2", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Duração\nFase 2", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Temp.\nFase 3", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Duração\nFase 3", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Temp.\nFase 4", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Duração\nFase 4", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Temp.\nFase 5", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Duração\nFase 5", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Velocidade\nArrefecimento", + "description": "Arrefecer a este ritmo após sair do perfil selecionado (graus por segundo)" + }, + "MotionSensitivity": { + "displayText": "Sensibilidade\nmovimento", + "description": "Sensibilidade ao movimento (1=Menor | ... | 9=Maior)" + }, + "SleepTemperature": { + "displayText": "Temperatura\nrepouso", + "description": "Temperatura de repouso (C)" + }, + "SleepTimeout": { + "displayText": "Tempo\nrepouso", + "description": "Tempo para repouso (Minutos | Segundos)" + }, + "ShutdownTimeout": { + "displayText": "Tempo\ndesligar", + "description": "Tempo para desligar (Minutos)" + }, + "HallEffSensitivity": { + "displayText": "Sensibilidade de\nmagnetismo", + "description": "Sensibilidade de magnetismo (1=Menor | ... | 9=Maior)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Intervalo antes do início do \"modo de suspensão\" quando o efeito Hall está acima do limite" + }, + "TemperatureUnit": { + "displayText": "Unidade\ntemperatura", + "description": "Unidade de temperatura (C=Celsius | F=Fahrenheit)" + }, + "DisplayRotation": { + "displayText": "Orientação\necrã", + "description": "Orientação do ecrã (D=estro | C=anhoto | A=utomática)" + }, + "CooldownBlink": { + "displayText": "Piscar ao\narrefecer", + "description": "Faz o valor da temperatura piscar durante o arrefecimento" + }, + "ScrollingSpeed": { + "displayText": "Velocidade\ntexto ajuda", + "description": "Velocidade a que o texto de ajuda é apresentado" + }, + "ReverseButtonTempChange": { + "displayText": "Trocar\nbotões + -", + "description": "Inverte o funcionamento dos botões de ajuste da temperatura" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Velocidade\nde animação", + "description": "Velocidade das animações no menu (S=lenta | M=média | F=rápida)" + }, + "AnimLoop": { + "displayText": "Repetir\nanimações", + "description": "Repete animações de ícones no menu principal" + }, + "Brightness": { + "displayText": "Brilho\ndo ecrã", + "description": "Ajusta o brilho do ecrã OLED" + }, + "ColourInversion": { + "displayText": "Inverter\necrã", + "description": "Inverte as cores do ecrã OLED" + }, + "LOGOTime": { + "displayText": "Tempo img.\nno arranque", + "description": "Define a duração do logotipo no arranque em (s=segundos)" + }, + "AdvancedIdle": { + "displayText": "Ecrã repouso\navançado", + "description": "Mostra informações avançadas quando em repouso" + }, + "AdvancedSoldering": { + "displayText": "Ecrã solda\navançado", + "description": "Mostra informações avançadas durante a solda" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Ativa o Bluetooth Low Energy (BLE)" + }, + "PowerLimit": { + "displayText": "Limite\npotência", + "description": "Potência máxima a usar (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Calibrar CJC\nno próximo arranque", + "description": "No próximo arranque CJC será calibrada (não será necessário caso o Delta T seja < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Calibrar\ntensão", + "description": "Calibra a tensão de alimentação. Use os botões para ajustar o valor. Mantenha pressionado para sair" + }, + "PowerPulsePower": { + "displayText": "Potência\ndo pulso", + "description": "Intensidade de potência de arranque (W=watt)" + }, + "PowerPulseWait": { + "displayText": "Espera do\npulso", + "description": "Espera entre o acordar e o envio da rectivação (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Duração\npulso", + "description": "Manter os inplosus de rectivação em (x 250ms)" + }, + "SettingsReset": { + "displayText": "Reset de\nfábrica?", + "description": "Repôe todos os ajustes" + }, + "LanguageSwitch": { + "displayText": "Idioma:\n PT Português", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_RO.json b/Translations/translation_RO.json index 0d03d0bc4..75a269dd6 100644 --- a/Translations/translation_RO.json +++ b/Translations/translation_RO.json @@ -1,319 +1,351 @@ { - "languageCode": "RO", - "languageLocalName": "Română", - "tempUnitFahrenheit": true, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Setările au fost\nresetate!" - }, - "NoAccelerometerMessage": { - "message": "Fără accelerometru\ndetectat!" - }, - "NoPowerDeliveryMessage": { - "message": "Fără USB-PD IC\ndetectat!" - }, - "LockingKeysString": { - "message": "BLOCAT" - }, - "UnlockingKeysString": { - "message": "DEBLOCAT" - }, - "WarningKeysLockedString": { - "message": "!BLOCAT!" - }, - "WarningThermalRunaway": { - "message": "Încălzire\nEşuată" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Înainte de repornire, asiguraţi-vă că vârful şi mânerul sunt la temperatura camerei!" - }, - "CJCCalibrating": { - "message": "calibrare\n" - }, - "SettingsResetWarning": { - "message": "Sigur doriţi să restauraţi la setările implicite?" - }, - "UVLOWarningString": { - "message": "DC SCĂZUT" - }, - "UndervoltageString": { - "message": "Voltaj scăzut\n" - }, - "InputVoltageString": { - "message": "Intrare V: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Adormit...\n" - }, - "SleepingTipAdvancedString": { - "message": "Tip: \n" - }, - "OffString": { - "message": "Nu" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Dispozitivul dvs. este cel mai probabil un fals!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "D", - "SettingLeftChar": "S", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "Î", - "SettingMediumChar": "M", - "SettingFastChar": "R", - "SettingStartNoneChar": "O", - "SettingStartSolderingChar": "S", - "SettingStartSleepChar": "Z", - "SettingStartSleepOffChar": "R", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Setări de\nalimentare", - "description": "" - }, - "SolderingMenu": { - "displayText": "Setări de\nlipire", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Modul\nrepaus", - "description": "" - }, - "UIMenu": { - "displayText": "Interfaţă\nutilizator", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Opţiuni\navansate", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Sursa de\nalimentare", - "description": "Sursa de alimentare. Setează tensiunea de întrerupere. (DC 10V) (S 3.3V per celulă, dezactivaţi limita de alimentare)" - }, - "MinVolCell": { - "displayText": "Voltaj\nminim", - "description": "Tensiunea minimă admisă pe celulă (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "QC\nvoltaj", - "description": "Tensiunea maximă QC dorită pentru care negociază letconul" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "Timp limită de negociere pentru tranzacţia PD, în paşi de 100ms, pentru compatibilitate cu alimentatoarele QC" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Modifică\ntemp. impuls", - "description": "Temperatura utilizată în \"modul de impuls\"" - }, - "AutoStart": { - "displayText": "Auto\nstart", - "description": "Start letcon în modul de lipire la pornire (O=oprit | S=lipire | Z=repaus | R=repaus la temperatura camerei)" - }, - "TempChangeShortStep": { - "displayText": "Schimbare temp.\napăsare scută", - "description": "Schimbarea temperaturii la apăsarea scurtă a butonului" - }, - "TempChangeLongStep": { - "displayText": "Schimbare temp.\napăsare lungă", - "description": "Schimbarea temperaturii la apăsarea lungă a butonului" - }, - "LockingMode": { - "displayText": "Blocare\nbutoane", - "description": "Când lipiţi, apăsaţi lung ambele butoane, pentru a le bloca (D=dezactivare | B=numai \"modul boost\" | F=blocare completă)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Sensibilitate\nla miscare", - "description": "Sensibilitate senzor miscare (0=oprit | 1=puţin sensibil | ... | 9=cel mai sensibil)" - }, - "SleepTemperature": { - "displayText": "Temp\nrepaus", - "description": "Temperatura vârfului în \"modul repaus\"" - }, - "SleepTimeout": { - "displayText": "Expirare\nrepaus", - "description": "Interval înainte de lansarea \"modului de repaus\" în (s=secunde | m=minute)" - }, - "ShutdownTimeout": { - "displayText": "Expirare\noprire", - "description": "Interval înainte ca letconul să se oprească (m=minute)" - }, - "HallEffSensitivity": { - "displayText": "Sensibilitate\nsenzor Hall", - "description": "Sensibilitate senzor cu efect Hall pentru a detecta repausul (0=oprit | 1=putin sensibil | ... | 9=cel mai sensibil)" - }, - "TemperatureUnit": { - "displayText": "Unitate de\ntemperatură", - "description": "C=Celsius | F=Fahrenheit" - }, - "DisplayRotation": { - "displayText": "Orientare\necran", - "description": "R=dreptaci | L=stângaci | A=auto" - }, - "CooldownBlink": { - "displayText": "Clipeşte\nla răcire", - "description": "Clipeşte temperatura după oprirea încălzirii, în timp ce vârful este încă fierbinte" - }, - "ScrollingSpeed": { - "displayText": "Viteză\nderulare", - "description": "Viteză derulare text cu informatii la (S=lent | F=rapid)" - }, - "ReverseButtonTempChange": { - "displayText": "Inversare\n+ - butoane", - "description": "Inversarea butoanelor de reglare a temperaturii" - }, - "AnimSpeed": { - "displayText": "Animaţii\nviteză", - "description": "Ritmul animaţiilor pictogramei din meniu (O=oprit | Î=încet | M=mediu | R=rapid)" - }, - "AnimLoop": { - "displayText": "Animaţii\nbuclă", - "description": "Animaţii de pictograme în meniul principal" - }, - "Brightness": { - "displayText": "Ecranului\nluminozitatea", - "description": "Ajusteaza luminozitatea ecranului" - }, - "ColourInversion": { - "displayText": "Inversează\nculoarea", - "description": "Inversează culoarea ecranului" - }, - "LOGOTime": { - "displayText": "Durată\nlogo încărcare", - "description": "Setaţi durată logo de pornire (s=secunde)" - }, - "AdvancedIdle": { - "displayText": "Detalii,\necran inactiv", - "description": "Afisaţi informaţii detaliate într-un font mai mic pe ecranul de repaus" - }, - "AdvancedSoldering": { - "displayText": "Detalii\necran lipire", - "description": "Afisaţi informaţii detaliate într-un font mai mic pe ecranul de lipire" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Activează BLE" - }, - "PowerLimit": { - "displayText": "Putere\nlimită", - "description": "Puterea maximă pe care letconul o poate folosi (W=watt)" - }, - "CalibrateCJC": { - "displayText": "Calibrare CJC\nla următoarea pornire", - "description": "La următorul vârf de pornire, compensarea joncţiunii reci va fi calibrată (nu este necesară dacă Delta T este < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Calibrare tens.\nde intrare?", - "description": "Porniţi calibrarea VIN (apăsaţi lung pentru a ieşi)" - }, - "PowerPulsePower": { - "displayText": "Putere\npuls", - "description": "Puterea pulsului de menţinere activă a blocului de alimentare (watt)" - }, - "PowerPulseWait": { - "displayText": "Întârziere\npuls putere", - "description": "Perioada pulsului de mentinere (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Durată\npuls putere", - "description": "Durata pulsului de menţinere (x 250ms)" - }, - "SettingsReset": { - "displayText": "Setări\ndin fabrică", - "description": "Reveniţi la setările din fabrică" - }, - "LanguageSwitch": { - "displayText": "Limbă:\n RO Română", - "description": "" - } + "languageCode": "RO", + "languageLocalName": "Română", + "tempUnitFahrenheit": true, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibration\ndone!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Setările au fost\nresetate!" + }, + "NoAccelerometerMessage": { + "message": "Fără accelerometru\ndetectat!" + }, + "NoPowerDeliveryMessage": { + "message": "Fără USB-PD IC\ndetectat!" + }, + "LockingKeysString": { + "message": "BLOCAT" + }, + "UnlockingKeysString": { + "message": "DEBLOCAT" + }, + "WarningKeysLockedString": { + "message": "!BLOCAT!" + }, + "WarningThermalRunaway": { + "message": "Încălzire\nEşuată" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Înainte de repornire, asiguraţi-vă că vârful şi mânerul sunt la temperatura camerei!" + }, + "CJCCalibrating": { + "message": "calibrare\n" + }, + "SettingsResetWarning": { + "message": "Sigur doriţi să restauraţi la setările implicite?" + }, + "UVLOWarningString": { + "message": "DC SCĂZUT" + }, + "UndervoltageString": { + "message": "Voltaj scăzut\n" + }, + "InputVoltageString": { + "message": "Intrare V: \n" + }, + "SleepingAdvancedString": { + "message": "Adormit...\n" + }, + "SleepingTipAdvancedString": { + "message": "Tip: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Dispozitivul dvs. este cel mai probabil un fals!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "D", + "SettingLeftChar": "S", + "SettingAutoChar": "A", + "SettingSlowChar": "Î", + "SettingMediumChar": "M", + "SettingFastChar": "R", + "SettingStartSolderingChar": "S", + "SettingStartSleepChar": "Z", + "SettingStartSleepOffChar": "R", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Setări de\nalimentare", + "description": "" + }, + "SolderingMenu": { + "displayText": "Setări de\nlipire", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Modul\nrepaus", + "description": "" + }, + "UIMenu": { + "displayText": "Interfaţă\nutilizator", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Opţiuni\navansate", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Sursa de\nalimentare", + "description": "Sursa de alimentare. Setează tensiunea de întrerupere. (DC 10V) (S 3.3V per celulă, dezactivaţi limita de alimentare)" + }, + "MinVolCell": { + "displayText": "Voltaj\nminim", + "description": "Tensiunea minimă admisă pe celulă (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\nvoltaj", + "description": "Tensiunea maximă QC dorită pentru care negociază letconul" + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "Timp limită de negociere pentru tranzacţia PD, în paşi de 100ms, pentru compatibilitate cu alimentatoarele QC" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Modifică\ntemp. impuls", + "description": "Temperatura utilizată în \"modul de impuls\"" + }, + "AutoStart": { + "displayText": "Auto\nstart", + "description": "Start letcon în modul de lipire la pornire (S=lipire | Z=repaus | R=repaus la temperatura camerei)" + }, + "TempChangeShortStep": { + "displayText": "Schimbare temp.\napăsare scută", + "description": "Schimbarea temperaturii la apăsarea scurtă a butonului" + }, + "TempChangeLongStep": { + "displayText": "Schimbare temp.\napăsare lungă", + "description": "Schimbarea temperaturii la apăsarea lungă a butonului" + }, + "LockingMode": { + "displayText": "Blocare\nbutoane", + "description": "Când lipiţi, apăsaţi lung ambele butoane, pentru a le bloca (B=numai \"modul boost\" | F=blocare completă)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Sensibilitate\nla miscare", + "description": "Sensibilitate senzor miscare (1=puţin sensibil | ... | 9=cel mai sensibil)" + }, + "SleepTemperature": { + "displayText": "Temp\nrepaus", + "description": "Temperatura vârfului în \"modul repaus\"" + }, + "SleepTimeout": { + "displayText": "Expirare\nrepaus", + "description": "Interval înainte de lansarea \"modului de repaus\" în (s=secunde | m=minute)" + }, + "ShutdownTimeout": { + "displayText": "Expirare\noprire", + "description": "Interval înainte ca letconul să se oprească (m=minute)" + }, + "HallEffSensitivity": { + "displayText": "Sensibilitate\nsenzor Hall", + "description": "Sensibilitate senzor cu efect Hall pentru a detecta repausul (1=putin sensibil | ... | 9=cel mai sensibil)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Intervalul înainte de începerea \"modului de repaus\" când efectul de sală este peste prag" + }, + "TemperatureUnit": { + "displayText": "Unitate de\ntemperatură", + "description": "C=Celsius | F=Fahrenheit" + }, + "DisplayRotation": { + "displayText": "Orientare\necran", + "description": "R=dreptaci | L=stângaci | A=auto" + }, + "CooldownBlink": { + "displayText": "Clipeşte\nla răcire", + "description": "Clipeşte temperatura după oprirea încălzirii, în timp ce vârful este încă fierbinte" + }, + "ScrollingSpeed": { + "displayText": "Viteză\nderulare", + "description": "Viteză derulare text cu informatii la (S=lent | F=rapid)" + }, + "ReverseButtonTempChange": { + "displayText": "Inversare\n+ - butoane", + "description": "Inversarea butoanelor de reglare a temperaturii" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Animaţii\nviteză", + "description": "Ritmul animaţiilor pictogramei din meniu (Î=încet | M=mediu | R=rapid)" + }, + "AnimLoop": { + "displayText": "Animaţii\nbuclă", + "description": "Animaţii de pictograme în meniul principal" + }, + "Brightness": { + "displayText": "Ecranului\nluminozitatea", + "description": "Ajusteaza luminozitatea ecranului" + }, + "ColourInversion": { + "displayText": "Inversează\nculoarea", + "description": "Inversează culoarea ecranului" + }, + "LOGOTime": { + "displayText": "Durată\nlogo încărcare", + "description": "Setaţi durată logo de pornire (s=secunde)" + }, + "AdvancedIdle": { + "displayText": "Detalii,\necran inactiv", + "description": "Afisaţi informaţii detaliate într-un font mai mic pe ecranul de repaus" + }, + "AdvancedSoldering": { + "displayText": "Detalii\necran lipire", + "description": "Afisaţi informaţii detaliate într-un font mai mic pe ecranul de lipire" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Activează BLE" + }, + "PowerLimit": { + "displayText": "Putere\nlimită", + "description": "Puterea maximă pe care letconul o poate folosi (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Calibrare CJC\nla următoarea pornire", + "description": "La următorul vârf de pornire, compensarea joncţiunii reci va fi calibrată (nu este necesară dacă Delta T este < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Calibrare tens.\nde intrare?", + "description": "Porniţi calibrarea VIN (apăsaţi lung pentru a ieşi)" + }, + "PowerPulsePower": { + "displayText": "Putere\npuls", + "description": "Puterea pulsului de menţinere activă a blocului de alimentare (watt)" + }, + "PowerPulseWait": { + "displayText": "Întârziere\npuls putere", + "description": "Perioada pulsului de mentinere (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Durată\npuls putere", + "description": "Durata pulsului de menţinere (x 250ms)" + }, + "SettingsReset": { + "displayText": "Setări\ndin fabrică", + "description": "Reveniţi la setările din fabrică" + }, + "LanguageSwitch": { + "displayText": "Limbă:\n RO Română", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_RU.json b/Translations/translation_RU.json index ccd066caf..f47383de5 100644 --- a/Translations/translation_RU.json +++ b/Translations/translation_RU.json @@ -1,319 +1,351 @@ { - "languageCode": "RU", - "languageLocalName": "Русский", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Калибровка\nзавершена!" - }, - "ResetOKMessage": { - "message": "Готово!" - }, - "SettingsResetMessage": { - "message": "Настройки\nсброшены!" - }, - "NoAccelerometerMessage": { - "message": "Акселерометр\nне обнаружен!" - }, - "NoPowerDeliveryMessage": { - "message": "Питание по USB-PD\nне обнаружено" - }, - "LockingKeysString": { - "message": "ЗАБЛОК" - }, - "UnlockingKeysString": { - "message": "РАЗБЛОК" - }, - "WarningKeysLockedString": { - "message": "!ЗАБЛОК!" - }, - "WarningThermalRunaway": { - "message": "Неуправляемый\nразогрев" - }, - "WarningTipShorted": { - "message": "!КЗ на жале!" - }, - "SettingsCalibrationWarning": { - "message": "Пожалуйста, убедитесь, что жало и корпус имеют комнатную температуру при следующей загрузке!" - }, - "CJCCalibrating": { - "message": "калибровка\n" - }, - "SettingsResetWarning": { - "message": "Вы уверены, что хотите сбросить настройки к значениям по умолчанию?" - }, - "UVLOWarningString": { - "message": "НИЗ.НАПР" - }, - "UndervoltageString": { - "message": "Низ. напряжение\n" - }, - "InputVoltageString": { - "message": "Питание(В):\n" - }, - "SleepingSimpleString": { - "message": "Хххррп" - }, - "SleepingAdvancedString": { - "message": "Сон...\n" - }, - "SleepingTipAdvancedString": { - "message": "Жало: \n" - }, - "OffString": { - "message": "Выкл" - }, - "ProfilePreheatString": { - "message": "Преднагрев\n" - }, - "ProfileCooldownString": { - "message": "Остывание\n" - }, - "DeviceFailedValidationWarning": { - "message": "Вероятно, это поддельное устройство!" - }, - "TooHotToStartProfileWarning": { - "message": "Слишком горячо для\nстарта профиля" - } - }, - "characters": { - "SettingRightChar": "П", - "SettingLeftChar": "Л", - "SettingAutoChar": "А", - "SettingOffChar": "О", - "SettingSlowChar": "М", - "SettingMediumChar": "С", - "SettingFastChar": "Б", - "SettingStartNoneChar": "О", - "SettingStartSolderingChar": "П", - "SettingStartSleepChar": "С", - "SettingStartSleepOffChar": "К", - "SettingLockDisableChar": "О", - "SettingLockBoostChar": "Т", - "SettingLockFullChar": "П" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Настройки\nпитания", - "description": "" - }, - "SolderingMenu": { - "displayText": "Настройки\nпайки", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Авто\nвыключение", - "description": "" - }, - "UIMenu": { - "displayText": "Интерфейс\n", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Доп.\nнастройки", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Предельное\nнапряжение", - "description": "Установка минимально предельного напряжения от аккумулятора для предотвращения глубокого разряда (DC 10В | S 3,3В на ячейку, без ограничения мощности)" - }, - "MinVolCell": { - "displayText": "Мин.\nнапряжение", - "description": "Минимально разрешённое напряжение на ячейку (3S: 3 - 3,7В | 4S-6S: 2,4 - 3,7В)" - }, - "QCMaxVoltage": { - "displayText": "Напр-е\nдля QC", - "description": "Максимальное напряжение для согласования с источником питания по QC" - }, - "PDNegTimeout": { - "displayText": "PD\nинтервал", - "description": "Интервал согласования питания по Power Delivery с шагом 100 мс для совместимости с некоторыми источниками питания по QC (0=Откл.)" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Включить режимы PPS & EPR" - }, - "BoostTemperature": { - "displayText": "t° турбо\nрежима", - "description": "Температура жала в турбо-режиме" - }, - "AutoStart": { - "displayText": "Режим при\nвключении", - "description": "Режим, в котором включается паяльник (О=Откл. | П=Пайка | С=Сон | К=Ожидание при комн. темп.)" - }, - "TempChangeShortStep": { - "displayText": "Шаг t° при\nкор.наж-ии", - "description": "Шаг изменения температуры при коротком нажатии кнопок" - }, - "TempChangeLongStep": { - "displayText": "Шаг t° при\nдол.наж-ии", - "description": "Шаг изменения температуры при долгом нажатии кнопок" - }, - "LockingMode": { - "displayText": "Разрешить\nблок. кнопок", - "description": "Блокировать кнопки при их долгом нажатии в режиме пайки (О=Откл. | Т=Только турбо | П=Полная блокировка)" - }, - "ProfilePhases": { - "displayText": "Этапы\nпрофиля", - "description": "Количество этапов в режиме профиля" - }, - "ProfilePreheatTemp": { - "displayText": "Температура\nпреднагрева", - "description": "Температура предварительного нагрева в начале режима термопрофиля" - }, - "ProfilePreheatSpeed": { - "displayText": "Скорость\nпреднагрева", - "description": "Скорость предварительного нагрева в начале режима термопрофиля (в градусах в секунду)" - }, - "ProfilePhase1Temp": { - "displayText": "Температура\n1-го этапа", - "description": "Необходимая температура в конце 1-го этапа" - }, - "ProfilePhase1Duration": { - "displayText": "Длительность\n1-го этапа", - "description": "Необходимая длительность 1-го этапа (в секундах)" - }, - "ProfilePhase2Temp": { - "displayText": "Температура\n2-го этапа", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Длительность\n2-го этапа", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Температура\n3-го этапа", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Длительность\n3-го этапа", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Температура\n4-го этапа", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Длительность\n4-го этапа", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Температура\n5-го этапа", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Длительность\n5-го этапа", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Скорость\nостывания", - "description": "Скорость остывания в конце режима термопрофиля (в градусах в секунду)" - }, - "MotionSensitivity": { - "displayText": "Чувствительн.\nакселерометра", - "description": "Чувствительность акселерометра (0=Откл. | 1=мин. | ... | 9=макс.)" - }, - "SleepTemperature": { - "displayText": "t° при\nсне", - "description": "Температура жала в режиме сна" - }, - "SleepTimeout": { - "displayText": "Интервал\nсна", - "description": "Время до перехода в режим сна (секунды | минуты)" - }, - "ShutdownTimeout": { - "displayText": "Интервал\nотключ-я", - "description": "Время до выключения паяльника (в минутах)" - }, - "HallEffSensitivity": { - "displayText": "Датчик\nХолла", - "description": "Чувствительность датчика Холла к магнитному полю (0=Откл. | 1=мин. | ... | 9=макс.)" - }, - "TemperatureUnit": { - "displayText": "Единицы\nизмерения", - "description": "Единицы измерения температуры (C=°Цельcия | F=°Фаренгейта)" - }, - "DisplayRotation": { - "displayText": "Поворот\nэкрана", - "description": "Поворот экрана (П=Правша | Л=Левша | А=Авто)" - }, - "CooldownBlink": { - "displayText": "Мигание t°\nпри остывании", - "description": "Мигать температурой на экране при остывании, пока жало ещё горячее" - }, - "ScrollingSpeed": { - "displayText": "Скорость\nтекста", - "description": "Скорость прокрутки текста (М=Медленная | Б=Быстрая)" - }, - "ReverseButtonTempChange": { - "displayText": "Поменять\nкнопки +/-", - "description": "Поменять кнопки изменения температуры" - }, - "AnimSpeed": { - "displayText": "Скорость\nанимации", - "description": "Скорость анимации иконок в главном меню (О=Откл. | М=Медленная| С=Средняя | Б=Быстрая)" - }, - "AnimLoop": { - "displayText": "Зацикленная\nанимация", - "description": "Зацикленная анимация иконок в главном меню" - }, - "Brightness": { - "displayText": "Яркость\nэкрана", - "description": "Уровень яркости пикселей на экране" - }, - "ColourInversion": { - "displayText": "Инверсия\nэкрана", - "description": "Инвертировать пиксели на экране" - }, - "LOGOTime": { - "displayText": "Длит-ть\nлоготипа", - "description": "Длительность отображения логотипа (в секундах)" - }, - "AdvancedIdle": { - "displayText": "Подробный\nэкран ожидания", - "description": "Показывать дополнительную информацию на экране ожидания уменьшенным шрифтом" - }, - "AdvancedSoldering": { - "displayText": "Подробный\nэкран пайки", - "description": "Показывать дополнительную информацию на экране пайки уменьшенным шрифтом" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Включить BLE" - }, - "PowerLimit": { - "displayText": "Предел\nмощ-ти", - "description": "Максимальная мощность, которую может использовать паяльник (в ваттах)" - }, - "CalibrateCJC": { - "displayText": "Калибровка\nтемпературы", - "description": "Калибровка температуры (CJC) при следующем включении (не требуется при разнице менее 5°C)" - }, - "VoltageCalibration": { - "displayText": "Калибровка\nнапряжения", - "description": "Калибровка входного напряжения (долгое нажатие для выхода)" - }, - "PowerPulsePower": { - "displayText": "Сила имп.\nпитания", - "description": "Сила импульса, удерживающего от автовыключения источник питания (в ваттах)" - }, - "PowerPulseWait": { - "displayText": "Пауза имп.\nпитания (К)", - "description": "Коэффициент паузы между импульсами, удерживающими от автовыключения источник питания (К x 2,5 с)" - }, - "PowerPulseDuration": { - "displayText": "Длина имп.\nпитания (К)", - "description": "Коэффициент длины импульса, удерживающего от автовыключения источник питания (К x 250 мс)" - }, - "SettingsReset": { - "displayText": "Сброс\nнастроек", - "description": "Сброс настроек к значениям по умолчанию" - }, - "LanguageSwitch": { - "displayText": "Язык:\n RU Русский", - "description": "" - } + "languageCode": "RU", + "languageLocalName": "Русский", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Калибровка\nзавершена!" + }, + "ResetOKMessage": { + "message": "Готово!" + }, + "SettingsResetMessage": { + "message": "Настройки\nсброшены!" + }, + "NoAccelerometerMessage": { + "message": "Акселерометр\nне обнаружен!" + }, + "NoPowerDeliveryMessage": { + "message": "Питание по USB-PD\nне обнаружено" + }, + "LockingKeysString": { + "message": "ЗАБЛОК" + }, + "UnlockingKeysString": { + "message": "РАЗБЛОК" + }, + "WarningKeysLockedString": { + "message": "!ЗАБЛОК!" + }, + "WarningThermalRunaway": { + "message": "Неуправляемый\nразогрев" + }, + "WarningTipShorted": { + "message": "!КЗ на жале!" + }, + "SettingsCalibrationWarning": { + "message": "Пожалуйста, убедитесь, что жало и корпус имеют комнатную температуру при следующей загрузке!" + }, + "CJCCalibrating": { + "message": "калибровка\n" + }, + "SettingsResetWarning": { + "message": "Вы уверены, что хотите сбросить настройки к значениям по умолчанию?" + }, + "UVLOWarningString": { + "message": "НИЗ.НАПР" + }, + "UndervoltageString": { + "message": "Низ. напряжение\n" + }, + "InputVoltageString": { + "message": "Питание(В):\n" + }, + "SleepingAdvancedString": { + "message": "Сон...\n" + }, + "SleepingTipAdvancedString": { + "message": "Жало: \n" + }, + "ProfilePreheatString": { + "message": "Преднагрев\n" + }, + "ProfileCooldownString": { + "message": "Остывание\n" + }, + "DeviceFailedValidationWarning": { + "message": "Вероятно, это поддельное устройство!" + }, + "TooHotToStartProfileWarning": { + "message": "Слишком горячо для\nстарта профиля" + } + }, + "characters": { + "SettingRightChar": "П", + "SettingLeftChar": "Л", + "SettingAutoChar": "А", + "SettingSlowChar": "М", + "SettingMediumChar": "С", + "SettingFastChar": "Б", + "SettingStartSolderingChar": "П", + "SettingStartSleepChar": "С", + "SettingStartSleepOffChar": "К", + "SettingLockBoostChar": "Т", + "SettingLockFullChar": "П" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Настройки\nпитания", + "description": "" + }, + "SolderingMenu": { + "displayText": "Настройки\nпайки", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Авто\nвыключение", + "description": "" + }, + "UIMenu": { + "displayText": "Интерфейс\n", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Доп.\nнастройки", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Вкл.\nPPSиEPR" + }, + "USBPDModeNoDynamic": { + "displayText": "Откл.\n" + }, + "USBPDModeSafe": { + "displayText": "Вкл.без\nзапроса" + }, + "TipTypeAuto": { + "displayText": "Авто\nопред-е" + }, + "TipTypeT12Long": { + "displayText": "TS100\nстанд." + }, + "TipTypeT12Short": { + "displayText": "Pine\nкоротк." + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80(P)\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Предельное\nнапряжение", + "description": "Установка минимально предельного напряжения от аккумулятора для предотвращения глубокого разряда (DC 10В | S 3,3В на ячейку, без ограничения мощности)" + }, + "MinVolCell": { + "displayText": "Мин.\nнапряжение", + "description": "Минимально разрешённое напряжение на ячейку (3S: 3 - 3,7В | 4S-6S: 2,4 - 3,7В)" + }, + "QCMaxVoltage": { + "displayText": "Напр-е\nдля QC", + "description": "Максимальное напряжение для согласования с источником питания по QC" + }, + "PDNegTimeout": { + "displayText": "Интервал\nPD", + "description": "Интервал согласования питания по Power Delivery с шагом 100 мс для совместимости с некоторыми источниками питания по QC (0=Откл.)" + }, + "USBPDMode": { + "displayText": "Режим\nPD", + "description": "Вкл.без запроса: включить PPS и EPR без запроса большей мощности" + }, + "BoostTemperature": { + "displayText": "t° турбо\nрежима", + "description": "Температура жала в турбо-режиме" + }, + "AutoStart": { + "displayText": "Режим при\nвключении", + "description": "Режим, в котором включается паяльник (П=Пайка | С=Сон | К=Ожидание при комн. темп.)" + }, + "TempChangeShortStep": { + "displayText": "Шаг t° при\nкор.наж-ии", + "description": "Шаг изменения температуры при коротком нажатии кнопок" + }, + "TempChangeLongStep": { + "displayText": "Шаг t° при\nдол.наж-ии", + "description": "Шаг изменения температуры при долгом нажатии кнопок" + }, + "LockingMode": { + "displayText": "Разрешить\nблок. кнопок", + "description": "Блокировать кнопки при их долгом нажатии в режиме пайки (Т=Только турбо | П=Полная блокировка)" + }, + "ProfilePhases": { + "displayText": "Этапы\nпрофиля", + "description": "Количество этапов в режиме профиля" + }, + "ProfilePreheatTemp": { + "displayText": "Температура\nпреднагрева", + "description": "Температура предварительного нагрева в начале режима термопрофиля" + }, + "ProfilePreheatSpeed": { + "displayText": "Скорость\nпреднагрева", + "description": "Скорость предварительного нагрева в начале режима термопрофиля (в градусах в секунду)" + }, + "ProfilePhase1Temp": { + "displayText": "Температура\n1-го этапа", + "description": "Необходимая температура в конце 1-го этапа" + }, + "ProfilePhase1Duration": { + "displayText": "Длительность\n1-го этапа", + "description": "Необходимая длительность 1-го этапа (в секундах)" + }, + "ProfilePhase2Temp": { + "displayText": "Температура\n2-го этапа", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Длительность\n2-го этапа", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Температура\n3-го этапа", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Длительность\n3-го этапа", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Температура\n4-го этапа", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Длительность\n4-го этапа", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Температура\n5-го этапа", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Длительность\n5-го этапа", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Скорость\nостывания", + "description": "Скорость остывания в конце режима термопрофиля (в градусах в секунду)" + }, + "MotionSensitivity": { + "displayText": "Чувствительн.\nакселерометра", + "description": "Чувствительность акселерометра (1=мин. | ... | 9=макс.)" + }, + "SleepTemperature": { + "displayText": "t° при\nсне", + "description": "Температура жала в режиме сна" + }, + "SleepTimeout": { + "displayText": "Интервал\nсна", + "description": "Время до перехода в режим сна (секунды | минуты)" + }, + "ShutdownTimeout": { + "displayText": "Интервал\nотключ-я", + "description": "Время до выключения паяльника (в минутах)" + }, + "HallEffSensitivity": { + "displayText": "Датчик\nХолла", + "description": "Чувствительность датчика Холла к магнитному полю (1=мин. | ... | 9=макс.)" + }, + "HallEffSleepTimeout": { + "displayText": "Интервал\nдатчика Холла", + "description": "Время между превышением датчиком Холла порогового значения и режимом сна" + }, + "TemperatureUnit": { + "displayText": "Единицы\nизмерения", + "description": "Единицы измерения температуры (C=°Цельcия | F=°Фаренгейта)" + }, + "DisplayRotation": { + "displayText": "Поворот\nэкрана", + "description": "Поворот экрана (П=Правша | Л=Левша | А=Авто)" + }, + "CooldownBlink": { + "displayText": "Мигание t°\nпри остывании", + "description": "Мигать температурой на экране при остывании, пока жало ещё горячее" + }, + "ScrollingSpeed": { + "displayText": "Скорость\nтекста", + "description": "Скорость прокрутки текста (М=Медленная | Б=Быстрая)" + }, + "ReverseButtonTempChange": { + "displayText": "Поменять\nкнопки +/-", + "description": "Поменять кнопки изменения температуры" + }, + "ReverseButtonSettings": { + "displayText": "Поменять\nкнопки A/B", + "description": "Поменять назначение кнопок A/B в меню настроек" + }, + "AnimSpeed": { + "displayText": "Скорость\nанимации", + "description": "Скорость анимации иконок в главном меню (М=Медленная| С=Средняя | Б=Быстрая)" + }, + "AnimLoop": { + "displayText": "Зацикленная\nанимация", + "description": "Зацикленная анимация иконок в главном меню" + }, + "Brightness": { + "displayText": "Яркость\nэкрана", + "description": "Уровень яркости пикселей на экране" + }, + "ColourInversion": { + "displayText": "Инверсия\nэкрана", + "description": "Инвертировать пиксели на экране" + }, + "LOGOTime": { + "displayText": "Длит-ть\nлоготипа", + "description": "Длительность отображения логотипа (в секундах)" + }, + "AdvancedIdle": { + "displayText": "Подробный\nэкран ожидания", + "description": "Показывать дополнительную информацию на экране ожидания уменьшенным шрифтом" + }, + "AdvancedSoldering": { + "displayText": "Подробный\nэкран пайки", + "description": "Показывать дополнительную информацию на экране пайки уменьшенным шрифтом" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Включить BLE" + }, + "PowerLimit": { + "displayText": "Предел\nмощ-ти", + "description": "Максимальная мощность, которую может использовать паяльник (в ваттах)" + }, + "CalibrateCJC": { + "displayText": "Калибровка\nтемпературы", + "description": "Калибровка температуры (CJC) при следующем включении (не требуется при разнице менее 5°C)" + }, + "VoltageCalibration": { + "displayText": "Калибровка\nнапряжения", + "description": "Калибровка входного напряжения (долгое нажатие для выхода)" + }, + "PowerPulsePower": { + "displayText": "Сила имп.\nпитания", + "description": "Сила импульса, удерживающего от автовыключения источник питания (в ваттах)" + }, + "PowerPulseWait": { + "displayText": "Пауза имп.\nпитания (К)", + "description": "Коэффициент паузы между импульсами, удерживающими от автовыключения источник питания (К x 2,5 с)" + }, + "PowerPulseDuration": { + "displayText": "Длина имп.\nпитания (К)", + "description": "Коэффициент длины импульса, удерживающего от автовыключения источник питания (К x 250 мс)" + }, + "SettingsReset": { + "displayText": "Сброс\nнастроек", + "description": "Сброс настроек к значениям по умолчанию" + }, + "LanguageSwitch": { + "displayText": "Язык:\n RU Русский", + "description": "" + }, + "SolderingTipType": { + "displayText": "Тип\nжала", + "description": "Выбор типа установленного жала" } + } } diff --git a/Translations/translation_SK.json b/Translations/translation_SK.json index cea45ced1..a6ff47a58 100644 --- a/Translations/translation_SK.json +++ b/Translations/translation_SK.json @@ -1,319 +1,351 @@ { - "languageCode": "SK", - "languageLocalName": "Slovenčina", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Kalibrácia\ndokončená!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Nastavenia\nresetované" - }, - "NoAccelerometerMessage": { - "message": "Bez pohybového\nsenzora!" - }, - "NoPowerDeliveryMessage": { - "message": "Chýba čip\nUSB-PD!" - }, - "LockingKeysString": { - "message": "ZABLOK." - }, - "UnlockingKeysString": { - "message": "ODBLOK." - }, - "WarningKeysLockedString": { - "message": "!ZABLOK!" - }, - "WarningThermalRunaway": { - "message": "Únik\nTepla" - }, - "WarningTipShorted": { - "message": "!Skrat hrotu!" - }, - "SettingsCalibrationWarning": { - "message": "Pred reštartovaním sa uistite, že hrot a rúčka sú v izbovej teplote!" - }, - "CJCCalibrating": { - "message": "kalibrovanie\n" - }, - "SettingsResetWarning": { - "message": "Naozaj chcete obnoviť továrenské nastavenia?" - }, - "UVLOWarningString": { - "message": "Nízke U!" - }, - "UndervoltageString": { - "message": "Nízke napätie\n" - }, - "InputVoltageString": { - "message": "Vstupné U: \n" - }, - "SleepingSimpleString": { - "message": "Chrr" - }, - "SleepingAdvancedString": { - "message": "Pokojový režim.\n" - }, - "SleepingTipAdvancedString": { - "message": "Hrot: \n" - }, - "OffString": { - "message": "Vyp" - }, - "ProfilePreheatString": { - "message": "Predhrievanie\n" - }, - "ProfileCooldownString": { - "message": "Schladzovanie\n" - }, - "DeviceFailedValidationWarning": { - "message": "Vaše zariadenie je pravdepodobne falzifikát!" - }, - "TooHotToStartProfileWarning": { - "message": "Teplota príliš vysoká pre štart profilu" - } - }, - "characters": { - "SettingRightChar": "P", - "SettingLeftChar": "L", - "SettingAutoChar": "A", - "SettingOffChar": "Z", - "SettingSlowChar": "P", - "SettingMediumChar": "S", - "SettingFastChar": "R", - "SettingStartNoneChar": "V", - "SettingStartSolderingChar": "Z", - "SettingStartSleepChar": "S", - "SettingStartSleepOffChar": "I", - "SettingLockDisableChar": "Z", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "P" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Nastavenie\nvýkonu", - "description": "" - }, - "SolderingMenu": { - "displayText": "Nastavenie\nspájkovania", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Úsporný\nrežim", - "description": "" - }, - "UIMenu": { - "displayText": "Nastavenie\nzobrazenia", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Pokročilé\nnastavenia", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Zdroj\nnapätia", - "description": "Zdroj napätia. Nastavenie napätia pre vypnutie (cutoff) (DC=10V | nS=n*3.3V pre LiIon články)" - }, - "MinVolCell": { - "displayText": "Minimálne\nnapätie", - "description": "Minimálne napätie povolené na jeden článok (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "Obmedzenie QC\nnapätia", - "description": "Maximálne QC napätie ktoré si má systém vyžiadať" - }, - "PDNegTimeout": { - "displayText": "Čas vypršania\nPower Delivery", - "description": "Čas vyjednávania Power Delivery v 100ms krokoch pre kompatibilitu s niektorými QC nabíjačkami (0: vypnuté)" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Zapína PPS & EPR režimy" - }, - "BoostTemperature": { - "displayText": "Boost\nteplota", - "description": "Cieľová teplota pre prudký náhrev (v nastavených jednotkách)" - }, - "AutoStart": { - "displayText": "Automatické\nspustenie", - "description": "Pri štarte spustiť režim spájkovania (V=Vyp | Z=Spájkovanie | S=Spanok | I=Spanok izbová teplota)" - }, - "TempChangeShortStep": { - "displayText": "Malý krok\nteploty", - "description": "Zmena teploty pri krátkom stlačení tlačidla" - }, - "TempChangeLongStep": { - "displayText": "Veľký krok\nteploty", - "description": "Zmena teploty pri držaní tlačidla" - }, - "LockingMode": { - "displayText": "Povoliť zámok\ntlačidiel", - "description": "Zamknutie tlačidiel - dlhé stlačenie oboch naraz počas spájkovania (Z=Zakázať | B=Okrem boost | P=Plné zamknutie)" - }, - "ProfilePhases": { - "displayText": "Profilové\nFázy", - "description": "Počet fáz v profilovóm režime" - }, - "ProfilePreheatTemp": { - "displayText": "Teplota\nPredhriatia", - "description": "Teplota na ktorú sa má predohriať na začiatku profilového režimu" - }, - "ProfilePreheatSpeed": { - "displayText": "Rýchlosť\nPredhriatia", - "description": "Rýchlosť predhrievania (stupňe za sekundu)" - }, - "ProfilePhase1Temp": { - "displayText": "Teplota\nFáza 1", - "description": "Cieľová teplota na konci tejto fázy" - }, - "ProfilePhase1Duration": { - "displayText": "Trvanie\nFáza 1", - "description": "Doba trvania tejto fázy (sekundy)" - }, - "ProfilePhase2Temp": { - "displayText": "Teplota\nFáza 2", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Trvanie\nFáza 2", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Teplota\nFáza 3", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Trvanie\nFáza 3", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Teplota\nFáza 4", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Trvanie\nFáza 4", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Teplota\nFáza 5", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Trvanie\nFáza 4", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Rýchlosť\nochladzovania", - "description": "Rýchlosť ochladzovania na konci profilového režimu (stupne za sekundu)" - }, - "MotionSensitivity": { - "displayText": "Citlivosť\npohybu", - "description": "Citlivosť detekcie pohybu (0=Vyp | 1=Min | ... | 9=Max)" - }, - "SleepTemperature": { - "displayText": "Pokojová\nteplota", - "description": "Pokojová teplota (v nastavených jednotkách)" - }, - "SleepTimeout": { - "displayText": "Pokojový\nrežim po", - "description": "Pokojový režim po (s=sekundách | m=minútach)" - }, - "ShutdownTimeout": { - "displayText": "Vypnutie\npo", - "description": "Čas na vypnutie (minúty)" - }, - "HallEffSensitivity": { - "displayText": "Citliv.\nHall", - "description": "Citlivosť Hallovho senzora pre detekciu spánku (0=Vyp | 1=Min | ... | 9=Max)" - }, - "TemperatureUnit": { - "displayText": "Jednotka\nteploty", - "description": "Jednotky merania teploty (C=stupne Celzia | F=stupne Fahrenheita)" - }, - "DisplayRotation": { - "displayText": "Orientácia\ndispleja", - "description": "Orientácia displeja (P=Pravák | L=Ľavák | A=Auto)" - }, - "CooldownBlink": { - "displayText": "Blikanie pri\nchladnutí", - "description": "Blikanie ukazovateľa teploty počas chladnutia hrotu" - }, - "ScrollingSpeed": { - "displayText": "Rýchlosť\nskrolovania", - "description": "Rýchlosť pohybu tohto textu" - }, - "ReverseButtonTempChange": { - "displayText": "Otočenie\ntlačidiel +/-", - "description": "Prehodenie tlačidiel na nastavovanie teploty" - }, - "AnimSpeed": { - "displayText": "Rýchlosť\nanimácií", - "description": "Rýchlosť animácií ikoniek v menu (O=off | P=pomaly | S=stredne | R=rýchlo)" - }, - "AnimLoop": { - "displayText": "Opakovanie\nanimácií", - "description": "Opakovanie animácií ikoniek v hlavnom menu" - }, - "Brightness": { - "displayText": "Jas\nobrazovky", - "description": "Mení jas/kontrast OLED displeja" - }, - "ColourInversion": { - "displayText": "Invertovať\nobrazovku", - "description": "Invertovať farby OLED displeja" - }, - "LOGOTime": { - "displayText": "Trvanie\nboot loga", - "description": "Doba trvania boot loga (s=sekundy)" - }, - "AdvancedIdle": { - "displayText": "Detaily v\npokoj. režime", - "description": "Zobraziť detailné informácie v pokojovom režime (T=Zap | F=Vyp)" - }, - "AdvancedSoldering": { - "displayText": "Detaily počas\nspájkovania", - "description": "Zobrazenie detailov počas spájkovania" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Zapne BLE" - }, - "PowerLimit": { - "displayText": "Obmedzenie\nvýkonu", - "description": "Obmedzenie výkonu podľa použitého zdroja (watt)" - }, - "CalibrateCJC": { - "displayText": "Kalibrácia CJC\npri nasledujúcom štarte", - "description": "Pri nasledujúcom štarte bude kalibrovaná kompenzácia studeného spoja (nie je potrebné ak Delta T je < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Kalibrácia\nnap. napätia", - "description": "Kalibrácia napájacieho napätia. Krátke stlačenie mení nastavenie, dlhé stlačenie pre návrat" - }, - "PowerPulsePower": { - "displayText": "Intenzita\nimpulzu", - "description": "Impulz udržujúci napájací zdroj zapnutý (power banky) (watt)" - }, - "PowerPulseWait": { - "displayText": "Interval\nimpulzu", - "description": "Interval medzi impulzami udržujúcimi napájací zdroj zapnutý (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Dĺžka\nimpulzu", - "description": "Dĺžka impulzu udržujúci napájací zdroj zapnutý (x 250ms)" - }, - "SettingsReset": { - "displayText": "Obnovenie\nnastavení", - "description": "Obnovenie nastavení na pôvodné hodnoty" - }, - "LanguageSwitch": { - "displayText": "Jazyk:\n SK Slovenčina", - "description": "" - } + "languageCode": "SK", + "languageLocalName": "Slovenčina", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibrácia\ndokončená!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Nastavenia\nresetované" + }, + "NoAccelerometerMessage": { + "message": "Bez pohybového\nsenzora!" + }, + "NoPowerDeliveryMessage": { + "message": "Chýba čip\nUSB-PD!" + }, + "LockingKeysString": { + "message": "ZABLOK." + }, + "UnlockingKeysString": { + "message": "ODBLOK." + }, + "WarningKeysLockedString": { + "message": "!ZABLOK!" + }, + "WarningThermalRunaway": { + "message": "Únik\nTepla" + }, + "WarningTipShorted": { + "message": "!Skrat hrotu!" + }, + "SettingsCalibrationWarning": { + "message": "Pred reštartovaním sa uistite, že hrot a rúčka sú v izbovej teplote!" + }, + "CJCCalibrating": { + "message": "kalibrovanie\n" + }, + "SettingsResetWarning": { + "message": "Naozaj chcete obnoviť továrenské nastavenia?" + }, + "UVLOWarningString": { + "message": "Nízke U!" + }, + "UndervoltageString": { + "message": "Nízke napätie\n" + }, + "InputVoltageString": { + "message": "Vstupné U: \n" + }, + "SleepingAdvancedString": { + "message": "Pokojový režim.\n" + }, + "SleepingTipAdvancedString": { + "message": "Hrot: \n" + }, + "ProfilePreheatString": { + "message": "Predhrievanie\n" + }, + "ProfileCooldownString": { + "message": "Schladzovanie\n" + }, + "DeviceFailedValidationWarning": { + "message": "Vaše zariadenie je pravdepodobne falzifikát!" + }, + "TooHotToStartProfileWarning": { + "message": "Teplota príliš vysoká pre štart profilu" + } + }, + "characters": { + "SettingRightChar": "P", + "SettingLeftChar": "L", + "SettingAutoChar": "A", + "SettingSlowChar": "P", + "SettingMediumChar": "S", + "SettingFastChar": "R", + "SettingStartSolderingChar": "Z", + "SettingStartSleepChar": "S", + "SettingStartSleepOffChar": "I", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "P" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Nastavenie\nvýkonu", + "description": "" + }, + "SolderingMenu": { + "displayText": "Nastavenie\nspájkovania", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Úsporný\nrežim", + "description": "" + }, + "UIMenu": { + "displayText": "Nastavenie\nzobrazenia", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Pokročilé\nnastavenia", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Zdroj\nnapätia", + "description": "Zdroj napätia. Nastavenie napätia pre vypnutie (cutoff) (DC=10V | nS=n*3.3V pre LiIon články)" + }, + "MinVolCell": { + "displayText": "Minimálne\nnapätie", + "description": "Minimálne napätie povolené na jeden článok (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "Obmedzenie QC\nnapätia", + "description": "Maximálne QC napätie ktoré si má systém vyžiadať" + }, + "PDNegTimeout": { + "displayText": "Čas vypršania\nPower Delivery", + "description": "Čas vyjednávania Power Delivery v 100ms krokoch pre kompatibilitu s niektorými QC nabíjačkami (0: vypnuté)" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "Zapína PPS & EPR režimy" + }, + "BoostTemperature": { + "displayText": "Boost\nteplota", + "description": "Cieľová teplota pre prudký náhrev (v nastavených jednotkách)" + }, + "AutoStart": { + "displayText": "Automatické\nspustenie", + "description": "Pri štarte spustiť režim spájkovania (Z=Spájkovanie | S=Spanok | I=Spanok izbová teplota)" + }, + "TempChangeShortStep": { + "displayText": "Malý krok\nteploty", + "description": "Zmena teploty pri krátkom stlačení tlačidla" + }, + "TempChangeLongStep": { + "displayText": "Veľký krok\nteploty", + "description": "Zmena teploty pri držaní tlačidla" + }, + "LockingMode": { + "displayText": "Povoliť zámok\ntlačidiel", + "description": "Zamknutie tlačidiel - dlhé stlačenie oboch naraz počas spájkovania (B=Okrem boost | P=Plné zamknutie)" + }, + "ProfilePhases": { + "displayText": "Profilové\nFázy", + "description": "Počet fáz v profilovóm režime" + }, + "ProfilePreheatTemp": { + "displayText": "Teplota\nPredhriatia", + "description": "Teplota na ktorú sa má predohriať na začiatku profilového režimu" + }, + "ProfilePreheatSpeed": { + "displayText": "Rýchlosť\nPredhriatia", + "description": "Rýchlosť predhrievania (stupňe za sekundu)" + }, + "ProfilePhase1Temp": { + "displayText": "Teplota\nFáza 1", + "description": "Cieľová teplota na konci tejto fázy" + }, + "ProfilePhase1Duration": { + "displayText": "Trvanie\nFáza 1", + "description": "Doba trvania tejto fázy (sekundy)" + }, + "ProfilePhase2Temp": { + "displayText": "Teplota\nFáza 2", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Trvanie\nFáza 2", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Teplota\nFáza 3", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Trvanie\nFáza 3", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Teplota\nFáza 4", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Trvanie\nFáza 4", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Teplota\nFáza 5", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Trvanie\nFáza 5", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Rýchlosť\nochladzovania", + "description": "Rýchlosť ochladzovania na konci profilového režimu (stupne za sekundu)" + }, + "MotionSensitivity": { + "displayText": "Citlivosť\npohybu", + "description": "Citlivosť detekcie pohybu (1=Min | ... | 9=Max)" + }, + "SleepTemperature": { + "displayText": "Pokojová\nteplota", + "description": "Pokojová teplota (v nastavených jednotkách)" + }, + "SleepTimeout": { + "displayText": "Pokojový\nrežim po", + "description": "Pokojový režim po (s=sekundách | m=minútach)" + }, + "ShutdownTimeout": { + "displayText": "Vypnutie\npo", + "description": "Čas na vypnutie (minúty)" + }, + "HallEffSensitivity": { + "displayText": "Citliv.\nHall", + "description": "Citlivosť Hallovho senzora pre detekciu spánku (1=Min | ... | 9=Max)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval pred spustením \"režimu spánku\" keď je hall efekt nad prahovou hodnotou" + }, + "TemperatureUnit": { + "displayText": "Jednotka\nteploty", + "description": "Jednotky merania teploty (C=stupne Celzia | F=stupne Fahrenheita)" + }, + "DisplayRotation": { + "displayText": "Orientácia\ndispleja", + "description": "Orientácia displeja (P=Pravák | L=Ľavák | A=Auto)" + }, + "CooldownBlink": { + "displayText": "Blikanie pri\nchladnutí", + "description": "Blikanie ukazovateľa teploty počas chladnutia hrotu" + }, + "ScrollingSpeed": { + "displayText": "Rýchlosť\nskrolovania", + "description": "Rýchlosť pohybu tohto textu" + }, + "ReverseButtonTempChange": { + "displayText": "Otočenie\ntlačidiel +/-", + "description": "Prehodenie tlačidiel na nastavovanie teploty" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Rýchlosť\nanimácií", + "description": "Rýchlosť animácií ikoniek v menu (P=pomaly | S=stredne | R=rýchlo)" + }, + "AnimLoop": { + "displayText": "Opakovanie\nanimácií", + "description": "Opakovanie animácií ikoniek v hlavnom menu" + }, + "Brightness": { + "displayText": "Jas\nobrazovky", + "description": "Mení jas/kontrast OLED displeja" + }, + "ColourInversion": { + "displayText": "Invertovať\nobrazovku", + "description": "Invertovať farby OLED displeja" + }, + "LOGOTime": { + "displayText": "Trvanie\nboot loga", + "description": "Doba trvania boot loga (s=sekundy)" + }, + "AdvancedIdle": { + "displayText": "Detaily v\npokoj. režime", + "description": "Zobraziť detailné informácie v pokojovom režime (T=Zap | F=Vyp)" + }, + "AdvancedSoldering": { + "displayText": "Detaily počas\nspájkovania", + "description": "Zobrazenie detailov počas spájkovania" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Zapne BLE" + }, + "PowerLimit": { + "displayText": "Obmedzenie\nvýkonu", + "description": "Obmedzenie výkonu podľa použitého zdroja (watt)" + }, + "CalibrateCJC": { + "displayText": "Kalibrácia CJC\npri nasledujúcom štarte", + "description": "Pri nasledujúcom štarte bude kalibrovaná kompenzácia studeného spoja (nie je potrebné ak Delta T je < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibrácia\nnap. napätia", + "description": "Kalibrácia napájacieho napätia. Krátke stlačenie mení nastavenie, dlhé stlačenie pre návrat" + }, + "PowerPulsePower": { + "displayText": "Intenzita\nimpulzu", + "description": "Impulz udržujúci napájací zdroj zapnutý (power banky) (watt)" + }, + "PowerPulseWait": { + "displayText": "Interval\nimpulzu", + "description": "Interval medzi impulzami udržujúcimi napájací zdroj zapnutý (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Dĺžka\nimpulzu", + "description": "Dĺžka impulzu udržujúci napájací zdroj zapnutý (x 250ms)" + }, + "SettingsReset": { + "displayText": "Obnovenie\nnastavení", + "description": "Obnovenie nastavení na pôvodné hodnoty" + }, + "LanguageSwitch": { + "displayText": "Jazyk:\n SK Slovenčina", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_SL.json b/Translations/translation_SL.json index 2537823be..0bf842c97 100644 --- a/Translations/translation_SL.json +++ b/Translations/translation_SL.json @@ -1,319 +1,351 @@ { - "languageCode": "SL", - "languageLocalName": "Slovenščina", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Nastavitve \nOK!" - }, - "NoAccelerometerMessage": { - "message": "Ni \npospeševalnik" - }, - "NoPowerDeliveryMessage": { - "message": "Ni USB-PD \nčipa!" - }, - "LockingKeysString": { - "message": "ZAKLENJ." - }, - "UnlockingKeysString": { - "message": "ODKLENJ." - }, - "WarningKeysLockedString": { - "message": "ZAKLENJ." - }, - "WarningThermalRunaway": { - "message": "Thermal\nRunaway" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Res želite ponastaviti na privzete nastavitve?" - }, - "UVLOWarningString": { - "message": "NIZKA U" - }, - "UndervoltageString": { - "message": "Nizka napetost\n" - }, - "InputVoltageString": { - "message": "Vhodna U: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Spim...\n" - }, - "SleepingTipAdvancedString": { - "message": "Konica \n" - }, - "OffString": { - "message": "Off" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Your device is most likely a counterfeit!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "D", - "SettingLeftChar": "L", - "SettingAutoChar": "S", - "SettingOffChar": "U", - "SettingSlowChar": "P", - "SettingMediumChar": "M", - "SettingFastChar": "H", - "SettingStartNoneChar": "U", - "SettingStartSolderingChar": "S", - "SettingStartSleepChar": "Z", - "SettingStartSleepOffChar": "V", - "SettingLockDisableChar": "O", - "SettingLockBoostChar": "L", - "SettingLockFullChar": "P" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Power\nsettings", - "description": "" - }, - "SolderingMenu": { - "displayText": "Nastavitve\nspajkanja", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Način\nspanja", - "description": "" - }, - "UIMenu": { - "displayText": "Uporabniški\nvmesnik", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Napredne\nmožnosti", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Vir\nnapajanja", - "description": "Vir napajanja. Nastavi napetost izklopa. (DC 10V) (S 3.3V na celico)" - }, - "MinVolCell": { - "displayText": "Minimum\nvoltage", - "description": "Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "QC\nnapetost", - "description": "Moč napajalnega vira v vatih [W]" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Pospešena\ntemp.", - "description": "Temperatura v pospešenem načinu" - }, - "AutoStart": { - "displayText": "Samodejni\nzagon", - "description": "Samodejno gretje konice ob vklopu (U=ugasnjeno | S=spajkanje | Z=spanje | V=spanje na sobni temperaturi)" - }, - "TempChangeShortStep": { - "displayText": "Kratka sprememba\ntemperature?", - "description": "Temperatura se spremeni ob kratkem pritisku na gumb." - }, - "TempChangeLongStep": { - "displayText": "Dolga sprememba\ntemperature?", - "description": "Temperatura se spremeni ob dolgem pritisku na gumb." - }, - "LockingMode": { - "displayText": "Omogoči\nzaklep gumbov", - "description": "Za zaklep med spajkanjem drži oba gumba (O=onemogoči | L=le pospešeno | P=polno)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Občutljivost\npremikanja", - "description": "0=izklopljeno | 1=najmanjša | ... | 9=največja" - }, - "SleepTemperature": { - "displayText": "Temp. med\nspanjem", - "description": "Temperatura med spanjem" - }, - "SleepTimeout": { - "displayText": "Čas do\nspanja", - "description": "Čas pred spanjem (s=sekunde | m=minute)" - }, - "ShutdownTimeout": { - "displayText": "Čas do\nizklopa", - "description": "Čas do izklopa (m=minute)" - }, - "HallEffSensitivity": { - "displayText": "Občut.\nHall son", - "description": "Občutljivost Hallove sonde za zaznavanje spanja (0=izklopljeno | 1=najmanjša | ... | 9=največja)" - }, - "TemperatureUnit": { - "displayText": "Enota za\ntemperaturo", - "description": "Enota za temperaturo (C=celzij | F=fahrenheit)" - }, - "DisplayRotation": { - "displayText": "Orientacija\nzaslona", - "description": "D=desničar | L=levičar | S=samodejno" - }, - "CooldownBlink": { - "displayText": "Utripanje med\nhlajenjem", - "description": "Ko je konica še vroča, utripaj prikaz temperature med hlajenjem." - }, - "ScrollingSpeed": { - "displayText": "Hitrost\nbesedila", - "description": "Hitrost, s katero se prikazuje besedilo (P=počasi | H=hitro)" - }, - "ReverseButtonTempChange": { - "displayText": "Obrni\ntipki + -?", - "description": "Zamenjaj funkciji gumbov." - }, - "AnimSpeed": { - "displayText": "Anim.\nspeed", - "description": "Pace of icon animations in menu (O=off | P=slow | M=medium | H=fast)" - }, - "AnimLoop": { - "displayText": "Anim.\nloop", - "description": "Loop icon animations in main menu" - }, - "Brightness": { - "displayText": "Screen\nbrightness", - "description": "Adjust the OLED screen brightness" - }, - "ColourInversion": { - "displayText": "Invert\nscreen", - "description": "Invert the OLED screen colors" - }, - "LOGOTime": { - "displayText": "Boot logo\nduration", - "description": "Set boot logo duration (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Več info. na\nmir. zaslonu", - "description": "Prikaži več informacij z manjšo pisavo na mirovalnem zaslonu." - }, - "AdvancedSoldering": { - "displayText": "Več info na\nzaslonu spaj.", - "description": "Prikaže več informacij z manjšo pisavo na zaslonu med spajkanjem." - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Meja\nmoči", - "description": "Največja dovoljena moč v vatih [W]" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nat next boot", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Kalibriram\nvhodno napetost?", - "description": "Kalibracija VIN (nastavitve z gumbi, dolg pritisk za izhod)" - }, - "PowerPulsePower": { - "displayText": "Pulz\nmoči", - "description": "Velikost moči za vzdrževanje budnosti." - }, - "PowerPulseWait": { - "displayText": "Power pulse\ndelay", - "description": "Delay before keep-awake-pulse is triggered (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Power pulse\nduration", - "description": "Keep-awake-pulse duration (x 250ms)" - }, - "SettingsReset": { - "displayText": "Tovarniške\nnastavitve?", - "description": "Ponastavitev vseh nastavitev" - }, - "LanguageSwitch": { - "displayText": "Jezik:\n SL Slovenščina", - "description": "" - } + "languageCode": "SL", + "languageLocalName": "Slovenščina", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibration\ndone!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Nastavitve \nOK!" + }, + "NoAccelerometerMessage": { + "message": "Ni \npospeševalnik" + }, + "NoPowerDeliveryMessage": { + "message": "Ni USB-PD \nčipa!" + }, + "LockingKeysString": { + "message": "ZAKLENJ." + }, + "UnlockingKeysString": { + "message": "ODKLENJ." + }, + "WarningKeysLockedString": { + "message": "ZAKLENJ." + }, + "WarningThermalRunaway": { + "message": "Thermal\nRunaway" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Before rebooting, make sure tip & handle are at room temperature!" + }, + "CJCCalibrating": { + "message": "calibrating\n" + }, + "SettingsResetWarning": { + "message": "Res želite ponastaviti na privzete nastavitve?" + }, + "UVLOWarningString": { + "message": "NIZKA U" + }, + "UndervoltageString": { + "message": "Nizka napetost\n" + }, + "InputVoltageString": { + "message": "Vhodna U: \n" + }, + "SleepingAdvancedString": { + "message": "Spim...\n" + }, + "SleepingTipAdvancedString": { + "message": "Konica \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Your device is most likely a counterfeit!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "D", + "SettingLeftChar": "L", + "SettingAutoChar": "S", + "SettingSlowChar": "P", + "SettingMediumChar": "M", + "SettingFastChar": "H", + "SettingStartSolderingChar": "S", + "SettingStartSleepChar": "Z", + "SettingStartSleepOffChar": "V", + "SettingLockBoostChar": "L", + "SettingLockFullChar": "P" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Power\nsettings", + "description": "" + }, + "SolderingMenu": { + "displayText": "Nastavitve\nspajkanja", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Način\nspanja", + "description": "" + }, + "UIMenu": { + "displayText": "Uporabniški\nvmesnik", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Napredne\nmožnosti", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Vir\nnapajanja", + "description": "Vir napajanja. Nastavi napetost izklopa. (DC 10V) (S 3.3V na celico)" + }, + "MinVolCell": { + "displayText": "Minimum\nvoltage", + "description": "Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\nnapetost", + "description": "Moč napajalnega vira v vatih [W]" + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Pospešena\ntemp.", + "description": "Temperatura v pospešenem načinu" + }, + "AutoStart": { + "displayText": "Samodejni\nzagon", + "description": "Samodejno gretje konice ob vklopu (S=spajkanje | Z=spanje | V=spanje na sobni temperaturi)" + }, + "TempChangeShortStep": { + "displayText": "Kratka sprememba\ntemperature?", + "description": "Temperatura se spremeni ob kratkem pritisku na gumb." + }, + "TempChangeLongStep": { + "displayText": "Dolga sprememba\ntemperature?", + "description": "Temperatura se spremeni ob dolgem pritisku na gumb." + }, + "LockingMode": { + "displayText": "Omogoči\nzaklep gumbov", + "description": "Za zaklep med spajkanjem drži oba gumba (L=le pospešeno | P=polno)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Občutljivost\npremikanja", + "description": "1=najmanjša | ... | 9=največja" + }, + "SleepTemperature": { + "displayText": "Temp. med\nspanjem", + "description": "Temperatura med spanjem" + }, + "SleepTimeout": { + "displayText": "Čas do\nspanja", + "description": "Čas pred spanjem (s=sekunde | m=minute)" + }, + "ShutdownTimeout": { + "displayText": "Čas do\nizklopa", + "description": "Čas do izklopa (m=minute)" + }, + "HallEffSensitivity": { + "displayText": "Občut.\nHall son", + "description": "Občutljivost Hallove sonde za zaznavanje spanja (1=najmanjša | ... | 9=največja)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval pred začetkom \"načina mirovanja\", ko je Hallov učinek nad pragom" + }, + "TemperatureUnit": { + "displayText": "Enota za\ntemperaturo", + "description": "Enota za temperaturo (C=celzij | F=fahrenheit)" + }, + "DisplayRotation": { + "displayText": "Orientacija\nzaslona", + "description": "D=desničar | L=levičar | S=samodejno" + }, + "CooldownBlink": { + "displayText": "Utripanje med\nhlajenjem", + "description": "Ko je konica še vroča, utripaj prikaz temperature med hlajenjem." + }, + "ScrollingSpeed": { + "displayText": "Hitrost\nbesedila", + "description": "Hitrost, s katero se prikazuje besedilo (P=počasi | H=hitro)" + }, + "ReverseButtonTempChange": { + "displayText": "Obrni\ntipki + -?", + "description": "Zamenjaj funkciji gumbov." + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\nspeed", + "description": "Pace of icon animations in menu (P=slow | M=medium | H=fast)" + }, + "AnimLoop": { + "displayText": "Anim.\nloop", + "description": "Loop icon animations in main menu" + }, + "Brightness": { + "displayText": "Screen\nbrightness", + "description": "Adjust the OLED screen brightness" + }, + "ColourInversion": { + "displayText": "Invert\nscreen", + "description": "Invert the OLED screen colors" + }, + "LOGOTime": { + "displayText": "Boot logo\nduration", + "description": "Set boot logo duration (s=seconds)" + }, + "AdvancedIdle": { + "displayText": "Več info. na\nmir. zaslonu", + "description": "Prikaži več informacij z manjšo pisavo na mirovalnem zaslonu." + }, + "AdvancedSoldering": { + "displayText": "Več info na\nzaslonu spaj.", + "description": "Prikaže več informacij z manjšo pisavo na zaslonu med spajkanjem." + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Meja\nmoči", + "description": "Največja dovoljena moč v vatih [W]" + }, + "CalibrateCJC": { + "displayText": "Calibrate CJC\nat next boot", + "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibriram\nvhodno napetost?", + "description": "Kalibracija VIN (nastavitve z gumbi, dolg pritisk za izhod)" + }, + "PowerPulsePower": { + "displayText": "Pulz\nmoči", + "description": "Velikost moči za vzdrževanje budnosti." + }, + "PowerPulseWait": { + "displayText": "Power pulse\ndelay", + "description": "Delay before keep-awake-pulse is triggered (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Power pulse\nduration", + "description": "Keep-awake-pulse duration (x 250ms)" + }, + "SettingsReset": { + "displayText": "Tovarniške\nnastavitve?", + "description": "Ponastavitev vseh nastavitev" + }, + "LanguageSwitch": { + "displayText": "Jezik:\n SL Slovenščina", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_SR_CYRL.json b/Translations/translation_SR_CYRL.json index e4fc5c83f..1a093746d 100644 --- a/Translations/translation_SR_CYRL.json +++ b/Translations/translation_SR_CYRL.json @@ -1,319 +1,351 @@ { - "languageCode": "SR_CYRL", - "languageLocalName": "Српски", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Certain settings\nwere changed!" - }, - "NoAccelerometerMessage": { - "message": "No accelerometer\ndetected!" - }, - "NoPowerDeliveryMessage": { - "message": "No USB-PD IC\ndetected!" - }, - "LockingKeysString": { - "message": "LOCKED" - }, - "UnlockingKeysString": { - "message": "UNLOCKED" - }, - "WarningKeysLockedString": { - "message": "!LOCKED!" - }, - "WarningThermalRunaway": { - "message": "Thermal\nRunaway" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Да ли заиста желите да вратите поставке на фабричке вредности?" - }, - "UVLOWarningString": { - "message": "НИЗ.НАП." - }, - "UndervoltageString": { - "message": "ПРЕНИЗАК НАПОН\n" - }, - "InputVoltageString": { - "message": "Ул. напон: \n" - }, - "SleepingSimpleString": { - "message": "Сан" - }, - "SleepingAdvancedString": { - "message": "Спавање...\n" - }, - "SleepingTipAdvancedString": { - "message": "Врх: \n" - }, - "OffString": { - "message": "Иск" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Your device is most likely a counterfeit!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "Д", - "SettingLeftChar": "Л", - "SettingAutoChar": "А", - "SettingOffChar": "O", - "SettingSlowChar": "С", - "SettingMediumChar": "M", - "SettingFastChar": "Б", - "SettingStartNoneChar": "И", - "SettingStartSolderingChar": "Л", - "SettingStartSleepChar": "С", - "SettingStartSleepOffChar": "X", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Power\nsettings", - "description": "" - }, - "SolderingMenu": { - "displayText": "Поставке\nлемљења", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Уштеда\nенергије", - "description": "" - }, - "UIMenu": { - "displayText": "Корисничко\nсучеље", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Напредне\nпоставке", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Врста\nнапајања", - "description": "Тип напајања; одређује најнижи радни напон. (DC=адаптер [10V] | S=батерија [3,3V по ћелији])" - }, - "MinVolCell": { - "displayText": "Minimum\nvoltage", - "description": "Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "Улазна\nснага", - "description": "Снага напајања у ватима." - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Темп.\nпојачања", - "description": "Температура врха лемилице у току појачања." - }, - "AutoStart": { - "displayText": "Врући\nстарт", - "description": "Лемилица одмах по покретању прелази у режим лемљења и греје се. (И=искључити | Л=лемљење | С=спавати | X=спавати собна температура)" - }, - "TempChangeShortStep": { - "displayText": "Temp change\nshort", - "description": "Temperature-change-increment on short button press" - }, - "TempChangeLongStep": { - "displayText": "Temp change\nlong", - "description": "Temperature-change-increment on long button press" - }, - "LockingMode": { - "displayText": "Allow locking\nbuttons", - "description": "While soldering, hold down both buttons to toggle locking them (D=disable | B=boost mode only | F=full locking)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Осетљивост\nна покрет", - "description": "Осетљивост сензора покрета. (0=искључено | 1=најмање осетљиво | ... | 9=најосетљивије)" - }, - "SleepTemperature": { - "displayText": "Темп.\nспавања", - "description": "Температура на коју се спушта лемилица након одређеног времена мировања. (C | F)" - }, - "SleepTimeout": { - "displayText": "Време до\nспавања", - "description": "Време мировања након кога лемилица спушта температуру. (m=минути | s=секунде)" - }, - "ShutdownTimeout": { - "displayText": "Време до\nгашења", - "description": "Време мировања након кога се лемилица гаси. (m=минути)" - }, - "HallEffSensitivity": { - "displayText": "Hall sensor\nsensitivity", - "description": "Sensitivity to magnets (0=искључено | 1=најмање осетљиво | ... | 9=најосетљивије)" - }, - "TemperatureUnit": { - "displayText": "Јединица\nтемпературе", - "description": "Јединице у којима се приказује температура. (C=целзијус | F=фаренхајт)" - }, - "DisplayRotation": { - "displayText": "Оријентација\nекрана", - "description": "Како је окренут екран. (Д=за десноруке | Л=за леворуке | А=аутоматски)" - }, - "CooldownBlink": { - "displayText": "Упозорење\nпри хлађењу", - "description": "Приказ температуре трепће приликом хлађења докле год је врх и даље врућ." - }, - "ScrollingSpeed": { - "displayText": "Брзина\nпорука", - "description": "Брзина кретања описних порука попут ове. (С=споро | Б=брзо)" - }, - "ReverseButtonTempChange": { - "displayText": "Swap\n+ - keys", - "description": "Reverse assignment of buttons for temperature adjustment" - }, - "AnimSpeed": { - "displayText": "Anim.\nspeed", - "description": "Pace of icon animations in menu (O=off | С=slow | M=medium | Б=fast)" - }, - "AnimLoop": { - "displayText": "Anim.\nloop", - "description": "Loop icon animations in main menu" - }, - "Brightness": { - "displayText": "Screen\nbrightness", - "description": "Adjust the OLED screen brightness" - }, - "ColourInversion": { - "displayText": "Invert\nscreen", - "description": "Invert the OLED screen colors" - }, - "LOGOTime": { - "displayText": "Boot logo\nduration", - "description": "Set boot logo duration (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Детаљи током\nмировања", - "description": "Приказивање детаљних информација на екрану током мировања." - }, - "AdvancedSoldering": { - "displayText": "Детаљи током\nлемљења", - "description": "Приказивање детаљних информација на екрану током лемљења." - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Power\nlimit", - "description": "Average maximum power the iron can use (W=watt)" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nat next boot", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5 C)" - }, - "VoltageCalibration": { - "displayText": "Калибрација\nулазног напона", - "description": "Калибрисање улазног напона. Подешава се на тастере; дуги притисак за крај." - }, - "PowerPulsePower": { - "displayText": "Power\npulse", - "description": "Intensity of power of keep-awake-pulse (W=watt)" - }, - "PowerPulseWait": { - "displayText": "Power pulse\ndelay", - "description": "Delay before keep-awake-pulse is triggered (x 2.5с)" - }, - "PowerPulseDuration": { - "displayText": "Power pulse\nduration", - "description": "Keep-awake-pulse duration (x 250мс)" - }, - "SettingsReset": { - "displayText": "Фабричке\nпоставке", - "description": "Враћање свих поставки на фабричке вредности." - }, - "LanguageSwitch": { - "displayText": "Jезик:\n SR Српски", - "description": "" - } + "languageCode": "SR_CYRL", + "languageLocalName": "Српски", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibration\ndone!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Certain settings\nwere changed!" + }, + "NoAccelerometerMessage": { + "message": "No accelerometer\ndetected!" + }, + "NoPowerDeliveryMessage": { + "message": "No USB-PD IC\ndetected!" + }, + "LockingKeysString": { + "message": "LOCKED" + }, + "UnlockingKeysString": { + "message": "UNLOCKED" + }, + "WarningKeysLockedString": { + "message": "!LOCKED!" + }, + "WarningThermalRunaway": { + "message": "Thermal\nRunaway" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Before rebooting, make sure tip & handle are at room temperature!" + }, + "CJCCalibrating": { + "message": "calibrating\n" + }, + "SettingsResetWarning": { + "message": "Да ли заиста желите да вратите поставке на фабричке вредности?" + }, + "UVLOWarningString": { + "message": "НИЗ.НАП." + }, + "UndervoltageString": { + "message": "ПРЕНИЗАК НАПОН\n" + }, + "InputVoltageString": { + "message": "Ул. напон: \n" + }, + "SleepingAdvancedString": { + "message": "Спавање...\n" + }, + "SleepingTipAdvancedString": { + "message": "Врх: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Your device is most likely a counterfeit!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "Д", + "SettingLeftChar": "Л", + "SettingAutoChar": "А", + "SettingSlowChar": "С", + "SettingMediumChar": "M", + "SettingFastChar": "Б", + "SettingStartSolderingChar": "Л", + "SettingStartSleepChar": "С", + "SettingStartSleepOffChar": "X", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Power\nsettings", + "description": "" + }, + "SolderingMenu": { + "displayText": "Поставке\nлемљења", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Уштеда\nенергије", + "description": "" + }, + "UIMenu": { + "displayText": "Корисничко\nсучеље", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Напредне\nпоставке", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Врста\nнапајања", + "description": "Тип напајања; одређује најнижи радни напон. (DC=адаптер [10V] | S=батерија [3,3V по ћелији])" + }, + "MinVolCell": { + "displayText": "Minimum\nvoltage", + "description": "Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "Улазна\nснага", + "description": "Снага напајања у ватима." + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Темп.\nпојачања", + "description": "Температура врха лемилице у току појачања." + }, + "AutoStart": { + "displayText": "Врући\nстарт", + "description": "Лемилица одмах по покретању прелази у режим лемљења и греје се. (Л=лемљење | С=спавати | X=спавати собна температура)" + }, + "TempChangeShortStep": { + "displayText": "Temp change\nshort", + "description": "Temperature-change-increment on short button press" + }, + "TempChangeLongStep": { + "displayText": "Temp change\nlong", + "description": "Temperature-change-increment on long button press" + }, + "LockingMode": { + "displayText": "Allow locking\nbuttons", + "description": "While soldering, hold down both buttons to toggle locking them (B=boost mode only | F=full locking)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Осетљивост\nна покрет", + "description": "Осетљивост сензора покрета. (1=најмање осетљиво | ... | 9=најосетљивије)" + }, + "SleepTemperature": { + "displayText": "Темп.\nспавања", + "description": "Температура на коју се спушта лемилица након одређеног времена мировања. (C | F)" + }, + "SleepTimeout": { + "displayText": "Време до\nспавања", + "description": "Време мировања након кога лемилица спушта температуру. (m=минути | s=секунде)" + }, + "ShutdownTimeout": { + "displayText": "Време до\nгашења", + "description": "Време мировања након кога се лемилица гаси. (m=минути)" + }, + "HallEffSensitivity": { + "displayText": "Hall sensor\nsensitivity", + "description": "Sensitivity to magnets (1=најмање осетљиво | ... | 9=најосетљивије)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Интервал пре почетка \"режима спавања\" када је ефекат Хола изнад прага" + }, + "TemperatureUnit": { + "displayText": "Јединица\nтемпературе", + "description": "Јединице у којима се приказује температура. (C=целзијус | F=фаренхајт)" + }, + "DisplayRotation": { + "displayText": "Оријентација\nекрана", + "description": "Како је окренут екран. (Д=за десноруке | Л=за леворуке | А=аутоматски)" + }, + "CooldownBlink": { + "displayText": "Упозорење\nпри хлађењу", + "description": "Приказ температуре трепће приликом хлађења докле год је врх и даље врућ." + }, + "ScrollingSpeed": { + "displayText": "Брзина\nпорука", + "description": "Брзина кретања описних порука попут ове. (С=споро | Б=брзо)" + }, + "ReverseButtonTempChange": { + "displayText": "Swap\n+ - keys", + "description": "Reverse assignment of buttons for temperature adjustment" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\nspeed", + "description": "Pace of icon animations in menu (С=slow | M=medium | Б=fast)" + }, + "AnimLoop": { + "displayText": "Anim.\nloop", + "description": "Loop icon animations in main menu" + }, + "Brightness": { + "displayText": "Screen\nbrightness", + "description": "Adjust the OLED screen brightness" + }, + "ColourInversion": { + "displayText": "Invert\nscreen", + "description": "Invert the OLED screen colors" + }, + "LOGOTime": { + "displayText": "Boot logo\nduration", + "description": "Set boot logo duration (s=seconds)" + }, + "AdvancedIdle": { + "displayText": "Детаљи током\nмировања", + "description": "Приказивање детаљних информација на екрану током мировања." + }, + "AdvancedSoldering": { + "displayText": "Детаљи током\nлемљења", + "description": "Приказивање детаљних информација на екрану током лемљења." + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Power\nlimit", + "description": "Average maximum power the iron can use (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Calibrate CJC\nat next boot", + "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5 C)" + }, + "VoltageCalibration": { + "displayText": "Калибрација\nулазног напона", + "description": "Калибрисање улазног напона. Подешава се на тастере; дуги притисак за крај." + }, + "PowerPulsePower": { + "displayText": "Power\npulse", + "description": "Intensity of power of keep-awake-pulse (W=watt)" + }, + "PowerPulseWait": { + "displayText": "Power pulse\ndelay", + "description": "Delay before keep-awake-pulse is triggered (x 2.5с)" + }, + "PowerPulseDuration": { + "displayText": "Power pulse\nduration", + "description": "Keep-awake-pulse duration (x 250мс)" + }, + "SettingsReset": { + "displayText": "Фабричке\nпоставке", + "description": "Враћање свих поставки на фабричке вредности." + }, + "LanguageSwitch": { + "displayText": "Jезик:\n SR Српски", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_SR_LATN.json b/Translations/translation_SR_LATN.json index f17a35f4a..a68eb2530 100644 --- a/Translations/translation_SR_LATN.json +++ b/Translations/translation_SR_LATN.json @@ -1,319 +1,351 @@ { - "languageCode": "SR_LATN", - "languageLocalName": "Srpski", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Certain settings\nwere changed!" - }, - "NoAccelerometerMessage": { - "message": "No accelerometer\ndetected!" - }, - "NoPowerDeliveryMessage": { - "message": "No USB-PD IC\ndetected!" - }, - "LockingKeysString": { - "message": "LOCKED" - }, - "UnlockingKeysString": { - "message": "UNLOCKED" - }, - "WarningKeysLockedString": { - "message": "!LOCKED!" - }, - "WarningThermalRunaway": { - "message": "Thermal\nRunaway" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Da li zaista želite da vratite postavke na fabričke vrednosti?" - }, - "UVLOWarningString": { - "message": "NIZ.NAP." - }, - "UndervoltageString": { - "message": "PRENIZAK NAPON\n" - }, - "InputVoltageString": { - "message": "Ul. napon: \n" - }, - "SleepingSimpleString": { - "message": "Zzz" - }, - "SleepingAdvancedString": { - "message": "Spavanje...\n" - }, - "SleepingTipAdvancedString": { - "message": "Vrh: \n" - }, - "OffString": { - "message": "Isk" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Your device is most likely a counterfeit!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "D", - "SettingLeftChar": "L", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "S", - "SettingMediumChar": "M", - "SettingFastChar": "B", - "SettingStartNoneChar": "I", - "SettingStartSolderingChar": "L", - "SettingStartSleepChar": "S", - "SettingStartSleepOffChar": "X", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Power\nsettings", - "description": "" - }, - "SolderingMenu": { - "displayText": "Postavke\nlemljenja", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Ušteda\nenergije", - "description": "" - }, - "UIMenu": { - "displayText": "Korisničko\nsučelje", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Napredne\npostavke", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Vrsta\nnapajanja", - "description": "Tip napajanja; određuje najniži radni napon. (DC=adapter [10V], S=baterija [3,3V po ćeliji])" - }, - "MinVolCell": { - "displayText": "Minimum\nvoltage", - "description": "Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "Ulazna\nsnaga", - "description": "Snaga napajanja u vatima." - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Temp.\npojačanja", - "description": "Temperatura vrha lemilice u toku pojačanja." - }, - "AutoStart": { - "displayText": "Vrući\nstart", - "description": "Lemilica odmah po pokretanju prelazi u režim lemljenja i greje se. (I=isključiti | L=lemljenje | S=spavati | X=spavati sobna temperatura)" - }, - "TempChangeShortStep": { - "displayText": "Temp change\nshort", - "description": "Temperature-change-increment on short button press" - }, - "TempChangeLongStep": { - "displayText": "Temp change\nlong", - "description": "Temperature-change-increment on long button press" - }, - "LockingMode": { - "displayText": "Allow locking\nbuttons", - "description": "While soldering, hold down both buttons to toggle locking them (D=disable | B=boost mode only | F=full locking)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Osetljivost\nna pokret", - "description": "Osetljivost senzora pokreta. (0=isključeno | 1=najmanje osetljivo | ... | 9=najosetljivije)" - }, - "SleepTemperature": { - "displayText": "Temp.\nspavanja", - "description": "Temperatura na koju se spušta lemilica nakon određenog vremena mirovanja. (C | F)" - }, - "SleepTimeout": { - "displayText": "Vreme do\nspavanja", - "description": "Vreme mirovanja nakon koga lemilica spušta temperaturu. (m=minuti | s=sekunde)" - }, - "ShutdownTimeout": { - "displayText": "Vreme do\ngašenja", - "description": "Vreme mirovanja nakon koga se lemilica gasi. (m=minuti)" - }, - "HallEffSensitivity": { - "displayText": "Hall sensor\nsensitivity", - "description": "Sensitivity to magnets (0=isključeno | 1=najmanje osetljivo | ... | 9=najosetljivije)" - }, - "TemperatureUnit": { - "displayText": "Jedinica\ntemperature", - "description": "Jedinice u kojima se prikazuje temperatura. (C=celzijus | F=farenhajt)" - }, - "DisplayRotation": { - "displayText": "Orijentacija\nekrana", - "description": "Kako je okrenut ekran. (D=za desnoruke | L=za levoruke | A=automatski)" - }, - "CooldownBlink": { - "displayText": "Upozorenje\npri hlađenju", - "description": "Prikaz temperature trepće prilikom hlađenja dokle god je vrh i dalje vruć." - }, - "ScrollingSpeed": { - "displayText": "Brzina\nporuka", - "description": "Brzina kretanja opisnih poruka poput ove. (S=sporo | B=brzo)" - }, - "ReverseButtonTempChange": { - "displayText": "Swap\n+ - keys", - "description": "Reverse assignment of buttons for temperature adjustment" - }, - "AnimSpeed": { - "displayText": "Anim.\nspeed", - "description": "Pace of icon animations in menu (O=off | S=slow | M=medium | B=fast)" - }, - "AnimLoop": { - "displayText": "Anim.\nloop", - "description": "Loop icon animations in main menu" - }, - "Brightness": { - "displayText": "Screen\nbrightness", - "description": "Adjust the OLED screen brightness" - }, - "ColourInversion": { - "displayText": "Invert\nscreen", - "description": "Invert the OLED screen colors" - }, - "LOGOTime": { - "displayText": "Boot logo\nduration", - "description": "Set boot logo duration (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Detalji tokom\nmirovanja", - "description": "Prikazivanje detaljnih informacija na ekranu tokom mirovanja." - }, - "AdvancedSoldering": { - "displayText": "Detalji tokom\nlemljenja", - "description": "Prikazivanje detaljnih informacija na ekranu tokom lemljenja." - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Power\nlimit", - "description": "Average maximum power the iron can use (W=watt)" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nat next boot", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Kalibracija\nulaznog napona", - "description": "Kalibrisanje ulaznog napona. Podešava se na tastere; dugi pritisak za kraj." - }, - "PowerPulsePower": { - "displayText": "Power\npulse", - "description": "Intensity of power of keep-awake-pulse (W=watt)" - }, - "PowerPulseWait": { - "displayText": "Power pulse\ndelay", - "description": "Delay before keep-awake-pulse is triggered (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Power pulse\nduration", - "description": "Keep-awake-pulse duration (x 250ms)" - }, - "SettingsReset": { - "displayText": "Fabričke\npostavke", - "description": "Vraćanje svih postavki na fabričke vrednosti." - }, - "LanguageSwitch": { - "displayText": "Jezik:\n SR Srpski", - "description": "" - } + "languageCode": "SR_LATN", + "languageLocalName": "Srpski", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibration\ndone!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Certain settings\nwere changed!" + }, + "NoAccelerometerMessage": { + "message": "No accelerometer\ndetected!" + }, + "NoPowerDeliveryMessage": { + "message": "No USB-PD IC\ndetected!" + }, + "LockingKeysString": { + "message": "LOCKED" + }, + "UnlockingKeysString": { + "message": "UNLOCKED" + }, + "WarningKeysLockedString": { + "message": "!LOCKED!" + }, + "WarningThermalRunaway": { + "message": "Thermal\nRunaway" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Before rebooting, make sure tip & handle are at room temperature!" + }, + "CJCCalibrating": { + "message": "calibrating\n" + }, + "SettingsResetWarning": { + "message": "Da li zaista želite da vratite postavke na fabričke vrednosti?" + }, + "UVLOWarningString": { + "message": "NIZ.NAP." + }, + "UndervoltageString": { + "message": "PRENIZAK NAPON\n" + }, + "InputVoltageString": { + "message": "Ul. napon: \n" + }, + "SleepingAdvancedString": { + "message": "Spavanje...\n" + }, + "SleepingTipAdvancedString": { + "message": "Vrh: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Your device is most likely a counterfeit!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "D", + "SettingLeftChar": "L", + "SettingAutoChar": "A", + "SettingSlowChar": "S", + "SettingMediumChar": "M", + "SettingFastChar": "B", + "SettingStartSolderingChar": "L", + "SettingStartSleepChar": "S", + "SettingStartSleepOffChar": "X", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Power\nsettings", + "description": "" + }, + "SolderingMenu": { + "displayText": "Postavke\nlemljenja", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Ušteda\nenergije", + "description": "" + }, + "UIMenu": { + "displayText": "Korisničko\nsučelje", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Napredne\npostavke", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Vrsta\nnapajanja", + "description": "Tip napajanja; određuje najniži radni napon. (DC=adapter [10V], S=baterija [3,3V po ćeliji])" + }, + "MinVolCell": { + "displayText": "Minimum\nvoltage", + "description": "Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "Ulazna\nsnaga", + "description": "Snaga napajanja u vatima." + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Temp.\npojačanja", + "description": "Temperatura vrha lemilice u toku pojačanja." + }, + "AutoStart": { + "displayText": "Vrući\nstart", + "description": "Lemilica odmah po pokretanju prelazi u režim lemljenja i greje se. (L=lemljenje | S=spavati | X=spavati sobna temperatura)" + }, + "TempChangeShortStep": { + "displayText": "Temp change\nshort", + "description": "Temperature-change-increment on short button press" + }, + "TempChangeLongStep": { + "displayText": "Temp change\nlong", + "description": "Temperature-change-increment on long button press" + }, + "LockingMode": { + "displayText": "Allow locking\nbuttons", + "description": "While soldering, hold down both buttons to toggle locking them (B=boost mode only | F=full locking)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Osetljivost\nna pokret", + "description": "Osetljivost senzora pokreta. (1=najmanje osetljivo | ... | 9=najosetljivije)" + }, + "SleepTemperature": { + "displayText": "Temp.\nspavanja", + "description": "Temperatura na koju se spušta lemilica nakon određenog vremena mirovanja. (C | F)" + }, + "SleepTimeout": { + "displayText": "Vreme do\nspavanja", + "description": "Vreme mirovanja nakon koga lemilica spušta temperaturu. (m=minuti | s=sekunde)" + }, + "ShutdownTimeout": { + "displayText": "Vreme do\ngašenja", + "description": "Vreme mirovanja nakon koga se lemilica gasi. (m=minuti)" + }, + "HallEffSensitivity": { + "displayText": "Hall sensor\nsensitivity", + "description": "Sensitivity to magnets (1=najmanje osetljivo | ... | 9=najosetljivije)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval before \"sleep mode\" starts when hall effect is above threshold" + }, + "TemperatureUnit": { + "displayText": "Jedinica\ntemperature", + "description": "Jedinice u kojima se prikazuje temperatura. (C=celzijus | F=farenhajt)" + }, + "DisplayRotation": { + "displayText": "Orijentacija\nekrana", + "description": "Kako je okrenut ekran. (D=za desnoruke | L=za levoruke | A=automatski)" + }, + "CooldownBlink": { + "displayText": "Upozorenje\npri hlađenju", + "description": "Prikaz temperature trepće prilikom hlađenja dokle god je vrh i dalje vruć." + }, + "ScrollingSpeed": { + "displayText": "Brzina\nporuka", + "description": "Brzina kretanja opisnih poruka poput ove. (S=sporo | B=brzo)" + }, + "ReverseButtonTempChange": { + "displayText": "Swap\n+ - keys", + "description": "Reverse assignment of buttons for temperature adjustment" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\nspeed", + "description": "Pace of icon animations in menu (S=slow | M=medium | B=fast)" + }, + "AnimLoop": { + "displayText": "Anim.\nloop", + "description": "Loop icon animations in main menu" + }, + "Brightness": { + "displayText": "Screen\nbrightness", + "description": "Adjust the OLED screen brightness" + }, + "ColourInversion": { + "displayText": "Invert\nscreen", + "description": "Invert the OLED screen colors" + }, + "LOGOTime": { + "displayText": "Boot logo\nduration", + "description": "Set boot logo duration (s=seconds)" + }, + "AdvancedIdle": { + "displayText": "Detalji tokom\nmirovanja", + "description": "Prikazivanje detaljnih informacija na ekranu tokom mirovanja." + }, + "AdvancedSoldering": { + "displayText": "Detalji tokom\nlemljenja", + "description": "Prikazivanje detaljnih informacija na ekranu tokom lemljenja." + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Power\nlimit", + "description": "Average maximum power the iron can use (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Calibrate CJC\nat next boot", + "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibracija\nulaznog napona", + "description": "Kalibrisanje ulaznog napona. Podešava se na tastere; dugi pritisak za kraj." + }, + "PowerPulsePower": { + "displayText": "Power\npulse", + "description": "Intensity of power of keep-awake-pulse (W=watt)" + }, + "PowerPulseWait": { + "displayText": "Power pulse\ndelay", + "description": "Delay before keep-awake-pulse is triggered (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Power pulse\nduration", + "description": "Keep-awake-pulse duration (x 250ms)" + }, + "SettingsReset": { + "displayText": "Fabričke\npostavke", + "description": "Vraćanje svih postavki na fabričke vrednosti." + }, + "LanguageSwitch": { + "displayText": "Jezik:\n SR Srpski", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_SV.json b/Translations/translation_SV.json index 50215ae16..3c9750259 100644 --- a/Translations/translation_SV.json +++ b/Translations/translation_SV.json @@ -1,319 +1,351 @@ { - "languageCode": "SV", - "languageLocalName": "Svenska", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Kalibrering\nfärdig!" - }, - "ResetOKMessage": { - "message": "Återställning\nOK" - }, - "SettingsResetMessage": { - "message": "Inställningar\nåterställda" - }, - "NoAccelerometerMessage": { - "message": "Ingen\naccelerometer" - }, - "NoPowerDeliveryMessage": { - "message": "Ingen USB-PD IC\nhittades!" - }, - "LockingKeysString": { - "message": "LÅST" - }, - "UnlockingKeysString": { - "message": "UPPLÅST" - }, - "WarningKeysLockedString": { - "message": "!LÅST!" - }, - "WarningThermalRunaway": { - "message": "Termisk\nFlykt" - }, - "WarningTipShorted": { - "message": "!Spets Kortsluten!" - }, - "SettingsCalibrationWarning": { - "message": "Före omstart, säkerställ att spetsen och handtaget är i rumstemperatur!" - }, - "CJCCalibrating": { - "message": "kalibrerar\n" - }, - "SettingsResetWarning": { - "message": "Är du säker på att du vill återställa inställningarna?" - }, - "UVLOWarningString": { - "message": "DC LÅG" - }, - "UndervoltageString": { - "message": "Underspänning\n" - }, - "InputVoltageString": { - "message": "Inspän. V: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Viloläge...\n" - }, - "SleepingTipAdvancedString": { - "message": "Spets: \n" - }, - "OffString": { - "message": "Av" - }, - "ProfilePreheatString": { - "message": "Förvärmning\n" - }, - "ProfileCooldownString": { - "message": "Nedkyldning\n" - }, - "DeviceFailedValidationWarning": { - "message": "Din enhet är sannerligen oäkta!" - }, - "TooHotToStartProfileWarning": { - "message": "För varm för att\nstarta profilen!" - } - }, - "characters": { - "SettingRightChar": "H", - "SettingLeftChar": "V", - "SettingAutoChar": "A", - "SettingOffChar": "A", - "SettingSlowChar": "L", - "SettingMediumChar": "M", - "SettingFastChar": "S", - "SettingStartNoneChar": "A", - "SettingStartSolderingChar": "L", - "SettingStartSleepChar": "V", - "SettingStartSleepOffChar": "R", - "SettingLockDisableChar": "A", - "SettingLockBoostChar": "T", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Effekt-\ninställning", - "description": "" - }, - "SolderingMenu": { - "displayText": "Lödnings-\ninställning", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Vilo-\nläge", - "description": "" - }, - "UIMenu": { - "displayText": "Användar-\ngränssnitt", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Avancerade\nalternativ", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Ström-\nkälla", - "description": "Strömkälla. Anger lägsta spänning. (DC 10V) (S 3.3V per cell)" - }, - "MinVolCell": { - "displayText": "Minimim-\nspänning", - "description": "Minimumspänning per cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "QC\nspänning", - "description": "Maximal QC-spänning enheten skall efterfråga" - }, - "PDNegTimeout": { - "displayText": "PD\npauser", - "description": "PD förhandlings pauser i 100ms steg för kompatibilitet med vissa PD laddare" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Slår på PPS & EPR lägen" - }, - "BoostTemperature": { - "displayText": "Turbo-\ntemp", - "description": "Temperatur i \"turbo-läge\"" - }, - "AutoStart": { - "displayText": "Auto\nstart", - "description": "Startar automatiskt lödpennan vid uppstart. (A=Av | L=Lödning | V=Viloläge | R=Viloläge Rumstemperatur)" - }, - "TempChangeShortStep": { - "displayText": "Temp.just\nkorttryck", - "description": "Temperaturjustering vid kort knapptryckning" - }, - "TempChangeLongStep": { - "displayText": "Temp.just\nlångtryck", - "description": "Temperaturjustering vid lång knapptryckning" - }, - "LockingMode": { - "displayText": "Tillåt lås\nvia knappar", - "description": "Vid lödning, håll nere bägge knappar för att slå på lås (A=Av | T=Bara turbo | F=Fullt lås)" - }, - "ProfilePhases": { - "displayText": "Profil-\nfaser", - "description": "Antal faser i profil läge" - }, - "ProfilePreheatTemp": { - "displayText": "Förvärmnings-\ntemp", - "description": "Förvärm till denna temperatur i början av provil läget" - }, - "ProfilePreheatSpeed": { - "displayText": "Förvärmnings-\nhastighet", - "description": "Förvärm enligt denna hastighet (grader per sekund)" - }, - "ProfilePhase1Temp": { - "displayText": "Fas 1\nTemp", - "description": "Måltemperatur i slutet av denna fas" - }, - "ProfilePhase1Duration": { - "displayText": "Fas 1\nTidslängd", - "description": "Mållängd av denna fasen (sekunder)" - }, - "ProfilePhase2Temp": { - "displayText": "Fas 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Fas 2\nTidslängd", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Fas 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Fas 3\nTidslängd", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Fas 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Fas 4\nTidslängd", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Fas 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Fas 5\nTidslängd", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Nedkylnings-\nhastighet", - "description": "Kyl ned i denna hastighet i slutet av profilen (grader per sekund)" - }, - "MotionSensitivity": { - "displayText": "Rörelse-\nkänslighet", - "description": "Rörelsekänslighet (0=Av | 1=minst känslig | ... | 9=mest känslig)" - }, - "SleepTemperature": { - "displayText": "Vilo-\ntemp", - "description": "Vilotemperatur (C)" - }, - "SleepTimeout": { - "displayText": "Vilo-\ntimeout", - "description": "Vilo-timeout (m=Minuter | s=Sekunder)" - }, - "ShutdownTimeout": { - "displayText": "Avstängn.\ntimeout", - "description": "Avstängnings-timeout (Minuter)" - }, - "HallEffSensitivity": { - "displayText": "Sensor-\nkänslght", - "description": "Känslighet för halleffekt-sensorn för viloläges-detektering (0=Av | 1=minst känslig | ... | 9=mest känslig)" - }, - "TemperatureUnit": { - "displayText": "Temperatur-\nenheter", - "description": "Temperaturenhet (C=Celsius | F=Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "Visnings\nläge", - "description": "Visningsläge (H=Högerhänt | V=Vänsterhänt | A=Automatisk)" - }, - "CooldownBlink": { - "displayText": "Nedkylnings-\nblink", - "description": "Blinka temperaturen medan spetsen kyls av och fortfarande är varm." - }, - "ScrollingSpeed": { - "displayText": "Beskrivning\nrullhast.", - "description": "Hastighet som den här texten rullar i" - }, - "ReverseButtonTempChange": { - "displayText": "Omvända\n+- knappar", - "description": "Omvänd ordning för temperaturjustering via plus/minus knapparna" - }, - "AnimSpeed": { - "displayText": "Anim.-\nhastighet", - "description": "Animationshastighet för ikoner i menyer (A=av | L=långsam | M=medel | S=snabb)" - }, - "AnimLoop": { - "displayText": "Anim.\nloop", - "description": "Loopa animationer i huvudmeny" - }, - "Brightness": { - "displayText": "Skärmens\nLjusstyrka", - "description": "Justera OLED skärmens ljusstyrka" - }, - "ColourInversion": { - "displayText": "Invertera\nskärm", - "description": "Invertera OLED skärmens färger" - }, - "LOGOTime": { - "displayText": "Start logo\nTidslängd", - "description": "Sätt uppstartslogotypens tidslängd (s=sekunder)" - }, - "AdvancedIdle": { - "displayText": "Detaljerad\nvid inaktiv", - "description": "Visa detaljerad information i mindre typsnitt när inaktiv." - }, - "AdvancedSoldering": { - "displayText": "Detaljerad\nlödng.skärm", - "description": "Visa detaljerad information vid lödning" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Tillåter BLE" - }, - "PowerLimit": { - "displayText": "Max-\neffekt", - "description": "Maximal effekt som enheten kan använda (Watt)" - }, - "CalibrateCJC": { - "displayText": "Kalibrera CJC\nnästa uppstart", - "description": "Vid nästa uppstart kommer spets Cold Junction Compensation kalibreras (ej nödvändigt om Delta T är < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Kalibrera\ninspänning?", - "description": "Inspänningskalibrering. Knapparna justerar, håll inne för avslut" - }, - "PowerPulsePower": { - "displayText": "Effekt\npuls", - "description": "Intensiteten av effekt för håll-vaken-puls (W=watt)" - }, - "PowerPulseWait": { - "displayText": "Effekt puls\nfördröjning", - "description": "Fördröjning innan håll-vaken-pulsen skickas (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Effekt puls\ntidsmängd", - "description": "Håll-vaken-puls varaktighet (x 250ms)" - }, - "SettingsReset": { - "displayText": "Fabriks-\ninställ?", - "description": "Återställ alla inställningar" - }, - "LanguageSwitch": { - "displayText": "Språk:\n SV Svenska", - "description": "" - } + "languageCode": "SV", + "languageLocalName": "Svenska", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibrering\nfärdig!" + }, + "ResetOKMessage": { + "message": "Återställning\nOK" + }, + "SettingsResetMessage": { + "message": "Inställningar\nåterställda" + }, + "NoAccelerometerMessage": { + "message": "Ingen\naccelerometer" + }, + "NoPowerDeliveryMessage": { + "message": "Ingen USB-PD IC\nhittades!" + }, + "LockingKeysString": { + "message": "LÅST" + }, + "UnlockingKeysString": { + "message": "UPPLÅST" + }, + "WarningKeysLockedString": { + "message": "!LÅST!" + }, + "WarningThermalRunaway": { + "message": "Termisk\nFlykt" + }, + "WarningTipShorted": { + "message": "!Spets Kortsluten!" + }, + "SettingsCalibrationWarning": { + "message": "Före omstart, säkerställ att spetsen och handtaget är i rumstemperatur!" + }, + "CJCCalibrating": { + "message": "kalibrerar\n" + }, + "SettingsResetWarning": { + "message": "Är du säker på att du vill återställa inställningarna?" + }, + "UVLOWarningString": { + "message": "DC LÅG" + }, + "UndervoltageString": { + "message": "Underspänning\n" + }, + "InputVoltageString": { + "message": "Inspän. V: \n" + }, + "SleepingAdvancedString": { + "message": "Viloläge...\n" + }, + "SleepingTipAdvancedString": { + "message": "Spets: \n" + }, + "ProfilePreheatString": { + "message": "Förvärmning\n" + }, + "ProfileCooldownString": { + "message": "Nedkyldning\n" + }, + "DeviceFailedValidationWarning": { + "message": "Din enhet är sannerligen oäkta!" + }, + "TooHotToStartProfileWarning": { + "message": "För varm för att\nstarta profilen!" + } + }, + "characters": { + "SettingRightChar": "H", + "SettingLeftChar": "V", + "SettingAutoChar": "A", + "SettingSlowChar": "L", + "SettingMediumChar": "M", + "SettingFastChar": "S", + "SettingStartSolderingChar": "L", + "SettingStartSleepChar": "V", + "SettingStartSleepOffChar": "R", + "SettingLockBoostChar": "T", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Effekt-\ninställning", + "description": "" + }, + "SolderingMenu": { + "displayText": "Lödnings-\ninställning", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Vilo-\nläge", + "description": "" + }, + "UIMenu": { + "displayText": "Användar-\ngränssnitt", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Avancerade\nalternativ", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Ström-\nkälla", + "description": "Strömkälla. Anger lägsta spänning. (DC 10V) (S 3.3V per cell)" + }, + "MinVolCell": { + "displayText": "Minimim-\nspänning", + "description": "Minimumspänning per cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\nspänning", + "description": "Maximal QC-spänning enheten skall efterfråga" + }, + "PDNegTimeout": { + "displayText": "PD\npauser", + "description": "PD förhandlings pauser i 100ms steg för kompatibilitet med vissa PD laddare" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "Slår på PPS & EPR lägen" + }, + "BoostTemperature": { + "displayText": "Turbo-\ntemp", + "description": "Temperatur i \"turbo-läge\"" + }, + "AutoStart": { + "displayText": "Auto\nstart", + "description": "Startar automatiskt lödpennan vid uppstart. (L=Lödning | V=Viloläge | R=Viloläge Rumstemperatur)" + }, + "TempChangeShortStep": { + "displayText": "Temp.just\nkorttryck", + "description": "Temperaturjustering vid kort knapptryckning" + }, + "TempChangeLongStep": { + "displayText": "Temp.just\nlångtryck", + "description": "Temperaturjustering vid lång knapptryckning" + }, + "LockingMode": { + "displayText": "Tillåt lås\nvia knappar", + "description": "Vid lödning, håll nere bägge knappar för att slå på lås (T=Bara turbo | F=Fullt lås)" + }, + "ProfilePhases": { + "displayText": "Profil-\nfaser", + "description": "Antal faser i profil läge" + }, + "ProfilePreheatTemp": { + "displayText": "Förvärmnings-\ntemp", + "description": "Förvärm till denna temperatur i början av provil läget" + }, + "ProfilePreheatSpeed": { + "displayText": "Förvärmnings-\nhastighet", + "description": "Förvärm enligt denna hastighet (grader per sekund)" + }, + "ProfilePhase1Temp": { + "displayText": "Fas 1\nTemp", + "description": "Måltemperatur i slutet av denna fas" + }, + "ProfilePhase1Duration": { + "displayText": "Fas 1\nTidslängd", + "description": "Mållängd av denna fasen (sekunder)" + }, + "ProfilePhase2Temp": { + "displayText": "Fas 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Fas 2\nTidslängd", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Fas 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Fas 3\nTidslängd", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Fas 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Fas 4\nTidslängd", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Fas 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Fas 5\nTidslängd", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Nedkylnings-\nhastighet", + "description": "Kyl ned i denna hastighet i slutet av profilen (grader per sekund)" + }, + "MotionSensitivity": { + "displayText": "Rörelse-\nkänslighet", + "description": "Rörelsekänslighet (1=minst känslig | ... | 9=mest känslig)" + }, + "SleepTemperature": { + "displayText": "Vilo-\ntemp", + "description": "Vilotemperatur (C)" + }, + "SleepTimeout": { + "displayText": "Vilo-\ntimeout", + "description": "Vilo-timeout (m=Minuter | s=Sekunder)" + }, + "ShutdownTimeout": { + "displayText": "Avstängn.\ntimeout", + "description": "Avstängnings-timeout (Minuter)" + }, + "HallEffSensitivity": { + "displayText": "Sensor-\nkänslght", + "description": "Känslighet för halleffekt-sensorn för viloläges-detektering (1=minst känslig | ... | 9=mest känslig)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval before \"sleep mode\" starts when hall effect is above threshold" + }, + "TemperatureUnit": { + "displayText": "Temperatur-\nenheter", + "description": "Temperaturenhet (C=Celsius | F=Fahrenheit)" + }, + "DisplayRotation": { + "displayText": "Visnings\nläge", + "description": "Visningsläge (H=Högerhänt | V=Vänsterhänt | A=Automatisk)" + }, + "CooldownBlink": { + "displayText": "Nedkylnings-\nblink", + "description": "Blinka temperaturen medan spetsen kyls av och fortfarande är varm." + }, + "ScrollingSpeed": { + "displayText": "Beskrivning\nrullhast.", + "description": "Hastighet som den här texten rullar i" + }, + "ReverseButtonTempChange": { + "displayText": "Omvända\n+- knappar", + "description": "Omvänd ordning för temperaturjustering via plus/minus knapparna" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.-\nhastighet", + "description": "Animationshastighet för ikoner i menyer (L=långsam | M=medel | S=snabb)" + }, + "AnimLoop": { + "displayText": "Anim.\nloop", + "description": "Loopa animationer i huvudmeny" + }, + "Brightness": { + "displayText": "Skärmens\nLjusstyrka", + "description": "Justera OLED skärmens ljusstyrka" + }, + "ColourInversion": { + "displayText": "Invertera\nskärm", + "description": "Invertera OLED skärmens färger" + }, + "LOGOTime": { + "displayText": "Start logo\nTidslängd", + "description": "Sätt uppstartslogotypens tidslängd (s=sekunder)" + }, + "AdvancedIdle": { + "displayText": "Detaljerad\nvid inaktiv", + "description": "Visa detaljerad information i mindre typsnitt när inaktiv." + }, + "AdvancedSoldering": { + "displayText": "Detaljerad\nlödng.skärm", + "description": "Visa detaljerad information vid lödning" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Tillåter BLE" + }, + "PowerLimit": { + "displayText": "Max-\neffekt", + "description": "Maximal effekt som enheten kan använda (Watt)" + }, + "CalibrateCJC": { + "displayText": "Kalibrera CJC\nnästa uppstart", + "description": "Vid nästa uppstart kommer spets Cold Junction Compensation kalibreras (ej nödvändigt om Delta T är < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Kalibrera\ninspänning?", + "description": "Inspänningskalibrering. Knapparna justerar, håll inne för avslut" + }, + "PowerPulsePower": { + "displayText": "Effekt\npuls", + "description": "Intensiteten av effekt för håll-vaken-puls (W=watt)" + }, + "PowerPulseWait": { + "displayText": "Effekt puls\nfördröjning", + "description": "Fördröjning innan håll-vaken-pulsen skickas (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Effekt puls\ntidsmängd", + "description": "Håll-vaken-puls varaktighet (x 250ms)" + }, + "SettingsReset": { + "displayText": "Fabriks-\ninställ?", + "description": "Återställ alla inställningar" + }, + "LanguageSwitch": { + "displayText": "Språk:\n SV Svenska", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_TR.json b/Translations/translation_TR.json index 34278c140..e5e4df361 100644 --- a/Translations/translation_TR.json +++ b/Translations/translation_TR.json @@ -1,319 +1,351 @@ { - "languageCode": "TR", - "languageLocalName": "Türkçe", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Sıfırlama Tamam" - }, - "SettingsResetMessage": { - "message": "Ayarlar\nSıfırlandı" - }, - "NoAccelerometerMessage": { - "message": "No accelerometer\ndetected!" - }, - "NoPowerDeliveryMessage": { - "message": "No USB-PD IC\ndetected!" - }, - "LockingKeysString": { - "message": "LOCKED" - }, - "UnlockingKeysString": { - "message": "UNLOCKED" - }, - "WarningKeysLockedString": { - "message": "!LOCKED!" - }, - "WarningThermalRunaway": { - "message": "Thermal\nRunaway" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Ayarları varsayılan değerlere sıfırlamak istediğinizden emin misiniz?" - }, - "UVLOWarningString": { - "message": "Güç Az" - }, - "UndervoltageString": { - "message": "Düşük Voltaj\n" - }, - "InputVoltageString": { - "message": "Giriş V: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Bekleme Modu...\n" - }, - "SleepingTipAdvancedString": { - "message": "Uç: \n" - }, - "OffString": { - "message": "Kapalı" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Your device is most likely a counterfeit!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "R", - "SettingLeftChar": "L", - "SettingAutoChar": "O", - "SettingOffChar": "K", - "SettingSlowChar": "Y", - "SettingMediumChar": "O", - "SettingFastChar": "H", - "SettingStartNoneChar": "K", - "SettingStartSolderingChar": "L", - "SettingStartSleepChar": "U", - "SettingStartSleepOffChar": "S", - "SettingLockDisableChar": "K", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Power\nsettings", - "description": "" - }, - "SolderingMenu": { - "displayText": "Lehimleme\nAyarları", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Uyku\nModları", - "description": "" - }, - "UIMenu": { - "displayText": "Kullanıcı\nArayüzü", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Gelişmiş\nAyarlar", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "GÇKYN\n", - "description": "\"Güç Kaynağı\". En düşük çalışma voltajını ayarlar. (DC 10V) (S 3.3V hücre başına)" - }, - "MinVolCell": { - "displayText": "Minimum\nvoltage", - "description": "Minimum allowed voltage per battery cell (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "QC\nvoltage", - "description": "Max QC voltage the iron should negotiate for" - }, - "PDNegTimeout": { - "displayText": "PD\ntimeout", - "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "YKSC\n", - "description": "Yüksek Performans Modu Sıcaklığı" - }, - "AutoStart": { - "displayText": "OTOBAŞ\n", - "description": "Güç verildiğinde otomatik olarak lehimleme modunda başlat. (K=Kapalı | L=Lehimleme Modu | U=Uyku Modu | S=Uyku Modu Oda Sıcaklığı)" - }, - "TempChangeShortStep": { - "displayText": "Temp change\nshort", - "description": "Kısa basışlardaki sıcaklık derecesi atlama oranı" - }, - "TempChangeLongStep": { - "displayText": "Temp change\nlong", - "description": "Uzun başışlardaki sıcaklık derecesi atlama oranı" - }, - "LockingMode": { - "displayText": "Allow locking\nbuttons", - "description": "While soldering, hold down both buttons to toggle locking them (K=Kapalı | B=boost mode only | F=full locking)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "HARHAS\n", - "description": "Hareket Hassasiyeti (0=Kapalı | 1=En az duyarlı | ... | 9=En duyarlı)" - }, - "SleepTemperature": { - "displayText": "BKSC\n", - "description": "Bekleme Modu Sıcaklığı (C)" - }, - "SleepTimeout": { - "displayText": "BMZA\n", - "description": "Bekleme Modu Zaman Aşımı (Dakika | Saniye)" - }, - "ShutdownTimeout": { - "displayText": "KPTZA\n", - "description": "Kapatma Zaman Aşımı (Dakika)" - }, - "HallEffSensitivity": { - "displayText": "Hall sensor\nsensitivity", - "description": "Sensitivity to magnets (0=Kapalı | 1=En az duyarlı | ... | 9=En duyarlı)" - }, - "TemperatureUnit": { - "displayText": "SCKBRM\n", - "description": "Sıcaklık Birimi (C=Celsius | F=Fahrenheit)" - }, - "DisplayRotation": { - "displayText": "GRNYÖN\n", - "description": "Görüntü Yönlendirme (R=Sağlak | L=Solak | O=Otomatik)" - }, - "CooldownBlink": { - "displayText": "SĞGÖST\n", - "description": "Soğutma ekranında uç hala sıcakken derece gösterilsin." - }, - "ScrollingSpeed": { - "displayText": "YZKYHZ\n", - "description": "Bu yazının kayma hızı (Y=Yavaş | H=Hızlı)" - }, - "ReverseButtonTempChange": { - "displayText": "Swap\n+ - keys", - "description": "\"Düğme Yerleri Rotasyonu\" Sıcaklık ayar düğmelerinin yerini değiştirin" - }, - "AnimSpeed": { - "displayText": "Anim.\nspeed", - "description": "Pace of icon animations in menu (K=Kapalı | Y=Yavaş | O=Orta | H=Hızlı)" - }, - "AnimLoop": { - "displayText": "Anim.\nloop", - "description": "Loop icon animations in main menu" - }, - "Brightness": { - "displayText": "Screen\nbrightness", - "description": "Adjust the OLED screen brightness" - }, - "ColourInversion": { - "displayText": "Invert\nscreen", - "description": "Invert the OLED screen colors" - }, - "LOGOTime": { - "displayText": "Boot logo\nduration", - "description": "Set boot logo duration (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "AYRBİL\n", - "description": "Boş ekranda ayrıntılı bilgileri daha küçük bir yazı tipi ile göster." - }, - "AdvancedSoldering": { - "displayText": "GELLHM\n", - "description": "\"Gelişmiş Lehimleme\" Lehimleme yaparken detaylı bilgi göster" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Power\nlimit", - "description": "Havyanın kullanacağı en yüksek güç (W=Watts)" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nat next boot", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "VOL KAL?\n", - "description": "Voltaj Girişi Kalibrasyonu. Düğmeler ayarlar, çıkmak için uzun bas." - }, - "PowerPulsePower": { - "displayText": "Power\npulse", - "description": "Güç girişi voltajı ölçüm yoğunluğunu sık tut." - }, - "PowerPulseWait": { - "displayText": "Power pulse\ndelay", - "description": "Delay before keep-awake-pulse is triggered (x 2.5s)" - }, - "PowerPulseDuration": { - "displayText": "Power pulse\nduration", - "description": "Keep-awake-pulse duration (x 250ms)" - }, - "SettingsReset": { - "displayText": "SIFIRLA?\n", - "description": "Bütün ayarları sıfırlar" - }, - "LanguageSwitch": { - "displayText": "Dil:\n TR Türkçe", - "description": "" - } + "languageCode": "TR", + "languageLocalName": "Türkçe", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibrasyon\ntamam!" + }, + "ResetOKMessage": { + "message": "Sıfırlama Tamam" + }, + "SettingsResetMessage": { + "message": "Ayarlar\nSıfırlandı" + }, + "NoAccelerometerMessage": { + "message": "İvme sensörü\ntespit edilmedi!" + }, + "NoPowerDeliveryMessage": { + "message": "USB-PD IC\ntespit edilmedi!" + }, + "LockingKeysString": { + "message": "KİLİTLİ" + }, + "UnlockingKeysString": { + "message": "KİLİT AÇIK" + }, + "WarningKeysLockedString": { + "message": "!KİLİTLİ!" + }, + "WarningThermalRunaway": { + "message": "Termal\nKaçak" + }, + "WarningTipShorted": { + "message": "!Uç Kısa Devre!" + }, + "SettingsCalibrationWarning": { + "message": "Yeniden başlatmadan önce uç ve sapın oda sıcaklığında olduğundan emin olun!" + }, + "CJCCalibrating": { + "message": "kalibre ediliyor\n" + }, + "SettingsResetWarning": { + "message": "Ayarları varsayılan değerlere sıfırlamak istediğinizden emin misiniz?" + }, + "UVLOWarningString": { + "message": "Güç Az" + }, + "UndervoltageString": { + "message": "Düşük Voltaj\n" + }, + "InputVoltageString": { + "message": "Giriş V: \n" + }, + "SleepingAdvancedString": { + "message": "Bekleme Modu...\n" + }, + "SleepingTipAdvancedString": { + "message": "Uç: \n" + }, + "ProfilePreheatString": { + "message": "Ön Isıtma\n" + }, + "ProfileCooldownString": { + "message": "Soğuma\n" + }, + "DeviceFailedValidationWarning": { + "message": "Cihazınız büyük olasılıkla sahte!" + }, + "TooHotToStartProfileWarning": { + "message": "Profil başlatmak için\nçok sıcak" + } + }, + "characters": { + "SettingRightChar": "R", + "SettingLeftChar": "L", + "SettingAutoChar": "O", + "SettingSlowChar": "Y", + "SettingMediumChar": "O", + "SettingFastChar": "H", + "SettingStartSolderingChar": "L", + "SettingStartSleepChar": "U", + "SettingStartSleepOffChar": "S", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Güç\nAyarları", + "description": "" + }, + "SolderingMenu": { + "displayText": "Lehimleme\nAyarları", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Uyku\nModları", + "description": "" + }, + "UIMenu": { + "displayText": "Kullanıcı\nArayüzü", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Gelişmiş\nAyarlar", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "GÇKYN\n", + "description": "\"Güç Kaynağı\". En düşük çalışma voltajını ayarlar. (DC 10V) (S 3.3V hücre başına)" + }, + "MinVolCell": { + "displayText": "Minimum\nVoltaj", + "description": "Pil hücresi başına izin verilen minimum voltaj (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\nvoltajı", + "description": "Max istenecek QC voltajı" + }, + "PDNegTimeout": { + "displayText": "PD\nTimeout", + "description": "Bazı QC şarj cihazlarıyla uyumluluk için 100ms adımlarında PD pazarlık zaman aşımı" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "PPS & EPR modlarını etkinleştirir" + }, + "BoostTemperature": { + "displayText": "YKSC\n", + "description": "Yüksek Performans Modu Sıcaklığı" + }, + "AutoStart": { + "displayText": "OTOBAŞ\n", + "description": "Güç verildiğinde otomatik olarak lehimleme modunda başlat. (L=Lehimleme Modu | U=Uyku Modu | S=Uyku Modu Oda Sıcaklığı)" + }, + "TempChangeShortStep": { + "displayText": "Sıcaklık değişimi\nkısa", + "description": "Kısa basışlardaki sıcaklık derecesi atlama oranı" + }, + "TempChangeLongStep": { + "displayText": "Sıcaklık değişimi\nuzun", + "description": "Uzun başışlardaki sıcaklık derecesi atlama oranı" + }, + "LockingMode": { + "displayText": "Kilitleme\nİzni", + "description": "Lehimleme sırasında, her iki düğmeye basılı tutarak kilitleme modunu değiştirin (B=Sadece performans modu | F=tam kilit)" + }, + "ProfilePhases": { + "displayText": "Profil\nAşamaları", + "description": "Profil modundaki aşamaların sayısı" + }, + "ProfilePreheatTemp": { + "displayText": "Ön Isıtma\nSıcaklık", + "description": "Profil modunun başlangıcında bu sıcaklığa kadar ön ısıtma yapar" + }, + "ProfilePreheatSpeed": { + "displayText": "Ön Isıtma\nHızı", + "description": "Bu hızda ön ısıtma yapın (saniye başına derece)" + }, + "ProfilePhase1Temp": { + "displayText": "Aşama 1\nSıcaklık", + "description": "Bu aşamanın sonunda hedeflenen sıcaklık" + }, + "ProfilePhase1Duration": { + "displayText": "Aşama 1\nSüre", + "description": "Bu aşamanın hedef süresi (saniye)" + }, + "ProfilePhase2Temp": { + "displayText": "Aşama 2\nSıcaklık", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Aşama 2\nSüre", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Aşama 3\nSıcaklık", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Aşama 3\nSüre", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Aşama 4\nSıcaklık", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Aşama 4\nSüre", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Aşama 5\nSıcaklık", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Aşama 5\nSüre", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Soğuma\nHızı", + "description": "Profil modunun sonunda bu hızda soğuma yapın (saniye başına derece)" + }, + "MotionSensitivity": { + "displayText": "HARHAS\n", + "description": "Hareket Hassasiyeti (1=En az duyarlı | ... | 9=En duyarlı)" + }, + "SleepTemperature": { + "displayText": "BKSC\n", + "description": "Bekleme Modu Sıcaklığı (C)" + }, + "SleepTimeout": { + "displayText": "BMZA\n", + "description": "Bekleme Modu Zaman Aşımı (Dakika | Saniye)" + }, + "ShutdownTimeout": { + "displayText": "KPTZA\n", + "description": "Kapatma Zaman Aşımı (Dakika)" + }, + "HallEffSensitivity": { + "displayText": "Hall Sensör\nHassasiyeti", + "description": "Mıknatıslara duyarlılık (1=En az duyarlı | ... | 9=En duyarlı)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Hall etkisi eşiğin üzerinde olduğunda \"uyku modu\" başlamadan önceki aralık" + }, + "TemperatureUnit": { + "displayText": "SCKBRM\n", + "description": "Sıcaklık Birimi (C=Celsius | F=Fahrenheit)" + }, + "DisplayRotation": { + "displayText": "GRNYÖN\n", + "description": "Görüntü Yönlendirme (R=Sağlak | L=Solak | O=Otomatik)" + }, + "CooldownBlink": { + "displayText": "SĞGÖST\n", + "description": "Soğutma ekranında uç hala sıcakken derece gösterilsin." + }, + "ScrollingSpeed": { + "displayText": "YZKYHZ\n", + "description": "Bu yazının kayma hızı (Y=Yavaş | H=Hızlı)" + }, + "ReverseButtonTempChange": { + "displayText": "Düğme Yerleri\nRotasyonu", + "description": "\"Düğme Yerleri Rotasyonu\" Sıcaklık ayar düğmelerinin yerini değiştirin" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Animasyon\nHızı", + "description": "Menüdeki simge animasyonlarının hızı (Y=Yavaş | O=Orta | H=Hızlı)" + }, + "AnimLoop": { + "displayText": "Animasyon\nDöngüsü", + "description": "Ana menüde simge animasyonlarının döngüsü" + }, + "Brightness": { + "displayText": "Ekran\nparlaklığı", + "description": "OLED ekran parlaklığını ayarlar" + }, + "ColourInversion": { + "displayText": "Ekran\nRenkleri", + "description": "OLED ekran renklerini ters çevir" + }, + "LOGOTime": { + "displayText": "Boot Logo\nSüresi", + "description": "Boot logo süresi (s=saniye)" + }, + "AdvancedIdle": { + "displayText": "AYRBİL\n", + "description": "Boş ekranda ayrıntılı bilgileri daha küçük bir yazı tipi ile göster." + }, + "AdvancedSoldering": { + "displayText": "GELLHM\n", + "description": "\"Gelişmiş Lehimleme\" Lehimleme yaparken detaylı bilgi göster" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Bluetooth LE'yi etkinleştirir" + }, + "PowerLimit": { + "displayText": "Güç\nlimiti", + "description": "Havyanın kullanacağı en yüksek güç (W=Watts)" + }, + "CalibrateCJC": { + "displayText": "CJC Kalibrasyonu\nSonraki Boot'ta", + "description": "Sonraki boot'ta uç Soğuk Nokta Kompansasyonu kalibre edilecek (Delta T < 5°C ise gerekmez)" + }, + "VoltageCalibration": { + "displayText": "VOL KAL?\n", + "description": "Voltaj Girişi Kalibrasyonu. Düğmeler ayarlar, çıkmak için uzun bas." + }, + "PowerPulsePower": { + "displayText": "Güç\nDarbeleri", + "description": "Güç girişi voltajı ölçüm yoğunluğunu sık tut." + }, + "PowerPulseWait": { + "displayText": "Güç Darbesi\nGecikmesi", + "description": "Uyanık tutma darbesinin tetiklenmeden önceki gecikme süresi (x 2.5s)" + }, + "PowerPulseDuration": { + "displayText": "Güç Darbesi\nSüresi", + "description": "Uyanık tutma darbesi süresi (x 250ms)" + }, + "SettingsReset": { + "displayText": "SIFIRLA?\n", + "description": "Bütün ayarları sıfırlar" + }, + "LanguageSwitch": { + "displayText": "Dil:\n TR Türkçe", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_UK.json b/Translations/translation_UK.json index 4da1441f4..e5b035fe8 100644 --- a/Translations/translation_UK.json +++ b/Translations/translation_UK.json @@ -1,319 +1,351 @@ { - "languageCode": "UK", - "languageLocalName": "Українська", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "КХС\nвідкалібровано!" - }, - "ResetOKMessage": { - "message": "Скид. OK" - }, - "SettingsResetMessage": { - "message": "Налаштування\nскинуті!" - }, - "NoAccelerometerMessage": { - "message": "Акселерометр\nне виявлено!" - }, - "NoPowerDeliveryMessage": { - "message": "USB-PD IC\nне виявлено!" - }, - "LockingKeysString": { - "message": "ЗАБЛОК." - }, - "UnlockingKeysString": { - "message": "РОЗБЛОК." - }, - "WarningKeysLockedString": { - "message": "!ЗАБЛОК!" - }, - "WarningThermalRunaway": { - "message": "Некерований\nрозігрів" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Під час наступного завантаження переконайтеся, що жало і ручка мають кімнатну температуру!" - }, - "CJCCalibrating": { - "message": "калібрування\n" - }, - "SettingsResetWarning": { - "message": "Ви дійсно хочете скинути налаштування до значень за замовчуванням? (A=Так, В=Ні)" - }, - "UVLOWarningString": { - "message": "АККУМ--" - }, - "UndervoltageString": { - "message": "Низька напруга\n" - }, - "InputVoltageString": { - "message": "Жив.(B): \n" - }, - "SleepingSimpleString": { - "message": "ZzZzz" - }, - "SleepingAdvancedString": { - "message": "Очікування...\n" - }, - "SleepingTipAdvancedString": { - "message": "Жало: \n" - }, - "OffString": { - "message": "Вимк" - }, - "ProfilePreheatString": { - "message": "Попередній\nрозігрів" - }, - "ProfileCooldownString": { - "message": "Охолодження\n" - }, - "DeviceFailedValidationWarning": { - "message": "Вірогідно ваш пристрій підробний!" - }, - "TooHotToStartProfileWarning": { - "message": "Занадто гараче для\nзміни профілів" - } - }, - "characters": { - "SettingRightChar": "П", - "SettingLeftChar": "Л", - "SettingAutoChar": "A", - "SettingOffChar": "B", - "SettingSlowChar": "Н", - "SettingMediumChar": "С", - "SettingFastChar": "М", - "SettingStartNoneChar": "В", - "SettingStartSolderingChar": "П", - "SettingStartSleepChar": "О", - "SettingStartSleepOffChar": "К", - "SettingLockDisableChar": "В", - "SettingLockBoostChar": "Т", - "SettingLockFullChar": "П" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Параметри\nживлення", - "description": "" - }, - "SolderingMenu": { - "displayText": "Параметри\nпайки", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Режим\nсну", - "description": "" - }, - "UIMenu": { - "displayText": "Параметри\nінтерфейсу", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Додаткові\nпараметри", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Джерело\nживлення", - "description": "Встановлює напругу відсічки. (DC - 10V) (3S - 9.9V | 4S - 13.2V | 5S - 16.5V | 6S - 19.8V)" - }, - "MinVolCell": { - "displayText": "Мін.\nнапруга", - "description": "Мінімальна дозволена напруга на комірку (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" - }, - "QCMaxVoltage": { - "displayText": "Потужність\nдж. живлення", - "description": "Потужність джерела живлення в Ватах" - }, - "PDNegTimeout": { - "displayText": "PD\nзатримка", - "description": "Затримка у 100мс інкрементах для PD для сумісності з деякими QC зарядними пристроями (0: вимкнено)" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Вмикає режими PPS & EPR." - }, - "BoostTemperature": { - "displayText": "Темпер.\nТурбо", - "description": "Температура в \"Турбо\" режимі" - }, - "AutoStart": { - "displayText": "Гарячий\nстарт", - "description": "Режим в якому запускається паяльник при ввімкненні (В=Вимк. | П=Пайка | О=Очікування | К=Очікування при кімн. темп.)" - }, - "TempChangeShortStep": { - "displayText": "Зміна темп.\nкоротко?", - "description": "Змінювати температуру при короткому натисканні!" - }, - "TempChangeLongStep": { - "displayText": "Зміна темп.\nдовго?", - "description": "Змінювати температуру при довгому натисканні!" - }, - "LockingMode": { - "displayText": "Дозволити\nблок. кнопок", - "description": "Під час пайки тривале натискання обох кнопок заблокує їх (В=Вимк | Т=Тільки турбо | П=Повне)" - }, - "ProfilePhases": { - "displayText": "Етапи\nпрофілів", - "description": "Кількість етапів в режимі профілів" - }, - "ProfilePreheatTemp": { - "displayText": "Температура\nПоп.Розігріву", - "description": "Попередньо розігріти до цієї температури на початку режимку профілів" - }, - "ProfilePreheatSpeed": { - "displayText": "Швидкість\nПоп.Розігріву", - "description": "Розігрівати з такою швидкістю (градусів в секунду)" - }, - "ProfilePhase1Temp": { - "displayText": "Етап 1\nТемпература", - "description": "Температура в кінці цього етапу" - }, - "ProfilePhase1Duration": { - "displayText": "Етап 1\nТривалість", - "description": "Тривалість цього етапу (секунд)" - }, - "ProfilePhase2Temp": { - "displayText": "Етап 2\nТемпература", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Етап 2\nТривалість", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Етап 3\nТемпература", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Етап 3\nТривалість", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Етап 4\nТемпература", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Етап 4\nТривалість", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Етап 5\nТемпература", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Етап 5\nТривалість", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Швидкість\nОхолодження", - "description": "Швидкість охолодження в кінці режиму профілів (градусів в секунду)" - }, - "MotionSensitivity": { - "displayText": "Чутливість\nсенсору руху", - "description": "Акселерометр (0=Вимк. | 1=мін. чутливості | ... | 9=макс. чутливості)" - }, - "SleepTemperature": { - "displayText": "Темпер.\nсну", - "description": "Температура режиму очікування (C° | F°)" - }, - "SleepTimeout": { - "displayText": "Тайм-аут\nсну", - "description": "Час до переходу в режим очікування (Хвилини | Секунди)" - }, - "ShutdownTimeout": { - "displayText": "Часу до\nвимкнення", - "description": "Час до вимкнення (Хвилини)" - }, - "HallEffSensitivity": { - "displayText": "Чутливість\nЕфекту Холла", - "description": "Чутливість датчика ефекту Холла при виявленні сну (0=Вимк. | 1=мін. чутливості | ... | 9=макс. чутливості)" - }, - "TemperatureUnit": { - "displayText": "Формат темпе-\nратури(C°/F°)", - "description": "Одиниця виміру температури (C=Цельсій | F=Фаренгейт)" - }, - "DisplayRotation": { - "displayText": "Автоповорот\nекрану", - "description": "Орієнтація дисплея (П=Правша | Л=Лівша | A=Автоповорот)" - }, - "CooldownBlink": { - "displayText": "Показ t° при\nохолодженні", - "description": "Показувати температуру на екрані охолодження, поки жало залишається гарячим, при цьому екран моргає" - }, - "ScrollingSpeed": { - "displayText": "Швидкість\nтексту", - "description": "Швидкість прокрутки тексту (Н=Низькa | М=Максимальна)" - }, - "ReverseButtonTempChange": { - "displayText": "Інвертувати\nкнопки +-?", - "description": "Інвертувати кнопки зміни температури." - }, - "AnimSpeed": { - "displayText": "Швидкість\nанімації", - "description": "Швидкість анімації іконок у головному меню (В=Вимк | Н=Низькa | С=Середня | М=Максимальна)" - }, - "AnimLoop": { - "displayText": "Циклічна\nанімація", - "description": "Циклічна анімація іконок в головному меню" - }, - "Brightness": { - "displayText": "Яскравість\nекрану", - "description": "Налаштування контрасту/яскравості OLED екрану" - }, - "ColourInversion": { - "displayText": "Інверт\nекрану", - "description": "Інвертувати кольори на OLED екрані" - }, - "LOGOTime": { - "displayText": "Тривалість\nлоготипу завантаження", - "description": "Встановити тривалість показу лого при завантаженні (с=секунд)" - }, - "AdvancedIdle": { - "displayText": "Детальний ре-\nжим очікуван.", - "description": "Показувати детальну інформацію маленьким шрифтом на домашньому екрані" - }, - "AdvancedSoldering": { - "displayText": "Детальний\nрежим пайки", - "description": "Показувати детальну інформацію при пайці." - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Увімкнути BLE" - }, - "PowerLimit": { - "displayText": "Макс.\nпотуж.", - "description": "Макс. потужність, яку може використовувати паяльник (Ват)" - }, - "CalibrateCJC": { - "displayText": "Калібрувати КХС\nпри наступному завантаженні", - "description": "При наступному завантаження буде відкалібровано Компенсацію Холодного Спаю жала (непотрібне при різниці температур < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Калібрування\nнапруги", - "description": "Калібрування напруги входу. Налаштувати кнопками, натиснути і утримати щоб завершити." - }, - "PowerPulsePower": { - "displayText": "Пульс.\nНавантаж.", - "description": "Деякі PowerBank-и з часом вимк. живлення, якщо пристрій споживає дуже мало енергії)" - }, - "PowerPulseWait": { - "displayText": "Час між імп.\nнапруги", - "description": "Час між імпульсами напруги яка не дає PowerBank-у заснути (x 2.5с)" - }, - "PowerPulseDuration": { - "displayText": "Тривалість\nімп. напруги", - "description": "Тривалість імпульсу напруги яка не дає PowerBank-у заснути (x 250мс)" - }, - "SettingsReset": { - "displayText": "Скинути всі\nналаштування?", - "description": "Скидання всіх параметрів до стандартних значень." - }, - "LanguageSwitch": { - "displayText": "Мова:\n UK Українська", - "description": "" - } + "languageCode": "UK", + "languageLocalName": "Українська", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "КХС\nвідкалібровано!" + }, + "ResetOKMessage": { + "message": "Скид. OK" + }, + "SettingsResetMessage": { + "message": "Налаштування\nскинуті!" + }, + "NoAccelerometerMessage": { + "message": "Акселерометр\nне виявлено!" + }, + "NoPowerDeliveryMessage": { + "message": "USB-PD IC\nне виявлено!" + }, + "LockingKeysString": { + "message": "ЗАБЛОК." + }, + "UnlockingKeysString": { + "message": "РОЗБЛОК." + }, + "WarningKeysLockedString": { + "message": "!ЗАБЛОК!" + }, + "WarningThermalRunaway": { + "message": "Некерований\nрозігрів" + }, + "WarningTipShorted": { + "message": "!Жало закорочено!" + }, + "SettingsCalibrationWarning": { + "message": "Під час наступного завантаження переконайтеся, що жало і ручка мають кімнатну температуру!" + }, + "CJCCalibrating": { + "message": "калібрування\n" + }, + "SettingsResetWarning": { + "message": "Ви дійсно хочете скинути налаштування до значень за замовчуванням? (A=Так, В=Ні)" + }, + "UVLOWarningString": { + "message": "АККУМ--" + }, + "UndervoltageString": { + "message": "Низька напруга\n" + }, + "InputVoltageString": { + "message": "Жив.(B): \n" + }, + "SleepingAdvancedString": { + "message": "Сон...\n" + }, + "SleepingTipAdvancedString": { + "message": "Жало: \n" + }, + "ProfilePreheatString": { + "message": "Попередній\nрозігрів" + }, + "ProfileCooldownString": { + "message": "Охолодження\n" + }, + "DeviceFailedValidationWarning": { + "message": "Вірогідно ваш пристрій підробний!" + }, + "TooHotToStartProfileWarning": { + "message": "Занадто гараче для\nзміни профілів" + } + }, + "characters": { + "SettingRightChar": "П", + "SettingLeftChar": "Л", + "SettingAutoChar": "A", + "SettingSlowChar": "Н", + "SettingMediumChar": "С", + "SettingFastChar": "М", + "SettingStartSolderingChar": "П", + "SettingStartSleepChar": "С", + "SettingStartSleepOffChar": "К", + "SettingLockBoostChar": "Т", + "SettingLockFullChar": "П" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Параметри\nживлення", + "description": "" + }, + "SolderingMenu": { + "displayText": "Параметри\nпайки", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Режим сну\n", + "description": "" + }, + "UIMenu": { + "displayText": "Параметри\nінтерфейсу", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Додаткові\nпараметри", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Режим\nЗамовчуванню" + }, + "USBPDModeNoDynamic": { + "displayText": "Без\nДинамічного" + }, + "USBPDModeSafe": { + "displayText": "Безпечний\nРежим" + }, + "TipTypeAuto": { + "displayText": "Авто\nВизначення" + }, + "TipTypeT12Long": { + "displayText": "TS100\nДовге" + }, + "TipTypeT12Short": { + "displayText": "Pine\nКоротке" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Джерело\nживлення", + "description": "Встановлює напругу відсічки. (DC - 10V) (3S - 9.9V | 4S - 13.2V | 5S - 16.5V | 6S - 19.8V)" + }, + "MinVolCell": { + "displayText": "Мін.\nнапруга", + "description": "Мінімальна дозволена напруга на комірку (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "Потужність\nдж. живлення", + "description": "Потужність ДЖ в Ватах" + }, + "PDNegTimeout": { + "displayText": "PD\nЗатримка", + "description": "Затримка у 100мс інкрементах для PD для сумісності з деякими версіями QC (0: вимкнена)" + }, + "USBPDMode": { + "displayText": "PD\nРежим", + "description": "Вмикає режими PPS & EPR." + }, + "BoostTemperature": { + "displayText": "Темпер.\nТурбо", + "description": "Температура \"Турбо\" режиму" + }, + "AutoStart": { + "displayText": "Гарячий\nстарт", + "description": "Режим запуску паяльника (П=Пайка | С=Сон | К=Сон при кімн. темп.)" + }, + "TempChangeShortStep": { + "displayText": "Зміна темп.\nкоротким", + "description": "Зміна температуру при короткому натисканні!" + }, + "TempChangeLongStep": { + "displayText": "Зміна темп.\nдовгим", + "description": "Зміна температуру при довгому натисканні!" + }, + "LockingMode": { + "displayText": "Дозволити\nблок. кнопок", + "description": "Під час пайки тривале натискання обох кнопок заблокує їх (Т=Тільки турбо | П=Повне)" + }, + "ProfilePhases": { + "displayText": "Етапи\nпрофілів", + "description": "Кількість етапів в режимі профілів" + }, + "ProfilePreheatTemp": { + "displayText": "Температура\nПоп.Розігріву", + "description": "Попередньо розігріти до цієї температури на початку режимку профілів" + }, + "ProfilePreheatSpeed": { + "displayText": "Швидкість\nПоп.Розігріву", + "description": "Розігрівати з швидкістю (t° у сек)" + }, + "ProfilePhase1Temp": { + "displayText": "Етап 1\nТемпература", + "description": "Температура на кінці цього етапу" + }, + "ProfilePhase1Duration": { + "displayText": "Етап 1\nТривалість", + "description": "Тривалість цього етапу (сек)" + }, + "ProfilePhase2Temp": { + "displayText": "Етап 2\nТемпература", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Етап 2\nТривалість", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Етап 3\nТемпература", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Етап 3\nТривалість", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Етап 4\nТемпература", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Етап 4\nТривалість", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Етап 5\nТемпература", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Етап 5\nТривалість", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Швидкість\nОхолодження", + "description": "Швидкість охолодження на кінці режиму профілів (t° у сек)" + }, + "MotionSensitivity": { + "displayText": "Чутливість\nдатчику руху", + "description": "Акселерометр (1=мін. чутливості | ... | 9=макс. чутливість)" + }, + "SleepTemperature": { + "displayText": "Темпер.\nсну", + "description": "Температура режиму сну (C° | F°)" + }, + "SleepTimeout": { + "displayText": "Тайм-аут\nсну", + "description": "Час до переходу до сну (Хв | Сек)" + }, + "ShutdownTimeout": { + "displayText": "Часу до\nвимкнення", + "description": "Час до вимкнення (Хв)" + }, + "HallEffSensitivity": { + "displayText": "Чутливість\nДатчику Холла", + "description": "Чутливість датчика Холла при виявленні сну (1=мін. чутливість | ... | 9=макс. чутливість)" + }, + "HallEffSleepTimeout": { + "displayText": "Датчик Холла\nЧас сну", + "description": "Проміжок часу до \"часу сну\" за умови спрацювання датчику Холла" + }, + "TemperatureUnit": { + "displayText": "Формат темпе-\nратури(C°/F°)", + "description": "Одиниця виміру температури (C=Цельсій | F=Фаренгейт)" + }, + "DisplayRotation": { + "displayText": "Обертання\nекрану", + "description": "Орієнтація екрану (П=Правша | Л=Лівша | A=Автооберт.)" + }, + "CooldownBlink": { + "displayText": "Показ t° при\nохолодженні", + "description": "Показувати температуру на екрані охолодження, поки жало залишається гарячим, при цьому екран мерехтить" + }, + "ScrollingSpeed": { + "displayText": "Швидкість\nтексту", + "description": "Швидкість прокрутки тексту (Н=Низькa | М=Максимальна)" + }, + "ReverseButtonTempChange": { + "displayText": "Інвертувати\nкнопки +-?", + "description": "Інвертувати кнопки зміни температури." + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Швидкість\nанімації", + "description": "Швидкість анімації іконок у меню (Н=Низькa | С=Середня | М=Максимальна)" + }, + "AnimLoop": { + "displayText": "Циклічна\nанімація", + "description": "Циклічна анімація іконок у меню" + }, + "Brightness": { + "displayText": "Яскравість\nекрану", + "description": "Налаштування контрасту/яскравості OLED екрану" + }, + "ColourInversion": { + "displayText": "Інверт\nекрану", + "description": "Інвертувати кольори на OLED екрані" + }, + "LOGOTime": { + "displayText": "Тривалість\nлоготипу при запуску", + "description": "Поточна тривалість показу лого при запуску (сек)" + }, + "AdvancedIdle": { + "displayText": "Детальний ре-\nжим очікуван.", + "description": "Показувати детальну інформацію маленьким шрифтом на домашньому екрані" + }, + "AdvancedSoldering": { + "displayText": "Детальний\nрежим пайки", + "description": "Показувати детальну інформацію при пайці." + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Увімкнути BLE" + }, + "PowerLimit": { + "displayText": "Макс.\nпотуж.", + "description": "Макс. потужність, яку може використовувати паяльник (Ватт)" + }, + "CalibrateCJC": { + "displayText": "Калібрувати КХС\nпри наступному запуску", + "description": "При наступному запуску буде відкалібровано Компенсацію Холодного Спаю жала (непотрібне при різниці температур < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Калібрування\nнапруги", + "description": "Калібрування напруги входу. Налаштувати кнопками, натиснути і утримати щоб завершити." + }, + "PowerPulsePower": { + "displayText": "Пульс.\nНавантаж.", + "description": "Деякі PowerBank-и з часом вимк. живлення, якщо пристрій споживає дуже мало енергії)" + }, + "PowerPulseWait": { + "displayText": "Час між імп.\nнапруги", + "description": "Час між імпульсами напруги яка не дає PowerBank-у заснути (x 2.5с)" + }, + "PowerPulseDuration": { + "displayText": "Тривалість\nімп. напруги", + "description": "Тривалість імпульсу напруги яка не дає PowerBank-у заснути (x 250мс)" + }, + "SettingsReset": { + "displayText": "Скинути всі\nналаштування?", + "description": "Скидання всіх параметрів до стандартних значень." + }, + "LanguageSwitch": { + "displayText": "Мова:\n UK Українська", + "description": "" + }, + "SolderingTipType": { + "displayText": "Тип Жала", + "description": "Оберіть відповідний тип жала" } + } } diff --git a/Translations/translation_UZ.json b/Translations/translation_UZ.json new file mode 100644 index 000000000..9d3dc231b --- /dev/null +++ b/Translations/translation_UZ.json @@ -0,0 +1,351 @@ +{ + "languageCode": "UZ", + "languageLocalName": "O'zbek", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Kalibrovka\nyakunlandi!" + }, + "ResetOKMessage": { + "message": "Sozlamalar\ntiklandi" + }, + "SettingsResetMessage": { + "message": "Ayrim sozlamalar\no'zgartirildi" + }, + "NoAccelerometerMessage": { + "message": "Akselerometr\ntopilmadi!" + }, + "NoPowerDeliveryMessage": { + "message": "USB-PD IC\ntopilmadi!" + }, + "LockingKeysString": { + "message": "QULFLANDI" + }, + "UnlockingKeysString": { + "message": "QULF OCHILDI" + }, + "WarningKeysLockedString": { + "message": "!QULFLANGAN!" + }, + "WarningThermalRunaway": { + "message": "Issiqlik\nqochishi" + }, + "WarningTipShorted": { + "message": "!Uchida qisqa tutashuv!" + }, + "SettingsCalibrationWarning": { + "message": "Qayta yuklashdan oldin, uchi va tutqich xona haroratida ekanligiga ishonch hosil qiling!" + }, + "CJCCalibrating": { + "message": "Kalibrovka\nqilinmoqda" + }, + "SettingsResetWarning": { + "message": "Sozlamalarni standart holatga qaytarishni istaysizmi?" + }, + "UVLOWarningString": { + "message": "DC PAST" + }, + "UndervoltageString": { + "message": "Past kuchlanish\n" + }, + "InputVoltageString": { + "message": "Kirish kuchlanishi: \n" + }, + "SleepingAdvancedString": { + "message": "Uyqu holati...\n" + }, + "SleepingTipAdvancedString": { + "message": "Uch: \n" + }, + "ProfilePreheatString": { + "message": "Qizdirish\n" + }, + "ProfileCooldownString": { + "message": "Sovutish\n" + }, + "DeviceFailedValidationWarning": { + "message": "Qurilmangiz soxta bo'lishi mumkin!" + }, + "TooHotToStartProfileWarning": { + "message": "Profilni boshlash uchun\njuda issiq" + } + }, + "characters": { + "SettingRightChar": "O", + "SettingLeftChar": "C", + "SettingAutoChar": "A", + "SettingSlowChar": "S", + "SettingMediumChar": "O", + "SettingFastChar": "T", + "SettingStartSolderingChar": "P", + "SettingStartSleepChar": "U", + "SettingStartSleepOffChar": "X", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "T" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Quvvat\nsozlamalari", + "description": "" + }, + "SolderingMenu": { + "displayText": "Paylash\nsozlamalari", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Uyqu\nrejimi", + "description": "" + }, + "UIMenu": { + "displayText": "Foydalanuvchi\ninterfeysi", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Kengaytirilgan\nsozlamalar", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Quvvat\nmanbai", + "description": "Batareya haddan tashqari zaryadsizlanishini oldini olish uchun kuchlanish chegarasini o'rnatish (DC 10V) (S=3.3V har bir yacheyka uchun, quvvat PWR chegarasini o'chirish)" + }, + "MinVolCell": { + "displayText": "Minimal\nkuchlanish", + "description": "Batareya yacheyka uchun minimal ruxsat etilgan kuchlanish (3S: 3 - 3.7V | 4-6S: 2.4 - 3.7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\nvoltage", + "description": "Max QC voltage the iron should negotiate for" + }, + "PDNegTimeout": { + "displayText": "PD\ntimeout", + "description": "PD negotiation timeout in 100ms steps for compatibility with some QC chargers" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Kuchaytirish\nharorati", + "description": "\"Boost mode\" rejimida uch harorati" + }, + "AutoStart": { + "displayText": "Boshlash\nholati", + "description": "P=paylash temperaturasigacha qizdirish | U=qo'zg'atilmagunicha uyqu rejimida ushlash | X=qo'zg'atilmagunicha qizdirilmagan holda ushlash" + }, + "TempChangeShortStep": { + "displayText": "Tugmaning qisqa\nbosilishi", + "description": "Qisqa bosilgandagi harorat o'zgarishi-oshirish" + }, + "TempChangeLongStep": { + "displayText": "Tugmaning uzoqroq\nbosilishi", + "description": "Uzoqroq bosilgandagi harorat o'zgarishi-oshirish" + }, + "LockingMode": { + "displayText": "Tugmalarni qulflashni\nfaollashtirish", + "description": "Qulflash uchun paylash davomida ikkala tugmani bosib turing (B=faqat boost mode uchun | T=to'liq qulflash)" + }, + "ProfilePhases": { + "displayText": "Profil\nbosqichlari", + "description": "Profil rejimlarida bosqichlar soni" + }, + "ProfilePreheatTemp": { + "displayText": "Dastlabgi\nHarorat", + "description": "Profil rejimida dastlab ushbu haroratga qizdirish" + }, + "ProfilePreheatSpeed": { + "displayText": "Qizdirish\nTezligi", + "description": "Ushbu tezlikda qizdirish (1 sekundda shuncha daraja)" + }, + "ProfilePhase1Temp": { + "displayText": "1-faza\nHarorati", + "description": "Bu fazaning oxirida mo'ljallangan harorat" + }, + "ProfilePhase1Duration": { + "displayText": "1-faza\nDavomiyligi", + "description": "Ushbu fazaning davomiyligi (sekund)" + }, + "ProfilePhase2Temp": { + "displayText": "2-faza\nHarorati", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "2-faza\nDavomiyligi", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "3-faza\nHarorati", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "3-faza\nDavomiyligi", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "4-faza\nHarorati", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "4-faza\nDavomiyligi", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "5-faza\nHarorati", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "5-faza\nDavomiyligi", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Sovutish\ntezligi", + "description": "Profil rejimi oxirida bu tezlikda sovutish (1 sekundda shuncha daraja)" + }, + "MotionSensitivity": { + "displayText": "Harakat\nsezgirligi", + "description": "1=quyi sezgirlik | ... | 9=eng yuqori sezgirlik" + }, + "SleepTemperature": { + "displayText": "Uyqu\nharorati", + "description": "\"Uyqu holati\"dagi uch harorati" + }, + "SleepTimeout": { + "displayText": "Uyquga ketish\nvaqti", + "description": "\"Uyqu holati\" boshlanishidan oldingi interval sleep mode (s=sekund | m=minut)" + }, + "ShutdownTimeout": { + "displayText": "O'chish\nvaqti", + "description": "Temirni o'chirishdan oldingi interval (m=minut)" + }, + "HallEffSensitivity": { + "displayText": "Hall sensori\nsezgirligi", + "description": "Magnitlarga nisbatan sezgirlik darajasi (1=quyi sezgirlik | ... | 9=eng yuqori sezgirlik)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval before \"sleep mode\" starts when hall effect is above threshold" + }, + "TemperatureUnit": { + "displayText": "Harorat o'lchov\nbirligi", + "description": "C=°Selsiy | F=°Fahrenheit" + }, + "DisplayRotation": { + "displayText": "Ekran\nyo'nalishi", + "description": "O=o'ng qo'l | C=chap qo'l | A=avtomatik" + }, + "CooldownBlink": { + "displayText": "Sovutish\nindikatori", + "description": "Uchi qizigan bo'sh turgan holatida harorat o'lchovini yangilab turish" + }, + "ScrollingSpeed": { + "displayText": "Matn aylanish\ntezligi", + "description": "Matn aylanish tezligini sozlash (S=sekin | T=tez)" + }, + "ReverseButtonTempChange": { + "displayText": "(+) va (-) tugmalarni\nalmashtirish", + "description": "Harorat o'zgarishi uchun tugmachalarni vazifasini almashish" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Anim.\ntezligi", + "description": "Menyudagi ikonka animatsiyalari tezligini sozlash (S=sekin | O=o'rtacha | T=tez)" + }, + "AnimLoop": { + "displayText": "Anim.\nqaytarilishi", + "description": "Bosh menyudagi ikonka anim. qaytarilishi" + }, + "Brightness": { + "displayText": "Ekran\nyorqinligi", + "description": "OLED ekran yorqinligini sozlash" + }, + "ColourInversion": { + "displayText": "Ranglarni\ninvert qilish", + "description": "OLED ekran ranglarini teskari qilish" + }, + "LOGOTime": { + "displayText": "Yuklanish logosi\ndavomiyligi", + "description": "Yuklanish logosi davomiyligini o'rnatish (s=sekund)" + }, + "AdvancedIdle": { + "displayText": "Batafsil\nbo'sh turgandagi ekran", + "description": "B'sh turgandagi ekranda kichik shriftda batafsil ma’lumotni ko'rsatish" + }, + "AdvancedSoldering": { + "displayText": "Batafsil\npayvandlash ekrani", + "description": "Payvandlash ekrani uchun kichik shrift bilan batafsil ma’lumotni ko'rsatish" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Faollashtirish BLE" + }, + "PowerLimit": { + "displayText": "Quvvat\nchegarasi", + "description": "Temir foydalanishi mumkin bo'lgan o'rtacha maksimal quvvat (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Keyingi yuklashda\nCJC kalibrovkasi", + "description": "Keyingi yuklashda Sovuq Tugun Kompensatsiyasini (CJC) kalibrlash (Delta T < 5°C bo'lsa, talab qilinmaydi)" + }, + "VoltageCalibration": { + "displayText": "Kirish kuchlanishini\nkalibrlash", + "description": "VIN kalibrovkasini boshlash (chiqish uchun uzoq bosib turing)" + }, + "PowerPulsePower": { + "displayText": "Quvvat\npulsi", + "description": "Uxlashdan saqlash pulsining quvvat intensivligi (W=watt)" + }, + "PowerPulseWait": { + "displayText": "Quvvat pulsi\nkechikishi", + "description": "Uxlashdan saqlash pulsi boshlanishigacha bo'lgan kechikish (x 2.5 soniya)" + }, + "PowerPulseDuration": { + "displayText": "Quvvat pulsi\ndavomiyligi", + "description": "Uxlashdan saqlash pulsi davomiyligi (x 250ms)" + }, + "SettingsReset": { + "displayText": "Sozlamalarni\nqayta tiklash", + "description": "Barcha sozlamalarni odatiy holatga qaytarish" + }, + "LanguageSwitch": { + "displayText": "Til:\n UZ O'zbek tili", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" + } + } +} diff --git a/Translations/translation_VI.json b/Translations/translation_VI.json index 514c391ab..1a0a1af32 100644 --- a/Translations/translation_VI.json +++ b/Translations/translation_VI.json @@ -1,319 +1,351 @@ { - "languageCode": "VI", - "languageLocalName": "Tieng Viet", - "tempUnitFahrenheit": false, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration\ndone!" - }, - "ResetOKMessage": { - "message": "Reset OK" - }, - "SettingsResetMessage": { - "message": "Mot so cài đat\nđã thay đoi" - }, - "NoAccelerometerMessage": { - "message": "Không phát hien\ngia toc ke!" - }, - "NoPowerDeliveryMessage": { - "message": "Không phát hien\nUSB-PD IC!" - }, - "LockingKeysString": { - "message": "Đã khóa" - }, - "UnlockingKeysString": { - "message": "Mo khóa" - }, - "WarningKeysLockedString": { - "message": "Đã khóa!" - }, - "WarningThermalRunaway": { - "message": "Nhiet\nTat gia nhiet" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating\n" - }, - "SettingsResetWarning": { - "message": "Ban chac chan muon khôi phuc tat ca cài đat ve mac đinh?" - }, - "UVLOWarningString": { - "message": "DC thap" - }, - "UndervoltageString": { - "message": "Đien áp thap\n" - }, - "InputVoltageString": { - "message": "Đau vào V: \n" - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Đang ngu...\n" - }, - "SleepingTipAdvancedString": { - "message": "Meo: \n" - }, - "OffString": { - "message": "Tat" - }, - "ProfilePreheatString": { - "message": "Preheat\n" - }, - "ProfileCooldownString": { - "message": "Cooldown\n" - }, - "DeviceFailedValidationWarning": { - "message": "Your device is most likely a counterfeit!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to\nstart profile" - } - }, - "characters": { - "SettingRightChar": "R", - "SettingLeftChar": "L", - "SettingAutoChar": "A", - "SettingOffChar": "O", - "SettingSlowChar": "S", - "SettingMediumChar": "M", - "SettingFastChar": "F", - "SettingStartNoneChar": "O", - "SettingStartSolderingChar": "S", - "SettingStartSleepChar": "Z", - "SettingStartSleepOffChar": "R", - "SettingLockDisableChar": "D", - "SettingLockBoostChar": "B", - "SettingLockFullChar": "F" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "Cài đat\nnguon đien", - "description": "" - }, - "SolderingMenu": { - "displayText": "Cài đat\ntay hàn", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "Che đo\nngu", - "description": "" - }, - "UIMenu": { - "displayText": "Giao dien\nnguoi dùng", - "description": "" - }, - "AdvancedMenu": { - "displayText": "Cài đat\nnâng cao", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "Nguon\nđien", - "description": "Nguon đien, đat đien áp giam. (DC 10V) (S 3.3V moi cell, tat gioi han công suat)" - }, - "MinVolCell": { - "displayText": "Voltage\ntoi thieu", - "description": "Đien áp toi thieu cho phép trên moi cell (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" - }, - "QCMaxVoltage": { - "displayText": "QC\nvoltage", - "description": "Đien áp QC toi đa mà tay hàn yêu cau" - }, - "PDNegTimeout": { - "displayText": "PD\nsau", - "description": "Thoi gian cho đàm phán PD trong các buoc 100ms đe tuong thích voi mot so bo sac QC" - }, - "PDVpdo": { - "displayText": "PD\nVPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "Tăng\nnhiet đo", - "description": "Nhiet đo dùng trong che đo \"tăng cuong\"" - }, - "AutoStart": { - "displayText": "Nhiet đo\nđang tăng", - "description": "- O=tat | S=nhiet đo hàn | Z=cho o nhiet đo ngu đen khi cu đong | R=cho mà không gia nhiet đen khi cu đong" - }, - "TempChangeShortStep": { - "displayText": "Thay đoi n.đo\nan nút nhanh", - "description": "Biên đo tăng/giam nhiet đo khi an nút nhanh" - }, - "TempChangeLongStep": { - "displayText": "Thay đoi n.đo\nan nút lâu", - "description": "Biên đo tăng/giam nhiet đo khi an nút lâu" - }, - "LockingMode": { - "displayText": "Cho phép khóa\ncác nút", - "description": "Trong khi hàn, giu ca 2 nút đe khóa(D=tat | B=chi che đo tăng cuong | F=khóa hoàn toàn)" - }, - "ProfilePhases": { - "displayText": "Profile\nPhases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat\nTemp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat\nSpeed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1\nTemp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1\nDuration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2\nTemp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2\nDuration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3\nTemp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3\nDuration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4\nTemp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4\nDuration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5\nTemp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5\nDuration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown\nSpeed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "Cam bien\ncu đong", - "description": "- 0=tat | 1=đo nhay thap nhat| ... | 9=đo nhay cao nhat" - }, - "SleepTemperature": { - "displayText": "Nhiet đo\nkhi ngu", - "description": "Giam nhiet đo khi o \"Che đo ngu\"" - }, - "SleepTimeout": { - "displayText": "Ngu\nsau", - "description": "- thoi gian truoc khi \"Che đo ngu\" bat đau (s=giây | m=phút)" - }, - "ShutdownTimeout": { - "displayText": "Tat\nsau", - "description": "- khoang thoi gian truoc khi tay hàn tat (m=phút)" - }, - "HallEffSensitivity": { - "displayText": "Hall\nđo nhay", - "description": "Đo nhay cam bien Hall đe phát hien che đo ngu (0=tat | 1=ít nhay nhat |...| 9=nhay nhat)" - }, - "TemperatureUnit": { - "displayText": "Đon vi\nnhiet đo", - "description": "C= Đo C | F= Đo F" - }, - "DisplayRotation": { - "displayText": "Huong\nhien thi", - "description": "- R=huong tay phai | L=huong tay trái | A=tu đong" - }, - "CooldownBlink": { - "displayText": "Nguoi đi\nchop mat", - "description": "-Nhap nháy nhiet đo sau khi viec gia nhiet tam dung trong khi mui hàn van nóng" - }, - "ScrollingSpeed": { - "displayText": "Toc đo\ncuon", - "description": "Toc đo cuon văn ban(S=cham | F=nhanh)" - }, - "ReverseButtonTempChange": { - "displayText": "Đao nguoc\nnút + -", - "description": "Đao nguoc chuc năng các nút đieu chinh nhiet đo" - }, - "AnimSpeed": { - "displayText": "Toc đo\nhoat anh", - "description": "-Toc đo cua hoat anh menu (O=tat | S=cham | M=trung bình | F=nhanh)" - }, - "AnimLoop": { - "displayText": "Hoat anh\nlap lai", - "description": "Lap lai các hoat anh trong màn hình chính" - }, - "Brightness": { - "displayText": "Đo tuong phan\nmàn hình", - "description": "-Đieu chinh đo sáng màn hình OLED" - }, - "ColourInversion": { - "displayText": "Đao nguoc màu\nmàn hình", - "description": "-Đao nguoc màu màn hình OLED" - }, - "LOGOTime": { - "displayText": "Boot logo\nduration", - "description": "Set boot logo duration (s=seconds)" - }, - "AdvancedIdle": { - "displayText": "Chi tiet\nmàn hình cho", - "description": "- hien thi thông tin chi tiet bang phông chu nho hon trên màn hình cho" - }, - "AdvancedSoldering": { - "displayText": "Chi tiet\nmàn hình hàn", - "description": "-Hien thi thông tin bang phông chu nho hon trên màn hình hàn" - }, - "BluetoothLE": { - "displayText": "Bluetooth\n", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "Công suat\ngioi han", - "description": "-Công suat toi đa mà tay hàn có the su dung (W=watt)" - }, - "CalibrateCJC": { - "displayText": "Calibrate CJC\nat next boot", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5°C)" - }, - "VoltageCalibration": { - "displayText": "Hieu chinh\nđien áp đau vào?", - "description": "-bat đau hieu chuan VIN (nhan và giu đe thoát)" - }, - "PowerPulsePower": { - "displayText": "Công suat\nkích nguon", - "description": "-Cuong đo công suat kích nguon (watt)" - }, - "PowerPulseWait": { - "displayText": "Trì hoãn\nđien áp kích", - "description": "Trì hoãn truoc khi kích hoat kích nguon(x 2,5 giây)" - }, - "PowerPulseDuration": { - "displayText": "Thoi luong\nkích nguon", - "description": "-thoi luong kích nguon (x 250ms)" - }, - "SettingsReset": { - "displayText": "Khôi phuc\ncài đat goc?", - "description": "-đat lai tat ca cài đat ve mac đinh" - }, - "LanguageSwitch": { - "displayText": "Ngôn ngu:\n VI Tieng Viet", - "description": "" - } + "languageCode": "VI", + "languageLocalName": "Tieng Viet", + "tempUnitFahrenheit": false, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibration\ndone!" + }, + "ResetOKMessage": { + "message": "Reset OK" + }, + "SettingsResetMessage": { + "message": "Mot so cài đat\nđã thay đoi" + }, + "NoAccelerometerMessage": { + "message": "Không phát hien\ngia toc ke!" + }, + "NoPowerDeliveryMessage": { + "message": "Không phát hien\nUSB-PD IC!" + }, + "LockingKeysString": { + "message": "Đã khóa" + }, + "UnlockingKeysString": { + "message": "Mo khóa" + }, + "WarningKeysLockedString": { + "message": "Đã khóa!" + }, + "WarningThermalRunaway": { + "message": "Nhiet\nTat gia nhiet" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Before rebooting, make sure tip & handle are at room temperature!" + }, + "CJCCalibrating": { + "message": "calibrating\n" + }, + "SettingsResetWarning": { + "message": "Ban chac chan muon khôi phuc tat ca cài đat ve mac đinh?" + }, + "UVLOWarningString": { + "message": "DC thap" + }, + "UndervoltageString": { + "message": "Đien áp thap\n" + }, + "InputVoltageString": { + "message": "Đau vào V: \n" + }, + "SleepingAdvancedString": { + "message": "Đang ngu...\n" + }, + "SleepingTipAdvancedString": { + "message": "Meo: \n" + }, + "ProfilePreheatString": { + "message": "Preheat\n" + }, + "ProfileCooldownString": { + "message": "Cooldown\n" + }, + "DeviceFailedValidationWarning": { + "message": "Your device is most likely a counterfeit!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to\nstart profile" + } + }, + "characters": { + "SettingRightChar": "R", + "SettingLeftChar": "L", + "SettingAutoChar": "A", + "SettingSlowChar": "S", + "SettingMediumChar": "M", + "SettingFastChar": "F", + "SettingStartSolderingChar": "S", + "SettingStartSleepChar": "Z", + "SettingStartSleepOffChar": "R", + "SettingLockBoostChar": "B", + "SettingLockFullChar": "F" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "Cài đat\nnguon đien", + "description": "" + }, + "SolderingMenu": { + "displayText": "Cài đat\ntay hàn", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "Che đo\nngu", + "description": "" + }, + "UIMenu": { + "displayText": "Giao dien\nnguoi dùng", + "description": "" + }, + "AdvancedMenu": { + "displayText": "Cài đat\nnâng cao", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "Nguon\nđien", + "description": "Nguon đien, đat đien áp giam. (DC 10V) (S 3.3V moi cell, tat gioi han công suat)" + }, + "MinVolCell": { + "displayText": "Voltage\ntoi thieu", + "description": "Đien áp toi thieu cho phép trên moi cell (3S: 3 - 3,7V | 4-6S: 2,4 - 3,7V)" + }, + "QCMaxVoltage": { + "displayText": "QC\nvoltage", + "description": "Đien áp QC toi đa mà tay hàn yêu cau" + }, + "PDNegTimeout": { + "displayText": "PD\nsau", + "description": "Thoi gian cho đàm phán PD trong các buoc 100ms đe tuong thích voi mot so bo sac QC" + }, + "USBPDMode": { + "displayText": "PD\nMode", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "Tăng\nnhiet đo", + "description": "Nhiet đo dùng trong che đo \"tăng cuong\"" + }, + "AutoStart": { + "displayText": "Nhiet đo\nđang tăng", + "description": "S=nhiet đo hàn | Z=cho o nhiet đo ngu đen khi cu đong | R=cho mà không gia nhiet đen khi cu đong" + }, + "TempChangeShortStep": { + "displayText": "Thay đoi n.đo\nan nút nhanh", + "description": "Biên đo tăng/giam nhiet đo khi an nút nhanh" + }, + "TempChangeLongStep": { + "displayText": "Thay đoi n.đo\nan nút lâu", + "description": "Biên đo tăng/giam nhiet đo khi an nút lâu" + }, + "LockingMode": { + "displayText": "Cho phép khóa\ncác nút", + "description": "Trong khi hàn, giu ca 2 nút đe khóa (B=chi che đo tăng cuong | F=khóa hoàn toàn)" + }, + "ProfilePhases": { + "displayText": "Profile\nPhases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat\nTemp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat\nSpeed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1\nTemp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1\nDuration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2\nTemp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2\nDuration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3\nTemp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3\nDuration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4\nTemp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4\nDuration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5\nTemp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5\nDuration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown\nSpeed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "Cam bien\ncu đong", + "description": "1=đo nhay thap nhat| ... | 9=đo nhay cao nhat" + }, + "SleepTemperature": { + "displayText": "Nhiet đo\nkhi ngu", + "description": "Giam nhiet đo khi o \"Che đo ngu\"" + }, + "SleepTimeout": { + "displayText": "Ngu\nsau", + "description": "thoi gian truoc khi \"Che đo ngu\" bat đau (s=giây | m=phút)" + }, + "ShutdownTimeout": { + "displayText": "Tat\nsau", + "description": "khoang thoi gian truoc khi tay hàn tat (m=phút)" + }, + "HallEffSensitivity": { + "displayText": "Hall\nđo nhay", + "description": "Đo nhay cam bien Hall đe phát hien che đo ngu (1=ít nhay nhat |...| 9=nhay nhat)" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval before \"sleep mode\" starts when hall effect is above threshold" + }, + "TemperatureUnit": { + "displayText": "Đon vi\nnhiet đo", + "description": "C= Đo C | F= Đo F" + }, + "DisplayRotation": { + "displayText": "Huong\nhien thi", + "description": "R=huong tay phai | L=huong tay trái | A=tu đong" + }, + "CooldownBlink": { + "displayText": "Nguoi đi\nchop mat", + "description": "Nhap nháy nhiet đo sau khi viec gia nhiet tam dung trong khi mui hàn van nóng" + }, + "ScrollingSpeed": { + "displayText": "Toc đo\ncuon", + "description": "Toc đo cuon văn ban(S=cham | F=nhanh)" + }, + "ReverseButtonTempChange": { + "displayText": "Đao nguoc\nnút + -", + "description": "Đao nguoc chuc năng các nút đieu chinh nhiet đo" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "Toc đo\nhoat anh", + "description": "Toc đo cua hoat anh menu (S=cham | M=trung bình | F=nhanh)" + }, + "AnimLoop": { + "displayText": "Hoat anh\nlap lai", + "description": "Lap lai các hoat anh trong màn hình chính" + }, + "Brightness": { + "displayText": "Đo tuong phan\nmàn hình", + "description": "Đieu chinh đo sáng màn hình OLED" + }, + "ColourInversion": { + "displayText": "Đao nguoc màu\nmàn hình", + "description": "Đao nguoc màu màn hình OLED" + }, + "LOGOTime": { + "displayText": "Boot logo\nduration", + "description": "Set boot logo duration (s=seconds)" + }, + "AdvancedIdle": { + "displayText": "Chi tiet\nmàn hình cho", + "description": "hien thi thông tin chi tiet bang phông chu nho hon trên màn hình cho" + }, + "AdvancedSoldering": { + "displayText": "Chi tiet\nmàn hình hàn", + "description": "Hien thi thông tin bang phông chu nho hon trên màn hình hàn" + }, + "BluetoothLE": { + "displayText": "Bluetooth\n", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "Công suat\ngioi han", + "description": "Công suat toi đa mà tay hàn có the su dung (W=watt)" + }, + "CalibrateCJC": { + "displayText": "Calibrate CJC\nat next boot", + "description": "Calbrate Cold Junction Compensation at next boot (not required if Delta T is < 5°C)" + }, + "VoltageCalibration": { + "displayText": "Hieu chinh\nđien áp đau vào?", + "description": "bat đau hieu chuan VIN (nhan và giu đe thoát)" + }, + "PowerPulsePower": { + "displayText": "Công suat\nkích nguon", + "description": "Cuong đo công suat kích nguon (watt)" + }, + "PowerPulseWait": { + "displayText": "Trì hoãn\nđien áp kích", + "description": "Trì hoãn truoc khi kích hoat kích nguon(x 2,5 giây)" + }, + "PowerPulseDuration": { + "displayText": "Thoi luong\nkích nguon", + "description": "thoi luong kích nguon (x 250ms)" + }, + "SettingsReset": { + "displayText": "Khôi phuc\ncài đat goc?", + "description": "đat lai tat ca cài đat ve mac đinh" + }, + "LanguageSwitch": { + "displayText": "Ngôn ngu:\n VI Tieng Viet", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_YUE_HK.json b/Translations/translation_YUE_HK.json index 3e84fad42..052d81be2 100644 --- a/Translations/translation_YUE_HK.json +++ b/Translations/translation_YUE_HK.json @@ -1,319 +1,351 @@ { - "languageCode": "YUE_HK", - "languageLocalName": "廣東話 (香港)", - "tempUnitFahrenheit": true, - "messagesWarn": { - "CalibrationDone": { - "message": "Calibration done!" - }, - "ResetOKMessage": { - "message": "已重設!" - }, - "SettingsResetMessage": { - "message": "設定已被重設!" - }, - "NoAccelerometerMessage": { - "message": "未能偵測加速度計" - }, - "NoPowerDeliveryMessage": { - "message": "未能偵測PD晶片" - }, - "LockingKeysString": { - "message": "已鎖定" - }, - "UnlockingKeysString": { - "message": "已解除鎖定" - }, - "WarningKeysLockedString": { - "message": "!撳掣鎖定!" - }, - "WarningThermalRunaway": { - "message": "加熱失控" - }, - "WarningTipShorted": { - "message": "!Tip Shorted!" - }, - "SettingsCalibrationWarning": { - "message": "Before rebooting, make sure tip & handle are at room temperature!" - }, - "CJCCalibrating": { - "message": "calibrating" - }, - "SettingsResetWarning": { - "message": "你係咪確定要將全部設定重設到預設值?" - }, - "UVLOWarningString": { - "message": "電壓過低" - }, - "UndervoltageString": { - "message": "Undervoltage" - }, - "InputVoltageString": { - "message": "Input V: " - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Sleeping..." - }, - "SleepingTipAdvancedString": { - "message": "Tip: " - }, - "OffString": { - "message": "關" - }, - "ProfilePreheatString": { - "message": "Preheat" - }, - "ProfileCooldownString": { - "message": "Cooldown" - }, - "DeviceFailedValidationWarning": { - "message": "依支焫雞好有可能係冒牌貨!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to start profile" - } - }, - "characters": { - "SettingRightChar": "右", - "SettingLeftChar": "左", - "SettingAutoChar": "自", - "SettingOffChar": "關", - "SettingSlowChar": "慢", - "SettingMediumChar": "中", - "SettingFastChar": "快", - "SettingStartNoneChar": "無", - "SettingStartSolderingChar": "焊", - "SettingStartSleepChar": "待", - "SettingStartSleepOffChar": "室", - "SettingLockDisableChar": "無", - "SettingLockBoostChar": "增", - "SettingLockFullChar": "全" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "電源設定", - "description": "" - }, - "SolderingMenu": { - "displayText": "焊接設定", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "待機設定", - "description": "" - }, - "UIMenu": { - "displayText": "使用者介面", - "description": "" - }, - "AdvancedMenu": { - "displayText": "進階設定", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "電源", - "description": "輸入電源;設定自動停機電壓 " - }, - "MinVolCell": { - "displayText": "最低電壓", - "description": "每粒電池嘅最低可用電壓 <伏特> <3S: 3.0V - 3.7V, 4/5/6S: 2.4V - 3.7V>" - }, - "QCMaxVoltage": { - "displayText": "QC電壓", - "description": "使用QC電源時請求嘅最高目標電壓" - }, - "PDNegTimeout": { - "displayText": "PD逾時", - "description": "設定USB PD協定交涉嘅逾時時限;為兼容某啲QC電源而設 " - }, - "PDVpdo": { - "displayText": "PD VPDO", - "description": "Enables PPS & EPR modes" - }, - "BoostTemperature": { - "displayText": "增熱温度", - "description": "喺增熱模式時使用嘅温度" - }, - "AutoStart": { - "displayText": "自動啓用", - "description": "開機時自動啓用 <無=停用 | 焊=焊接模式 | 待=待機模式 | 室=室温待機>" - }, - "TempChangeShortStep": { - "displayText": "温度調整 短", - "description": "調校温度時短撳一下嘅温度變幅" - }, - "TempChangeLongStep": { - "displayText": "温度調整 長", - "description": "調校温度時長撳嘅温度變幅" - }, - "LockingMode": { - "displayText": "撳掣鎖定", - "description": "喺焊接模式時,同時長撳兩粒掣啓用撳掣鎖定 <無=停用 | 增=淨係容許增熱模式 | 全=鎖定全部>" - }, - "ProfilePhases": { - "displayText": "Profile Phases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat Temp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat Speed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1 Temp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1 Duration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2 Temp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2 Duration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3 Temp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3 Duration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4 Temp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4 Duration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5 Temp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5 Duration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown Speed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "動作敏感度", - "description": "0=停用 | 1=最低敏感度 | ... | 9=最高敏感度" - }, - "SleepTemperature": { - "displayText": "待機温度", - "description": "喺待機模式時嘅焫雞咀温度" - }, - "SleepTimeout": { - "displayText": "待機延時", - "description": "自動進入待機模式前嘅閒置等候時間 " - }, - "ShutdownTimeout": { - "displayText": "自動熄機", - "description": "自動熄機前嘅閒置等候時間 " - }, - "HallEffSensitivity": { - "displayText": "磁場敏感度", - "description": "磁場感應器用嚟啓動待機模式嘅敏感度 <0=停用 | 1=最低敏感度 | ... | 9=最高敏感度>" - }, - "TemperatureUnit": { - "displayText": "温度單位", - "description": "C=攝氏 | F=華氏" - }, - "DisplayRotation": { - "displayText": "畫面方向", - "description": "右=使用右手 | 左=使用左手 | 自=自動" - }, - "CooldownBlink": { - "displayText": "降温時閃爍", - "description": "停止加熱之後,當焫雞咀仲係熱嗰陣閃爍畫面" - }, - "ScrollingSpeed": { - "displayText": "捲動速度", - "description": "解說文字嘅捲動速度" - }, - "ReverseButtonTempChange": { - "displayText": "反轉加減掣", - "description": "反轉調校温度時加減掣嘅方向" - }, - "AnimSpeed": { - "displayText": "動畫速度", - "description": "功能表圖示動畫嘅速度 <關=不顯示動畫 | 慢=慢速 | 中=中速 | 快=快速>" - }, - "AnimLoop": { - "displayText": "動畫循環", - "description": "循環顯示功能表圖示動畫" - }, - "Brightness": { - "displayText": "熒幕亮度", - "description": "設定OLED熒幕嘅亮度" - }, - "ColourInversion": { - "displayText": "熒幕反轉色", - "description": "反轉OLED熒幕嘅黑白色" - }, - "LOGOTime": { - "displayText": "開機畫面", - "description": "設定開機畫面顯示時長 " - }, - "AdvancedIdle": { - "displayText": "詳細閒置畫面", - "description": "喺閒置畫面以英文細字顯示詳細嘅資料" - }, - "AdvancedSoldering": { - "displayText": "詳細焊接畫面", - "description": "喺焊接模式畫面以英文細字顯示詳細嘅資料" - }, - "BluetoothLE": { - "displayText": "Bluetooth", - "description": "Enables BLE" - }, - "PowerLimit": { - "displayText": "功率限制", - "description": "限制焫雞可用嘅最大功率 " - }, - "CalibrateCJC": { - "displayText": "校正CJC", - "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5 C)" - }, - "VoltageCalibration": { - "displayText": "輸入電壓校正?", - "description": "開始校正VIN輸入電壓 <長撳以退出>" - }, - "PowerPulsePower": { - "displayText": "電源脈衝", - "description": "為保持電源喚醒而通電所用嘅功率 " - }, - "PowerPulseWait": { - "displayText": "電源脈衝間隔", - "description": "為保持電源喚醒,每次通電之間嘅間隔時間 " - }, - "PowerPulseDuration": { - "displayText": "電源脈衝時長", - "description": "為保持電源喚醒,每次通電脈衝嘅時間長度 " - }, - "SettingsReset": { - "displayText": "全部重設?", - "description": "將所有設定重設到預設值" - }, - "LanguageSwitch": { - "displayText": "語言: 廣東話", - "description": "" - } + "languageCode": "YUE_HK", + "languageLocalName": "廣東話 (香港)", + "tempUnitFahrenheit": true, + "messagesWarn": { + "CalibrationDone": { + "message": "Calibration done!" + }, + "ResetOKMessage": { + "message": "已重設!" + }, + "SettingsResetMessage": { + "message": "設定已被重設!" + }, + "NoAccelerometerMessage": { + "message": "未能偵測加速度計" + }, + "NoPowerDeliveryMessage": { + "message": "未能偵測PD晶片" + }, + "LockingKeysString": { + "message": "已鎖定" + }, + "UnlockingKeysString": { + "message": "已解除鎖定" + }, + "WarningKeysLockedString": { + "message": "!撳掣鎖定!" + }, + "WarningThermalRunaway": { + "message": "加熱失控" + }, + "WarningTipShorted": { + "message": "!Tip Shorted!" + }, + "SettingsCalibrationWarning": { + "message": "Before rebooting, make sure tip & handle are at room temperature!" + }, + "CJCCalibrating": { + "message": "calibrating" + }, + "SettingsResetWarning": { + "message": "你係咪確定要將全部設定重設到預設值?" + }, + "UVLOWarningString": { + "message": "電壓過低" + }, + "UndervoltageString": { + "message": "Undervoltage" + }, + "InputVoltageString": { + "message": "Input V: " + }, + "SleepingAdvancedString": { + "message": "Sleeping..." + }, + "SleepingTipAdvancedString": { + "message": "Tip: " + }, + "ProfilePreheatString": { + "message": "Preheat" + }, + "ProfileCooldownString": { + "message": "Cooldown" + }, + "DeviceFailedValidationWarning": { + "message": "依支焫雞好有可能係冒牌貨!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to start profile" + } + }, + "characters": { + "SettingRightChar": "右", + "SettingLeftChar": "左", + "SettingAutoChar": "自", + "SettingSlowChar": "慢", + "SettingMediumChar": "中", + "SettingFastChar": "快", + "SettingStartSolderingChar": "焊", + "SettingStartSleepChar": "待", + "SettingStartSleepOffChar": "室", + "SettingLockBoostChar": "增", + "SettingLockFullChar": "全" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "電源設定", + "description": "" + }, + "SolderingMenu": { + "displayText": "焊接設定", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "待機設定", + "description": "" + }, + "UIMenu": { + "displayText": "使用者介面", + "description": "" + }, + "AdvancedMenu": { + "displayText": "進階設定", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "電源", + "description": "輸入電源;設定自動停機電壓 " + }, + "MinVolCell": { + "displayText": "最低電壓", + "description": "每粒電池嘅最低可用電壓 <伏特> <3S: 3.0V - 3.7V, 4/5/6S: 2.4V - 3.7V>" + }, + "QCMaxVoltage": { + "displayText": "QC電壓", + "description": "使用QC電源時請求嘅最高目標電壓" + }, + "PDNegTimeout": { + "displayText": "PD逾時", + "description": "設定USB PD協定交涉嘅逾時時限;為兼容某啲QC電源而設 " + }, + "USBPDMode": { + "displayText": "PD VPDO", + "description": "No Dynamic disables EPR & PPS, Safe mode does not use padding resistance" + }, + "BoostTemperature": { + "displayText": "增熱温度", + "description": "喺增熱模式時使用嘅温度" + }, + "AutoStart": { + "displayText": "自動啓用", + "description": "開機時自動啓用 <焊=焊接模式 | 待=待機模式 | 室=室温待機>" + }, + "TempChangeShortStep": { + "displayText": "温度調整 短", + "description": "調校温度時短撳一下嘅温度變幅" + }, + "TempChangeLongStep": { + "displayText": "温度調整 長", + "description": "調校温度時長撳嘅温度變幅" + }, + "LockingMode": { + "displayText": "撳掣鎖定", + "description": "喺焊接模式時,同時長撳兩粒掣啓用撳掣鎖定 <增=淨係容許增熱模式 | 全=鎖定全部>" + }, + "ProfilePhases": { + "displayText": "Profile Phases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat Temp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat Speed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1 Temp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1 Duration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2 Temp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2 Duration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3 Temp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3 Duration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4 Temp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4 Duration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5 Temp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5 Duration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown Speed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "動作敏感度", + "description": "1=最低敏感度 | ... | 9=最高敏感度" + }, + "SleepTemperature": { + "displayText": "待機温度", + "description": "喺待機模式時嘅焫雞咀温度" + }, + "SleepTimeout": { + "displayText": "待機延時", + "description": "自動進入待機模式前嘅閒置等候時間 " + }, + "ShutdownTimeout": { + "displayText": "自動熄機", + "description": "自動熄機前嘅閒置等候時間 " + }, + "HallEffSensitivity": { + "displayText": "磁場敏感度", + "description": "磁場感應器用嚟啓動待機模式嘅敏感度 <1=最低敏感度 | ... | 9=最高敏感度>" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval before \"sleep mode\" starts when hall effect is above threshold" + }, + "TemperatureUnit": { + "displayText": "温度單位", + "description": "C=攝氏 | F=華氏" + }, + "DisplayRotation": { + "displayText": "畫面方向", + "description": "右=使用右手 | 左=使用左手 | 自=自動" + }, + "CooldownBlink": { + "displayText": "降温時閃爍", + "description": "停止加熱之後,當焫雞咀仲係熱嗰陣閃爍畫面" + }, + "ScrollingSpeed": { + "displayText": "捲動速度", + "description": "解說文字嘅捲動速度" + }, + "ReverseButtonTempChange": { + "displayText": "反轉加減掣", + "description": "反轉調校温度時加減掣嘅方向" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "動畫速度", + "description": "功能表圖示動畫嘅速度 <慢=慢速 | 中=中速 | 快=快速>" + }, + "AnimLoop": { + "displayText": "動畫循環", + "description": "循環顯示功能表圖示動畫" + }, + "Brightness": { + "displayText": "熒幕亮度", + "description": "設定OLED熒幕嘅亮度" + }, + "ColourInversion": { + "displayText": "熒幕反轉色", + "description": "反轉OLED熒幕嘅黑白色" + }, + "LOGOTime": { + "displayText": "開機畫面", + "description": "設定開機畫面顯示時長 " + }, + "AdvancedIdle": { + "displayText": "詳細閒置畫面", + "description": "喺閒置畫面以英文細字顯示詳細嘅資料" + }, + "AdvancedSoldering": { + "displayText": "詳細焊接畫面", + "description": "喺焊接模式畫面以英文細字顯示詳細嘅資料" + }, + "BluetoothLE": { + "displayText": "Bluetooth", + "description": "Enables BLE" + }, + "PowerLimit": { + "displayText": "功率限制", + "description": "限制焫雞可用嘅最大功率 " + }, + "CalibrateCJC": { + "displayText": "校正CJC", + "description": "At next boot tip Cold Junction Compensation will be calibrated (not required if Delta T is < 5 C)" + }, + "VoltageCalibration": { + "displayText": "輸入電壓校正?", + "description": "開始校正VIN輸入電壓 <長撳以退出>" + }, + "PowerPulsePower": { + "displayText": "電源脈衝", + "description": "為保持電源喚醒而通電所用嘅功率 " + }, + "PowerPulseWait": { + "displayText": "電源脈衝間隔", + "description": "為保持電源喚醒,每次通電之間嘅間隔時間 " + }, + "PowerPulseDuration": { + "displayText": "電源脈衝時長", + "description": "為保持電源喚醒,每次通電脈衝嘅時間長度 " + }, + "SettingsReset": { + "displayText": "全部重設?", + "description": "將所有設定重設到預設值" + }, + "LanguageSwitch": { + "displayText": "語言: 廣東話", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translation_ZH_CN.json b/Translations/translation_ZH_CN.json index 9b23ce255..f0177978a 100644 --- a/Translations/translation_ZH_CN.json +++ b/Translations/translation_ZH_CN.json @@ -1,319 +1,351 @@ { - "languageCode": "ZH_CN", - "languageLocalName": "简体中文", - "tempUnitFahrenheit": true, - "messagesWarn": { - "CalibrationDone": { - "message": "校正完成!" - }, - "ResetOKMessage": { - "message": "已重置!" - }, - "SettingsResetMessage": { - "message": "设定已被重置!" - }, - "NoAccelerometerMessage": { - "message": "未检测到加速度计" - }, - "NoPowerDeliveryMessage": { - "message": "未检测到PD电路" - }, - "LockingKeysString": { - "message": "已锁定" - }, - "UnlockingKeysString": { - "message": "已解锁" - }, - "WarningKeysLockedString": { - "message": "!按键锁定!" - }, - "WarningThermalRunaway": { - "message": "加热失控" - }, - "WarningTipShorted": { - "message": "!烙铁头短路!" - }, - "SettingsCalibrationWarning": { - "message": "在重启前请确认烙铁头及本体已完全冷却!" - }, - "CJCCalibrating": { - "message": "校正中" - }, - "SettingsResetWarning": { - "message": "你是否确定要将全部设定重置为默认值?" - }, - "UVLOWarningString": { - "message": "电压过低" - }, - "UndervoltageString": { - "message": "Undervoltage" - }, - "InputVoltageString": { - "message": "VIN: " - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Zzzz..." - }, - "SleepingTipAdvancedString": { - "message": "<--- " - }, - "OffString": { - "message": "关" - }, - "ProfilePreheatString": { - "message": "Preheat" - }, - "ProfileCooldownString": { - "message": "Cooldown" - }, - "DeviceFailedValidationWarning": { - "message": "这支电烙铁很有可能是冒牌货!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to start profile" - } - }, - "characters": { - "SettingRightChar": "右", - "SettingLeftChar": "左", - "SettingAutoChar": "自", - "SettingOffChar": "关", - "SettingSlowChar": "慢", - "SettingMediumChar": "中", - "SettingFastChar": "快", - "SettingStartNoneChar": "无", - "SettingStartSolderingChar": "焊", - "SettingStartSleepChar": "待", - "SettingStartSleepOffChar": "室", - "SettingLockDisableChar": "无", - "SettingLockBoostChar": "增", - "SettingLockFullChar": "全" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "电源设置", - "description": "" - }, - "SolderingMenu": { - "displayText": "焊接设置", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "待机设置", - "description": "" - }, - "UIMenu": { - "displayText": "用户界面", - "description": "" - }, - "AdvancedMenu": { - "displayText": "高级设置", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "下限电压", - "description": "设置自动停机电压 " - }, - "MinVolCell": { - "displayText": "最低电压", - "description": "每节电池的最低允许电压 <3S: 3.0V - 3.7V, 4/5/6S: 2.4V - 3.7V>" - }, - "QCMaxVoltage": { - "displayText": "QC电压", - "description": "使用QC电源时请求的最高目标电压" - }, - "PDNegTimeout": { - "displayText": "PD超时", - "description": "设定USB-PD协议交涉的超时时限;为兼容某些QC电源而设 " - }, - "PDVpdo": { - "displayText": "PD VPDO", - "description": "启用PPS和EPR快充支持" - }, - "BoostTemperature": { - "displayText": "增热温度", - "description": "增热模式时使用的温度" - }, - "AutoStart": { - "displayText": "自动启动", - "description": "开机时自动启动 <无=禁用 | 焊=焊接模式 | 待=待机模式 | 室=室温待机>" - }, - "TempChangeShortStep": { - "displayText": "短按温度调整", - "description": "调校温度时短按按键的温度变幅" - }, - "TempChangeLongStep": { - "displayText": "长按温度调整", - "description": "调校温度时长按按键的温度变幅" - }, - "LockingMode": { - "displayText": "按键锁定", - "description": "焊接模式时,同时长按两个按键启用按键锁定 <无=禁用 | 增=只容许增热模式 | 全=完全锁定>" - }, - "ProfilePhases": { - "displayText": "Profile Phases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat Temp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat Speed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1 Temp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1 Duration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2 Temp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2 Duration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3 Temp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3 Duration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4 Temp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4 Duration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5 Temp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5 Duration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown Speed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "动作灵敏度", - "description": "0=禁用 | 1=最低灵敏度 | ... | 9=最高灵敏度" - }, - "SleepTemperature": { - "displayText": "待机温度", - "description": "待机模式时的烙铁头温度" - }, - "SleepTimeout": { - "displayText": "待机超时", - "description": "自动进入待机模式前的等候时间 " - }, - "ShutdownTimeout": { - "displayText": "自动关机", - "description": "自动关机前的等候时间 " - }, - "HallEffSensitivity": { - "displayText": "磁场灵敏度", - "description": "霍尔效应传感器用作启动待机模式的灵敏度 <0=禁用 | 1=最低灵敏度 | ... | 9=最高灵敏度>" - }, - "TemperatureUnit": { - "displayText": "温度单位", - "description": "C=摄氏 | F=华氏" - }, - "DisplayRotation": { - "displayText": "显示方向", - "description": "右=右手 | 左=左手 | 自=自动" - }, - "CooldownBlink": { - "displayText": "降温时闪显", - "description": "停止加热之后,闪动温度显示提醒烙铁头仍处于高温状态" - }, - "ScrollingSpeed": { - "displayText": "滚动速度", - "description": "解说文字的滚动速度" - }, - "ReverseButtonTempChange": { - "displayText": "调换加减键", - "description": "调校温度时更换加减键的方向" - }, - "AnimSpeed": { - "displayText": "动画速度", - "description": "主菜单中功能图标动画的播放速度 <关=不显示动画 | 慢=慢速 | 中=中速 | 快=快速>" - }, - "AnimLoop": { - "displayText": "动画循环", - "description": "主菜单中循环播放功能图标动画" - }, - "Brightness": { - "displayText": "屏幕亮度", - "description": "调整OLED屏幕的亮度" - }, - "ColourInversion": { - "displayText": "反转屏幕颜色", - "description": "反转OLED黑/白屏幕" - }, - "LOGOTime": { - "displayText": "开机画面", - "description": "设定开机画面显示时长 " - }, - "AdvancedIdle": { - "displayText": "闲置画面详情", - "description": "闲置画面以英语小字体显示详情" - }, - "AdvancedSoldering": { - "displayText": "焊接画面详情", - "description": "焊接模式画面以英语小字体显示详请" - }, - "BluetoothLE": { - "displayText": "蓝牙", - "description": "启用蓝牙支持" - }, - "PowerLimit": { - "displayText": "功率限制", - "description": "限制烙铁可用的最大功率 " - }, - "CalibrateCJC": { - "displayText": "校正CJC", - "description": "在下次重启时校正烙铁头热电偶冷接点补偿值(CJC)(温差小于5摄氏度时无需校正)" - }, - "VoltageCalibration": { - "displayText": "输入电压校正?", - "description": "开始校正输入电压(VIN)<长按以退出>" - }, - "PowerPulsePower": { - "displayText": "电源脉冲", - "description": "为保持电源处于唤醒状态所用的功率 " - }, - "PowerPulseWait": { - "displayText": "电源脉冲间隔", - "description": "为保持电源处于唤醒状态,每次通电之间的间隔时间 " - }, - "PowerPulseDuration": { - "displayText": "电源脉冲时长", - "description": "为保持电源处于唤醒状态,每次通电脉冲的时间长度 " - }, - "SettingsReset": { - "displayText": "全部重置?", - "description": "将所有设定重置为默认值" - }, - "LanguageSwitch": { - "displayText": "语言:简体中文", - "description": "" - } + "languageCode": "ZH_CN", + "languageLocalName": "简体中文", + "tempUnitFahrenheit": true, + "messagesWarn": { + "CalibrationDone": { + "message": "校正完成!" + }, + "ResetOKMessage": { + "message": "已重置!" + }, + "SettingsResetMessage": { + "message": "设定已被重置!" + }, + "NoAccelerometerMessage": { + "message": "未检测到加速度计" + }, + "NoPowerDeliveryMessage": { + "message": "未检测到PD电路" + }, + "LockingKeysString": { + "message": "已锁定" + }, + "UnlockingKeysString": { + "message": "已解锁" + }, + "WarningKeysLockedString": { + "message": "!按键锁定!" + }, + "WarningThermalRunaway": { + "message": "加热失控" + }, + "WarningTipShorted": { + "message": "!烙铁头短路!" + }, + "SettingsCalibrationWarning": { + "message": "在重启前请确认烙铁头及本体已完全冷却!" + }, + "CJCCalibrating": { + "message": "校正中" + }, + "SettingsResetWarning": { + "message": "你是否确定要将全部设定重置为默认值?" + }, + "UVLOWarningString": { + "message": "电压过低" + }, + "UndervoltageString": { + "message": "欠压" + }, + "InputVoltageString": { + "message": "VIN: \n" + }, + "SleepingAdvancedString": { + "message": "Zzzz..." + }, + "SleepingTipAdvancedString": { + "message": "<--- " + }, + "ProfilePreheatString": { + "message": "预热中" + }, + "ProfileCooldownString": { + "message": "冷却" + }, + "DeviceFailedValidationWarning": { + "message": "这支电烙铁很有可能是冒牌货!" + }, + "TooHotToStartProfileWarning": { + "message": "设备过热" + } + }, + "characters": { + "SettingRightChar": "右", + "SettingLeftChar": "左", + "SettingAutoChar": "自", + "SettingSlowChar": "慢", + "SettingMediumChar": "中", + "SettingFastChar": "快", + "SettingStartSolderingChar": "焊", + "SettingStartSleepChar": "待", + "SettingStartSleepOffChar": "室", + "SettingLockBoostChar": "增", + "SettingLockFullChar": "全" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "电源设置", + "description": "" + }, + "SolderingMenu": { + "displayText": "焊接设置", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "待机设置", + "description": "" + }, + "UIMenu": { + "displayText": "用户界面", + "description": "" + }, + "AdvancedMenu": { + "displayText": "高级设置", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "默认模式" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "安全模式" + }, + "TipTypeAuto": { + "displayText": "自动检测" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "下限电压", + "description": "设置自动停机电压 " + }, + "MinVolCell": { + "displayText": "最低电压", + "description": "每节电池的最低允许电压 <3S: 3.0V - 3.7V, 4/5/6S: 2.4V - 3.7V>" + }, + "QCMaxVoltage": { + "displayText": "QC电压", + "description": "使用QC电源时请求的最高目标电压" + }, + "PDNegTimeout": { + "displayText": "PD超时", + "description": "设定USB-PD协议交涉的超时时限;为兼容某些QC电源而设 " + }, + "USBPDMode": { + "displayText": "PD\nVPDO", + "description": "启用PPS和EPR快充支持" + }, + "BoostTemperature": { + "displayText": "增热温度", + "description": "增热模式时使用的温度" + }, + "AutoStart": { + "displayText": "自动启动", + "description": "开机时自动启动 <焊=焊接模式 | 待=待机模式 | 室=室温待机>" + }, + "TempChangeShortStep": { + "displayText": "短按温度调整", + "description": "调校温度时短按按键的温度变幅" + }, + "TempChangeLongStep": { + "displayText": "长按温度调整", + "description": "调校温度时长按按键的温度变幅" + }, + "LockingMode": { + "displayText": "按键锁定", + "description": "焊接模式时,同时长按两个按键启用按键锁定 <增=只容许增热模式 | 全=完全锁定>" + }, + "ProfilePhases": { + "displayText": "配置阶数", + "description": "配置模式下的阶段数量" + }, + "ProfilePreheatTemp": { + "displayText": "预热温度", + "description": "配置开始时的目标温度" + }, + "ProfilePreheatSpeed": { + "displayText": "预热速度", + "description": "将以此速度进行预热 (度/秒)" + }, + "ProfilePhase1Temp": { + "displayText": "阶段1温度", + "description": "此阶段结束时的目标温度" + }, + "ProfilePhase1Duration": { + "displayText": "阶段1时间", + "description": "此阶段的目标持续时间(秒)" + }, + "ProfilePhase2Temp": { + "displayText": "阶段2温度", + "description": "此阶段结束时的目标温度" + }, + "ProfilePhase2Duration": { + "displayText": "阶段2时间", + "description": "此阶段的目标持续时间(秒)" + }, + "ProfilePhase3Temp": { + "displayText": "阶段3温度", + "description": "此阶段结束时的目标温度" + }, + "ProfilePhase3Duration": { + "displayText": "阶段3时间", + "description": "此阶段的目标持续时间(秒)" + }, + "ProfilePhase4Temp": { + "displayText": "阶段4温度", + "description": "此阶段结束时的目标温度" + }, + "ProfilePhase4Duration": { + "displayText": "阶段4时间", + "description": "此阶段的目标持续时间(秒)" + }, + "ProfilePhase5Temp": { + "displayText": "阶段5温度", + "description": "此阶段结束时的目标温度" + }, + "ProfilePhase5Duration": { + "displayText": "阶段5时间", + "description": "此阶段的目标持续时间(秒)" + }, + "ProfileCooldownSpeed": { + "displayText": "冷却速度", + "description": "在配置模式结束时以此速度进行冷却(度/秒)" + }, + "MotionSensitivity": { + "displayText": "动作灵敏度", + "description": "1=最低灵敏度 | ... | 9=最高灵敏度" + }, + "SleepTemperature": { + "displayText": "待机温度", + "description": "待机模式时的烙铁头温度" + }, + "SleepTimeout": { + "displayText": "待机超时", + "description": "自动进入待机模式前的等候时间 " + }, + "ShutdownTimeout": { + "displayText": "自动关机", + "description": "自动关机前的等候时间 " + }, + "HallEffSensitivity": { + "displayText": "磁场灵敏度", + "description": "霍尔效应传感器用作启动待机模式的灵敏度 <1=最低灵敏度 | ... | 9=最高灵敏度>" + }, + "HallEffSleepTimeout": { + "displayText": "霍尔传感器休眠时间", + "description": "当霍尔传感器检测值高于阈值时,进入“睡眠模式”前的间隔时间" + }, + "TemperatureUnit": { + "displayText": "温度单位", + "description": "C=摄氏 | F=华氏" + }, + "DisplayRotation": { + "displayText": "显示方向", + "description": "右=右手 | 左=左手 | 自=自动" + }, + "CooldownBlink": { + "displayText": "降温时闪显", + "description": "停止加热之后,闪动温度显示提醒烙铁头仍处于高温状态" + }, + "ScrollingSpeed": { + "displayText": "滚动速度", + "description": "解说文字的滚动速度" + }, + "ReverseButtonTempChange": { + "displayText": "调换加减键", + "description": "调校温度时更换加减键的方向" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "动画速度", + "description": "主菜单中功能图标动画的播放速度 <慢=慢速 | 中=中速 | 快=快速>" + }, + "AnimLoop": { + "displayText": "动画循环", + "description": "主菜单中循环播放功能图标动画" + }, + "Brightness": { + "displayText": "屏幕亮度", + "description": "调整OLED屏幕的亮度" + }, + "ColourInversion": { + "displayText": "反转屏幕颜色", + "description": "反转OLED黑/白屏幕" + }, + "LOGOTime": { + "displayText": "开机画面", + "description": "设定开机画面显示时长 " + }, + "AdvancedIdle": { + "displayText": "闲置画面详情", + "description": "闲置画面以英语小字体显示详情" + }, + "AdvancedSoldering": { + "displayText": "焊接画面详情", + "description": "焊接模式画面以英语小字体显示详请" + }, + "BluetoothLE": { + "displayText": "蓝牙", + "description": "启用蓝牙支持" + }, + "PowerLimit": { + "displayText": "功率限制", + "description": "限制烙铁可用的最大功率 " + }, + "CalibrateCJC": { + "displayText": "校正CJC", + "description": "在下次重启时校正烙铁头热电偶冷接点补偿值(CJC)(温差小于5摄氏度时无需校正)" + }, + "VoltageCalibration": { + "displayText": "输入电压校正", + "description": "开始校正输入电压(VIN)<长按以退出>" + }, + "PowerPulsePower": { + "displayText": "电源脉冲", + "description": "为保持电源处于唤醒状态所用的功率 " + }, + "PowerPulseWait": { + "displayText": "电源脉冲间隔", + "description": "为保持电源处于唤醒状态,每次通电之间的间隔时间 " + }, + "PowerPulseDuration": { + "displayText": "电源脉冲时长", + "description": "为保持电源处于唤醒状态,每次通电脉冲的时间长度 " + }, + "SettingsReset": { + "displayText": "全部重置", + "description": "将所有设定重置为默认值" + }, + "LanguageSwitch": { + "displayText": "语言:简体中文", + "description": "" + }, + "SolderingTipType": { + "displayText": "焊接头类型", + "description": "选择安装合适的尖端类型" } + } } diff --git a/Translations/translation_ZH_TW.json b/Translations/translation_ZH_TW.json index ca3fef453..f73008061 100644 --- a/Translations/translation_ZH_TW.json +++ b/Translations/translation_ZH_TW.json @@ -1,319 +1,351 @@ { - "languageCode": "ZH_TW", - "languageLocalName": "正體中文", - "tempUnitFahrenheit": true, - "messagesWarn": { - "CalibrationDone": { - "message": "校正完成!" - }, - "ResetOKMessage": { - "message": "已重設!" - }, - "SettingsResetMessage": { - "message": "設定已被重設!" - }, - "NoAccelerometerMessage": { - "message": "未能偵測加速度計" - }, - "NoPowerDeliveryMessage": { - "message": "未能偵測PD晶片" - }, - "LockingKeysString": { - "message": "已鎖定" - }, - "UnlockingKeysString": { - "message": "已解除鎖定" - }, - "WarningKeysLockedString": { - "message": "!按鍵鎖定!" - }, - "WarningThermalRunaway": { - "message": "加熱失控" - }, - "WarningTipShorted": { - "message": "!烙鐵頭短路!" - }, - "SettingsCalibrationWarning": { - "message": "在重啟前請確認烙鐵頭及本體已完全冷卻!" - }, - "CJCCalibrating": { - "message": "校正中" - }, - "SettingsResetWarning": { - "message": "你是否確定要將全部設定重設到預設值?" - }, - "UVLOWarningString": { - "message": "電壓過低" - }, - "UndervoltageString": { - "message": "Undervoltage" - }, - "InputVoltageString": { - "message": "Input V: " - }, - "SleepingSimpleString": { - "message": "Zzzz" - }, - "SleepingAdvancedString": { - "message": "Sleeping..." - }, - "SleepingTipAdvancedString": { - "message": "Tip: " - }, - "OffString": { - "message": "關" - }, - "ProfilePreheatString": { - "message": "Preheat" - }, - "ProfileCooldownString": { - "message": "Cooldown" - }, - "DeviceFailedValidationWarning": { - "message": "這支電烙鐵很有可能是冒牌貨!" - }, - "TooHotToStartProfileWarning": { - "message": "Too hot to start profile" - } - }, - "characters": { - "SettingRightChar": "右", - "SettingLeftChar": "左", - "SettingAutoChar": "自", - "SettingOffChar": "關", - "SettingSlowChar": "慢", - "SettingMediumChar": "中", - "SettingFastChar": "快", - "SettingStartNoneChar": "無", - "SettingStartSolderingChar": "焊", - "SettingStartSleepChar": "待", - "SettingStartSleepOffChar": "室", - "SettingLockDisableChar": "無", - "SettingLockBoostChar": "增", - "SettingLockFullChar": "全" - }, - "menuGroups": { - "PowerMenu": { - "displayText": "電源設定", - "description": "" - }, - "SolderingMenu": { - "displayText": "焊接設定", - "description": "" - }, - "PowerSavingMenu": { - "displayText": "待機設定", - "description": "" - }, - "UIMenu": { - "displayText": "使用者介面", - "description": "" - }, - "AdvancedMenu": { - "displayText": "進階設定", - "description": "" - } - }, - "menuOptions": { - "DCInCutoff": { - "displayText": "電源", - "description": "輸入電源;設定自動停機電壓 " - }, - "MinVolCell": { - "displayText": "最低電壓", - "description": "每顆電池的最低可用電壓 <伏特> <3S: 3.0V - 3.7V, 4/5/6S: 2.4V - 3.7V>" - }, - "QCMaxVoltage": { - "displayText": "QC電壓", - "description": "使用QC電源時請求的最高目標電壓" - }, - "PDNegTimeout": { - "displayText": "PD逾時", - "description": "設定USB PD協定交涉的逾時時限;為兼容某些QC電源而設 " - }, - "PDVpdo": { - "displayText": "PD VPDO", - "description": "開啟PPS及EPR支援" - }, - "BoostTemperature": { - "displayText": "增熱溫度", - "description": "於增熱模式時使用的溫度" - }, - "AutoStart": { - "displayText": "自動啟用", - "description": "開機時自動啟用 <無=停用 | 焊=焊接模式 | 待=待機模式 | 室=室溫待機>" - }, - "TempChangeShortStep": { - "displayText": "溫度調整 短", - "description": "調校溫度時短按一下的溫度變幅" - }, - "TempChangeLongStep": { - "displayText": "溫度調整 長", - "description": "調校溫度時長按按鍵的溫度變幅" - }, - "LockingMode": { - "displayText": "按鍵鎖定", - "description": "於焊接模式時,同時長按兩個按鍵啟用按鍵鎖定 <無=停用 | 增=只容許增熱模式 | 全=鎖定全部>" - }, - "ProfilePhases": { - "displayText": "Profile Phases", - "description": "Number of phases in profile mode" - }, - "ProfilePreheatTemp": { - "displayText": "Preheat Temp", - "description": "Preheat to this temperature at the start of profile mode" - }, - "ProfilePreheatSpeed": { - "displayText": "Preheat Speed", - "description": "Preheat at this rate (degrees per second)" - }, - "ProfilePhase1Temp": { - "displayText": "Phase 1 Temp", - "description": "Target temperature for the end of this phase" - }, - "ProfilePhase1Duration": { - "displayText": "Phase 1 Duration", - "description": "Target duration of this phase (seconds)" - }, - "ProfilePhase2Temp": { - "displayText": "Phase 2 Temp", - "description": "" - }, - "ProfilePhase2Duration": { - "displayText": "Phase 2 Duration", - "description": "" - }, - "ProfilePhase3Temp": { - "displayText": "Phase 3 Temp", - "description": "" - }, - "ProfilePhase3Duration": { - "displayText": "Phase 3 Duration", - "description": "" - }, - "ProfilePhase4Temp": { - "displayText": "Phase 4 Temp", - "description": "" - }, - "ProfilePhase4Duration": { - "displayText": "Phase 4 Duration", - "description": "" - }, - "ProfilePhase5Temp": { - "displayText": "Phase 5 Temp", - "description": "" - }, - "ProfilePhase5Duration": { - "displayText": "Phase 5 Duration", - "description": "" - }, - "ProfileCooldownSpeed": { - "displayText": "Cooldown Speed", - "description": "Cooldown at this rate at the end of profile mode (degrees per second)" - }, - "MotionSensitivity": { - "displayText": "動作敏感度", - "description": "0=停用 | 1=最低敏感度 | ... | 9=最高敏感度" - }, - "SleepTemperature": { - "displayText": "待機溫度", - "description": "於待機模式時的烙鐵頭溫度" - }, - "SleepTimeout": { - "displayText": "待機延時", - "description": "自動進入待機模式前的閒置等候時間 " - }, - "ShutdownTimeout": { - "displayText": "自動關機", - "description": "自動關機前的閒置等候時間 " - }, - "HallEffSensitivity": { - "displayText": "磁場敏感度", - "description": "磁場感應器用作啟動待機模式的敏感度 <0=停用 | 1=最低敏感度 | ... | 9=最高敏感度>" - }, - "TemperatureUnit": { - "displayText": "溫標", - "description": "C=攝氏 | F=華氏" - }, - "DisplayRotation": { - "displayText": "畫面方向", - "description": "右=使用右手 | 左=使用左手 | 自=自動" - }, - "CooldownBlink": { - "displayText": "降溫時閃爍", - "description": "停止加熱之後,當烙鐵頭仍處於高溫時閃爍畫面" - }, - "ScrollingSpeed": { - "displayText": "捲動速度", - "description": "解說文字的捲動速度" - }, - "ReverseButtonTempChange": { - "displayText": "調換加減鍵", - "description": "調校溫度時調換加減鍵的方向" - }, - "AnimSpeed": { - "displayText": "動畫速度", - "description": "功能表圖示動畫的速度 <關=不顯示動畫 | 慢=慢速 | 中=中速 | 快=快速>" - }, - "AnimLoop": { - "displayText": "動畫循環", - "description": "循環顯示功能表圖示動畫" - }, - "Brightness": { - "displayText": "螢幕亮度", - "description": "設定OLED螢幕的亮度" - }, - "ColourInversion": { - "displayText": "螢幕反轉色", - "description": "反轉OLED螢幕的黑白色彩" - }, - "LOGOTime": { - "displayText": "開機畫面", - "description": "設定開機畫面顯示時長 " - }, - "AdvancedIdle": { - "displayText": "詳細閒置畫面", - "description": "於閒置畫面以英文小字型顯示詳細資料" - }, - "AdvancedSoldering": { - "displayText": "詳細焊接畫面", - "description": "於焊接模式畫面以英文小字型顯示詳細資料" - }, - "BluetoothLE": { - "displayText": "藍牙", - "description": "開啟藍牙支援" - }, - "PowerLimit": { - "displayText": "功率限制", - "description": "限制烙鐵可用的最大功率 " - }, - "CalibrateCJC": { - "displayText": "校正CJC", - "description": "在下次重啟時校正烙鐵頭熱電偶冷接點補償值(CJC)(溫差小於5攝氏度時無需校正)" - }, - "VoltageCalibration": { - "displayText": "輸入電壓校正?", - "description": "開始校正VIN輸入電壓 <長按以退出>" - }, - "PowerPulsePower": { - "displayText": "電源脈衝", - "description": "為保持電源喚醒而通電所用的功率 " - }, - "PowerPulseWait": { - "displayText": "電源脈衝間隔", - "description": "為保持電源喚醒,每次通電之間的間隔時間 " - }, - "PowerPulseDuration": { - "displayText": "電源脈衝時長", - "description": "為保持電源喚醒,每次通電脈衝的時間長度 " - }, - "SettingsReset": { - "displayText": "全部重設?", - "description": "將所有設定重設到預設值" - }, - "LanguageSwitch": { - "displayText": "語言:正體中文", - "description": "" - } + "languageCode": "ZH_TW", + "languageLocalName": "正體中文", + "tempUnitFahrenheit": true, + "messagesWarn": { + "CalibrationDone": { + "message": "校正完成!" + }, + "ResetOKMessage": { + "message": "已重設!" + }, + "SettingsResetMessage": { + "message": "設定已被重設!" + }, + "NoAccelerometerMessage": { + "message": "未能偵測加速度計" + }, + "NoPowerDeliveryMessage": { + "message": "未能偵測PD晶片" + }, + "LockingKeysString": { + "message": "已鎖定" + }, + "UnlockingKeysString": { + "message": "已解除鎖定" + }, + "WarningKeysLockedString": { + "message": "!按鍵鎖定!" + }, + "WarningThermalRunaway": { + "message": "加熱失控" + }, + "WarningTipShorted": { + "message": "!烙鐵頭短路!" + }, + "SettingsCalibrationWarning": { + "message": "在重啟前請確認烙鐵頭及本體已完全冷卻!" + }, + "CJCCalibrating": { + "message": "校正中" + }, + "SettingsResetWarning": { + "message": "你是否確定要將全部設定重設到預設值?" + }, + "UVLOWarningString": { + "message": "電壓過低" + }, + "UndervoltageString": { + "message": "Undervoltage" + }, + "InputVoltageString": { + "message": "Input V: " + }, + "SleepingAdvancedString": { + "message": "Sleeping..." + }, + "SleepingTipAdvancedString": { + "message": "Tip: " + }, + "ProfilePreheatString": { + "message": "Preheat" + }, + "ProfileCooldownString": { + "message": "Cooldown" + }, + "DeviceFailedValidationWarning": { + "message": "這支電烙鐵很有可能是冒牌貨!" + }, + "TooHotToStartProfileWarning": { + "message": "Too hot to start profile" + } + }, + "characters": { + "SettingRightChar": "右", + "SettingLeftChar": "左", + "SettingAutoChar": "自", + "SettingSlowChar": "慢", + "SettingMediumChar": "中", + "SettingFastChar": "快", + "SettingStartSolderingChar": "焊", + "SettingStartSleepChar": "待", + "SettingStartSleepOffChar": "室", + "SettingLockBoostChar": "增", + "SettingLockFullChar": "全" + }, + "menuGroups": { + "PowerMenu": { + "displayText": "電源設定", + "description": "" + }, + "SolderingMenu": { + "displayText": "焊接設定", + "description": "" + }, + "PowerSavingMenu": { + "displayText": "待機設定", + "description": "" + }, + "UIMenu": { + "displayText": "使用者介面", + "description": "" + }, + "AdvancedMenu": { + "displayText": "進階設定", + "description": "" + } + }, + "menuValues": { + "USBPDModeDefault": { + "displayText": "Default\nMode" + }, + "USBPDModeNoDynamic": { + "displayText": "No\nDynamic" + }, + "USBPDModeSafe": { + "displayText": "Safe\nMode" + }, + "TipTypeAuto": { + "displayText": "Auto\nSense" + }, + "TipTypeT12Long": { + "displayText": "TS100\nLong" + }, + "TipTypeT12Short": { + "displayText": "Pine\nShort" + }, + "TipTypeT12PTS": { + "displayText": "PTS\n200" + }, + "TipTypeTS80": { + "displayText": "TS80\n" + }, + "TipTypeJBCC210": { + "displayText": "JBC\nC210" + } + }, + "menuOptions": { + "DCInCutoff": { + "displayText": "電源", + "description": "輸入電源;設定自動停機電壓 " + }, + "MinVolCell": { + "displayText": "最低電壓", + "description": "每顆電池的最低可用電壓 <伏特> <3S: 3.0V - 3.7V, 4/5/6S: 2.4V - 3.7V>" + }, + "QCMaxVoltage": { + "displayText": "QC電壓", + "description": "使用QC電源時請求的最高目標電壓" + }, + "PDNegTimeout": { + "displayText": "PD逾時", + "description": "設定USB PD協定交涉的逾時時限;為兼容某些QC電源而設 " + }, + "USBPDMode": { + "displayText": "PD VPDO", + "description": "開啟PPS及EPR支援" + }, + "BoostTemperature": { + "displayText": "增熱溫度", + "description": "於增熱模式時使用的溫度" + }, + "AutoStart": { + "displayText": "自動啟用", + "description": "開機時自動啟用 <焊=焊接模式 | 待=待機模式 | 室=室溫待機>" + }, + "TempChangeShortStep": { + "displayText": "溫度調整 短", + "description": "調校溫度時短按一下的溫度變幅" + }, + "TempChangeLongStep": { + "displayText": "溫度調整 長", + "description": "調校溫度時長按按鍵的溫度變幅" + }, + "LockingMode": { + "displayText": "按鍵鎖定", + "description": "於焊接模式時,同時長按兩個按鍵啟用按鍵鎖定 <增=只容許增熱模式 | 全=鎖定全部>" + }, + "ProfilePhases": { + "displayText": "Profile Phases", + "description": "Number of phases in profile mode" + }, + "ProfilePreheatTemp": { + "displayText": "Preheat Temp", + "description": "Preheat to this temperature at the start of profile mode" + }, + "ProfilePreheatSpeed": { + "displayText": "Preheat Speed", + "description": "Preheat at this rate (degrees per second)" + }, + "ProfilePhase1Temp": { + "displayText": "Phase 1 Temp", + "description": "Target temperature for the end of this phase" + }, + "ProfilePhase1Duration": { + "displayText": "Phase 1 Duration", + "description": "Target duration of this phase (seconds)" + }, + "ProfilePhase2Temp": { + "displayText": "Phase 2 Temp", + "description": "" + }, + "ProfilePhase2Duration": { + "displayText": "Phase 2 Duration", + "description": "" + }, + "ProfilePhase3Temp": { + "displayText": "Phase 3 Temp", + "description": "" + }, + "ProfilePhase3Duration": { + "displayText": "Phase 3 Duration", + "description": "" + }, + "ProfilePhase4Temp": { + "displayText": "Phase 4 Temp", + "description": "" + }, + "ProfilePhase4Duration": { + "displayText": "Phase 4 Duration", + "description": "" + }, + "ProfilePhase5Temp": { + "displayText": "Phase 5 Temp", + "description": "" + }, + "ProfilePhase5Duration": { + "displayText": "Phase 5 Duration", + "description": "" + }, + "ProfileCooldownSpeed": { + "displayText": "Cooldown Speed", + "description": "Cooldown at this rate at the end of profile mode (degrees per second)" + }, + "MotionSensitivity": { + "displayText": "動作敏感度", + "description": "1=最低敏感度 | ... | 9=最高敏感度" + }, + "SleepTemperature": { + "displayText": "待機溫度", + "description": "於待機模式時的烙鐵頭溫度" + }, + "SleepTimeout": { + "displayText": "待機延時", + "description": "自動進入待機模式前的閒置等候時間 " + }, + "ShutdownTimeout": { + "displayText": "自動關機", + "description": "自動關機前的閒置等候時間 " + }, + "HallEffSensitivity": { + "displayText": "磁場敏感度", + "description": "磁場感應器用作啟動待機模式的敏感度 <1=最低敏感度 | ... | 9=最高敏感度>" + }, + "HallEffSleepTimeout": { + "displayText": "HallSensor\nSleepTime", + "description": "Interval before \"sleep mode\" starts when hall effect is above threshold" + }, + "TemperatureUnit": { + "displayText": "溫標", + "description": "C=攝氏 | F=華氏" + }, + "DisplayRotation": { + "displayText": "畫面方向", + "description": "右=使用右手 | 左=使用左手 | 自=自動" + }, + "CooldownBlink": { + "displayText": "降溫時閃爍", + "description": "停止加熱之後,當烙鐵頭仍處於高溫時閃爍畫面" + }, + "ScrollingSpeed": { + "displayText": "捲動速度", + "description": "解說文字的捲動速度" + }, + "ReverseButtonTempChange": { + "displayText": "調換加減鍵", + "description": "調校溫度時調換加減鍵的方向" + }, + "ReverseButtonSettings": { + "displayText": "Swap\nA B keys", + "description": "Reverse assignment of buttons for Settings menu" + }, + "AnimSpeed": { + "displayText": "動畫速度", + "description": "功能表圖示動畫的速度 <慢=慢速 | 中=中速 | 快=快速>" + }, + "AnimLoop": { + "displayText": "動畫循環", + "description": "循環顯示功能表圖示動畫" + }, + "Brightness": { + "displayText": "螢幕亮度", + "description": "設定OLED螢幕的亮度" + }, + "ColourInversion": { + "displayText": "螢幕反轉色", + "description": "反轉OLED螢幕的黑白色彩" + }, + "LOGOTime": { + "displayText": "開機畫面", + "description": "設定開機畫面顯示時長 " + }, + "AdvancedIdle": { + "displayText": "詳細閒置畫面", + "description": "於閒置畫面以英文小字型顯示詳細資料" + }, + "AdvancedSoldering": { + "displayText": "詳細焊接畫面", + "description": "於焊接模式畫面以英文小字型顯示詳細資料" + }, + "BluetoothLE": { + "displayText": "藍牙", + "description": "開啟藍牙支援" + }, + "PowerLimit": { + "displayText": "功率限制", + "description": "限制烙鐵可用的最大功率 " + }, + "CalibrateCJC": { + "displayText": "校正CJC", + "description": "在下次重啟時校正烙鐵頭熱電偶冷接點補償值(CJC)(溫差小於5攝氏度時無需校正)" + }, + "VoltageCalibration": { + "displayText": "輸入電壓校正?", + "description": "開始校正VIN輸入電壓 <長按以退出>" + }, + "PowerPulsePower": { + "displayText": "電源脈衝", + "description": "為保持電源喚醒而通電所用的功率 " + }, + "PowerPulseWait": { + "displayText": "電源脈衝間隔", + "description": "為保持電源喚醒,每次通電之間的間隔時間 " + }, + "PowerPulseDuration": { + "displayText": "電源脈衝時長", + "description": "為保持電源喚醒,每次通電脈衝的時間長度 " + }, + "SettingsReset": { + "displayText": "全部重設?", + "description": "將所有設定重設到預設值" + }, + "LanguageSwitch": { + "displayText": "語言:正體中文", + "description": "" + }, + "SolderingTipType": { + "displayText": "Soldering\nTip Type", + "description": "Select the tip type fitted" } + } } diff --git a/Translations/translations_definitions.json b/Translations/translations_definitions.json index 6fa8cb9ee..1f2751d51 100644 --- a/Translations/translations_definitions.json +++ b/Translations/translations_definitions.json @@ -1,626 +1,586 @@ { - "messagesWarn": [{ - "id": "CalibrationDone", - "description": "Confirmation message indicating calibration is complete." - }, - { - "id": "ResetOKMessage", - "description": "Shown when the settings are reset to factory defaults by the user." - }, - { - "id": "SettingsResetMessage", - "description": "Shown when certain settings are reset to factory defaults due to incompatible firmware changes." - }, - { - "id": "NoAccelerometerMessage", - "description": "No accelerometer could be communicated with. This means that either the device's accelerometer is broken or unknown to IronOS. All motion-based settings are disabled and motion-based features will not work." - }, - { - "id": "NoPowerDeliveryMessage", - "include": [ - "POW_PD" - ], - "description": "The IC required for USB-PD could not be communicated with. This is an error warning that USB-PD WILL NOT FUNCTION. Generally indicative of either a hardware or software issues." - }, - { - "id": "LockingKeysString", - "description": "Shown when keys are locked" - }, - { - "id": "UnlockingKeysString", - "description": "Shown when keys are unlocked" - }, - { - "id": "WarningKeysLockedString", - "description": "Warning that is shown when input is ignored due to the key lock being on" - }, - { - "id": "WarningThermalRunaway", - "description": "Warning text shown when the software has disabled the heater as a safety precaution as the temperature reading didn't react as expected." - }, - { - "id": "WarningTipShorted", - "description": "Warning text shown when the software has detected that the users tip is likely shorted." - }, - { - "id": "SettingsCalibrationWarning", - "description": "Confirmation message shown before performing an offset calibration. Should warn the user to make sure tip and handle are at the same temperature." - }, - { - "id": "CJCCalibrating", - "description": "Message indicating CJC is being calibrated." - }, - { - "id": "SettingsResetWarning", - "description": "Confirmation message shown before confirming a settings reset." - }, - { - "id": "UVLOWarningString", - "maxLen": 8, - "include": [ - "POW_DC" - ], - "description": "Warning text shown when the unit turns off due to undervoltage in simple mode." - }, - { - "id": "UndervoltageString", - "maxLen": 15, - "include": [ - "POW_DC" - ], - "description": "Warning text shown when the unit turns off due to undervoltage in advanced mode." - }, - { - "id": "InputVoltageString", - "maxLen": 11, - "note": "Preferably end with a space", - "include": [ - "POW_DC" - ], - "description": "Prefix text for 'Input Voltage' shown before showing the input voltage reading." - }, - { - "id": "ProfilePreheatString", - "maxLen": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Shown in profile mode while preheating" - }, - { - "id": "ProfileCooldownString", - "maxLen": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Shown in profile mode while cooling down" - }, - { - "id": "SleepingSimpleString", - "maxLen": 4, - "exclude": [ - "NO_SLEEP_MODE" - ], - "description": "The text shown to indicate the unit is in sleep mode when the advanced view is NOT on." - }, - { - "id": "SleepingAdvancedString", - "maxLen": 15, - "exclude": [ - "NO_SLEEP_MODE" - ], - "description": "The text shown to indicate the unit is in sleep mode when the advanced view is turned on." - }, - { - "id": "SleepingTipAdvancedString", - "maxLen": 6, - "exclude": [ - "NO_SLEEP_MODE" - ], - "description": "The prefix text shown before tip temperature when the unit is sleeping with advanced view on." - }, - { - "id": "OffString", - "maxLen": 3, - "description": "Shown when a setting is turned off." - }, - { - "id": "DeviceFailedValidationWarning", - "default": "Device may be\ncounterfeit", - "description": "Warning shown if the device may be a clone or counterfeit unit." - }, - { - "id": "TooHotToStartProfileWarning", - "default": "Too hot to\nstart profile", - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Shown when profile mode is started while the device is too hot." - } - ], - "characters": [ - { - "id": "SettingRightChar", - "len": 1, - "description": "Shown for fixed Right-handed display rotation." - }, - { - "id": "SettingLeftChar", - "len": 1, - "description": "Shown for fixed Left-handed display rotation." - }, - { - "id": "SettingAutoChar", - "len": 1, - "description": "Shown for automatic display rotation." - }, - { - "id": "SettingOffChar", - "len": 1, - "description": "Shown when a setting is turned off" - }, - { - "id": "SettingSlowChar", - "len": 1, - "description": "Shown when a setting is set to a slow value i.e. animation speed" - }, - { - "id": "SettingMediumChar", - "len": 1, - "description": "Shown when a setting is set to a medium value i.e. animation speed" - }, - { - "id": "SettingFastChar", - "len": 1, - "description": "Shown when a setting is set to a fast value i.e. animation speed" - }, - { - "id": "SettingStartNoneChar", - "len": 1, - "description": "Shown when autostart state is to do nothing and go to a normal boot" - }, - { - "id": "SettingStartSolderingChar", - "len": 1, - "description": "Shown when the auto start mode is set to go straight to soldering." - }, - { - "id": "SettingStartSleepChar", - "len": 1, - "description": "Shown when the auto start mode is set to start in sleep mode." - }, - { - "id": "SettingStartSleepOffChar", - "len": 1, - "description": "Shown when the auto start state is set to go to an off state, but on movement wake into soldering mode." - }, - { - "id": "SettingLockDisableChar", - "len": 1, - "default": "D", - "description": "Shown when locking mode is turned off." - }, - { - "id": "SettingLockBoostChar", - "len": 1, - "default": "B", - "description": "Shown when the locking mode is set to lock all buttons except for boost mode." - }, - { - "id": "SettingLockFullChar", - "len": 1, - "default": "F", - "description": "Shown when the locking mode is set to lock all buttons." - } - ], - "menuGroups": [ - { - "id": "PowerMenu", - "maxLen": 5, - "maxLen2": 11, - "include": [ - "POW_DC", - "POW_QC" - ], - "description": "Menu for settings related to power. Main settings to do with the input voltage." - }, - { - "id": "SolderingMenu", - "maxLen": 5, - "maxLen2": 11, - "description": "Settings for soldering mode, such as boost temps, the increment used when pressing buttons and if button locking is enabled." - }, - { - "id": "PowerSavingMenu", - "maxLen": 5, - "maxLen2": 11, - "description": "Settings to do with power saving, such as sleep mode, sleep temps, and shutdown modes." - }, - { - "id": "UIMenu", - "maxLen": 5, - "maxLen2": 11, - "description": "User interface related settings, such as units." - }, - { - "id": "AdvancedMenu", - "maxLen": 5, - "maxLen2": 11, - "description": "Advanced settings. Misc catchall for settings that don't fit anywhere else or settings that require some thought before use." - } - ], - "menuOptions": [ - { - "id": "DCInCutoff", - "maxLen": 5, - "maxLen2": 11, - "include": [ - "POW_DC" - ], - "description": "When the device is powered by a battery, this adjusts the low voltage threshold for when the unit should turn off the heater to protect the battery." - }, - { - "id": "MinVolCell", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "POW_DC" - ], - "description": "When powered by a battery, this adjusts the minimum voltage per cell before shutdown. (This is multiplied by the cell count.)" - }, - { - "id": "QCMaxVoltage", - "maxLen": 8, - "maxLen2": 15, - "include": [ - "POW_QC" - ], - "description": "This adjusts the maximum voltage the QC negotiation will adjust to. Does NOT affect USB-PD. Should be set safely based on the current rating of your power supply." - }, - { - "id": "PDNegTimeout", - "maxLen": 8, - "maxLen2": 15, - "include": [ - "POW_PD" - ], - "description": "How long until firmware stops trying to negotiate for USB-PD and tries QC instead. Longer times may help dodgy / old PD adapters, faster times move onto PD quickly. Units of 100ms. Recommended to keep small values." - }, - { - "id": "PDVpdo", - "maxLen": 7, - "maxLen2": 15, - "include": [ - "POW_PD" - ], - "description": "Enabled PPS & EPR modes." - }, - { - "id": "BoostTemperature", - "maxLen": 4, - "maxLen2": 9, - "description": "When the unit is in soldering mode. You can hold down the button at the front of the device to temporarily override the soldering temperature to this value. This SETS the temperature, it does not ADD to it." - }, - { - "id": "AutoStart", - "maxLen": 6, - "maxLen2": 13, - "description": "When the device powers up, should it enter into a special mode. These settings set it to either start into soldering mode, sleeping mode or auto mode (Enters into soldering mode on the first movement)." - }, - { - "id": "TempChangeShortStep", - "maxLen": 8, - "maxLen2": 15, - "description": "Factor by which the temperature is changed with a quick press of the buttons." - }, - { - "id": "TempChangeLongStep", - "maxLen": 6, - "maxLen2": 15, - "description": "Factor by which the temperature is changed with a hold of the buttons." - }, - { - "id": "LockingMode", - "maxLen": 6, - "maxLen2": 13, - "description": "If locking the buttons against accidental presses is enabled." - }, - { - "id": "ProfilePhases", - "maxLen": 6, - "maxLen2": 13, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "set the number of phases for profile mode." - }, - { - "id": "ProfilePreheatTemp", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Preheat to this temperature at the start of profile mode." - }, - { - "id": "ProfilePreheatSpeed", - "maxLen": 5, - "maxLen2": 11, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "How fast the temperature is allowed to rise during the preheat phase at the start of profile mode." - }, - { - "id": "ProfilePhase1Temp", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Target temperature for the end of phase 1 of profile mode." - }, - { - "id": "ProfilePhase1Duration", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Duration of phase 1 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature." - }, - { - "id": "ProfilePhase2Temp", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Target temperature for the end of phase 2 of profile mode." - }, - { - "id": "ProfilePhase2Duration", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Duration of phase 2 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature." - }, - { - "id": "ProfilePhase3Temp", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Target temperature for the end of phase 3 of profile mode." - }, - { - "id": "ProfilePhase3Duration", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Duration of phase 3 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature." - }, - { - "id": "ProfilePhase4Temp", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Target temperature for the end of phase 5 of profile mode." - }, - { - "id": "ProfilePhase4Duration", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Duration of phase 5 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature." - }, - { - "id": "ProfilePhase5Temp", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Target temperature for the end of phase 5 of profile mode." - }, - { - "id": "ProfilePhase5Duration", - "maxLen": 4, - "maxLen2": 9, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "Duration of phase 5 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature." - }, - { - "id": "ProfileCooldownSpeed", - "maxLen": 5, - "maxLen2": 11, - "include": [ - "PROFILE_SUPPORT" - ], - "description": "How fast the temperature is allowed to drop during the cooldown phase at the end of profile mode." - }, - { - "id": "MotionSensitivity", - "maxLen": 6, - "maxLen2": 13, - "description": "Scale of how sensitive the device is to movement. Higher numbers == more sensitive. 0 == motion detection turned off." - }, - { - "id": "SleepTemperature", - "maxLen": 4, - "maxLen2": 9, - "exclude": [ - "NO_SLEEP_MODE" - ], - "description": "Temperature the device will drop down to while asleep. Typically around halfway between off and soldering temperature." - }, - { - "id": "SleepTimeout", - "maxLen": 4, - "maxLen2": 9, - "exclude": [ - "NO_SLEEP_MODE" - ], - "description": "How long of a period without movement / button-pressing is required before the device drops down to the sleep temperature." - }, - { - "id": "ShutdownTimeout", - "maxLen": 5, - "maxLen2": 11, - "description": "How long of a period without movement / button-pressing is required before the device turns off the tip heater completely and returns to the main idle screen." - }, - { - "id": "HallEffSensitivity", - "maxLen": 6, - "maxLen2": 13, - "include": [ - "HALL_SENSOR" - ], - "description": "If the unit has a hall effect sensor (Pinecil), this adjusts how sensitive it is at detecting a magnet to put the device into sleep mode." - }, - { - "id": "TemperatureUnit", - "maxLen": 6, - "maxLen2": 13, - "description": "If the device shows temperatures in °C or °F." - }, - { - "id": "DisplayRotation", - "maxLen": 6, - "maxLen2": 13, - "exclude": [ - "NO_DISPLAY_ROTATE" - ], - "description": "If the display should rotate automatically or if it should be fixed for left- or right-handed mode." - }, - { - "id": "CooldownBlink", - "maxLen": 6, - "maxLen2": 13, - "description": "If the idle screen should blink the tip temperature for attention while the tip is over 50°C. Intended as a 'tip is still hot' warning." - }, - { - "id": "ScrollingSpeed", - "maxLen": 6, - "maxLen2": 11, - "description": "How fast the description text scrolls when hovering on a menu. Faster speeds may induce tearing, but allow reading the whole description faster." - }, - { - "id": "ReverseButtonTempChange", - "maxLen": 6, - "maxLen2": 15, - "description": "Swaps which button increments and decrements on temperature change screens." - }, - { - "id": "AnimSpeed", - "maxLen": 6, - "maxLen2": 13, - "description": "How fast should the menu animations loop, or if they should not loop at all." - }, - { - "id": "AnimLoop", - "maxLen": 6, - "maxLen2": 13, - "description": "Should the menu animations loop. Only visible if the animation speed is not set to \"Off\"" - }, - { - "id": "Brightness", - "maxLen": 7, - "maxLen2": 15, - "description": "Display brightness. Higher values age the OLED faster due to burn-in. (However, it is notable that most of these screens die from other causes first.)" - }, - { - "id": "ColourInversion", - "maxLen": 7, - "maxLen2": 15, - "description": "Inverts the entire OLED." - }, - { - "id": "LOGOTime", - "maxLen": 7, - "maxLen2": 15, - "description": "Sets the duration for the boot logo (s=seconds)." - }, - { - "id": "AdvancedIdle", - "maxLen": 6, - "maxLen2": 13, - "description": "Should the device show an 'advanced' view on the idle screen. The advanced view uses text to show more details than the typical icons." - }, - { - "id": "AdvancedSoldering", - "maxLen": 6, - "maxLen2": 13, - "description": "Should the device show an 'advanced' soldering view. This is a text-based view that shows more information at the cost of no nice graphics." - }, - { - "id": "BluetoothLE", - "maxLen": 7, - "maxLen2": 15, - "include": [ - "BLE_ENABLED" - ], - "description": "Should BLE be enabled at boot time." - }, - { - "id": "PowerLimit", - "maxLen": 5, - "maxLen2": 11, - "description": "Allows setting a custom wattage for the device to aim to keep the AVERAGE power below. The unit can't control its peak power no matter how you set this. (Except for MHP30 which will regulate nicely to this). If USB-PD is in use, the limit will be set to the lower of this and the supplies advertised wattage." - }, - { - "id": "CalibrateCJC", - "maxLen": 8, - "maxLen2": 15, - "description": "Used to calibrate the ADC+Op-amp offsets for the tip. This calibration must be performed when the tip temperature and the handle temperature are equal. Generally not required unless your device is reading more than 5°C off target." - }, - { - "id": "VoltageCalibration", - "maxLen": 8, - "maxLen2": 15, - "description": "Enters an adjustment mode where you can gradually adjust the measured voltage to compensate for any unit-to-unit variance in the voltage sense resistors." - }, - { - "id": "PowerPulsePower", - "maxLen": 6, - "maxLen2": 15, - "description": "Enables and sets the wattage of the power pulse. Power pulse causes the device to briefly turn on the heater to draw power to avoid power banks going to sleep." - }, - { - "id": "PowerPulseWait", - "maxLen": 6, - "maxLen2": 13, - "description": "Adjusts the time interval between power pulses. Longer gaps reduce undesired heating of the tip, but needs to be fast enough to keep your power bank awake." - }, - { - "id": "PowerPulseDuration", - "maxLen": 6, - "maxLen2": 13, - "description": "How long should the power pulse go for. Some power banks require seeing the power draw be sustained for a certain duration to keep awake. Should be kept as short as possible to avoid wasting power / undesired heating of the tip." - }, - { - "id": "SettingsReset", - "maxLen": 8, - "maxLen2": 15, - "description": "Resets all settings and calibrations to factory defaults. Does NOT erase custom user boot up logo's." - }, - { - "id": "LanguageSwitch", - "maxLen": 7, - "maxLen2": 15, - "description": "Changes the device language on multi-lingual builds." - } - ] -} \ No newline at end of file + "messagesWarn": [ + { + "id": "CalibrationDone", + "description": "Confirmation message indicating calibration is complete." + }, + { + "id": "ResetOKMessage", + "description": "Shown when the settings are reset to factory defaults by the user." + }, + { + "id": "SettingsResetMessage", + "description": "Shown when certain settings are reset to factory defaults due to incompatible firmware changes." + }, + { + "id": "NoAccelerometerMessage", + "description": "No accelerometer could be communicated with. This means that either the device's accelerometer is broken or unknown to IronOS. All motion-based settings are disabled and motion-based features will not work." + }, + { + "id": "NoPowerDeliveryMessage", + "include": ["POW_PD"], + "description": "The IC required for USB-PD could not be communicated with. This is an error warning that USB-PD WILL NOT FUNCTION. Generally indicative of either a hardware or software issues." + }, + { + "id": "LockingKeysString", + "description": "Shown when keys are locked" + }, + { + "id": "UnlockingKeysString", + "description": "Shown when keys are unlocked" + }, + { + "id": "WarningKeysLockedString", + "description": "Warning that is shown when input is ignored due to the key lock being on" + }, + { + "id": "WarningThermalRunaway", + "description": "Warning text shown when the software has disabled the heater as a safety precaution as the temperature reading didn't react as expected." + }, + { + "id": "WarningTipShorted", + "description": "Warning text shown when the software has detected that the users tip is likely shorted." + }, + { + "id": "SettingsCalibrationWarning", + "description": "Confirmation message shown before performing an offset calibration. Should warn the user to make sure tip and handle are at the same temperature." + }, + { + "id": "CJCCalibrating", + "description": "Message indicating CJC is being calibrated." + }, + { + "id": "SettingsResetWarning", + "description": "Confirmation message shown before confirming a settings reset." + }, + { + "id": "UVLOWarningString", + "maxLen": 8, + "include": ["POW_DC"], + "description": "Warning text shown when the unit turns off due to undervoltage in simple mode." + }, + { + "id": "UndervoltageString", + "maxLen": 15, + "include": ["POW_DC"], + "description": "Warning text shown when the unit turns off due to undervoltage in advanced mode." + }, + { + "id": "InputVoltageString", + "maxLen": 11, + "note": "Preferably end with a space", + "include": ["POW_DC"], + "description": "Prefix text for 'Input Voltage' shown before showing the input voltage reading." + }, + { + "id": "ProfilePreheatString", + "maxLen": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Shown in profile mode while preheating" + }, + { + "id": "ProfileCooldownString", + "maxLen": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Shown in profile mode while cooling down" + }, + { + "id": "SleepingAdvancedString", + "maxLen": 15, + "exclude": ["NO_SLEEP_MODE"], + "description": "The text shown to indicate the unit is in sleep mode when the advanced view is turned on." + }, + { + "id": "SleepingTipAdvancedString", + "maxLen": 6, + "exclude": ["NO_SLEEP_MODE"], + "description": "The prefix text shown before tip temperature when the unit is sleeping with advanced view on." + }, + { + "id": "DeviceFailedValidationWarning", + "default": "Device may be\ncounterfeit", + "description": "Warning shown if the device may be a clone or counterfeit unit." + }, + { + "id": "TooHotToStartProfileWarning", + "default": "Too hot to\nstart profile", + "include": ["PROFILE_SUPPORT"], + "description": "Shown when profile mode is started while the device is too hot." + } + ], + "characters": [ + { + "id": "SettingRightChar", + "len": 1, + "description": "Shown for fixed Right-handed display rotation." + }, + { + "id": "SettingLeftChar", + "len": 1, + "description": "Shown for fixed Left-handed display rotation." + }, + { + "id": "SettingAutoChar", + "len": 1, + "description": "Shown for automatic display rotation." + }, + { + "id": "SettingSlowChar", + "len": 1, + "description": "Shown when a setting is set to a slow value i.e. animation speed" + }, + { + "id": "SettingMediumChar", + "len": 1, + "description": "Shown when a setting is set to a medium value i.e. animation speed" + }, + { + "id": "SettingFastChar", + "len": 1, + "description": "Shown when a setting is set to a fast value i.e. animation speed" + }, + { + "id": "SettingStartSolderingChar", + "len": 1, + "description": "Shown when the auto start mode is set to go straight to soldering." + }, + { + "id": "SettingStartSleepChar", + "len": 1, + "description": "Shown when the auto start mode is set to start in sleep mode." + }, + { + "id": "SettingStartSleepOffChar", + "len": 1, + "description": "Shown when the auto start state is set to go to an off state, but on movement wake into soldering mode." + }, + { + "id": "SettingLockBoostChar", + "len": 1, + "default": "B", + "description": "Shown when the locking mode is set to lock all buttons except for boost mode." + }, + { + "id": "SettingLockFullChar", + "len": 1, + "default": "F", + "description": "Shown when the locking mode is set to lock all buttons." + } + ], + "menuGroups": [ + { + "id": "PowerMenu", + "maxLen": 5, + "maxLen2": 11, + "include": ["POW_DC", "POW_PD", "POW_QC"], + "description": "Menu for settings related to power. Main settings to do with the input voltage." + }, + { + "id": "SolderingMenu", + "maxLen": 5, + "maxLen2": 11, + "description": "Settings for soldering mode, such as boost temps, the increment used when pressing buttons and if button locking is enabled." + }, + { + "id": "PowerSavingMenu", + "maxLen": 5, + "maxLen2": 11, + "description": "Settings to do with power saving, such as sleep mode, sleep temps, and shutdown modes." + }, + { + "id": "UIMenu", + "maxLen": 5, + "maxLen2": 11, + "description": "User interface related settings, such as units." + }, + { + "id": "AdvancedMenu", + "maxLen": 5, + "maxLen2": 11, + "description": "Advanced settings. Misc catchall for settings that don't fit anywhere else or settings that require some thought before use." + } + ], + "menuValues": [ + { + "id": "USBPDModeDefault", + "description": "When in this mode we enable all PD features, and we pad resistance slightly to account for cable and PCB trace loss" + }, + { + "id": "USBPDModeNoDynamic", + "description": "When in this mode we only enable fixed voltage USB-PD options, and we pad resistance slightly to account for cable and PCB trace loss" + }, + { + "id": "USBPDModeSafe", + "description": "When in this mode we enable all PD features, but we don't pad resistance slightly to account for cable and PCB trace loss" + }, + { + "id": "TipTypeAuto", + "description": "This is for automatic best-effort tip selection based on resistance" + }, + { + "id": "TipTypeT12Long", + "description": "Hakko T12 or older (long) TS100 tips" + }, + { + "id": "TipTypeT12Short", + "description": "Pine 6.2 ohm short TS100 style tips" + }, + { + "id": "TipTypeT12PTS", + "description": "PTS200 4 ohm short TS100 style tips" + }, + { + "id": "TipTypeTS80", + "description": "Miniware TS80(P) tips" + }, + { + "id": "TipTypeJBCC210", + "description": "JBC (or clone) tips" + } + ], + "menuOptions": [ + { + "id": "DCInCutoff", + "maxLen": 5, + "maxLen2": 11, + "include": ["POW_DC"], + "description": "When the device is powered by a battery, this adjusts the low voltage threshold for when the unit should turn off the heater to protect the battery." + }, + { + "id": "MinVolCell", + "maxLen": 4, + "maxLen2": 9, + "include": ["POW_DC"], + "description": "When powered by a battery, this adjusts the minimum voltage per cell before shutdown. (This is multiplied by the cell count.)" + }, + { + "id": "QCMaxVoltage", + "maxLen": 8, + "maxLen2": 15, + "include": ["POW_QC"], + "description": "This adjusts the maximum voltage the QC negotiation will adjust to. Does NOT affect USB-PD. Should be set safely based on the current rating of your power supply." + }, + { + "id": "PDNegTimeout", + "maxLen": 8, + "maxLen2": 15, + "include": ["POW_PD"], + "description": "How long until firmware stops trying to negotiate for USB-PD and tries QC instead. Longer times may help dodgy / old PD adapters, faster times move onto PD quickly. Units of 100ms. Recommended to keep small values." + }, + { + "id": "USBPDMode", + "maxLen": 7, + "maxLen2": 15, + "include": ["POW_PD"], + "description": "Adjusts how the USB-PD Logic selects the voltage. No Dynamic disables EPR & PPS protocols, Safe mode does not use padding resistance (will select a slightly lower voltage)." + }, + { + "id": "BoostTemperature", + "maxLen": 4, + "maxLen2": 9, + "description": "When the unit is in soldering mode. You can hold down the button at the front of the device to temporarily override the soldering temperature to this value. This SETS the temperature, it does not ADD to it." + }, + { + "id": "AutoStart", + "maxLen": 6, + "maxLen2": 13, + "description": "When the device powers up, should it enter into a special mode. These settings set it to either start into soldering mode, sleeping mode or auto mode (Enters into soldering mode on the first movement)." + }, + { + "id": "TempChangeShortStep", + "maxLen": 8, + "maxLen2": 15, + "description": "Factor by which the temperature is changed with a quick press of the buttons." + }, + { + "id": "TempChangeLongStep", + "maxLen": 6, + "maxLen2": 15, + "description": "Factor by which the temperature is changed with a hold of the buttons." + }, + { + "id": "LockingMode", + "maxLen": 6, + "maxLen2": 13, + "description": "If locking the buttons against accidental presses is enabled." + }, + { + "id": "ProfilePhases", + "maxLen": 6, + "maxLen2": 13, + "include": ["PROFILE_SUPPORT"], + "description": "set the number of phases for profile mode." + }, + { + "id": "ProfilePreheatTemp", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Preheat to this temperature at the start of profile mode." + }, + { + "id": "ProfilePreheatSpeed", + "maxLen": 5, + "maxLen2": 11, + "include": ["PROFILE_SUPPORT"], + "description": "How fast the temperature is allowed to rise during the preheat phase at the start of profile mode." + }, + { + "id": "ProfilePhase1Temp", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Target temperature for the end of phase 1 of profile mode." + }, + { + "id": "ProfilePhase1Duration", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Duration of phase 1 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature." + }, + { + "id": "ProfilePhase2Temp", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Target temperature for the end of phase 2 of profile mode." + }, + { + "id": "ProfilePhase2Duration", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Duration of phase 2 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature." + }, + { + "id": "ProfilePhase3Temp", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Target temperature for the end of phase 3 of profile mode." + }, + { + "id": "ProfilePhase3Duration", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Duration of phase 3 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature." + }, + { + "id": "ProfilePhase4Temp", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Target temperature for the end of phase 5 of profile mode." + }, + { + "id": "ProfilePhase4Duration", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Duration of phase 5 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature." + }, + { + "id": "ProfilePhase5Temp", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Target temperature for the end of phase 5 of profile mode." + }, + { + "id": "ProfilePhase5Duration", + "maxLen": 4, + "maxLen2": 9, + "include": ["PROFILE_SUPPORT"], + "description": "Duration of phase 5 of profile mode. The phase might actually take longer if it takes longer to reach the target temperature." + }, + { + "id": "ProfileCooldownSpeed", + "maxLen": 5, + "maxLen2": 11, + "include": ["PROFILE_SUPPORT"], + "description": "How fast the temperature is allowed to drop during the cooldown phase at the end of profile mode." + }, + { + "id": "MotionSensitivity", + "maxLen": 6, + "maxLen2": 13, + "description": "Scale of how sensitive the device is to movement. Higher numbers == more sensitive. 0 == motion detection turned off." + }, + { + "id": "SleepTemperature", + "maxLen": 4, + "maxLen2": 9, + "exclude": ["NO_SLEEP_MODE"], + "description": "Temperature the device will drop down to while asleep. Typically around halfway between off and soldering temperature." + }, + { + "id": "SleepTimeout", + "maxLen": 4, + "maxLen2": 9, + "exclude": ["NO_SLEEP_MODE"], + "description": "How long of a period without movement / button-pressing is required before the device drops down to the sleep temperature." + }, + { + "id": "ShutdownTimeout", + "maxLen": 5, + "maxLen2": 11, + "description": "How long of a period without movement / button-pressing is required before the device turns off the tip heater completely and returns to the main idle screen." + }, + { + "id": "HallEffSensitivity", + "maxLen": 6, + "maxLen2": 13, + "include": ["HALL_SENSOR"], + "description": "If the unit has a hall effect sensor (Pinecil), this adjusts how sensitive it is at detecting a magnet to put the device into sleep mode." + }, + { + "id": "HallEffSleepTimeout", + "maxLen": 10, + "maxLen2": 10, + "include": ["HALL_SENSOR"], + "description": "If the unit has a hall effect sensor (Pinecil), this adjusts how long the device takes before it drops down to the sleep temperature when hall sensor is over threshold." + }, + { + "id": "TemperatureUnit", + "maxLen": 6, + "maxLen2": 13, + "description": "If the device shows temperatures in °C or °F." + }, + { + "id": "DisplayRotation", + "maxLen": 6, + "maxLen2": 13, + "exclude": ["NO_DISPLAY_ROTATE"], + "description": "If the display should rotate automatically or if it should be fixed for left- or right-handed mode." + }, + { + "id": "CooldownBlink", + "maxLen": 6, + "maxLen2": 13, + "description": "If the idle screen should blink the tip temperature for attention while the tip is over 50°C. Intended as a 'tip is still hot' warning." + }, + { + "id": "ScrollingSpeed", + "maxLen": 6, + "maxLen2": 11, + "description": "How fast the description text scrolls when hovering on a menu. Faster speeds may induce tearing, but allow reading the whole description faster." + }, + { + "id": "ReverseButtonTempChange", + "maxLen": 6, + "maxLen2": 15, + "description": "Swaps which button increments and decrements on temperature change screens." + }, + { + "id": "ReverseButtonSettings", + "maxLen": 6, + "maxLen2": 15, + "description": "Swaps which button is used as Enter/Change and as Scroll/Back in Settings menu." + }, + { + "id": "AnimSpeed", + "maxLen": 6, + "maxLen2": 13, + "description": "How fast should the menu animations loop, or if they should not loop at all." + }, + { + "id": "AnimLoop", + "maxLen": 6, + "maxLen2": 13, + "description": "Should the menu animations loop. Only visible if the animation speed is not set to \"Off\"" + }, + { + "id": "Brightness", + "maxLen": 7, + "maxLen2": 15, + "description": "Display brightness. Higher values age the OLED faster due to burn-in. (However, it is notable that most of these screens die from other causes first.)" + }, + { + "id": "ColourInversion", + "maxLen": 7, + "maxLen2": 15, + "description": "Inverts the entire OLED." + }, + { + "id": "LOGOTime", + "maxLen": 7, + "maxLen2": 15, + "description": "Sets the duration for the boot logo (s=seconds)." + }, + { + "id": "AdvancedIdle", + "maxLen": 6, + "maxLen2": 13, + "description": "Should the device show an 'advanced' view on the idle screen. The advanced view uses text to show more details than the typical icons." + }, + { + "id": "AdvancedSoldering", + "maxLen": 6, + "maxLen2": 13, + "description": "Should the device show an 'advanced' soldering view. This is a text-based view that shows more information at the cost of no nice graphics." + }, + { + "id": "BluetoothLE", + "maxLen": 7, + "maxLen2": 15, + "include": ["BLE_ENABLED"], + "description": "Should BLE be enabled at boot time." + }, + { + "id": "PowerLimit", + "maxLen": 5, + "maxLen2": 11, + "description": "Allows setting a custom wattage for the device to aim to keep the AVERAGE power below. The unit can't control its peak power no matter how you set this. (Except for MHP30 which will regulate nicely to this). If USB-PD is in use, the limit will be set to the lower of this and the supplies advertised wattage." + }, + { + "id": "CalibrateCJC", + "maxLen": 8, + "maxLen2": 15, + "description": "Note:\r\nIf the difference between the target temperature and the measured temperature is less than 5°C, **calibration is NOT required at all**.\r\n\r\nThis is used to calibrate the offset between ADC and Op-amp of the tip **at next boot** (Ideally it has to be done at boot, before internal components get warm.). If the checkbox is set, the calibration will only be performed at the next boot. After a successful calibration the checkbox will be unchecked again! If you need to repeat the calibration however, you have to set the checkbox *again*, unplug your device and let it cool down to room/ambient temperature & power it up, ideally while it sits on the desk.\r\n\r\n\r\nAlso, the calibration will only take place if both of the following conditions are met:\r\n- The tip must be installed.\r\n- The temperature difference between tip and handle must be less than 10°C. (~ ambient / room temperature)\r\n\r\nOtherwise, the calibration will be performed the next time the device is started and both conditions are met, unless the corresponding checkbox is unchecked.\r\nHence, never repeat the calibration in quick succession!" + }, + { + "id": "VoltageCalibration", + "maxLen": 8, + "maxLen2": 15, + "description": "Enters an adjustment mode where you can gradually adjust the measured voltage to compensate for any unit-to-unit variance in the voltage sense resistors." + }, + { + "id": "PowerPulsePower", + "maxLen": 6, + "maxLen2": 15, + "description": "Enables and sets the wattage of the power pulse. Power pulse causes the device to briefly turn on the heater to draw power to avoid power banks going to sleep." + }, + { + "id": "PowerPulseWait", + "maxLen": 6, + "maxLen2": 13, + "description": "Adjusts the time interval between power pulses. Longer gaps reduce undesired heating of the tip, but needs to be fast enough to keep your power bank awake." + }, + { + "id": "PowerPulseDuration", + "maxLen": 6, + "maxLen2": 13, + "description": "How long should the power pulse go for. Some power banks require seeing the power draw be sustained for a certain duration to keep awake. Should be kept as short as possible to avoid wasting power / undesired heating of the tip." + }, + { + "id": "SettingsReset", + "maxLen": 8, + "maxLen2": 15, + "description": "Resets all settings and calibrations to factory defaults. Does NOT erase custom user boot up logo's." + }, + { + "id": "LanguageSwitch", + "maxLen": 7, + "maxLen2": 15, + "description": "Changes the device language on multi-lingual builds." + }, + { + "id": "SolderingTipType", + "maxLen": 7, + "maxLen2": 15, + "description": "For manually selecting the type of tip fitted" + } + ] +} diff --git a/scripts/IronOS-mkdocs.yml b/scripts/IronOS-mkdocs.yml index cb41061ca..4966bbc44 100644 --- a/scripts/IronOS-mkdocs.yml +++ b/scripts/IronOS-mkdocs.yml @@ -12,10 +12,10 @@ edit_uri: edit/dev/Documentation/ # Theme and config theme: - name: readthedocs - highlightsjs: true - hljs_languages: - - yaml + name: readthedocs + highlightsjs: true + hljs_languages: + - yaml # Navigation structure nav: @@ -35,12 +35,15 @@ nav: - Temperature: Temperature.md - Startup Logo: Logo.md - Hardware: - - Hall Sensor (Pinecil): HallSensor.md - Bluetooth (Pinecil V2): Bluetooth.md + - Debugging USB-PD: DebuggingPD.md + - Hall Sensor (Pinecil): HallSensor.md - Hardware Notes: Hardware.md - - Troubleshooting: Troubleshooting.md - Known Hardware Issues: HardwareIssues.md + - New Hardware Requirements: PortingToNewDevice.md - Power sources: PowerSources.md + - Troubleshooting: Troubleshooting.md + - WS2812B RGB Modding (Pinecil V2): WS2812BModding.md - Translations: Translation.md - Development: Development.md - Changelog: History.md diff --git a/scripts/IronOS.Dockerfile b/scripts/IronOS.Dockerfile index 8da2e4af3..fa4d3a22b 100644 --- a/scripts/IronOS.Dockerfile +++ b/scripts/IronOS.Dockerfile @@ -1,6 +1,7 @@ # Default Reference Distro for development env & deploy: -# * Alpine Linux, version 3.16 * -FROM alpine:3.16 +# * Alpine Linux, version 3.21 * + +FROM alpine:3.21 LABEL maintainer="Ben V. Brown " # Default current dir when container starts @@ -14,7 +15,7 @@ WORKDIR /build/ironos ## - clang (required for clang-format to check C++ code formatting) ## - shellcheck (to check sh scripts) -ARG APK_COMPS="gcc-riscv-none-elf gcc-arm-none-eabi newlib-riscv-none-elf newlib-arm-none-eabi" +ARG APK_COMPS="gcc-riscv-none-elf g++-riscv-none-elf gcc-arm-none-eabi g++-arm-none-eabi newlib-riscv-none-elf newlib-arm-none-eabi" ARG APK_PYTHON="python3 py3-pip black" ARG APK_MISC="findutils make git diffutils zip" ARG APK_DEV="musl-dev clang bash clang-extra-tools shellcheck" @@ -25,8 +26,8 @@ ARG PIP_PKGS='bdflib flake8 pymdown-extensions mkdocs mkdocs-autolinks-plugin mk # Install system packages using alpine package manager RUN apk add --no-cache ${APK_COMPS} ${APK_PYTHON} ${APK_MISC} ${APK_DEV} -# Install Python3 packages as modules using pip -RUN python3 -m pip install ${PIP_PKGS} +# Install Python3 packages as modules using pip, yes we dont care if packages break +RUN python3 -m pip install --break-system-packages ${PIP_PKGS} # Git trust to avoid related warning RUN git config --global --add safe.directory /build/ironos diff --git a/scripts/deploy.sh b/scripts/deploy.sh index f7964ce49..5ebd28df3 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -19,7 +19,9 @@ usage() echo -e "\tbuild - compile builds of IronOS inside docker container for supported hardware" echo -e "\tclean - delete created docker image for IronOS & its build cache objects\n" echo "CMD (helper routines):" + echo -e "\tdocs - high level target to run docs_readme and docs_history (see below)\n" echo -e "\tdocs_readme - generate & OVERWRITE(!) README.md inside Documentation/ based on nav section from mkdocs.yml if it changed\n" + echo -e "\tdocs_history - check if History.md has the changelog for the latest stable release\n" echo -e "\tcheck_style_file SRC - run code style checks based on clang-format & custom parsers for source code file SRC\n" echo -e "\tcheck_style_log - run clang-format using source/Makefile and generate gcc-compatible error log in source/check-style.log\n" echo -e "STORAGE NOTICE: for \"shell\" and \"build\" commands extra files will be downloaded so make sure that you have ~5GB of free space.\n" @@ -71,6 +73,76 @@ EOF return "${ret}" } +# Documentation/History.md automagical changelog routine +docs_history() +{ + md="Documentation/History.md" + ver_md="$(sed -ne 's/^## //1p' "${md}" | head -1)" + echo "Latest changelog: ${ver_md}" + ver_git="$(git tag -l | sort | grep -e "^v" | grep -v "rc" | tail -1)" + echo "Latest release tag: ${ver_git}" + ret=0 + if [ "${ver_md}" != "${ver_git}" ]; then + ret=1 + echo "It seems there is no changelog information for ${ver_git} in ${md} yet." + echo "Please, update changelog information in ${md}." + fi; + return "${ret}" +} + +# Check for links to release builds in README.md +docs_links() +{ + ver_git="$(git tag -l | sort | grep -e "^v" | grep -v "rc" | tail -1)" + md="README.md" + test -f "${md}" || (echo "deploy.sh: docs_links: ERROR with the project directory structure!" && exit 1) + ver_md="$(grep -c "${ver_git}" "${md}")" + ret=0 + if [ "${ver_md}" -eq 0 ]; then + ret=1 + echo "Please, update mention & links in ${md} inside Builds section for release builds with version ${ver_git}." + fi; + return "${ret}" +} + +# source/Makefile:ALL_LANGUAGES & Translations/*.json automagical routine +build_langs() +{ + mk="../source/Makefile" + cd Translations/ || (echo "deploy.sh: build_langs: ERROR with the project directory structure!" && exit 1) + langs="$(echo "$(find ./*.json | sed -ne 's,^\./translation_,,; s,\.json$,,; /[A-Z]/p' ; sed -ne 's/^ALL_LANGUAGES=//p;' "${mk}")" | sed 's, ,\n,g; s,\r,,g' | sort | uniq -u)" + if [ -n "${langs}" ]; then + echo "It seems there is mismatch between supported languages and enabled builds." + echo "Please, check files in Translations/ and ALL_LANGUAGES variable in source/Makefile for:" + echo "${langs}" + return 1 + fi; + cd .. + + echo -ne "\n" + grep -nH $'\11' Translations/translation*.json + ret="${?}" + if [ "${ret}" -eq 0 ]; then + echo -ne "\t^^^^\t^^^^\n" + echo "Please, remove any tabs as indention from json file(s) in Translations/ directory (see the exact files & lines in the list above)." + echo "Use spaces only to indent in the future, please." + echo -ne "\n" + return 1 + fi; + + grep -nEH -e "^( {1}| {3}| {5}| {7}| {9}| {11})[^ ]" Translations/translation*.json + ret="${?}" + if [ "${ret}" -eq 0 ]; then + echo -ne "\t^^^^\t^^^^\n" + echo "Please, remove any odd amount of extra spaces as indention from json file(s) in Translations/ directory (see the exact files & lines in the list above)." + echo "Use even amount of spaces to indent in the future, please (two actual spaces per one indent, not tab)." + echo -ne "\n" + return 1 + fi; + + return 0 +} + # Helper function to check code style using clang-format & grep/sed custom parsers: # - basic logic moved from source/Makefile : `check-style` target for better maintainance since a lot of sh script involved; # - output goes in gcc-like error compatible format for IDEs/editors. @@ -91,21 +163,6 @@ check_style_file() fi; ret=1 fi; - # - clang-format has neat option for { } in condition blocks but it's available only since version 15: - # * https://clang.llvm.org/docs/ClangFormatStyleOptions.html#insertbraces - # - since reference env is alpine 3.16 with clang-format 13, implement custom parser to do the similar thing here with grep: - # it used to trace missing { and } for if/else/do/while/for BUT IT'S VERY SPECULATIVE, very-very hacky & dirty. - # - if file is problematic but filename only requested make final grep in pipe silent ... UPD: make code messy but shellcheck happy - if [ -z "${LIST}" ]; then - grep -H -n -e "^ .*if .*)$" -e "^ .*else$" -e "^ .* do$" -e "^ .*while .*)$" -e "^ .*for .*)$" "${src}" | grep -v -e "^.*//" -e "^.*:.*: .*if ((.*[^)])$" | sed 's,^,\n\n,; s,: ,:1: error: probably missing { or } for conditional or loop block:\n>>>,;' | grep -e "^.*$" - else - grep -H -n -e "^ .*if .*)$" -e "^ .*else$" -e "^ .* do$" -e "^ .*while .*)$" -e "^ .*for .*)$" "${src}" | grep -v -e "^.*//" -e "^.*:.*: .*if ((.*[^)])$" | sed 's,^,\n\n,; s,: ,:1: error: probably missing { or } for conditional or loop block:\n>>>,;' | grep -q -e "^.*$" - fi; - if [ "${?}" -ne 1 ]; then - # ... and only print the filename - test -z "${LIST}" || echo "${src}" - ret=1; - fi; return "${ret}" } @@ -141,27 +198,46 @@ docker_file="-f ${root_dir}/${docker_conf}" # (compose sub-command must be included, i.e. DOCKER_BIN="/usr/local/bin/docker compose" ./deploy.sh) if [ -z "${DOCKER_BIN}" ]; then - docker_bin="" + docker_app="" else - docker_bin="${DOCKER_BIN}" + docker_app="${DOCKER_BIN}" fi; # detect availability of docker docker_compose="$(command -v docker-compose)" -if [ -n "${docker_compose}" ] && [ -z "${docker_bin}" ]; then - docker_bin="${docker_compose}" +if [ -n "${docker_compose}" ] && [ -z "${docker_app}" ]; then + docker_app="${docker_compose}" fi; docker_tool="$(command -v docker)" -if [ -n "${docker_tool}" ] && [ -z "${docker_bin}" ]; then - docker_bin="${docker_tool} compose" +if [ -n "${docker_tool}" ] && [ -z "${docker_app}" ]; then + docker_app="${docker_tool} compose" fi; # give function argument a name cmd="${1}" +# meta target to verify markdown documents + +if [ "docs" = "${cmd}" ]; then + docs_readme + readme="${?}" + docs_history + hist="${?}" + build_langs + langs="${?}" + docs_links + links="${?}" + if [ "${readme}" -eq 0 ] && [ "${hist}" -eq 0 ] && [ "${langs}" -eq 0 ] && [ "${links}" -eq 0 ]; then + ret=0 + else + ret=1 + fi; + exit ${ret} +fi; + # if only README.md for Documentation update is required then run it & exit if [ "docs_readme" = "${cmd}" ]; then @@ -169,6 +245,23 @@ if [ "docs_readme" = "${cmd}" ]; then exit "${?}" fi; +# if only History.md for Documentation update is required then run it & exit + +if [ "docs_history" = "${cmd}" ]; then + docs_history + exit "${?}" +fi; + +if [ "build_langs" = "${cmd}" ]; then + build_langs + exit "${?}" +fi; + +if [ "docs_links" = "${cmd}" ]; then + docs_links + exit "${?}" +fi; + if [ "check_style_file" = "${cmd}" ]; then check_style_file "${2}" exit "${?}" @@ -181,7 +274,7 @@ fi; # if docker is not presented in any way show warning & exit -if [ -z "${docker_bin}" ]; then +if [ -z "${docker_app}" ]; then echo "ERROR: Can't find docker-compose nor docker tool. Please, install docker and try again." exit 1 fi; @@ -209,6 +302,6 @@ if [ "${cmd}" = "shell" ]; then echo -e "\t* type \"exit\" to end the session when done;" fi; echo -e "\t* type \"${0} clean\" to delete created container (but not cached data)" -echo -e "\n====>>>> ${docker_bin} ${docker_file} ${docker_cmd}\n" -eval "${docker_bin} ${docker_file} ${docker_cmd}" +echo -e "\n====>>>> ${docker_app} ${docker_file} ${docker_cmd}\n" +eval "${docker_app} ${docker_file} ${docker_cmd}" exit "${?}" diff --git a/scripts/flash_ts100_linux.sh b/scripts/flash_ts10X_linux.sh similarity index 73% rename from scripts/flash_ts100_linux.sh rename to scripts/flash_ts10X_linux.sh index dbd65a778..c33c9d066 100755 --- a/scripts/flash_ts100_linux.sh +++ b/scripts/flash_ts10X_linux.sh @@ -1,19 +1,21 @@ #!/bin/bash # TS100 Flasher for Linux by Alex Wigen (https://github.com/awigen) # Jan 2021 - Update by Ysard (https://github.com/ysard) +# Jul 2025 - Update by Karakurt -DIR_TMP="/tmp/ts100" +DIR_TMP="/tmp/ironos" HEX_FIRMWARE="$DIR_TMP/ts100.hex" +MAX_TRIES=5 usage() { echo - echo "#################" - echo "# TS100 Flasher #" - echo "#################" + echo "#######################" + echo "# TS100/TS101 Flasher #" + echo "#######################" echo echo " Usage: $0 " echo - echo "This script has been tested to work on Fedora." + echo "This script has been tested to work on Fedora and Arch Linux." echo "If you experience any issues please open a ticket at:" echo "https://github.com/Ralim/IronOS/issues/new" echo @@ -44,12 +46,12 @@ is_attached() { } instructions="not printed" -wait_for_ts100() { +wait_for_iron() { while ! is_attached; do if [ "$instructions" = "not printed" ]; then echo echo "#####################################################" - echo "# Waiting for TS100 config disk device to appear #" + echo "# Waiting for config disk device to appear #" echo "# #" echo "# Connect the soldering iron with a USB cable while #" echo "# holding the button closest to the tip pressed #" @@ -61,21 +63,22 @@ wait_for_ts100() { done } -mount_ts100() { +mount_iron() { mkdir -p "$DIR_TMP" user="${UID:-$(id -u)}" - if ! sudo mount -t msdos -o uid=$user "$DEVICE" "$DIR_TMP"; then + if ! sudo mount -t msdos -o uid="$user" "$DEVICE" "$DIR_TMP"; then echo "Failed to mount $DEVICE on $DIR_TMP" exit 1 fi } -umount_ts100() { +umount_iron() { if ! (mountpoint "$DIR_TMP" > /dev/null && sudo umount "$DIR_TMP"); then echo "Failed to unmount $DIR_TMP" exit 1 fi - rmdir "$DIR_TMP" + sleep 1 + sudo rmdir "$DIR_TMP" } check_flash() { @@ -84,19 +87,22 @@ check_flash() { if [ -f "$RDY_FIRMWARE" ]; then echo -e "\e[92mFlash is done\e[0m" echo "Disconnect the USB and power up the iron. You're good to go." + return 0 elif [ -f "$ERR_FIRMWARE" ]; then echo -e "\e[91mFlash error; Please retry!\e[0m" + return 1 else echo -e "\e[91mUNKNOWN error\e[0m" echo "Flash result: " ls "$DIR_TMP"/ts100* + return 1 fi } cleanup() { enable_gautomount if [ -d "$DIR_TMP" ]; then - umount_ts100 + umount_iron fi } trap cleanup EXIT @@ -121,20 +127,28 @@ fi disable_gautomount -wait_for_ts100 -echo "Found TS100 config disk device on $DEVICE" - -mount_ts100 -echo "Mounted config disk drive, flashing..." -cp -v "$1" "$HEX_FIRMWARE" -sync - -echo "Waiting for TS100 to flash" -sleep 5 - -echo "Remounting config disk drive" -umount_ts100 -wait_for_ts100 -mount_ts100 -check_flash +TRIES=0 +while [ $TRIES -lt $MAX_TRIES ]; do + wait_for_iron + NAME=$(sudo fatlabel "$DEVICE" 2>/dev/null) + echo "Found $NAME config disk device on $DEVICE" + + mount_iron + echo "Mounted config disk drive, flashing..." + dd if="$1" of="$HEX_FIRMWARE" oflag=direct + umount_iron + + echo "Waiting for $NAME to flash" + sleep 5 + + echo "Remounting config disk drive" + wait_for_iron + mount_iron + check_flash && exit 0 + + echo "Retrying automatically..." + TRIES=$((TRIES + 1)) +done +echo -e "\e[91mMax retries reached.\e[0m" +exit 1 diff --git a/source/.clang-format b/source/.clang-format index a737f88cf..a7bddf26a 100644 --- a/source/.clang-format +++ b/source/.clang-format @@ -1,139 +1,236 @@ -# Roughly based on LLVM, tweaked a tad for readability on wide screens --- -Language: Cpp +Language: Cpp # BasedOnStyle: LLVM AccessModifierOffset: -2 AlignAfterOpenBracket: Align -AlignConsecutiveMacros: true -AlignConsecutiveAssignments: true -AlignConsecutiveDeclarations: true -AlignEscapedNewlines: Left -AlignOperands: true -AlignTrailingComments: true +AlignArrayOfStructures: Right +AlignConsecutiveAssignments: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 AllowAllArgumentsOnNextLine: true -AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: Empty +AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: true AllowShortFunctionsOnASingleLine: All -AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All AllowShortLoopsOnASingleLine: false -AllowShortEnumsOnASingleLine: false ### <<< Keeps enums as is AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability BinPackArguments: true BinPackParameters: true +BitFieldColonSpacing: Both BraceWrapping: - AfterCaseLabel: false - AfterClass: false - AfterControlStatement: false - AfterEnum: false - AfterFunction: false - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false AfterExternBlock: false - BeforeCatch: false - BeforeElse: false - IndentBraces: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true -BreakBeforeBinaryOperators: true +BreakAfterAttributes: Never +BreakAfterJavaFieldAnnotations: false +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always BreakBeforeBraces: Attach -BreakBeforeInheritanceComma: false -BreakInheritanceList: BeforeColon +BreakBeforeInlineASMColon: OnlyMultiline BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeColon -BreakAfterJavaFieldAnnotations: false +BreakInheritanceList: BeforeColon BreakStringLiterals: true -ColumnLimit: 200 -CommentPragmas: '^ IWYU pragma:' +ColumnLimit: 200 +CommentPragmas: "^ IWYU pragma:" CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true -DeriveLineEnding: true DerivePointerAlignment: false -DisableFormat: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH -IncludeBlocks: Preserve +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve IncludeCategories: - - Regex: '^"(llvm|llvm-c|clang|clang-c)/' - Priority: 2 - SortPriority: 0 - - Regex: '^(<|"(gtest|gmock|isl|json)/)' - Priority: 3 - SortPriority: 0 - - Regex: '.*' - Priority: 1 - SortPriority: 0 -IncludeIsMainRegex: '(Test)?$' -IncludeIsMainSourceRegex: '' + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: ".*" + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: "(Test)?$" +IncludeIsMainSourceRegex: "" +IndentAccessModifiers: false +IndentCaseBlocks: false IndentCaseLabels: false +IndentExternBlock: AfterExternBlock IndentGotoLabels: true IndentPPDirectives: None -IndentWidth: 2 +IndentRequiresClause: true +IndentWidth: 2 IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: true -MacroBlockBegin: '' -MacroBlockEnd: '' +KeepEmptyLinesAtEOF: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: "" +MacroBlockEnd: "" MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Auto ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: BinPack PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Right -ReflowComments: true -SortIncludes: true -SortUsingDeclarations: true +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric SpaceAfterCStyleCast: false SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false SpaceInEmptyBlock: false -SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 -SpacesInAngles: false -SpacesInConditionalStatement: false +SpacesInAngles: Never SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false SpacesInSquareBrackets: false -SpaceBeforeSquareBrackets: false -Standard: Latest +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION -TabWidth: 8 -UseCRLF: false -UseTab: Never -... +TabWidth: 8 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +--- diff --git a/source/Core/BSP/BSP_Power.h b/source/Core/BSP/BSP_Power.h index 348dc7a76..d37106f12 100644 --- a/source/Core/BSP/BSP_Power.h +++ b/source/Core/BSP/BSP_Power.h @@ -8,6 +8,8 @@ #ifndef BSP_POWER_H_ #define BSP_POWER_H_ +#include "Types.h" + #ifdef __cplusplus extern "C" { #endif @@ -22,6 +24,8 @@ uint8_t getTipResistanceX10(); uint16_t getTipThermalMass(); uint16_t getTipInertia(); +TemperatureType_t getCustomTipMaxInC(); + #ifdef __cplusplus } #endif diff --git a/source/Core/BSP/MHP30/BSP.cpp b/source/Core/BSP/MHP30/BSP.cpp index 70149f4f9..aa88f28e8 100644 --- a/source/Core/BSP/MHP30/BSP.cpp +++ b/source/Core/BSP/MHP30/BSP.cpp @@ -6,7 +6,7 @@ #include "Pins.h" #include "Setup.h" #include "TipThermoModel.h" -#include "Utils.h" +#include "Utils.hpp" #include "WS2812.h" #include "configuration.h" #include "history.hpp" @@ -230,8 +230,9 @@ uint16_t getInputVoltageX10(uint16_t divisor, uint8_t sample) { static uint32_t samples[BATTFILTERDEPTH]; static uint8_t index = 0; if (preFillneeded) { - for (uint8_t i = 0; i < BATTFILTERDEPTH; i++) + for (uint8_t i = 0; i < BATTFILTERDEPTH; i++) { samples[i] = getADC(1); + } preFillneeded--; } if (sample) { @@ -240,8 +241,9 @@ uint16_t getInputVoltageX10(uint16_t divisor, uint8_t sample) { } uint32_t sum = 0; - for (uint8_t i = 0; i < BATTFILTERDEPTH; i++) + for (uint8_t i = 0; i < BATTFILTERDEPTH; i++) { sum += samples[i]; + } sum /= BATTFILTERDEPTH; if (divisor == 0) { @@ -263,25 +265,6 @@ void unstick_I2C() { int timeout = 100; int timeout_cnt = 0; - // 1. Clear PE bit. - hi2c1.Instance->CR1 &= ~(0x0001); - /**I2C1 GPIO Configuration - PB6 ------> I2C1_SCL - PB7 ------> I2C1_SDA - */ - // 2. Configure the SCL and SDA I/Os as General Purpose Output Open-Drain, High level (Write 1 to GPIOx_ODR). - GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD; - GPIO_InitStruct.Pull = GPIO_PULLUP; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; - - GPIO_InitStruct.Pin = SCL_Pin; - HAL_GPIO_Init(SCL_GPIO_Port, &GPIO_InitStruct); - HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET); - - GPIO_InitStruct.Pin = SDA_Pin; - HAL_GPIO_Init(SDA_GPIO_Port, &GPIO_InitStruct); - HAL_GPIO_WritePin(SDA_GPIO_Port, SDA_Pin, GPIO_PIN_SET); - while (GPIO_PIN_SET != HAL_GPIO_ReadPin(SDA_GPIO_Port, SDA_Pin)) { // Move clock to release I2C HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_RESET); @@ -292,39 +275,10 @@ void unstick_I2C() { HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET); timeout_cnt++; - if (timeout_cnt > timeout) + if (timeout_cnt > timeout) { return; + } } - - // 12. Configure the SCL and SDA I/Os as Alternate function Open-Drain. - GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; - GPIO_InitStruct.Pull = GPIO_PULLUP; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; - - GPIO_InitStruct.Pin = SCL_Pin; - HAL_GPIO_Init(SCL_GPIO_Port, &GPIO_InitStruct); - - GPIO_InitStruct.Pin = SDA_Pin; - HAL_GPIO_Init(SDA_GPIO_Port, &GPIO_InitStruct); - - HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET); - HAL_GPIO_WritePin(SDA_GPIO_Port, SDA_Pin, GPIO_PIN_SET); - - // 13. Set SWRST bit in I2Cx_CR1 register. - hi2c1.Instance->CR1 |= 0x8000; - - asm("nop"); - - // 14. Clear SWRST bit in I2Cx_CR1 register. - hi2c1.Instance->CR1 &= ~0x8000; - - asm("nop"); - - // 15. Enable the I2C peripheral by setting the PE bit in I2Cx_CR1 register - hi2c1.Instance->CR1 |= 0x0001; - - // Call initialization function. - HAL_I2C_Init(&hi2c1); } uint8_t getButtonA() { return HAL_GPIO_ReadPin(KEY_A_GPIO_Port, KEY_A_Pin) == GPIO_PIN_RESET ? 1 : 0; } @@ -341,15 +295,9 @@ void setPlatePullup(bool pullingUp) { GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Pin = PLATE_SENSOR_PULLUP_Pin; GPIO_InitStruct.Pull = GPIO_NOPULL; - if (pullingUp) { - GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; - HAL_GPIO_WritePin(PLATE_SENSOR_PULLUP_GPIO_Port, PLATE_SENSOR_PULLUP_Pin, GPIO_PIN_SET); - } else { - // Hi-z - GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; - HAL_GPIO_WritePin(PLATE_SENSOR_PULLUP_GPIO_Port, PLATE_SENSOR_PULLUP_Pin, GPIO_PIN_RESET); - } + GPIO_InitStruct.Mode = pullingUp ? GPIO_MODE_OUTPUT_PP : GPIO_MODE_INPUT; HAL_GPIO_Init(PLATE_SENSOR_PULLUP_GPIO_Port, &GPIO_InitStruct); + HAL_GPIO_WritePin(PLATE_SENSOR_PULLUP_GPIO_Port, PLATE_SENSOR_PULLUP_Pin, pullingUp ? GPIO_PIN_SET : GPIO_PIN_RESET); } void performTipMeasurementStep(bool start) { diff --git a/source/Core/BSP/MHP30/FreeRTOSConfig.h b/source/Core/BSP/MHP30/FreeRTOSConfig.h index c051701a7..7e5dba58d 100644 --- a/source/Core/BSP/MHP30/FreeRTOSConfig.h +++ b/source/Core/BSP/MHP30/FreeRTOSConfig.h @@ -101,16 +101,16 @@ extern uint32_t SystemCoreClock; #define configUSE_TICK_HOOK 0 #define configCPU_CLOCK_HZ (SystemCoreClock) #define configTICK_RATE_HZ ((TickType_t)1000) -#define configMAX_PRIORITIES (6) +#define configMAX_PRIORITIES (7) #define configMINIMAL_STACK_SIZE ((uint16_t)256) #define configTOTAL_HEAP_SIZE ((size_t)1024 * 14) /*Currently use about 9000*/ #define configMAX_TASK_NAME_LEN (32) -#define configUSE_16_BIT_TICKS 0 #define configUSE_MUTEXES 1 #define configQUEUE_REGISTRY_SIZE 8 #define configUSE_TIMERS 0 #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #define configCHECK_FOR_STACK_OVERFLOW 2 /*Bump this to 2 during development and bug hunting*/ +#define configTICK_TYPE_WIDTH_IN_BITS TICK_TYPE_WIDTH_32_BITS /* Co-routine definitions. */ #define configUSE_CO_ROUTINES 0 @@ -156,11 +156,11 @@ extern uint32_t SystemCoreClock; /* Normal assert() semantics without relying on the provision of an assert.h header file. */ /* USER CODE BEGIN 1 */ -#define configASSERT(x) \ - if ((x) == 0) { \ - taskDISABLE_INTERRUPTS(); \ - for (;;) \ - ; \ +#define configASSERT(x) \ + if ((x) == 0) { \ + taskDISABLE_INTERRUPTS(); \ + for (;;) \ + ; \ } /* USER CODE END 1 */ diff --git a/source/Core/BSP/MHP30/I2C_Wrapper.cpp b/source/Core/BSP/MHP30/I2C_Wrapper.cpp deleted file mode 100644 index 37d521c1c..000000000 --- a/source/Core/BSP/MHP30/I2C_Wrapper.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * FRToSI2C.cpp - * - * Created on: 14Apr.,2018 - * Author: Ralim - */ -#include "BSP.h" -#include "Setup.h" -#include -SemaphoreHandle_t FRToSI2C::I2CSemaphore = nullptr; -StaticSemaphore_t FRToSI2C::xSemaphoreBuffer; - -void FRToSI2C::CpltCallback() { - hi2c1.State = HAL_I2C_STATE_READY; // Force state reset (even if tx error) - if (I2CSemaphore) { - xSemaphoreGiveFromISR(I2CSemaphore, NULL); - } -} - -bool FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) { - - if (!lock()) - return false; - if (HAL_I2C_Mem_Read(&hi2c1, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 500) != HAL_OK) { - - I2C_Unstick(); - unlock(); - return false; - } - - unlock(); - return true; -} -bool FRToSI2C::I2C_RegisterWrite(uint8_t address, uint8_t reg, uint8_t data) { return Mem_Write(address, reg, &data, 1); } - -uint8_t FRToSI2C::I2C_RegisterRead(uint8_t add, uint8_t reg) { - uint8_t tx_data[1]; - Mem_Read(add, reg, tx_data, 1); - return tx_data[0]; -} -bool FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) { - - if (!lock()) - return false; - if (HAL_I2C_Mem_Write(&hi2c1, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 500) != HAL_OK) { - - I2C_Unstick(); - unlock(); - return false; - } - - unlock(); - return true; -} - -bool FRToSI2C::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) - return false; - if (HAL_I2C_Master_Transmit_DMA(&hi2c1, DevAddress, pData, Size) != HAL_OK) { - I2C_Unstick(); - unlock(); - return false; - } - return true; -} - -bool FRToSI2C::probe(uint16_t DevAddress) { - if (!lock()) - return false; - uint8_t buffer[1]; - bool worked = HAL_I2C_Mem_Read(&hi2c1, DevAddress, 0x0F, I2C_MEMADD_SIZE_8BIT, buffer, 1, 1000) == HAL_OK; - unlock(); - return worked; -} - -void FRToSI2C::I2C_Unstick() { unstick_I2C(); } - -void FRToSI2C::unlock() { xSemaphoreGive(I2CSemaphore); } - -bool FRToSI2C::lock() { return xSemaphoreTake(I2CSemaphore, (TickType_t)50) == pdTRUE; } - -bool FRToSI2C::writeRegistersBulk(const uint8_t address, const I2C_REG *registers, const uint8_t registersLength) { - for (int index = 0; index < registersLength; index++) { - if (!I2C_RegisterWrite(address, registers[index].reg, registers[index].val)) { - return false; - } - if (registers[index].pause_ms) - delay_ms(registers[index].pause_ms); - } - return true; -} diff --git a/source/Core/BSP/MHP30/IRQ.cpp b/source/Core/BSP/MHP30/IRQ.cpp index 6b087447a..d5331ed61 100644 --- a/source/Core/BSP/MHP30/IRQ.cpp +++ b/source/Core/BSP/MHP30/IRQ.cpp @@ -27,12 +27,6 @@ void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc) { } } } -void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } extern osThreadId POWTaskHandle; void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { diff --git a/source/Core/BSP/MHP30/IRQ.h b/source/Core/BSP/MHP30/IRQ.h index 9fe3e4ca8..e5631f461 100644 --- a/source/Core/BSP/MHP30/IRQ.h +++ b/source/Core/BSP/MHP30/IRQ.h @@ -18,12 +18,6 @@ extern "C" { #endif void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc); -void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_GPIO_EXTI_Callback(uint16_t); #ifdef __cplusplus diff --git a/source/Core/BSP/MHP30/Setup.c b/source/Core/BSP/MHP30/Setup.c index 79f49626e..b354c6e3a 100644 --- a/source/Core/BSP/MHP30/Setup.c +++ b/source/Core/BSP/MHP30/Setup.c @@ -11,10 +11,6 @@ ADC_HandleTypeDef hadc1; ADC_HandleTypeDef hadc2; DMA_HandleTypeDef hdma_adc1; -I2C_HandleTypeDef hi2c1; -DMA_HandleTypeDef hdma_i2c1_rx; -DMA_HandleTypeDef hdma_i2c1_tx; - IWDG_HandleTypeDef hiwdg; TIM_HandleTypeDef htim2; TIM_HandleTypeDef htim3; @@ -25,7 +21,7 @@ uint32_t ADCReadings[ADC_SAMPLES * ADC_CHANNELS]; // room for 32 lots of the pai // Functions static void SystemClock_Config(void); static void MX_ADC1_Init(void); -static void MX_I2C1_Init(void); + static void MX_IWDG_Init(void); static void MX_TIM3_Init(void); static void MX_TIM2_Init(void); @@ -39,7 +35,7 @@ void Setup_HAL() { MX_GPIO_Init(); MX_DMA_Init(); - MX_I2C1_Init(); + MX_ADC1_Init(); MX_ADC2_Init(); MX_TIM3_Init(); @@ -196,19 +192,6 @@ static void MX_ADC2_Init(void) { ; } } -/* I2C1 init function */ -static void MX_I2C1_Init(void) { - hi2c1.Instance = I2C1; - hi2c1.Init.ClockSpeed = 300000; - hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2; - hi2c1.Init.OwnAddress1 = 0; - hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; - hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; - hi2c1.Init.OwnAddress2 = 0; - hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; - hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; - HAL_I2C_Init(&hi2c1); -} /* IWDG init function */ static void MX_IWDG_Init(void) { @@ -353,8 +336,8 @@ static void MX_GPIO_Init(void) { GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_10 | GPIO_PIN_15; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 - | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15; + GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 | + GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pins : KEY_B_Pin KEY_A_Pin */ diff --git a/source/Core/BSP/MHP30/Setup.h b/source/Core/BSP/MHP30/Setup.h index 045b951c6..c0005f5f1 100644 --- a/source/Core/BSP/MHP30/Setup.h +++ b/source/Core/BSP/MHP30/Setup.h @@ -20,7 +20,6 @@ extern DMA_HandleTypeDef hdma_adc1; extern DMA_HandleTypeDef hdma_i2c1_rx; extern DMA_HandleTypeDef hdma_i2c1_tx; -extern I2C_HandleTypeDef hi2c1; extern IWDG_HandleTypeDef hiwdg; diff --git a/source/Core/BSP/MHP30/Software_I2C.h b/source/Core/BSP/MHP30/Software_I2C.h index a9b1bdc41..e3a95a710 100644 --- a/source/Core/BSP/MHP30/Software_I2C.h +++ b/source/Core/BSP/MHP30/Software_I2C.h @@ -18,13 +18,26 @@ #define SOFT_SDA2_LOW() HAL_GPIO_WritePin(SDA2_GPIO_Port, SDA2_Pin, GPIO_PIN_RESET) #define SOFT_SDA2_READ() (HAL_GPIO_ReadPin(SDA2_GPIO_Port, SDA2_Pin) == GPIO_PIN_SET ? 1 : 0) #define SOFT_SCL2_READ() (HAL_GPIO_ReadPin(SCL2_GPIO_Port, SCL2_Pin) == GPIO_PIN_SET ? 1 : 0) + +#endif + +#ifdef I2C_SOFT_BUS_1 +#define SOFT_SCL1_HIGH() HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET) +#define SOFT_SCL1_LOW() HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_RESET) +#define SOFT_SDA1_HIGH() HAL_GPIO_WritePin(SDA_GPIO_Port, SDA_Pin, GPIO_PIN_SET) +#define SOFT_SDA1_LOW() HAL_GPIO_WritePin(SDA_GPIO_Port, SDA_Pin, GPIO_PIN_RESET) +#define SOFT_SDA1_READ() (HAL_GPIO_ReadPin(SDA_GPIO_Port, SDA_Pin) == GPIO_PIN_SET ? 1 : 0) +#define SOFT_SCL1_READ() (HAL_GPIO_ReadPin(SCL_GPIO_Port, SCL_Pin) == GPIO_PIN_SET ? 1 : 0) + +#endif + #define SOFT_I2C_DELAY() \ { \ - for (int xx = 0; xx < 20; xx++) { \ + for (int xx = 0; xx < 15; xx++) { \ asm("nop"); \ } \ } -#endif +// 40 ~= 100kHz; 15 gives around 250kHz or so which is fast _and_ stable #endif /* BSP_MINIWARE_SOFTWARE_I2C_H_ */ diff --git a/source/Startup/startup_stm32f103t8ux.S b/source/Core/BSP/MHP30/Startup/startup_stm32f103t8ux.S similarity index 100% rename from source/Startup/startup_stm32f103t8ux.S rename to source/Core/BSP/MHP30/Startup/startup_stm32f103t8ux.S diff --git a/source/Core/BSP/MHP30/ThermoModel.cpp b/source/Core/BSP/MHP30/ThermoModel.cpp index 9275d835c..b779aba9c 100644 --- a/source/Core/BSP/MHP30/ThermoModel.cpp +++ b/source/Core/BSP/MHP30/ThermoModel.cpp @@ -7,7 +7,7 @@ #include "Setup.h" #include "TipThermoModel.h" #include "Types.h" -#include "Utils.h" +#include "Utils.hpp" #include "configuration.h" extern uint16_t tipSenseResistancex10Ohms; diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h deleted file mode 100644 index 4acd16342..000000000 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h +++ /dev/null @@ -1,728 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_hal_i2c.h - * @author MCD Application Team - * @brief Header file of I2C HAL module. - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2016 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_HAL_I2C_H -#define __STM32F1xx_HAL_I2C_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_hal_def.h" - -/** @addtogroup STM32F1xx_HAL_Driver - * @{ - */ - -/** @addtogroup I2C - * @{ - */ - -/* Exported types ------------------------------------------------------------*/ -/** @defgroup I2C_Exported_Types I2C Exported Types - * @{ - */ - -/** @defgroup I2C_Configuration_Structure_definition I2C Configuration Structure definition - * @brief I2C Configuration Structure definition - * @{ - */ -typedef struct { - uint32_t ClockSpeed; /*!< Specifies the clock frequency. - This parameter must be set to a value lower than 400kHz */ - - uint32_t DutyCycle; /*!< Specifies the I2C fast mode duty cycle. - This parameter can be a value of @ref I2C_duty_cycle_in_fast_mode */ - - uint32_t OwnAddress1; /*!< Specifies the first device own address. - This parameter can be a 7-bit or 10-bit address. */ - - uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. - This parameter can be a value of @ref I2C_addressing_mode */ - - uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. - This parameter can be a value of @ref I2C_dual_addressing_mode */ - - uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected - This parameter can be a 7-bit address. */ - - uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. - This parameter can be a value of @ref I2C_general_call_addressing_mode */ - - uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. - This parameter can be a value of @ref I2C_nostretch_mode */ - -} I2C_InitTypeDef; - -/** - * @} - */ - -/** @defgroup HAL_state_structure_definition HAL state structure definition - * @brief HAL State structure definition - * @note HAL I2C State value coding follow below described bitmap : - * b7-b6 Error information - * 00 : No Error - * 01 : Abort (Abort user request on going) - * 10 : Timeout - * 11 : Error - * b5 Peripheral initilisation status - * 0 : Reset (Peripheral not initialized) - * 1 : Init done (Peripheral initialized and ready to use. HAL I2C Init function called) - * b4 (not used) - * x : Should be set to 0 - * b3 - * 0 : Ready or Busy (No Listen mode ongoing) - * 1 : Listen (Peripheral in Address Listen Mode) - * b2 Intrinsic process state - * 0 : Ready - * 1 : Busy (Peripheral busy with some configuration or internal operations) - * b1 Rx state - * 0 : Ready (no Rx operation ongoing) - * 1 : Busy (Rx operation ongoing) - * b0 Tx state - * 0 : Ready (no Tx operation ongoing) - * 1 : Busy (Tx operation ongoing) - * @{ - */ -typedef enum { - HAL_I2C_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized */ - HAL_I2C_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use */ - HAL_I2C_STATE_BUSY = 0x24U, /*!< An internal process is ongoing */ - HAL_I2C_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing */ - HAL_I2C_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing */ - HAL_I2C_STATE_LISTEN = 0x28U, /*!< Address Listen Mode is ongoing */ - HAL_I2C_STATE_BUSY_TX_LISTEN = 0x29U, /*!< Address Listen Mode and Data Transmission - process is ongoing */ - HAL_I2C_STATE_BUSY_RX_LISTEN = 0x2AU, /*!< Address Listen Mode and Data Reception - process is ongoing */ - HAL_I2C_STATE_ABORT = 0x60U, /*!< Abort user request ongoing */ - HAL_I2C_STATE_TIMEOUT = 0xA0U, /*!< Timeout state */ - HAL_I2C_STATE_ERROR = 0xE0U /*!< Error */ - -} HAL_I2C_StateTypeDef; - -/** - * @} - */ - -/** @defgroup HAL_mode_structure_definition HAL mode structure definition - * @brief HAL Mode structure definition - * @note HAL I2C Mode value coding follow below described bitmap :\n - * b7 (not used)\n - * x : Should be set to 0\n - * b6\n - * 0 : None\n - * 1 : Memory (HAL I2C communication is in Memory Mode)\n - * b5\n - * 0 : None\n - * 1 : Slave (HAL I2C communication is in Slave Mode)\n - * b4\n - * 0 : None\n - * 1 : Master (HAL I2C communication is in Master Mode)\n - * b3-b2-b1-b0 (not used)\n - * xxxx : Should be set to 0000 - * @{ - */ -typedef enum { - HAL_I2C_MODE_NONE = 0x00U, /*!< No I2C communication on going */ - HAL_I2C_MODE_MASTER = 0x10U, /*!< I2C communication is in Master Mode */ - HAL_I2C_MODE_SLAVE = 0x20U, /*!< I2C communication is in Slave Mode */ - HAL_I2C_MODE_MEM = 0x40U /*!< I2C communication is in Memory Mode */ - -} HAL_I2C_ModeTypeDef; - -/** - * @} - */ - -/** @defgroup I2C_Error_Code_definition I2C Error Code definition - * @brief I2C Error Code definition - * @{ - */ -#define HAL_I2C_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_I2C_ERROR_BERR 0x00000001U /*!< BERR error */ -#define HAL_I2C_ERROR_ARLO 0x00000002U /*!< ARLO error */ -#define HAL_I2C_ERROR_AF 0x00000004U /*!< AF error */ -#define HAL_I2C_ERROR_OVR 0x00000008U /*!< OVR error */ -#define HAL_I2C_ERROR_DMA 0x00000010U /*!< DMA transfer error */ -#define HAL_I2C_ERROR_TIMEOUT 0x00000020U /*!< Timeout Error */ -#define HAL_I2C_ERROR_SIZE 0x00000040U /*!< Size Management error */ -#define HAL_I2C_ERROR_DMA_PARAM 0x00000080U /*!< DMA Parameter Error */ -#define HAL_I2C_WRONG_START 0x00000200U /*!< Wrong start Error */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) -#define HAL_I2C_ERROR_INVALID_CALLBACK 0x00000100U /*!< Invalid Callback error */ -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ -/** - * @} - */ - -/** @defgroup I2C_handle_Structure_definition I2C handle Structure definition - * @brief I2C handle Structure definition - * @{ - */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) -typedef struct __I2C_HandleTypeDef -#else -typedef struct -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ -{ - I2C_TypeDef *Instance; /*!< I2C registers base address */ - - I2C_InitTypeDef Init; /*!< I2C communication parameters */ - - uint8_t *pBuffPtr; /*!< Pointer to I2C transfer buffer */ - - uint16_t XferSize; /*!< I2C transfer size */ - - __IO uint16_t XferCount; /*!< I2C transfer counter */ - - __IO uint32_t XferOptions; /*!< I2C transfer options */ - - __IO uint32_t PreviousState; /*!< I2C communication Previous state and mode - context for internal usage */ - - DMA_HandleTypeDef *hdmatx; /*!< I2C Tx DMA handle parameters */ - - DMA_HandleTypeDef *hdmarx; /*!< I2C Rx DMA handle parameters */ - - HAL_LockTypeDef Lock; /*!< I2C locking object */ - - __IO HAL_I2C_StateTypeDef State; /*!< I2C communication state */ - - __IO HAL_I2C_ModeTypeDef Mode; /*!< I2C communication mode */ - - __IO uint32_t ErrorCode; /*!< I2C Error code */ - - __IO uint32_t Devaddress; /*!< I2C Target device address */ - - __IO uint32_t Memaddress; /*!< I2C Target memory address */ - - __IO uint32_t MemaddSize; /*!< I2C Target memory address size */ - - __IO uint32_t EventCount; /*!< I2C Event counter */ -#ifndef USE_HAL_I2C_REGISTER_CALLBACKS -#define USE_HAL_I2C_REGISTER_CALLBACKS 0 -#endif -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - void (*MasterTxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Master Tx Transfer completed callback */ - void (*MasterRxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Master Rx Transfer completed callback */ - void (*SlaveTxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Slave Tx Transfer completed callback */ - void (*SlaveRxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Slave Rx Transfer completed callback */ - void (*ListenCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Listen Complete callback */ - void (*MemTxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Memory Tx Transfer completed callback */ - void (*MemRxCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Memory Rx Transfer completed callback */ - void (*ErrorCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Error callback */ - void (*AbortCpltCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Abort callback */ - - void (*AddrCallback)(struct __I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode); /*!< I2C Slave Address Match callback */ - - void (*MspInitCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Msp Init callback */ - void (*MspDeInitCallback)(struct __I2C_HandleTypeDef *hi2c); /*!< I2C Msp DeInit callback */ - -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ -} I2C_HandleTypeDef; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) -/** - * @brief HAL I2C Callback ID enumeration definition - */ -typedef enum { - HAL_I2C_MASTER_TX_COMPLETE_CB_ID = 0x00U, /*!< I2C Master Tx Transfer completed callback ID */ - HAL_I2C_MASTER_RX_COMPLETE_CB_ID = 0x01U, /*!< I2C Master Rx Transfer completed callback ID */ - HAL_I2C_SLAVE_TX_COMPLETE_CB_ID = 0x02U, /*!< I2C Slave Tx Transfer completed callback ID */ - HAL_I2C_SLAVE_RX_COMPLETE_CB_ID = 0x03U, /*!< I2C Slave Rx Transfer completed callback ID */ - HAL_I2C_LISTEN_COMPLETE_CB_ID = 0x04U, /*!< I2C Listen Complete callback ID */ - HAL_I2C_MEM_TX_COMPLETE_CB_ID = 0x05U, /*!< I2C Memory Tx Transfer callback ID */ - HAL_I2C_MEM_RX_COMPLETE_CB_ID = 0x06U, /*!< I2C Memory Rx Transfer completed callback ID */ - HAL_I2C_ERROR_CB_ID = 0x07U, /*!< I2C Error callback ID */ - HAL_I2C_ABORT_CB_ID = 0x08U, /*!< I2C Abort callback ID */ - - HAL_I2C_MSPINIT_CB_ID = 0x09U, /*!< I2C Msp Init callback ID */ - HAL_I2C_MSPDEINIT_CB_ID = 0x0AU /*!< I2C Msp DeInit callback ID */ - -} HAL_I2C_CallbackIDTypeDef; - -/** - * @brief HAL I2C Callback pointer definition - */ -typedef void (*pI2C_CallbackTypeDef)(I2C_HandleTypeDef *hi2c); /*!< pointer to an I2C callback function */ -typedef void (*pI2C_AddrCallbackTypeDef)(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode); /*!< pointer to an I2C Address Match callback function */ - -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ -/** - * @} - */ - -/** - * @} - */ -/* Exported constants --------------------------------------------------------*/ - -/** @defgroup I2C_Exported_Constants I2C Exported Constants - * @{ - */ - -/** @defgroup I2C_duty_cycle_in_fast_mode I2C duty cycle in fast mode - * @{ - */ -#define I2C_DUTYCYCLE_2 0x00000000U -#define I2C_DUTYCYCLE_16_9 I2C_CCR_DUTY -/** - * @} - */ - -/** @defgroup I2C_addressing_mode I2C addressing mode - * @{ - */ -#define I2C_ADDRESSINGMODE_7BIT 0x00004000U -#define I2C_ADDRESSINGMODE_10BIT (I2C_OAR1_ADDMODE | 0x00004000U) -/** - * @} - */ - -/** @defgroup I2C_dual_addressing_mode I2C dual addressing mode - * @{ - */ -#define I2C_DUALADDRESS_DISABLE 0x00000000U -#define I2C_DUALADDRESS_ENABLE I2C_OAR2_ENDUAL -/** - * @} - */ - -/** @defgroup I2C_general_call_addressing_mode I2C general call addressing mode - * @{ - */ -#define I2C_GENERALCALL_DISABLE 0x00000000U -#define I2C_GENERALCALL_ENABLE I2C_CR1_ENGC -/** - * @} - */ - -/** @defgroup I2C_nostretch_mode I2C nostretch mode - * @{ - */ -#define I2C_NOSTRETCH_DISABLE 0x00000000U -#define I2C_NOSTRETCH_ENABLE I2C_CR1_NOSTRETCH -/** - * @} - */ - -/** @defgroup I2C_Memory_Address_Size I2C Memory Address Size - * @{ - */ -#define I2C_MEMADD_SIZE_8BIT 0x00000001U -#define I2C_MEMADD_SIZE_16BIT 0x00000010U -/** - * @} - */ - -/** @defgroup I2C_XferDirection_definition I2C XferDirection definition - * @{ - */ -#define I2C_DIRECTION_RECEIVE 0x00000000U -#define I2C_DIRECTION_TRANSMIT 0x00000001U -/** - * @} - */ - -/** @defgroup I2C_XferOptions_definition I2C XferOptions definition - * @{ - */ -#define I2C_FIRST_FRAME 0x00000001U -#define I2C_FIRST_AND_NEXT_FRAME 0x00000002U -#define I2C_NEXT_FRAME 0x00000004U -#define I2C_FIRST_AND_LAST_FRAME 0x00000008U -#define I2C_LAST_FRAME_NO_STOP 0x00000010U -#define I2C_LAST_FRAME 0x00000020U - -/* List of XferOptions in usage of : - * 1- Restart condition in all use cases (direction change or not) - */ -#define I2C_OTHER_FRAME (0x00AA0000U) -#define I2C_OTHER_AND_LAST_FRAME (0xAA000000U) -/** - * @} - */ - -/** @defgroup I2C_Interrupt_configuration_definition I2C Interrupt configuration definition - * @brief I2C Interrupt definition - * Elements values convention: 0xXXXXXXXX - * - XXXXXXXX : Interrupt control mask - * @{ - */ -#define I2C_IT_BUF I2C_CR2_ITBUFEN -#define I2C_IT_EVT I2C_CR2_ITEVTEN -#define I2C_IT_ERR I2C_CR2_ITERREN -/** - * @} - */ - -/** @defgroup I2C_Flag_definition I2C Flag definition - * @{ - */ - -#define I2C_FLAG_OVR 0x00010800U -#define I2C_FLAG_AF 0x00010400U -#define I2C_FLAG_ARLO 0x00010200U -#define I2C_FLAG_BERR 0x00010100U -#define I2C_FLAG_TXE 0x00010080U -#define I2C_FLAG_RXNE 0x00010040U -#define I2C_FLAG_STOPF 0x00010010U -#define I2C_FLAG_ADD10 0x00010008U -#define I2C_FLAG_BTF 0x00010004U -#define I2C_FLAG_ADDR 0x00010002U -#define I2C_FLAG_SB 0x00010001U -#define I2C_FLAG_DUALF 0x00100080U -#define I2C_FLAG_GENCALL 0x00100010U -#define I2C_FLAG_TRA 0x00100004U -#define I2C_FLAG_BUSY 0x00100002U -#define I2C_FLAG_MSL 0x00100001U -/** - * @} - */ - -/** - * @} - */ - -/* Exported macros -----------------------------------------------------------*/ - -/** @defgroup I2C_Exported_Macros I2C Exported Macros - * @{ - */ - -/** @brief Reset I2C handle state. - * @param __HANDLE__ specifies the I2C Handle. - * @retval None - */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) -#define __HAL_I2C_RESET_HANDLE_STATE(__HANDLE__) \ - do { \ - (__HANDLE__)->State = HAL_I2C_STATE_RESET; \ - (__HANDLE__)->MspInitCallback = NULL; \ - (__HANDLE__)->MspDeInitCallback = NULL; \ - } while (0) -#else -#define __HAL_I2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2C_STATE_RESET) -#endif - -/** @brief Enable or disable the specified I2C interrupts. - * @param __HANDLE__ specifies the I2C Handle. - * @param __INTERRUPT__ specifies the interrupt source to enable or disable. - * This parameter can be one of the following values: - * @arg I2C_IT_BUF: Buffer interrupt enable - * @arg I2C_IT_EVT: Event interrupt enable - * @arg I2C_IT_ERR: Error interrupt enable - * @retval None - */ -#define __HAL_I2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CR2, (__INTERRUPT__)) -#define __HAL_I2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) CLEAR_BIT((__HANDLE__)->Instance->CR2, (__INTERRUPT__)) - -/** @brief Checks if the specified I2C interrupt source is enabled or disabled. - * @param __HANDLE__ specifies the I2C Handle. - * @param __INTERRUPT__ specifies the I2C interrupt source to check. - * This parameter can be one of the following values: - * @arg I2C_IT_BUF: Buffer interrupt enable - * @arg I2C_IT_EVT: Event interrupt enable - * @arg I2C_IT_ERR: Error interrupt enable - * @retval The new state of __INTERRUPT__ (TRUE or FALSE). - */ -#define __HAL_I2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) - -/** @brief Checks whether the specified I2C flag is set or not. - * @param __HANDLE__ specifies the I2C Handle. - * @param __FLAG__ specifies the flag to check. - * This parameter can be one of the following values: - * @arg I2C_FLAG_OVR: Overrun/Underrun flag - * @arg I2C_FLAG_AF: Acknowledge failure flag - * @arg I2C_FLAG_ARLO: Arbitration lost flag - * @arg I2C_FLAG_BERR: Bus error flag - * @arg I2C_FLAG_TXE: Data register empty flag - * @arg I2C_FLAG_RXNE: Data register not empty flag - * @arg I2C_FLAG_STOPF: Stop detection flag - * @arg I2C_FLAG_ADD10: 10-bit header sent flag - * @arg I2C_FLAG_BTF: Byte transfer finished flag - * @arg I2C_FLAG_ADDR: Address sent flag - * Address matched flag - * @arg I2C_FLAG_SB: Start bit flag - * @arg I2C_FLAG_DUALF: Dual flag - * @arg I2C_FLAG_GENCALL: General call header flag - * @arg I2C_FLAG_TRA: Transmitter/Receiver flag - * @arg I2C_FLAG_BUSY: Bus busy flag - * @arg I2C_FLAG_MSL: Master/Slave flag - * @retval The new state of __FLAG__ (TRUE or FALSE). - */ -#define __HAL_I2C_GET_FLAG(__HANDLE__, __FLAG__) \ - ((((uint8_t)((__FLAG__) >> 16U)) == 0x01U) ? (((((__HANDLE__)->Instance->SR1) & ((__FLAG__)&I2C_FLAG_MASK)) == ((__FLAG__)&I2C_FLAG_MASK)) ? SET : RESET) \ - : (((((__HANDLE__)->Instance->SR2) & ((__FLAG__)&I2C_FLAG_MASK)) == ((__FLAG__)&I2C_FLAG_MASK)) ? SET : RESET)) - -/** @brief Clears the I2C pending flags which are cleared by writing 0 in a specific bit. - * @param __HANDLE__ specifies the I2C Handle. - * @param __FLAG__ specifies the flag to clear. - * This parameter can be any combination of the following values: - * @arg I2C_FLAG_OVR: Overrun/Underrun flag (Slave mode) - * @arg I2C_FLAG_AF: Acknowledge failure flag - * @arg I2C_FLAG_ARLO: Arbitration lost flag (Master mode) - * @arg I2C_FLAG_BERR: Bus error flag - * @retval None - */ -#define __HAL_I2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR1 = ~((__FLAG__)&I2C_FLAG_MASK)) - -/** @brief Clears the I2C ADDR pending flag. - * @param __HANDLE__ specifies the I2C Handle. - * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. - * @retval None - */ -#define __HAL_I2C_CLEAR_ADDRFLAG(__HANDLE__) \ - do { \ - __IO uint32_t tmpreg = 0x00U; \ - tmpreg = (__HANDLE__)->Instance->SR1; \ - tmpreg = (__HANDLE__)->Instance->SR2; \ - UNUSED(tmpreg); \ - } while (0) - -/** @brief Clears the I2C STOPF pending flag. - * @param __HANDLE__ specifies the I2C Handle. - * @retval None - */ -#define __HAL_I2C_CLEAR_STOPFLAG(__HANDLE__) \ - do { \ - __IO uint32_t tmpreg = 0x00U; \ - tmpreg = (__HANDLE__)->Instance->SR1; \ - SET_BIT((__HANDLE__)->Instance->CR1, I2C_CR1_PE); \ - UNUSED(tmpreg); \ - } while (0) - -/** @brief Enable the specified I2C peripheral. - * @param __HANDLE__ specifies the I2C Handle. - * @retval None - */ -#define __HAL_I2C_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR1, I2C_CR1_PE) - -/** @brief Disable the specified I2C peripheral. - * @param __HANDLE__ specifies the I2C Handle. - * @retval None - */ -#define __HAL_I2C_DISABLE(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR1, I2C_CR1_PE) - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup I2C_Exported_Functions - * @{ - */ - -/** @addtogroup I2C_Exported_Functions_Group1 Initialization and de-initialization functions - * @{ - */ -/* Initialization and de-initialization functions******************************/ -HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c); -HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c); - -/* Callbacks Register/UnRegister functions ***********************************/ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) -HAL_StatusTypeDef HAL_I2C_RegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID, pI2C_CallbackTypeDef pCallback); -HAL_StatusTypeDef HAL_I2C_UnRegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID); - -HAL_StatusTypeDef HAL_I2C_RegisterAddrCallback(I2C_HandleTypeDef *hi2c, pI2C_AddrCallbackTypeDef pCallback); -HAL_StatusTypeDef HAL_I2C_UnRegisterAddrCallback(I2C_HandleTypeDef *hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ -/** - * @} - */ - -/** @addtogroup I2C_Exported_Functions_Group2 Input and Output operation functions - * @{ - */ -/* IO operation functions ****************************************************/ -/******* Blocking mode: Polling */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); - -/******* Non-Blocking mode: Interrupt */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); - -HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c); -HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c); -HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress); - -/******* Non-Blocking mode: DMA */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); - -HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -/** - * @} - */ - -/** @addtogroup I2C_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks - * @{ - */ -/******* I2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ -void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c); -void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode); -void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c); -/** - * @} - */ - -/** @addtogroup I2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions - * @{ - */ -/* Peripheral State, Mode and Error functions *********************************/ -HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c); -HAL_I2C_ModeTypeDef HAL_I2C_GetMode(I2C_HandleTypeDef *hi2c); -uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c); - -/** - * @} - */ - -/** - * @} - */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup I2C_Private_Constants I2C Private Constants - * @{ - */ -#define I2C_FLAG_MASK 0x0000FFFFU -#define I2C_MIN_PCLK_FREQ_STANDARD 2000000U /*!< 2 MHz */ -#define I2C_MIN_PCLK_FREQ_FAST 4000000U /*!< 4 MHz */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup I2C_Private_Macros I2C Private Macros - * @{ - */ - -#define I2C_MIN_PCLK_FREQ(__PCLK__, __SPEED__) (((__SPEED__) <= 100000U) ? ((__PCLK__) < I2C_MIN_PCLK_FREQ_STANDARD) : ((__PCLK__) < I2C_MIN_PCLK_FREQ_FAST)) -#define I2C_CCR_CALCULATION(__PCLK__, __SPEED__, __COEFF__) (((((__PCLK__)-1U) / ((__SPEED__) * (__COEFF__))) + 1U) & I2C_CCR_CCR) -#define I2C_FREQRANGE(__PCLK__) ((__PCLK__) / 1000000U) -#define I2C_RISE_TIME(__FREQRANGE__, __SPEED__) (((__SPEED__) <= 100000U) ? ((__FREQRANGE__) + 1U) : ((((__FREQRANGE__)*300U) / 1000U) + 1U)) -#define I2C_SPEED_STANDARD(__PCLK__, __SPEED__) ((I2C_CCR_CALCULATION((__PCLK__), (__SPEED__), 2U) < 4U) ? 4U : I2C_CCR_CALCULATION((__PCLK__), (__SPEED__), 2U)) -#define I2C_SPEED_FAST(__PCLK__, __SPEED__, __DUTYCYCLE__) \ - (((__DUTYCYCLE__) == I2C_DUTYCYCLE_2) ? I2C_CCR_CALCULATION((__PCLK__), (__SPEED__), 3U) : (I2C_CCR_CALCULATION((__PCLK__), (__SPEED__), 25U) | I2C_DUTYCYCLE_16_9)) -#define I2C_SPEED(__PCLK__, __SPEED__, __DUTYCYCLE__) \ - (((__SPEED__) <= 100000U) ? (I2C_SPEED_STANDARD((__PCLK__), (__SPEED__))) \ - : ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__)) & I2C_CCR_CCR) == 0U) ? 1U \ - : ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__))) | I2C_CCR_FS)) - -#define I2C_7BIT_ADD_WRITE(__ADDRESS__) ((uint8_t)((__ADDRESS__) & (uint8_t)(~I2C_OAR1_ADD0))) -#define I2C_7BIT_ADD_READ(__ADDRESS__) ((uint8_t)((__ADDRESS__) | I2C_OAR1_ADD0)) - -#define I2C_10BIT_ADDRESS(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)0x00FF))) -#define I2C_10BIT_HEADER_WRITE(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)0x0300)) >> 7) | (uint16_t)0x00F0))) -#define I2C_10BIT_HEADER_READ(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)0x0300)) >> 7) | (uint16_t)(0x00F1)))) - -#define I2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)0xFF00)) >> 8))) -#define I2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)0x00FF))) - -/** @defgroup I2C_IS_RTC_Definitions I2C Private macros to check input parameters - * @{ - */ -#define IS_I2C_DUTY_CYCLE(CYCLE) (((CYCLE) == I2C_DUTYCYCLE_2) || ((CYCLE) == I2C_DUTYCYCLE_16_9)) -#define IS_I2C_ADDRESSING_MODE(ADDRESS) (((ADDRESS) == I2C_ADDRESSINGMODE_7BIT) || ((ADDRESS) == I2C_ADDRESSINGMODE_10BIT)) -#define IS_I2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == I2C_DUALADDRESS_DISABLE) || ((ADDRESS) == I2C_DUALADDRESS_ENABLE)) -#define IS_I2C_GENERAL_CALL(CALL) (((CALL) == I2C_GENERALCALL_DISABLE) || ((CALL) == I2C_GENERALCALL_ENABLE)) -#define IS_I2C_NO_STRETCH(STRETCH) (((STRETCH) == I2C_NOSTRETCH_DISABLE) || ((STRETCH) == I2C_NOSTRETCH_ENABLE)) -#define IS_I2C_MEMADD_SIZE(SIZE) (((SIZE) == I2C_MEMADD_SIZE_8BIT) || ((SIZE) == I2C_MEMADD_SIZE_16BIT)) -#define IS_I2C_CLOCK_SPEED(SPEED) (((SPEED) > 0U) && ((SPEED) <= 400000U)) -#define IS_I2C_OWN_ADDRESS1(ADDRESS1) (((ADDRESS1)&0xFFFFFC00U) == 0U) -#define IS_I2C_OWN_ADDRESS2(ADDRESS2) (((ADDRESS2)&0xFFFFFF01U) == 0U) -#define IS_I2C_TRANSFER_OPTIONS_REQUEST(REQUEST) \ - (((REQUEST) == I2C_FIRST_FRAME) || ((REQUEST) == I2C_FIRST_AND_NEXT_FRAME) || ((REQUEST) == I2C_NEXT_FRAME) || ((REQUEST) == I2C_FIRST_AND_LAST_FRAME) || ((REQUEST) == I2C_LAST_FRAME) \ - || ((REQUEST) == I2C_LAST_FRAME_NO_STOP) || IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(REQUEST)) - -#define IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(REQUEST) (((REQUEST) == I2C_OTHER_FRAME) || ((REQUEST) == I2C_OTHER_AND_LAST_FRAME)) - -#define I2C_CHECK_FLAG(__ISR__, __FLAG__) ((((__ISR__) & ((__FLAG__)&I2C_FLAG_MASK)) == ((__FLAG__)&I2C_FLAG_MASK)) ? SET : RESET) -#define I2C_CHECK_IT_SOURCE(__CR1__, __IT__) ((((__CR1__) & (__IT__)) == (__IT__)) ? SET : RESET) -/** - * @} - */ - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/** @defgroup I2C_Private_Functions I2C Private Functions - * @{ - */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_HAL_I2C_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c index f71efb0f4..4f8a7576f 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c @@ -139,8 +139,8 @@ HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT; /* 1KHz */ HAL_StatusTypeDef HAL_Init(void) { /* Configure Flash prefetch */ #if (PREFETCH_ENABLE != 0) -#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) \ - || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) +#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) || \ + defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) /* Prefetch buffer is not available on value line devices */ __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); @@ -347,7 +347,8 @@ __weak void HAL_Delay(uint32_t Delay) { wait += (uint32_t)(uwTickFreq); } - while ((HAL_GetTick() - tickstart) < wait) {} + while ((HAL_GetTick() - tickstart) < wait) { + } } /** diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c index bb7ac4fcf..d0ea179ad 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c @@ -620,12 +620,12 @@ HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_JEOC | ADC_FLAG_EOC | ADC_FLAG_JSTRT | ADC_FLAG_STRT)); /* Reset register CR1 */ - CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | ADC_CR1_AWDIE - | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); + CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | + ADC_CR1_AWDIE | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); /* Reset register CR2 */ - CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA - | ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); + CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA | + ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); /* Reset register SMPR1 */ CLEAR_BIT(hadc->Instance->SMPR1, (ADC_SMPR1_SMP17 | ADC_SMPR1_SMP16 | ADC_SMPR1_SMP15 | ADC_SMPR1_SMP14 | ADC_SMPR1_SMP13 | ADC_SMPR1_SMP12 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP10)); @@ -1874,8 +1874,8 @@ HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDG assert_param(IS_ADC_RANGE(AnalogWDGConfig->HighThreshold)); assert_param(IS_ADC_RANGE(AnalogWDGConfig->LowThreshold)); - if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) - || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { + if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || + (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel)); } diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c index e24c8e54d..ce5414e98 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c @@ -941,8 +941,8 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I ADC_JSQR_JL | ADC_JSQR_RK_JL(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion), - ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) - | ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); + ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) | + ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); } else { /* Clear the old SQx bits for the selected rank */ MODIFY_REG(hadc->Instance->JSQR, diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c index c77c46085..f64449972 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c @@ -305,9 +305,9 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) { assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) - | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) - | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } else { MPU->RBAR = 0x00U; MPU->RASR = 0x00U; diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c index 2c3b06e8e..c4ec13b8f 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c @@ -182,7 +182,7 @@ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) { tmp = hdma->Instance->CCR; /* Clear PL, MSIZE, PSIZE, MINC, PINC, CIRC and DIR bits */ - tmp &= ((uint32_t) ~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | DMA_CCR_DIR)); + tmp &= ((uint32_t)~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | DMA_CCR_DIR)); /* Prepare the DMA Channel configuration */ tmp |= hdma->Init.Direction | hdma->Init.PeriphInc | hdma->Init.MemInc | hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment | hdma->Init.Mode | hdma->Init.Priority; diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c deleted file mode 100644 index 4a83bee20..000000000 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c +++ /dev/null @@ -1,6623 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_hal_i2c.c - * @author MCD Application Team - * @brief I2C HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Inter Integrated Circuit (I2C) peripheral: - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral State, Mode and Error functions - * - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The I2C HAL driver can be used as follows: - - (#) Declare a I2C_HandleTypeDef handle structure, for example: - I2C_HandleTypeDef hi2c; - - (#)Initialize the I2C low level resources by implementing the @ref HAL_I2C_MspInit() API: - (##) Enable the I2Cx interface clock - (##) I2C pins configuration - (+++) Enable the clock for the I2C GPIOs - (+++) Configure I2C pins as alternate function open-drain - (##) NVIC configuration if you need to use interrupt process - (+++) Configure the I2Cx interrupt priority - (+++) Enable the NVIC I2C IRQ Channel - (##) DMA Configuration if you need to use DMA process - (+++) Declare a DMA_HandleTypeDef handle structure for the transmit or receive channel - (+++) Enable the DMAx interface clock using - (+++) Configure the DMA handle parameters - (+++) Configure the DMA Tx or Rx channel - (+++) Associate the initialized DMA handle to the hi2c DMA Tx or Rx handle - (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on - the DMA Tx or Rx channel - - (#) Configure the Communication Speed, Duty cycle, Addressing mode, Own Address1, - Dual Addressing mode, Own Address2, General call and Nostretch mode in the hi2c Init structure. - - (#) Initialize the I2C registers by calling the @ref HAL_I2C_Init(), configures also the low level Hardware - (GPIO, CLOCK, NVIC...etc) by calling the customized @ref HAL_I2C_MspInit() API. - - (#) To check if target device is ready for communication, use the function @ref HAL_I2C_IsDeviceReady() - - (#) For I2C IO and IO MEM operations, three operation modes are available within this driver : - - *** Polling mode IO operation *** - ================================= - [..] - (+) Transmit in master mode an amount of data in blocking mode using @ref HAL_I2C_Master_Transmit() - (+) Receive in master mode an amount of data in blocking mode using @ref HAL_I2C_Master_Receive() - (+) Transmit in slave mode an amount of data in blocking mode using @ref HAL_I2C_Slave_Transmit() - (+) Receive in slave mode an amount of data in blocking mode using @ref HAL_I2C_Slave_Receive() - - *** Polling mode IO MEM operation *** - ===================================== - [..] - (+) Write an amount of data in blocking mode to a specific memory address using @ref HAL_I2C_Mem_Write() - (+) Read an amount of data in blocking mode from a specific memory address using @ref HAL_I2C_Mem_Read() - - - *** Interrupt mode IO operation *** - =================================== - [..] - (+) Transmit in master mode an amount of data in non-blocking mode using @ref HAL_I2C_Master_Transmit_IT() - (+) At transmission end of transfer, @ref HAL_I2C_MasterTxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_MasterTxCpltCallback() - (+) Receive in master mode an amount of data in non-blocking mode using @ref HAL_I2C_Master_Receive_IT() - (+) At reception end of transfer, @ref HAL_I2C_MasterRxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_MasterRxCpltCallback() - (+) Transmit in slave mode an amount of data in non-blocking mode using @ref HAL_I2C_Slave_Transmit_IT() - (+) At transmission end of transfer, @ref HAL_I2C_SlaveTxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_SlaveTxCpltCallback() - (+) Receive in slave mode an amount of data in non-blocking mode using @ref HAL_I2C_Slave_Receive_IT() - (+) At reception end of transfer, @ref HAL_I2C_SlaveRxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_SlaveRxCpltCallback() - (+) In case of transfer Error, @ref HAL_I2C_ErrorCallback() function is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_ErrorCallback() - (+) Abort a master I2C process communication with Interrupt using @ref HAL_I2C_Master_Abort_IT() - (+) End of abort process, @ref HAL_I2C_AbortCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_AbortCpltCallback() - - *** Interrupt mode or DMA mode IO sequential operation *** - ========================================================== - [..] - (@) These interfaces allow to manage a sequential transfer with a repeated start condition - when a direction change during transfer - [..] - (+) A specific option field manage the different steps of a sequential transfer - (+) Option field values are defined through @ref I2C_XferOptions_definition and are listed below: - (++) I2C_FIRST_AND_LAST_FRAME: No sequential usage, functionnal is same as associated interfaces in no sequential mode - (++) I2C_FIRST_FRAME: Sequential usage, this option allow to manage a sequence with start condition, address - and data to transfer without a final stop condition - (++) I2C_FIRST_AND_NEXT_FRAME: Sequential usage (Master only), this option allow to manage a sequence with start condition, address - and data to transfer without a final stop condition, an then permit a call the same master sequential interface - several times (like @ref HAL_I2C_Master_Seq_Transmit_IT() then @ref HAL_I2C_Master_Seq_Transmit_IT() - or @ref HAL_I2C_Master_Seq_Transmit_DMA() then @ref HAL_I2C_Master_Seq_Transmit_DMA()) - (++) I2C_NEXT_FRAME: Sequential usage, this option allow to manage a sequence with a restart condition, address - and with new data to transfer if the direction change or manage only the new data to transfer - if no direction change and without a final stop condition in both cases - (++) I2C_LAST_FRAME: Sequential usage, this option allow to manage a sequance with a restart condition, address - and with new data to transfer if the direction change or manage only the new data to transfer - if no direction change and with a final stop condition in both cases - (++) I2C_LAST_FRAME_NO_STOP: Sequential usage (Master only), this option allow to manage a restart condition after several call of the same master sequential - interface several times (link with option I2C_FIRST_AND_NEXT_FRAME). - Usage can, transfer several bytes one by one using HAL_I2C_Master_Seq_Transmit_IT(option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME) - or HAL_I2C_Master_Seq_Receive_IT(option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME) - or HAL_I2C_Master_Seq_Transmit_DMA(option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME) - or HAL_I2C_Master_Seq_Receive_DMA(option I2C_FIRST_AND_NEXT_FRAME then I2C_NEXT_FRAME). - Then usage of this option I2C_LAST_FRAME_NO_STOP at the last Transmit or Receive sequence permit to call the oposite interface Receive or Transmit - without stopping the communication and so generate a restart condition. - (++) I2C_OTHER_FRAME: Sequential usage (Master only), this option allow to manage a restart condition after each call of the same master sequential - interface. - Usage can, transfer several bytes one by one with a restart with slave address between each bytes using HAL_I2C_Master_Seq_Transmit_IT(option I2C_FIRST_FRAME then - I2C_OTHER_FRAME) or HAL_I2C_Master_Seq_Receive_IT(option I2C_FIRST_FRAME then I2C_OTHER_FRAME) or HAL_I2C_Master_Seq_Transmit_DMA(option I2C_FIRST_FRAME then I2C_OTHER_FRAME) or - HAL_I2C_Master_Seq_Receive_DMA(option I2C_FIRST_FRAME then I2C_OTHER_FRAME). Then usage of this option I2C_OTHER_AND_LAST_FRAME at the last frame to help automatic generation of STOP condition. - - (+) Differents sequential I2C interfaces are listed below: - (++) Sequential transmit in master I2C mode an amount of data in non-blocking mode using @ref HAL_I2C_Master_Seq_Transmit_IT() - or using @ref HAL_I2C_Master_Seq_Transmit_DMA() - (+++) At transmission end of current frame transfer, @ref HAL_I2C_MasterTxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_MasterTxCpltCallback() - (++) Sequential receive in master I2C mode an amount of data in non-blocking mode using @ref HAL_I2C_Master_Seq_Receive_IT() - or using @ref HAL_I2C_Master_Seq_Receive_DMA() - (+++) At reception end of current frame transfer, @ref HAL_I2C_MasterRxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_MasterRxCpltCallback() - (++) Abort a master IT or DMA I2C process communication with Interrupt using @ref HAL_I2C_Master_Abort_IT() - (+++) End of abort process, @ref HAL_I2C_AbortCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_AbortCpltCallback() - (++) Enable/disable the Address listen mode in slave I2C mode using @ref HAL_I2C_EnableListen_IT() @ref HAL_I2C_DisableListen_IT() - (+++) When address slave I2C match, @ref HAL_I2C_AddrCallback() is executed and user can - add his own code to check the Address Match Code and the transmission direction request by master (Write/Read). - (+++) At Listen mode end @ref HAL_I2C_ListenCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_ListenCpltCallback() - (++) Sequential transmit in slave I2C mode an amount of data in non-blocking mode using @ref HAL_I2C_Slave_Seq_Transmit_IT() - or using @ref HAL_I2C_Slave_Seq_Transmit_DMA() - (+++) At transmission end of current frame transfer, @ref HAL_I2C_SlaveTxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_SlaveTxCpltCallback() - (++) Sequential receive in slave I2C mode an amount of data in non-blocking mode using @ref HAL_I2C_Slave_Seq_Receive_IT() - or using @ref HAL_I2C_Slave_Seq_Receive_DMA() - (+++) At reception end of current frame transfer, @ref HAL_I2C_SlaveRxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_SlaveRxCpltCallback() - (++) In case of transfer Error, @ref HAL_I2C_ErrorCallback() function is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_ErrorCallback() - - *** Interrupt mode IO MEM operation *** - ======================================= - [..] - (+) Write an amount of data in non-blocking mode with Interrupt to a specific memory address using - @ref HAL_I2C_Mem_Write_IT() - (+) At Memory end of write transfer, @ref HAL_I2C_MemTxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_MemTxCpltCallback() - (+) Read an amount of data in non-blocking mode with Interrupt from a specific memory address using - @ref HAL_I2C_Mem_Read_IT() - (+) At Memory end of read transfer, @ref HAL_I2C_MemRxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_MemRxCpltCallback() - (+) In case of transfer Error, @ref HAL_I2C_ErrorCallback() function is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_ErrorCallback() - - *** DMA mode IO operation *** - ============================== - [..] - (+) Transmit in master mode an amount of data in non-blocking mode (DMA) using - @ref HAL_I2C_Master_Transmit_DMA() - (+) At transmission end of transfer, @ref HAL_I2C_MasterTxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_MasterTxCpltCallback() - (+) Receive in master mode an amount of data in non-blocking mode (DMA) using - @ref HAL_I2C_Master_Receive_DMA() - (+) At reception end of transfer, @ref HAL_I2C_MasterRxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_MasterRxCpltCallback() - (+) Transmit in slave mode an amount of data in non-blocking mode (DMA) using - @ref HAL_I2C_Slave_Transmit_DMA() - (+) At transmission end of transfer, @ref HAL_I2C_SlaveTxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_SlaveTxCpltCallback() - (+) Receive in slave mode an amount of data in non-blocking mode (DMA) using - @ref HAL_I2C_Slave_Receive_DMA() - (+) At reception end of transfer, @ref HAL_I2C_SlaveRxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_SlaveRxCpltCallback() - (+) In case of transfer Error, @ref HAL_I2C_ErrorCallback() function is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_ErrorCallback() - (+) Abort a master I2C process communication with Interrupt using @ref HAL_I2C_Master_Abort_IT() - (+) End of abort process, @ref HAL_I2C_AbortCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_AbortCpltCallback() - - *** DMA mode IO MEM operation *** - ================================= - [..] - (+) Write an amount of data in non-blocking mode with DMA to a specific memory address using - @ref HAL_I2C_Mem_Write_DMA() - (+) At Memory end of write transfer, @ref HAL_I2C_MemTxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_MemTxCpltCallback() - (+) Read an amount of data in non-blocking mode with DMA from a specific memory address using - @ref HAL_I2C_Mem_Read_DMA() - (+) At Memory end of read transfer, @ref HAL_I2C_MemRxCpltCallback() is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_MemRxCpltCallback() - (+) In case of transfer Error, @ref HAL_I2C_ErrorCallback() function is executed and user can - add his own code by customization of function pointer @ref HAL_I2C_ErrorCallback() - - - *** I2C HAL driver macros list *** - ================================== - [..] - Below the list of most used macros in I2C HAL driver. - - (+) @ref __HAL_I2C_ENABLE: Enable the I2C peripheral - (+) @ref __HAL_I2C_DISABLE: Disable the I2C peripheral - (+) @ref __HAL_I2C_GET_FLAG: Checks whether the specified I2C flag is set or not - (+) @ref __HAL_I2C_CLEAR_FLAG: Clear the specified I2C pending flag - (+) @ref __HAL_I2C_ENABLE_IT: Enable the specified I2C interrupt - (+) @ref __HAL_I2C_DISABLE_IT: Disable the specified I2C interrupt - - *** Callback registration *** - ============================================= - [..] - The compilation flag USE_HAL_I2C_REGISTER_CALLBACKS when set to 1 - allows the user to configure dynamically the driver callbacks. - Use Functions @ref HAL_I2C_RegisterCallback() or @ref HAL_I2C_RegisterAddrCallback() - to register an interrupt callback. - [..] - Function @ref HAL_I2C_RegisterCallback() allows to register following callbacks: - (+) MasterTxCpltCallback : callback for Master transmission end of transfer. - (+) MasterRxCpltCallback : callback for Master reception end of transfer. - (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. - (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. - (+) ListenCpltCallback : callback for end of listen mode. - (+) MemTxCpltCallback : callback for Memory transmission end of transfer. - (+) MemRxCpltCallback : callback for Memory reception end of transfer. - (+) ErrorCallback : callback for error detection. - (+) AbortCpltCallback : callback for abort completion process. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - This function takes as parameters the HAL peripheral handle, the Callback ID - and a pointer to the user callback function. - [..] - For specific callback AddrCallback use dedicated register callbacks : @ref HAL_I2C_RegisterAddrCallback(). - [..] - Use function @ref HAL_I2C_UnRegisterCallback to reset a callback to the default - weak function. - @ref HAL_I2C_UnRegisterCallback takes as parameters the HAL peripheral handle, - and the Callback ID. - This function allows to reset following callbacks: - (+) MasterTxCpltCallback : callback for Master transmission end of transfer. - (+) MasterRxCpltCallback : callback for Master reception end of transfer. - (+) SlaveTxCpltCallback : callback for Slave transmission end of transfer. - (+) SlaveRxCpltCallback : callback for Slave reception end of transfer. - (+) ListenCpltCallback : callback for end of listen mode. - (+) MemTxCpltCallback : callback for Memory transmission end of transfer. - (+) MemRxCpltCallback : callback for Memory reception end of transfer. - (+) ErrorCallback : callback for error detection. - (+) AbortCpltCallback : callback for abort completion process. - (+) MspInitCallback : callback for Msp Init. - (+) MspDeInitCallback : callback for Msp DeInit. - [..] - For callback AddrCallback use dedicated register callbacks : @ref HAL_I2C_UnRegisterAddrCallback(). - [..] - By default, after the @ref HAL_I2C_Init() and when the state is @ref HAL_I2C_STATE_RESET - all callbacks are set to the corresponding weak functions: - examples @ref HAL_I2C_MasterTxCpltCallback(), @ref HAL_I2C_MasterRxCpltCallback(). - Exception done for MspInit and MspDeInit functions that are - reset to the legacy weak functions in the @ref HAL_I2C_Init()/ @ref HAL_I2C_DeInit() only when - these callbacks are null (not registered beforehand). - If MspInit or MspDeInit are not null, the @ref HAL_I2C_Init()/ @ref HAL_I2C_DeInit() - keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state. - [..] - Callbacks can be registered/unregistered in @ref HAL_I2C_STATE_READY state only. - Exception done MspInit/MspDeInit functions that can be registered/unregistered - in @ref HAL_I2C_STATE_READY or @ref HAL_I2C_STATE_RESET state, - thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. - Then, the user first registers the MspInit/MspDeInit user callbacks - using @ref HAL_I2C_RegisterCallback() before calling @ref HAL_I2C_DeInit() - or @ref HAL_I2C_Init() function. - [..] - When the compilation flag USE_HAL_I2C_REGISTER_CALLBACKS is set to 0 or - not defined, the callback registration feature is not available and all callbacks - are set to the corresponding weak functions. - - - *** I2C Workarounds linked to Silicon Limitation *** - ==================================================== - [..] - Below the list of all silicon limitations implemented for HAL on STM32F1xx product. - (@) See ErrataSheet to know full silicon limitation list of your product. - - (+) Workarounds Implemented inside I2C HAL Driver - (++) Wrong data read into data register (Polling and Interrupt mode) - (++) Start cannot be generated after a misplaced Stop - (++) Some software events must be managed before the current byte is being transferred: - Workaround: Use DMA in general, except when the Master is receiving a single byte. - For Interupt mode, I2C should have the highest priority in the application. - (++) Mismatch on the "Setup time for a repeated Start condition" timing parameter: - Workaround: Reduce the frequency down to 88 kHz or use the I2C Fast-mode if - supported by the slave. - (++) Data valid time (tVD;DAT) violated without the OVR flag being set: - Workaround: If the slave device allows it, use the clock stretching mechanism - by programming NoStretchMode = I2C_NOSTRETCH_DISABLE in @ref HAL_I2C_Init. - - [..] - (@) You can refer to the I2C HAL driver header file for more useful macros - - @endverbatim - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2016 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_hal.h" - -/** @addtogroup STM32F1xx_HAL_Driver - * @{ - */ - -/** @defgroup I2C I2C - * @brief I2C HAL module driver - * @{ - */ - -#ifdef HAL_I2C_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @addtogroup I2C_Private_Define - * @{ - */ -#define I2C_TIMEOUT_FLAG 35U /*!< Timeout 35 ms */ -#define I2C_TIMEOUT_BUSY_FLAG 25U /*!< Timeout 25 ms */ -#define I2C_TIMEOUT_STOP_FLAG 5U /*!< Timeout 5 ms */ -#define I2C_NO_OPTION_FRAME 0xFFFF0000U /*!< XferOptions default value */ - -/* Private define for @ref PreviousState usage */ -#define I2C_STATE_MSK \ - ((uint32_t)((uint32_t)((uint32_t)HAL_I2C_STATE_BUSY_TX | (uint32_t)HAL_I2C_STATE_BUSY_RX) & (uint32_t)(~((uint32_t)HAL_I2C_STATE_READY)))) /*!< Mask State define, keep only RX and TX bits */ -#define I2C_STATE_NONE ((uint32_t)(HAL_I2C_MODE_NONE)) /*!< Default Value */ -#define I2C_STATE_MASTER_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | (uint32_t)HAL_I2C_MODE_MASTER)) /*!< Master Busy TX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_MASTER_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | (uint32_t)HAL_I2C_MODE_MASTER)) /*!< Master Busy RX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_SLAVE_BUSY_TX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | (uint32_t)HAL_I2C_MODE_SLAVE)) /*!< Slave Busy TX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_SLAVE_BUSY_RX ((uint32_t)(((uint32_t)HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | (uint32_t)HAL_I2C_MODE_SLAVE)) /*!< Slave Busy RX, combinaison of State LSB and Mode enum */ - -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ - -/** @defgroup I2C_Private_Functions I2C Private Functions - * @{ - */ -/* Private functions to handle DMA transfer */ -static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma); -static void I2C_DMAError(DMA_HandleTypeDef *hdma); -static void I2C_DMAAbort(DMA_HandleTypeDef *hdma); - -static void I2C_ITError(I2C_HandleTypeDef *hi2c); - -static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart); - -/* Private functions to handle flags during polling transfer */ -static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnTXEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnBTFFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnSTOPRequestThroughIT(I2C_HandleTypeDef *hi2c); -static HAL_StatusTypeDef I2C_IsAcknowledgeFailed(I2C_HandleTypeDef *hi2c); - -/* Private functions for I2C transfer IRQ handler */ -static void I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c); -static void I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c); -static void I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c); -static void I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c); -static void I2C_Master_SB(I2C_HandleTypeDef *hi2c); -static void I2C_Master_ADD10(I2C_HandleTypeDef *hi2c); -static void I2C_Master_ADDR(I2C_HandleTypeDef *hi2c); - -static void I2C_SlaveTransmit_TXE(I2C_HandleTypeDef *hi2c); -static void I2C_SlaveTransmit_BTF(I2C_HandleTypeDef *hi2c); -static void I2C_SlaveReceive_RXNE(I2C_HandleTypeDef *hi2c); -static void I2C_SlaveReceive_BTF(I2C_HandleTypeDef *hi2c); -static void I2C_Slave_ADDR(I2C_HandleTypeDef *hi2c, uint32_t IT2Flags); -static void I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c); -static void I2C_Slave_AF(I2C_HandleTypeDef *hi2c); - -static void I2C_MemoryTransmit_TXE_BTF(I2C_HandleTypeDef *hi2c); - -/* Private function to Convert Specific options */ -static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup I2C_Exported_Functions I2C Exported Functions - * @{ - */ - -/** @defgroup I2C_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions - * -@verbatim - =============================================================================== - ##### Initialization and de-initialization functions ##### - =============================================================================== - [..] This subsection provides a set of functions allowing to initialize and - deinitialize the I2Cx peripheral: - - (+) User must Implement HAL_I2C_MspInit() function in which he configures - all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC). - - (+) Call the function HAL_I2C_Init() to configure the selected device with - the selected configuration: - (++) Communication Speed - (++) Duty cycle - (++) Addressing mode - (++) Own Address 1 - (++) Dual Addressing mode - (++) Own Address 2 - (++) General call mode - (++) Nostretch mode - - (+) Call the function HAL_I2C_DeInit() to restore the default configuration - of the selected I2Cx peripheral. - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the I2C according to the specified parameters - * in the I2C_InitTypeDef and initialize the associated handle. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c) { - uint32_t freqrange; - uint32_t pclk1; - - /* Check the I2C handle allocation */ - if (hi2c == NULL) { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); - assert_param(IS_I2C_CLOCK_SPEED(hi2c->Init.ClockSpeed)); - assert_param(IS_I2C_DUTY_CYCLE(hi2c->Init.DutyCycle)); - assert_param(IS_I2C_OWN_ADDRESS1(hi2c->Init.OwnAddress1)); - assert_param(IS_I2C_ADDRESSING_MODE(hi2c->Init.AddressingMode)); - assert_param(IS_I2C_DUAL_ADDRESS(hi2c->Init.DualAddressMode)); - assert_param(IS_I2C_OWN_ADDRESS2(hi2c->Init.OwnAddress2)); - assert_param(IS_I2C_GENERAL_CALL(hi2c->Init.GeneralCallMode)); - assert_param(IS_I2C_NO_STRETCH(hi2c->Init.NoStretchMode)); - - if (hi2c->State == HAL_I2C_STATE_RESET) { - /* Allocate lock resource and initialize it */ - hi2c->Lock = HAL_UNLOCKED; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - /* Init the I2C Callback settings */ - hi2c->MasterTxCpltCallback = HAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ - hi2c->MasterRxCpltCallback = HAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ - hi2c->SlaveTxCpltCallback = HAL_I2C_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ - hi2c->SlaveRxCpltCallback = HAL_I2C_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ - hi2c->ListenCpltCallback = HAL_I2C_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ - hi2c->MemTxCpltCallback = HAL_I2C_MemTxCpltCallback; /* Legacy weak MemTxCpltCallback */ - hi2c->MemRxCpltCallback = HAL_I2C_MemRxCpltCallback; /* Legacy weak MemRxCpltCallback */ - hi2c->ErrorCallback = HAL_I2C_ErrorCallback; /* Legacy weak ErrorCallback */ - hi2c->AbortCpltCallback = HAL_I2C_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - hi2c->AddrCallback = HAL_I2C_AddrCallback; /* Legacy weak AddrCallback */ - - if (hi2c->MspInitCallback == NULL) { - hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */ - } - - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - hi2c->MspInitCallback(hi2c); -#else - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - HAL_I2C_MspInit(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - - hi2c->State = HAL_I2C_STATE_BUSY; - - /* Disable the selected I2C peripheral */ - __HAL_I2C_DISABLE(hi2c); - - /*Reset I2C*/ - hi2c->Instance->CR1 |= I2C_CR1_SWRST; - hi2c->Instance->CR1 &= ~I2C_CR1_SWRST; - - /* Get PCLK1 frequency */ - pclk1 = HAL_RCC_GetPCLK1Freq(); - - /* Check the minimum allowed PCLK1 frequency */ - if (I2C_MIN_PCLK_FREQ(pclk1, hi2c->Init.ClockSpeed) == 1U) { - return HAL_ERROR; - } - - /* Calculate frequency range */ - freqrange = I2C_FREQRANGE(pclk1); - - /*---------------------------- I2Cx CR2 Configuration ----------------------*/ - /* Configure I2Cx: Frequency range */ - MODIFY_REG(hi2c->Instance->CR2, I2C_CR2_FREQ, freqrange); - - /*---------------------------- I2Cx TRISE Configuration --------------------*/ - /* Configure I2Cx: Rise Time */ - MODIFY_REG(hi2c->Instance->TRISE, I2C_TRISE_TRISE, I2C_RISE_TIME(freqrange, hi2c->Init.ClockSpeed)); - - /*---------------------------- I2Cx CCR Configuration ----------------------*/ - /* Configure I2Cx: Speed */ - MODIFY_REG(hi2c->Instance->CCR, (I2C_CCR_FS | I2C_CCR_DUTY | I2C_CCR_CCR), I2C_SPEED(pclk1, hi2c->Init.ClockSpeed, hi2c->Init.DutyCycle)); - - /*---------------------------- I2Cx CR1 Configuration ----------------------*/ - /* Configure I2Cx: Generalcall and NoStretch mode */ - MODIFY_REG(hi2c->Instance->CR1, (I2C_CR1_ENGC | I2C_CR1_NOSTRETCH), (hi2c->Init.GeneralCallMode | hi2c->Init.NoStretchMode)); - - /*---------------------------- I2Cx OAR1 Configuration ---------------------*/ - /* Configure I2Cx: Own Address1 and addressing mode */ - MODIFY_REG(hi2c->Instance->OAR1, (I2C_OAR1_ADDMODE | I2C_OAR1_ADD8_9 | I2C_OAR1_ADD1_7 | I2C_OAR1_ADD0), (hi2c->Init.AddressingMode | hi2c->Init.OwnAddress1)); - - /*---------------------------- I2Cx OAR2 Configuration ---------------------*/ - /* Configure I2Cx: Dual mode and Own Address2 */ - MODIFY_REG(hi2c->Instance->OAR2, (I2C_OAR2_ENDUAL | I2C_OAR2_ADD2), (hi2c->Init.DualAddressMode | hi2c->Init.OwnAddress2)); - - /* Enable the selected I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->Mode = HAL_I2C_MODE_NONE; - - return HAL_OK; -} - -/** - * @brief DeInitialize the I2C peripheral. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c) { - /* Check the I2C handle allocation */ - if (hi2c == NULL) { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); - - hi2c->State = HAL_I2C_STATE_BUSY; - - /* Disable the I2C Peripheral Clock */ - __HAL_I2C_DISABLE(hi2c); - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - if (hi2c->MspDeInitCallback == NULL) { - hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ - } - - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - hi2c->MspDeInitCallback(hi2c); -#else - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - HAL_I2C_MspDeInit(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - hi2c->State = HAL_I2C_STATE_RESET; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Release Lock */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; -} - -/** - * @brief Initialize the I2C MSP. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MspInit could be implemented in the user file - */ -} - -/** - * @brief DeInitialize the I2C MSP. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MspDeInit could be implemented in the user file - */ -} - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) -/** - * @brief Register a User I2C Callback - * To be used instead of the weak predefined callback - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param CallbackID ID of the callback to be registered - * This parameter can be one of the following values: - * @arg @ref HAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID - * @arg @ref HAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID - * @arg @ref HAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID - * @arg @ref HAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID - * @arg @ref HAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID - * @arg @ref HAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID - * @arg @ref HAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID - * @arg @ref HAL_I2C_ERROR_CB_ID Error callback ID - * @arg @ref HAL_I2C_ABORT_CB_ID Abort callback ID - * @arg @ref HAL_I2C_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID - * @param pCallback pointer to the Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_RegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID, pI2C_CallbackTypeDef pCallback) { - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hi2c); - - if (HAL_I2C_STATE_READY == hi2c->State) { - switch (CallbackID) { - case HAL_I2C_MASTER_TX_COMPLETE_CB_ID: - hi2c->MasterTxCpltCallback = pCallback; - break; - - case HAL_I2C_MASTER_RX_COMPLETE_CB_ID: - hi2c->MasterRxCpltCallback = pCallback; - break; - - case HAL_I2C_SLAVE_TX_COMPLETE_CB_ID: - hi2c->SlaveTxCpltCallback = pCallback; - break; - - case HAL_I2C_SLAVE_RX_COMPLETE_CB_ID: - hi2c->SlaveRxCpltCallback = pCallback; - break; - - case HAL_I2C_LISTEN_COMPLETE_CB_ID: - hi2c->ListenCpltCallback = pCallback; - break; - - case HAL_I2C_MEM_TX_COMPLETE_CB_ID: - hi2c->MemTxCpltCallback = pCallback; - break; - - case HAL_I2C_MEM_RX_COMPLETE_CB_ID: - hi2c->MemRxCpltCallback = pCallback; - break; - - case HAL_I2C_ERROR_CB_ID: - hi2c->ErrorCallback = pCallback; - break; - - case HAL_I2C_ABORT_CB_ID: - hi2c->AbortCpltCallback = pCallback; - break; - - case HAL_I2C_MSPINIT_CB_ID: - hi2c->MspInitCallback = pCallback; - break; - - case HAL_I2C_MSPDEINIT_CB_ID: - hi2c->MspDeInitCallback = pCallback; - break; - - default: - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } else if (HAL_I2C_STATE_RESET == hi2c->State) { - switch (CallbackID) { - case HAL_I2C_MSPINIT_CB_ID: - hi2c->MspInitCallback = pCallback; - break; - - case HAL_I2C_MSPDEINIT_CB_ID: - hi2c->MspDeInitCallback = pCallback; - break; - - default: - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } else { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hi2c); - return status; -} - -/** - * @brief Unregister an I2C Callback - * I2C callback is redirected to the weak predefined callback - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param CallbackID ID of the callback to be unregistered - * This parameter can be one of the following values: - * This parameter can be one of the following values: - * @arg @ref HAL_I2C_MASTER_TX_COMPLETE_CB_ID Master Tx Transfer completed callback ID - * @arg @ref HAL_I2C_MASTER_RX_COMPLETE_CB_ID Master Rx Transfer completed callback ID - * @arg @ref HAL_I2C_SLAVE_TX_COMPLETE_CB_ID Slave Tx Transfer completed callback ID - * @arg @ref HAL_I2C_SLAVE_RX_COMPLETE_CB_ID Slave Rx Transfer completed callback ID - * @arg @ref HAL_I2C_LISTEN_COMPLETE_CB_ID Listen Complete callback ID - * @arg @ref HAL_I2C_MEM_TX_COMPLETE_CB_ID Memory Tx Transfer callback ID - * @arg @ref HAL_I2C_MEM_RX_COMPLETE_CB_ID Memory Rx Transfer completed callback ID - * @arg @ref HAL_I2C_ERROR_CB_ID Error callback ID - * @arg @ref HAL_I2C_ABORT_CB_ID Abort callback ID - * @arg @ref HAL_I2C_MSPINIT_CB_ID MspInit callback ID - * @arg @ref HAL_I2C_MSPDEINIT_CB_ID MspDeInit callback ID - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_UnRegisterCallback(I2C_HandleTypeDef *hi2c, HAL_I2C_CallbackIDTypeDef CallbackID) { - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hi2c); - - if (HAL_I2C_STATE_READY == hi2c->State) { - switch (CallbackID) { - case HAL_I2C_MASTER_TX_COMPLETE_CB_ID: - hi2c->MasterTxCpltCallback = HAL_I2C_MasterTxCpltCallback; /* Legacy weak MasterTxCpltCallback */ - break; - - case HAL_I2C_MASTER_RX_COMPLETE_CB_ID: - hi2c->MasterRxCpltCallback = HAL_I2C_MasterRxCpltCallback; /* Legacy weak MasterRxCpltCallback */ - break; - - case HAL_I2C_SLAVE_TX_COMPLETE_CB_ID: - hi2c->SlaveTxCpltCallback = HAL_I2C_SlaveTxCpltCallback; /* Legacy weak SlaveTxCpltCallback */ - break; - - case HAL_I2C_SLAVE_RX_COMPLETE_CB_ID: - hi2c->SlaveRxCpltCallback = HAL_I2C_SlaveRxCpltCallback; /* Legacy weak SlaveRxCpltCallback */ - break; - - case HAL_I2C_LISTEN_COMPLETE_CB_ID: - hi2c->ListenCpltCallback = HAL_I2C_ListenCpltCallback; /* Legacy weak ListenCpltCallback */ - break; - - case HAL_I2C_MEM_TX_COMPLETE_CB_ID: - hi2c->MemTxCpltCallback = HAL_I2C_MemTxCpltCallback; /* Legacy weak MemTxCpltCallback */ - break; - - case HAL_I2C_MEM_RX_COMPLETE_CB_ID: - hi2c->MemRxCpltCallback = HAL_I2C_MemRxCpltCallback; /* Legacy weak MemRxCpltCallback */ - break; - - case HAL_I2C_ERROR_CB_ID: - hi2c->ErrorCallback = HAL_I2C_ErrorCallback; /* Legacy weak ErrorCallback */ - break; - - case HAL_I2C_ABORT_CB_ID: - hi2c->AbortCpltCallback = HAL_I2C_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ - break; - - case HAL_I2C_MSPINIT_CB_ID: - hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_I2C_MSPDEINIT_CB_ID: - hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default: - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } else if (HAL_I2C_STATE_RESET == hi2c->State) { - switch (CallbackID) { - case HAL_I2C_MSPINIT_CB_ID: - hi2c->MspInitCallback = HAL_I2C_MspInit; /* Legacy weak MspInit */ - break; - - case HAL_I2C_MSPDEINIT_CB_ID: - hi2c->MspDeInitCallback = HAL_I2C_MspDeInit; /* Legacy weak MspDeInit */ - break; - - default: - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - break; - } - } else { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hi2c); - return status; -} - -/** - * @brief Register the Slave Address Match I2C Callback - * To be used instead of the weak HAL_I2C_AddrCallback() predefined callback - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pCallback pointer to the Address Match Callback function - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_RegisterAddrCallback(I2C_HandleTypeDef *hi2c, pI2C_AddrCallbackTypeDef pCallback) { - HAL_StatusTypeDef status = HAL_OK; - - if (pCallback == NULL) { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - return HAL_ERROR; - } - /* Process locked */ - __HAL_LOCK(hi2c); - - if (HAL_I2C_STATE_READY == hi2c->State) { - hi2c->AddrCallback = pCallback; - } else { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hi2c); - return status; -} - -/** - * @brief UnRegister the Slave Address Match I2C Callback - * Info Ready I2C Callback is redirected to the weak HAL_I2C_AddrCallback() predefined callback - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_UnRegisterAddrCallback(I2C_HandleTypeDef *hi2c) { - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hi2c); - - if (HAL_I2C_STATE_READY == hi2c->State) { - hi2c->AddrCallback = HAL_I2C_AddrCallback; /* Legacy weak AddrCallback */ - } else { - /* Update the error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_INVALID_CALLBACK; - - /* Return error status */ - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hi2c); - return status; -} - -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - -/** - * @} - */ - -/** @defgroup I2C_Exported_Functions_Group2 Input and Output operation functions - * @brief Data transfers functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the I2C data - transfers. - - (#) There are two modes of transfer: - (++) Blocking mode : The communication is performed in the polling mode. - The status of all data processing is returned by the same function - after finishing transfer. - (++) No-Blocking mode : The communication is performed using Interrupts - or DMA. These functions return the status of the transfer startup. - The end of the data processing will be indicated through the - dedicated I2C IRQ when using Interrupt mode or the DMA IRQ when - using DMA mode. - - (#) Blocking mode functions are : - (++) HAL_I2C_Master_Transmit() - (++) HAL_I2C_Master_Receive() - (++) HAL_I2C_Slave_Transmit() - (++) HAL_I2C_Slave_Receive() - (++) HAL_I2C_Mem_Write() - (++) HAL_I2C_Mem_Read() - (++) HAL_I2C_IsDeviceReady() - - (#) No-Blocking mode functions with Interrupt are : - (++) HAL_I2C_Master_Transmit_IT() - (++) HAL_I2C_Master_Receive_IT() - (++) HAL_I2C_Slave_Transmit_IT() - (++) HAL_I2C_Slave_Receive_IT() - (++) HAL_I2C_Mem_Write_IT() - (++) HAL_I2C_Mem_Read_IT() - (++) HAL_I2C_Master_Seq_Transmit_IT() - (++) HAL_I2C_Master_Seq_Receive_IT() - (++) HAL_I2C_Slave_Seq_Transmit_IT() - (++) HAL_I2C_Slave_Seq_Receive_IT() - (++) HAL_I2C_EnableListen_IT() - (++) HAL_I2C_DisableListen_IT() - (++) HAL_I2C_Master_Abort_IT() - - (#) No-Blocking mode functions with DMA are : - (++) HAL_I2C_Master_Transmit_DMA() - (++) HAL_I2C_Master_Receive_DMA() - (++) HAL_I2C_Slave_Transmit_DMA() - (++) HAL_I2C_Slave_Receive_DMA() - (++) HAL_I2C_Mem_Write_DMA() - (++) HAL_I2C_Mem_Read_DMA() - (++) HAL_I2C_Master_Seq_Transmit_DMA() - (++) HAL_I2C_Master_Seq_Receive_DMA() - (++) HAL_I2C_Slave_Seq_Transmit_DMA() - (++) HAL_I2C_Slave_Seq_Receive_DMA() - - (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: - (++) HAL_I2C_MasterTxCpltCallback() - (++) HAL_I2C_MasterRxCpltCallback() - (++) HAL_I2C_SlaveTxCpltCallback() - (++) HAL_I2C_SlaveRxCpltCallback() - (++) HAL_I2C_MemTxCpltCallback() - (++) HAL_I2C_MemRxCpltCallback() - (++) HAL_I2C_AddrCallback() - (++) HAL_I2C_ListenCpltCallback() - (++) HAL_I2C_ErrorCallback() - (++) HAL_I2C_AbortCpltCallback() - -@endverbatim - * @{ - */ - -/** - * @brief Transmits in master mode an amount of data in blocking mode. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - /* Init tickstart for timeout management*/ - uint32_t tickstart = HAL_GetTick(); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Send Slave Address */ - if (I2C_MasterRequestWrite(hi2c, DevAddress, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - while (hi2c->XferSize > 0U) { - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - return HAL_ERROR; - } - - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - hi2c->XferSize--; - - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) { - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - hi2c->XferSize--; - } - - /* Wait until BTF flag is set */ - if (I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - return HAL_ERROR; - } - } - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receives in master mode an amount of data in blocking mode. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - __IO uint32_t count = 0U; - - /* Init tickstart for timeout management*/ - uint32_t tickstart = HAL_GetTick(); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Send Slave Address */ - if (I2C_MasterRequestRead(hi2c, DevAddress, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - if (hi2c->XferSize == 0U) { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } else if (hi2c->XferSize == 1U) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - /* Re-enable IRQs */ - __enable_irq(); - } else if (hi2c->XferSize == 2U) { - /* Enable Pos */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Re-enable IRQs */ - __enable_irq(); - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } - - while (hi2c->XferSize > 0U) { - if (hi2c->XferSize <= 3U) { - /* One byte */ - if (hi2c->XferSize == 1U) { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - } - /* Two bytes */ - else if (hi2c->XferSize == 2U) { - /* Wait until BTF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - - /* Re-enable IRQs */ - __enable_irq(); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - } - /* 3 Last bytes */ - else { - /* Wait until BTF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - - /* Wait until BTF flag is set */ - count = I2C_TIMEOUT_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Re-enable IRQs */ - __enable_irq(); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == RESET); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - - /* Re-enable IRQs */ - __enable_irq(); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - } - } else { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - } - } - } - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Transmits in slave mode an amount of data in blocking mode. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - /* Init tickstart for timeout management*/ - uint32_t tickstart = HAL_GetTick(); - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Enable Address Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* If 10bit addressing mode is selected */ - if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) { - /* Wait until ADDR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } - - while (hi2c->XferSize > 0U) { - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - /* Disable Address Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - return HAL_ERROR; - } - - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - hi2c->XferSize--; - - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) { - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - hi2c->XferSize--; - } - } - - /* Wait until AF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Clear AF flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Disable Address Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receive in slave mode an amount of data in blocking mode - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - /* Init tickstart for timeout management*/ - uint32_t tickstart = HAL_GetTick(); - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == (uint16_t)0)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Enable Address Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - while (hi2c->XferSize > 0U) { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - /* Disable Address Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - return HAL_ERROR; - } - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - } - } - - /* Wait until STOP flag is set */ - if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - /* Disable Address Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - return HAL_ERROR; - } - - /* Clear STOP flag */ - __HAL_I2C_CLEAR_STOPFLAG(hi2c); - - /* Disable Address Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in master mode an amount of data in non-blocking mode with Interrupt - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->Devaddress = DevAddress; - - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receive in master mode an amount of data in non-blocking mode with Interrupt - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->Devaddress = DevAddress; - - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in slave mode an amount of data in non-blocking mode with Interrupt - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) { - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Enable Address Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receive in slave mode an amount of data in non-blocking mode with Interrupt - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) { - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Enable Address Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in master mode an amount of data in non-blocking mode with DMA - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - HAL_StatusTypeDef dmaxferstatus; - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->Devaddress = DevAddress; - - if (hi2c->XferSize > 0U) { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize); - - if (dmaxferstatus == HAL_OK) { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Enable DMA Request */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - } - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receive in master mode an amount of data in non-blocking mode with DMA - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - HAL_StatusTypeDef dmaxferstatus; - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->Devaddress = DevAddress; - - if (hi2c->XferSize > 0U) { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); - - if (dmaxferstatus == HAL_OK) { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Enable DMA Request */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - } - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in slave mode an amount of data in non-blocking mode with DMA - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef dmaxferstatus; - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize); - - if (dmaxferstatus == HAL_OK) { - /* Enable Address Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Enable DMA Request */ - hi2c->Instance->CR2 |= I2C_CR2_DMAEN; - - return HAL_OK; - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receive in slave mode an amount of data in non-blocking mode with DMA - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef dmaxferstatus; - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); - - if (dmaxferstatus == HAL_OK) { - /* Enable Address Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Enable DMA Request */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - return HAL_OK; - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - return HAL_BUSY; - } -} - -/** - * @brief Write an amount of data in blocking mode to a specific memory address - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - /* Init tickstart for timeout management*/ - uint32_t tickstart = HAL_GetTick(); - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - while (hi2c->XferSize > 0U) { - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - return HAL_ERROR; - } - - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) { - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - } - } - - /* Wait until BTF flag is set */ - if (I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - return HAL_ERROR; - } - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Read an amount of data in blocking mode from a specific memory address - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - __IO uint32_t count = 0U; - - /* Init tickstart for timeout management*/ - uint32_t tickstart = HAL_GetTick(); - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - if (hi2c->XferSize == 0U) { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } else if (hi2c->XferSize == 1U) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - /* Re-enable IRQs */ - __enable_irq(); - } else if (hi2c->XferSize == 2U) { - /* Enable Pos */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Re-enable IRQs */ - __enable_irq(); - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } - - while (hi2c->XferSize > 0U) { - if (hi2c->XferSize <= 3U) { - /* One byte */ - if (hi2c->XferSize == 1U) { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - } - /* Two bytes */ - else if (hi2c->XferSize == 2U) { - /* Wait until BTF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - - /* Re-enable IRQs */ - __enable_irq(); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - } - /* 3 Last bytes */ - else { - /* Wait until BTF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - - /* Wait until BTF flag is set */ - count = I2C_TIMEOUT_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Re-enable IRQs */ - __enable_irq(); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == RESET); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - - /* Re-enable IRQs */ - __enable_irq(); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - } - } else { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferSize--; - hi2c->XferCount--; - } - } - } - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Write an amount of data in non-blocking mode with Interrupt to a specific memory address - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->Devaddress = DevAddress; - hi2c->Memaddress = MemAddress; - hi2c->MemaddSize = MemAddSize; - hi2c->EventCount = 0U; - - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Read an amount of data in non-blocking mode with Interrupt from a specific memory address - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->Devaddress = DevAddress; - hi2c->Memaddress = MemAddress; - hi2c->MemaddSize = MemAddSize; - hi2c->EventCount = 0U; - - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - if (hi2c->XferSize > 0U) { - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - } - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Write an amount of data in non-blocking mode with DMA to a specific memory address - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - HAL_StatusTypeDef dmaxferstatus; - - /* Init tickstart for timeout management*/ - uint32_t tickstart = HAL_GetTick(); - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - if (hi2c->XferSize > 0U) { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize); - - if (dmaxferstatus == HAL_OK) { - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK) { - /* Abort the ongoing DMA */ - dmaxferstatus = HAL_DMA_Abort_IT(hi2c->hdmatx); - - /* Prevent unused argument(s) compilation and MISRA warning */ - UNUSED(dmaxferstatus); - - /* Clear directly Complete callback as no XferAbortCallback is used to finalize Abort treatment */ - if (hi2c->hdmatx != NULL) { - hi2c->hdmatx->XferCpltCallback = NULL; - } - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - hi2c->XferSize = 0U; - hi2c->XferCount = 0U; - - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_ERR); - - /* Enable DMA Request */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - return HAL_OK; - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_SIZE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - return HAL_BUSY; - } -} - -/** - * @brief Reads an amount of data in non-blocking mode with DMA from a specific memory address. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be read - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) { - /* Init tickstart for timeout management*/ - uint32_t tickstart = HAL_GetTick(); - __IO uint32_t count = 0U; - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - if (hi2c->XferSize > 0U) { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); - - if (dmaxferstatus == HAL_OK) { - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK) { - /* Abort the ongoing DMA */ - dmaxferstatus = HAL_DMA_Abort_IT(hi2c->hdmarx); - - /* Prevent unused argument(s) compilation and MISRA warning */ - UNUSED(dmaxferstatus); - - /* Clear directly Complete callback as no XferAbortCallback is used to finalize Abort treatment */ - if (hi2c->hdmarx != NULL) { - hi2c->hdmarx->XferCpltCallback = NULL; - } - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - hi2c->XferSize = 0U; - hi2c->XferCount = 0U; - - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - return HAL_ERROR; - } - - if (hi2c->XferSize == 1U) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } else { - /* Enable Last DMA bit */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_LAST); - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_ERR); - - /* Enable DMA Request */ - hi2c->Instance->CR2 |= I2C_CR2_DMAEN; - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - } - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Checks if target device is ready for communication. - * @note This function is used with Memory devices - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param Trials Number of trials - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout) { - /* Get tick */ - uint32_t tickstart = HAL_GetTick(); - uint32_t I2C_Trials = 1U; - FlagStatus tmp1; - FlagStatus tmp2; - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - do { - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, tickstart) != HAL_OK) { - if (READ_BIT(hi2c->Instance->CR1, I2C_CR1_START) == I2C_CR1_START) { - hi2c->ErrorCode = HAL_I2C_WRONG_START; - } - return HAL_TIMEOUT; - } - - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); - - /* Wait until ADDR or AF flag are set */ - /* Get tick */ - tickstart = HAL_GetTick(); - - tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); - tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF); - while ((hi2c->State != HAL_I2C_STATE_TIMEOUT) && (tmp1 == RESET) && (tmp2 == RESET)) { - if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0U)) { - hi2c->State = HAL_I2C_STATE_TIMEOUT; - } - tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); - tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF); - } - - hi2c->State = HAL_I2C_STATE_READY; - - /* Check if the ADDR flag has been set */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR) == SET) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - /* Clear ADDR Flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_ERROR; - } - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - /* Clear AF Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_ERROR; - } - } - - /* Increment Trials */ - I2C_Trials++; - } while (I2C_Trials < Trials); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential transmit in master I2C mode an amount of data in non-blocking mode with Interrupt. - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - __IO uint32_t Prev_State = 0x00U; - __IO uint32_t count = 0x00U; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Check Busy Flag only if FIRST call of Master interface */ - if ((READ_BIT(hi2c->Instance->CR1, I2C_CR1_STOP) == I2C_CR1_STOP) || (XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - hi2c->Devaddress = DevAddress; - - Prev_State = hi2c->PreviousState; - - /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - if ((Prev_State != I2C_STATE_MASTER_BUSY_TX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) { - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential transmit in master I2C mode an amount of data in non-blocking mode with DMA. - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - __IO uint32_t Prev_State = 0x00U; - __IO uint32_t count = 0x00U; - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Check Busy Flag only if FIRST call of Master interface */ - if ((READ_BIT(hi2c->Instance->CR1, I2C_CR1_STOP) == I2C_CR1_STOP) || (XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - hi2c->Devaddress = DevAddress; - - Prev_State = hi2c->PreviousState; - - if (hi2c->XferSize > 0U) { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize); - - if (dmaxferstatus == HAL_OK) { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - if ((Prev_State != I2C_STATE_MASTER_BUSY_TX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) { - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* If XferOptions is not associated to a new frame, mean no start bit is request, enable directly the DMA request */ - /* In other cases, DMA request is enabled after Slave address treatment in IRQHandler */ - if ((XferOptions == I2C_NEXT_FRAME) || (XferOptions == I2C_LAST_FRAME) || (XferOptions == I2C_LAST_FRAME_NO_STOP)) { - /* Enable DMA Request */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - } - - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - if ((Prev_State != I2C_STATE_MASTER_BUSY_TX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) { - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - } - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential receive in master I2C mode an amount of data in non-blocking mode with Interrupt - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - __IO uint32_t Prev_State = 0x00U; - __IO uint32_t count = 0U; - uint32_t enableIT = (I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Check Busy Flag only if FIRST call of Master interface */ - if ((READ_BIT(hi2c->Instance->CR1, I2C_CR1_STOP) == I2C_CR1_STOP) || (XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - hi2c->Devaddress = DevAddress; - - Prev_State = hi2c->PreviousState; - - if ((hi2c->XferCount == 2U) && ((XferOptions == I2C_LAST_FRAME) || (XferOptions == I2C_LAST_FRAME_NO_STOP))) { - if (Prev_State == I2C_STATE_MASTER_BUSY_RX) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Enable Pos */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - /* Remove Enabling of IT_BUF, mean RXNE treatment, treat the 2 bytes through BTF */ - enableIT &= ~I2C_IT_BUF; - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } - - /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - if ((Prev_State != I2C_STATE_MASTER_BUSY_RX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) { - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable interrupts */ - __HAL_I2C_ENABLE_IT(hi2c, enableIT); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential receive in master mode an amount of data in non-blocking mode with DMA - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - __IO uint32_t Prev_State = 0x00U; - __IO uint32_t count = 0U; - uint32_t enableIT = (I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Check Busy Flag only if FIRST call of Master interface */ - if ((READ_BIT(hi2c->Instance->CR1, I2C_CR1_STOP) == I2C_CR1_STOP) || (XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - /* Clear Last DMA bit */ - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_LAST); - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - hi2c->Devaddress = DevAddress; - - Prev_State = hi2c->PreviousState; - - if (hi2c->XferSize > 0U) { - if ((hi2c->XferCount == 2U) && ((XferOptions == I2C_LAST_FRAME) || (XferOptions == I2C_LAST_FRAME_NO_STOP))) { - if (Prev_State == I2C_STATE_MASTER_BUSY_RX) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Enable Pos */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - /* Enable Last DMA bit */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_LAST); - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - if ((XferOptions == I2C_LAST_FRAME) || (XferOptions == I2C_OTHER_AND_LAST_FRAME) || (XferOptions == I2C_LAST_FRAME_NO_STOP)) { - /* Enable Last DMA bit */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_LAST); - } - } - - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); - - if (dmaxferstatus == HAL_OK) { - /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - if ((Prev_State != I2C_STATE_MASTER_BUSY_RX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) { - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Update interrupt for only EVT and ERR */ - enableIT = (I2C_IT_EVT | I2C_IT_ERR); - } else { - /* Update interrupt for only ERR */ - enableIT = I2C_IT_ERR; - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* If XferOptions is not associated to a new frame, mean no start bit is request, enable directly the DMA request */ - /* In other cases, DMA request is enabled after Slave address treatment in IRQHandler */ - if ((XferOptions == I2C_NEXT_FRAME) || (XferOptions == I2C_LAST_FRAME) || (XferOptions == I2C_LAST_FRAME_NO_STOP)) { - /* Enable DMA Request */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - } - - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, enableIT); - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* If transfer direction not change and there is no request to start another frame, do not generate Restart Condition */ - /* Mean Previous state is same as current state */ - if ((Prev_State != I2C_STATE_MASTER_BUSY_RX) || (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(XferOptions) == 1)) { - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable interrupts */ - __HAL_I2C_ENABLE_IT(hi2c, enableIT); - } - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential transmit in slave mode an amount of data in non-blocking mode with Interrupt - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX_LISTEN; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential transmit in slave mode an amount of data in non-blocking mode with DMA - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ - /* and then toggle the HAL slave RX state to TX state */ - if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN) { - if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - /* Abort DMA Xfer if any */ - if (hi2c->hdmarx != NULL) { - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); - } - } - } - } else if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) { - if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - /* Abort DMA Xfer if any */ - if (hi2c->hdmatx != NULL) { - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); - } - } - } - } else { - /* Nothing to do */ - } - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_TX_LISTEN; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize); - - if (dmaxferstatus == HAL_OK) { - /* Enable Address Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Enable DMA Request */ - hi2c->Instance->CR2 |= I2C_CR2_DMAEN; - - return HAL_OK; - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential receive in slave mode an amount of data in non-blocking mode with Interrupt - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX_LISTEN; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential receive in slave mode an amount of data in non-blocking mode with DMA - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Seq_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - HAL_StatusTypeDef dmaxferstatus; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* I2C cannot manage full duplex exchange so disable previous IT enabled if any */ - /* and then toggle the HAL slave RX state to TX state */ - if (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN) { - if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - /* Abort DMA Xfer if any */ - if (hi2c->hdmarx != NULL) { - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); - } - } - } - } else if (hi2c->State == HAL_I2C_STATE_BUSY_TX_LISTEN) { - if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - /* Abort DMA Xfer if any */ - if (hi2c->hdmatx != NULL) { - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); - } - } - } - } else { - /* Nothing to do */ - } - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - hi2c->State = HAL_I2C_STATE_BUSY_RX_LISTEN; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferSize = hi2c->XferCount; - hi2c->XferOptions = XferOptions; - - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - dmaxferstatus = HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); - - if (dmaxferstatus == HAL_OK) { - /* Enable Address Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Enable DMA Request */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - return HAL_OK; - } else { - /* Update I2C state */ - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Update I2C error code */ - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } else { - return HAL_BUSY; - } -} - -/** - * @brief Enable the Address listen mode with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c) { - if (hi2c->State == HAL_I2C_STATE_READY) { - hi2c->State = HAL_I2C_STATE_LISTEN; - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Enable Address Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Disable the Address listen mode with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) { - /* Declaration of tmp to prevent undefined behavior of volatile usage */ - uint32_t tmp; - - /* Disable Address listen mode only if a transfer is not ongoing */ - if (hi2c->State == HAL_I2C_STATE_LISTEN) { - tmp = (uint32_t)(hi2c->State) & I2C_STATE_MSK; - hi2c->PreviousState = tmp | (uint32_t)(hi2c->Mode); - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Disable Address Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Disable EVT and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Abort a master I2C IT or DMA process communication with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - HAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(DevAddress); - - /* Abort Master transfer during Receive or Transmit process */ - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET) && (CurrentMode == HAL_I2C_MODE_MASTER)) { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_ABORT; - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - hi2c->XferCount = 0U; - - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c); - - return HAL_OK; - } else { - /* Wrong usage of abort function */ - /* This function should be used only in case of abort monitored by master device */ - /* Or periphal is not in busy state, mean there is no active sequence to be abort */ - return HAL_ERROR; - } -} - -/** - * @} - */ - -/** @defgroup I2C_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks - * @{ - */ - -/** - * @brief This function handles I2C event interrupt request. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c) { - uint32_t sr1itflags; - uint32_t sr2itflags = 0U; - uint32_t itsources = READ_REG(hi2c->Instance->CR2); - uint32_t CurrentXferOptions = hi2c->XferOptions; - HAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; - HAL_I2C_StateTypeDef CurrentState = hi2c->State; - - /* Master or Memory mode selected */ - if ((CurrentMode == HAL_I2C_MODE_MASTER) || (CurrentMode == HAL_I2C_MODE_MEM)) { - sr2itflags = READ_REG(hi2c->Instance->SR2); - sr1itflags = READ_REG(hi2c->Instance->SR1); - - /* Exit IRQ event until Start Bit detected in case of Other frame requested */ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_SB) == RESET) && (IS_I2C_TRANSFER_OTHER_OPTIONS_REQUEST(CurrentXferOptions) == 1U)) { - return; - } - - /* SB Set ----------------------------------------------------------------*/ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_SB) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) { - /* Convert OTHER_xxx XferOptions if any */ - I2C_ConvertOtherXferOptions(hi2c); - - I2C_Master_SB(hi2c); - } - /* ADD10 Set -------------------------------------------------------------*/ - else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_ADD10) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) { - I2C_Master_ADD10(hi2c); - } - /* ADDR Set --------------------------------------------------------------*/ - else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_ADDR) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) { - I2C_Master_ADDR(hi2c); - } - /* I2C in mode Transmitter -----------------------------------------------*/ - else if (I2C_CHECK_FLAG(sr2itflags, I2C_FLAG_TRA) != RESET) { - /* Do not check buffer and BTF flag if a Xfer DMA is on going */ - if (READ_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN) != I2C_CR2_DMAEN) { - /* TXE set and BTF reset -----------------------------------------------*/ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_TXE) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_BUF) != RESET) && (I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) == RESET)) { - I2C_MasterTransmit_TXE(hi2c); - } - /* BTF set -------------------------------------------------------------*/ - else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) { - if (CurrentMode == HAL_I2C_MODE_MASTER) { - I2C_MasterTransmit_BTF(hi2c); - } else /* HAL_I2C_MODE_MEM */ - { - I2C_MemoryTransmit_TXE_BTF(hi2c); - } - } else { - /* Do nothing */ - } - } - } - /* I2C in mode Receiver --------------------------------------------------*/ - else { - /* Do not check buffer and BTF flag if a Xfer DMA is on going */ - if (READ_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN) != I2C_CR2_DMAEN) { - /* RXNE set and BTF reset -----------------------------------------------*/ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_RXNE) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_BUF) != RESET) && (I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) == RESET)) { - I2C_MasterReceive_RXNE(hi2c); - } - /* BTF set -------------------------------------------------------------*/ - else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) { - I2C_MasterReceive_BTF(hi2c); - } else { - /* Do nothing */ - } - } - } - } - /* Slave mode selected */ - else { - /* If an error is detected, read only SR1 register to prevent */ - /* a clear of ADDR flags by reading SR2 after reading SR1 in Error treatment */ - if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) { - sr1itflags = READ_REG(hi2c->Instance->SR1); - } else { - sr2itflags = READ_REG(hi2c->Instance->SR2); - sr1itflags = READ_REG(hi2c->Instance->SR1); - } - - /* ADDR set --------------------------------------------------------------*/ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_ADDR) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) { - /* Now time to read SR2, this will clear ADDR flag automatically */ - if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) { - sr2itflags = READ_REG(hi2c->Instance->SR2); - } - I2C_Slave_ADDR(hi2c, sr2itflags); - } - /* STOPF set --------------------------------------------------------------*/ - else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_STOPF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) { - I2C_Slave_STOPF(hi2c); - } - /* I2C in mode Transmitter -----------------------------------------------*/ - else if ((CurrentState == HAL_I2C_STATE_BUSY_TX) || (CurrentState == HAL_I2C_STATE_BUSY_TX_LISTEN)) { - /* TXE set and BTF reset -----------------------------------------------*/ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_TXE) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_BUF) != RESET) && (I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) == RESET)) { - I2C_SlaveTransmit_TXE(hi2c); - } - /* BTF set -------------------------------------------------------------*/ - else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) { - I2C_SlaveTransmit_BTF(hi2c); - } else { - /* Do nothing */ - } - } - /* I2C in mode Receiver --------------------------------------------------*/ - else { - /* RXNE set and BTF reset ----------------------------------------------*/ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_RXNE) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_BUF) != RESET) && (I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) == RESET)) { - I2C_SlaveReceive_RXNE(hi2c); - } - /* BTF set -------------------------------------------------------------*/ - else if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BTF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_EVT) != RESET)) { - I2C_SlaveReceive_BTF(hi2c); - } else { - /* Do nothing */ - } - } - } -} - -/** - * @brief This function handles I2C error interrupt request. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) { - HAL_I2C_ModeTypeDef tmp1; - uint32_t tmp2; - HAL_I2C_StateTypeDef tmp3; - uint32_t tmp4; - uint32_t sr1itflags = READ_REG(hi2c->Instance->SR1); - uint32_t itsources = READ_REG(hi2c->Instance->CR2); - uint32_t error = HAL_I2C_ERROR_NONE; - HAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; - - /* I2C Bus error interrupt occurred ----------------------------------------*/ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_BERR) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERR) != RESET)) { - error |= HAL_I2C_ERROR_BERR; - - /* Clear BERR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR); - - /* Workaround: Start cannot be generated after a misplaced Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_SWRST); - } - - /* I2C Arbitration Lost error interrupt occurred ---------------------------*/ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_ARLO) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERR) != RESET)) { - error |= HAL_I2C_ERROR_ARLO; - - /* Clear ARLO flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO); - } - - /* I2C Acknowledge failure error interrupt occurred ------------------------*/ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_AF) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERR) != RESET)) { - tmp1 = CurrentMode; - tmp2 = hi2c->XferCount; - tmp3 = hi2c->State; - tmp4 = hi2c->PreviousState; - if ((tmp1 == HAL_I2C_MODE_SLAVE) && (tmp2 == 0U) - && ((tmp3 == HAL_I2C_STATE_BUSY_TX) || (tmp3 == HAL_I2C_STATE_BUSY_TX_LISTEN) || ((tmp3 == HAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX)))) { - I2C_Slave_AF(hi2c); - } else { - /* Clear AF flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - error |= HAL_I2C_ERROR_AF; - - /* Do not generate a STOP in case of Slave receive non acknowledge during transfer (mean not at the end of transfer) */ - if ((CurrentMode == HAL_I2C_MODE_MASTER) || (CurrentMode == HAL_I2C_MODE_MEM)) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - } - } - - /* I2C Over-Run/Under-Run interrupt occurred -------------------------------*/ - if ((I2C_CHECK_FLAG(sr1itflags, I2C_FLAG_OVR) != RESET) && (I2C_CHECK_IT_SOURCE(itsources, I2C_IT_ERR) != RESET)) { - error |= HAL_I2C_ERROR_OVR; - /* Clear OVR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR); - } - - /* Call the Error Callback in case of Error detected -----------------------*/ - if (error != HAL_I2C_ERROR_NONE) { - hi2c->ErrorCode |= error; - I2C_ITError(hi2c); - } -} - -/** - * @brief Master Tx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MasterTxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Master Rx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MasterRxCpltCallback could be implemented in the user file - */ -} - -/** @brief Slave Tx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_SlaveTxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Slave Rx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_SlaveRxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Slave Address Match callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param TransferDirection Master request Transfer Direction (Write/Read), value of @ref I2C_XferDirection_definition - * @param AddrMatchCode Address Match Code - * @retval None - */ -__weak void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - UNUSED(TransferDirection); - UNUSED(AddrMatchCode); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_AddrCallback() could be implemented in the user file - */ -} - -/** - * @brief Listen Complete callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_ListenCpltCallback() could be implemented in the user file - */ -} - -/** - * @brief Memory Tx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MemTxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Memory Rx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MemRxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief I2C error callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief I2C abort callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_AbortCpltCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup I2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions - * @brief Peripheral State, Mode and Error functions - * -@verbatim - =============================================================================== - ##### Peripheral State, Mode and Error functions ##### - =============================================================================== - [..] - This subsection permit to get in run-time the status of the peripheral - and the data flow. - -@endverbatim - * @{ - */ - -/** - * @brief Return the I2C handle state. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL state - */ -HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c) { - /* Return I2C handle state */ - return hi2c->State; -} - -/** - * @brief Returns the I2C Master, Slave, Memory or no mode. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL mode - */ -HAL_I2C_ModeTypeDef HAL_I2C_GetMode(I2C_HandleTypeDef *hi2c) { return hi2c->Mode; } - -/** - * @brief Return the I2C error code. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval I2C Error Code - */ -uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c) { return hi2c->ErrorCode; } - -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup I2C_Private_Functions - * @{ - */ - -/** - * @brief Handle TXE flag for Master - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - HAL_I2C_StateTypeDef CurrentState = hi2c->State; - HAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; - uint32_t CurrentXferOptions = hi2c->XferOptions; - - if ((hi2c->XferSize == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_TX)) { - /* Call TxCpltCallback() directly if no stop mode is set */ - if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME)) { - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterTxCpltCallback(hi2c); -#else - HAL_I2C_MasterTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else /* Generate Stop condition then Call TxCpltCallback() */ - { - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - hi2c->Mode = HAL_I2C_MODE_NONE; -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MemTxCpltCallback(hi2c); -#else - HAL_I2C_MemTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - hi2c->Mode = HAL_I2C_MODE_NONE; -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterTxCpltCallback(hi2c); -#else - HAL_I2C_MasterTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } - } else if ((CurrentState == HAL_I2C_STATE_BUSY_TX) || ((CurrentMode == HAL_I2C_MODE_MEM) && (CurrentState == HAL_I2C_STATE_BUSY_RX))) { - if (hi2c->XferCount == 0U) { - /* Disable BUF interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); - } else { - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - I2C_MemoryTransmit_TXE_BTF(hi2c); - } else { - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - } - } - } else { - /* Do nothing */ - } -} - -/** - * @brief Handle BTF flag for Master transmitter - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - uint32_t CurrentXferOptions = hi2c->XferOptions; - - if (hi2c->State == HAL_I2C_STATE_BUSY_TX) { - if (hi2c->XferCount != 0U) { - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - } else { - /* Call TxCpltCallback() directly if no stop mode is set */ - if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME)) { - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterTxCpltCallback(hi2c); -#else - HAL_I2C_MasterTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else /* Generate Stop condition then Call TxCpltCallback() */ - { - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterTxCpltCallback(hi2c); -#else - HAL_I2C_MasterTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } - } else { - /* Do nothing */ - } -} - -/** - * @brief Handle TXE and BTF flag for Memory transmitter - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_MemoryTransmit_TXE_BTF(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - HAL_I2C_StateTypeDef CurrentState = hi2c->State; - - if (hi2c->EventCount == 0U) { - /* If Memory address size is 8Bit */ - if (hi2c->MemaddSize == I2C_MEMADD_SIZE_8BIT) { - /* Send Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(hi2c->Memaddress); - - hi2c->EventCount += 2U; - } - /* If Memory address size is 16Bit */ - else { - /* Send MSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_MSB(hi2c->Memaddress); - - hi2c->EventCount++; - } - } else if (hi2c->EventCount == 1U) { - /* Send LSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(hi2c->Memaddress); - - hi2c->EventCount++; - } else if (hi2c->EventCount == 2U) { - if (CurrentState == HAL_I2C_STATE_BUSY_RX) { - /* Generate Restart */ - hi2c->Instance->CR1 |= I2C_CR1_START; - } else if ((hi2c->XferCount > 0U) && (CurrentState == HAL_I2C_STATE_BUSY_TX)) { - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - } else if ((hi2c->XferCount == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_TX)) { - /* Generate Stop condition then Call TxCpltCallback() */ - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MemTxCpltCallback(hi2c); -#else - HAL_I2C_MemTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - /* Do nothing */ - } - } else { - /* Do nothing */ - } -} - -/** - * @brief Handle RXNE flag for Master - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c) { - if (hi2c->State == HAL_I2C_STATE_BUSY_RX) { - uint32_t tmp; - - tmp = hi2c->XferCount; - if (tmp > 3U) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - - if (hi2c->XferCount == (uint16_t)3) { - /* Disable BUF interrupt, this help to treat correctly the last 4 bytes - on BTF subroutine */ - /* Disable BUF interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); - } - } else if ((hi2c->XferOptions != I2C_FIRST_AND_NEXT_FRAME) && ((tmp == 1U) || (tmp == 0U))) { - if (I2C_WaitOnSTOPRequestThroughIT(hi2c) == HAL_OK) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - - hi2c->State = HAL_I2C_STATE_READY; - - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_NONE; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MemRxCpltCallback(hi2c); -#else - HAL_I2C_MemRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterRxCpltCallback(hi2c); -#else - HAL_I2C_MasterRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } else { - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Call user error callback */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ErrorCallback(hi2c); -#else - HAL_I2C_ErrorCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } else { - /* Do nothing */ - } - } -} - -/** - * @brief Handle BTF flag for Master receiver - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - uint32_t CurrentXferOptions = hi2c->XferOptions; - - if (hi2c->XferCount == 4U) { - /* Disable BUF interrupt, this help to treat correctly the last 2 bytes - on BTF subroutine if there is a reception delay between N-1 and N byte */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - } else if (hi2c->XferCount == 3U) { - /* Disable BUF interrupt, this help to treat correctly the last 2 bytes - on BTF subroutine if there is a reception delay between N-1 and N byte */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); - - if ((CurrentXferOptions != I2C_NEXT_FRAME) && (CurrentXferOptions != I2C_FIRST_AND_NEXT_FRAME)) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - } else if (hi2c->XferCount == 2U) { - /* Prepare next transfer or stop current transfer */ - if ((CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME_NO_STOP)) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } else if ((CurrentXferOptions == I2C_NEXT_FRAME) || (CurrentXferOptions == I2C_FIRST_AND_NEXT_FRAME)) { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } else if (CurrentXferOptions != I2C_LAST_FRAME_NO_STOP) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } else { - /* Do nothing */ - } - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - - /* Disable EVT and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - hi2c->State = HAL_I2C_STATE_READY; - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_NONE; -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MemRxCpltCallback(hi2c); -#else - HAL_I2C_MemRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterRxCpltCallback(hi2c); -#else - HAL_I2C_MasterRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } else { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - } -} - -/** - * @brief Handle SB flag for Master - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_Master_SB(I2C_HandleTypeDef *hi2c) { - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - if (hi2c->EventCount == 0U) { - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(hi2c->Devaddress); - } else { - hi2c->Instance->DR = I2C_7BIT_ADD_READ(hi2c->Devaddress); - } - } else { - if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) { - /* Send slave 7 Bits address */ - if (hi2c->State == HAL_I2C_STATE_BUSY_TX) { - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(hi2c->Devaddress); - } else { - hi2c->Instance->DR = I2C_7BIT_ADD_READ(hi2c->Devaddress); - } - - if (((hi2c->hdmatx != NULL) && (hi2c->hdmatx->XferCpltCallback != NULL)) || ((hi2c->hdmarx != NULL) && (hi2c->hdmarx->XferCpltCallback != NULL))) { - /* Enable DMA Request */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - } - } else { - if (hi2c->EventCount == 0U) { - /* Send header of slave address */ - hi2c->Instance->DR = I2C_10BIT_HEADER_WRITE(hi2c->Devaddress); - } else if (hi2c->EventCount == 1U) { - /* Send header of slave address */ - hi2c->Instance->DR = I2C_10BIT_HEADER_READ(hi2c->Devaddress); - } else { - /* Do nothing */ - } - } - } -} - -/** - * @brief Handle ADD10 flag for Master - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_Master_ADD10(I2C_HandleTypeDef *hi2c) { - /* Send slave address */ - hi2c->Instance->DR = I2C_10BIT_ADDRESS(hi2c->Devaddress); - - if ((hi2c->hdmatx != NULL) || (hi2c->hdmarx != NULL)) { - if ((hi2c->hdmatx->XferCpltCallback != NULL) || (hi2c->hdmarx->XferCpltCallback != NULL)) { - /* Enable DMA Request */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - } - } -} - -/** - * @brief Handle ADDR flag for Master - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_Master_ADDR(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - HAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; - uint32_t CurrentXferOptions = hi2c->XferOptions; - uint32_t Prev_State = hi2c->PreviousState; - - if (hi2c->State == HAL_I2C_STATE_BUSY_RX) { - if ((hi2c->EventCount == 0U) && (CurrentMode == HAL_I2C_MODE_MEM)) { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } else if ((hi2c->EventCount == 0U) && (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)) { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Restart */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - hi2c->EventCount++; - } else { - if (hi2c->XferCount == 0U) { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } else if (hi2c->XferCount == 1U) { - if (CurrentXferOptions == I2C_NO_OPTION_FRAME) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } else { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - } - /* Prepare next transfer or stop current transfer */ - else if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && ((Prev_State != I2C_STATE_MASTER_BUSY_RX) || (CurrentXferOptions == I2C_FIRST_FRAME))) { - if ((CurrentXferOptions != I2C_NEXT_FRAME) && (CurrentXferOptions != I2C_FIRST_AND_NEXT_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME_NO_STOP)) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } else { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - } else if (hi2c->XferCount == 2U) { - if ((CurrentXferOptions != I2C_NEXT_FRAME) && (CurrentXferOptions != I2C_FIRST_AND_NEXT_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME_NO_STOP)) { - /* Enable Pos */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_POS); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } - - if (((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) - && ((CurrentXferOptions == I2C_NO_OPTION_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) - || (CurrentXferOptions == I2C_LAST_FRAME_NO_STOP) || (CurrentXferOptions == I2C_LAST_FRAME))) { - /* Enable Last DMA bit */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_LAST); - } - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - if (((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) - && ((CurrentXferOptions == I2C_NO_OPTION_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) - || (CurrentXferOptions == I2C_LAST_FRAME_NO_STOP) || (CurrentXferOptions == I2C_LAST_FRAME))) { - /* Enable Last DMA bit */ - SET_BIT(hi2c->Instance->CR2, I2C_CR2_LAST); - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } - - /* Reset Event counter */ - hi2c->EventCount = 0U; - } - } else { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } -} - -/** - * @brief Handle TXE flag for Slave - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_SlaveTransmit_TXE(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - HAL_I2C_StateTypeDef CurrentState = hi2c->State; - - if (hi2c->XferCount != 0U) { - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - - if ((hi2c->XferCount == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_TX_LISTEN)) { - /* Last Byte is received, disable Interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); - - /* Set state at HAL_I2C_STATE_LISTEN */ - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; - hi2c->State = HAL_I2C_STATE_LISTEN; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveTxCpltCallback(hi2c); -#else - HAL_I2C_SlaveTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } -} - -/** - * @brief Handle BTF flag for Slave transmitter - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_SlaveTransmit_BTF(I2C_HandleTypeDef *hi2c) { - if (hi2c->XferCount != 0U) { - /* Write data to DR */ - hi2c->Instance->DR = *hi2c->pBuffPtr; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - } -} - -/** - * @brief Handle RXNE flag for Slave - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_SlaveReceive_RXNE(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - HAL_I2C_StateTypeDef CurrentState = hi2c->State; - - if (hi2c->XferCount != 0U) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - - if ((hi2c->XferCount == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN)) { - /* Last Byte is received, disable Interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); - - /* Set state at HAL_I2C_STATE_LISTEN */ - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX; - hi2c->State = HAL_I2C_STATE_LISTEN; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveRxCpltCallback(hi2c); -#else - HAL_I2C_SlaveRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } -} - -/** - * @brief Handle BTF flag for Slave receiver - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_SlaveReceive_BTF(I2C_HandleTypeDef *hi2c) { - if (hi2c->XferCount != 0U) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - } -} - -/** - * @brief Handle ADD flag for Slave - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param IT2Flags Interrupt2 flags to handle. - * @retval None - */ -static void I2C_Slave_ADDR(I2C_HandleTypeDef *hi2c, uint32_t IT2Flags) { - uint8_t TransferDirection = I2C_DIRECTION_RECEIVE; - uint16_t SlaveAddrCode; - - if (((uint32_t)hi2c->State & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) { - /* Disable BUF interrupt, BUF enabling is manage through slave specific interface */ - __HAL_I2C_DISABLE_IT(hi2c, (I2C_IT_BUF)); - - /* Transfer Direction requested by Master */ - if (I2C_CHECK_FLAG(IT2Flags, I2C_FLAG_TRA) == RESET) { - TransferDirection = I2C_DIRECTION_TRANSMIT; - } - - if (I2C_CHECK_FLAG(IT2Flags, I2C_FLAG_DUALF) == RESET) { - SlaveAddrCode = (uint16_t)hi2c->Init.OwnAddress1; - } else { - SlaveAddrCode = (uint16_t)hi2c->Init.OwnAddress2; - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call Slave Addr callback */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->AddrCallback(hi2c, TransferDirection, SlaveAddrCode); -#else - HAL_I2C_AddrCallback(hi2c, TransferDirection, SlaveAddrCode); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - } -} - -/** - * @brief Handle STOPF flag for Slave - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - HAL_I2C_StateTypeDef CurrentState = hi2c->State; - - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Clear STOPF flag */ - __HAL_I2C_CLEAR_STOPFLAG(hi2c); - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* If a DMA is ongoing, Update handle size context */ - if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - if ((CurrentState == HAL_I2C_STATE_BUSY_RX) || (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN)) { - hi2c->XferCount = (uint16_t)(__HAL_DMA_GET_COUNTER(hi2c->hdmarx)); - - if (hi2c->XferCount != 0U) { - /* Set ErrorCode corresponding to a Non-Acknowledge */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - } - - /* Disable, stop the current DMA */ - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - /* Abort DMA Xfer if any */ - if (HAL_DMA_GetState(hi2c->hdmarx) != HAL_DMA_STATE_READY) { - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA RX */ - if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); - } - } - } else { - hi2c->XferCount = (uint16_t)(__HAL_DMA_GET_COUNTER(hi2c->hdmatx)); - - if (hi2c->XferCount != 0U) { - /* Set ErrorCode corresponding to a Non-Acknowledge */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - } - - /* Disable, stop the current DMA */ - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - /* Abort DMA Xfer if any */ - if (HAL_DMA_GetState(hi2c->hdmatx) != HAL_DMA_STATE_READY) { - /* Set the I2C DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; - - /* Abort DMA TX */ - if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) { - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); - } - } - } - } - - /* All data are not transferred, so set error code accordingly */ - if (hi2c->XferCount != 0U) { - /* Store Last receive data if any */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - } - - /* Store Last receive data if any */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - - /* Update counter */ - hi2c->XferCount--; - } - - if (hi2c->XferCount != 0U) { - /* Set ErrorCode corresponding to a Non-Acknowledge */ - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - } - } - - if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) { - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c); - } else { - if (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN) { - /* Set state at HAL_I2C_STATE_LISTEN */ - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_LISTEN; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveRxCpltCallback(hi2c); -#else - HAL_I2C_SlaveRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - - if (hi2c->State == HAL_I2C_STATE_LISTEN) { - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ListenCpltCallback(hi2c); -#else - HAL_I2C_ListenCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - if ((hi2c->PreviousState == I2C_STATE_SLAVE_BUSY_RX) || (CurrentState == HAL_I2C_STATE_BUSY_RX)) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveRxCpltCallback(hi2c); -#else - HAL_I2C_SlaveRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } - } -} - -/** - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -static void I2C_Slave_AF(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - HAL_I2C_StateTypeDef CurrentState = hi2c->State; - uint32_t CurrentXferOptions = hi2c->XferOptions; - - if (((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) && (CurrentState == HAL_I2C_STATE_LISTEN)) { - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Clear AF flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ListenCpltCallback(hi2c); -#else - HAL_I2C_ListenCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else if (CurrentState == HAL_I2C_STATE_BUSY_TX) { - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Clear AF flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveTxCpltCallback(hi2c); -#else - HAL_I2C_SlaveTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - /* Clear AF flag only */ - /* State Listen, but XferOptions == FIRST or NEXT */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - } -} - -/** - * @brief I2C interrupts error process - * @param hi2c I2C handle. - * @retval None - */ -static void I2C_ITError(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - HAL_I2C_StateTypeDef CurrentState = hi2c->State; - HAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; - uint32_t CurrentError; - - if (((CurrentMode == HAL_I2C_MODE_MASTER) || (CurrentMode == HAL_I2C_MODE_MEM)) && (CurrentState == HAL_I2C_STATE_BUSY_RX)) { - /* Disable Pos bit in I2C CR1 when error occurred in Master/Mem Receive IT Process */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - } - - if (((uint32_t)CurrentState & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) { - /* keep HAL_I2C_STATE_LISTEN */ - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_LISTEN; - } else { - /* If state is an abort treatment on going, don't change state */ - /* This change will be do later */ - if ((READ_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN) != I2C_CR2_DMAEN) && (CurrentState != HAL_I2C_STATE_ABORT)) { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - } - hi2c->PreviousState = I2C_STATE_NONE; - } - - /* Abort DMA transfer */ - if (READ_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN; - - if (hi2c->hdmatx->State != HAL_DMA_STATE_READY) { - /* Set the DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; - - if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) { - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); - } - } else { - /* Set the DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; - - if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) { - /* Store Last receive data if any */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - } - - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Call Directly hi2c->hdmarx->XferAbortCallback function in case of error */ - hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); - } - } - } else if (hi2c->State == HAL_I2C_STATE_ABORT) { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Store Last receive data if any */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - } - - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->AbortCpltCallback(hi2c); -#else - HAL_I2C_AbortCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - /* Store Last receive data if any */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) { - /* Read data from DR */ - *hi2c->pBuffPtr = (uint8_t)hi2c->Instance->DR; - - /* Increment Buffer pointer */ - hi2c->pBuffPtr++; - } - - /* Call user error callback */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ErrorCallback(hi2c); -#else - HAL_I2C_ErrorCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - - /* STOP Flag is not set after a NACK reception, BusError, ArbitrationLost, OverRun */ - CurrentError = hi2c->ErrorCode; - - if (((CurrentError & HAL_I2C_ERROR_BERR) == HAL_I2C_ERROR_BERR) || ((CurrentError & HAL_I2C_ERROR_ARLO) == HAL_I2C_ERROR_ARLO) || ((CurrentError & HAL_I2C_ERROR_AF) == HAL_I2C_ERROR_AF) - || ((CurrentError & HAL_I2C_ERROR_OVR) == HAL_I2C_ERROR_OVR)) { - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - } - - /* So may inform upper layer that listen phase is stopped */ - /* during NACK error treatment */ - CurrentState = hi2c->State; - if (((hi2c->ErrorCode & HAL_I2C_ERROR_AF) == HAL_I2C_ERROR_AF) && (CurrentState == HAL_I2C_STATE_LISTEN)) { - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ListenCpltCallback(hi2c); -#else - HAL_I2C_ListenCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } -} - -/** - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart) { - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - uint32_t CurrentXferOptions = hi2c->XferOptions; - - /* Generate Start condition if first transfer */ - if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME)) { - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - } else if (hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) { - /* Generate ReStart */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - } else { - /* Do nothing */ - } - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - if (READ_BIT(hi2c->Instance->CR1, I2C_CR1_START) == I2C_CR1_START) { - hi2c->ErrorCode = HAL_I2C_WRONG_START; - } - return HAL_TIMEOUT; - } - - if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) { - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); - } else { - /* Send header of slave address */ - hi2c->Instance->DR = I2C_10BIT_HEADER_WRITE(DevAddress); - - /* Wait until ADD10 flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADD10, Timeout, Tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Send slave address */ - hi2c->Instance->DR = I2C_10BIT_ADDRESS(DevAddress); - } - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Master sends target device address for read request. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart) { - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - uint32_t CurrentXferOptions = hi2c->XferOptions; - - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Generate Start condition if first transfer */ - if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME)) { - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - } else if (hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) { - /* Generate ReStart */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - } else { - /* Do nothing */ - } - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - if (READ_BIT(hi2c->Instance->CR1, I2C_CR1_START) == I2C_CR1_START) { - hi2c->ErrorCode = HAL_I2C_WRONG_START; - } - return HAL_TIMEOUT; - } - - if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) { - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_READ(DevAddress); - } else { - /* Send header of slave address */ - hi2c->Instance->DR = I2C_10BIT_HEADER_WRITE(DevAddress); - - /* Wait until ADD10 flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADD10, Timeout, Tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Send slave address */ - hi2c->Instance->DR = I2C_10BIT_ADDRESS(DevAddress); - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Restart */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - if (READ_BIT(hi2c->Instance->CR1, I2C_CR1_START) == I2C_CR1_START) { - hi2c->ErrorCode = HAL_I2C_WRONG_START; - } - return HAL_TIMEOUT; - } - - /* Send header of slave address */ - hi2c->Instance->DR = I2C_10BIT_HEADER_READ(DevAddress); - } - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief Master sends target device address followed by internal memory address for write request. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart) { - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - if (READ_BIT(hi2c->Instance->CR1, I2C_CR1_START) == I2C_CR1_START) { - hi2c->ErrorCode = HAL_I2C_WRONG_START; - } - return HAL_TIMEOUT; - } - - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - return HAL_ERROR; - } - - /* If Memory address size is 8Bit */ - if (MemAddSize == I2C_MEMADD_SIZE_8BIT) { - /* Send Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(MemAddress); - } - /* If Memory address size is 16Bit */ - else { - /* Send MSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_MSB(MemAddress); - - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - return HAL_ERROR; - } - - /* Send LSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(MemAddress); - } - - return HAL_OK; -} - -/** - * @brief Master sends target device address followed by internal memory address for read request. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart) { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Generate Start */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - if (READ_BIT(hi2c->Instance->CR1, I2C_CR1_START) == I2C_CR1_START) { - hi2c->ErrorCode = HAL_I2C_WRONG_START; - } - return HAL_TIMEOUT; - } - - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - return HAL_ERROR; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - return HAL_ERROR; - } - - /* If Memory address size is 8Bit */ - if (MemAddSize == I2C_MEMADD_SIZE_8BIT) { - /* Send Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(MemAddress); - } - /* If Memory address size is 16Bit */ - else { - /* Send MSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_MSB(MemAddress); - - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - return HAL_ERROR; - } - - /* Send LSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(MemAddress); - } - - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - return HAL_ERROR; - } - - /* Generate Restart */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_START); - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - if (READ_BIT(hi2c->Instance->CR1, I2C_CR1_START) == I2C_CR1_START) { - hi2c->ErrorCode = HAL_I2C_WRONG_START; - } - return HAL_TIMEOUT; - } - - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_READ(DevAddress); - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief DMA I2C process complete callback. - * @param hdma DMA handle - * @retval None - */ -static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma) { - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ - - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - HAL_I2C_StateTypeDef CurrentState = hi2c->State; - HAL_I2C_ModeTypeDef CurrentMode = hi2c->Mode; - uint32_t CurrentXferOptions = hi2c->XferOptions; - - /* Disable EVT and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Clear Complete callback */ - if (hi2c->hdmatx != NULL) { - hi2c->hdmatx->XferCpltCallback = NULL; - } - if (hi2c->hdmarx != NULL) { - hi2c->hdmarx->XferCpltCallback = NULL; - } - - if ((((uint32_t)CurrentState & (uint32_t)HAL_I2C_STATE_BUSY_TX) == (uint32_t)HAL_I2C_STATE_BUSY_TX) - || ((((uint32_t)CurrentState & (uint32_t)HAL_I2C_STATE_BUSY_RX) == (uint32_t)HAL_I2C_STATE_BUSY_RX) && (CurrentMode == HAL_I2C_MODE_SLAVE))) { - /* Disable DMA Request */ - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - hi2c->XferCount = 0U; - - if (CurrentState == HAL_I2C_STATE_BUSY_TX_LISTEN) { - /* Set state at HAL_I2C_STATE_LISTEN */ - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX; - hi2c->State = HAL_I2C_STATE_LISTEN; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveTxCpltCallback(hi2c); -#else - HAL_I2C_SlaveTxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else if (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN) { - /* Set state at HAL_I2C_STATE_LISTEN */ - hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX; - hi2c->State = HAL_I2C_STATE_LISTEN; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->SlaveRxCpltCallback(hi2c); -#else - HAL_I2C_SlaveRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - /* Do nothing */ - } - - /* Enable EVT and ERR interrupt to treat end of transfer in IRQ handler */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - } - /* Check current Mode, in case of treatment DMA handler have been preempted by a prior interrupt */ - else if (hi2c->Mode != HAL_I2C_MODE_NONE) { - if (hi2c->XferCount == (uint16_t)1) { - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - } - - /* Disable EVT and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Prepare next transfer or stop current transfer */ - if ((CurrentXferOptions == I2C_NO_OPTION_FRAME) || (CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_OTHER_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - - /* Disable Last DMA */ - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_LAST); - - /* Disable DMA Request */ - CLEAR_BIT(hi2c->Instance->CR2, I2C_CR2_DMAEN); - - hi2c->XferCount = 0U; - - /* Check if Errors has been detected during transfer */ - if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) { -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ErrorCallback(hi2c); -#else - HAL_I2C_ErrorCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - hi2c->State = HAL_I2C_STATE_READY; - - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_NONE; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MemRxCpltCallback(hi2c); -#else - HAL_I2C_MemRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_RX; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->MasterRxCpltCallback(hi2c); -#else - HAL_I2C_MasterRxCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } - } - } else { - /* Do nothing */ - } -} - -/** - * @brief DMA I2C communication error callback. - * @param hdma DMA handle - * @retval None - */ -static void I2C_DMAError(DMA_HandleTypeDef *hdma) { - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ - - /* Clear Complete callback */ - if (hi2c->hdmatx != NULL) { - hi2c->hdmatx->XferCpltCallback = NULL; - } - if (hi2c->hdmarx != NULL) { - hi2c->hdmarx->XferCpltCallback = NULL; - } - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - hi2c->XferCount = 0U; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ErrorCallback(hi2c); -#else - HAL_I2C_ErrorCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ -} - -/** - * @brief DMA I2C communication abort callback - * (To be called at end of DMA Abort procedure). - * @param hdma DMA handle. - * @retval None - */ -static void I2C_DMAAbort(DMA_HandleTypeDef *hdma) { - __IO uint32_t count = 0U; - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; /* Derogation MISRAC2012-Rule-11.5 */ - - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - HAL_I2C_StateTypeDef CurrentState = hi2c->State; - - /* During abort treatment, check that there is no pending STOP request */ - /* Wait until STOP flag is reset */ - count = I2C_TIMEOUT_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count == 0U) { - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - break; - } - count--; - } while (READ_BIT(hi2c->Instance->CR1, I2C_CR1_STOP) == I2C_CR1_STOP); - - /* Clear Complete callback */ - if (hi2c->hdmatx != NULL) { - hi2c->hdmatx->XferCpltCallback = NULL; - } - if (hi2c->hdmarx != NULL) { - hi2c->hdmarx->XferCpltCallback = NULL; - } - - /* Disable Acknowledge */ - CLEAR_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - hi2c->XferCount = 0U; - - /* Reset XferAbortCallback */ - if (hi2c->hdmatx != NULL) { - hi2c->hdmatx->XferAbortCallback = NULL; - } - if (hi2c->hdmarx != NULL) { - hi2c->hdmarx->XferAbortCallback = NULL; - } - - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - /* Check if come from abort from user */ - if (hi2c->State == HAL_I2C_STATE_ABORT) { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->AbortCpltCallback(hi2c); -#else - HAL_I2C_AbortCpltCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } else { - if (((uint32_t)CurrentState & (uint32_t)HAL_I2C_STATE_LISTEN) == (uint32_t)HAL_I2C_STATE_LISTEN) { - /* Renable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* keep HAL_I2C_STATE_LISTEN */ - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_LISTEN; - } else { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - } - - /* Call the corresponding callback to inform upper layer of End of Transfer */ -#if (USE_HAL_I2C_REGISTER_CALLBACKS == 1) - hi2c->ErrorCallback(hi2c); -#else - HAL_I2C_ErrorCallback(hi2c); -#endif /* USE_HAL_I2C_REGISTER_CALLBACKS */ - } -} - -/** - * @brief This function handles I2C Communication Timeout. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param Flag specifies the I2C flag to check. - * @param Status The new Flag status (SET or RESET). - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart) { - /* Wait until flag is set */ - while (__HAL_I2C_GET_FLAG(hi2c, Flag) == Status) { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for Master addressing phase. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param Flag specifies the I2C flag to check. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, uint32_t Timeout, uint32_t Tickstart) { - while (__HAL_I2C_GET_FLAG(hi2c, Flag) == RESET) { - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - - /* Clear AF Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of TXE flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnTXEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) { - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE) == RESET) { - /* Check if a NACK is detected */ - if (I2C_IsAcknowledgeFailed(hi2c) != HAL_OK) { - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of BTF flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnBTFFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) { - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == RESET) { - /* Check if a NACK is detected */ - if (I2C_IsAcknowledgeFailed(hi2c) != HAL_OK) { - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) { - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of STOP flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) { - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) { - /* Check if a NACK is detected */ - if (I2C_IsAcknowledgeFailed(hi2c) != HAL_OK) { - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of STOP request through Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnSTOPRequestThroughIT(I2C_HandleTypeDef *hi2c) { - __IO uint32_t count = 0U; - - /* Wait until STOP flag is reset */ - count = I2C_TIMEOUT_STOP_FLAG * (SystemCoreClock / 25U / 1000U); - do { - count--; - if (count == 0U) { - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - return HAL_ERROR; - } - } while (READ_BIT(hi2c->Instance->CR1, I2C_CR1_STOP) == I2C_CR1_STOP); - - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of RXNE flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) { - - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET) { - /* Check if a STOPF is detected */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) { - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - } - return HAL_OK; -} - -/** - * @brief This function handles Acknowledge failed detection during an I2C Communication. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_IsAcknowledgeFailed(I2C_HandleTypeDef *hi2c) { - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) { - /* Clear NACKF Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - return HAL_OK; -} - -/** - * @brief Convert I2Cx OTHER_xxx XferOptions to functionnal XferOptions. - * @param hi2c I2C handle. - * @retval None - */ -static void I2C_ConvertOtherXferOptions(I2C_HandleTypeDef *hi2c) { - /* if user set XferOptions to I2C_OTHER_FRAME */ - /* it request implicitly to generate a restart condition */ - /* set XferOptions to I2C_FIRST_FRAME */ - if (hi2c->XferOptions == I2C_OTHER_FRAME) { - hi2c->XferOptions = I2C_FIRST_FRAME; - } - /* else if user set XferOptions to I2C_OTHER_AND_LAST_FRAME */ - /* it request implicitly to generate a restart condition */ - /* then generate a stop condition at the end of transfer */ - /* set XferOptions to I2C_FIRST_AND_LAST_FRAME */ - else if (hi2c->XferOptions == I2C_OTHER_AND_LAST_FRAME) { - hi2c->XferOptions = I2C_FIRST_AND_LAST_FRAME; - } else { - /* Nothing to do */ - } -} - -/** - * @} - */ - -#endif /* HAL_I2C_MODULE_ENABLED */ -/** - * @} - */ - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c index dfea429d1..f1a5d2c3b 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c @@ -387,8 +387,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue)); /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */ - if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) - || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { + if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) || + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { /* When HSI is used as system clock it will not disabled */ if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) { return HAL_ERROR; @@ -535,8 +535,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { if ((RCC_OscInitStruct->PLL2.PLL2State) != RCC_PLL2_NONE) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { if ((RCC_OscInitStruct->PLL2.PLL2State) == RCC_PLL2_ON) { diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c index d82d6fea6..4051fb910 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c @@ -454,8 +454,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -474,8 +474,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -654,8 +654,8 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Check the parameters */ @@ -714,8 +714,8 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Disable the main PLL2. */ diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c index 1990dcc57..c7e3f8cda 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c @@ -2450,8 +2450,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t Outpu UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2541,8 +2541,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t Ou UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2874,8 +2874,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channe TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -2997,8 +2997,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Cha TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -3142,11 +3142,11 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Ch return HAL_ERROR; } } else { - if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { + if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; - } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { + } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((((pData1 == NULL) || (pData2 == NULL))) && (Length > 0U)) { return HAL_ERROR; } else { diff --git a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c index 9d6123bf2..87f66c3fd 100644 --- a/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c +++ b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c @@ -311,8 +311,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -382,8 +382,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } diff --git a/source/Core/BSP/MHP30/configuration.h b/source/Core/BSP/MHP30/configuration.h index 17b803f5f..8698a857a 100644 --- a/source/Core/BSP/MHP30/configuration.h +++ b/source/Core/BSP/MHP30/configuration.h @@ -1,6 +1,5 @@ #ifndef CONFIGURATION_H_ #define CONFIGURATION_H_ -#include "Settings.h" #include /** * Configuration.h @@ -57,6 +56,7 @@ * */ #define ORIENTATION_MODE 0 // 0: Right 1:Left 2:Automatic - Default right +#define MAX_ORIENTATION_MODE 1 // Unlikely to ever change #define REVERSE_BUTTON_TEMP_CHANGE 0 // 0:Default 1:Reverse - Reverse the plus and minus button assigment for temperature change /** @@ -103,8 +103,8 @@ #define DETAILED_IDLE 0 // 0: Disable 1: Enable - Default 0 // Due to large thermal mass of the PCB being heated we need to pull this back a bit -#define THERMAL_RUNAWAY_TIME_SEC 45 -#define THERMAL_RUNAWAY_TEMP_C 3 +#define THERMAL_RUNAWAY_TIME_SEC 20 +#define THERMAL_RUNAWAY_TEMP_C 2 #define CUT_OUT_SETTING 0 // default to no cut-off voltage #define RECOM_VOL_CELL 33 // Minimum voltage per cell (Recommended 3.3V (33)) @@ -146,16 +146,20 @@ #define MIN_BOOST_TEMP_F 300 // The min settable temp for boost mode °F #define NO_DISPLAY_ROTATE // Disable OLED rotation by accel #define SLEW_LIMIT 50 // Limit to 3.0 Watts per 64ms pid loop update rate slew rate - +#define TIPTYPE_MHP30 1 // It's own special tip #define ACCEL_SC7 #define ACCEL_MSA #define PROFILE_SUPPORT - -#define POW_PD 1 -#define POW_PD_EXT 0 +#define OLED_96x16 1 +#define POW_PD 1 +#define POW_PD_EXT 0 +#define USB_PD_EPR_WATTAGE 0 /*No EPR*/ #define TEMP_NTC -#define I2C_SOFT_BUS_2 +#define I2C_SOFT_BUS_2 1 +#define I2C_SOFT_BUS_1 1 +#define OLED_I2CBB1 1 +#define ACCEL_I2CBB1 1 #define BATTFILTERDEPTH 8 #define OLED_I2CBB2 #define ACCEL_EXITS_ON_MOVEMENT diff --git a/source/Core/BSP/MHP30/fusb_user.cpp b/source/Core/BSP/MHP30/fusb_user.cpp index 0ccb1810a..e0d8373ad 100644 --- a/source/Core/BSP/MHP30/fusb_user.cpp +++ b/source/Core/BSP/MHP30/fusb_user.cpp @@ -1,13 +1,13 @@ #include "configuration.h" #ifdef POW_PD #include "BSP.h" -#include "I2C_Wrapper.hpp" +#include "I2CBB1.hpp" #include "Pins.h" #include "Setup.h" #include "USBPD.h" -bool fusb_read_buf(const uint8_t deviceAddr, const uint8_t registerAdd, const uint8_t size, uint8_t *buf) { return FRToSI2C::Mem_Read(deviceAddr, registerAdd, buf, size); } +bool fusb_read_buf(const uint8_t deviceAddr, const uint8_t registerAdd, const uint8_t size, uint8_t *buf) { return I2CBB1::Mem_Read(deviceAddr, registerAdd, buf, size); } -bool fusb_write_buf(const uint8_t deviceAddr, const uint8_t registerAdd, const uint8_t size, uint8_t *buf) { return FRToSI2C::Mem_Write(deviceAddr, registerAdd, (uint8_t *)buf, size); } +bool fusb_write_buf(const uint8_t deviceAddr, const uint8_t registerAdd, const uint8_t size, uint8_t *buf) { return I2CBB1::Mem_Write(deviceAddr, registerAdd, (uint8_t *)buf, size); } void setupFUSBIRQ() { GPIO_InitTypeDef GPIO_InitStruct; diff --git a/source/Core/BSP/MHP30/preRTOS.cpp b/source/Core/BSP/MHP30/preRTOS.cpp index 7b4494834..550997ad1 100644 --- a/source/Core/BSP/MHP30/preRTOS.cpp +++ b/source/Core/BSP/MHP30/preRTOS.cpp @@ -6,6 +6,7 @@ */ #include "BSP.h" +#include "I2CBB1.hpp" #include "I2CBB2.hpp" #include "Pins.h" #include "Setup.h" @@ -18,6 +19,5 @@ void preRToSInit() { Setup_HAL(); // Setup all the HAL objects BSPInit(); I2CBB2::init(); - /* Init the IPC objects */ - FRToSI2C::FRToSInit(); + I2CBB1::init(); } diff --git a/source/Core/BSP/MHP30/stm32f1xx_hal_msp.c b/source/Core/BSP/MHP30/stm32f1xx_hal_msp.c index d3a849a43..9115a709d 100644 --- a/source/Core/BSP/MHP30/stm32f1xx_hal_msp.c +++ b/source/Core/BSP/MHP30/stm32f1xx_hal_msp.c @@ -1,6 +1,7 @@ #include "Pins.h" #include "Setup.h" #include "stm32f1xx_hal.h" +#include "string.h" /** * Initializes the Global MSP. */ @@ -29,6 +30,7 @@ void HAL_MspInit(void) { void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { GPIO_InitTypeDef GPIO_InitStruct; + memset(&GPIO_InitStruct, 0, sizeof(GPIO_InitStruct)); if (hadc->Instance == ADC1) { __HAL_RCC_ADC1_CLK_ENABLE(); @@ -51,6 +53,7 @@ void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { HAL_NVIC_EnableIRQ(ADC1_2_IRQn); } else { __HAL_RCC_ADC2_CLK_ENABLE(); + GPIO_InitStruct.Pull = GPIO_NOPULL; /**ADC2 GPIO Configuration PB0 ------> ADC2_IN8 @@ -59,9 +62,11 @@ void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { GPIO_InitStruct.Pin = TIP_TEMP_Pin; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; HAL_GPIO_Init(TIP_TEMP_GPIO_Port, &GPIO_InitStruct); + GPIO_InitStruct.Pin = TMP36_INPUT_Pin; - GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; HAL_GPIO_Init(TMP36_INPUT_GPIO_Port, &GPIO_InitStruct); + GPIO_InitStruct.Pin = VIN_Pin; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; HAL_GPIO_Init(VIN_GPIO_Port, &GPIO_InitStruct); @@ -75,55 +80,6 @@ void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { } } -void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) { - - GPIO_InitTypeDef GPIO_InitStruct; - /**I2C1 GPIO Configuration - PB6 ------> I2C1_SCL - PB7 ------> I2C1_SDA - */ - GPIO_InitStruct.Pin = SCL_Pin | SDA_Pin; - GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; - GPIO_InitStruct.Pull = GPIO_PULLUP; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; - HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); - - /* Peripheral clock enable */ - __HAL_RCC_I2C1_CLK_ENABLE(); - /* I2C1 DMA Init */ - /* I2C1_RX Init */ - hdma_i2c1_rx.Instance = DMA1_Channel7; - hdma_i2c1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; - hdma_i2c1_rx.Init.PeriphInc = DMA_PINC_DISABLE; - hdma_i2c1_rx.Init.MemInc = DMA_MINC_ENABLE; - hdma_i2c1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; - hdma_i2c1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; - hdma_i2c1_rx.Init.Mode = DMA_NORMAL; - hdma_i2c1_rx.Init.Priority = DMA_PRIORITY_LOW; - HAL_DMA_Init(&hdma_i2c1_rx); - - __HAL_LINKDMA(hi2c, hdmarx, hdma_i2c1_rx); - - /* I2C1_TX Init */ - hdma_i2c1_tx.Instance = DMA1_Channel6; - hdma_i2c1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; - hdma_i2c1_tx.Init.PeriphInc = DMA_PINC_DISABLE; - hdma_i2c1_tx.Init.MemInc = DMA_MINC_ENABLE; - hdma_i2c1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; - hdma_i2c1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; - hdma_i2c1_tx.Init.Mode = DMA_NORMAL; - hdma_i2c1_tx.Init.Priority = DMA_PRIORITY_MEDIUM; - HAL_DMA_Init(&hdma_i2c1_tx); - - __HAL_LINKDMA(hi2c, hdmatx, hdma_i2c1_tx); - - /* I2C1 interrupt Init */ - HAL_NVIC_SetPriority(I2C1_EV_IRQn, 15, 0); - HAL_NVIC_EnableIRQ(I2C1_EV_IRQn); - HAL_NVIC_SetPriority(I2C1_ER_IRQn, 15, 0); - HAL_NVIC_EnableIRQ(I2C1_ER_IRQn); -} - void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim_base) { if (htim_base->Instance == TIM3) { diff --git a/source/Core/BSP/MHP30/stm32f1xx_it.c b/source/Core/BSP/MHP30/stm32f1xx_it.c index 087bf0373..4421d274b 100644 --- a/source/Core/BSP/MHP30/stm32f1xx_it.c +++ b/source/Core/BSP/MHP30/stm32f1xx_it.c @@ -44,10 +44,5 @@ void ADC1_2_IRQHandler(void) { HAL_ADC_IRQHandler(&hadc1); } // used for hal ticks void TIM4_IRQHandler(void) { HAL_TIM_IRQHandler(&htim4); } -void I2C1_EV_IRQHandler(void) { HAL_I2C_EV_IRQHandler(&hi2c1); } -void I2C1_ER_IRQHandler(void) { HAL_I2C_ER_IRQHandler(&hi2c1); } -void DMA1_Channel6_IRQHandler(void) { HAL_DMA_IRQHandler(&hdma_i2c1_tx); } - -void DMA1_Channel7_IRQHandler(void) { HAL_DMA_IRQHandler(&hdma_i2c1_rx); } void EXTI9_5_IRQHandler(void) { HAL_GPIO_EXTI_IRQHandler(INT_PD_Pin); } diff --git a/source/Core/BSP/MHP30/system_stm32f1xx.c b/source/Core/BSP/MHP30/system_stm32f1xx.c index e950ea24e..e9b08e106 100644 --- a/source/Core/BSP/MHP30/system_stm32f1xx.c +++ b/source/Core/BSP/MHP30/system_stm32f1xx.c @@ -3,8 +3,8 @@ #include "stm32f1xx.h" #if !defined(HSI_VALUE) -#define HSI_VALUE \ - 8000000U /*!< Default value of the Internal oscillator in Hz. \ +#define HSI_VALUE \ + 8000000U /*!< Default value of the Internal oscillator in Hz. \ This value can be provided and adapted by the user application. */ #endif /* HSI_VALUE */ @@ -83,7 +83,7 @@ void SystemInit(void) { #ifdef VECT_TAB_SRAM SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */ #else - SCB->VTOR = FLASH_BASE | 0x8000; /* Vector Table Relocation in Internal FLASH. */ + SCB->VTOR = FLASH_BASE | 0x8000; /* Vector Table Relocation in Internal FLASH. */ #endif } diff --git a/source/Core/BSP/Miniware/BSP.cpp b/source/Core/BSP/Miniware/BSP.cpp index e930f6824..efb52edc5 100644 --- a/source/Core/BSP/Miniware/BSP.cpp +++ b/source/Core/BSP/Miniware/BSP.cpp @@ -4,6 +4,7 @@ #include "BootLogo.h" #include "I2C_Wrapper.hpp" #include "Pins.h" +#include "Settings.h" #include "Setup.h" #include "TipThermoModel.h" #include "USBPD.h" @@ -207,8 +208,9 @@ void unstick_I2C() { HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET); timeout_cnt++; - if (timeout_cnt > timeout) + if (timeout_cnt > timeout) { return; + } } // 12. Configure the SCL and SDA I/Os as Alternate function Open-Drain. @@ -307,6 +309,8 @@ void FinishMeasureTipResistance() { return; } else if (reading < 200) { tipShorted = true; + } else if (reading < 520) { + newRes = 40; } else if (reading < 800) { newRes = 62; } else { @@ -359,14 +363,7 @@ uint8_t preStartChecks() { } #endif -#ifdef POW_PD - // If we are in the middle of negotiating PD, wait until timeout - // Before turning on the heater - if (!USBPowerDelivery::negotiationComplete()) { - return 0; - } -#endif return 1; } uint64_t getDeviceID() { @@ -386,9 +383,18 @@ uint8_t getTipResistanceX10() { #ifdef TIP_RESISTANCE_SENSE_Pin // Return tip resistance in x10 ohms // We can measure this using the op-amp - return lastTipResistance; + uint8_t user_selected_tip = getUserSelectedTipResistance(); + if (user_selected_tip == 0) { + return lastTipResistance; // Auto mode + } + return user_selected_tip; + #else - return TIP_RESISTANCE; + uint8_t user_selected_tip = getUserSelectedTipResistance(); + if (user_selected_tip == 0) { + return TIP_RESISTANCE; // Auto mode + } + return user_selected_tip; #endif } #ifdef TIP_RESISTANCE_SENSE_Pin diff --git a/source/Core/BSP/Miniware/FreeRTOSConfig.h b/source/Core/BSP/Miniware/FreeRTOSConfig.h index ef0451ef4..a9b8bb91e 100644 --- a/source/Core/BSP/Miniware/FreeRTOSConfig.h +++ b/source/Core/BSP/Miniware/FreeRTOSConfig.h @@ -101,16 +101,16 @@ extern uint32_t SystemCoreClock; #define configUSE_TICK_HOOK 0 #define configCPU_CLOCK_HZ (SystemCoreClock) #define configTICK_RATE_HZ (1000) -#define configMAX_PRIORITIES (6) +#define configMAX_PRIORITIES (7) #define configMINIMAL_STACK_SIZE ((uint16_t)256) #define configTOTAL_HEAP_SIZE ((size_t)1024 * 14) /*Currently use about 9000*/ #define configMAX_TASK_NAME_LEN (32) -#define configUSE_16_BIT_TICKS 0 #define configUSE_MUTEXES 1 #define configQUEUE_REGISTRY_SIZE 8 #define configUSE_TIMERS 0 #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #define configCHECK_FOR_STACK_OVERFLOW 2 /*Bump this to 2 during development and bug hunting*/ +#define configTICK_TYPE_WIDTH_IN_BITS TICK_TYPE_WIDTH_32_BITS /* Co-routine definitions. */ #define configUSE_CO_ROUTINES 0 @@ -156,11 +156,11 @@ extern uint32_t SystemCoreClock; /* Normal assert() semantics without relying on the provision of an assert.h header file. */ /* USER CODE BEGIN 1 */ -#define configASSERT(x) \ - if ((x) == 0) { \ - taskDISABLE_INTERRUPTS(); \ - for (;;) \ - ; \ +#define configASSERT(x) \ + if ((x) == 0) { \ + taskDISABLE_INTERRUPTS(); \ + for (;;) \ + ; \ } /* USER CODE END 1 */ diff --git a/source/Core/BSP/Miniware/I2C_Wrapper.cpp b/source/Core/BSP/Miniware/I2C_Wrapper.cpp deleted file mode 100644 index 47150ab5b..000000000 --- a/source/Core/BSP/Miniware/I2C_Wrapper.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * FRToSI2C.cpp - * - * Created on: 14Apr.,2018 - * Author: Ralim - */ -#include "BSP.h" -#include "Setup.h" -#include -SemaphoreHandle_t FRToSI2C::I2CSemaphore = nullptr; -StaticSemaphore_t FRToSI2C::xSemaphoreBuffer; - -void FRToSI2C::CpltCallback() { - hi2c1.State = HAL_I2C_STATE_READY; // Force state reset (even if tx error) - if (I2CSemaphore) { - xSemaphoreGiveFromISR(I2CSemaphore, NULL); - } -} - -bool FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) { - - if (!lock()) - return false; - if (HAL_I2C_Mem_Read(&hi2c1, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 500) != HAL_OK) { - - I2C_Unstick(); - unlock(); - return false; - } - - unlock(); - return true; -} -bool FRToSI2C::I2C_RegisterWrite(uint8_t address, uint8_t reg, uint8_t data) { return Mem_Write(address, reg, &data, 1); } - -uint8_t FRToSI2C::I2C_RegisterRead(uint8_t add, uint8_t reg) { - uint8_t tx_data[1]; - Mem_Read(add, reg, tx_data, 1); - return tx_data[0]; -} -bool FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) { - - if (!lock()) - return false; - if (HAL_I2C_Mem_Write(&hi2c1, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 500) != HAL_OK) { - - I2C_Unstick(); - unlock(); - return false; - } - - unlock(); - return true; -} - -bool FRToSI2C::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) - return false; - if (HAL_I2C_Master_Transmit_IT(&hi2c1, DevAddress, pData, Size) != HAL_OK) { - I2C_Unstick(); - unlock(); - return false; - } - return true; -} - -bool FRToSI2C::probe(uint16_t DevAddress) { - if (!lock()) - return false; - uint8_t buffer[1]; - bool worked = HAL_I2C_Mem_Read(&hi2c1, DevAddress, 0x0F, I2C_MEMADD_SIZE_8BIT, buffer, 1, 1000) == HAL_OK; - unlock(); - return worked; -} - -void FRToSI2C::I2C_Unstick() { unstick_I2C(); } - -void FRToSI2C::unlock() { xSemaphoreGive(I2CSemaphore); } - -bool FRToSI2C::lock() { return xSemaphoreTake(I2CSemaphore, (TickType_t)50) == pdTRUE; } - -bool FRToSI2C::writeRegistersBulk(const uint8_t address, const I2C_REG *registers, const uint8_t registersLength) { - for (int index = 0; index < registersLength; index++) { - if (!I2C_RegisterWrite(address, registers[index].reg, registers[index].val)) { - return false; - } - if (registers[index].pause_ms) - delay_ms(registers[index].pause_ms); - } - return true; -} diff --git a/source/Core/BSP/Miniware/IRQ.cpp b/source/Core/BSP/Miniware/IRQ.cpp index 7fa800e5d..d7e86c00e 100644 --- a/source/Core/BSP/Miniware/IRQ.cpp +++ b/source/Core/BSP/Miniware/IRQ.cpp @@ -23,12 +23,6 @@ void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc) { } } } -void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } extern osThreadId POWTaskHandle; diff --git a/source/Core/BSP/Miniware/IRQ.h b/source/Core/BSP/Miniware/IRQ.h index 27a3b13db..b3024636d 100644 --- a/source/Core/BSP/Miniware/IRQ.h +++ b/source/Core/BSP/Miniware/IRQ.h @@ -18,12 +18,6 @@ extern "C" { #endif void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc); -void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_GPIO_EXTI_Callback(uint16_t); #ifdef __cplusplus diff --git a/source/Core/BSP/Miniware/Setup.cpp b/source/Core/BSP/Miniware/Setup.cpp index cd3f81c30..3f0702a43 100644 --- a/source/Core/BSP/Miniware/Setup.cpp +++ b/source/Core/BSP/Miniware/Setup.cpp @@ -7,16 +7,13 @@ #include "Setup.h" #include "BSP.h" #include "Pins.h" +#include "configuration.h" #include "history.hpp" #include ADC_HandleTypeDef hadc1; ADC_HandleTypeDef hadc2; DMA_HandleTypeDef hdma_adc1; -I2C_HandleTypeDef hi2c1; -DMA_HandleTypeDef hdma_i2c1_rx; -DMA_HandleTypeDef hdma_i2c1_tx; - IWDG_HandleTypeDef hiwdg; TIM_HandleTypeDef htimADC; TIM_HandleTypeDef htimTip; @@ -27,7 +24,6 @@ uint16_t ADCReadings[ADC_SAMPLES]; // Used to store the adc readings for the han // Functions static void SystemClock_Config(void); static void MX_ADC1_Init(void); -static void MX_I2C1_Init(void); static void MX_IWDG_Init(void); static void MX_TIP_CONTROL_TIMER_Init(void); static void MX_ADC_CONTROL_TIMER_Init(void); @@ -46,7 +42,7 @@ void Setup_HAL() { MX_GPIO_Init(); MX_DMA_Init(); #ifndef I2C_SOFT_BUS_1 - MX_I2C1_Init(); +#error "Only Bit-Bang now" #endif MX_ADC1_Init(); MX_ADC2_Init(); @@ -277,20 +273,6 @@ static void MX_ADC2_Init(void) { ; } } -/* I2C1 init function */ -static void MX_I2C1_Init(void) { - hi2c1.Instance = I2C1; - hi2c1.Init.ClockSpeed = 75000; - // OLED doesnt handle >100k when its asleep (off). - hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2; - hi2c1.Init.OwnAddress1 = 0; - hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; - hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; - hi2c1.Init.OwnAddress2 = 0; - hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; - hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; - HAL_I2C_Init(&hi2c1); -} /* IWDG init function */ static void MX_IWDG_Init(void) { @@ -335,7 +317,7 @@ static void MX_TIP_CONTROL_TIMER_Init(void) { #ifdef TIP_HAS_DIRECT_PWM sConfigOC.Pulse = 0; // PWM is direct to tip #else - sConfigOC.Pulse = 127; // 50% duty cycle, that is AC coupled through the cap to provide an on signal (This does not do tip at 50% duty cycle) + sConfigOC.Pulse = 127; // 50% duty cycle, that is AC coupled through the cap to provide an on signal (This does not do tip at 50% duty cycle) #endif sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; sConfigOC.OCFastMode = TIM_OCFAST_ENABLE; @@ -354,7 +336,7 @@ static void MX_TIP_CONTROL_TIMER_Init(void) { // Remap TIM3_CH1 to be on PB4 __HAL_AFIO_REMAP_TIM3_PARTIAL(); #else - // No re-map required + // No re-map required #endif HAL_TIM_PWM_Start(&htimTip, PWM_Out_CHANNEL); } @@ -498,8 +480,8 @@ static void MX_GPIO_Init(void) { HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); #endif #else - /* TS80 */ - /* Leave USB lines open circuit*/ + /* TS80 */ + /* Leave USB lines open circuit*/ #endif diff --git a/source/Core/BSP/Miniware/Setup.h b/source/Core/BSP/Miniware/Setup.h index 94864f8f4..1841ff9d2 100644 --- a/source/Core/BSP/Miniware/Setup.h +++ b/source/Core/BSP/Miniware/Setup.h @@ -18,10 +18,6 @@ extern ADC_HandleTypeDef hadc1; extern ADC_HandleTypeDef hadc2; extern DMA_HandleTypeDef hdma_adc1; -extern DMA_HandleTypeDef hdma_i2c1_rx; -extern DMA_HandleTypeDef hdma_i2c1_tx; -extern I2C_HandleTypeDef hi2c1; - extern IWDG_HandleTypeDef hiwdg; extern TIM_HandleTypeDef htimADC; diff --git a/source/Core/BSP/Miniware/Startup/startup_stm32f103t8ux.S b/source/Core/BSP/Miniware/Startup/startup_stm32f103t8ux.S new file mode 100644 index 000000000..f8d1c8ed7 --- /dev/null +++ b/source/Core/BSP/Miniware/Startup/startup_stm32f103t8ux.S @@ -0,0 +1,344 @@ +/** + ****************************************************************************** + * @file startup_stm32.s + * @author Ac6 + * @version V1.0.0 + * @date 12-June-2014 + ****************************************************************************** + */ + + .syntax unified + .cpu cortex-m3 + .thumb + +.global g_pfnVectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _sidata +/* start address for the .data section. defined in linker script */ +.word _sdata +/* end address for the .data section. defined in linker script */ +.word _edata +/* start address for the .bss section. defined in linker script */ +.word _sbss +/* end address for the .bss section. defined in linker script */ +.word _ebss + +.equ BootRAM, 0xF1E0F85F +/** + * @brief This is the code that gets called when the processor first + * starts execution following a reset event. Only the absolutely + * necessary set is performed, after which the application + * supplied main() routine is called. + * @param None + * @retval : None +*/ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +Reset_Handler: + +/* Copy the data segment initializers from flash to SRAM */ + movs r1, #0 + b LoopCopyDataInit + +CopyDataInit: + ldr r3, =_sidata + ldr r3, [r3, r1] + str r3, [r0, r1] + adds r1, r1, #4 + +LoopCopyDataInit: + ldr r0, =_sdata + ldr r3, =_edata + adds r2, r0, r1 + cmp r2, r3 + bcc CopyDataInit + ldr r2, =_sbss + b LoopFillZerobss +/* Zero fill the bss segment. */ +FillZerobss: + movs r3, #0 + str r3, [r2] + adds r2, r2, #4 + +LoopFillZerobss: + ldr r3, = _ebss + cmp r2, r3 + bcc FillZerobss + +/* Call the clock system intitialization function.*/ + bl SystemInit +/* Call static constructors */ + bl __libc_init_array +/* Call the application's entry point.*/ + bl main + +LoopForever: + b LoopForever + +.size Reset_Handler, .-Reset_Handler + +/** + * @brief This is the code that gets called when the processor receives an + * unexpected interrupt. This simply enters an infinite loop, preserving + * the system state for examination by a debugger. + * + * @param None + * @retval : None +*/ + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +/****************************************************************************** +* +* The minimal vector table for a Cortex-M. Note that the proper constructs +* must be placed on this to ensure that it ends up at physical address +* 0x0000.0000. +* +******************************************************************************/ + .section .isr_vector,"a",%progbits + .type g_pfnVectors, %object + .size g_pfnVectors, .-g_pfnVectors + +g_pfnVectors: + .word _estack + .word Reset_Handler + .word NMI_Handler + .word HardFault_Handler + .word MemManage_Handler + .word BusFault_Handler + .word UsageFault_Handler + .word 0 + .word 0 + .word 0 + .word 0 + .word SVC_Handler + .word DebugMon_Handler + .word 0 + .word PendSV_Handler + .word SysTick_Handler + .word WWDG_IRQHandler + .word PVD_IRQHandler + .word TAMPER_IRQHandler + .word RTC_IRQHandler + .word FLASH_IRQHandler + .word RCC_IRQHandler + .word EXTI0_IRQHandler + .word EXTI1_IRQHandler + .word EXTI2_IRQHandler + .word EXTI3_IRQHandler + .word EXTI4_IRQHandler + .word DMA1_Channel1_IRQHandler + .word DMA1_Channel2_IRQHandler + .word DMA1_Channel3_IRQHandler + .word DMA1_Channel4_IRQHandler + .word DMA1_Channel5_IRQHandler + .word DMA1_Channel6_IRQHandler + .word DMA1_Channel7_IRQHandler + .word ADC1_2_IRQHandler + .word USB_HP_CAN1_TX_IRQHandler + .word USB_LP_CAN1_RX0_IRQHandler + .word CAN1_RX1_IRQHandler + .word CAN1_SCE_IRQHandler + .word EXTI9_5_IRQHandler + .word TIM1_BRK_IRQHandler + .word TIM1_UP_IRQHandler + .word TIM1_TRG_COM_IRQHandler + .word TIM1_CC_IRQHandler + .word TIM2_IRQHandler + .word TIM3_IRQHandler + .word TIM4_IRQHandler + .word I2C1_EV_IRQHandler + .word I2C1_ER_IRQHandler + .word I2C2_EV_IRQHandler + .word I2C2_ER_IRQHandler + .word SPI1_IRQHandler + .word SPI2_IRQHandler + .word USART1_IRQHandler + .word USART2_IRQHandler + .word USART3_IRQHandler + .word EXTI15_10_IRQHandler + .word RTC_Alarm_IRQHandler + .word USBWakeUp_IRQHandler + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word BootRAM /* @0x108. This is for boot in RAM mode for + STM32F10x Medium Density devices. */ + +/******************************************************************************* +* +* Provide weak aliases for each Exception handler to the Default_Handler. +* As they are weak aliases, any function with the same name will override +* this definition. +* +*******************************************************************************/ + + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDG_IRQHandler + .thumb_set WWDG_IRQHandler,Default_Handler + + .weak PVD_IRQHandler + .thumb_set PVD_IRQHandler,Default_Handler + + .weak TAMPER_IRQHandler + .thumb_set TAMPER_IRQHandler,Default_Handler + + .weak RTC_IRQHandler + .thumb_set RTC_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCC_IRQHandler + .thumb_set RCC_IRQHandler,Default_Handler + + .weak EXTI0_IRQHandler + .thumb_set EXTI0_IRQHandler,Default_Handler + + .weak EXTI1_IRQHandler + .thumb_set EXTI1_IRQHandler,Default_Handler + + .weak EXTI2_IRQHandler + .thumb_set EXTI2_IRQHandler,Default_Handler + + .weak EXTI3_IRQHandler + .thumb_set EXTI3_IRQHandler,Default_Handler + + .weak EXTI4_IRQHandler + .thumb_set EXTI4_IRQHandler,Default_Handler + + .weak DMA1_Channel1_IRQHandler + .thumb_set DMA1_Channel1_IRQHandler,Default_Handler + + .weak DMA1_Channel2_IRQHandler + .thumb_set DMA1_Channel2_IRQHandler,Default_Handler + + .weak DMA1_Channel3_IRQHandler + .thumb_set DMA1_Channel3_IRQHandler,Default_Handler + + .weak DMA1_Channel4_IRQHandler + .thumb_set DMA1_Channel4_IRQHandler,Default_Handler + + .weak DMA1_Channel5_IRQHandler + .thumb_set DMA1_Channel5_IRQHandler,Default_Handler + + .weak DMA1_Channel6_IRQHandler + .thumb_set DMA1_Channel6_IRQHandler,Default_Handler + + .weak DMA1_Channel7_IRQHandler + .thumb_set DMA1_Channel7_IRQHandler,Default_Handler + + .weak ADC1_2_IRQHandler + .thumb_set ADC1_2_IRQHandler,Default_Handler + + .weak USB_HP_CAN1_TX_IRQHandler + .thumb_set USB_HP_CAN1_TX_IRQHandler,Default_Handler + + .weak USB_LP_CAN1_RX0_IRQHandler + .thumb_set USB_LP_CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EXTI9_5_IRQHandler + .thumb_set EXTI9_5_IRQHandler,Default_Handler + + .weak TIM1_BRK_IRQHandler + .thumb_set TIM1_BRK_IRQHandler,Default_Handler + + .weak TIM1_UP_IRQHandler + .thumb_set TIM1_UP_IRQHandler,Default_Handler + + .weak TIM1_TRG_COM_IRQHandler + .thumb_set TIM1_TRG_COM_IRQHandler,Default_Handler + + .weak TIM1_CC_IRQHandler + .thumb_set TIM1_CC_IRQHandler,Default_Handler + + .weak TIM2_IRQHandler + .thumb_set TIM2_IRQHandler,Default_Handler + + .weak TIM3_IRQHandler + .thumb_set TIM3_IRQHandler,Default_Handler + + .weak TIM4_IRQHandler + .thumb_set TIM4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EXTI15_10_IRQHandler + .thumb_set EXTI15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak USBWakeUp_IRQHandler + .thumb_set USBWakeUp_IRQHandler,Default_Handler + + +/************************ (C) COPYRIGHT Ac6 *****END OF FILE****/ diff --git a/source/Core/BSP/Miniware/ThermoModel.cpp b/source/Core/BSP/Miniware/ThermoModel.cpp index da9dac4c3..ddfd720ae 100644 --- a/source/Core/BSP/Miniware/ThermoModel.cpp +++ b/source/Core/BSP/Miniware/ThermoModel.cpp @@ -5,7 +5,7 @@ * Author: Ralim */ #include "TipThermoModel.h" -#include "Utils.h" +#include "Utils.hpp" #include "configuration.h" #ifdef TEMP_uV_LOOKUP_HAKKO diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h index 817f86e98..a9c8a2276 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h @@ -1,639 +1,5 @@ -/** - ****************************************************************************** - * @file stm32f1xx_hal_i2c.h - * @author MCD Application Team - * @brief Header file of I2C HAL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -/* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F1xx_HAL_I2C_H #define __STM32F1xx_HAL_I2C_H -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_hal_def.h" - -/** @addtogroup STM32F1xx_HAL_Driver - * @{ - */ - -/** @addtogroup I2C - * @{ - */ - -/* Exported types ------------------------------------------------------------*/ -/** @defgroup I2C_Exported_Types I2C Exported Types - * @{ - */ - -/** - * @brief I2C Configuration Structure definition - */ -typedef struct { - uint32_t ClockSpeed; /*!< Specifies the clock frequency. - This parameter must be set to a value lower than 400kHz */ - - uint32_t DutyCycle; /*!< Specifies the I2C fast mode duty cycle. - This parameter can be a value of @ref I2C_duty_cycle_in_fast_mode */ - - uint32_t OwnAddress1; /*!< Specifies the first device own address. - This parameter can be a 7-bit or 10-bit address. */ - - uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. - This parameter can be a value of @ref I2C_addressing_mode */ - - uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. - This parameter can be a value of @ref I2C_dual_addressing_mode */ - - uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected - This parameter can be a 7-bit address. */ - - uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. - This parameter can be a value of @ref I2C_general_call_addressing_mode */ - - uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. - This parameter can be a value of @ref I2C_nostretch_mode */ - -} I2C_InitTypeDef; - -/** - * @brief HAL State structure definition - * @note HAL I2C State value coding follow below described bitmap : - * b7-b6 Error information - * 00 : No Error - * 01 : Abort (Abort user request on going) - * 10 : Timeout - * 11 : Error - * b5 IP initilisation status - * 0 : Reset (IP not initialized) - * 1 : Init done (IP initialized and ready to use. HAL I2C Init function called) - * b4 (not used) - * x : Should be set to 0 - * b3 - * 0 : Ready or Busy (No Listen mode ongoing) - * 1 : Listen (IP in Address Listen Mode) - * b2 Intrinsic process state - * 0 : Ready - * 1 : Busy (IP busy with some configuration or internal operations) - * b1 Rx state - * 0 : Ready (no Rx operation ongoing) - * 1 : Busy (Rx operation ongoing) - * b0 Tx state - * 0 : Ready (no Tx operation ongoing) - * 1 : Busy (Tx operation ongoing) - */ -typedef enum { - HAL_I2C_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized */ - HAL_I2C_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use */ - HAL_I2C_STATE_BUSY = 0x24U, /*!< An internal process is ongoing */ - HAL_I2C_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing */ - HAL_I2C_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing */ - HAL_I2C_STATE_LISTEN = 0x28U, /*!< Address Listen Mode is ongoing */ - HAL_I2C_STATE_BUSY_TX_LISTEN = 0x29U, /*!< Address Listen Mode and Data Transmission - process is ongoing */ - HAL_I2C_STATE_BUSY_RX_LISTEN = 0x2AU, /*!< Address Listen Mode and Data Reception - process is ongoing */ - HAL_I2C_STATE_ABORT = 0x60U, /*!< Abort user request ongoing */ - HAL_I2C_STATE_TIMEOUT = 0xA0U, /*!< Timeout state */ - HAL_I2C_STATE_ERROR = 0xE0U /*!< Error */ - -} HAL_I2C_StateTypeDef; - -/** - * @brief HAL Mode structure definition - * @note HAL I2C Mode value coding follow below described bitmap : - * b7 (not used) - * x : Should be set to 0 - * b6 - * 0 : None - * 1 : Memory (HAL I2C communication is in Memory Mode) - * b5 - * 0 : None - * 1 : Slave (HAL I2C communication is in Slave Mode) - * b4 - * 0 : None - * 1 : Master (HAL I2C communication is in Master Mode) - * b3-b2-b1-b0 (not used) - * xxxx : Should be set to 0000 - */ -typedef enum { - HAL_I2C_MODE_NONE = 0x00U, /*!< No I2C communication on going */ - HAL_I2C_MODE_MASTER = 0x10U, /*!< I2C communication is in Master Mode */ - HAL_I2C_MODE_SLAVE = 0x20U, /*!< I2C communication is in Slave Mode */ - HAL_I2C_MODE_MEM = 0x40U /*!< I2C communication is in Memory Mode */ - -} HAL_I2C_ModeTypeDef; - -/** - * @brief I2C handle Structure definition - */ -typedef struct { - I2C_TypeDef *Instance; /*!< I2C registers base address */ - - I2C_InitTypeDef Init; /*!< I2C communication parameters */ - - uint8_t *pBuffPtr; /*!< Pointer to I2C transfer buffer */ - - uint16_t XferSize; /*!< I2C transfer size */ - - __IO uint16_t XferCount; /*!< I2C transfer counter */ - - __IO uint32_t XferOptions; /*!< I2C transfer options */ - - __IO uint32_t PreviousState; /*!< I2C communication Previous state and mode - context for internal usage */ - - DMA_HandleTypeDef *hdmatx; /*!< I2C Tx DMA handle parameters */ - - DMA_HandleTypeDef *hdmarx; /*!< I2C Rx DMA handle parameters */ - - HAL_LockTypeDef Lock; /*!< I2C locking object */ - - __IO HAL_I2C_StateTypeDef State; /*!< I2C communication state */ - - __IO HAL_I2C_ModeTypeDef Mode; /*!< I2C communication mode */ - - __IO uint32_t ErrorCode; /*!< I2C Error code */ - - __IO uint32_t Devaddress; /*!< I2C Target device address */ - - __IO uint32_t Memaddress; /*!< I2C Target memory address */ - - __IO uint32_t MemaddSize; /*!< I2C Target memory address size */ - - __IO uint32_t EventCount; /*!< I2C Event counter */ - -} I2C_HandleTypeDef; - -/** - * @} - */ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup I2C_Exported_Constants I2C Exported Constants - * @{ - */ - -/** @defgroup I2C_Error_Code I2C Error Code - * @brief I2C Error Code - * @{ - */ -#define HAL_I2C_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_I2C_ERROR_BERR 0x00000001U /*!< BERR error */ -#define HAL_I2C_ERROR_ARLO 0x00000002U /*!< ARLO error */ -#define HAL_I2C_ERROR_AF 0x00000004U /*!< AF error */ -#define HAL_I2C_ERROR_OVR 0x00000008U /*!< OVR error */ -#define HAL_I2C_ERROR_DMA 0x00000010U /*!< DMA transfer error */ -#define HAL_I2C_ERROR_TIMEOUT 0x00000020U /*!< Timeout Error */ -/** - * @} - */ - -/** @defgroup I2C_duty_cycle_in_fast_mode I2C duty cycle in fast mode - * @{ - */ -#define I2C_DUTYCYCLE_2 0x00000000U -#define I2C_DUTYCYCLE_16_9 I2C_CCR_DUTY -/** - * @} - */ - -/** @defgroup I2C_addressing_mode I2C addressing mode - * @{ - */ -#define I2C_ADDRESSINGMODE_7BIT 0x00004000U -// #define I2C_ADDRESSINGMODE_10BIT (I2C_OAR1_ADDMODE | 0x00004000U) -/** - * @} - */ - -/** @defgroup I2C_dual_addressing_mode I2C dual addressing mode - * @{ - */ -#define I2C_DUALADDRESS_DISABLE 0x00000000U -#define I2C_DUALADDRESS_ENABLE I2C_OAR2_ENDUAL -/** - * @} - */ - -/** @defgroup I2C_general_call_addressing_mode I2C general call addressing mode - * @{ - */ -#define I2C_GENERALCALL_DISABLE 0x00000000U -#define I2C_GENERALCALL_ENABLE I2C_CR1_ENGC -/** - * @} - */ - -/** @defgroup I2C_nostretch_mode I2C nostretch mode - * @{ - */ -#define I2C_NOSTRETCH_DISABLE 0x00000000U -#define I2C_NOSTRETCH_ENABLE I2C_CR1_NOSTRETCH -/** - * @} - */ - -/** @defgroup I2C_Memory_Address_Size I2C Memory Address Size - * @{ - */ -#define I2C_MEMADD_SIZE_8BIT 0x00000001U -#define I2C_MEMADD_SIZE_16BIT 0x00000010U -/** - * @} - */ - -/** @defgroup I2C_XferDirection_definition I2C XferDirection definition - * @{ - */ -#define I2C_DIRECTION_RECEIVE 0x00000000U -#define I2C_DIRECTION_TRANSMIT 0x00000001U -/** - * @} - */ - -/** @defgroup I2C_XferOptions_definition I2C XferOptions definition - * @{ - */ -#define I2C_FIRST_FRAME 0x00000001U -#define I2C_NEXT_FRAME 0x00000002U -#define I2C_FIRST_AND_LAST_FRAME 0x00000004U -#define I2C_LAST_FRAME 0x00000008U -/** - * @} - */ - -/** @defgroup I2C_Interrupt_configuration_definition I2C Interrupt configuration definition - * @{ - */ -#define I2C_IT_BUF I2C_CR2_ITBUFEN -#define I2C_IT_EVT I2C_CR2_ITEVTEN -#define I2C_IT_ERR I2C_CR2_ITERREN -/** - * @} - */ - -/** @defgroup I2C_Flag_definition I2C Flag definition - * @{ - */ -#define I2C_FLAG_SMBALERT 0x00018000U -#define I2C_FLAG_TIMEOUT 0x00014000U -#define I2C_FLAG_PECERR 0x00011000U -#define I2C_FLAG_OVR 0x00010800U -#define I2C_FLAG_AF 0x00010400U -#define I2C_FLAG_ARLO 0x00010200U -#define I2C_FLAG_BERR 0x00010100U -#define I2C_FLAG_TXE 0x00010080U -#define I2C_FLAG_RXNE 0x00010040U -#define I2C_FLAG_STOPF 0x00010010U -// #define I2C_FLAG_ADD10 0x00010008U -#define I2C_FLAG_BTF 0x00010004U -#define I2C_FLAG_ADDR 0x00010002U -#define I2C_FLAG_SB 0x00010001U -#define I2C_FLAG_DUALF 0x00100080U -#define I2C_FLAG_SMBHOST 0x00100040U -#define I2C_FLAG_SMBDEFAULT 0x00100020U -#define I2C_FLAG_GENCALL 0x00100010U -#define I2C_FLAG_TRA 0x00100004U -#define I2C_FLAG_BUSY 0x00100002U -#define I2C_FLAG_MSL 0x00100001U -/** - * @} - */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup I2C_Exported_Macros I2C Exported Macros - * @{ - */ - -/** @brief Reset I2C handle state - * @param __HANDLE__: specifies the I2C Handle. - * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. - * @retval None - */ -#define __HAL_I2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2C_STATE_RESET) - -/** @brief Enable or disable the specified I2C interrupts. - * @param __HANDLE__: specifies the I2C Handle. - * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. - * @param __INTERRUPT__: specifies the interrupt source to enable or disable. - * This parameter can be one of the following values: - * @arg I2C_IT_BUF: Buffer interrupt enable - * @arg I2C_IT_EVT: Event interrupt enable - * @arg I2C_IT_ERR: Error interrupt enable - * @retval None - */ -#define __HAL_I2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) -#define __HAL_I2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (~(__INTERRUPT__))) - -/** @brief Checks if the specified I2C interrupt source is enabled or disabled. - * @param __HANDLE__: specifies the I2C Handle. - * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. - * @param __INTERRUPT__: specifies the I2C interrupt source to check. - * This parameter can be one of the following values: - * @arg I2C_IT_BUF: Buffer interrupt enable - * @arg I2C_IT_EVT: Event interrupt enable - * @arg I2C_IT_ERR: Error interrupt enable - * @retval The new state of __INTERRUPT__ (TRUE or FALSE). - */ -#define __HAL_I2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) - -/** @brief Checks whether the specified I2C flag is set or not. - * @param __HANDLE__: specifies the I2C Handle. - * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. - * @param __FLAG__: specifies the flag to check. - * This parameter can be one of the following values: - * @arg I2C_FLAG_SMBALERT: SMBus Alert flag - * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow error flag - * @arg I2C_FLAG_PECERR: PEC error in reception flag - * @arg I2C_FLAG_OVR: Overrun/Underrun flag - * @arg I2C_FLAG_AF: Acknowledge failure flag - * @arg I2C_FLAG_ARLO: Arbitration lost flag - * @arg I2C_FLAG_BERR: Bus error flag - * @arg I2C_FLAG_TXE: Data register empty flag - * @arg I2C_FLAG_RXNE: Data register not empty flag - * @arg I2C_FLAG_STOPF: Stop detection flag - * @arg I2C_FLAG_ADD10: 10-bit header sent flag - * @arg I2C_FLAG_BTF: Byte transfer finished flag - * @arg I2C_FLAG_ADDR: Address sent flag - * Address matched flag - * @arg I2C_FLAG_SB: Start bit flag - * @arg I2C_FLAG_DUALF: Dual flag - * @arg I2C_FLAG_SMBHOST: SMBus host header - * @arg I2C_FLAG_SMBDEFAULT: SMBus default header - * @arg I2C_FLAG_GENCALL: General call header flag - * @arg I2C_FLAG_TRA: Transmitter/Receiver flag - * @arg I2C_FLAG_BUSY: Bus busy flag - * @arg I2C_FLAG_MSL: Master/Slave flag - * @retval The new state of __FLAG__ (TRUE or FALSE). - */ -#define __HAL_I2C_GET_FLAG(__HANDLE__, __FLAG__) \ - ((((uint8_t)((__FLAG__) >> 16U)) == 0x01U) ? ((((__HANDLE__)->Instance->SR1) & ((__FLAG__)&I2C_FLAG_MASK)) == ((__FLAG__)&I2C_FLAG_MASK)) \ - : ((((__HANDLE__)->Instance->SR2) & ((__FLAG__)&I2C_FLAG_MASK)) == ((__FLAG__)&I2C_FLAG_MASK))) - -/** @brief Clears the I2C pending flags which are cleared by writing 0 in a specific bit. - * @param __HANDLE__: specifies the I2C Handle. - * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. - * @param __FLAG__: specifies the flag to clear. - * This parameter can be any combination of the following values: - * @arg I2C_FLAG_SMBALERT: SMBus Alert flag - * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow error flag - * @arg I2C_FLAG_PECERR: PEC error in reception flag - * @arg I2C_FLAG_OVR: Overrun/Underrun flag (Slave mode) - * @arg I2C_FLAG_AF: Acknowledge failure flag - * @arg I2C_FLAG_ARLO: Arbitration lost flag (Master mode) - * @arg I2C_FLAG_BERR: Bus error flag - * @retval None - */ -#define __HAL_I2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR1 = ~((__FLAG__)&I2C_FLAG_MASK)) - -/** @brief Clears the I2C ADDR pending flag. - * @param __HANDLE__: specifies the I2C Handle. - * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. - * @retval None - */ -#define __HAL_I2C_CLEAR_ADDRFLAG(__HANDLE__) \ - do { \ - __IO uint32_t tmpreg = 0x00U; \ - tmpreg = (__HANDLE__)->Instance->SR1; \ - tmpreg = (__HANDLE__)->Instance->SR2; \ - UNUSED(tmpreg); \ - } while (0U) - -/** @brief Clears the I2C STOPF pending flag. - * @param __HANDLE__: specifies the I2C Handle. - * This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral. - * @retval None - */ -#define __HAL_I2C_CLEAR_STOPFLAG(__HANDLE__) \ - do { \ - __IO uint32_t tmpreg = 0x00U; \ - tmpreg = (__HANDLE__)->Instance->SR1; \ - (__HANDLE__)->Instance->CR1 |= I2C_CR1_PE; \ - UNUSED(tmpreg); \ - } while (0U) - -/** @brief Enable the I2C peripheral. - * @param __HANDLE__: specifies the I2C Handle. - * This parameter can be I2Cx where x: 1 or 2 to select the I2C peripheral. - * @retval None - */ -#define __HAL_I2C_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= I2C_CR1_PE) - -/** @brief Disable the I2C peripheral. - * @param __HANDLE__: specifies the I2C Handle. - * This parameter can be I2Cx where x: 1 or 2 to select the I2C peripheral. - * @retval None - */ -#define __HAL_I2C_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~I2C_CR1_PE) - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup I2C_Exported_Functions - * @{ - */ - -/** @addtogroup I2C_Exported_Functions_Group1 - * @{ - */ -/* Initialization/de-initialization functions **********************************/ -HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c); -HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c); -/** - * @} - */ - -/** @addtogroup I2C_Exported_Functions_Group2 - * @{ - */ -/* I/O operation functions *****************************************************/ -/******* Blocking mode: Polling */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); -HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); - -/******* Non-Blocking mode: Interrupt */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); - -HAL_StatusTypeDef HAL_I2C_Master_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_Master_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions); -HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress); -HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c); -HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c); - -/******* Non-Blocking mode: DMA */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); -HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); - -/******* I2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ -void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c); -void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode); -void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c); -/** - * @} - */ - -/** @addtogroup I2C_Exported_Functions_Group3 - * @{ - */ -/* Peripheral State, Mode and Errors functions *********************************/ -HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c); -HAL_I2C_ModeTypeDef HAL_I2C_GetMode(I2C_HandleTypeDef *hi2c); -uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c); - -/** - * @} - */ - -/** - * @} - */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup I2C_Private_Constants I2C Private Constants - * @{ - */ -#define I2C_FLAG_MASK 0x0000FFFFU -#define I2C_MIN_PCLK_FREQ_STANDARD 2000000U /*!< 2 MHz */ -#define I2C_MIN_PCLK_FREQ_FAST 4000000U /*!< 4 MHz */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup I2C_Private_Macros I2C Private Macros - * @{ - */ - -#define I2C_MIN_PCLK_FREQ(__PCLK__, __SPEED__) (((__SPEED__) <= 100000U) ? ((__PCLK__) < I2C_MIN_PCLK_FREQ_STANDARD) : ((__PCLK__) < I2C_MIN_PCLK_FREQ_FAST)) -#define I2C_CCR_CALCULATION(__PCLK__, __SPEED__, __COEFF__) (((((__PCLK__)-1U) / ((__SPEED__) * (__COEFF__))) + 1U) & I2C_CCR_CCR) -#define I2C_FREQRANGE(__PCLK__) ((__PCLK__) / 1000000U) -#define I2C_RISE_TIME(__FREQRANGE__, __SPEED__) (((__SPEED__) <= 100000U) ? ((__FREQRANGE__) + 1U) : ((((__FREQRANGE__)*300U) / 1000U) + 1U)) -#define I2C_SPEED_STANDARD(__PCLK__, __SPEED__) ((I2C_CCR_CALCULATION((__PCLK__), (__SPEED__), 2U) < 4U) ? 4U : I2C_CCR_CALCULATION((__PCLK__), (__SPEED__), 2U)) -#define I2C_SPEED_FAST(__PCLK__, __SPEED__, __DUTYCYCLE__) \ - (((__DUTYCYCLE__) == I2C_DUTYCYCLE_2) ? I2C_CCR_CALCULATION((__PCLK__), (__SPEED__), 3U) : (I2C_CCR_CALCULATION((__PCLK__), (__SPEED__), 25U) | I2C_DUTYCYCLE_16_9)) -#define I2C_SPEED(__PCLK__, __SPEED__, __DUTYCYCLE__) \ - (((__SPEED__) <= 100000U) ? (I2C_SPEED_STANDARD((__PCLK__), (__SPEED__))) \ - : ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__)) & I2C_CCR_CCR) == 0U) ? 1U \ - : ((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__))) | I2C_CCR_FS)) - -#define I2C_7BIT_ADD_WRITE(__ADDRESS__) ((uint8_t)((__ADDRESS__) & (~I2C_OAR1_ADD0))) -#define I2C_7BIT_ADD_READ(__ADDRESS__) ((uint8_t)((__ADDRESS__) | I2C_OAR1_ADD0)) - -#define I2C_10BIT_ADDRESS(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FFU)))) -#define I2C_10BIT_HEADER_WRITE(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300U))) >> 7U) | (uint16_t)(0x00F0U)))) -#define I2C_10BIT_HEADER_READ(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300U))) >> 7U) | (uint16_t)(0x00F1U)))) - -#define I2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0xFF00U))) >> 8U))) -#define I2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FFU)))) - -/** @defgroup I2C_IS_RTC_Definitions I2C Private macros to check input parameters - * @{ - */ -#define IS_I2C_DUTY_CYCLE(CYCLE) (((CYCLE) == I2C_DUTYCYCLE_2) || ((CYCLE) == I2C_DUTYCYCLE_16_9)) -#define IS_I2C_ADDRESSING_MODE(ADDRESS) (((ADDRESS) == I2C_ADDRESSINGMODE_7BIT) || ((ADDRESS) == I2C_ADDRESSINGMODE_10BIT)) -#define IS_I2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == I2C_DUALADDRESS_DISABLE) || ((ADDRESS) == I2C_DUALADDRESS_ENABLE)) -#define IS_I2C_GENERAL_CALL(CALL) (((CALL) == I2C_GENERALCALL_DISABLE) || ((CALL) == I2C_GENERALCALL_ENABLE)) -#define IS_I2C_NO_STRETCH(STRETCH) (((STRETCH) == I2C_NOSTRETCH_DISABLE) || ((STRETCH) == I2C_NOSTRETCH_ENABLE)) -#define IS_I2C_MEMADD_SIZE(SIZE) (((SIZE) == I2C_MEMADD_SIZE_8BIT) || ((SIZE) == I2C_MEMADD_SIZE_16BIT)) -#define IS_I2C_CLOCK_SPEED(SPEED) (((SPEED) > 0) && ((SPEED) <= 400000U)) -#define IS_I2C_OWN_ADDRESS1(ADDRESS1) (((ADDRESS1) & (uint32_t)(0xFFFFFC00U)) == 0U) -#define IS_I2C_OWN_ADDRESS2(ADDRESS2) (((ADDRESS2) & (uint32_t)(0xFFFFFF01U)) == 0U) -#define IS_I2C_TRANSFER_OPTIONS_REQUEST(REQUEST) (((REQUEST) == I2C_FIRST_FRAME) || ((REQUEST) == I2C_NEXT_FRAME) || ((REQUEST) == I2C_FIRST_AND_LAST_FRAME) || ((REQUEST) == I2C_LAST_FRAME)) -/** - * @} - */ - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/** @defgroup I2C_Private_Functions I2C Private Functions - * @{ - */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - #endif /* __STM32F1xx_HAL_I2C_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c index cb32ffdf1..8725243aa 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c @@ -155,8 +155,8 @@ HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT; /* 1KHz */ HAL_StatusTypeDef HAL_Init(void) { /* Configure Flash prefetch */ #if (PREFETCH_ENABLE != 0) -#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) \ - || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) +#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) || \ + defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) /* Prefetch buffer is not available on value line devices */ __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); @@ -352,7 +352,8 @@ __weak void HAL_Delay(uint32_t Delay) { wait += (uint32_t)(uwTickFreq); } - while ((HAL_GetTick() - tickstart) < wait) {} + while ((HAL_GetTick() - tickstart) < wait) { + } } /** diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c index f29ea6c51..19ac9e7db 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c @@ -555,12 +555,12 @@ HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_JEOC | ADC_FLAG_EOC | ADC_FLAG_JSTRT | ADC_FLAG_STRT)); /* Reset register CR1 */ - CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | ADC_CR1_AWDIE - | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); + CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | + ADC_CR1_AWDIE | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); /* Reset register CR2 */ - CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA - | ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); + CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA | + ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); /* Reset register SMPR1 */ CLEAR_BIT(hadc->Instance->SMPR1, (ADC_SMPR1_SMP17 | ADC_SMPR1_SMP16 | ADC_SMPR1_SMP15 | ADC_SMPR1_SMP14 | ADC_SMPR1_SMP13 | ADC_SMPR1_SMP12 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP10)); @@ -1194,7 +1194,6 @@ HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, ui /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; - /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ /* start (in case of SW start): */ @@ -1352,7 +1351,6 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { } } - /* Clear regular group conversion flag */ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_STRT | ADC_FLAG_EOC); } @@ -1393,12 +1391,8 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JSTRT | ADC_FLAG_JEOC)); } } - - } - - /** * @} */ @@ -1438,7 +1432,7 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { * @retval HAL status */ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConfTypeDef *sConfig) { - HAL_StatusTypeDef tmp_hal_status = HAL_OK; + HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -1472,8 +1466,6 @@ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConf MODIFY_REG(hadc->Instance->SMPR2, ADC_SMPR2(ADC_SMPR2_SMP0, sConfig->Channel), ADC_SMPR2(sConfig->SamplingTime, sConfig->Channel)); } - - /* Process unlocked */ __HAL_UNLOCK(hadc); @@ -1503,8 +1495,8 @@ HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDG assert_param(IS_ADC_RANGE(AnalogWDGConfig->HighThreshold)); assert_param(IS_ADC_RANGE(AnalogWDGConfig->LowThreshold)); - if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) - || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { + if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || + (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel)); } @@ -1712,11 +1704,6 @@ void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma) { } } - - - - - /** * @} */ diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c index dc2e20e8a..03c947f34 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c @@ -661,7 +661,6 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef *hadc, uint32_t /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; - /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ /* start (in case of SW start): */ @@ -899,7 +898,7 @@ __weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc) { * @retval None */ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_InjectionConfTypeDef *sConfigInjected) { - HAL_StatusTypeDef tmp_hal_status = HAL_OK; + HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -964,8 +963,8 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I ADC_JSQR_JL | ADC_JSQR_RK_JL(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion), - ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) - | ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); + ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) | + ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); } else { /* Clear the old SQx bits for the selected rank */ MODIFY_REG(hadc->Instance->JSQR, @@ -1028,9 +1027,6 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I MODIFY_REG(hadc->Instance->SMPR2, ADC_SMPR2(ADC_SMPR2_SMP0, sConfigInjected->InjectedChannel), ADC_SMPR2(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel)); } - - - /* Configure the offset: offset enable/disable, InjectedChannel, offset value */ switch (sConfigInjected->InjectedRank) { case 1: @@ -1051,7 +1047,6 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I break; } - /* Process unlocked */ __HAL_UNLOCK(hadc); diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c index e1f9b4e4a..b973ec025 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c @@ -321,9 +321,9 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) { assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) - | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) - | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } else { MPU->RBAR = 0x00U; MPU->RASR = 0x00U; diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c index 5d46145df..d21cfac8d 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c @@ -198,7 +198,7 @@ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) { tmp = hdma->Instance->CCR; /* Clear PL, MSIZE, PSIZE, MINC, PINC, CIRC and DIR bits */ - tmp &= ((uint32_t) ~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | DMA_CCR_DIR)); + tmp &= ((uint32_t)~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | DMA_CCR_DIR)); /* Prepare the DMA Channel configuration */ tmp |= hdma->Init.Direction | hdma->Init.PeriphInc | hdma->Init.MemInc | hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment | hdma->Init.Mode | hdma->Init.Priority; diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c deleted file mode 100644 index 5dd8b7c77..000000000 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c +++ /dev/null @@ -1,4574 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_hal_i2c.c - * @author MCD Application Team - * @brief I2C HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Inter Integrated Circuit (I2C) peripheral: - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral State, Mode and Error functions - * - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - The I2C HAL driver can be used as follows: - - (#) Declare a I2C_HandleTypeDef handle structure, for example: - I2C_HandleTypeDef hi2c; - - (#)Initialize the I2C low level resources by implementing the HAL_I2C_MspInit() API: - (##) Enable the I2Cx interface clock - (##) I2C pins configuration - (+++) Enable the clock for the I2C GPIOs - (+++) Configure I2C pins as alternate function open-drain - (##) NVIC configuration if you need to use interrupt process - (+++) Configure the I2Cx interrupt priority - (+++) Enable the NVIC I2C IRQ Channel - (##) DMA Configuration if you need to use DMA process - (+++) Declare a DMA_HandleTypeDef handle structure for the transmit or receive channel - (+++) Enable the DMAx interface clock using - (+++) Configure the DMA handle parameters - (+++) Configure the DMA Tx or Rx channel - (+++) Associate the initialized DMA handle to the hi2c DMA Tx or Rx handle - (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on - the DMA Tx or Rx channel - - (#) Configure the Communication Speed, Duty cycle, Addressing mode, Own Address1, - Dual Addressing mode, Own Address2, General call and Nostretch mode in the hi2c Init structure. - - (#) Initialize the I2C registers by calling the HAL_I2C_Init(), configures also the low level Hardware - (GPIO, CLOCK, NVIC...etc) by calling the customized HAL_I2C_MspInit(&hi2c) API. - - (#) To check if target device is ready for communication, use the function HAL_I2C_IsDeviceReady() - - (#) For I2C IO and IO MEM operations, three operation modes are available within this driver : - - *** Polling mode IO operation *** - ================================= - [..] - (+) Transmit in master mode an amount of data in blocking mode using HAL_I2C_Master_Transmit() - (+) Receive in master mode an amount of data in blocking mode using HAL_I2C_Master_Receive() - (+) Transmit in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Transmit() - (+) Receive in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Receive() - - *** Polling mode IO MEM operation *** - ===================================== - [..] - (+) Write an amount of data in blocking mode to a specific memory address using HAL_I2C_Mem_Write() - (+) Read an amount of data in blocking mode from a specific memory address using HAL_I2C_Mem_Read() - - - *** Interrupt mode IO operation *** - =================================== - [..] - (+) Transmit in master mode an amount of data in non blocking mode using HAL_I2C_Master_Transmit_IT() - (+) At transmission end of transfer HAL_I2C_MasterTxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_MasterTxCpltCallback - (+) Receive in master mode an amount of data in non blocking mode using HAL_I2C_Master_Receive_IT() - (+) At reception end of transfer HAL_I2C_MasterRxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback - (+) Transmit in slave mode an amount of data in non blocking mode using HAL_I2C_Slave_Transmit_IT() - (+) At transmission end of transfer HAL_I2C_SlaveTxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback - (+) Receive in slave mode an amount of data in non blocking mode using HAL_I2C_Slave_Receive_IT() - (+) At reception end of transfer HAL_I2C_SlaveRxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback - (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can - add his own code by customization of function pointer HAL_I2C_ErrorCallback - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() - (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and user can - add his own code by customization of function pointer HAL_I2C_AbortCpltCallback() - - *** Interrupt mode IO sequential operation *** - ============================================== - [..] - (@) These interfaces allow to manage a sequential transfer with a repeated start condition - when a direction change during transfer - [..] - (+) A specific option field manage the different steps of a sequential transfer - (+) Option field values are defined through @ref I2C_XFEROPTIONS and are listed below: - (++) I2C_FIRST_AND_LAST_FRAME: No sequential usage, functionnal is same as associated interfaces in no sequential mode - (++) I2C_FIRST_FRAME: Sequential usage, this option allow to manage a sequence with start condition, address - and data to transfer without a final stop condition - (++) I2C_NEXT_FRAME: Sequential usage, this option allow to manage a sequence with a restart condition, address - and with new data to transfer if the direction change or manage only the new data to transfer - if no direction change and without a final stop condition in both cases - (++) I2C_LAST_FRAME: Sequential usage, this option allow to manage a sequance with a restart condition, address - and with new data to transfer if the direction change or manage only the new data to transfer - if no direction change and with a final stop condition in both cases - - (+) Differents sequential I2C interfaces are listed below: - (++) Sequential transmit in master I2C mode an amount of data in non-blocking mode using HAL_I2C_Master_Sequential_Transmit_IT() - (+++) At transmission end of current frame transfer, HAL_I2C_MasterTxCpltCallback() is executed and user can - add his own code by customization of function pointer HAL_I2C_MasterTxCpltCallback() - (++) Sequential receive in master I2C mode an amount of data in non-blocking mode using HAL_I2C_Master_Sequential_Receive_IT() - (+++) At reception end of current frame transfer, HAL_I2C_MasterRxCpltCallback() is executed and user can - add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback() - (++) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() - (+++) End of abort process, HAL_I2C_AbortCpltCallback() is executed and user can - add his own code by customization of function pointer HAL_I2C_AbortCpltCallback() - (++) Enable/disable the Address listen mode in slave I2C mode using HAL_I2C_EnableListen_IT() HAL_I2C_DisableListen_IT() - (+++) When address slave I2C match, HAL_I2C_AddrCallback() is executed and user can - add his own code to check the Address Match Code and the transmission direction request by master (Write/Read). - (+++) At Listen mode end HAL_I2C_ListenCpltCallback() is executed and user can - add his own code by customization of function pointer HAL_I2C_ListenCpltCallback() - (++) Sequential transmit in slave I2C mode an amount of data in non-blocking mode using HAL_I2C_Slave_Sequential_Transmit_IT() - (+++) At transmission end of current frame transfer, HAL_I2C_SlaveTxCpltCallback() is executed and user can - add his own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback() - (++) Sequential receive in slave I2C mode an amount of data in non-blocking mode using HAL_I2C_Slave_Sequential_Receive_IT() - (+++) At reception end of current frame transfer, HAL_I2C_SlaveRxCpltCallback() is executed and user can - add his own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback() - (++) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can - add his own code by customization of function pointer HAL_I2C_ErrorCallback() - - *** Interrupt mode IO MEM operation *** - ======================================= - [..] - (+) Write an amount of data in no-blocking mode with Interrupt to a specific memory address using - HAL_I2C_Mem_Write_IT() - (+) At MEM end of write transfer HAL_I2C_MemTxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_MemTxCpltCallback - (+) Read an amount of data in no-blocking mode with Interrupt from a specific memory address using - HAL_I2C_Mem_Read_IT() - (+) At MEM end of read transfer HAL_I2C_MemRxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_MemRxCpltCallback - (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can - add his own code by customization of function pointer HAL_I2C_ErrorCallback - - *** DMA mode IO operation *** - ============================== - [..] - (+) Transmit in master mode an amount of data in non blocking mode (DMA) using - HAL_I2C_Master_Transmit_DMA() - (+) At transmission end of transfer HAL_I2C_MasterTxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_MasterTxCpltCallback - (+) Receive in master mode an amount of data in non blocking mode (DMA) using - HAL_I2C_Master_Receive_DMA() - (+) At reception end of transfer HAL_I2C_MasterRxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback - (+) Transmit in slave mode an amount of data in non blocking mode (DMA) using - HAL_I2C_Slave_Transmit_DMA() - (+) At transmission end of transfer HAL_I2C_SlaveTxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback - (+) Receive in slave mode an amount of data in non blocking mode (DMA) using - HAL_I2C_Slave_Receive_DMA() - (+) At reception end of transfer HAL_I2C_SlaveRxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback - (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can - add his own code by customization of function pointer HAL_I2C_ErrorCallback - (+) Abort a master I2C process communication with Interrupt using HAL_I2C_Master_Abort_IT() - (+) End of abort process, HAL_I2C_AbortCpltCallback() is executed and user can - add his own code by customization of function pointer HAL_I2C_AbortCpltCallback() - - *** DMA mode IO MEM operation *** - ================================= - [..] - (+) Write an amount of data in no-blocking mode with DMA to a specific memory address using - HAL_I2C_Mem_Write_DMA() - (+) At MEM end of write transfer HAL_I2C_MemTxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_MemTxCpltCallback - (+) Read an amount of data in no-blocking mode with DMA from a specific memory address using - HAL_I2C_Mem_Read_DMA() - (+) At MEM end of read transfer HAL_I2C_MemRxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2C_MemRxCpltCallback - (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can - add his own code by customization of function pointer HAL_I2C_ErrorCallback - - - *** I2C HAL driver macros list *** - ================================== - [..] - Below the list of most used macros in I2C HAL driver. - - (+) __HAL_I2C_ENABLE: Enable the I2C peripheral - (+) __HAL_I2C_DISABLE: Disable the I2C peripheral - (+) __HAL_I2C_GET_FLAG : Checks whether the specified I2C flag is set or not - (+) __HAL_I2C_CLEAR_FLAG : Clear the specified I2C pending flag - (+) __HAL_I2C_ENABLE_IT: Enable the specified I2C interrupt - (+) __HAL_I2C_DISABLE_IT: Disable the specified I2C interrupt - - [..] - (@) You can refer to the I2C HAL driver header file for more useful macros - - *** I2C Workarounds linked to Silicon Limitation *** - ==================================================== - [..] - Below the list of all silicon limitations implemented for HAL on STM32F1xx product. - (@) See ErrataSheet to know full silicon limitation list of your product. - - (#) Workarounds Implemented inside I2C HAL Driver - (##) Wrong data read into data register (Polling and Interrupt mode) - (##) Start cannot be generated after a misplaced Stop - (##) Some software events must be managed before the current byte is being transferred: - Workaround: Use DMA in general, except when the Master is receiving a single byte. - For Interupt mode, I2C should have the highest priority in the application. - (##) Mismatch on the "Setup time for a repeated Start condition" timing parameter: - Workaround: Reduce the frequency down to 88 kHz or use the I2C Fast-mode if - supported by the slave. - (##) Data valid time (tVD;DAT) violated without the OVR flag being set: - Workaround: If the slave device allows it, use the clock stretching mechanism - by programming NoStretchMode = I2C_NOSTRETCH_DISABLE in HAL_I2C_Init. - - @endverbatim - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_hal.h" - -/** @addtogroup STM32F1xx_HAL_Driver - * @{ - */ - -/** @defgroup I2C I2C - * @brief I2C HAL module driver - * @{ - */ - -#ifdef HAL_I2C_MODULE_ENABLED - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @addtogroup I2C_Private_Define - * @{ - */ -#define I2C_TIMEOUT_FLAG 35U /*!< Timeout 35 ms */ -#define I2C_TIMEOUT_BUSY_FLAG 25U /*!< Timeout 25 ms */ -#define I2C_NO_OPTION_FRAME 0xFFFF0000U /*!< XferOptions default value */ - -/* Private define for @ref PreviousState usage */ -#define I2C_STATE_MSK ((uint32_t)((HAL_I2C_STATE_BUSY_TX | HAL_I2C_STATE_BUSY_RX) & (~(uint32_t)HAL_I2C_STATE_READY))) /*!< Mask State define, keep only RX and TX bits */ -#define I2C_STATE_NONE ((uint32_t)(HAL_I2C_MODE_NONE)) /*!< Default Value */ -#define I2C_STATE_MASTER_BUSY_TX ((uint32_t)((HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | HAL_I2C_MODE_MASTER)) /*!< Master Busy TX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_MASTER_BUSY_RX ((uint32_t)((HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | HAL_I2C_MODE_MASTER)) /*!< Master Busy RX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_SLAVE_BUSY_TX ((uint32_t)((HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | HAL_I2C_MODE_SLAVE)) /*!< Slave Busy TX, combinaison of State LSB and Mode enum */ -#define I2C_STATE_SLAVE_BUSY_RX ((uint32_t)((HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | HAL_I2C_MODE_SLAVE)) /*!< Slave Busy RX, combinaison of State LSB and Mode enum */ - -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/** @addtogroup I2C_Private_Functions - * @{ - */ -/* Private functions to handle DMA transfer */ -static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma); -static void I2C_DMAError(DMA_HandleTypeDef *hdma); -static void I2C_DMAAbort(DMA_HandleTypeDef *hdma); - -static void I2C_ITError(I2C_HandleTypeDef *hi2c); - -static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnTXEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnBTFFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart); -static HAL_StatusTypeDef I2C_IsAcknowledgeFailed(I2C_HandleTypeDef *hi2c); - -/* Private functions for I2C transfer IRQ handler */ -static HAL_StatusTypeDef I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c); -static HAL_StatusTypeDef I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c); -static HAL_StatusTypeDef I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c); -static HAL_StatusTypeDef I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c); -static HAL_StatusTypeDef I2C_Master_SB(I2C_HandleTypeDef *hi2c); -static HAL_StatusTypeDef I2C_Master_ADDR(I2C_HandleTypeDef *hi2c); - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup I2C_Exported_Functions I2C Exported Functions - * @{ - */ - -/** @defgroup I2C_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions - * -@verbatim - =============================================================================== - ##### Initialization and de-initialization functions ##### - =============================================================================== - [..] This subsection provides a set of functions allowing to initialize and - de-initialize the I2Cx peripheral: - - (+) User must Implement HAL_I2C_MspInit() function in which he configures - all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC). - - (+) Call the function HAL_I2C_Init() to configure the selected device with - the selected configuration: - (++) Communication Speed - (++) Duty cycle - (++) Addressing mode - (++) Own Address 1 - (++) Dual Addressing mode - (++) Own Address 2 - (++) General call mode - (++) Nostretch mode - - (+) Call the function HAL_I2C_DeInit() to restore the default configuration - of the selected I2Cx peripheral. - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the I2C according to the specified parameters - * in the I2C_InitTypeDef and create the associated handle. - * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c) { - uint32_t freqrange = 0U; - uint32_t pclk1 = 0U; - - /* Check the I2C handle allocation */ - if (hi2c == NULL) { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); - assert_param(IS_I2C_CLOCK_SPEED(hi2c->Init.ClockSpeed)); - assert_param(IS_I2C_DUTY_CYCLE(hi2c->Init.DutyCycle)); - assert_param(IS_I2C_OWN_ADDRESS1(hi2c->Init.OwnAddress1)); - assert_param(IS_I2C_ADDRESSING_MODE(hi2c->Init.AddressingMode)); - assert_param(IS_I2C_DUAL_ADDRESS(hi2c->Init.DualAddressMode)); - assert_param(IS_I2C_OWN_ADDRESS2(hi2c->Init.OwnAddress2)); - assert_param(IS_I2C_GENERAL_CALL(hi2c->Init.GeneralCallMode)); - assert_param(IS_I2C_NO_STRETCH(hi2c->Init.NoStretchMode)); - - if (hi2c->State == HAL_I2C_STATE_RESET) { - /* Allocate lock resource and initialize it */ - hi2c->Lock = HAL_UNLOCKED; - /* Init the low level hardware : GPIO, CLOCK, NVIC */ - HAL_I2C_MspInit(hi2c); - } - - hi2c->State = HAL_I2C_STATE_BUSY; - - /* Disable the selected I2C peripheral */ - __HAL_I2C_DISABLE(hi2c); - - /* Get PCLK1 frequency */ - pclk1 = HAL_RCC_GetPCLK1Freq(); - - /* Check the minimum allowed PCLK1 frequency */ - if (I2C_MIN_PCLK_FREQ(pclk1, hi2c->Init.ClockSpeed) == 1U) { - return HAL_ERROR; - } - - /* Calculate frequency range */ - freqrange = I2C_FREQRANGE(pclk1); - - /*---------------------------- I2Cx CR2 Configuration ----------------------*/ - /* Configure I2Cx: Frequency range */ - hi2c->Instance->CR2 = freqrange; - - /*---------------------------- I2Cx TRISE Configuration --------------------*/ - /* Configure I2Cx: Rise Time */ - hi2c->Instance->TRISE = I2C_RISE_TIME(freqrange, hi2c->Init.ClockSpeed); - - /*---------------------------- I2Cx CCR Configuration ----------------------*/ - /* Configure I2Cx: Speed */ - hi2c->Instance->CCR = I2C_SPEED(pclk1, hi2c->Init.ClockSpeed, hi2c->Init.DutyCycle); - - /*---------------------------- I2Cx CR1 Configuration ----------------------*/ - /* Configure I2Cx: Generalcall and NoStretch mode */ - hi2c->Instance->CR1 = (hi2c->Init.GeneralCallMode | hi2c->Init.NoStretchMode); - - /*---------------------------- I2Cx OAR1 Configuration ---------------------*/ - /* Configure I2Cx: Own Address1 and addressing mode */ - hi2c->Instance->OAR1 = (hi2c->Init.AddressingMode | hi2c->Init.OwnAddress1); - - /*---------------------------- I2Cx OAR2 Configuration ---------------------*/ - /* Configure I2Cx: Dual mode and Own Address2 */ - hi2c->Instance->OAR2 = (hi2c->Init.DualAddressMode | hi2c->Init.OwnAddress2); - - /* Enable the selected I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->Mode = HAL_I2C_MODE_NONE; - - return HAL_OK; -} - -/** - * @brief DeInitializes the I2C peripheral. - * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c) { - /* Check the I2C handle allocation */ - if (hi2c == NULL) { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); - - hi2c->State = HAL_I2C_STATE_BUSY; - - /* Disable the I2C Peripheral Clock */ - __HAL_I2C_DISABLE(hi2c); - - /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ - HAL_I2C_MspDeInit(hi2c); - - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - hi2c->State = HAL_I2C_STATE_RESET; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Release Lock */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; -} - -/** - * @brief I2C MSP Init. - * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -__weak void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2C_MspInit could be implemented in the user file - */ -} - -/** - * @brief I2C MSP DeInit - * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval None - */ -__weak void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_I2C_MspDeInit could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup I2C_Exported_Functions_Group2 IO operation functions - * @brief Data transfers functions - * -@verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the I2C data - transfers. - - (#) There are two modes of transfer: - (++) Blocking mode : The communication is performed in the polling mode. - The status of all data processing is returned by the same function - after finishing transfer. - (++) No-Blocking mode : The communication is performed using Interrupts - or DMA. These functions return the status of the transfer startup. - The end of the data processing will be indicated through the - dedicated I2C IRQ when using Interrupt mode or the DMA IRQ when - using DMA mode. - - (#) Blocking mode functions are : - (++) HAL_I2C_Master_Transmit() - (++) HAL_I2C_Master_Receive() - (++) HAL_I2C_Slave_Transmit() - (++) HAL_I2C_Slave_Receive() - (++) HAL_I2C_Mem_Write() - (++) HAL_I2C_Mem_Read() - (++) HAL_I2C_IsDeviceReady() - - (#) No-Blocking mode functions with Interrupt are : - (++) HAL_I2C_Master_Transmit_IT() - (++) HAL_I2C_Master_Receive_IT() - (++) HAL_I2C_Slave_Transmit_IT() - (++) HAL_I2C_Slave_Receive_IT() - (++) HAL_I2C_Master_Sequential_Transmit_IT() - (++) HAL_I2C_Master_Sequential_Receive_IT() - (++) HAL_I2C_Slave_Sequential_Transmit_IT() - (++) HAL_I2C_Slave_Sequential_Receive_IT() - (++) HAL_I2C_Mem_Write_IT() - (++) HAL_I2C_Mem_Read_IT() - - (#) No-Blocking mode functions with DMA are : - (++) HAL_I2C_Master_Transmit_DMA() - (++) HAL_I2C_Master_Receive_DMA() - (++) HAL_I2C_Slave_Transmit_DMA() - (++) HAL_I2C_Slave_Receive_DMA() - (++) HAL_I2C_Mem_Write_DMA() - (++) HAL_I2C_Mem_Read_DMA() - - (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: - (++) HAL_I2C_MemTxCpltCallback() - (++) HAL_I2C_MemRxCpltCallback() - (++) HAL_I2C_MasterTxCpltCallback() - (++) HAL_I2C_MasterRxCpltCallback() - (++) HAL_I2C_SlaveTxCpltCallback() - (++) HAL_I2C_SlaveRxCpltCallback() - (++) HAL_I2C_ErrorCallback() - (++) HAL_I2C_AbortCpltCallback() - -@endverbatim - * @{ - */ - -/** - * @brief Transmits in master mode an amount of data in blocking mode. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint32_t tickstart = 0x00U; - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - - /* Send Slave Address */ - if (I2C_MasterRequestWrite(hi2c, DevAddress, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_ERROR; - } else { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_TIMEOUT; - } - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - while (hi2c->XferSize > 0U) { - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* Write data to DR */ - hi2c->Instance->DR = (*hi2c->pBuffPtr++); - hi2c->XferCount--; - hi2c->XferSize--; - - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) { - /* Write data to DR */ - hi2c->Instance->DR = (*hi2c->pBuffPtr++); - hi2c->XferCount--; - hi2c->XferSize--; - } - - /* Wait until BTF flag is set */ - if (I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - } - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receives in master mode an amount of data in blocking mode. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint32_t tickstart = 0x00U; - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - - /* Send Slave Address */ - if (I2C_MasterRequestRead(hi2c, DevAddress, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_ERROR; - } else { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_TIMEOUT; - } - } - - if (hi2c->XferSize == 0U) { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - } else if (hi2c->XferSize == 1U) { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - /* Re-enable IRQs */ - __enable_irq(); - } else if (hi2c->XferSize == 2U) { - /* Enable Pos */ - hi2c->Instance->CR1 |= I2C_CR1_POS; - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Re-enable IRQs */ - __enable_irq(); - } else { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } - - while (hi2c->XferSize > 0U) { - if (hi2c->XferSize <= 3U) { - /* One byte */ - if (hi2c->XferSize == 1U) { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT) { - return HAL_TIMEOUT; - } else { - return HAL_ERROR; - } - } - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - } - /* Two bytes */ - else if (hi2c->XferSize == 2U) { - /* Wait until BTF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - - /* Re-enable IRQs */ - __enable_irq(); - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - } - /* 3 Last bytes */ - else { - /* Wait until BTF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - - /* Wait until BTF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - - /* Re-enable IRQs */ - __enable_irq(); - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - } - } else { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT) { - return HAL_TIMEOUT; - } else { - return HAL_ERROR; - } - } - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) { - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - } - } - } - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Transmits in slave mode an amount of data in blocking mode. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint32_t tickstart = 0x00U; - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - - - while (hi2c->XferSize > 0U) { - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - /* Disable Address Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* Write data to DR */ - hi2c->Instance->DR = (*hi2c->pBuffPtr++); - hi2c->XferCount--; - hi2c->XferSize--; - - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) { - /* Write data to DR */ - hi2c->Instance->DR = (*hi2c->pBuffPtr++); - hi2c->XferCount--; - hi2c->XferSize--; - } - } - - /* Wait until AF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Clear AF flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Disable Address Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receive in slave mode an amount of data in blocking mode - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint32_t tickstart = 0x00U; - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - while (hi2c->XferSize > 0U) { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - /* Disable Address Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - if (hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT) { - return HAL_TIMEOUT; - } else { - return HAL_ERROR; - } - } - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) { - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - } - } - - /* Wait until STOP flag is set */ - if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - /* Disable Address Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* Clear STOP flag */ - __HAL_I2C_CLEAR_STOPFLAG(hi2c); - - /* Disable Address Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in master mode an amount of data in non-blocking mode with Interrupt - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - hi2c->Devaddress = DevAddress; - - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receive in master mode an amount of data in non-blocking mode with Interrupt - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - hi2c->Devaddress = DevAddress; - - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential transmit in master mode an amount of data in non-blocking mode with Interrupt - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - __IO uint32_t Prev_State = 0x00U; - __IO uint32_t count = 0x00U; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Check Busy Flag only if FIRST call of Master interface */ - if ((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = XferOptions; - hi2c->XferSize = hi2c->XferCount; - hi2c->Devaddress = DevAddress; - - Prev_State = hi2c->PreviousState; - - /* Generate Start */ - if ((Prev_State == I2C_STATE_MASTER_BUSY_RX) || (Prev_State == I2C_STATE_NONE)) { - /* Generate Start condition if first transfer */ - if ((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) { - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - } else { - /* Generate ReStart */ - hi2c->Instance->CR1 |= I2C_CR1_START; - } - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential receive in master mode an amount of data in non-blocking mode with Interrupt - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - __IO uint32_t count = 0U; - - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Check Busy Flag only if FIRST call of Master interface */ - if ((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = XferOptions; - hi2c->XferSize = hi2c->XferCount; - hi2c->Devaddress = DevAddress; - - if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) || (hi2c->PreviousState == I2C_STATE_NONE)) { - /* Generate Start condition if first transfer */ - if ((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME) || (XferOptions == I2C_NO_OPTION_FRAME)) { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - } else { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Generate ReStart */ - hi2c->Instance->CR1 |= I2C_CR1_START; - } - } - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in slave mode an amount of data in non-blocking mode with Interrupt - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receive in slave mode an amount of data in non-blocking mode with Interrupt - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferSize = Size; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - /* Enable Address Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential transmit in slave mode an amount of data in no-blocking mode with Interrupt - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_LISTEN) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX_LISTEN; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = XferOptions; - hi2c->XferSize = hi2c->XferCount; - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Sequential receive in slave mode an amount of data in non-blocking mode with Interrupt - * @note This interface allow to manage repeated start condition when a direction change during transfer - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) { - /* Check the parameters */ - assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions)); - - if (hi2c->State == HAL_I2C_STATE_LISTEN) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX_LISTEN; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = XferOptions; - hi2c->XferSize = hi2c->XferCount; - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Enable the Address listen mode with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c) { - if (hi2c->State == HAL_I2C_STATE_READY) { - hi2c->State = HAL_I2C_STATE_LISTEN; - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Enable Address Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Disable the Address listen mode with Interrupt. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) { - /* Declaration of tmp to prevent undefined behavior of volatile usage */ - uint32_t tmp; - - /* Disable Address listen mode only if a transfer is not ongoing */ - if (hi2c->State == HAL_I2C_STATE_LISTEN) { - tmp = (uint32_t)(hi2c->State) & I2C_STATE_MSK; - hi2c->PreviousState = tmp | (uint32_t)(hi2c->Mode); - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Disable Address Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Disable EVT and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Transmit in master mode an amount of data in non-blocking mode with DMA - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - hi2c->Devaddress = DevAddress; - - if (hi2c->XferSize > 0U) { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize); - - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Enable DMA Request */ - hi2c->Instance->CR2 |= I2C_CR2_DMAEN; - } else { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - } - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receive in master mode an amount of data in non-blocking mode with DMA - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MASTER; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - hi2c->Devaddress = DevAddress; - - if (hi2c->XferSize > 0U) { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); - - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Enable DMA Request */ - hi2c->Instance->CR2 |= I2C_CR2_DMAEN; - } else { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - } - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Abort a master I2C process communication with Interrupt. - * @note This abort can be called only if state is ready - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(DevAddress); - - /* Abort Master transfer during Receive or Transmit process */ - if (hi2c->Mode == HAL_I2C_MODE_MASTER) { - /* Process Locked */ - __HAL_LOCK(hi2c); - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_ABORT; - - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - hi2c->XferCount = 0U; - - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - I2C_ITError(hi2c); - - return HAL_OK; - } else { - /* Wrong usage of abort function */ - /* This function should be used only in case of abort monitored by master device */ - return HAL_ERROR; - } -} - -/** - * @brief Transmit in slave mode an amount of data in non-blocking mode with DMA - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize); - - /* Enable Address Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Enable DMA Request */ - hi2c->Instance->CR2 |= I2C_CR2_DMAEN; - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Receive in slave mode an amount of data in non-blocking mode with DMA - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - if (hi2c->State == HAL_I2C_STATE_READY) { - if ((pData == NULL) || (Size == 0U)) { - return HAL_ERROR; - } - - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_SLAVE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferHalfCpltCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); - - /* Enable Address Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Enable DMA Request */ - hi2c->Instance->CR2 |= I2C_CR2_DMAEN; - - return HAL_OK; - } else { - return HAL_BUSY; - } -} -/** - * @brief Write an amount of data in blocking mode to a specific memory address - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint32_t tickstart = 0x00U; - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_ERROR; - } else { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_TIMEOUT; - } - } - - while (hi2c->XferSize > 0U) { - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* Write data to DR */ - hi2c->Instance->DR = (*hi2c->pBuffPtr++); - hi2c->XferSize--; - hi2c->XferCount--; - - if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) { - /* Write data to DR */ - hi2c->Instance->DR = (*hi2c->pBuffPtr++); - hi2c->XferSize--; - hi2c->XferCount--; - } - } - - /* Wait until BTF flag is set */ - if (I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Read an amount of data in blocking mode from a specific memory address - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint32_t tickstart = 0x00U; - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_ERROR; - } else { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_TIMEOUT; - } - } - - if (hi2c->XferSize == 0U) { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - } else if (hi2c->XferSize == 1U) { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - /* Re-enable IRQs */ - __enable_irq(); - } else if (hi2c->XferSize == 2U) { - /* Enable Pos */ - hi2c->Instance->CR1 |= I2C_CR1_POS; - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Re-enable IRQs */ - __enable_irq(); - } else { - /* Enable Acknowledge */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK); - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } - - while (hi2c->XferSize > 0U) { - if (hi2c->XferSize <= 3U) { - /* One byte */ - if (hi2c->XferSize == 1U) { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT) { - return HAL_TIMEOUT; - } else { - return HAL_ERROR; - } - } - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - } - /* Two bytes */ - else if (hi2c->XferSize == 2U) { - /* Wait until BTF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - - /* Re-enable IRQs */ - __enable_irq(); - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - } - /* 3 Last bytes */ - else { - /* Wait until BTF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3 - software sequence must complete before the current byte end of transfer */ - __disable_irq(); - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - - /* Wait until BTF flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - - /* Re-enable IRQs */ - __enable_irq(); - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - } - } else { - /* Wait until RXNE flag is set */ - if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT) { - return HAL_TIMEOUT; - } else { - return HAL_ERROR; - } - } - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) { - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferSize--; - hi2c->XferCount--; - } - } - } - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Write an amount of data in non-blocking mode with Interrupt to a specific memory address - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferSize = Size; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->Devaddress = DevAddress; - hi2c->Memaddress = MemAddress; - hi2c->MemaddSize = MemAddSize; - hi2c->EventCount = 0U; - - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Read an amount of data in non-blocking mode with Interrupt from a specific memory address - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferSize = Size; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->Devaddress = DevAddress; - hi2c->Memaddress = MemAddress; - hi2c->MemaddSize = MemAddSize; - hi2c->EventCount = 0U; - - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - if (hi2c->XferSize > 0U) { - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - - /* Enable EVT, BUF and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - } - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Write an amount of data in non-blocking mode with DMA to a specific memory address - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be sent - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) { - __IO uint32_t count = 0U; - - uint32_t tickstart = 0x00U; - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferSize = Size; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - if (hi2c->XferSize > 0U) { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmatx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmatx->XferHalfCpltCallback = NULL; - hi2c->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize); - - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_ERROR; - } else { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_TIMEOUT; - } - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_ERR); - - /* Enable DMA Request */ - hi2c->Instance->CR2 |= I2C_CR2_DMAEN; - } - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Reads an amount of data in non-blocking mode with DMA from a specific memory address. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param pData Pointer to data buffer - * @param Size Amount of data to be read - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) { - uint32_t tickstart = 0x00U; - __IO uint32_t count = 0U; - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - /* Check the parameters */ - assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U); - do { - if (count-- == 0U) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET); - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY_RX; - hi2c->Mode = HAL_I2C_MODE_MEM; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Prepare transfer parameters */ - hi2c->pBuffPtr = pData; - hi2c->XferCount = Size; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->XferSize = hi2c->XferCount; - - if (hi2c->XferSize > 0U) { - /* Set the I2C DMA transfer complete callback */ - hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt; - - /* Set the DMA error callback */ - hi2c->hdmarx->XferErrorCallback = I2C_DMAError; - - /* Set the unused DMA callbacks to NULL */ - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA channel */ - HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); - - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_ERROR; - } else { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_TIMEOUT; - } - } - - if (Size == 1U) { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - } else { - /* Enable Last DMA bit */ - hi2c->Instance->CR2 |= I2C_CR2_LAST; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - /* Note : The I2C interrupts must be enabled after unlocking current process - to avoid the risk of I2C interrupt handle execution before current - process unlock */ - /* Enable ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_ERR); - - /* Enable DMA Request */ - hi2c->Instance->CR2 |= I2C_CR2_DMAEN; - } else { - /* Send Slave Address and Memory Address */ - if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_ERROR; - } else { - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - return HAL_TIMEOUT; - } - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - } - - return HAL_OK; - } else { - return HAL_BUSY; - } -} - -/** - * @brief Checks if target device is ready for communication. - * @note This function is used with Memory devices - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param Trials Number of trials - * @param Timeout Timeout duration - * @retval HAL status - */ -HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout) { - uint32_t tickstart = 0U, tmp1 = 0U, tmp2 = 0U, tmp3 = 0U, I2C_Trials = 1U; - - /* Get tick */ - tickstart = HAL_GetTick(); - - if (hi2c->State == HAL_I2C_STATE_READY) { - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_BUSY; - } - - /* Process Locked */ - __HAL_LOCK(hi2c); - - /* Check if the I2C is already enabled */ - if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) { - /* Enable I2C peripheral */ - __HAL_I2C_ENABLE(hi2c); - } - - /* Disable Pos */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - hi2c->State = HAL_I2C_STATE_BUSY; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - - do { - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); - - /* Wait until ADDR or AF flag are set */ - /* Get tick */ - tickstart = HAL_GetTick(); - - tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); - tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF); - tmp3 = hi2c->State; - while ((tmp1 == RESET) && (tmp2 == RESET) && (tmp3 != HAL_I2C_STATE_TIMEOUT)) { - if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) { - hi2c->State = HAL_I2C_STATE_TIMEOUT; - } - tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR); - tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF); - tmp3 = hi2c->State; - } - - hi2c->State = HAL_I2C_STATE_READY; - - /* Check if the ADDR flag has been set */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR) == SET) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - /* Clear ADDR Flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_OK; - } else { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - /* Clear AF Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - /* Wait until BUSY flag is reset */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - } - } while (I2C_Trials++ < Trials); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } else { - return HAL_BUSY; - } -} - -/** - * @brief This function handles I2C event interrupt request. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c) { - uint32_t sr2itflags = READ_REG(hi2c->Instance->SR2); - uint32_t sr1itflags = READ_REG(hi2c->Instance->SR1); - uint32_t itsources = READ_REG(hi2c->Instance->CR2); - - uint32_t CurrentMode = hi2c->Mode; - - /* Master or Memory mode selected */ - if ((CurrentMode == HAL_I2C_MODE_MASTER) || (CurrentMode == HAL_I2C_MODE_MEM)) { - /* SB Set ----------------------------------------------------------------*/ - if (((sr1itflags & I2C_FLAG_SB) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) { - I2C_Master_SB(hi2c); - } - /* ADDR Set --------------------------------------------------------------*/ - else if (((sr1itflags & I2C_FLAG_ADDR) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) { - I2C_Master_ADDR(hi2c); - } - - /* I2C in mode Transmitter -----------------------------------------------*/ - if ((sr2itflags & I2C_FLAG_TRA) != RESET) { - /* TXE set and BTF reset -----------------------------------------------*/ - if (((sr1itflags & I2C_FLAG_TXE) != RESET) && ((itsources & I2C_IT_BUF) != RESET) && ((sr1itflags & I2C_FLAG_BTF) == RESET)) { - I2C_MasterTransmit_TXE(hi2c); - } - /* BTF set -------------------------------------------------------------*/ - else if (((sr1itflags & I2C_FLAG_BTF) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) { - I2C_MasterTransmit_BTF(hi2c); - } - } - /* I2C in mode Receiver --------------------------------------------------*/ - else { - /* RXNE set and BTF reset -----------------------------------------------*/ - if (((sr1itflags & I2C_FLAG_RXNE) != RESET) && ((itsources & I2C_IT_BUF) != RESET) && ((sr1itflags & I2C_FLAG_BTF) == RESET)) { - I2C_MasterReceive_RXNE(hi2c); - } - /* BTF set -------------------------------------------------------------*/ - else if (((sr1itflags & I2C_FLAG_BTF) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) { - I2C_MasterReceive_BTF(hi2c); - } - } - } - /* Slave mode selected */ -#if 0 - else - { - /* ADDR set --------------------------------------------------------------*/ - if(((sr1itflags & I2C_FLAG_ADDR) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) - { - I2C_Slave_ADDR(hi2c); - } - /* STOPF set --------------------------------------------------------------*/ - else if(((sr1itflags & I2C_FLAG_STOPF) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) - { - I2C_Slave_STOPF(hi2c); - } - /* I2C in mode Transmitter -----------------------------------------------*/ - else if((sr2itflags & I2C_FLAG_TRA) != RESET) - { - /* TXE set and BTF reset -----------------------------------------------*/ - if(((sr1itflags & I2C_FLAG_TXE) != RESET) && ((itsources & I2C_IT_BUF) != RESET) && ((sr1itflags & I2C_FLAG_BTF) == RESET)) - { - I2C_SlaveTransmit_TXE(hi2c); - } - /* BTF set -------------------------------------------------------------*/ - else if(((sr1itflags & I2C_FLAG_BTF) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) - { - I2C_SlaveTransmit_BTF(hi2c); - } - } - /* I2C in mode Receiver --------------------------------------------------*/ - else - { - /* RXNE set and BTF reset ----------------------------------------------*/ - if(((sr1itflags & I2C_FLAG_RXNE) != RESET) && ((itsources & I2C_IT_BUF) != RESET) && ((sr1itflags & I2C_FLAG_BTF) == RESET)) - { - I2C_SlaveReceive_RXNE(hi2c); - } - /* BTF set -------------------------------------------------------------*/ - else if(((sr1itflags & I2C_FLAG_BTF) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) - { - I2C_SlaveReceive_BTF(hi2c); - } - } - } -#endif -} - -/** - * @brief This function handles I2C error interrupt request. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) { - uint32_t tmp1 = 0U, tmp2 = 0U, tmp3 = 0U, tmp4 = 0U; - uint32_t sr1itflags = READ_REG(hi2c->Instance->SR1); - uint32_t itsources = READ_REG(hi2c->Instance->CR2); - - /* I2C Bus error interrupt occurred ----------------------------------------*/ - if (((sr1itflags & I2C_FLAG_BERR) != RESET) && ((itsources & I2C_IT_ERR) != RESET)) { - hi2c->ErrorCode |= HAL_I2C_ERROR_BERR; - - /* Clear BERR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR); - - /* Workaround: Start cannot be generated after a misplaced Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_SWRST); - } - - /* I2C Arbitration Loss error interrupt occurred ---------------------------*/ - if (((sr1itflags & I2C_FLAG_ARLO) != RESET) && ((itsources & I2C_IT_ERR) != RESET)) { - hi2c->ErrorCode |= HAL_I2C_ERROR_ARLO; - - /* Clear ARLO flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO); - } - - /* I2C Acknowledge failure error interrupt occurred ------------------------*/ - if (((sr1itflags & I2C_FLAG_AF) != RESET) && ((itsources & I2C_IT_ERR) != RESET)) { - tmp1 = hi2c->Mode; - tmp2 = hi2c->XferCount; - tmp3 = hi2c->State; - tmp4 = hi2c->PreviousState; - if ((tmp1 == HAL_I2C_MODE_SLAVE) && (tmp2 == 0U) - && ((tmp3 == HAL_I2C_STATE_BUSY_TX) || (tmp3 == HAL_I2C_STATE_BUSY_TX_LISTEN) || ((tmp3 == HAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX)))) { - } else { - hi2c->ErrorCode |= HAL_I2C_ERROR_AF; - - /* Do not generate a STOP in case of Slave receive non acknowledge during transfer (mean not at the end of transfer) */ - if (hi2c->Mode == HAL_I2C_MODE_MASTER) { - /* Generate Stop */ - SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP); - } - - /* Clear AF flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - } - } - - /* I2C Over-Run/Under-Run interrupt occurred -------------------------------*/ - if (((sr1itflags & I2C_FLAG_OVR) != RESET) && ((itsources & I2C_IT_ERR) != RESET)) { - hi2c->ErrorCode |= HAL_I2C_ERROR_OVR; - /* Clear OVR flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR); - } - - /* Call the Error Callback in case of Error detected -----------------------*/ - if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) { - I2C_ITError(hi2c); - } -} - -/** - * @brief Master Tx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MasterTxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Master Rx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MasterRxCpltCallback can be implemented in the user file - */ -} - -/** @brief Slave Tx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_SlaveTxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Slave Rx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_SlaveRxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Slave Address Match callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param TransferDirection Master request Transfer Direction (Write/Read), value of @ref I2C_XferOptions_definition - * @param AddrMatchCode Address Match Code - * @retval None - */ -__weak void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - UNUSED(TransferDirection); - UNUSED(AddrMatchCode); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_AddrCallback can be implemented in the user file - */ -} - -/** - * @brief Listen Complete callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_ListenCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Memory Tx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MemTxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Memory Rx Transfer completed callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_MemRxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief I2C error callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_ErrorCallback can be implemented in the user file - */ -} - -/** - * @brief I2C abort callback. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval None - */ -__weak void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hi2c); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_I2C_AbortCpltCallback could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @defgroup I2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions - * @brief Peripheral State and Errors functions - * -@verbatim - =============================================================================== - ##### Peripheral State, Mode and Error functions ##### - =============================================================================== - [..] - This subsection permits to get in run-time the status of the peripheral - and the data flow. - -@endverbatim - * @{ - */ - -/** - * @brief Return the I2C handle state. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL state - */ -HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c) { - /* Return I2C handle state */ - return hi2c->State; -} - -/** - * @brief Return the I2C Master, Slave, Memory or no mode. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL mode - */ -HAL_I2C_ModeTypeDef HAL_I2C_GetMode(I2C_HandleTypeDef *hi2c) { return hi2c->Mode; } - -/** - * @brief Return the I2C error code - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval I2C Error Code - */ -uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c) { return hi2c->ErrorCode; } - -/** - * @} - */ - -/** - * @brief Handle TXE flag for Master - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - uint32_t CurrentState = hi2c->State; - uint32_t CurrentMode = hi2c->Mode; - uint32_t CurrentXferOptions = hi2c->XferOptions; - - if ((hi2c->XferSize == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_TX)) { - /* Call TxCpltCallback() directly if no stop mode is set */ - if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME)) { - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - HAL_I2C_MasterTxCpltCallback(hi2c); - } else /* Generate Stop condition then Call TxCpltCallback() */ - { - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - hi2c->Mode = HAL_I2C_MODE_NONE; - HAL_I2C_MemTxCpltCallback(hi2c); - } else { - hi2c->Mode = HAL_I2C_MODE_NONE; - HAL_I2C_MasterTxCpltCallback(hi2c); - } - } - } else if ((CurrentState == HAL_I2C_STATE_BUSY_TX) || ((CurrentMode == HAL_I2C_MODE_MEM) && (CurrentState == HAL_I2C_STATE_BUSY_RX))) { - if (hi2c->XferCount == 0U) { - /* Disable BUF interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); - } else { - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - if (hi2c->EventCount == 0) { - /* If Memory address size is 8Bit */ - if (hi2c->MemaddSize == I2C_MEMADD_SIZE_8BIT) { - /* Send Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(hi2c->Memaddress); - - hi2c->EventCount += 2; - } - /* If Memory address size is 16Bit */ - else { - /* Send MSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_MSB(hi2c->Memaddress); - - hi2c->EventCount++; - } - } else if (hi2c->EventCount == 1) { - /* Send LSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(hi2c->Memaddress); - - hi2c->EventCount++; - } else if (hi2c->EventCount == 2) { - if (hi2c->State == HAL_I2C_STATE_BUSY_RX) { - /* Generate Restart */ - hi2c->Instance->CR1 |= I2C_CR1_START; - } else if (hi2c->State == HAL_I2C_STATE_BUSY_TX) { - /* Write data to DR */ - hi2c->Instance->DR = (*hi2c->pBuffPtr++); - hi2c->XferCount--; - } - } - } else { - /* Write data to DR */ - hi2c->Instance->DR = (*hi2c->pBuffPtr++); - hi2c->XferCount--; - } - } - } - return HAL_OK; -} - -/** - * @brief Handle BTF flag for Master transmitter - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - uint32_t CurrentXferOptions = hi2c->XferOptions; - - if (hi2c->State == HAL_I2C_STATE_BUSY_TX) { - if (hi2c->XferCount != 0U) { - /* Write data to DR */ - hi2c->Instance->DR = (*hi2c->pBuffPtr++); - hi2c->XferCount--; - } else { - /* Call TxCpltCallback() directly if no stop mode is set */ - if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME)) { - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - HAL_I2C_MasterTxCpltCallback(hi2c); - } else /* Generate Stop condition then Call TxCpltCallback() */ - { - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - hi2c->Mode = HAL_I2C_MODE_NONE; - - HAL_I2C_MemTxCpltCallback(hi2c); - } else { - hi2c->Mode = HAL_I2C_MODE_NONE; - - HAL_I2C_MasterTxCpltCallback(hi2c); - } - } - } - } - return HAL_OK; -} - -/** - * @brief Handle RXNE flag for Master - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c) { - if (hi2c->State == HAL_I2C_STATE_BUSY_RX) { - uint32_t tmp = 0U; - - tmp = hi2c->XferCount; - if (tmp > 3U) { - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferCount--; - } else if ((tmp == 2U) || (tmp == 3U)) { - if (hi2c->XferOptions != I2C_NEXT_FRAME) { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Enable Pos */ - hi2c->Instance->CR1 |= I2C_CR1_POS; - } else { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - } - - /* Disable BUF interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF); - } else { - if (hi2c->XferOptions != I2C_NEXT_FRAME) { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - } else { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - } - - /* Disable EVT, BUF and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferCount--; - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - hi2c->Mode = HAL_I2C_MODE_NONE; - HAL_I2C_MemRxCpltCallback(hi2c); - } else { - hi2c->Mode = HAL_I2C_MODE_NONE; - HAL_I2C_MasterRxCpltCallback(hi2c); - } - } - } - return HAL_OK; -} - -/** - * @brief Handle BTF flag for Master receiver - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variables to prevent undefined behavior of volatile usage */ - uint32_t CurrentXferOptions = hi2c->XferOptions; - - if (hi2c->XferCount == 3U) { - if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME)) { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - } - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferCount--; - } else if (hi2c->XferCount == 2U) { - /* Prepare next transfer or stop current transfer */ - if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME)) { - if (CurrentXferOptions != I2C_NEXT_FRAME) { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - } else { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - } - - /* Disable EVT and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - } else { - /* Disable EVT and ERR interrupt */ - __HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - } - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferCount--; - - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferCount--; - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->PreviousState = I2C_STATE_NONE; - - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - hi2c->Mode = HAL_I2C_MODE_NONE; - - HAL_I2C_MemRxCpltCallback(hi2c); - } else { - hi2c->Mode = HAL_I2C_MODE_NONE; - - HAL_I2C_MasterRxCpltCallback(hi2c); - } - } else { - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - hi2c->XferCount--; - } - return HAL_OK; -} - -/** - * @brief Handle SB flag for Master - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_Master_SB(I2C_HandleTypeDef *hi2c) { - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - if (hi2c->EventCount == 0U) { - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(hi2c->Devaddress); - } else { - hi2c->Instance->DR = I2C_7BIT_ADD_READ(hi2c->Devaddress); - } - } else { - if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) { - /* Send slave 7 Bits address */ - if (hi2c->State == HAL_I2C_STATE_BUSY_TX) { - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(hi2c->Devaddress); - } else { - hi2c->Instance->DR = I2C_7BIT_ADD_READ(hi2c->Devaddress); - } - } else { - if (hi2c->EventCount == 0U) { - /* Send header of slave address */ - hi2c->Instance->DR = I2C_10BIT_HEADER_WRITE(hi2c->Devaddress); - } else if (hi2c->EventCount == 1U) { - /* Send header of slave address */ - hi2c->Instance->DR = I2C_10BIT_HEADER_READ(hi2c->Devaddress); - } - } - } - - return HAL_OK; -} - - -/** - * @brief Handle ADDR flag for Master - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_Master_ADDR(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - uint32_t CurrentMode = hi2c->Mode; - uint32_t CurrentXferOptions = hi2c->XferOptions; - uint32_t Prev_State = hi2c->PreviousState; - - if (hi2c->State == HAL_I2C_STATE_BUSY_RX) { - if ((hi2c->EventCount == 0U) && (CurrentMode == HAL_I2C_MODE_MEM)) { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } else { - if (hi2c->XferCount == 0U) { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - } else if (hi2c->XferCount == 1U) { - if (CurrentXferOptions == I2C_NO_OPTION_FRAME) { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } else { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - } - } - /* Prepare next transfer or stop current transfer */ - else if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (Prev_State != I2C_STATE_MASTER_BUSY_RX)) { - if (hi2c->XferOptions != I2C_NEXT_FRAME) { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - } else { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } else { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - } - } else if (hi2c->XferCount == 2U) { - if (hi2c->XferOptions != I2C_NEXT_FRAME) { - /* Enable Pos */ - hi2c->Instance->CR1 |= I2C_CR1_POS; - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - } else { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } - - if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - /* Enable Last DMA bit */ - hi2c->Instance->CR2 |= I2C_CR2_LAST; - } - } else { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - /* Enable Last DMA bit */ - hi2c->Instance->CR2 |= I2C_CR2_LAST; - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } - - /* Reset Event counter */ - hi2c->EventCount = 0U; - } - } else { - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - } - - return HAL_OK; -} - -/** - * @brief I2C interrupts error process - * @param hi2c I2C handle. - * @retval None - */ -static void I2C_ITError(I2C_HandleTypeDef *hi2c) { - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - uint32_t CurrentState = hi2c->State; - - if ((CurrentState == HAL_I2C_STATE_BUSY_TX_LISTEN) || (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN)) { - /* keep HAL_I2C_STATE_LISTEN */ - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_LISTEN; - } else { - /* If state is an abort treatment on going, don't change state */ - /* This change will be do later */ - if ((hi2c->State != HAL_I2C_STATE_ABORT) && ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) != I2C_CR2_DMAEN)) { - hi2c->State = HAL_I2C_STATE_READY; - } - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->Mode = HAL_I2C_MODE_NONE; - } - - /* Disable Pos bit in I2C CR1 when error occurred in Master/Mem Receive IT Process */ - hi2c->Instance->CR1 &= ~I2C_CR1_POS; - - /* Abort DMA transfer */ - if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) { - hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN; - - if (hi2c->hdmatx->State != HAL_DMA_STATE_READY) { - /* Set the DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort; - - if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) { - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Call Directly XferAbortCallback function in case of error */ - hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx); - } - } else { - /* Set the DMA Abort callback : - will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */ - hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort; - - if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) { - /* Store Last receive data if any */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) { - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - } - - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - hi2c->State = HAL_I2C_STATE_READY; - - /* Call Directly hi2c->hdmarx->XferAbortCallback function in case of error */ - hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx); - } - } - } else if (hi2c->State == HAL_I2C_STATE_ABORT) { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Store Last receive data if any */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) { - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - } - - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - HAL_I2C_AbortCpltCallback(hi2c); - } else { - /* Store Last receive data if any */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) { - /* Read data from DR */ - (*hi2c->pBuffPtr++) = hi2c->Instance->DR; - } - - /* Call user error callback */ - HAL_I2C_ErrorCallback(hi2c); - } - /* STOP Flag is not set after a NACK reception */ - /* So may inform upper layer that listen phase is stopped */ - /* during NACK error treatment */ - if ((hi2c->State == HAL_I2C_STATE_LISTEN) && ((hi2c->ErrorCode & HAL_I2C_ERROR_AF) == HAL_I2C_ERROR_AF)) { - hi2c->XferOptions = I2C_NO_OPTION_FRAME; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */ - HAL_I2C_ListenCpltCallback(hi2c); - } -} - -/** - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart) { - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - uint32_t CurrentXferOptions = hi2c->XferOptions; - - /* Generate Start condition if first transfer */ - if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME)) { - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - } else if (hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) { - /* Generate ReStart */ - hi2c->Instance->CR1 |= I2C_CR1_START; - } - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) { - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); - } - - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - return HAL_OK; -} - -/** - * @brief Master sends target device address for read request. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart) { - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - uint32_t CurrentXferOptions = hi2c->XferOptions; - - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Generate Start condition if first transfer */ - if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME)) { - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - } else if (hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) { - /* Generate ReStart */ - hi2c->Instance->CR1 |= I2C_CR1_START; - } - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) { - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_READ(DevAddress); - } - - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - return HAL_OK; -} - -/** - * @brief Master sends target device address followed by internal memory address for write request. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart) { - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* If Memory address size is 8Bit */ - if (MemAddSize == I2C_MEMADD_SIZE_8BIT) { - /* Send Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(MemAddress); - } - /* If Memory address size is 16Bit */ - else { - /* Send MSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_MSB(MemAddress); - - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* Send LSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(MemAddress); - } - - return HAL_OK; -} - -/** - * @brief Master sends target device address followed by internal memory address for read request. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param DevAddress Target device address: The device 7 bits address value - * in datasheet must be shifted to the left before calling the interface - * @param MemAddress Internal memory address - * @param MemAddSize Size of internal memory address - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart) { - /* Enable Acknowledge */ - hi2c->Instance->CR1 |= I2C_CR1_ACK; - - /* Generate Start */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* Clear ADDR flag */ - __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* If Memory address size is 8Bit */ - if (MemAddSize == I2C_MEMADD_SIZE_8BIT) { - /* Send Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(MemAddress); - } - /* If Memory address size is 16Bit */ - else { - /* Send MSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_MSB(MemAddress); - - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* Send LSB of Memory Address */ - hi2c->Instance->DR = I2C_MEM_ADD_LSB(MemAddress); - } - - /* Wait until TXE flag is set */ - if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - /* Generate Restart */ - hi2c->Instance->CR1 |= I2C_CR1_START; - - /* Wait until SB flag is set */ - if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) { - return HAL_TIMEOUT; - } - - /* Send slave address */ - hi2c->Instance->DR = I2C_7BIT_ADD_READ(DevAddress); - - /* Wait until ADDR flag is set */ - if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { - if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) { - return HAL_ERROR; - } else { - return HAL_TIMEOUT; - } - } - - return HAL_OK; -} - -/** - * @brief DMA I2C process complete callback. - * @param hdma DMA handle - * @retval None - */ -static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma) { - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Declaration of temporary variable to prevent undefined behavior of volatile usage */ - uint32_t CurrentState = hi2c->State; - uint32_t CurrentMode = hi2c->Mode; - - if ((CurrentState == HAL_I2C_STATE_BUSY_TX) || ((CurrentState == HAL_I2C_STATE_BUSY_RX) && (CurrentMode == HAL_I2C_MODE_SLAVE))) { - /* Disable DMA Request */ - hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN; - - hi2c->XferCount = 0U; - - /* Enable EVT and ERR interrupt */ - __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR); - } else { - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - /* Disable Last DMA */ - hi2c->Instance->CR2 &= ~I2C_CR2_LAST; - - /* Disable DMA Request */ - hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN; - - hi2c->XferCount = 0U; - - /* Check if Errors has been detected during transfer */ - if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) { - HAL_I2C_ErrorCallback(hi2c); - } else { - hi2c->State = HAL_I2C_STATE_READY; - - if (hi2c->Mode == HAL_I2C_MODE_MEM) { - hi2c->Mode = HAL_I2C_MODE_NONE; - - HAL_I2C_MemRxCpltCallback(hi2c); - } else { - hi2c->Mode = HAL_I2C_MODE_NONE; - - HAL_I2C_MasterRxCpltCallback(hi2c); - } - } - } -} - -/** - * @brief DMA I2C communication error callback. - * @param hdma DMA handle - * @retval None - */ -static void I2C_DMAError(DMA_HandleTypeDef *hdma) { - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - hi2c->XferCount = 0U; - - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; - - HAL_I2C_ErrorCallback(hi2c); -} - -/** - * @brief DMA I2C communication abort callback - * (To be called at end of DMA Abort procedure). - * @param hdma: DMA handle. - * @retval None - */ -static void I2C_DMAAbort(DMA_HandleTypeDef *hdma) { - I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent; - - /* Disable Acknowledge */ - hi2c->Instance->CR1 &= ~I2C_CR1_ACK; - - hi2c->XferCount = 0U; - - /* Reset XferAbortCallback */ - hi2c->hdmatx->XferAbortCallback = NULL; - hi2c->hdmarx->XferAbortCallback = NULL; - - /* Check if come from abort from user */ - if (hi2c->State == HAL_I2C_STATE_ABORT) { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - HAL_I2C_AbortCpltCallback(hi2c); - } else { - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Disable I2C peripheral to prevent dummy data in buffer */ - __HAL_I2C_DISABLE(hi2c); - - /* Call the corresponding callback to inform upper layer of End of Transfer */ - HAL_I2C_ErrorCallback(hi2c); - } -} - -/** - * @brief This function handles I2C Communication Timeout. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param Flag specifies the I2C flag to check. - * @param Status The new Flag status (SET or RESET). - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart) { - /* Wait until flag is set */ - while ((__HAL_I2C_GET_FLAG(hi2c, Flag) ? SET : RESET) == Status) { - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) { - if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - hi2c->Mode = HAL_I2C_MODE_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } - } - - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for Master addressing phase. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for I2C module - * @param Flag specifies the I2C flag to check. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, uint32_t Timeout, uint32_t Tickstart) { - while (__HAL_I2C_GET_FLAG(hi2c, Flag) == RESET) { - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) { - /* Generate Stop */ - hi2c->Instance->CR1 |= I2C_CR1_STOP; - - /* Clear AF Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - hi2c->ErrorCode = HAL_I2C_ERROR_AF; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) { - if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) { - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of TXE flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnTXEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) { - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE) == RESET) { - /* Check if a NACK is detected */ - if (I2C_IsAcknowledgeFailed(hi2c) != HAL_OK) { - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) { - if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) { - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of BTF flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnBTFFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) { - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == RESET) { - /* Check if a NACK is detected */ - if (I2C_IsAcknowledgeFailed(hi2c) != HAL_OK) { - return HAL_ERROR; - } - - /* Check for the Timeout */ - if (Timeout != HAL_MAX_DELAY) { - if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) { - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of STOP flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) { - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) { - /* Check if a NACK is detected */ - if (I2C_IsAcknowledgeFailed(hi2c) != HAL_OK) { - return HAL_ERROR; - } - - /* Check for the Timeout */ - if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) { - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } - return HAL_OK; -} - -/** - * @brief This function handles I2C Communication Timeout for specific usage of RXNE flag. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @param Timeout Timeout duration - * @param Tickstart Tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) { - - while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET) { - /* Check if a STOPF is detected */ - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) { - /* Clear STOP Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); - - hi2c->ErrorCode = HAL_I2C_ERROR_NONE; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - - /* Check for the Timeout */ - if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) { - hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_TIMEOUT; - } - } - return HAL_OK; -} - -/** - * @brief This function handles Acknowledge failed detection during an I2C Communication. - * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains - * the configuration information for the specified I2C. - * @retval HAL status - */ -static HAL_StatusTypeDef I2C_IsAcknowledgeFailed(I2C_HandleTypeDef *hi2c) { - if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) { - /* Clear NACKF Flag */ - __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); - - hi2c->ErrorCode = HAL_I2C_ERROR_AF; - hi2c->PreviousState = I2C_STATE_NONE; - hi2c->State = HAL_I2C_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hi2c); - - return HAL_ERROR; - } - return HAL_OK; -} -/** - * @} - */ - -#endif /* HAL_I2C_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c index e56f9cbd0..56515b0b9 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c @@ -360,8 +360,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue)); /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */ - if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) - || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { + if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) || + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { /* When HSI is used as system clock it will not disabled */ if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) { return HAL_ERROR; @@ -416,8 +416,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { if ((RCC_OscInitStruct->PLL2.PLL2State) != RCC_PLL2_NONE) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { if ((RCC_OscInitStruct->PLL2.PLL2State) == RCC_PLL2_ON) { diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c index d700f0cab..25e902fa0 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c @@ -470,8 +470,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -490,8 +490,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -670,8 +670,8 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Check the parameters */ @@ -730,8 +730,8 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Disable the main PLL2. */ diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c index 18e2fc377..dfa0b557f 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c @@ -2450,8 +2450,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t Outpu UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2541,8 +2541,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t Ou UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2874,8 +2874,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channe TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -2997,8 +2997,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Cha TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -3142,11 +3142,11 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Ch return HAL_ERROR; } } else { - if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { + if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; - } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { + } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((((pData1 == NULL) || (pData2 == NULL))) && (Length > 0U)) { return HAL_ERROR; } else { diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c index 9d6123bf2..87f66c3fd 100644 --- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c +++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c @@ -311,8 +311,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -382,8 +382,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } diff --git a/source/Core/BSP/Miniware/configuration.h b/source/Core/BSP/Miniware/configuration.h index d26fe0a3e..6aebed155 100644 --- a/source/Core/BSP/Miniware/configuration.h +++ b/source/Core/BSP/Miniware/configuration.h @@ -1,6 +1,5 @@ #ifndef CONFIGURATION_H_ #define CONFIGURATION_H_ -#include "Settings.h" #include /** * Configuration.h @@ -57,14 +56,20 @@ * */ #define ORIENTATION_MODE 2 // 0: Right 1:Left 2:Automatic - Default Automatic +#define MAX_ORIENTATION_MODE 2 // Up to auto #define REVERSE_BUTTON_TEMP_CHANGE 0 // 0:Default 1:Reverse - Reverse the plus and minus button assigment for temperature change /** * OLED Brightness * */ -#define MIN_BRIGHTNESS 0 // Min OLED brightness selectable -#define MAX_BRIGHTNESS 100 // Max OLED brightness selectable +#if defined(MODEL_TS101) + #define MIN_BRIGHTNESS 1 // Min OLED brightness selectable + #define MAX_BRIGHTNESS 101 // Max OLED brightness selectable +#else + #define MIN_BRIGHTNESS 0 // Min OLED brightness selectable + #define MAX_BRIGHTNESS 100 // Max OLED brightness selectable +#endif #define BRIGHTNESS_STEP 25 // OLED brightness increment #define DEFAULT_BRIGHTNESS 25 // default OLED brightness @@ -86,7 +91,7 @@ #define POWER_PULSE_DEFAULT 0 #else #define POWER_PULSE_DEFAULT 5 -#endif /* TS100 */ +#endif /* TS100 */ #define POWER_PULSE_WAIT_DEFAULT 4 // Default rate of the power pulse: 4*2500 = 10000 ms = 10 s #define POWER_PULSE_DURATION_DEFAULT 1 // Default duration of the power pulse: 1*250 = 250 ms @@ -104,7 +109,7 @@ #define DETAILED_IDLE 0 // 0: Disable 1: Enable - Default 0 #define THERMAL_RUNAWAY_TIME_SEC 20 -#define THERMAL_RUNAWAY_TEMP_C 10 +#define THERMAL_RUNAWAY_TEMP_C 3 #define CUT_OUT_SETTING 0 // default to no cut-off voltage #define RECOM_VOL_CELL 33 // Minimum voltage per cell (Recommended 3.3V (33)) @@ -156,6 +161,10 @@ #define MIN_BOOST_TEMP_C 250 // The min settable temp for boost mode °C #define MIN_BOOST_TEMP_F 480 // The min settable temp for boost mode °F +// Miniware cant be trusted, and keep using the GD32 randomly now, so assume they will clones in the future + +#define I2C_SOFT_BUS_1 1 + #ifdef MODEL_TS100 #define VOLTAGE_DIV 467 // 467 - Default divider from schematic #define CALIBRATION_OFFSET 900 // 900 - Default adc offset in uV @@ -165,13 +174,18 @@ #define POWER_LIMIT_STEPS 5 #define OP_AMP_GAIN_STAGE OP_AMP_GAIN_STAGE_TS100 #define TEMP_uV_LOOKUP_HAKKO -#define USB_PD_VMAX 20 // Maximum voltage for PD to negotiate - +#define USB_PD_VMAX 20 // Maximum voltage for PD to negotiate +#define OLED_I2CBB1 1 +#define ACCEL_I2CBB1 1 #define HARDWARE_MAX_WATTAGE_X10 750 #define TIP_THERMAL_MASS 65 // X10 watts to raise 1 deg C in 1 second #define TIP_RESISTANCE 75 // x10 ohms, 7.5 typical for ts100 tips #define POW_DC +#define I2C_SOFT_BUS_1 1 +#define OLED_I2CBB1 1 +#define ACCEL_I2CBB1 1 +#define TIPTYPE_T12 1 // Can manually pick a T12 tip #define TEMP_TMP36 #endif /* TS100 */ @@ -185,7 +199,7 @@ #define POWER_LIMIT_STEPS 5 #define OP_AMP_GAIN_STAGE OP_AMP_GAIN_STAGE_TS100 #define TEMP_uV_LOOKUP_HAKKO - +#define ACCEL_LIS_CLONE 1 #define HARDWARE_MAX_WATTAGE_X10 1000 #define TIP_THERMAL_MASS 65 // X10 watts to raise 1 deg C in 1 second #define TIP_RESISTANCE 75 // x10 ohms, 7.5 typical for ts100 tips @@ -193,8 +207,8 @@ #define TIP_HAS_DIRECT_PWM 1 #define POW_DC 1 #define POW_PD 1 +#define USB_PD_EPR_WATTAGE 140 /* EPR Supported */ #define I2C_SOFT_BUS_2 1 -#define I2C_SOFT_BUS_1 1 #define OLED_I2CBB1 1 #define USB_PD_I2CBB2 1 #define USB_PD_VMAX 28 // Device supposedly can do 28V; looks like vmax is 33 ish @@ -204,6 +218,9 @@ #define TEMP_NTC 1 #define ACCEL_I2CBB1 1 #define POW_EPR 1 +#define TIP_TYPE_SUPPORT 1 // Support for tips of different types, i.e. resistance +#define AUTO_TIP_SELECTION 1 // Can auto-select the tip +#define TIPTYPE_T12 1 // Can manually pick a T12 tip #define HAS_POWER_DEBUG_MENU #define DEBUG_POWER_MENU_BUTTON_B @@ -218,9 +235,11 @@ #define TIP_THERMAL_MASS 40 #define TIP_RESISTANCE 45 // x10 ohms, 4.5 typical for ts80 tips - +#define I2C_SOFT_BUS_2 1 #define LIS_ORI_FLIP #define OLED_FLIP +#define TIPTYPE_TS80 1 // Only one tip type so far + #endif /* TS80(P) */ #ifdef MODEL_TS80 @@ -228,35 +247,52 @@ #define CALIBRATION_OFFSET 900 // the adc offset in uV #define PID_POWER_LIMIT 35 // Sets the max pwm power limit #define POWER_LIMIT 32 // 24 watts default power limit +#define OLED_I2CBB1 1 +#define ACCEL_I2CBB1 1 #define HARDWARE_MAX_WATTAGE_X10 320 #define POW_QC #define TEMP_TMP36 +#define I2C_SOFT_BUS_1 1 +#define OLED_I2CBB1 1 +#define ACCEL_I2CBB1 1 #endif /* TS80 */ #ifdef MODEL_TS80P -#define VOLTAGE_DIV 650 // Default for TS80P with slightly different resistors -#define CALIBRATION_OFFSET 1500 // the adc offset in uV -#define PID_POWER_LIMIT 35 // Sets the max pwm power limit -#define POWER_LIMIT 32 // 30 watts default power limit - +#define VOLTAGE_DIV 650 // Default for TS80P with slightly different resistors +#define CALIBRATION_OFFSET 1500 // the adc offset in uV +#define PID_POWER_LIMIT 35 // Sets the max pwm power limit +#define POWER_LIMIT 32 // 30 watts default power limit +#define I2C_SOFT_BUS_2 1 #define HARDWARE_MAX_WATTAGE_X10 320 +#define OLED_I2CBB1 1 +#define ACCEL_I2CBB1 1 -#define POW_PD 1 -#define POW_QC 1 +#define POW_PD 1 +#define USB_PD_EPR_WATTAGE 0 /*No EPR*/ +#define POW_QC 1 #define TEMP_NTC #define I2C_SOFT_BUS_2 1 +#define I2C_SOFT_BUS_1 1 +#define OLED_I2CBB1 1 +#define ACCEL_I2CBB1 1 #define SC7_ORI_FLIP #endif /* TS80P */ #ifdef MODEL_TS101 -#define FLASH_LOGOADDR (0x08000000 + (126 * 1024)) +// For whatever reason, Miniware decided to not build a reliable DFU bootloader +// It can't appear to flash to some of the upper pages of flash, +// I'm slightly suspect a watchdog or something runs out +// as device resets before file finishes copying +// So logo has to be located on page 99 or else it cant be flashed on stock bootloader +#define FLASH_LOGOADDR (0x08000000 + (99 * 1024)) #define SETTINGS_START_PAGE (0x08000000 + (127 * 1024)) #else -#define FLASH_LOGOADDR (0x08000000 + (62 * 1024)) -#define SETTINGS_START_PAGE (0x08000000 + (63 * 1024)) +#define FLASH_LOGOADDR (0x08000000 + (62 * 1024)) +#define SETTINGS_START_PAGE (0x08000000 + (63 * 1024)) +#define OLED_96x16 1 #endif /* TS101 */ #endif /* CONFIGURATION_H_ */ diff --git a/source/Core/BSP/Miniware/port.c b/source/Core/BSP/Miniware/port.c index a79eab6fa..fb0e03304 100644 --- a/source/Core/BSP/Miniware/port.c +++ b/source/Core/BSP/Miniware/port.c @@ -208,7 +208,8 @@ static void prvTaskExitError(void) { // therefore not output an 'unreachable code' warning for code that appears // after it. */ // } - for (;;) {} + for (;;) { + } } /*-----------------------------------------------------------*/ diff --git a/source/Core/BSP/Miniware/preRTOS.cpp b/source/Core/BSP/Miniware/preRTOS.cpp index 2dbfa8b3e..2f903bfa4 100644 --- a/source/Core/BSP/Miniware/preRTOS.cpp +++ b/source/Core/BSP/Miniware/preRTOS.cpp @@ -25,7 +25,4 @@ void preRToSInit() { #ifdef I2C_SOFT_BUS_1 I2CBB1::init(); #endif - - /* Init the IPC objects */ - FRToSI2C::FRToSInit(); } diff --git a/source/Core/BSP/Miniware/stm32f1xx_hal_msp.c b/source/Core/BSP/Miniware/stm32f1xx_hal_msp.c index b3b6007d3..de4a46d0c 100644 --- a/source/Core/BSP/Miniware/stm32f1xx_hal_msp.c +++ b/source/Core/BSP/Miniware/stm32f1xx_hal_msp.c @@ -81,55 +81,6 @@ void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { } } -void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) { - - GPIO_InitTypeDef GPIO_InitStruct; - /**I2C1 GPIO Configuration - PB6 ------> I2C1_SCL - PB7 ------> I2C1_SDA - */ - GPIO_InitStruct.Pin = SCL_Pin | SDA_Pin; - GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; - GPIO_InitStruct.Pull = GPIO_PULLUP; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; - HAL_GPIO_Init(SCL_GPIO_Port, &GPIO_InitStruct); - - /* Peripheral clock enable */ - __HAL_RCC_I2C1_CLK_ENABLE(); - /* I2C1 DMA Init */ - /* I2C1_RX Init */ - hdma_i2c1_rx.Instance = DMA1_Channel7; - hdma_i2c1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; - hdma_i2c1_rx.Init.PeriphInc = DMA_PINC_DISABLE; - hdma_i2c1_rx.Init.MemInc = DMA_MINC_ENABLE; - hdma_i2c1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; - hdma_i2c1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; - hdma_i2c1_rx.Init.Mode = DMA_NORMAL; - hdma_i2c1_rx.Init.Priority = DMA_PRIORITY_LOW; - HAL_DMA_Init(&hdma_i2c1_rx); - - __HAL_LINKDMA(hi2c, hdmarx, hdma_i2c1_rx); - - /* I2C1_TX Init */ - hdma_i2c1_tx.Instance = DMA1_Channel6; - hdma_i2c1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; - hdma_i2c1_tx.Init.PeriphInc = DMA_PINC_DISABLE; - hdma_i2c1_tx.Init.MemInc = DMA_MINC_ENABLE; - hdma_i2c1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; - hdma_i2c1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; - hdma_i2c1_tx.Init.Mode = DMA_NORMAL; - hdma_i2c1_tx.Init.Priority = DMA_PRIORITY_MEDIUM; - HAL_DMA_Init(&hdma_i2c1_tx); - - __HAL_LINKDMA(hi2c, hdmatx, hdma_i2c1_tx); - - /* I2C1 interrupt Init */ - HAL_NVIC_SetPriority(I2C1_EV_IRQn, 15, 0); - HAL_NVIC_EnableIRQ(I2C1_EV_IRQn); - HAL_NVIC_SetPriority(I2C1_ER_IRQn, 15, 0); - HAL_NVIC_EnableIRQ(I2C1_ER_IRQn); -} - void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim_base) { if (htim_base->Instance == TIM3) { /* Peripheral clock enable */ diff --git a/source/Core/BSP/Miniware/stm32f1xx_it.c b/source/Core/BSP/Miniware/stm32f1xx_it.c index 4e1b04ca0..d2e1894d9 100644 --- a/source/Core/BSP/Miniware/stm32f1xx_it.c +++ b/source/Core/BSP/Miniware/stm32f1xx_it.c @@ -57,13 +57,6 @@ void TIM4_IRQHandler(void) { HAL_TIM_IRQHandler(handle); } -void I2C1_EV_IRQHandler(void) { HAL_I2C_EV_IRQHandler(&hi2c1); } -void I2C1_ER_IRQHandler(void) { HAL_I2C_ER_IRQHandler(&hi2c1); } - -void DMA1_Channel6_IRQHandler(void) { HAL_DMA_IRQHandler(&hdma_i2c1_tx); } - -void DMA1_Channel7_IRQHandler(void) { HAL_DMA_IRQHandler(&hdma_i2c1_rx); } - void EXTI9_5_IRQHandler(void) { #ifdef INT_PD_Pin HAL_GPIO_EXTI_IRQHandler(INT_PD_Pin); diff --git a/source/Core/BSP/Miniware/system_stm32f1xx.c b/source/Core/BSP/Miniware/system_stm32f1xx.c index 2fd8e60e5..4c5df9cc0 100644 --- a/source/Core/BSP/Miniware/system_stm32f1xx.c +++ b/source/Core/BSP/Miniware/system_stm32f1xx.c @@ -3,8 +3,8 @@ #include "stm32f1xx.h" #if !defined(HSI_VALUE) -#define HSI_VALUE \ - 8000000U /*!< Default value of the Internal oscillator in Hz. \ +#define HSI_VALUE \ + 8000000U /*!< Default value of the Internal oscillator in Hz. \ This value can be provided and adapted by the user application. */ #endif /* HSI_VALUE */ @@ -86,7 +86,7 @@ void SystemInit(void) { #ifdef VECT_TAB_SRAM SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */ #else - SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */ + SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */ #endif } diff --git a/source/Core/BSP/Pinecil/BSP.cpp b/source/Core/BSP/Pinecil/BSP.cpp index 56e968108..dca65fd6e 100644 --- a/source/Core/BSP/Pinecil/BSP.cpp +++ b/source/Core/BSP/Pinecil/BSP.cpp @@ -5,6 +5,7 @@ #include "I2C_Wrapper.hpp" #include "IRQ.h" #include "Pins.h" +#include "Settings.h" #include "Setup.h" #include "TipThermoModel.h" #include "configuration.h" @@ -93,7 +94,13 @@ void setBuzzer(bool on) {} uint8_t preStartChecks() { return 1; } uint64_t getDeviceID() { return dbg_id_get(); } -uint8_t getTipResistanceX10() { return TIP_RESISTANCE; } +uint8_t getTipResistanceX10() { + uint8_t user_selected_tip = getUserSelectedTipResistance(); + if (user_selected_tip == 0) { + return TIP_RESISTANCE; // Auto mode + } + return user_selected_tip; +} bool isTipShorted() { return false; } uint8_t preStartChecksDone() { return 1; } diff --git a/source/Core/BSP/Pinecil/FreeRTOSConfig.h b/source/Core/BSP/Pinecil/FreeRTOSConfig.h index 91a5e4b6d..d9d1b9a1f 100644 --- a/source/Core/BSP/Pinecil/FreeRTOSConfig.h +++ b/source/Core/BSP/Pinecil/FreeRTOSConfig.h @@ -8,10 +8,9 @@ #define configCPU_CLOCK_HZ ((uint32_t)SystemCoreClock) #define configRTC_CLOCK_HZ ((uint32_t)32768) #define configTICK_RATE_HZ ((TickType_t)1000) -#define configMAX_PRIORITIES (4) +#define configMAX_PRIORITIES (7) #define configMINIMAL_STACK_SIZE ((unsigned short)128) #define configMAX_TASK_NAME_LEN 24 -#define configUSE_16_BIT_TICKS 0 #define configIDLE_SHOULD_YIELD 0 #define configUSE_TASK_NOTIFICATIONS 1 #define configUSE_MUTEXES 1 @@ -22,6 +21,7 @@ #define configUSE_TIME_SLICING 1 #define configUSE_NEWLIB_REENTRANT 0 #define configENABLE_BACKWARD_COMPATIBILITY 0 +#define configTICK_TYPE_WIDTH_IN_BITS TICK_TYPE_WIDTH_32_BITS #define INCLUDE_uxTaskGetStackHighWaterMark 1 #define INCLUDE_xTaskGetSchedulerState 1 @@ -62,11 +62,11 @@ #define configMAX_SYSCALL_INTERRUPT_PRIORITY (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) /* Define to trap errors during development. */ -#define configASSERT(x) \ - if ((x) == 0) { \ - taskDISABLE_INTERRUPTS(); \ - for (;;) \ - ; \ +#define configASSERT(x) \ + if ((x) == 0) { \ + taskDISABLE_INTERRUPTS(); \ + for (;;) \ + ; \ } #define INCLUDE_vTaskPrioritySet 1 diff --git a/source/Core/BSP/Pinecil/I2C_Wrapper.cpp b/source/Core/BSP/Pinecil/I2C_Wrapper.cpp index 46f334360..853f5fabe 100644 --- a/source/Core/BSP/Pinecil/I2C_Wrapper.cpp +++ b/source/Core/BSP/Pinecil/I2C_Wrapper.cpp @@ -145,11 +145,13 @@ void perform_i2c_step() { if (currentState.numberOfBytes == 1) { /* disable acknowledge */ i2c_master_addressing(I2C0, currentState.deviceAddress, I2C_RECEIVER); - while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND)) { + } i2c_ack_config(I2C0, I2C_ACK_DISABLE); i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND); /* wait for the byte to be received */ - while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { + } /* read the byte received from the EEPROM */ *currentState.buffer = i2c_data_receive(I2C0); while (i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { @@ -163,10 +165,12 @@ void perform_i2c_step() { } else if (currentState.numberOfBytes == 2) { /* disable acknowledge */ i2c_master_addressing(I2C0, currentState.deviceAddress, I2C_RECEIVER); - while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND)) { + } i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND); /* wait for the byte to be received */ - while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { + } i2c_ackpos_config(I2C0, I2C_ACKPOS_CURRENT); i2c_ack_config(I2C0, I2C_ACK_DISABLE); @@ -175,7 +179,8 @@ void perform_i2c_step() { currentState.buffer++; /* wait for the byte to be received */ - while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { + } /* read the byte received from the EEPROM */ *currentState.buffer = i2c_data_receive(I2C0); while (i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { @@ -204,20 +209,23 @@ void perform_i2c_step() { if (3 == currentState.numberOfBytes) { /* wait until BTC bit is set */ - while (!i2c_flag_get(I2C0, I2C_FLAG_BTC)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_BTC)) { + } i2c_ackpos_config(I2C0, I2C_ACKPOS_CURRENT); /* disable acknowledge */ i2c_ack_config(I2C0, I2C_ACK_DISABLE); } else if (2 == currentState.numberOfBytes) { /* wait until BTC bit is set */ - while (!i2c_flag_get(I2C0, I2C_FLAG_BTC)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_BTC)) { + } /* disable acknowledge */ i2c_ack_config(I2C0, I2C_ACK_DISABLE); /* send a stop condition to I2C bus */ i2c_stop_on_bus(I2C0); } /* wait until RBNE bit is set */ - while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) {} + while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE)) { + } /* read a byte from the EEPROM */ *currentState.buffer = i2c_data_receive(I2C0); @@ -296,8 +304,9 @@ bool perform_i2c_transaction(uint16_t DevAddress, uint16_t memory_address, uint8 } bool FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t read_address, uint8_t *p_buffer, uint16_t number_of_byte) { - if (!lock()) + if (!lock()) { return false; + } bool res = perform_i2c_transaction(DevAddress, read_address, p_buffer, number_of_byte, false, false); if (!res) { I2C_Unstick(); @@ -307,8 +316,9 @@ bool FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t read_address, uint8_t *p_b } bool FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, uint8_t *p_buffer, uint16_t number_of_byte) { - if (!lock()) + if (!lock()) { return false; + } bool res = perform_i2c_transaction(DevAddress, MemAddress, p_buffer, number_of_byte, true, false); if (!res) { I2C_Unstick(); @@ -349,8 +359,9 @@ bool FRToSI2C::writeRegistersBulk(const uint8_t address, const I2C_REG *register bool FRToSI2C::wakePart(uint16_t DevAddress) { // wakepart is a special case where only the device address is sent - if (!lock()) + if (!lock()) { return false; + } bool res = perform_i2c_transaction(DevAddress, 0, NULL, 0, false, true); if (!res) { I2C_Unstick(); diff --git a/source/Core/BSP/Pinecil/ThermoModel.cpp b/source/Core/BSP/Pinecil/ThermoModel.cpp index a20fe0aad..9a6b589ef 100644 --- a/source/Core/BSP/Pinecil/ThermoModel.cpp +++ b/source/Core/BSP/Pinecil/ThermoModel.cpp @@ -5,7 +5,7 @@ * Author: Ralim */ #include "TipThermoModel.h" -#include "Utils.h" +#include "Utils.hpp" #include "configuration.h" #ifdef TEMP_uV_LOOKUP_HAKKO diff --git a/source/Core/BSP/Pinecil/Vendor/NMSIS/Core/Include/core_feature_base.h b/source/Core/BSP/Pinecil/Vendor/NMSIS/Core/Include/core_feature_base.h index 0c0e9c3b6..437719128 100644 --- a/source/Core/BSP/Pinecil/Vendor/NMSIS/Core/Include/core_feature_base.h +++ b/source/Core/BSP/Pinecil/Vendor/NMSIS/Core/Include/core_feature_base.h @@ -282,7 +282,7 @@ typedef union { */ #define __RV_CSR_SWAP(csr, val) \ ({ \ - register rv_csr_t __v = (unsigned long)(val); \ + volatile rv_csr_t __v = (unsigned long)(val); \ __ASM volatile("csrrw %0, " STRINGIFY(csr) ", %1" : "=r"(__v) : "rK"(__v) : "memory"); \ __v; \ }) @@ -297,7 +297,7 @@ typedef union { */ #define __RV_CSR_READ(csr) \ ({ \ - register rv_csr_t __v; \ + volatile rv_csr_t __v; \ __ASM volatile("csrr %0, " STRINGIFY(csr) : "=r"(__v) : : "memory"); \ __v; \ }) @@ -312,7 +312,7 @@ typedef union { */ #define __RV_CSR_WRITE(csr, val) \ ({ \ - register rv_csr_t __v = (rv_csr_t)(val); \ + volatile rv_csr_t __v = (rv_csr_t)(val); \ __ASM volatile("csrw " STRINGIFY(csr) ", %0" : : "rK"(__v) : "memory"); \ }) @@ -328,7 +328,7 @@ typedef union { */ #define __RV_CSR_READ_SET(csr, val) \ ({ \ - register rv_csr_t __v = (rv_csr_t)(val); \ + volatile rv_csr_t __v = (rv_csr_t)(val); \ __ASM volatile("csrrs %0, " STRINGIFY(csr) ", %1" : "=r"(__v) : "rK"(__v) : "memory"); \ __v; \ }) @@ -343,7 +343,7 @@ typedef union { */ #define __RV_CSR_SET(csr, val) \ ({ \ - register rv_csr_t __v = (rv_csr_t)(val); \ + volatile rv_csr_t __v = (rv_csr_t)(val); \ __ASM volatile("csrs " STRINGIFY(csr) ", %0" : : "rK"(__v) : "memory"); \ }) @@ -359,7 +359,7 @@ typedef union { */ #define __RV_CSR_READ_CLEAR(csr, val) \ ({ \ - register rv_csr_t __v = (rv_csr_t)(val); \ + volatile rv_csr_t __v = (rv_csr_t)(val); \ __ASM volatile("csrrc %0, " STRINGIFY(csr) ", %1" : "=r"(__v) : "rK"(__v) : "memory"); \ __v; \ }) @@ -374,7 +374,7 @@ typedef union { */ #define __RV_CSR_CLEAR(csr, val) \ ({ \ - register rv_csr_t __v = (rv_csr_t)(val); \ + volatile rv_csr_t __v = (rv_csr_t)(val); \ __ASM volatile("csrc " STRINGIFY(csr) ", %0" : : "rK"(__v) : "memory"); \ }) #endif /* __ASSEMBLY__ */ @@ -748,8 +748,8 @@ __STATIC_FORCEINLINE void __SD(volatile void *addr, uint64_t val) { __ASM volati * \return return the initial value in memory */ __STATIC_FORCEINLINE uint32_t __CAS_W(volatile uint32_t *addr, uint32_t oldval, uint32_t newval) { - register uint32_t result; - register uint32_t rc; + uint32_t result; + uint32_t rc; __ASM volatile("0: lr.w %0, %2 \n" " bne %0, %z3, 1f \n" @@ -770,7 +770,7 @@ __STATIC_FORCEINLINE uint32_t __CAS_W(volatile uint32_t *addr, uint32_t oldval, * \return return the original value in memory */ __STATIC_FORCEINLINE uint32_t __AMOSWAP_W(volatile uint32_t *addr, uint32_t newval) { - register uint32_t result; + uint32_t result; __ASM volatile("amoswap.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(newval) : "memory"); return result; @@ -784,7 +784,7 @@ __STATIC_FORCEINLINE uint32_t __AMOSWAP_W(volatile uint32_t *addr, uint32_t newv * \return return memory value + add value */ __STATIC_FORCEINLINE int32_t __AMOADD_W(volatile int32_t *addr, int32_t value) { - register int32_t result; + int32_t result; __ASM volatile("amoadd.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); return *addr; @@ -798,7 +798,7 @@ __STATIC_FORCEINLINE int32_t __AMOADD_W(volatile int32_t *addr, int32_t value) { * \return return memory value & and value */ __STATIC_FORCEINLINE int32_t __AMOAND_W(volatile int32_t *addr, int32_t value) { - register int32_t result; + int32_t result; __ASM volatile("amoand.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); return *addr; @@ -812,7 +812,7 @@ __STATIC_FORCEINLINE int32_t __AMOAND_W(volatile int32_t *addr, int32_t value) { * \return return memory value | and value */ __STATIC_FORCEINLINE int32_t __AMOOR_W(volatile int32_t *addr, int32_t value) { - register int32_t result; + int32_t result; __ASM volatile("amoor.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); return *addr; @@ -826,7 +826,7 @@ __STATIC_FORCEINLINE int32_t __AMOOR_W(volatile int32_t *addr, int32_t value) { * \return return memory value ^ and value */ __STATIC_FORCEINLINE int32_t __AMOXOR_W(volatile int32_t *addr, int32_t value) { - register int32_t result; + int32_t result; __ASM volatile("amoxor.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); return *addr; @@ -840,7 +840,7 @@ __STATIC_FORCEINLINE int32_t __AMOXOR_W(volatile int32_t *addr, int32_t value) { * \return return the bigger value */ __STATIC_FORCEINLINE uint32_t __AMOMAXU_W(volatile uint32_t *addr, uint32_t value) { - register uint32_t result; + uint32_t result; __ASM volatile("amomaxu.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); return *addr; @@ -854,7 +854,7 @@ __STATIC_FORCEINLINE uint32_t __AMOMAXU_W(volatile uint32_t *addr, uint32_t valu * \return the bigger value */ __STATIC_FORCEINLINE int32_t __AMOMAX_W(volatile int32_t *addr, int32_t value) { - register int32_t result; + int32_t result; __ASM volatile("amomax.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); return *addr; @@ -868,7 +868,7 @@ __STATIC_FORCEINLINE int32_t __AMOMAX_W(volatile int32_t *addr, int32_t value) { * \return the smaller value */ __STATIC_FORCEINLINE uint32_t __AMOMINU_W(volatile uint32_t *addr, uint32_t value) { - register uint32_t result; + uint32_t result; __ASM volatile("amominu.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); return *addr; @@ -882,7 +882,7 @@ __STATIC_FORCEINLINE uint32_t __AMOMINU_W(volatile uint32_t *addr, uint32_t valu * \return the smaller value */ __STATIC_FORCEINLINE int32_t __AMOMIN_W(volatile int32_t *addr, int32_t value) { - register int32_t result; + int32_t result; __ASM volatile("amomin.w %0, %2, %1" : "=r"(result), "+A"(*addr) : "r"(value) : "memory"); return *addr; diff --git a/source/Core/BSP/Pinecil/Vendor/OS/FreeRTOS/Source/portable/GCC/port.c b/source/Core/BSP/Pinecil/Vendor/OS/FreeRTOS/Source/portable/GCC/port.c index a20833aab..0d4b93ea7 100644 --- a/source/Core/BSP/Pinecil/Vendor/OS/FreeRTOS/Source/portable/GCC/port.c +++ b/source/Core/BSP/Pinecil/Vendor/OS/FreeRTOS/Source/portable/GCC/port.c @@ -34,7 +34,7 @@ #include "task.h" #include -//#define ENABLE_KERNEL_DEBUG +// #define ENABLE_KERNEL_DEBUG #ifdef ENABLE_KERNEL_DEBUG #define FREERTOS_PORT_DEBUG(...) printf(__VA_ARGS__) diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usb_dev.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usb_dev.c index 2700e660c..0b61201f8 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usb_dev.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usb_dev.c @@ -46,8 +46,8 @@ static uint16_t USBFS_TX_FIFO_SIZE[USBFS_MAX_EP_COUNT] = {(uint16_t)TX0_FIFO_FS_ #elif defined(USB_HS_CORE) -uint16_t USBHS_TX_FIFO_SIZE[USBHS_MAX_EP_COUNT] - = {(uint16_t)TX0_FIFO_HS_SIZE, (uint16_t)TX1_FIFO_HS_SIZE, (uint16_t)TX2_FIFO_HS_SIZE, (uint16_t)TX3_FIFO_HS_SIZE, (uint16_t)TX4_FIFO_HS_SIZE, (uint16_t)TX5_FIFO_HS_SIZE}; +uint16_t USBHS_TX_FIFO_SIZE[USBHS_MAX_EP_COUNT] = {(uint16_t)TX0_FIFO_HS_SIZE, (uint16_t)TX1_FIFO_HS_SIZE, (uint16_t)TX2_FIFO_HS_SIZE, + (uint16_t)TX3_FIFO_HS_SIZE, (uint16_t)TX4_FIFO_HS_SIZE, (uint16_t)TX5_FIFO_HS_SIZE}; #endif /* USBFS_CORE */ diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c index 4a7d0e9c1..900a1e25d 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/drv_usbd_int.c @@ -32,7 +32,7 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSI OF SUCH DAMAGE. */ #include "gd32vf103_libopt.h" -//#include "usbd_conf.h" +// #include "usbd_conf.h" #include "drv_usbd_int.h" #include "usbd_transc.h" @@ -45,8 +45,8 @@ static uint32_t usbd_int_suspend(usb_core_driver *udev); static uint32_t usbd_emptytxfifo_write(usb_core_driver *udev, uint32_t ep_num); -static const uint8_t USB_SPEED[4] - = {[DSTAT_EM_HS_PHY_30MHZ_60MHZ] = USB_SPEED_HIGH, [DSTAT_EM_FS_PHY_30MHZ_60MHZ] = USB_SPEED_FULL, [DSTAT_EM_FS_PHY_48MHZ] = USB_SPEED_FULL, [DSTAT_EM_LS_PHY_6MHZ] = USB_SPEED_LOW}; +static const uint8_t USB_SPEED[4] = { + [DSTAT_EM_HS_PHY_30MHZ_60MHZ] = USB_SPEED_HIGH, [DSTAT_EM_FS_PHY_30MHZ_60MHZ] = USB_SPEED_FULL, [DSTAT_EM_FS_PHY_48MHZ] = USB_SPEED_FULL, [DSTAT_EM_LS_PHY_6MHZ] = USB_SPEED_LOW}; __IO uint8_t setupc_flag = 0U; @@ -230,7 +230,8 @@ void usbd_isr(usb_core_driver *udev) { /* OTG mode interrupt */ if (intr & GINTF_OTGIF) { - if (udev->regs.gr->GOTGINTF & GOTGINTF_SESEND) {} + if (udev->regs.gr->GOTGINTF & GOTGINTF_SESEND) { + } /* Clear OTG interrupt */ udev->regs.gr->GINTF = GINTF_OTGIF; diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbd_enum.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbd_enum.c index 8b976709c..a1d359bb4 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbd_enum.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbd_enum.c @@ -70,8 +70,8 @@ static usb_reqsta (*_std_dev_req[])(usb_core_driver *udev, usb_req *req) = { }; /* get standard descriptor handler */ -static uint8_t *(*std_desc_get[])(usb_core_driver *udev, uint8_t index, uint16_t *len) - = {[USB_DESCTYPE_DEV - 1] = _usb_dev_desc_get, [USB_DESCTYPE_CONFIG - 1] = _usb_config_desc_get, [USB_DESCTYPE_STR - 1] = _usb_str_desc_get}; +static uint8_t *(*std_desc_get[])(usb_core_driver *udev, uint8_t index, + uint16_t *len) = {[USB_DESCTYPE_DEV - 1] = _usb_dev_desc_get, [USB_DESCTYPE_CONFIG - 1] = _usb_config_desc_get, [USB_DESCTYPE_STR - 1] = _usb_str_desc_get}; /*! \brief handle USB standard device request diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c index 22b474c06..edb73d0fe 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/Usb/usbh_enum.c @@ -72,8 +72,8 @@ usbh_status usbh_devdesc_get(usb_core_driver *pudev, usbh_host *puhost, uint8_t usbh_control *usb_ctl = &puhost->control; if (CTL_IDLE == usb_ctl->ctl_state) { - usb_ctl->setup.req - = (usb_req){.bmRequestType = USB_TRX_IN | USB_RECPTYPE_DEV | USB_REQTYPE_STRD, .bRequest = USB_GET_DESCRIPTOR, .wValue = USBH_DESC(USB_DESCTYPE_DEV), .wIndex = 0U, .wLength = len}; + usb_ctl->setup.req = + (usb_req){.bmRequestType = USB_TRX_IN | USB_RECPTYPE_DEV | USB_REQTYPE_STRD, .bRequest = USB_GET_DESCRIPTOR, .wValue = USBH_DESC(USB_DESCTYPE_DEV), .wIndex = 0U, .wLength = len}; usbh_ctlstate_config(puhost, pudev->host.rx_buf, len); } @@ -102,8 +102,8 @@ usbh_status usbh_cfgdesc_get(usb_core_driver *pudev, usbh_host *puhost, uint16_t usbh_control *usb_ctl = &puhost->control; if (CTL_IDLE == usb_ctl->ctl_state) { - usb_ctl->setup.req - = (usb_req){.bmRequestType = USB_TRX_IN | USB_RECPTYPE_DEV | USB_REQTYPE_STRD, .bRequest = USB_GET_DESCRIPTOR, .wValue = USBH_DESC(USB_DESCTYPE_CONFIG), .wIndex = 0U, .wLength = len}; + usb_ctl->setup.req = + (usb_req){.bmRequestType = USB_TRX_IN | USB_RECPTYPE_DEV | USB_REQTYPE_STRD, .bRequest = USB_GET_DESCRIPTOR, .wValue = USBH_DESC(USB_DESCTYPE_CONFIG), .wIndex = 0U, .wLength = len}; usbh_ctlstate_config(puhost, pudev->host.rx_buf, len); } @@ -266,13 +266,15 @@ usbh_status usbh_clrfeature(usb_core_driver *pudev, usbh_host *puhost, uint8_t e \retval operation status */ static void usbh_devdesc_parse(usb_desc_dev *dev_desc, uint8_t *buf, uint16_t len) { - *dev_desc = (usb_desc_dev){.header = {.bLength = *(uint8_t *)(buf + 0U), .bDescriptorType = *(uint8_t *)(buf + 1U)}, + *dev_desc = (usb_desc_dev){ + .header = {.bLength = *(uint8_t *)(buf + 0U), .bDescriptorType = *(uint8_t *)(buf + 1U)}, - .bcdUSB = BYTE_SWAP(buf + 2U), - .bDeviceClass = *(uint8_t *)(buf + 4U), - .bDeviceSubClass = *(uint8_t *)(buf + 5U), - .bDeviceProtocol = *(uint8_t *)(buf + 6U), - .bMaxPacketSize0 = *(uint8_t *)(buf + 7U)}; + .bcdUSB = BYTE_SWAP(buf + 2U), + .bDeviceClass = *(uint8_t *)(buf + 4U), + .bDeviceSubClass = *(uint8_t *)(buf + 5U), + .bDeviceProtocol = *(uint8_t *)(buf + 6U), + .bMaxPacketSize0 = *(uint8_t *)(buf + 7U) + }; if (len > 8U) { /* for 1st time after device connection, host may issue only 8 bytes for device descriptor length */ @@ -295,19 +297,20 @@ static void usbh_devdesc_parse(usb_desc_dev *dev_desc, uint8_t *buf, uint16_t le */ static void usbh_cfgdesc_parse(usb_desc_config *cfg_desc, uint8_t *buf) { /* parse configuration descriptor */ - *cfg_desc = (usb_desc_config) { - .header = { - .bLength = *(uint8_t *)(buf + 0U), - .bDescriptorType = *(uint8_t *)(buf + 1U), - }, - - .wTotalLength = BYTE_SWAP(buf + 2U), - .bNumInterfaces = *(uint8_t *)(buf + 4U), - .bConfigurationValue = *(uint8_t *)(buf + 5U), - .iConfiguration = *(uint8_t *)(buf + 6U), - .bmAttributes = *(uint8_t *)(buf + 7U), - .bMaxPower = *(uint8_t *)(buf + 8U) - }; + *cfg_desc = (usb_desc_config){ + .header = + { + .bLength = *(uint8_t *)(buf + 0U), + .bDescriptorType = *(uint8_t *)(buf + 1U), + }, + + .wTotalLength = BYTE_SWAP(buf + 2U), + .bNumInterfaces = *(uint8_t *)(buf + 4U), + .bConfigurationValue = *(uint8_t *)(buf + 5U), + .iConfiguration = *(uint8_t *)(buf + 6U), + .bmAttributes = *(uint8_t *)(buf + 7U), + .bMaxPower = *(uint8_t *)(buf + 8U) + }; } /*! @@ -318,7 +321,7 @@ static void usbh_cfgdesc_parse(usb_desc_config *cfg_desc, uint8_t *buf) { \retval operation status */ static void usbh_cfgset_parse(usb_dev_prop *udev, uint8_t *buf) { - usb_desc_ep * ep = NULL; + usb_desc_ep *ep = NULL; usb_desc_itf *itf = NULL, itf_value; usb_desc_header *pdesc = (usb_desc_header *)buf; @@ -388,20 +391,21 @@ static void usbh_cfgset_parse(usb_dev_prop *udev, uint8_t *buf) { \retval operation status */ static void usbh_itfdesc_parse(usb_desc_itf *itf_desc, uint8_t *buf) { - *itf_desc = (usb_desc_itf) { - .header = { - .bLength = *(uint8_t *)(buf + 0U), - .bDescriptorType = *(uint8_t *)(buf + 1U), - }, - - .bInterfaceNumber = *(uint8_t *)(buf + 2U), - .bAlternateSetting = *(uint8_t *)(buf + 3U), - .bNumEndpoints = *(uint8_t *)(buf + 4U), - .bInterfaceClass = *(uint8_t *)(buf + 5U), - .bInterfaceSubClass = *(uint8_t *)(buf + 6U), - .bInterfaceProtocol = *(uint8_t *)(buf + 7U), - .iInterface = *(uint8_t *)(buf + 8U) - }; + *itf_desc = (usb_desc_itf){ + .header = + { + .bLength = *(uint8_t *)(buf + 0U), + .bDescriptorType = *(uint8_t *)(buf + 1U), + }, + + .bInterfaceNumber = *(uint8_t *)(buf + 2U), + .bAlternateSetting = *(uint8_t *)(buf + 3U), + .bNumEndpoints = *(uint8_t *)(buf + 4U), + .bInterfaceClass = *(uint8_t *)(buf + 5U), + .bInterfaceSubClass = *(uint8_t *)(buf + 6U), + .bInterfaceProtocol = *(uint8_t *)(buf + 7U), + .iInterface = *(uint8_t *)(buf + 8U) + }; } /*! @@ -412,12 +416,14 @@ static void usbh_itfdesc_parse(usb_desc_itf *itf_desc, uint8_t *buf) { \retval operation status */ static void usbh_epdesc_parse(usb_desc_ep *ep_desc, uint8_t *buf) { - *ep_desc = (usb_desc_ep){.header = {.bLength = *(uint8_t *)(buf + 0U), .bDescriptorType = *(uint8_t *)(buf + 1U)}, - - .bEndpointAddress = *(uint8_t *)(buf + 2U), - .bmAttributes = *(uint8_t *)(buf + 3U), - .wMaxPacketSize = BYTE_SWAP(buf + 4U), - .bInterval = *(uint8_t *)(buf + 6U)}; + *ep_desc = (usb_desc_ep){ + .header = {.bLength = *(uint8_t *)(buf + 0U), .bDescriptorType = *(uint8_t *)(buf + 1U)}, + + .bEndpointAddress = *(uint8_t *)(buf + 2U), + .bmAttributes = *(uint8_t *)(buf + 3U), + .wMaxPacketSize = BYTE_SWAP(buf + 4U), + .bInterval = *(uint8_t *)(buf + 6U) + }; } /*! diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_adc.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_adc.c index 9c04ec58a..e3e22dd17 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_adc.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_adc.c @@ -199,11 +199,13 @@ void adc_calibration_enable(uint32_t adc_periph) { /* reset the selected ADC1 calibration registers */ ADC_CTL1(adc_periph) |= (uint32_t)ADC_CTL1_RSTCLB; /* check the RSTCLB bit state */ - while ((uint32_t)RESET != (ADC_CTL1(adc_periph) & ADC_CTL1_RSTCLB)) {} + while ((uint32_t)RESET != (ADC_CTL1(adc_periph) & ADC_CTL1_RSTCLB)) { + } /* enable ADC calibration process */ ADC_CTL1(adc_periph) |= ADC_CTL1_CLB; /* check the CLB bit state */ - while ((uint32_t)RESET != (ADC_CTL1(adc_periph) & ADC_CTL1_CLB)) {} + while ((uint32_t)RESET != (ADC_CTL1(adc_periph) & ADC_CTL1_CLB)) { + } } /*! @@ -630,7 +632,7 @@ uint32_t adc_sync_mode_convert_value_read(void) { \retval none */ void adc_watchdog_single_channel_enable(uint32_t adc_periph, uint8_t adc_channel) { - ADC_CTL0(adc_periph) &= (uint32_t) ~(ADC_CTL0_RWDEN | ADC_CTL0_IWDEN | ADC_CTL0_WDSC | ADC_CTL0_WDCHSEL); + ADC_CTL0(adc_periph) &= (uint32_t)~(ADC_CTL0_RWDEN | ADC_CTL0_IWDEN | ADC_CTL0_WDSC | ADC_CTL0_WDCHSEL); /* analog watchdog channel select */ ADC_CTL0(adc_periph) |= (uint32_t)adc_channel; ADC_CTL0(adc_periph) |= (uint32_t)(ADC_CTL0_RWDEN | ADC_CTL0_IWDEN | ADC_CTL0_WDSC); @@ -648,7 +650,7 @@ void adc_watchdog_single_channel_enable(uint32_t adc_periph, uint8_t adc_channel \retval none */ void adc_watchdog_group_channel_enable(uint32_t adc_periph, uint8_t adc_channel_group) { - ADC_CTL0(adc_periph) &= (uint32_t) ~(ADC_CTL0_RWDEN | ADC_CTL0_IWDEN | ADC_CTL0_WDSC); + ADC_CTL0(adc_periph) &= (uint32_t)~(ADC_CTL0_RWDEN | ADC_CTL0_IWDEN | ADC_CTL0_WDSC); /* select the group */ switch (adc_channel_group) { case ADC_REGULAR_CHANNEL: @@ -674,7 +676,7 @@ void adc_watchdog_group_channel_enable(uint32_t adc_periph, uint8_t adc_channel_ \param[out] none \retval none */ -void adc_watchdog_disable(uint32_t adc_periph) { ADC_CTL0(adc_periph) &= (uint32_t) ~(ADC_CTL0_RWDEN | ADC_CTL0_IWDEN | ADC_CTL0_WDSC | ADC_CTL0_WDCHSEL); } +void adc_watchdog_disable(uint32_t adc_periph) { ADC_CTL0(adc_periph) &= (uint32_t)~(ADC_CTL0_RWDEN | ADC_CTL0_IWDEN | ADC_CTL0_WDSC | ADC_CTL0_WDCHSEL); } /*! \brief configure ADC analog watchdog threshold diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_bkp.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_bkp.c index 2c26ab52b..b31e299ee 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_bkp.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_bkp.c @@ -45,8 +45,7 @@ OF SUCH DAMAGE. \param[out] none \retval none */ -void bkp_deinit(void) { /* reset BKP domain register*/ -} +void bkp_deinit(void) { /* reset BKP domain register*/ } /*! \brief write BKP data register diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_dma.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_dma.c index e129f7cce..b2eebe3ec 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_dma.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_dma.c @@ -37,8 +37,9 @@ OF SUCH DAMAGE. #include "gd32vf103_dma.h" #include "gd32vf103_rcu.h" -#define DMA_WRONG_HANDLE \ - while (1) {} +#define DMA_WRONG_HANDLE \ + while (1) { \ + } /* check whether peripheral matches channels or not */ static ErrStatus dma_periph_and_channel_check(uint32_t dma_periph, dma_channel_enum channelx); diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_exmc.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_exmc.c index d14858816..fb7cb916c 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_exmc.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_exmc.c @@ -112,16 +112,16 @@ void exmc_norsram_init(exmc_norsram_parameter_struct *exmc_norsram_init_struct) snctl = EXMC_SNCTL(exmc_norsram_init_struct->norsram_region); /* clear relative bits */ - snctl &= ((uint32_t) ~(EXMC_SNCTL_NREN | EXMC_SNCTL_NRTP | EXMC_SNCTL_NRW | EXMC_SNCTL_NRWTPOL | EXMC_SNCTL_WREN | EXMC_SNCTL_NRWTEN | EXMC_SNCTL_ASYNCWAIT | EXMC_SNCTL_NRMUX)); + snctl &= ((uint32_t)~(EXMC_SNCTL_NREN | EXMC_SNCTL_NRTP | EXMC_SNCTL_NRW | EXMC_SNCTL_NRWTPOL | EXMC_SNCTL_WREN | EXMC_SNCTL_NRWTEN | EXMC_SNCTL_ASYNCWAIT | EXMC_SNCTL_NRMUX)); - snctl |= (uint32_t)((uint32_t)exmc_norsram_init_struct->address_data_mux << SNCTL_NRMUX_OFFSET) | exmc_norsram_init_struct->memory_type | exmc_norsram_init_struct->databus_width - | exmc_norsram_init_struct->nwait_polarity | ((uint32_t)exmc_norsram_init_struct->memory_write << SNCTL_WREN_OFFSET) - | ((uint32_t)exmc_norsram_init_struct->nwait_signal << SNCTL_NRWTEN_OFFSET) | ((uint32_t)exmc_norsram_init_struct->asyn_wait << SNCTL_ASYNCWAIT_OFFSET); + snctl |= (uint32_t)((uint32_t)exmc_norsram_init_struct->address_data_mux << SNCTL_NRMUX_OFFSET) | exmc_norsram_init_struct->memory_type | exmc_norsram_init_struct->databus_width | + exmc_norsram_init_struct->nwait_polarity | ((uint32_t)exmc_norsram_init_struct->memory_write << SNCTL_WREN_OFFSET) | + ((uint32_t)exmc_norsram_init_struct->nwait_signal << SNCTL_NRWTEN_OFFSET) | ((uint32_t)exmc_norsram_init_struct->asyn_wait << SNCTL_ASYNCWAIT_OFFSET); - sntcfg = (uint32_t)((exmc_norsram_init_struct->read_write_timing->asyn_address_setuptime - 1U) & EXMC_SNTCFG_ASET) - | (((exmc_norsram_init_struct->read_write_timing->asyn_address_holdtime - 1U) << SNTCFG_AHLD_OFFSET) & EXMC_SNTCFG_AHLD) - | (((exmc_norsram_init_struct->read_write_timing->asyn_data_setuptime - 1U) << SNTCFG_DSET_OFFSET) & EXMC_SNTCFG_DSET) - | (((exmc_norsram_init_struct->read_write_timing->bus_latency - 1U) << SNTCFG_BUSLAT_OFFSET) & EXMC_SNTCFG_BUSLAT); + sntcfg = (uint32_t)((exmc_norsram_init_struct->read_write_timing->asyn_address_setuptime - 1U) & EXMC_SNTCFG_ASET) | + (((exmc_norsram_init_struct->read_write_timing->asyn_address_holdtime - 1U) << SNTCFG_AHLD_OFFSET) & EXMC_SNTCFG_AHLD) | + (((exmc_norsram_init_struct->read_write_timing->asyn_data_setuptime - 1U) << SNTCFG_DSET_OFFSET) & EXMC_SNTCFG_DSET) | + (((exmc_norsram_init_struct->read_write_timing->bus_latency - 1U) << SNTCFG_BUSLAT_OFFSET) & EXMC_SNTCFG_BUSLAT); /* nor flash access enable */ if (EXMC_MEMORY_TYPE_NOR == exmc_norsram_init_struct->memory_type) { diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_fmc.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_fmc.c index 4811ec877..3b38e5bde 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_fmc.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_fmc.c @@ -188,7 +188,8 @@ void ob_unlock(void) { } /* wait until OBWEN bit is set by hardware */ - while (RESET == (FMC_CTL & FMC_CTL_OBWEN)) {} + while (RESET == (FMC_CTL & FMC_CTL_OBWEN)) { + } } /*! diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rcu.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rcu.c index af0b669d8..231431ac9 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rcu.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rcu.c @@ -54,8 +54,8 @@ void rcu_deinit(void) { RCU_CTL &= ~RCU_CTL_HXTALBPS; RCU_CTL &= ~(RCU_CTL_PLL1EN | RCU_CTL_PLL2EN); /* reset CFG0 register */ - RCU_CFG0 &= ~(RCU_CFG0_SCS | RCU_CFG0_AHBPSC | RCU_CFG0_APB1PSC | RCU_CFG0_APB2PSC | RCU_CFG0_ADCPSC | RCU_CFG0_PLLSEL | RCU_CFG0_PREDV0_LSB | RCU_CFG0_PLLMF | RCU_CFG0_USBFSPSC | RCU_CFG0_CKOUT0SEL - | RCU_CFG0_ADCPSC_2 | RCU_CFG0_PLLMF_4); + RCU_CFG0 &= ~(RCU_CFG0_SCS | RCU_CFG0_AHBPSC | RCU_CFG0_APB1PSC | RCU_CFG0_APB2PSC | RCU_CFG0_ADCPSC | RCU_CFG0_PLLSEL | RCU_CFG0_PREDV0_LSB | RCU_CFG0_PLLMF | RCU_CFG0_USBFSPSC | + RCU_CFG0_CKOUT0SEL | RCU_CFG0_ADCPSC_2 | RCU_CFG0_PLLMF_4); /* reset INT and CFG1 register */ RCU_INT = 0x00ff0000U; RCU_CFG1 &= ~(RCU_CFG1_PREDV0 | RCU_CFG1_PREDV1 | RCU_CFG1_PLL1MF | RCU_CFG1_PLL2MF | RCU_CFG1_PREDV0SEL | RCU_CFG1_I2S1SEL | RCU_CFG1_I2S2SEL); diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rtc.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rtc.c index 8a7bb21fd..50d2909ab 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rtc.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_rtc.c @@ -97,7 +97,8 @@ void rtc_prescaler_set(uint32_t psc) { */ void rtc_lwoff_wait(void) { /* loop until LWOFF flag is set */ - while (RESET == (RTC_CTL & RTC_CTL_LWOFF)) {} + while (RESET == (RTC_CTL & RTC_CTL_LWOFF)) { + } } /*! @@ -110,7 +111,8 @@ void rtc_register_sync_wait(void) { /* clear RSYNF flag */ RTC_CTL &= ~RTC_CTL_RSYNF; /* loop until RSYNF flag is set */ - while (RESET == (RTC_CTL & RTC_CTL_RSYNF)) {} + while (RESET == (RTC_CTL & RTC_CTL_RSYNF)) { + } } /*! diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_timer.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_timer.c index 08192e351..652fff3f7 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_timer.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/gd32vf103_timer.c @@ -482,8 +482,8 @@ void timer_break_struct_para_init(timer_break_parameter_struct *breakpara) { \retval none */ void timer_break_config(uint32_t timer_periph, timer_break_parameter_struct *breakpara) { - TIMER_CCHP(timer_periph) = (uint32_t)(((uint32_t)(breakpara->runoffstate)) | ((uint32_t)(breakpara->ideloffstate)) | ((uint32_t)(breakpara->deadtime)) | ((uint32_t)(breakpara->breakpolarity)) - | ((uint32_t)(breakpara->outputautostate)) | ((uint32_t)(breakpara->protectmode)) | ((uint32_t)(breakpara->breakstate))); + TIMER_CCHP(timer_periph) = (uint32_t)(((uint32_t)(breakpara->runoffstate)) | ((uint32_t)(breakpara->ideloffstate)) | ((uint32_t)(breakpara->deadtime)) | ((uint32_t)(breakpara->breakpolarity)) | + ((uint32_t)(breakpara->outputautostate)) | ((uint32_t)(breakpara->protectmode)) | ((uint32_t)(breakpara->breakstate))); } /*! diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c index c4f213d12..48618134f 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/Drivers/n200_func.c @@ -44,8 +44,9 @@ uint64_t get_timer_value(void) { while (1) { uint32_t hi = mtime_hi(); uint32_t lo = mtime_lo(); - if (hi == mtime_hi()) + if (hi == mtime_hi()) { return ((uint64_t)hi << 32) | lo; + } } } @@ -278,8 +279,8 @@ void eclic_mode_enable() { write_csr(CSR_MTVEC, mtvec_value); #elif defined(__GNUC__) uint32_t mtvec_value = read_csr(mtvec); - mtvec_value = mtvec_value & 0xFFFFFFC0; - mtvec_value = mtvec_value | 0x00000003; + mtvec_value = mtvec_value & 0xFFFFFFC0; + mtvec_value = mtvec_value | 0x00000003; write_csr(mtvec, mtvec_value); #endif } diff --git a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c index 171bb151c..7ec03a1f2 100644 --- a/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c +++ b/source/Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source/system_gd32vf103.c @@ -110,7 +110,8 @@ static void system_clock_108m_hxtal(void) { /* if fail */ if (0U == (RCU_CTL & RCU_CTL_HXTALSTB)) { - while (1) {} + while (1) { + } } /* HXTAL is stable */ @@ -133,12 +134,14 @@ static void system_clock_108m_hxtal(void) { /* enable PLL1 */ RCU_CTL |= RCU_CTL_PLL1EN; /* wait till PLL1 is ready */ - while (0U == (RCU_CTL & RCU_CTL_PLL1STB)) {} + while (0U == (RCU_CTL & RCU_CTL_PLL1STB)) { + } /* enable PLL1 */ RCU_CTL |= RCU_CTL_PLL2EN; /* wait till PLL1 is ready */ - while (0U == (RCU_CTL & RCU_CTL_PLL2STB)) {} + while (0U == (RCU_CTL & RCU_CTL_PLL2STB)) { + } } else if (HXTAL_VALUE == 8000000) { RCU_CFG1 &= ~(RCU_CFG1_PREDV0SEL | RCU_CFG1_PREDV1 | RCU_CFG1_PLL1MF | RCU_CFG1_PREDV0); RCU_CFG1 |= (RCU_PREDV0SRC_HXTAL | RCU_PREDV0_DIV2 | RCU_PREDV1_DIV2 | RCU_PLL1_MUL20 | RCU_PLL2_MUL20); @@ -146,25 +149,29 @@ static void system_clock_108m_hxtal(void) { /* enable PLL1 */ RCU_CTL |= RCU_CTL_PLL1EN; /* wait till PLL1 is ready */ - while (0U == (RCU_CTL & RCU_CTL_PLL1STB)) {} + while (0U == (RCU_CTL & RCU_CTL_PLL1STB)) { + } /* enable PLL2 */ RCU_CTL |= RCU_CTL_PLL2EN; /* wait till PLL1 is ready */ - while (0U == (RCU_CTL & RCU_CTL_PLL2STB)) {} + while (0U == (RCU_CTL & RCU_CTL_PLL2STB)) { + } } /* enable PLL */ RCU_CTL |= RCU_CTL_PLLEN; /* wait until PLL is stable */ - while (0U == (RCU_CTL & RCU_CTL_PLLSTB)) {} + while (0U == (RCU_CTL & RCU_CTL_PLLSTB)) { + } /* select PLL as system clock */ RCU_CFG0 &= ~RCU_CFG0_SCS; RCU_CFG0 |= RCU_CKSYSSRC_PLL; /* wait until PLL is selected as system clock */ - while (0U == (RCU_CFG0 & RCU_SCSS_PLL)) {} + while (0U == (RCU_CFG0 & RCU_SCSS_PLL)) { + } } /*! @@ -343,8 +350,8 @@ static void system_default_exception_handler(unsigned long mcause, unsigned long printf("MCAUSE: 0x%lx\r\n", mcause); printf("MEPC : 0x%lx\r\n", __RV_CSR_READ(CSR_MEPC)); printf("MTVAL : 0x%lx\r\n", __RV_CSR_READ(CSR_MBADADDR)); - while (1) - ; + while (1) { + } } /** @@ -512,8 +519,7 @@ void _premain_init(void) { * by __libc_fini_array function, so we defined a new function * to do initialization */ -void _postmain_fini(int status) { /* TODO: Add your own finishing code here, called after main */ -} +void _postmain_fini(int status) { /* TODO: Add your own finishing code here, called after main */ } /** * \brief _init function called in __libc_init_array() @@ -524,8 +530,7 @@ void _postmain_fini(int status) { /* TODO: Add your own finishing code here, cal * \note * Please use \ref _premain_init function now */ -void _init(void) { /* Don't put any code here, please use _premain_init now */ -} +void _init(void) { /* Don't put any code here, please use _premain_init now */ } /** * \brief _fini function called in __libc_fini_array() @@ -536,7 +541,6 @@ void _init(void) { /* Don't put any code here, please use _premain_init now */ * \note * Please use \ref _postmain_fini function now */ -void _fini(void) { /* Don't put any code here, please use _postmain_fini now */ -} +void _fini(void) { /* Don't put any code here, please use _postmain_fini now */ } /** @} */ /* End of Doxygen Group NMSIS_Core_SystemAndClock */ diff --git a/source/Core/BSP/Pinecil/configuration.h b/source/Core/BSP/Pinecil/configuration.h index 06d2e7c47..bef59a934 100644 --- a/source/Core/BSP/Pinecil/configuration.h +++ b/source/Core/BSP/Pinecil/configuration.h @@ -1,6 +1,5 @@ #ifndef CONFIGURATION_H_ #define CONFIGURATION_H_ -#include "Settings.h" #include /** * Configuration.h @@ -57,6 +56,7 @@ * */ #define ORIENTATION_MODE 2 // 0: Right 1:Left 2:Automatic - Default Automatic +#define MAX_ORIENTATION_MODE 2 // Up to auto #define REVERSE_BUTTON_TEMP_CHANGE 0 // 0:Default 1:Reverse - Reverse the plus and minus button assigment for temperature change /** @@ -86,7 +86,7 @@ #define POWER_PULSE_DEFAULT 0 #else #define POWER_PULSE_DEFAULT 5 -#endif /* Pinecil */ +#endif /* Pinecil */ #define POWER_PULSE_WAIT_DEFAULT 4 // Default rate of the power pulse: 4*2500 = 10000 ms = 10 s #define POWER_PULSE_DURATION_DEFAULT 1 // Default duration of the power pulse: 1*250 = 250 ms @@ -104,7 +104,7 @@ #define DETAILED_IDLE 0 // 0: Disable 1: Enable - Default 0 #define THERMAL_RUNAWAY_TIME_SEC 20 -#define THERMAL_RUNAWAY_TEMP_C 20 +#define THERMAL_RUNAWAY_TEMP_C 3 #define CUT_OUT_SETTING 0 // default to no cut-off voltage #define RECOM_VOL_CELL 33 // Minimum voltage per cell (Recommended 3.3V (33)) @@ -145,12 +145,16 @@ #define MIN_BOOST_TEMP_C 250 // The min settable temp for boost mode °C #define MIN_BOOST_TEMP_F 480 // The min settable temp for boost mode °F -#define POW_PD 1 -#define POW_PD_EXT 0 -#define POW_QC 1 -#define POW_DC 1 -#define POW_QC_20V 1 -#define ENABLE_QC2 1 +#define OLED_96x16 1 +#define POW_PD 1 +#define USB_PD_EPR_WATTAGE 0 /*No EPR (Yet?) */ +#define POW_PD_EXT 0 +#define POW_QC 1 +#define POW_DC 1 +#define POW_QC_20V 1 +#define ENABLE_QC2 1 +#define MAG_SLEEP_SUPPORT 1 +#define TIPTYPE_T12 1 // Can manually pick a T12 tip #define TEMP_TMP36 #define ACCEL_BMA #define ACCEL_SC7 diff --git a/source/Core/BSP/Pinecilv2/BSP.cpp b/source/Core/BSP/Pinecilv2/BSP.cpp index c511be2eb..942f272e9 100644 --- a/source/Core/BSP/Pinecilv2/BSP.cpp +++ b/source/Core/BSP/Pinecilv2/BSP.cpp @@ -5,16 +5,24 @@ #include "I2C_Wrapper.hpp" #include "IRQ.h" #include "Pins.h" +#include "Settings.h" #include "Setup.h" +#if defined(WS2812B_ENABLE) +#include "WS2812B.h" +#endif #include "TipThermoModel.h" #include "USBPD.h" -#include "Utils.h" +#include "Utils.hpp" +#include "bflb_platform.h" +#include "bl702_adc.h" #include "configuration.h" #include "crc32.h" #include "hal_flash.h" #include "history.hpp" #include "main.hpp" +extern ADC_Gain_Coeff_Type adcGainCoeffCal; + // These control the period's of time used for the PWM const uint16_t powerPWM = 255; uint8_t holdoffTicks = 25; // This is the tick delay before temp measure starts (i.e. time for op-amp recovery) @@ -22,6 +30,10 @@ uint8_t tempMeasureTicks = 25; uint16_t totalPWM = 255; // Total length of the cycle's ticks +#if defined(WS2812B_ENABLE) +WS2812B ws2812b; +#endif + void resetWatchdog() { // #TODO } @@ -31,52 +43,44 @@ void resetWatchdog() { // Stored as ADCReading,Temp in degC static const int32_t NTCHandleLookup[] = { // ADC Reading , Temp in C x10 - - 3221, -400, // - 4144, -350, // - 5271, -300, // - 6622, -250, // - 8219, -200, // - 10075, -150, // - 12190, -100, // - 14554, -50, // - 17151, 0, // - 19937, 50, // - 22867, 100, // - 25886, 150, // - 28944, 200, // - 29546, 210, // - 30159, 220, // - 30769, 230, // - 31373, 240, // - 31969, 250, // - 32566, 260, // - 33159, 270, // - 33749, 280, // - 34334, 290, // - 34916, 300, // - 35491, 310, // - 36062, 320, // - 36628, 330, // - 37186, 340, // - 37739, 350, // - 38286, 360, // - 38825, 370, // - 39358, 380, // - 39884, 390, // - 40400, 400, // - 42879, 450, // - 45160, 500, // - 47235, 550, // - 49111, 600, // - 50792, 650, // - 52292, 700, // - 53621, 750, // - 54797, 800, // - 55836, 850, // - 56748, 900, // - 57550, 950, // - 58257, 1000, // + // Based on NTCG163JF103FTDS thermocouple datasheet values, + // arranged in a voltage divider configuration, with the NTC + // pulling up towards 3.3V, and with a 10k 1% pull-down resistor. + // ADC Reading = 3.3V * 10 / (10 + TypkOhm) / 3.2V * (2 ^ 16) + 3405, -400, // + 4380, -350, // + 5572, -300, // + 6999, -250, // + 8688, -200, // + 10650, -150, // + 12885, -100, // + 15384, -50, // + 18129, 0, // + 21074, 50, // + 24172, 100, // + 27362, 150, // + 30595, 200, // + 33792, 250, // + 36907, 300, // + 39891, 350, // + 42704, 400, // + 45325, 450, // + 47736, 500, // + 49929, 550, // + 51912, 600, // + 53689, 650, // + 55274, 700, // + 56679, 750, // + 57923, 800, // + 59020, 850, // + 59984, 900, // + 60832, 950, // + 61580, 1000, // + 62232, 1050, // + 62810, 1100, // + 63316, 1150, // + 63765, 1200, // + 64158, 1250, // }; #endif @@ -127,6 +131,12 @@ uint8_t getButtonB() { return val; } +void BSPInit(void) { +#if defined(WS2812B_ENABLE) + ws2812b.init(); +#endif +} + void reboot() { hal_system_reset(); } void delay_ms(uint16_t count) { @@ -146,7 +156,33 @@ bool isTipDisconnected() { } void setStatusLED(const enum StatusLED state) { - // Dont have one +#if defined(WS2812B_ENABLE) + static enum StatusLED lastState = LED_UNKNOWN; + + if (lastState != state || state == LED_HEATING) { + switch (state) { + default: + case LED_UNKNOWN: + case LED_OFF: + ws2812b.led_set_color(0, 0, 0, 0); + break; + case LED_STANDBY: + ws2812b.led_set_color(0, 0, 0xFF, 0); // green + break; + case LED_HEATING: { + ws2812b.led_set_color(0, ((xTaskGetTickCount() / 4) % 192) + 64, 0, 0); // Red fade + } break; + case LED_HOT: + ws2812b.led_set_color(0, 0xFF, 0, 0); // red + break; + case LED_COOLING_STILL_HOT: + ws2812b.led_set_color(0, 0xFF, 0x20, 0x00); // Orange + break; + } + ws2812b.led_update(); + lastState = state; + } +#endif } void setBuzzer(bool on) {} @@ -157,7 +193,11 @@ uint8_t tipResistanceReadingSlot = 0; uint8_t getTipResistanceX10() { // Return tip resistance in x10 ohms // We can measure this using the op-amp - return lastTipResistance; + uint8_t user_selected_tip = getUserSelectedTipResistance(); + if (user_selected_tip == 0) { + return lastTipResistance; // Auto mode + } + return user_selected_tip; } uint16_t getTipThermalMass() { return 120; } @@ -193,13 +233,14 @@ void FinishMeasureTipResistance() { ((tipResistanceReadings[1] - tipResistanceReadings[2]) + calculatedSkew) // jump 2 - skew ) // / 2; // Take average - // lastTipResistance = reading / 100; - // // As we are only detecting two resistances; we can split the difference for now + // As we are only detecting three resistances; we just bin to nearest uint8_t newRes = 0; if (reading > 8000) { - // return; // Change nothing as probably disconnected tip + // Let resistance be cleared to 0 } else if (reading < 500) { tipShorted = true; + } else if (reading < 2600) { + newRes = 40; } else if (reading < 4000) { newRes = 62; } else { @@ -276,7 +317,7 @@ uint8_t getDeviceValidationStatus() { } void showBootLogo(void) { - uint8_t scratch[1024]; + alignas(uint32_t) uint8_t scratch[1024]; flash_read(FLASH_LOGOADDR - 0x23000000, scratch, 1024); BootLogo::handleShowingLogo(scratch); diff --git a/source/Core/BSP/Pinecilv2/FreeRTOSConfig.h b/source/Core/BSP/Pinecilv2/FreeRTOSConfig.h index 718036a6a..2781fe54f 100644 --- a/source/Core/BSP/Pinecilv2/FreeRTOSConfig.h +++ b/source/Core/BSP/Pinecilv2/FreeRTOSConfig.h @@ -17,7 +17,6 @@ #define configTOTAL_HEAP_SIZE ((size_t)1024 * 8) #define configMAX_TASK_NAME_LEN (24) #define configUSE_TRACE_FACILITY 0 -#define configUSE_16_BIT_TICKS 0 #define configIDLE_SHOULD_YIELD 0 #define configUSE_MUTEXES 1 #define configQUEUE_REGISTRY_SIZE 8 @@ -30,6 +29,9 @@ #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #define configUSE_STATS_FORMATTING_FUNCTIONS 0 #define configUSE_TICKLESS_IDLE 0 +#define configTASK_NOTIFICATION_ARRAY_ENTRIES 2 +#define configUSE_TASK_NOTIFICATIONS 1 +#define configTICK_TYPE_WIDTH_IN_BITS TICK_TYPE_WIDTH_32_BITS /* Co-routine definitions. */ #define configUSE_CO_ROUTINES 0 @@ -52,8 +54,8 @@ extern "C" { header file. */ void vAssertCalled(void); -#define configASSERT(x) \ - if ((x) == 0) \ +#define configASSERT(x) \ + if ((x) == 0) \ vAssertCalled() #ifdef __cplusplus @@ -75,7 +77,7 @@ void vApplicationSleep(uint32_t xExpectedIdleTime); #define INCLUDE_xTaskGetCurrentTaskHandle 1 #define INCLUDE_uxTaskGetStackHighWaterMark 1 #define INCLUDE_xTaskGetIdleTaskHandle 1 -#define INCLUDE_eTaskGetState 0 +#define INCLUDE_eTaskGetState 1 #define INCLUDE_xEventGroupSetBitFromISR 1 #define INCLUDE_xTimerPendFunctionCall 0 #define INCLUDE_xTaskAbortDelay 0 diff --git a/source/Core/BSP/Pinecilv2/I2C_Wrapper.cpp b/source/Core/BSP/Pinecilv2/I2C_Wrapper.cpp index 93d11ae5b..add528c4a 100644 --- a/source/Core/BSP/Pinecilv2/I2C_Wrapper.cpp +++ b/source/Core/BSP/Pinecilv2/I2C_Wrapper.cpp @@ -7,17 +7,126 @@ #include "BSP.h" #include "IRQ.h" #include "Setup.h" +#include "bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_dma.h" extern "C" { #include "bflb_platform.h" +#include "bl702_dma.h" #include "bl702_glb.h" #include "bl702_i2c.h" } #include +// Semaphore for locking users of I2C SemaphoreHandle_t FRToSI2C::I2CSemaphore = nullptr; StaticSemaphore_t FRToSI2C::xSemaphoreBuffer; -#define I2C_TIME_OUT (uint16_t)(12000) -void FRToSI2C::CpltCallback() {} // Not used +#define I2C_TIME_OUT (uint16_t)(12000) +#define I2C_NOTIFY_INDEX 1 +#define I2C_TX_FIFO_ADDR (0x4000A300 + 0x88) +#define I2C_RX_FIFO_ADDR (0x4000A300 + 0x8C) + +// Used by the irq handler + +volatile uint8_t *IRQDataPointer; +volatile uint8_t IRQDataSizeLeft; +volatile bool IRQFailureMarker; +volatile TaskHandle_t IRQTaskWaitingHandle = NULL; +/****** IRQ Handlers ******/ +void i2c_irq_tx_fifo_low() { + // Filling tx fifo + // Fifo is 32 bit, LSB sent first + // FiFo can store up to 2, 32-bit words + // So we fill it until it has no free room (or we run out of data) + + while (IRQDataSizeLeft > 0 && I2C_GetTXFIFOAvailable() > 0) { + // Can put in at least 1 byte + + // Build a 32-bit word from bytes + uint32_t value = 0; + int packing = IRQDataSizeLeft >= 4 ? 0 : 4 - IRQDataSizeLeft; + for (int i = 0; i < 4 && IRQDataSizeLeft > 0; i++) { + value >>= 8; + value |= (*IRQDataPointer) << 24; // Shift to the left, adding new data to the higher byte + IRQDataPointer++; // Shift to next byte + IRQDataSizeLeft--; + } + // Handle shunting remaining bytes if not a full 4 to send + for (int i = 0; i < packing; i++) { + value >>= 8; + } + // Push the new value to the fifo + *((volatile uint32_t *)I2C_TX_FIFO_ADDR) = value; + } + if (IRQDataSizeLeft == 0) { + // Disable IRQ, were done + I2C_IntMask(I2C0_ID, I2C_TX_FIFO_READY_INT, MASK); + } +} + +void i2c_rx_pop_fifo() { + // Pop one word from the fifo and store it + uint32_t value = *((uint32_t *)I2C_RX_FIFO_ADDR); + + for (int i = 0; i < 4 && IRQDataSizeLeft > 0; i++) { + *IRQDataPointer = value & 0xFF; + IRQDataPointer++; + IRQDataSizeLeft--; + value >>= 8; + } +} + +void i2c_irq_rx_fifo_ready() { + // Draining the Rx FiFo + while (I2C_GetRXFIFOAvailable() > 0) { + i2c_rx_pop_fifo(); + } + + if (IRQDataSizeLeft == 0) { + // Disable IRQ, were done + I2C_IntMask(I2C0_ID, I2C_RX_FIFO_READY_INT, MASK); + } +} + +void i2c_irq_done_read() { + IRQFailureMarker = false; + // If there was a non multiple of 4 bytes to be read, they are pushed to the fifo now (end of transfer interrupt) + // So we catch them here + while (I2C_GetRXFIFOAvailable() > 0) { + i2c_rx_pop_fifo(); + } + + // Mask IRQ's back off + FRToSI2C::CpltCallback(); // Causes the lock to be released +} +void i2c_irq_done() { + IRQFailureMarker = false; + // Mask IRQ's back off + FRToSI2C::CpltCallback(); // Causes the lock to be released +} +void i2c_irq_nack() { + IRQFailureMarker = true; + // Mask IRQ's back off + FRToSI2C::CpltCallback(); // Causes the lock to be released +} + +/****** END IRQ Handlers ******/ +void FRToSI2C::CpltCallback() { + // This is only triggered from IRQ context + I2C_IntMask(I2C0_ID, I2C_TX_FIFO_READY_INT, MASK); + I2C_IntMask(I2C0_ID, I2C_RX_FIFO_READY_INT, MASK); + I2C_IntMask(I2C0_ID, I2C_TRANS_END_INT, MASK); + I2C_IntMask(I2C0_ID, I2C_NACK_RECV_INT, MASK); + + CPU_Interrupt_Disable(I2C_IRQn); // Disable IRQ's + + I2C_Disable(I2C0_ID); // Disable I2C to tidy up + + // Unlock the semaphore && allow task switch if desired by RTOS + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + + xSemaphoreGiveFromISR(I2CSemaphore, &xHigherPriorityTaskWoken); + xTaskNotifyIndexedFromISR(IRQTaskWaitingHandle, I2C_NOTIFY_INDEX, IRQFailureMarker ? 2 : 1, eSetValueWithOverwrite, &xHigherPriorityTaskWoken); + portYIELD_FROM_ISR(xHigherPriorityTaskWoken); +} bool FRToSI2C::I2C_RegisterWrite(uint8_t address, uint8_t reg, uint8_t data) { return Mem_Write(address, reg, &data, 1); } @@ -40,22 +149,41 @@ bool FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t read_address, uint8_t *p_b i2cCfg.data = p_buffer; i2cCfg.subAddrSize = 1; // one byte address - taskENTER_CRITICAL(); - /* --------------- */ - err = I2C_MasterReceiveBlocking(I2C0_ID, &i2cCfg); - taskEXIT_CRITICAL(); - bool res = err == SUCCESS; - if (!res) { - I2C_Unstick(); - } - unlock(); - return res; + // Store handles for IRQ + IRQDataPointer = p_buffer; + IRQDataSizeLeft = number_of_byte; + IRQTaskWaitingHandle = xTaskGetCurrentTaskHandle(); + IRQFailureMarker = false; + + I2C_Disable(I2C0_ID); + // Setup and run + I2C_Init(I2C0_ID, I2C_READ, &i2cCfg); // Setup hardware for the I2C init header with the device address + I2C_IntMask(I2C0_ID, I2C_TRANS_END_INT, UNMASK); + I2C_IntMask(I2C0_ID, I2C_NACK_RECV_INT, UNMASK); + I2C_IntMask(I2C0_ID, I2C_RX_FIFO_READY_INT, UNMASK); + I2C_Int_Callback_Install(I2C0_ID, I2C_TRANS_END_INT, i2c_irq_done_read); + I2C_Int_Callback_Install(I2C0_ID, I2C_NACK_RECV_INT, i2c_irq_nack); + I2C_Int_Callback_Install(I2C0_ID, I2C_RX_FIFO_READY_INT, i2c_irq_rx_fifo_ready); + CPU_Interrupt_Enable(I2C_IRQn); + + CPU_Interrupt_Disable(BLE_IRQn); + // Start + I2C_Enable(I2C0_ID); + + // Wait for transfer in background + uint32_t result = 0; + xTaskNotifyWaitIndexed(I2C_NOTIFY_INDEX, 0xFFFFFFFF, 0xFFFFFFFF, &result, 0xFFFFFFFF); + CPU_Interrupt_Enable(BLE_IRQn); + + return result == 1; } bool FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, uint8_t *p_buffer, uint16_t number_of_byte) { + if (!lock()) { return false; } + I2C_Transfer_Cfg i2cCfg = {0, DISABLE, 0, 0, 0, 0}; BL_Err_Type err = ERROR; i2cCfg.slaveAddr = DevAddress >> 1; @@ -65,16 +193,34 @@ bool FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, uint8_t *p_bu i2cCfg.data = p_buffer; i2cCfg.subAddrSize = 1; // one byte address - taskENTER_CRITICAL(); - /* --------------- */ - err = I2C_MasterSendBlocking(I2C0_ID, &i2cCfg); - taskEXIT_CRITICAL(); - bool res = err == SUCCESS; - if (!res) { - I2C_Unstick(); - } - unlock(); - return res; + // Store handles for IRQ + IRQDataPointer = p_buffer; + IRQDataSizeLeft = number_of_byte; + IRQTaskWaitingHandle = xTaskGetCurrentTaskHandle(); + IRQFailureMarker = false; + + // Setup and run + I2C_Init(I2C0_ID, I2C_WRITE, &i2cCfg); // Setup hardware for the I2C init header with the device address + I2C_IntMask(I2C0_ID, I2C_TRANS_END_INT, UNMASK); + I2C_IntMask(I2C0_ID, I2C_NACK_RECV_INT, UNMASK); + I2C_IntMask(I2C0_ID, I2C_TX_FIFO_READY_INT, UNMASK); + I2C_Int_Callback_Install(I2C0_ID, I2C_TRANS_END_INT, i2c_irq_done); + I2C_Int_Callback_Install(I2C0_ID, I2C_NACK_RECV_INT, i2c_irq_nack); + I2C_Int_Callback_Install(I2C0_ID, I2C_TX_FIFO_READY_INT, i2c_irq_tx_fifo_low); + CPU_Interrupt_Enable(I2C_IRQn); + + i2c_irq_tx_fifo_low(); + + CPU_Interrupt_Disable(BLE_IRQn); // Shut up BLE while we do the transfer + // Start + I2C_Enable(I2C0_ID); + + // Wait for transfer in background + uint32_t result = 0; + xTaskNotifyWaitIndexed(I2C_NOTIFY_INDEX, 0xFFFFFFFF, 0xFFFFFFFF, &result, 0xFFFFFFFF); + CPU_Interrupt_Enable(BLE_IRQn); // Now BLE can run + + return result == 1; } bool FRToSI2C::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { return Mem_Write(DevAddress, pData[0], pData + 1, Size - 1); } diff --git a/source/Core/BSP/Pinecilv2/IRQ.cpp b/source/Core/BSP/Pinecilv2/IRQ.cpp index 7a857b187..1fbb4e1c9 100644 --- a/source/Core/BSP/Pinecilv2/IRQ.cpp +++ b/source/Core/BSP/Pinecilv2/IRQ.cpp @@ -24,40 +24,48 @@ history ADC_Vin; history ADC_Temp; history ADC_Tip; -// IRQ is called at the end of the 8 set readings, pop these from the FIFO and send to filters -void adc_fifo_irq(void) { - if (ADC_GetIntStatus(ADC_INT_FIFO_READY) == SET) { - // Read out all entries in the fifo - while (ADC_Get_FIFO_Count()) { - uint32_t reading = ADC_Read_FIFO(); - // As per manual, 26 bit reading; lowest 16 are the ADC - uint16_t sample = reading & 0xFFFF; - uint8_t source = (reading >> 21) & 0b11111; - switch (source) { +void read_adc_fifo(void) { + // Read out all entries in the fifo + uint8_t pending_readings = ADC_Get_FIFO_Count(); + + // There _should_ always be 8 readings here. If there are not, it means that the adc didnt start when we wanted and timing slipped + // So if there isn't 8 readings, we throw them out + if (pending_readings != 8) { + MSG((char *)"Discarding out of sync adc %d\r\n", pending_readings); + } else { + while (pending_readings) { + pending_readings--; + uint32_t raw_reading = ADC_Read_FIFO(); + ADC_Result_Type parsed = {0, 0, 0}; + ADC_Parse_Result(&raw_reading, 1, &parsed); + // Rollover prevention + if (parsed.value > ((1 << 14) - 1)) { + parsed.value = ((1 << 14) - 1); + } + + switch (parsed.posChan) { case TMP36_ADC_CHANNEL: - ADC_Temp.update(sample); - break; - case TIP_TEMP_ADC_CHANNEL: - ADC_Tip.update(sample); + ADC_Temp.update(parsed.value << 2); break; + case TIP_TEMP_ADC_CHANNEL: { + ADC_Tip.update(parsed.value << 2); + } break; case VIN_ADC_CHANNEL: - ADC_Vin.update(sample); + ADC_Vin.update(parsed.value << 2); break; default: break; } } - // unblock the PID controller thread - if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) { - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - if (pidTaskNotification) { - vTaskNotifyGiveFromISR(pidTaskNotification, &xHigherPriorityTaskWoken); - portYIELD_FROM_ISR(xHigherPriorityTaskWoken); - } + } + // unblock the PID controller thread + if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) { + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + if (pidTaskNotification) { + vTaskNotifyGiveFromISR(pidTaskNotification, &xHigherPriorityTaskWoken); + portYIELD_FROM_ISR(xHigherPriorityTaskWoken); } } - // Clear IRQ - ADC_IntClr(ADC_INT_ALL); } volatile bool inFastPWMMode = false; @@ -69,7 +77,24 @@ volatile uint16_t PWMSafetyTimer = 0; volatile uint8_t pendingPWM = 0; volatile bool pendingNextPeriodIsFast = false; -void start_PWM_output(void) { +void timer0_comp0_callback(void) { + // Trigged at end of output cycle; turn off the tip PWM + PWM_Channel_Disable(PWM_Channel); + TIMER_ClearIntStatus(TIMER_CH0, TIMER_COMP_ID_0); +} + +// Timer 0 is used to co-ordinate the ADC and the output PWM +void timer0_comp1_callback(void) { + ADC_FIFO_Clear(); + ADC_Start(); + TIMER_ClearIntStatus(TIMER_CH0, TIMER_COMP_ID_1); +} +void timer0_comp2_callback(void) { + // Triggered at end of timer cycle; re-start the tip driver + ADC_Stop(); + TIMER_Disable(TIMER_CH0); + // Read the ADC data _now_. So that if things have gone out of sync, we know about it + read_adc_fifo(); if (PWMSafetyTimer) { PWMSafetyTimer--; @@ -82,64 +107,28 @@ void start_PWM_output(void) { } // Update trigger for the end point of the PWM cycle if (pendingPWM > 0) { - TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_1, pendingPWM - 1); + TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_0, pendingPWM - 1); // Turn on output PWM_Channel_Enable(PWM_Channel); } else { - // Leave output off PWM_Channel_Disable(PWM_Channel); } } else { PWM_Channel_Disable(PWM_Channel); - switchToFastPWM(); - } -} - -// Timer 0 is used to co-ordinate the ADC and the output PWM -void timer0_comp0_callback(void) { - if (PWM_Channel_Is_Enabled(PWM_Channel)) { - // So there appears to be a bug _somewhere_ where sometimes the comparator doesn't fire - // Its not re-occurring with specific values, so suspect its a weird bug - // For now, we just skip the cycle and throw away the ADC readings. Its a waste but - // It stops stupid glitches in readings, i'd take slight instability from the time jump - // Over the readings we get that are borked as the header is left on - // - PWM_Channel_Disable(PWM_Channel); - // MSG("ALERT PWM Glitch\r\n"); - // Triger the PID now instead - if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) { - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - if (pidTaskNotification) { - vTaskNotifyGiveFromISR(pidTaskNotification, &xHigherPriorityTaskWoken); - portYIELD_FROM_ISR(xHigherPriorityTaskWoken); - } - } - } else { - ADC_Start(); } - TIMER_ClearIntStatus(TIMER_CH0, TIMER_COMP_ID_0); -} -void timer0_comp1_callback(void) { - // Trigged at end of output cycle; turn off the tip PWM - PWM_Channel_Disable(PWM_Channel); - TIMER_ClearIntStatus(TIMER_CH0, TIMER_COMP_ID_1); -} - -void timer0_comp2_callback(void) { - // Triggered at end of timer cycle; re-start the tip driver - start_PWM_output(); + TIMER_Enable(TIMER_CH0); TIMER_ClearIntStatus(TIMER_CH0, TIMER_COMP_ID_2); } + void switchToFastPWM(void) { inFastPWMMode = true; - holdoffTicks = 10; + holdoffTicks = 20; tempMeasureTicks = 10; totalPWM = powerPWM + tempMeasureTicks + holdoffTicks; - TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_2, totalPWM); - // ~10Hz - TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_0, powerPWM + holdoffTicks); + TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_1, powerPWM + holdoffTicks); + TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_2, totalPWM); // Set divider to 10 ~= 10.5Hz uint32_t tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCDR); @@ -151,14 +140,14 @@ void switchToFastPWM(void) { void switchToSlowPWM(void) { // 5Hz inFastPWMMode = false; - holdoffTicks = 5; + holdoffTicks = 10; tempMeasureTicks = 5; totalPWM = powerPWM + tempMeasureTicks + holdoffTicks; - TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_2, totalPWM); // Adjust ADC - TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_0, powerPWM + holdoffTicks); + TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_1, powerPWM + holdoffTicks); + TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_2, totalPWM); // Set divider for ~ 5Hz uint32_t tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCDR); @@ -167,9 +156,11 @@ void switchToSlowPWM(void) { BL_WR_REG(TIMER_BASE, TIMER_TCDR, tmpVal); } + void setTipPWM(const uint8_t pulse, const bool shouldUseFastModePWM) { - PWMSafetyTimer = 10; // This is decremented in the handler for PWM so that the tip pwm is - // disabled if the PID task is not scheduled often enough. + PWMSafetyTimer = 10; + // This is decremented in the handler for PWM so that the tip pwm is + // disabled if the PID task is not scheduled often enough. pendingPWM = pulse; pendingNextPeriodIsFast = shouldUseFastModePWM; } diff --git a/source/Core/BSP/Pinecilv2/IRQ.h b/source/Core/BSP/Pinecilv2/IRQ.h index 4f6d6814d..bc7dca726 100644 --- a/source/Core/BSP/Pinecilv2/IRQ.h +++ b/source/Core/BSP/Pinecilv2/IRQ.h @@ -19,7 +19,6 @@ extern "C" { void timer0_comp0_callback(void); void timer0_comp1_callback(void); void timer0_comp2_callback(void); -void adc_fifo_irq(void); void GPIO_IRQHandler(void); #ifdef __cplusplus } diff --git a/source/Core/BSP/Pinecilv2/MemMang/heap_5.c b/source/Core/BSP/Pinecilv2/MemMang/heap_5.c index 3ee2639b0..d84de815c 100644 --- a/source/Core/BSP/Pinecilv2/MemMang/heap_5.c +++ b/source/Core/BSP/Pinecilv2/MemMang/heap_5.c @@ -79,21 +79,21 @@ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE -#if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) +#if (configSUPPORT_DYNAMIC_ALLOCATION == 0) #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* Block sizes must not get too small. */ -#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) +#define heapMINIMUM_BLOCK_SIZE ((size_t)(xHeapStructSize << 1)) /* Assumes 8bit bytes! */ -#define heapBITS_PER_BYTE ( ( size_t ) 8 ) +#define heapBITS_PER_BYTE ((size_t)8) /* Define the linked list structure. This is used to link free blocks in order * of their memory address. */ typedef struct A_BLOCK_LINK { - struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ - size_t xBlockSize; /*<< The size of the free block. */ + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ } BlockLink_t; /*-----------------------------------------------------------*/ @@ -104,13 +104,13 @@ typedef struct A_BLOCK_LINK { * the block in front it and/or the block behind it if the memory blocks are * adjacent to each other. */ -static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ); +static void prvInsertBlockIntoFreeList(BlockLink_t *pxBlockToInsert); /*-----------------------------------------------------------*/ /* The size of the structure placed at the beginning of each allocated memory * block must by correctly byte aligned. */ -static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); +static const size_t xHeapStructSize = (sizeof(BlockLink_t) + ((size_t)(portBYTE_ALIGNMENT - 1))) & ~((size_t)portBYTE_ALIGNMENT_MASK); /* Create a couple of list links to mark the start and end of the list. */ static BlockLink_t xStart, *pxEnd = NULL; @@ -130,13 +130,13 @@ static size_t xBlockAllocatedBit = 0; /*-----------------------------------------------------------*/ -void *pvPortMalloc( size_t xWantedSize ) { +void *pvPortMalloc(size_t xWantedSize) { BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; void *pvReturn = NULL; /* The heap must be initialised before the first call to * prvPortMalloc(). */ - configASSERT( pxEnd ); + configASSERT(pxEnd); vTaskSuspendAll(); { @@ -144,17 +144,17 @@ void *pvPortMalloc( size_t xWantedSize ) { * set. The top bit of the block size member of the BlockLink_t structure * is used to determine who owns the block - the application or the * kernel, so it must be free. */ - if ( ( xWantedSize & xBlockAllocatedBit ) == 0 ) { + if ((xWantedSize & xBlockAllocatedBit) == 0) { /* The wanted size is increased so it can contain a BlockLink_t * structure in addition to the requested amount of bytes. */ - if ( xWantedSize > 0 ) { + if (xWantedSize > 0) { xWantedSize += xHeapStructSize; /* Ensure that blocks are always aligned to the required number * of bytes. */ - if ( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) { + if ((xWantedSize & portBYTE_ALIGNMENT_MASK) != 0x00) { /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + xWantedSize += (portBYTE_ALIGNMENT - (xWantedSize & portBYTE_ALIGNMENT_MASK)); } else { mtCOVERAGE_TEST_MARKER(); } @@ -162,23 +162,23 @@ void *pvPortMalloc( size_t xWantedSize ) { mtCOVERAGE_TEST_MARKER(); } - if ( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) { + if ((xWantedSize > 0) && (xWantedSize <= xFreeBytesRemaining)) { /* Traverse the list from the start (lowest address) block until * one of adequate size is found. */ pxPreviousBlock = &xStart; - pxBlock = xStart.pxNextFreeBlock; + pxBlock = xStart.pxNextFreeBlock; - while ( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) { + while ((pxBlock->xBlockSize < xWantedSize) && (pxBlock->pxNextFreeBlock != NULL)) { pxPreviousBlock = pxBlock; pxBlock = pxBlock->pxNextFreeBlock; } /* If the end marker was reached then a block of adequate size * was not found. */ - if ( pxBlock != pxEnd ) { + if (pxBlock != pxEnd) { /* Return the memory space pointed to - jumping over the * BlockLink_t structure at its start. */ - pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + pvReturn = (void *)(((uint8_t *)pxPreviousBlock->pxNextFreeBlock) + xHeapStructSize); /* This block is being returned for use so must be taken out * of the list of free blocks. */ @@ -186,12 +186,12 @@ void *pvPortMalloc( size_t xWantedSize ) { /* If the block is larger than required it can be split into * two. */ - if ( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) { + if ((pxBlock->xBlockSize - xWantedSize) > heapMINIMUM_BLOCK_SIZE) { /* This block is to be split into two. Create a new * block following the number of bytes requested. The void * cast is used to prevent byte alignment warnings from the * compiler. */ - pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + pxNewBlockLink = (void *)(((uint8_t *)pxBlock) + xWantedSize); /* Calculate the sizes of two blocks split from the * single block. */ @@ -199,14 +199,14 @@ void *pvPortMalloc( size_t xWantedSize ) { pxBlock->xBlockSize = xWantedSize; /* Insert the new block into the list of free blocks. */ - prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); + prvInsertBlockIntoFreeList((pxNewBlockLink)); } else { mtCOVERAGE_TEST_MARKER(); } xFreeBytesRemaining -= pxBlock->xBlockSize; - if ( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) { + if (xFreeBytesRemaining < xMinimumEverFreeBytesRemaining) { xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; } else { mtCOVERAGE_TEST_MARKER(); @@ -227,14 +227,14 @@ void *pvPortMalloc( size_t xWantedSize ) { mtCOVERAGE_TEST_MARKER(); } - traceMALLOC( pvReturn, xWantedSize ); + traceMALLOC(pvReturn, xWantedSize); } - ( void ) xTaskResumeAll(); + (void)xTaskResumeAll(); -#if ( configUSE_MALLOC_FAILED_HOOK == 1 ) +#if (configUSE_MALLOC_FAILED_HOOK == 1) { - if ( pvReturn == NULL ) { - extern void vApplicationMallocFailedHook( void ); + if (pvReturn == NULL) { + extern void vApplicationMallocFailedHook(void); vApplicationMallocFailedHook(); } else { mtCOVERAGE_TEST_MARKER(); @@ -246,24 +246,24 @@ void *pvPortMalloc( size_t xWantedSize ) { } /*-----------------------------------------------------------*/ -void vPortFree( void *pv ) { - uint8_t *puc = ( uint8_t * ) pv; +void vPortFree(void *pv) { + uint8_t *puc = (uint8_t *)pv; BlockLink_t *pxLink; - if ( pv != NULL ) { + if (pv != NULL) { /* The memory being freed will have an BlockLink_t structure immediately * before it. */ puc -= xHeapStructSize; /* This casting is to keep the compiler from issuing warnings. */ - pxLink = ( void * ) puc; + pxLink = (void *)puc; /* Check the block is actually allocated. */ - configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); - configASSERT( pxLink->pxNextFreeBlock == NULL ); + configASSERT((pxLink->xBlockSize & xBlockAllocatedBit) != 0); + configASSERT(pxLink->pxNextFreeBlock == NULL); - if ( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) { - if ( pxLink->pxNextFreeBlock == NULL ) { + if ((pxLink->xBlockSize & xBlockAllocatedBit) != 0) { + if (pxLink->pxNextFreeBlock == NULL) { /* The block is being returned to the heap - it is no longer * allocated. */ pxLink->xBlockSize &= ~xBlockAllocatedBit; @@ -272,11 +272,11 @@ void vPortFree( void *pv ) { { /* Add this block to the list of free blocks. */ xFreeBytesRemaining += pxLink->xBlockSize; - traceFREE( pv, pxLink->xBlockSize ); - prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + traceFREE(pv, pxLink->xBlockSize); + prvInsertBlockIntoFreeList(((BlockLink_t *)pxLink)); xNumberOfSuccessfulFrees++; } - ( void ) xTaskResumeAll(); + (void)xTaskResumeAll(); } else { mtCOVERAGE_TEST_MARKER(); } @@ -287,27 +287,27 @@ void vPortFree( void *pv ) { } /*-----------------------------------------------------------*/ -size_t xPortGetFreeHeapSize( void ) { return xFreeBytesRemaining; } +size_t xPortGetFreeHeapSize(void) { return xFreeBytesRemaining; } /*-----------------------------------------------------------*/ -size_t xPortGetMinimumEverFreeHeapSize( void ) { return xMinimumEverFreeBytesRemaining; } +size_t xPortGetMinimumEverFreeHeapSize(void) { return xMinimumEverFreeBytesRemaining; } /*-----------------------------------------------------------*/ -static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) { +static void prvInsertBlockIntoFreeList(BlockLink_t *pxBlockToInsert) { BlockLink_t *pxIterator; uint8_t *puc; /* Iterate through the list until a block is found that has a higher address * than the block being inserted. */ - for ( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) { + for (pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock) { /* Nothing to do here, just iterate to the right position. */ } /* Do the block being inserted, and the block it is being inserted after * make a contiguous block of memory? */ - puc = ( uint8_t * ) pxIterator; + puc = (uint8_t *)pxIterator; - if ( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) { + if ((puc + pxIterator->xBlockSize) == (uint8_t *)pxBlockToInsert) { pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; pxBlockToInsert = pxIterator; } else { @@ -316,10 +316,10 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) { /* Do the block being inserted, and the block it is being inserted before * make a contiguous block of memory? */ - puc = ( uint8_t * ) pxBlockToInsert; + puc = (uint8_t *)pxBlockToInsert; - if ( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) { - if ( pxIterator->pxNextFreeBlock != pxEnd ) { + if ((puc + pxBlockToInsert->xBlockSize) == (uint8_t *)pxIterator->pxNextFreeBlock) { + if (pxIterator->pxNextFreeBlock != pxEnd) { /* Form one big block from the two blocks. */ pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; @@ -334,7 +334,7 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) { * before and the block after, then it's pxNextFreeBlock pointer will have * already been set, and should not be set here as that would make it point * to itself. */ - if ( pxIterator != pxBlockToInsert ) { + if (pxIterator != pxBlockToInsert) { pxIterator->pxNextFreeBlock = pxBlockToInsert; } else { mtCOVERAGE_TEST_MARKER(); @@ -342,7 +342,7 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) { } /*-----------------------------------------------------------*/ -void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) { +void vPortDefineHeapRegions(const HeapRegion_t *const pxHeapRegions) { BlockLink_t *pxFirstFreeBlockInRegion = NULL, *pxPreviousFreeBlock; size_t xAlignedHeap; size_t xTotalRegionSize, xTotalHeapSize = 0; @@ -351,39 +351,39 @@ void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) { const HeapRegion_t *pxHeapRegion; /* Can only call once! */ - configASSERT( pxEnd == NULL ); + configASSERT(pxEnd == NULL); - pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); + pxHeapRegion = &(pxHeapRegions[xDefinedRegions]); - while ( pxHeapRegion->xSizeInBytes > 0 ) { + while (pxHeapRegion->xSizeInBytes > 0) { xTotalRegionSize = pxHeapRegion->xSizeInBytes; /* Ensure the heap region starts on a correctly aligned boundary. */ - xAddress = ( size_t ) pxHeapRegion->pucStartAddress; + xAddress = (size_t)pxHeapRegion->pucStartAddress; - if ( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) { - xAddress += ( portBYTE_ALIGNMENT - 1 ); + if ((xAddress & portBYTE_ALIGNMENT_MASK) != 0) { + xAddress += (portBYTE_ALIGNMENT - 1); xAddress &= ~portBYTE_ALIGNMENT_MASK; /* Adjust the size for the bytes lost to alignment. */ - xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress; + xTotalRegionSize -= xAddress - (size_t)pxHeapRegion->pucStartAddress; } xAlignedHeap = xAddress; /* Set xStart if it has not already been set. */ - if ( xDefinedRegions == 0 ) { + if (xDefinedRegions == 0) { /* xStart is used to hold a pointer to the first item in the list of * free blocks. The void cast is used to prevent compiler warnings. */ - xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap; - xStart.xBlockSize = ( size_t ) 0; + xStart.pxNextFreeBlock = (BlockLink_t *)xAlignedHeap; + xStart.xBlockSize = (size_t)0; } else { /* Should only get here if one region has already been added to the * heap. */ - configASSERT( pxEnd != NULL ); + configASSERT(pxEnd != NULL); /* Check blocks are passed in with increasing start addresses. */ - configASSERT( xAddress > ( size_t ) pxEnd ); + configASSERT(xAddress > (size_t)pxEnd); } /* Remember the location of the end marker in the previous region, if @@ -392,24 +392,24 @@ void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) { /* pxEnd is used to mark the end of the list of free blocks and is * inserted at the end of the region space. */ - xAddress = xAlignedHeap + xTotalRegionSize; + xAddress = xAlignedHeap + xTotalRegionSize; xAddress -= xHeapStructSize; xAddress &= ~portBYTE_ALIGNMENT_MASK; - pxEnd = ( BlockLink_t * ) xAddress; + pxEnd = (BlockLink_t *)xAddress; pxEnd->xBlockSize = 0; pxEnd->pxNextFreeBlock = NULL; /* To start with there is a single free block in this region that is * sized to take up the entire heap region minus the space taken by the * free block structure. */ - pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap; - pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion; + pxFirstFreeBlockInRegion = (BlockLink_t *)xAlignedHeap; + pxFirstFreeBlockInRegion->xBlockSize = xAddress - (size_t)pxFirstFreeBlockInRegion; pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd; /* If this is not the first region that makes up the entire heap space * then link the previous region to this region. */ - if ( pxPreviousFreeBlock != NULL ) { + if (pxPreviousFreeBlock != NULL) { pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion; } @@ -417,21 +417,21 @@ void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) { /* Move onto the next HeapRegion_t structure. */ xDefinedRegions++; - pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); + pxHeapRegion = &(pxHeapRegions[xDefinedRegions]); } xMinimumEverFreeBytesRemaining = xTotalHeapSize; xFreeBytesRemaining = xTotalHeapSize; /* Check something was actually defined before it is accessed. */ - configASSERT( xTotalHeapSize ); + configASSERT(xTotalHeapSize); /* Work out the position of the top bit in a size_t variable. */ - xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); + xBlockAllocatedBit = ((size_t)1) << ((sizeof(size_t) * heapBITS_PER_BYTE) - 1); } /*-----------------------------------------------------------*/ -void vPortGetHeapStats( HeapStats_t *pxHeapStats ) { +void vPortGetHeapStats(HeapStats_t *pxHeapStats) { BlockLink_t *pxBlock; size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */ @@ -441,21 +441,21 @@ void vPortGetHeapStats( HeapStats_t *pxHeapStats ) { /* pxBlock will be NULL if the heap has not been initialised. The heap * is initialised automatically when the first allocation is made. */ - if ( pxBlock != NULL ) { + if (pxBlock != NULL) { do { /* Increment the number of blocks and record the largest block seen * so far. */ xBlocks++; - if ( pxBlock->xBlockSize > xMaxSize ) { - xMaxSize = pxBlock->xBlockSize; + if (pxBlock->xBlockSize > xMaxSize) { + xMaxSize = pxBlock->xBlockSize; } /* Heap five will have a zero sized block at the end of each * each region - the block is only used to link to the next * heap region so it not a real block. */ - if ( pxBlock->xBlockSize != 0 ) { - if ( pxBlock->xBlockSize < xMinSize ) { + if (pxBlock->xBlockSize != 0) { + if (pxBlock->xBlockSize < xMinSize) { xMinSize = pxBlock->xBlockSize; } } @@ -463,10 +463,10 @@ void vPortGetHeapStats( HeapStats_t *pxHeapStats ) { /* Move to the next block in the chain until the last block is * reached. */ pxBlock = pxBlock->pxNextFreeBlock; - } while ( pxBlock != pxEnd ); + } while (pxBlock != pxEnd); } } - ( void ) xTaskResumeAll(); + (void)xTaskResumeAll(); pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize; pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize; diff --git a/source/Core/BSP/Pinecilv2/Pins.h b/source/Core/BSP/Pinecilv2/Pins.h index 6037c1f92..623245139 100644 --- a/source/Core/BSP/Pinecilv2/Pins.h +++ b/source/Core/BSP/Pinecilv2/Pins.h @@ -41,4 +41,11 @@ #define UART_TX_Pin GPIO_PIN_22 #define UART_RX_Pin GPIO_PIN_23 +#if defined(WS2812B_ENABLE) +// WS2812B mod using TP10 +#define WS2812B_Pin GPIO_PIN_12 +// WS2812B mod using TP9 is doable too, but harder to reach. Thanks @t3chguy +//#define WS2812B_Pin GPIO_PIN_14 +#endif + #endif /* BSP_PINE64_PINS_H_ */ diff --git a/source/Core/BSP/Pinecilv2/Setup.cpp b/source/Core/BSP/Pinecilv2/Setup.cpp index 120ba2371..26385a826 100644 --- a/source/Core/BSP/Pinecilv2/Setup.cpp +++ b/source/Core/BSP/Pinecilv2/Setup.cpp @@ -10,6 +10,7 @@ #include "FreeRTOSConfig.h" #include "IRQ.h" #include "Pins.h" +#include "bl702_dma.h" #include "bl702_sec_eng.h" #include "history.hpp" #include @@ -23,8 +24,8 @@ extern uint8_t _heap_start; extern uint8_t _heap_size; // @suppress("Type cannot be resolved") static HeapRegion_t xHeapRegions[] = { {&_heap_start, (unsigned int)&_heap_size}, - {NULL, 0}, /* Terminates the array. */ - {NULL, 0} /* Terminates the array. */ + { NULL, 0}, /* Terminates the array. */ + { NULL, 0} /* Terminates the array. */ }; // Functions @@ -50,9 +51,10 @@ void hardware_init() { gpio_set_mode(OLED_RESET_Pin, GPIO_OUTPUT_MODE); gpio_set_mode(KEY_A_Pin, GPIO_INPUT_PD_MODE); gpio_set_mode(KEY_B_Pin, GPIO_INPUT_PD_MODE); - gpio_set_mode(TMP36_INPUT_Pin, GPIO_INPUT_MODE); - gpio_set_mode(TIP_TEMP_Pin, GPIO_INPUT_MODE); - gpio_set_mode(VIN_Pin, GPIO_INPUT_MODE); + + gpio_set_mode(TMP36_INPUT_Pin, GPIO_HZ_MODE); + gpio_set_mode(TIP_TEMP_Pin, GPIO_HZ_MODE); + gpio_set_mode(VIN_Pin, GPIO_HZ_MODE); gpio_set_mode(TIP_RESISTANCE_SENSE, GPIO_OUTPUT_MODE); gpio_write(TIP_RESISTANCE_SENSE, 0); @@ -65,8 +67,10 @@ void hardware_init() { I2C_SetDeglitchCount(I2C0_ID, 1); // Turn on de-glitch // Note on I2C clock rate @ 100Khz the screen update == 20ms which is too long for USB-PD to work // 200kHz and above works + I2C_ClockSet(I2C0_ID, 300000); // Sets clock to around 25 kHz less than set here - TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_1, 0); + + TIMER_SetCompValue(TIMER_CH0, TIMER_COMP_ID_0, 0); } void setup_pwm(void) { // Setup PWM we use for driving the tip @@ -77,7 +81,7 @@ void setup_pwm(void) { PWM_POL_NORMAL, // Normal Polarity 60, // Clock Div 100, // Period - 0, // Thres 1 - start at beginng + 0, // Thres 1 - start at beginning 50, // Thres 2 - turn off at 50% 0, // Interrupt pulse count }; @@ -86,8 +90,8 @@ void setup_pwm(void) { PWM_Channel_Disable(PWM_Channel); } -const ADC_Chan_Type adc_tip_pos_chans[] - = {TIP_TEMP_ADC_CHANNEL, TMP36_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, VIN_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, TMP36_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, VIN_ADC_CHANNEL}; +const ADC_Chan_Type adc_tip_pos_chans[] = {TMP36_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, VIN_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, + TMP36_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL, VIN_ADC_CHANNEL, TIP_TEMP_ADC_CHANNEL}; const ADC_Chan_Type adc_tip_neg_chans[] = {ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND, ADC_CHAN_GND}; static_assert(sizeof(adc_tip_pos_chans) == sizeof(adc_tip_neg_chans)); @@ -96,21 +100,55 @@ void setup_adc(void) { ADC_CFG_Type adc_cfg = {}; ADC_FIFO_Cfg_Type adc_fifo_cfg = {}; - CPU_Interrupt_Disable(GPADC_DMA_IRQn); - - ADC_IntMask(ADC_INT_ALL, MASK); + // Please also see PR #1529 for even more context + + /* + A note on ADC settings + + The bl70x ADC seems to be very sensitive to various analog settings. + It has been a challenge to determine what is the most correct way to + configure it in order to get accurate readings that can be transformed + into millivolts, for accurate measurements. + + This latest set of ADC parameters, matches the latest configuration from + the upstream bl_mcu_sdk repository from commit hash: + 9e189b69cbc0a75ffa170f600a28820848d56432 + except for one difference. + (Note: bl_mcu_sdk has been heavily refactored since it has been imported into IronOS.) + + You can make it match exactly by defining ENABLE_MIC2_DIFF, see the code + #ifdef ENABLE_MIC2_DIFF below. + I have decided to not apply this change because it appeared to make the + lower end of the input less precise. + + Note that this configuration uses an ADC trimming value that is stored in the Efuse + of the bl70x chip. The actual reading is divided by this "coe" value. + We have found the following coe values on 3 different chips: + 0.9629, 0.9438, 0.9876 + + Additional note for posterity: + PGA = programmable gain amplifier. + We would have expected to achieve the highest accuracy by disabling this amplifier, + however we found that not to be the case, and in almost all cases we have found + that there is a scaling error compared to the ideal Vref. + The only other configuration we have found to be accurate was if we had: + PGA disabled + Vref=2V + biasSel=AON + without trimming from the efuse. + But we can't use it because a Vref=2V limits the higher end of temperature and voltage readings. + Also we don't know if this other configuration is really accurate on all chips, or only + happened to be accurate on the one chip on which it has been found. + */ adc_cfg.clkDiv = ADC_CLK_DIV_4; adc_cfg.vref = ADC_VREF_3P2V; adc_cfg.resWidth = ADC_DATA_WIDTH_14_WITH_16_AVERAGE; adc_cfg.inputMode = ADC_INPUT_SINGLE_END; - adc_cfg.v18Sel = ADC_V18_SEL_1P72V; + adc_cfg.v18Sel = ADC_V18_SEL_1P82V; adc_cfg.v11Sel = ADC_V11_SEL_1P1V; - adc_cfg.gain1 = ADC_PGA_GAIN_NONE; - adc_cfg.gain2 = ADC_PGA_GAIN_NONE; - adc_cfg.chopMode = ADC_CHOP_MOD_AZ_ON; + adc_cfg.gain1 = ADC_PGA_GAIN_1; + adc_cfg.gain2 = ADC_PGA_GAIN_1; + adc_cfg.chopMode = ADC_CHOP_MOD_AZ_PGA_ON; adc_cfg.biasSel = ADC_BIAS_SEL_MAIN_BANDGAP; - adc_cfg.vcm = ADC_PGA_VCM_1P6V; + adc_cfg.vcm = ADC_PGA_VCM_1P2V; adc_cfg.offsetCalibEn = DISABLE; adc_cfg.offsetCalibVal = 0; @@ -119,16 +157,32 @@ void setup_adc(void) { ADC_Reset(); ADC_Init(&adc_cfg); +#ifdef ENABLE_MIC2_DIFF + // This is the change that enables MIC2_DIFF, for now deciding not to enable it, since it seems to make results slightly worse + { + uint32_t tmpVal; + tmpVal = BL_RD_REG(AON_BASE, AON_GPADC_REG_CMD); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_GPADC_MIC2_DIFF, 1); + BL_WR_REG(AON_BASE, AON_GPADC_REG_CMD, tmpVal); + } +#endif + +#if 1 + // this sets the CVSP field (ADC conversion speed) + { + uint32_t regCfg2; + regCfg2 = BL_RD_REG(AON_BASE, AON_GPADC_REG_CONFIG2); + regCfg2 = BL_SET_REG_BITS_VAL(regCfg2, AON_GPADC_DLY_SEL, 0x02); + BL_WR_REG(AON_BASE, AON_GPADC_REG_CONFIG2, regCfg2); + } +#endif + adc_fifo_cfg.dmaEn = DISABLE; - adc_fifo_cfg.fifoThreshold = ADC_FIFO_THRESHOLD_8; // Triger FIFO when all 8 measurements are done + adc_fifo_cfg.fifoThreshold = ADC_FIFO_THRESHOLD_1; ADC_FIFO_Cfg(&adc_fifo_cfg); ADC_MIC_Bias_Disable(); ADC_Tsen_Disable(); - - // Enable FiFo IRQ - Interrupt_Handler_Register(GPADC_DMA_IRQn, adc_fifo_irq); - ADC_IntMask(ADC_INT_FIFO_READY, UNMASK); - CPU_Interrupt_Enable(GPADC_DMA_IRQn); + ADC_Gain_Trim(); ADC_Stop(); ADC_FIFO_Clear(); ADC_Scan_Channel_Config(adc_tip_pos_chans, adc_tip_neg_chans, sizeof(adc_tip_pos_chans) / sizeof(ADC_Chan_Type), DISABLE); @@ -143,10 +197,10 @@ void setup_timer_scheduler() { TIMER_PRELOAD_TRIG_COMP2, // Trigger; reset after trigger 0 TIMER_COUNT_PRELOAD, // Counter mode 22, // Clock div - (uint16_t)(powerPWM + holdoffTicks), // CH0 compare (adc) - (uint16_t)(powerPWM), // CH1 compare (pwm out) + (uint16_t)(powerPWM), // CH0 compare (pwm out) + (uint16_t)(powerPWM + holdoffTicks), // CH1 compare (adc) (uint16_t)(powerPWM + holdoffTicks + tempMeasureTicks), // CH2 compare end of cycle - 0, // Preload + 0, // Preload, copied to counter on trigger of comp2 }; TIMER_Init(&cfg); diff --git a/source/Core/BSP/Pinecilv2/ThermoModel.cpp b/source/Core/BSP/Pinecilv2/ThermoModel.cpp index 028a477b7..80889d948 100644 --- a/source/Core/BSP/Pinecilv2/ThermoModel.cpp +++ b/source/Core/BSP/Pinecilv2/ThermoModel.cpp @@ -5,7 +5,7 @@ * Author: Ralim */ #include "TipThermoModel.h" -#include "Utils.h" +#include "Utils.hpp" #include "configuration.h" #ifdef TEMP_uV_LOOKUP_HAKKO diff --git a/source/Core/BSP/Pinecilv2/bl_irq.c b/source/Core/BSP/Pinecilv2/bl_irq.c new file mode 100644 index 000000000..b8cda6f90 --- /dev/null +++ b/source/Core/BSP/Pinecilv2/bl_irq.c @@ -0,0 +1,29 @@ +#include "bl_irq.h" + +extern pFunc __Interrupt_Handlers[IRQn_LAST]; + +void bl_irq_enable(unsigned int source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIE + source) = 1; } + +void bl_irq_disable(unsigned int source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIE + source) = 0; } + +void bl_irq_pending_set(unsigned int source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIP + source) = 1; } + +void bl_irq_pending_clear(unsigned int source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIP + source) = 0; } + +void bl_irq_register(int irqnum, void *handler) { + if (irqnum < IRQn_LAST) { + __Interrupt_Handlers[irqnum] = handler; + } +} + +void bl_irq_unregister(int irqnum, void *handler) { + if (irqnum < IRQn_LAST) { + __Interrupt_Handlers[irqnum] = NULL; + } +} + +void bl_irq_handler_get(int irqnum, void **handler) { + if (irqnum < IRQn_LAST) { + *handler = __Interrupt_Handlers[irqnum]; + } +} diff --git a/source/Core/BSP/Pinecilv2/bl_irq.h b/source/Core/BSP/Pinecilv2/bl_irq.h new file mode 100644 index 000000000..5b79e2556 --- /dev/null +++ b/source/Core/BSP/Pinecilv2/bl_irq.h @@ -0,0 +1,19 @@ +#ifndef __BL_IRQ_H__ +#define __BL_IRQ_H__ + + +#include "bl702_glb.h" +#include "risc-v/Core/Include/clic.h" +#include "risc-v/Core/Include/riscv_encoding.h" + + +void bl_irq_enable(unsigned int source); +void bl_irq_disable(unsigned int source); +void bl_irq_pending_set(unsigned int source); +void bl_irq_pending_clear(unsigned int source); +void bl_irq_register(int irqnum, void *handler); +void bl_irq_unregister(int irqnum, void *handler); +void bl_irq_handler_get(int irqnum, void **handler); + + +#endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/ReleaseNotes b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/ReleaseNotes index e55bbfb87..9b4041e77 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/ReleaseNotes +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/ReleaseNotes @@ -3,6 +3,34 @@ bl mcu sdk Release Notes 此文件包含 bl mcu sdk 软件开发包的发行说明。 每个版本的文字说明与发布时的说明保持一致(可能会有错别字的勘误)。 +bl mcu sdk Release V1.4.4 +---------------------------- + +新增功能说明: + 1. 增加 adc dma, uart dma p2p, at client, tensorflow vww demo + 2. boot2 更新 + 3. 删除 timer basic 和 dac_from_flash demo + 4. 更新 bflb flash tool 到 1.7.1 + 5. ble lib 更新,使用 t-head 10.2 工具链构建(小于此工具链版本编译将报错) + +修复问题说明: + 1. 修正 dma 相关命令宏,重命名 DMA_BURST_xBYTE 防止误导 + 2. 修正 readme 中相关编译命令 + +bl mcu sdk Release V1.4.3 +---------------------------- + +新增功能说明: + 1. 增加 pikascript 和 mac154 组件 + 2. 增加 ble pds 的 demo + 3. doc 缓存文件移出 + 4. 增加 cklink 和 jlink 在 eclipse 中的调试 + +修复问题说明: + 1. driver 更新 + 2. Os to O2 + 3. uart sig 选定功能后,对与其他 sig 使用相同功能进行调整 + bl mcu sdk Release V1.4.2 ---------------------------- diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/bflb_platform.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/bflb_platform.c index 47aad724f..5f8cdface 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/bflb_platform.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/bflb_platform.c @@ -36,7 +36,8 @@ static uint8_t uart_dbg_disable = 0; struct heap_info mmheap_root; static struct heap_region system_mmheap[] = { - {NULL, 0}, {NULL, 0}, /* Terminates the array. */ + {NULL, 0}, + {NULL, 0}, /* Terminates the array. */ }; __WEAK__ void board_init(void) {} diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/cpp_new.cpp b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/cpp_new.cpp new file mode 100644 index 000000000..ba2f1e082 --- /dev/null +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/cpp_new.cpp @@ -0,0 +1,10 @@ +#include +#include + +void *operator new(size_t size) { return malloc(size); } + +void *operator new[](size_t size) { return malloc(size); } + +void operator delete(void *ptr) { free(ptr); } + +void operator delete[](void *ptr) { free(ptr); } \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/syscalls.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/syscalls.c index a87c44d55..6299cad80 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/syscalls.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/syscalls.c @@ -203,7 +203,8 @@ void *_sbrk_r(struct _reent *ptr, ptrdiff_t incr) { return NULL; } /* for exit() and abort() */ void __attribute__((noreturn)) _exit(int status) { - while (1) {} + while (1) { + } } void _system(const char *s) {} diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c deleted file mode 100644 index 9fe57a5ed..000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.c +++ /dev/null @@ -1,194 +0,0 @@ -/** - * @file uart_interface.c - * @brief - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ -#include "bflb_platform.h" -#include "hal_gpio.h" -#include "uart_interface.h" -#include "hal_usb.h" -#include "hal_dma.h" - -#define USB_OUT_RINGBUFFER_SIZE (8 * 1024) -#define UART_RX_RINGBUFFER_SIZE (8 * 1024) -#define UART_TX_DMA_SIZE (4095) - -uint8_t usb_rx_mem[USB_OUT_RINGBUFFER_SIZE] __attribute__((section(".system_ram"))); -uint8_t uart_rx_mem[UART_RX_RINGBUFFER_SIZE] __attribute__((section(".system_ram"))); - -uint8_t src_buffer[UART_TX_DMA_SIZE] __attribute__((section(".tcm_code"))); - -struct device *uart1; -struct device *dma_ch2; - -Ring_Buffer_Type usb_rx_rb; -Ring_Buffer_Type uart1_rx_rb; - -void uart_irq_callback(struct device *dev, void *args, uint32_t size, uint32_t state) -{ - if (state == UART_EVENT_RX_FIFO) { - if (size && size < Ring_Buffer_Get_Empty_Length(&uart1_rx_rb)) { - Ring_Buffer_Write(&uart1_rx_rb, (uint8_t *)args, size); - } else { - MSG("RF OV\r\n"); - } - } else if (state == UART_EVENT_RTO) { - if (size && size < Ring_Buffer_Get_Empty_Length(&uart1_rx_rb)) { - Ring_Buffer_Write(&uart1_rx_rb, (uint8_t *)args, size); - } else { - MSG("RTO OV\r\n"); - } - } else if (state == UART_RX_FER_IT) { - MSG("RX ERR\r\n"); - } -} -void uart1_init(void) -{ -#ifdef UART1_INDEX - uart_register(UART1_INDEX, "uart1"); - uart1 = device_find("uart1"); - - if (uart1) { - // device_open(uart1, DEVICE_OFLAG_DMA_TX | DEVICE_OFLAG_INT_RX); - // device_set_callback(uart1, uart_irq_callback); - // device_control(uart1, DEVICE_CTRL_SET_INT, (void *)(UART_RX_FIFO_IT | UART_RTO_IT)); - } - - dma_register(DMA0_CH2_INDEX, "ch2"); - dma_ch2 = device_find("ch2"); - - if (dma_ch2) { - DMA_DEV(dma_ch2)->direction = DMA_MEMORY_TO_PERIPH; - DMA_DEV(dma_ch2)->transfer_mode = DMA_LLI_ONCE_MODE; - DMA_DEV(dma_ch2)->src_req = DMA_REQUEST_NONE; - DMA_DEV(dma_ch2)->dst_req = DMA_REQUEST_UART1_TX; - DMA_DEV(dma_ch2)->src_addr_inc = DMA_ADDR_INCREMENT_ENABLE; - DMA_DEV(dma_ch2)->dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE; - DMA_DEV(dma_ch2)->src_burst_size = DMA_BURST_1BYTE; - DMA_DEV(dma_ch2)->dst_burst_size = DMA_BURST_1BYTE; - DMA_DEV(dma_ch2)->src_width = DMA_TRANSFER_WIDTH_8BIT; - DMA_DEV(dma_ch2)->dst_width = DMA_TRANSFER_WIDTH_8BIT; - device_open(dma_ch2, 0); - } -#endif -} - -void uart1_config(uint32_t baudrate, uart_databits_t databits, uart_parity_t parity, uart_stopbits_t stopbits) -{ - device_close(uart1); - UART_DEV(uart1)->baudrate = baudrate; - UART_DEV(uart1)->stopbits = stopbits; - UART_DEV(uart1)->parity = parity; - UART_DEV(uart1)->databits = (databits - 5); - device_open(uart1, DEVICE_OFLAG_DMA_TX | DEVICE_OFLAG_INT_RX); - device_set_callback(uart1, uart_irq_callback); - device_control(uart1, DEVICE_CTRL_SET_INT, (void *)(UART_RX_FIFO_IT | UART_RTO_IT)); - Ring_Buffer_Reset(&usb_rx_rb); - Ring_Buffer_Reset(&uart1_rx_rb); -} - -static uint8_t uart1_dtr; -static uint8_t uart1_rts; - -void uart1_set_dtr_rts(uint8_t dtr, uint8_t rts) -{ - uart1_dtr = dtr; - uart1_rts = rts; -} - -void uart1_dtr_init(void) -{ - gpio_set_mode(uart1_dtr, GPIO_OUTPUT_MODE); -} -void uart1_rts_init(void) -{ - gpio_set_mode(uart1_rts, GPIO_OUTPUT_MODE); -} -void uart1_dtr_deinit(void) -{ - gpio_set_mode(uart1_dtr, GPIO_INPUT_MODE); -} -void uart1_rts_deinit(void) -{ - gpio_set_mode(uart1_rts, GPIO_INPUT_MODE); -} -void dtr_pin_set(uint8_t status) -{ - gpio_write(uart1_dtr, status); -} -void rts_pin_set(uint8_t status) -{ - gpio_write(uart1_rts, status); -} -void ringbuffer_lock() -{ - cpu_global_irq_disable(); -} -void ringbuffer_unlock() -{ - cpu_global_irq_enable(); -} - -void uart_ringbuffer_init(void) -{ - /* init mem for ring_buffer */ - memset(usb_rx_mem, 0, USB_OUT_RINGBUFFER_SIZE); - memset(uart_rx_mem, 0, UART_RX_RINGBUFFER_SIZE); - - /* init ring_buffer */ - Ring_Buffer_Init(&usb_rx_rb, usb_rx_mem, USB_OUT_RINGBUFFER_SIZE, ringbuffer_lock, ringbuffer_unlock); - Ring_Buffer_Init(&uart1_rx_rb, uart_rx_mem, UART_RX_RINGBUFFER_SIZE, ringbuffer_lock, ringbuffer_unlock); -} - -static dma_control_data_t uart_dma_ctrl_cfg = { - .bits.fix_cnt = 0, - .bits.dst_min_mode = 0, - .bits.dst_add_mode = 0, - .bits.SI = 1, - .bits.DI = 0, - .bits.SWidth = DMA_TRANSFER_WIDTH_8BIT, - .bits.DWidth = DMA_TRANSFER_WIDTH_8BIT, - .bits.SBSize = 0, - .bits.DBSize = 0, - .bits.I = 0, - .bits.TransferSize = 4095 -}; -static dma_lli_ctrl_t uart_lli_list = { - .src_addr = (uint32_t)src_buffer, - .dst_addr = DMA_ADDR_UART1_TDR, - .nextlli = 0 -}; - -void uart_send_from_ringbuffer(void) -{ - if (Ring_Buffer_Get_Length(&usb_rx_rb)) { - if (!dma_channel_check_busy(dma_ch2)) { - uint32_t avalibleCnt = Ring_Buffer_Read(&usb_rx_rb, src_buffer, UART_TX_DMA_SIZE); - - if (avalibleCnt) { - dma_channel_stop(dma_ch2); - uart_dma_ctrl_cfg.bits.TransferSize = avalibleCnt; - memcpy(&uart_lli_list.cfg, &uart_dma_ctrl_cfg, sizeof(dma_control_data_t)); - dma_channel_update(dma_ch2, (void *)((uint32_t)&uart_lli_list)); - dma_channel_start(dma_ch2); - } - } - } -} \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.h deleted file mode 100644 index 46d5b0c20..000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/uart_interface.h +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @file uart_interface.h - * @brief - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ - -#ifndef __UART_IF_H__ -#define __UART_IF_H__ - -#include "hal_uart.h" -#include "ring_buffer.h" - -extern Ring_Buffer_Type usb_rx_rb; -extern Ring_Buffer_Type uart1_rx_rb; - -void uart1_init(void); -void uart1_config(uint32_t baudrate, uart_databits_t databits, uart_parity_t parity, uart_stopbits_t stopbits); -void uart1_set_dtr_rts(uint8_t dtr, uint8_t rts); -void uart1_dtr_init(void); -void uart1_rts_init(void); -void uart1_dtr_deinit(void); -void uart1_rts_deinit(void); -void dtr_pin_set(uint8_t status); -void rts_pin_set(uint8_t status); -void uart_ringbuffer_init(void); -void uart_send_from_ringbuffer(void); -#endif \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c deleted file mode 100644 index 60dffbd09..000000000 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/usb/usb_dc.c +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @file usb_dc.c - * @brief - * - * Copyright (c) 2021 Bouffalolab team - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - */ - -#include "hal_usb.h" -#include "stdbool.h" -#include "usbd_core.h" - -struct device *usb; - -#ifdef USB_INDEX -static void usb_dc_event_callback(struct device *dev, void *args, uint32_t size, uint32_t state) -{ - usbd_event_notify_handler(state, args); -} -#endif -struct device *usb_dc_init(void) -{ -#ifdef USB_INDEX - usb_dc_register(USB_INDEX, "usb"); - usb = device_find("usb"); - device_set_callback(usb, usb_dc_event_callback); - device_open(usb, 0); - return usb; -#endif - return NULL; -} - -int usbd_set_address(const uint8_t addr) -{ - return usb_dc_set_dev_address(addr); -} - -int usbd_ep_open(const struct usbd_endpoint_cfg *ep_cfg) -{ - return usb_dc_ep_open(usb, (const struct usb_dc_ep_cfg *)ep_cfg); -} -int usbd_ep_close(const uint8_t ep) -{ - return usb_dc_ep_close(ep); -} -int usbd_ep_set_stall(const uint8_t ep) -{ - return usb_dc_ep_set_stall(ep); -} -int usbd_ep_clear_stall(const uint8_t ep) -{ - return usb_dc_ep_clear_stall(ep); -} -int usbd_ep_is_stalled(const uint8_t ep, uint8_t *stalled) -{ - return usb_dc_ep_is_stalled(usb, ep, stalled); -} - -int usbd_ep_write(const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes) -{ - return usb_dc_ep_write(usb, ep, data, data_len, ret_bytes); -} - -int usbd_ep_read(const uint8_t ep, uint8_t *data, uint32_t max_data_len, uint32_t *read_bytes) -{ - return usb_dc_ep_read(usb, ep, data, max_data_len, read_bytes); -} diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/bl_math/arm_dsp_wrapper.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/bl_math/arm_dsp_wrapper.c index 05c627927..28c478c0c 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/bl_math/arm_dsp_wrapper.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/bl_math/arm_dsp_wrapper.c @@ -23,28 +23,27 @@ #include "arm_dsp_wrapper.h" -void arm_fill_f32(float32_t value, float32_t *pDst, uint32_t blockSize) -{ - uint32_t blkCnt = blockSize >> 2u; +void arm_fill_f32(float32_t value, float32_t *pDst, uint32_t blockSize) { + uint32_t blkCnt = blockSize >> 2u; - float32_t in1 = value; - float32_t in2 = value; - float32_t in3 = value; - float32_t in4 = value; + float32_t in1 = value; + float32_t in2 = value; + float32_t in3 = value; + float32_t in4 = value; - while (blkCnt > 0u) { - *pDst++ = in1; - *pDst++ = in2; - *pDst++ = in3; - *pDst++ = in4; + while (blkCnt > 0u) { + *pDst++ = in1; + *pDst++ = in2; + *pDst++ = in3; + *pDst++ = in4; - blkCnt--; - } + blkCnt--; + } - blkCnt = blockSize % 0x4u; + blkCnt = blockSize % 0x4u; - while (blkCnt > 0u) { - *pDst++ = value; - blkCnt--; - } + while (blkCnt > 0u) { + *pDst++ = value; + blkCnt--; + } } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/device/drv_device.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/device/drv_device.c index e02a83710..d3dc7330a 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/device/drv_device.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/device/drv_device.c @@ -38,10 +38,7 @@ dlist_t device_head = DLIST_OBJECT_INIT(device_head); * * @return device header */ -dlist_t *device_get_list_header(void) -{ - return &device_head; -} +dlist_t *device_get_list_header(void) { return &device_head; } /** * This function registers a device driver with specified name. @@ -52,25 +49,23 @@ dlist_t *device_get_list_header(void) * * @return the error code, DEVICE_EOK on initialization successfully. */ -int device_register(struct device *dev, const char *name) -{ - dlist_t *node; +int device_register(struct device *dev, const char *name) { + dlist_t *node; - dlist_for_each(node, &device_head) - { - struct device *dev_obj; - dev_obj = dlist_entry(node, struct device, list); + dlist_for_each(node, &device_head) { + struct device *dev_obj; + dev_obj = dlist_entry(node, struct device, list); - if (dev_obj == dev) { - return -DEVICE_EEXIST; - } + if (dev_obj == dev) { + return -DEVICE_EEXIST; } + } - strcpy(dev->name, name); + strcpy(dev->name, name); - dlist_insert_after(&device_head, &(dev->list)); - dev->status = DEVICE_REGISTERED; - return DEVICE_EOK; + dlist_insert_after(&device_head, &(dev->list)); + dev->status = DEVICE_REGISTERED; + return DEVICE_EOK; } /** @@ -82,17 +77,16 @@ int device_register(struct device *dev, const char *name) * * @return the error code, DEVICE_EOK on initialization successfully. */ -int device_unregister(const char *name) -{ - struct device *dev = device_find(name); +int device_unregister(const char *name) { + struct device *dev = device_find(name); - if (!dev) { - return -DEVICE_ENODEV; - } - dev->status = DEVICE_UNREGISTER; - /* remove from old list */ - dlist_remove(&(dev->list)); - return DEVICE_EOK; + if (!dev) { + return -DEVICE_ENODEV; + } + dev->status = DEVICE_UNREGISTER; + /* remove from old list */ + dlist_remove(&(dev->list)); + return DEVICE_EOK; } /** @@ -102,20 +96,18 @@ int device_unregister(const char *name) * * @return the registered device driver on successful, or NULL on failure. */ -struct device *device_find(const char *name) -{ - struct device *dev; - dlist_t *node; +struct device *device_find(const char *name) { + struct device *dev; + dlist_t *node; - dlist_for_each(node, &device_head) - { - dev = dlist_entry(node, struct device, list); + dlist_for_each(node, &device_head) { + dev = dlist_entry(node, struct device, list); - if (strncmp(dev->name, name, DEVICE_NAME_MAX) == 0) { - return dev; - } + if (strncmp(dev->name, name, DEVICE_NAME_MAX) == 0) { + return dev; } - return NULL; + } + return NULL; } /** @@ -126,26 +118,25 @@ struct device *device_find(const char *name) * * @return the result */ -int device_open(struct device *dev, uint16_t oflag) -{ +int device_open(struct device *dev, uint16_t oflag) { #ifdef DEVICE_CHECK_PARAM - int retval = DEVICE_EOK; + int retval = DEVICE_EOK; - if ((dev->status == DEVICE_REGISTERED) || (dev->status == DEVICE_CLOSED)) { - if (dev_open != NULL) { - retval = dev_open(dev, oflag); - dev->status = DEVICE_OPENED; - dev->oflag |= oflag; - } else { - retval = -DEVICE_EFAULT; - } + if ((dev->status == DEVICE_REGISTERED) || (dev->status == DEVICE_CLOSED)) { + if (dev_open != NULL) { + retval = dev_open(dev, oflag); + dev->status = DEVICE_OPENED; + dev->oflag |= oflag; } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; #else - return dev_open(dev, oflag); + return dev_open(dev, oflag); #endif } /** @@ -155,26 +146,25 @@ int device_open(struct device *dev, uint16_t oflag) * * @return the result */ -int device_close(struct device *dev) -{ +int device_close(struct device *dev) { #ifdef DEVICE_CHECK_PARAM - int retval = DEVICE_EOK; + int retval = DEVICE_EOK; - if (dev->status == DEVICE_OPENED) { - if (dev_close != NULL) { - retval = dev_close(dev); - dev->status = DEVICE_CLOSED; - dev->oflag = 0; - } else { - retval = -DEVICE_EFAULT; - } + if (dev->status == DEVICE_OPENED) { + if (dev_close != NULL) { + retval = dev_close(dev); + dev->status = DEVICE_CLOSED; + dev->oflag = 0; } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; #else - return dev_close(dev); + return dev_close(dev); #endif } /** @@ -186,24 +176,23 @@ int device_close(struct device *dev) * * @return the result */ -int device_control(struct device *dev, int cmd, void *args) -{ +int device_control(struct device *dev, int cmd, void *args) { #ifdef DEVICE_CHECK_PARAM - int retval = DEVICE_EOK; + int retval = DEVICE_EOK; - if (dev->status > DEVICE_UNREGISTER) { - if (dev_control != NULL) { - retval = dev_control(dev, cmd, args); - } else { - retval = -DEVICE_EFAULT; - } + if (dev->status > DEVICE_UNREGISTER) { + if (dev_control != NULL) { + retval = dev_control(dev, cmd, args); } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; #else - return dev_control(dev, cmd, args); + return dev_control(dev, cmd, args); #endif } /** @@ -216,24 +205,23 @@ int device_control(struct device *dev, int cmd, void *args) * * @return the actually written size on successful, otherwise negative returned. */ -int device_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) -{ +int device_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) { #ifdef DEVICE_CHECK_PARAM - int retval = DEVICE_EOK; + int retval = DEVICE_EOK; - if (dev->status == DEVICE_OPENED) { - if (dev_write != NULL) { - retval = dev_write(dev, pos, buffer, size); - } else { - retval = -DEVICE_EFAULT; - } + if (dev->status == DEVICE_OPENED) { + if (dev_write != NULL) { + retval = dev_write(dev, pos, buffer, size); } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; #else - return dev_write(dev, pos, buffer, size); + return dev_write(dev, pos, buffer, size); #endif } /** @@ -246,24 +234,23 @@ int device_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t * * @return the actually read size on successful, otherwise negative returned. */ -int device_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) -{ +int device_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) { #ifdef DEVICE_CHECK_PARAM - int retval = DEVICE_EOK; + int retval = DEVICE_EOK; - if (dev->status == DEVICE_OPENED) { - if (dev_read != NULL) { - retval = dev_read(dev, pos, buffer, size); - } else { - retval = -DEVICE_EFAULT; - } + if (dev->status == DEVICE_OPENED) { + if (dev_read != NULL) { + retval = dev_read(dev, pos, buffer, size); } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; #else - return dev_read(dev, pos, buffer, size); + return dev_read(dev, pos, buffer, size); #endif } /** @@ -276,19 +263,18 @@ int device_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) * * @return the actually read size on successful, otherwise negative returned. */ -int device_set_callback(struct device *dev, void (*callback)(struct device *dev, void *args, uint32_t size, uint32_t event)) -{ - int retval = DEVICE_EOK; +int device_set_callback(struct device *dev, void (*callback)(struct device *dev, void *args, uint32_t size, uint32_t event)) { + int retval = DEVICE_EOK; - if (dev->status > DEVICE_UNREGISTER) { - if (callback != NULL) { - dev->callback = callback; - } else { - retval = -DEVICE_EFAULT; - } + if (dev->status > DEVICE_UNREGISTER) { + if (callback != NULL) { + dev->callback = callback; } else { - retval = -DEVICE_EINVAL; + retval = -DEVICE_EFAULT; } + } else { + retval = -DEVICE_EINVAL; + } - return retval; + return retval; } \ No newline at end of file diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/compiler/common.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/compiler/common.h index c72036f94..7bed6f276 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/compiler/common.h +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/compiler/common.h @@ -12,12 +12,12 @@ #define BL_WR_BYTE(addr, val) ((*(volatile uint8_t *)(uintptr_t)(addr)) = (val)) #define BL_RDWD_FRM_BYTEP(p) ((p[3] << 24) | (p[2] << 16) | (p[1] << 8) | (p[0])) -#define BL_WRWD_TO_BYTEP(p, val) \ - { \ - p[0] = val & 0xff; \ - p[1] = (val >> 8) & 0xff; \ - p[2] = (val >> 16) & 0xff; \ - p[3] = (val >> 24) & 0xff; \ +#define BL_WRWD_TO_BYTEP(p, val) \ + { \ + p[0] = val & 0xff; \ + p[1] = (val >> 8) & 0xff; \ + p[2] = (val >> 16) & 0xff; \ + p[3] = (val >> 24) & 0xff; \ } /** * @brief Register access macro @@ -27,29 +27,29 @@ #define BL_RD_REG(addr, regname) BL_RD_WORD(addr + regname##_OFFSET) #define BL_WR_REG(addr, regname, val) BL_WR_WORD(addr + regname##_OFFSET, val) #define BL_SET_REG_BIT(val, bitname) ((val) | (1U << bitname##_POS)) -#define BL_CLR_REG_BIT(val, bitname) ((val)&bitname##_UMSK) -#define BL_GET_REG_BITS_VAL(val, bitname) (((val)&bitname##_MSK) >> bitname##_POS) -#define BL_SET_REG_BITS_VAL(val, bitname, bitval) (((val)&bitname##_UMSK) | ((uint32_t)(bitval) << bitname##_POS)) +#define BL_CLR_REG_BIT(val, bitname) ((val) & bitname##_UMSK) +#define BL_GET_REG_BITS_VAL(val, bitname) (((val) & bitname##_MSK) >> bitname##_POS) +#define BL_SET_REG_BITS_VAL(val, bitname, bitval) (((val) & bitname##_UMSK) | ((uint32_t)(bitval) << bitname##_POS)) #define BL_IS_REG_BIT_SET(val, bitname) (((val) & (1U << (bitname##_POS))) != 0) -#define BL_DRV_DUMMY \ - { \ - __ASM volatile("nop"); \ - __ASM volatile("nop"); \ - __ASM volatile("nop"); \ - __ASM volatile("nop"); \ +#define BL_DRV_DUMMY \ + { \ + __ASM volatile("nop"); \ + __ASM volatile("nop"); \ + __ASM volatile("nop"); \ + __ASM volatile("nop"); \ } /* Std driver attribute macro*/ #ifndef BFLB_USE_CUSTOM_LD_SECTIONS // #define ATTR_UNI_SYMBOL -#define ATTR_STRINGIFY(x) #x -#define ATTR_TOSTRING(x) ATTR_STRINGIFY(x) -#define ATTR_UNI_SYMBOL __FILE__ ATTR_TOSTRING(__LINE__) -#define ATTR_CLOCK_SECTION __attribute__((section(".sclock_rlt_code." ATTR_UNI_SYMBOL))) -#define ATTR_CLOCK_CONST_SECTION __attribute__((section(".sclock_rlt_const." ATTR_UNI_SYMBOL))) -#define ATTR_TCM_SECTION __attribute__((section(".tcm_code." ATTR_UNI_SYMBOL))) -#define ATTR_TCM_CONST_SECTION __attribute__((section(".tcm_const." ATTR_UNI_SYMBOL))) -// #define ATTR_DTCM_SECTION __attribute__((section(".tcm_data"))) +#define ATTR_STRINGIFY(x) #x +#define ATTR_TOSTRING(x) ATTR_STRINGIFY(x) +#define ATTR_UNI_SYMBOL __FILE__ ATTR_TOSTRING(__LINE__) +#define ATTR_CLOCK_SECTION __attribute__((section(".sclock_rlt_code." ATTR_UNI_SYMBOL))) +#define ATTR_CLOCK_CONST_SECTION __attribute__((section(".sclock_rlt_const." ATTR_UNI_SYMBOL))) +#define ATTR_TCM_SECTION __attribute__((section(".tcm_code." ATTR_UNI_SYMBOL))) +#define ATTR_TCM_CONST_SECTION __attribute__((section(".tcm_const." ATTR_UNI_SYMBOL))) +#define ATTR_DTCM_SECTION __attribute__((section(".tcm_data"))) #define ATTR_HSRAM_SECTION __attribute__((section(".hsram_code"))) #define ATTR_DMA_RAM_SECTION __attribute__((section(".system_ram"))) #define ATTR_NOCACHE_RAM_SECTION __attribute__((section(".nocache_ram"))) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c index 3292a6835..92699a504 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c @@ -24,208 +24,199 @@ #ifndef BFLB_USE_ROM_DRIVER /****************************************************************************/ /** - * @brief Char memcpy - * - * @param dst: Destination - * @param src: Source - * @param n: Count of char - * - * @return Destination pointer - * - *******************************************************************************/ -__WEAK__ void *ATTR_TCM_SECTION arch_memcpy(void *dst, const void *src, uint32_t n) -{ - const uint8_t *p = src; - uint8_t *q = dst; - - while (n--) { - *q++ = *p++; - } - - return dst; + * @brief Char memcpy + * + * @param dst: Destination + * @param src: Source + * @param n: Count of char + * + * @return Destination pointer + * + *******************************************************************************/ +__WEAK__ void *ATTR_TCM_SECTION arch_memcpy(void *dst, const void *src, uint32_t n) { + const uint8_t *p = src; + uint8_t *q = dst; + + while (n--) { + *q++ = *p++; + } + + return dst; } /****************************************************************************/ /** - * @brief Word memcpy - * - * @param dst: Destination - * @param src: Source - * @param n: Count of words - * - * @return Destination pointer - * - *******************************************************************************/ -__WEAK__ uint32_t *ATTR_TCM_SECTION arch_memcpy4(uint32_t *dst, const uint32_t *src, uint32_t n) -{ - const uint32_t *p = src; - uint32_t *q = dst; - - while (n--) { - *q++ = *p++; - } - - return dst; + * @brief Word memcpy + * + * @param dst: Destination + * @param src: Source + * @param n: Count of words + * + * @return Destination pointer + * + *******************************************************************************/ +__WEAK__ uint32_t *ATTR_TCM_SECTION arch_memcpy4(uint32_t *dst, const uint32_t *src, uint32_t n) { + const uint32_t *p = src; + uint32_t *q = dst; + + while (n--) { + *q++ = *p++; + } + + return dst; } /****************************************************************************/ /** - * @brief Fast memcpy - * - * @param dst: Destination - * @param src: Source - * @param n: Count of bytes - * - * @return Destination pointer - * - *******************************************************************************/ -__WEAK__ void *ATTR_TCM_SECTION arch_memcpy_fast(void *pdst, const void *psrc, uint32_t n) -{ - uint32_t left, done, i = 0; - uint8_t *dst = (uint8_t *)pdst; - uint8_t *src = (uint8_t *)psrc; - - if (((uint32_t)(uintptr_t)dst & 0x3) == 0 && ((uint32_t)(uintptr_t)src & 0x3) == 0) { - arch_memcpy4((uint32_t *)dst, (const uint32_t *)src, n >> 2); - left = n % 4; - done = n - left; - - while (i < left) { - dst[done + i] = src[done + i]; - i++; - } - } else { - arch_memcpy(dst, src, n); + * @brief Fast memcpy + * + * @param dst: Destination + * @param src: Source + * @param n: Count of bytes + * + * @return Destination pointer + * + *******************************************************************************/ +__WEAK__ void *ATTR_TCM_SECTION arch_memcpy_fast(void *pdst, const void *psrc, uint32_t n) { + uint32_t left, done, i = 0; + uint8_t *dst = (uint8_t *)pdst; + uint8_t *src = (uint8_t *)psrc; + + if (((uint32_t)(uintptr_t)dst & 0x3) == 0 && ((uint32_t)(uintptr_t)src & 0x3) == 0) { + arch_memcpy4((uint32_t *)dst, (const uint32_t *)src, n >> 2); + left = n % 4; + done = n - left; + + while (i < left) { + dst[done + i] = src[done + i]; + i++; } + } else { + arch_memcpy(dst, src, n); + } - return dst; + return dst; } /****************************************************************************/ /** - * @brief char memset - * - * @param dst: Destination - * @param val: Value to set - * @param n: Count of char - * - * @return Destination pointer - * - *******************************************************************************/ -__WEAK__ void *ATTR_TCM_SECTION arch_memset(void *s, uint8_t c, uint32_t n) -{ - uint8_t *p = (uint8_t *)s; - - while (n > 0) { - *p++ = (uint8_t)c; - --n; - } - - return s; + * @brief char memset + * + * @param dst: Destination + * @param val: Value to set + * @param n: Count of char + * + * @return Destination pointer + * + *******************************************************************************/ +__WEAK__ void *ATTR_TCM_SECTION arch_memset(void *s, uint8_t c, uint32_t n) { + uint8_t *p = (uint8_t *)s; + + while (n > 0) { + *p++ = (uint8_t)c; + --n; + } + + return s; } /****************************************************************************/ /** - * @brief Word memset - * - * @param dst: Destination - * @param val: Value to set - * @param n: Count of words - * - * @return Destination pointer - * - *******************************************************************************/ -__WEAK__ uint32_t *ATTR_TCM_SECTION arch_memset4(uint32_t *dst, const uint32_t val, uint32_t n) -{ - uint32_t *q = dst; - - while (n--) { - *q++ = val; - } - - return dst; + * @brief Word memset + * + * @param dst: Destination + * @param val: Value to set + * @param n: Count of words + * + * @return Destination pointer + * + *******************************************************************************/ +__WEAK__ uint32_t *ATTR_TCM_SECTION arch_memset4(uint32_t *dst, const uint32_t val, uint32_t n) { + uint32_t *q = dst; + + while (n--) { + *q++ = val; + } + + return dst; } /****************************************************************************/ /** - * @brief string compare - * - * @param s1: string 1 - * @param s2: string 2 - * @param n: Count of chars - * - * @return compare result - * - *******************************************************************************/ -__WEAK__ int ATTR_TCM_SECTION arch_memcmp(const void *s1, const void *s2, uint32_t n) -{ - const unsigned char *c1 = s1, *c2 = s2; - int d = 0; - - while (n--) { - d = (int)*c1++ - (int)*c2++; - - if (d) { - break; - } + * @brief string compare + * + * @param s1: string 1 + * @param s2: string 2 + * @param n: Count of chars + * + * @return compare result + * + *******************************************************************************/ +__WEAK__ int ATTR_TCM_SECTION arch_memcmp(const void *s1, const void *s2, uint32_t n) { + const unsigned char *c1 = s1, *c2 = s2; + int d = 0; + + while (n--) { + d = (int)*c1++ - (int)*c2++; + + if (d) { + break; } + } - return d; + return d; } #endif -void memcopy_to_fifo(void *fifo_addr, uint8_t *data, uint32_t length) -{ - uint8_t *p = (uint8_t *)fifo_addr; - uint8_t *q = data; +void memcopy_to_fifo(void *fifo_addr, uint8_t *data, uint32_t length) { + uint8_t *p = (uint8_t *)fifo_addr; + uint8_t *q = data; - while (length--) { - *p = *q++; - } + while (length--) { + *p = *q++; + } } -void fifocopy_to_mem(void *fifo_addr, uint8_t *data, uint32_t length) -{ - uint8_t *p = (uint8_t *)fifo_addr; - uint8_t *q = data; +void fifocopy_to_mem(void *fifo_addr, uint8_t *data, uint32_t length) { + uint8_t *p = (uint8_t *)fifo_addr; + uint8_t *q = data; - while (length--) { - *q++ = *p; - } + while (length--) { + *q++ = *p; + } } /****************************************************************************/ /** - * @brief get u64 first number 1 from right to left - * - * @param val: target value - * @param bit: first 1 in bit - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -int arch_ffsll(uint64_t *val, uint32_t *bit) -{ - if (!*val) { - return ERROR; - } - - *bit = __builtin_ffsll(*val) - 1; - *val &= ~((1ULL) << (*bit)); - return 0; + * @brief get u64 first number 1 from right to left + * + * @param val: target value + * @param bit: first 1 in bit + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +int arch_ffsll(uint64_t *val, uint32_t *bit) { + if (!*val) { + return ERROR; + } + + *bit = __builtin_ffsll(*val) - 1; + *val &= ~((1ULL) << (*bit)); + return 0; } -int arch_ctzll(uint64_t *val, uint32_t *bit) -{ - if (!*val) - return -1; +int arch_ctzll(uint64_t *val, uint32_t *bit) { + if (!*val) { + return -1; + } - *bit = __builtin_ctzll(*val); - *val &= ~((1ULL) << (*bit)); - return 0; + *bit = __builtin_ctzll(*val); + *val &= ~((1ULL) << (*bit)); + return 0; } -int arch_clzll(uint64_t *val, uint32_t *bit) -{ - if (!*val) - return -1; +int arch_clzll(uint64_t *val, uint32_t *bit) { + if (!*val) { + return -1; + } - *bit = __builtin_clzll(*val); - *val &= ~((1ULL) << (*bit)); - return 0; + *bit = __builtin_clzll(*val); + *val &= ~((1ULL) << (*bit)); + return 0; } #ifdef DEBUG @@ -238,11 +229,10 @@ int arch_clzll(uint64_t *val, uint32_t *bit) * @return None *******************************************************************************/ -void check_failed(uint8_t *file, uint32_t line) -{ - /* Infinite loop */ - while (1) - ; +void check_failed(uint8_t *file, uint32_t line) { + /* Infinite loop */ + while (1) { + } } #endif /* DEBUG */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/partition/partition.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/partition/partition.c index 673dcbe88..a96f0b593 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/partition/partition.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/partition/partition.c @@ -1,42 +1,42 @@ /** - ****************************************************************************** - * @file partition.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2019 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file partition.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2019 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "partition.h" -#include "softcrc.h" #include "bflb_platform.h" +#include "softcrc.h" /** @addtogroup BFLB_Common_Driver * @{ @@ -61,9 +61,9 @@ /** @defgroup PARTITION_Private_Variables * @{ */ -p_pt_table_flash_erase gp_pt_table_flash_erase = NULL; -p_pt_table_flash_write gp_pt_table_flash_write = NULL; -p_pt_table_flash_read gp_pt_table_flash_read = NULL; +p_pt_table_flash_erase gp_pt_table_flash_erase = NULL; +p_pt_table_flash_write gp_pt_table_flash_write = NULL; +p_pt_table_flash_read gp_pt_table_flash_read = NULL; pt_table_iap_param_type p_iap_param; /*@} end of group PARTITION_Private_Variables */ @@ -86,44 +86,42 @@ extern int main(void); */ /****************************************************************************/ /** - * @brief Judge partition table valid - * - * @param ptStuff: Partition table stuff pointer - * - * @return 0 for invalid and 1 for valid - * -*******************************************************************************/ -static uint8_t pt_table_valid(pt_table_stuff_config *pt_stuff) -{ - pt_table_config *pt_table = &pt_stuff->pt_table; - pt_table_entry_config *pt_entries = pt_stuff->pt_entries; - uint32_t *p_crc32; - uint32_t entriesLen = sizeof(pt_table_entry_config) * pt_table->entryCnt; - - if (pt_table->magicCode == BFLB_PT_MAGIC_CODE) { - if (pt_table->entryCnt > PT_ENTRY_MAX) { - MSG("PT Entry Count Error\r\n"); - return 0; - } - - if (pt_table->crc32 != - BFLB_Soft_CRC32((uint8_t *)pt_table, sizeof(pt_table_config) - 4)) { - MSG("PT CRC Error\r\n"); - return 0; - } - - /* ToDo it is a trap here, when entryCnt > 8, crc32 will overflow, comment by zhangcheng */ - p_crc32 = (uint32_t *)((uintptr_t)pt_entries + entriesLen); - - if (*p_crc32 != BFLB_Soft_CRC32((uint8_t *)pt_entries, entriesLen)) { - MSG("PT Entry CRC Error\r\n"); - return 0; - } - - return 1; + * @brief Judge partition table valid + * + * @param ptStuff: Partition table stuff pointer + * + * @return 0 for invalid and 1 for valid + * + *******************************************************************************/ +static uint8_t pt_table_valid(pt_table_stuff_config *pt_stuff) { + pt_table_config *pt_table = &pt_stuff->pt_table; + pt_table_entry_config *pt_entries = pt_stuff->pt_entries; + uint32_t *p_crc32; + uint32_t entriesLen = sizeof(pt_table_entry_config) * pt_table->entryCnt; + + if (pt_table->magicCode == BFLB_PT_MAGIC_CODE) { + if (pt_table->entryCnt > PT_ENTRY_MAX) { + MSG("PT Entry Count Error\r\n"); + return 0; } - return 0; + if (pt_table->crc32 != BFLB_Soft_CRC32((uint8_t *)pt_table, sizeof(pt_table_config) - 4)) { + MSG("PT CRC Error\r\n"); + return 0; + } + + /* ToDo it is a trap here, when entryCnt > 8, crc32 will overflow, comment by zhangcheng */ + p_crc32 = (uint32_t *)((uintptr_t)pt_entries + entriesLen); + + if (*p_crc32 != BFLB_Soft_CRC32((uint8_t *)pt_entries, entriesLen)) { + MSG("PT Entry CRC Error\r\n"); + return 0; + } + + return 1; + } + + return 0; } /*@} end of group PARTITION_Private_Functions */ @@ -133,408 +131,392 @@ static uint8_t pt_table_valid(pt_table_stuff_config *pt_stuff) */ /****************************************************************************/ /** - * @brief Register partition flash read write erase fucntion - * - * @param erase: Flash erase function - * @param write: Flash write function - * @param read: Flash read function - * - * @return None - * -*******************************************************************************/ -void pt_table_set_flash_operation(p_pt_table_flash_erase erase, p_pt_table_flash_write write, p_pt_table_flash_read read) -{ - gp_pt_table_flash_erase = erase; - gp_pt_table_flash_write = write; - gp_pt_table_flash_read = read; + * @brief Register partition flash read write erase fucntion + * + * @param erase: Flash erase function + * @param write: Flash write function + * @param read: Flash read function + * + * @return None + * + *******************************************************************************/ +void pt_table_set_flash_operation(p_pt_table_flash_erase erase, p_pt_table_flash_write write, p_pt_table_flash_read read) { + gp_pt_table_flash_erase = erase; + gp_pt_table_flash_write = write; + gp_pt_table_flash_read = read; } /****************************************************************************/ /** - * @brief Get active partition table whole stuff - * - * @param ptStuff[2]: Partition table stuff pointer - * - * @return Active partition table ID - * -*******************************************************************************/ -pt_table_id_type pt_table_get_active_partition_need_lock(pt_table_stuff_config ptStuff[2]) -{ - uint32_t pt_valid[2] = { 0, 0 }; - pt_table_id_type activePtID; - - if (ptStuff == NULL) { - return PT_TABLE_ID_INVALID; - } - - activePtID = PT_TABLE_ID_INVALID; - - gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&ptStuff[0], sizeof(pt_table_stuff_config)); - pt_valid[0] = pt_table_valid(&ptStuff[0]); - - gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&ptStuff[1], sizeof(pt_table_stuff_config)); - pt_valid[1] = pt_table_valid(&ptStuff[1]); - - if (pt_valid[0] == 1 && pt_valid[1] == 1) { - if (ptStuff[0].pt_table.age >= ptStuff[1].pt_table.age) { - activePtID = PT_TABLE_ID_0; - } else { - activePtID = PT_TABLE_ID_1; - } - } else if (pt_valid[0] == 1) { - activePtID = PT_TABLE_ID_0; - } else if (pt_valid[1] == 1) { - activePtID = PT_TABLE_ID_1; + * @brief Get active partition table whole stuff + * + * @param ptStuff[2]: Partition table stuff pointer + * + * @return Active partition table ID + * + *******************************************************************************/ +pt_table_id_type pt_table_get_active_partition_need_lock(pt_table_stuff_config ptStuff[2]) { + uint32_t pt_valid[2] = {0, 0}; + pt_table_id_type activePtID; + + if (ptStuff == NULL) { + return PT_TABLE_ID_INVALID; + } + + activePtID = PT_TABLE_ID_INVALID; + + gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&ptStuff[0], sizeof(pt_table_stuff_config)); + pt_valid[0] = pt_table_valid(&ptStuff[0]); + + gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&ptStuff[1], sizeof(pt_table_stuff_config)); + pt_valid[1] = pt_table_valid(&ptStuff[1]); + + if (pt_valid[0] == 1 && pt_valid[1] == 1) { + if (ptStuff[0].pt_table.age >= ptStuff[1].pt_table.age) { + activePtID = PT_TABLE_ID_0; + } else { + activePtID = PT_TABLE_ID_1; } + } else if (pt_valid[0] == 1) { + activePtID = PT_TABLE_ID_0; + } else if (pt_valid[1] == 1) { + activePtID = PT_TABLE_ID_1; + } - return activePtID; + return activePtID; } /****************************************************************************/ /** - * @brief Get partition entry according to entry ID - * - * @param ptStuff: Partition table stuff pointer - * @param type: Type of partition entry - * @param ptEntry: Partition entry pointer to store read data - * - * @return PT_ERROR_SUCCESS or PT_ERROR_ENTRY_NOT_FOUND or PT_ERROR_PARAMETER - * -*******************************************************************************/ -pt_table_error_type pt_table_get_active_entries_by_id(pt_table_stuff_config *pt_stuff, - pt_table_entry_type type, - pt_table_entry_config *pt_entry) -{ - uint32_t i = 0; - - if (pt_stuff == NULL || pt_entry == NULL) { - return PT_ERROR_PARAMETER; - } - - for (i = 0; i < pt_stuff->pt_table.entryCnt; i++) { - if (pt_stuff->pt_entries[i].type == type) { - ARCH_MemCpy_Fast(pt_entry, &pt_stuff->pt_entries[i], sizeof(pt_table_entry_config)); - return PT_ERROR_SUCCESS; - } + * @brief Get partition entry according to entry ID + * + * @param ptStuff: Partition table stuff pointer + * @param type: Type of partition entry + * @param ptEntry: Partition entry pointer to store read data + * + * @return PT_ERROR_SUCCESS or PT_ERROR_ENTRY_NOT_FOUND or PT_ERROR_PARAMETER + * + *******************************************************************************/ +pt_table_error_type pt_table_get_active_entries_by_id(pt_table_stuff_config *pt_stuff, pt_table_entry_type type, pt_table_entry_config *pt_entry) { + uint32_t i = 0; + + if (pt_stuff == NULL || pt_entry == NULL) { + return PT_ERROR_PARAMETER; + } + + for (i = 0; i < pt_stuff->pt_table.entryCnt; i++) { + if (pt_stuff->pt_entries[i].type == type) { + ARCH_MemCpy_Fast(pt_entry, &pt_stuff->pt_entries[i], sizeof(pt_table_entry_config)); + return PT_ERROR_SUCCESS; } + } - return PT_ERROR_ENTRY_NOT_FOUND; + return PT_ERROR_ENTRY_NOT_FOUND; } /****************************************************************************/ /** - * @brief Get partition entry according to entry name - * - * @param ptStuff: Partition table stuff pointer - * @param name: Name of partition entry - * @param ptEntry: Partition entry pointer to store read data - * - * @return PT_ERROR_SUCCESS or PT_ERROR_ENTRY_NOT_FOUND or PT_ERROR_PARAMETER - * -*******************************************************************************/ -pt_table_error_type pt_table_get_active_entries_by_name(pt_table_stuff_config *pt_stuff, - uint8_t *name, - pt_table_entry_config *pt_entry) -{ - uint32_t i = 0; - uint32_t len = strlen((char *)name); - - if (pt_stuff == NULL || pt_entry == NULL) { - return PT_ERROR_PARAMETER; - } - - for (i = 0; i < pt_stuff->pt_table.entryCnt; i++) { - if (strlen((char *)pt_stuff->pt_entries[i].name) == len && - memcmp((char *)pt_stuff->pt_entries[i].name, (char *)name, len) == 0) { - ARCH_MemCpy_Fast(pt_entry, &pt_stuff->pt_entries[i], sizeof(pt_table_entry_config)); - return PT_ERROR_SUCCESS; - } + * @brief Get partition entry according to entry name + * + * @param ptStuff: Partition table stuff pointer + * @param name: Name of partition entry + * @param ptEntry: Partition entry pointer to store read data + * + * @return PT_ERROR_SUCCESS or PT_ERROR_ENTRY_NOT_FOUND or PT_ERROR_PARAMETER + * + *******************************************************************************/ +pt_table_error_type pt_table_get_active_entries_by_name(pt_table_stuff_config *pt_stuff, uint8_t *name, pt_table_entry_config *pt_entry) { + uint32_t i = 0; + uint32_t len = strlen((char *)name); + + if (pt_stuff == NULL || pt_entry == NULL) { + return PT_ERROR_PARAMETER; + } + + for (i = 0; i < pt_stuff->pt_table.entryCnt; i++) { + if (strlen((char *)pt_stuff->pt_entries[i].name) == len && memcmp((char *)pt_stuff->pt_entries[i].name, (char *)name, len) == 0) { + ARCH_MemCpy_Fast(pt_entry, &pt_stuff->pt_entries[i], sizeof(pt_table_entry_config)); + return PT_ERROR_SUCCESS; } + } - return PT_ERROR_ENTRY_NOT_FOUND; + return PT_ERROR_ENTRY_NOT_FOUND; } /****************************************************************************/ /** - * @brief Update partition entry - * - * @param targetTableID: Target partition table to update - * @param ptStuff: Partition table stuff pointer - * @param ptEntry: Partition entry pointer to update - * - * @return Partition update result - * -*******************************************************************************/ -pt_table_error_type pt_table_update_entry(pt_table_id_type target_table_id, - pt_table_stuff_config *pt_stuff, - pt_table_entry_config *pt_entry) -{ - uint32_t i = 0; - BL_Err_Type ret; - uint32_t write_addr; - uint32_t entries_len; - pt_table_config *pt_table; - pt_table_entry_config *pt_entries; - uint32_t *crc32; - - if (pt_entry == NULL || pt_stuff == NULL) { - return PT_ERROR_PARAMETER; + * @brief Update partition entry + * + * @param targetTableID: Target partition table to update + * @param ptStuff: Partition table stuff pointer + * @param ptEntry: Partition entry pointer to update + * + * @return Partition update result + * + *******************************************************************************/ +pt_table_error_type pt_table_update_entry(pt_table_id_type target_table_id, pt_table_stuff_config *pt_stuff, pt_table_entry_config *pt_entry) { + uint32_t i = 0; + BL_Err_Type ret; + uint32_t write_addr; + uint32_t entries_len; + pt_table_config *pt_table; + pt_table_entry_config *pt_entries; + uint32_t *crc32; + + if (pt_entry == NULL || pt_stuff == NULL) { + return PT_ERROR_PARAMETER; + } + + pt_table = &pt_stuff->pt_table; + pt_entries = pt_stuff->pt_entries; + + if (target_table_id == PT_TABLE_ID_INVALID) { + return PT_ERROR_TABLE_NOT_VALID; + } + + if (target_table_id == PT_TABLE_ID_0) { + write_addr = BFLB_PT_TABLE0_ADDRESS; + } else { + write_addr = BFLB_PT_TABLE1_ADDRESS; + } + + for (i = 0; i < pt_table->entryCnt; i++) { + if (pt_entries[i].type == pt_entry->type) { + ARCH_MemCpy_Fast(&pt_entries[i], pt_entry, sizeof(pt_table_entry_config)); + break; } + } - pt_table = &pt_stuff->pt_table; - pt_entries = pt_stuff->pt_entries; - - if (target_table_id == PT_TABLE_ID_INVALID) { - return PT_ERROR_TABLE_NOT_VALID; - } - - if (target_table_id == PT_TABLE_ID_0) { - write_addr = BFLB_PT_TABLE0_ADDRESS; + if (i == pt_table->entryCnt) { + /* Not found this entry ,add new one */ + if (pt_table->entryCnt < PT_ENTRY_MAX) { + ARCH_MemCpy_Fast(&pt_entries[pt_table->entryCnt], pt_entry, sizeof(pt_table_entry_config)); + pt_table->entryCnt++; } else { - write_addr = BFLB_PT_TABLE1_ADDRESS; - } - - for (i = 0; i < pt_table->entryCnt; i++) { - if (pt_entries[i].type == pt_entry->type) { - ARCH_MemCpy_Fast(&pt_entries[i], pt_entry, sizeof(pt_table_entry_config)); - break; - } - } - - if (i == pt_table->entryCnt) { - /* Not found this entry ,add new one */ - if (pt_table->entryCnt < PT_ENTRY_MAX) { - ARCH_MemCpy_Fast(&pt_entries[pt_table->entryCnt], pt_entry, sizeof(pt_table_entry_config)); - pt_table->entryCnt++; - } else { - return PT_ERROR_ENTRY_UPDATE_FAIL; - } + return PT_ERROR_ENTRY_UPDATE_FAIL; } + } - /* Prepare write back to flash */ - /* Update age */ - pt_table->age++; - pt_table->crc32 = BFLB_Soft_CRC32((uint8_t *)pt_table, sizeof(pt_table_config) - 4); + /* Prepare write back to flash */ + /* Update age */ + pt_table->age++; + pt_table->crc32 = BFLB_Soft_CRC32((uint8_t *)pt_table, sizeof(pt_table_config) - 4); - /* Update entries CRC */ - entries_len = pt_table->entryCnt * sizeof(pt_table_entry_config); - crc32 = (uint32_t *)((uintptr_t)pt_entries + entries_len); - *crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_entries[0], entries_len); + /* Update entries CRC */ + entries_len = pt_table->entryCnt * sizeof(pt_table_entry_config); + crc32 = (uint32_t *)((uintptr_t)pt_entries + entries_len); + *crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_entries[0], entries_len); - /* Write back to flash */ - /* Erase flash first */ - //ret = gp_pt_table_flash_erase(write_addr, write_addr + sizeof(pt_table_config) + entries_len + 4 - 1); - ret = gp_pt_table_flash_erase(write_addr, sizeof(pt_table_config) + entries_len + 4); + /* Write back to flash */ + /* Erase flash first */ + // ret = gp_pt_table_flash_erase(write_addr, write_addr + sizeof(pt_table_config) + entries_len + 4 - 1); + ret = gp_pt_table_flash_erase(write_addr, sizeof(pt_table_config) + entries_len + 4); - if (ret != SUCCESS) { - MSG_ERR("Flash Erase error\r\n"); - return PT_ERROR_FALSH_WRITE; - } + if (ret != SUCCESS) { + MSG_ERR("Flash Erase error\r\n"); + return PT_ERROR_FALSH_WRITE; + } - /* Write flash */ - ret = gp_pt_table_flash_write(write_addr, (uint8_t *)pt_stuff, sizeof(pt_table_stuff_config)); + /* Write flash */ + ret = gp_pt_table_flash_write(write_addr, (uint8_t *)pt_stuff, sizeof(pt_table_stuff_config)); - if (ret != SUCCESS) { - MSG_ERR("Flash Write error\r\n"); - return PT_ERROR_FALSH_WRITE; - } + if (ret != SUCCESS) { + MSG_ERR("Flash Write error\r\n"); + return PT_ERROR_FALSH_WRITE; + } - return PT_ERROR_SUCCESS; + return PT_ERROR_SUCCESS; } /****************************************************************************/ /** - * @brief Create partition entry - * - * @param ptID: Partition table ID - * - * @return Partition create result - * -*******************************************************************************/ -pt_table_error_type pt_table_create(pt_table_id_type pt_id) -{ - uint32_t write_addr; - BL_Err_Type ret; - pt_table_config pt_table; - - if (pt_id == PT_TABLE_ID_INVALID) { - return PT_ERROR_TABLE_NOT_VALID; - } - - if (pt_id == PT_TABLE_ID_0) { - write_addr = BFLB_PT_TABLE0_ADDRESS; - } else { - write_addr = BFLB_PT_TABLE1_ADDRESS; - } - - /* Prepare write back to flash */ - pt_table.magicCode = BFLB_PT_MAGIC_CODE; - pt_table.version = 0; - pt_table.entryCnt = 0; - pt_table.age = 0; - pt_table.crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_table, sizeof(pt_table_config) - 4); - /* Write back to flash */ - //ret = gp_pt_table_flash_erase(write_addr, write_addr + sizeof(pt_table_config) - 1); - ret = gp_pt_table_flash_erase(write_addr,sizeof(pt_table_config)); - - if (ret != SUCCESS) { - MSG_ERR("Flash Erase error\r\n"); - return PT_ERROR_FALSH_ERASE; - } - - ret = gp_pt_table_flash_write(write_addr, (uint8_t *)&pt_table, sizeof(pt_table_config)); + * @brief Create partition entry + * + * @param ptID: Partition table ID + * + * @return Partition create result + * + *******************************************************************************/ +pt_table_error_type pt_table_create(pt_table_id_type pt_id) { + uint32_t write_addr; + BL_Err_Type ret; + pt_table_config pt_table; + + if (pt_id == PT_TABLE_ID_INVALID) { + return PT_ERROR_TABLE_NOT_VALID; + } + + if (pt_id == PT_TABLE_ID_0) { + write_addr = BFLB_PT_TABLE0_ADDRESS; + } else { + write_addr = BFLB_PT_TABLE1_ADDRESS; + } + + /* Prepare write back to flash */ + pt_table.magicCode = BFLB_PT_MAGIC_CODE; + pt_table.version = 0; + pt_table.entryCnt = 0; + pt_table.age = 0; + pt_table.crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_table, sizeof(pt_table_config) - 4); + /* Write back to flash */ + // ret = gp_pt_table_flash_erase(write_addr, write_addr + sizeof(pt_table_config) - 1); + ret = gp_pt_table_flash_erase(write_addr, sizeof(pt_table_config)); + + if (ret != SUCCESS) { + MSG_ERR("Flash Erase error\r\n"); + return PT_ERROR_FALSH_ERASE; + } + + ret = gp_pt_table_flash_write(write_addr, (uint8_t *)&pt_table, sizeof(pt_table_config)); + + if (ret != SUCCESS) { + MSG_ERR("Flash Write error\r\n"); + return PT_ERROR_FALSH_WRITE; + } + + return PT_ERROR_SUCCESS; +} - if (ret != SUCCESS) { - MSG_ERR("Flash Write error\r\n"); - return PT_ERROR_FALSH_WRITE; +pt_table_error_type pt_table_dump(void) { + uint32_t pt_valid[2] = {0, 0}; + pt_table_stuff_config pt_stuff[2]; + + gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff[0], sizeof(pt_table_stuff_config)); + pt_valid[0] = pt_table_valid(&pt_stuff[0]); + + gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff[1], sizeof(pt_table_stuff_config)); + pt_valid[1] = pt_table_valid(&pt_stuff[1]); + + if (pt_valid[0]) { + MSG("PT TABLE0 valid\r\n"); + } else { + MSG("PT TABLE0 invalid\r\n"); + } + + if (pt_valid[1]) { + MSG("PT TABLE1 valid\r\n"); + } else { + MSG("PT TABLE1 invalid\r\n"); + } + + for (int i = 0; i < 2; i++) { + if (pt_valid[i] == 1) { + MSG("ptStuff[%d].pt_table.magicCode 0x%08x\r\n", i, pt_stuff[i].pt_table.magicCode); + MSG("ptStuff[%d].pt_table.version 0x%08x\r\n", i, pt_stuff[i].pt_table.version); + MSG("ptStuff[%d].pt_table.entryCnt 0x%08x\r\n", i, pt_stuff[i].pt_table.entryCnt); + MSG("ptStuff[%d].pt_table.age 0x%08x\r\n", i, pt_stuff[i].pt_table.age); + MSG("ptStuff[%d].pt_table.crc32 0x%08x\r\n", i, pt_stuff[i].pt_table.crc32); + + for (int j = 0; j < pt_stuff[i].pt_table.entryCnt; j++) { + MSG("ptStuff[%d].pt_entries[%d].type 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].type); + MSG("ptStuff[%d].pt_entries[%d].device 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].device); + MSG("ptStuff[%d].pt_entries[%d].active_index 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].active_index); + MSG("ptStuff[%d].pt_entries[%d].Address[0] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].start_address[0]); + MSG("ptStuff[%d].pt_entries[%d].Address[1] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].start_address[1]); + MSG("ptStuff[%d].pt_entries[%d].maxLen[0] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].max_len[0]); + MSG("ptStuff[%d].pt_entries[%d].maxLen[1] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].max_len[1]); + MSG("ptStuff[%d].pt_entries[%d].len 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].len); + MSG("ptStuff[%d].pt_entries[%d].age 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].age); + } } + } - return PT_ERROR_SUCCESS; + return PT_ERROR_SUCCESS; } -pt_table_error_type pt_table_dump(void) -{ - uint32_t pt_valid[2] = { 0, 0 }; - pt_table_stuff_config pt_stuff[2]; +pt_table_error_type pt_table_get_iap_para(pt_table_iap_param_type *para) { + uint32_t pt_valid[2] = {0, 0}; + pt_table_stuff_config pt_stuff[2]; + uint8_t active_index; - gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff[0], sizeof(pt_table_stuff_config)); - pt_valid[0] = pt_table_valid(&pt_stuff[0]); + gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff[0], sizeof(pt_table_stuff_config)); + pt_valid[0] = pt_table_valid(&pt_stuff[0]); - gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff[1], sizeof(pt_table_stuff_config)); - pt_valid[1] = pt_table_valid(&pt_stuff[1]); + gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff[1], sizeof(pt_table_stuff_config)); + pt_valid[1] = pt_table_valid(&pt_stuff[1]); - if (pt_valid[0]) { - MSG("PT TABLE0 valid\r\n"); - } else { - MSG("PT TABLE0 invalid\r\n"); - } + if ((pt_valid[0] == 1) && (pt_valid[1] == 1)) { + if (pt_stuff[0].pt_table.age >= pt_stuff[1].pt_table.age) { + active_index = pt_stuff[0].pt_entries[0].active_index; + para->iap_write_addr = para->iap_start_addr = pt_stuff[0].pt_entries[0].start_address[!(active_index & 0x01)]; + para->inactive_index = !(active_index & 0x01); + para->inactive_table_index = 1; - if (pt_valid[1]) { - MSG("PT TABLE1 valid\r\n"); } else { - MSG("PT TABLE1 invalid\r\n"); - } - - for (int i = 0; i < 2; i++) { - if (pt_valid[i] == 1) { - MSG("ptStuff[%d].pt_table.magicCode 0x%08x\r\n", i, pt_stuff[i].pt_table.magicCode); - MSG("ptStuff[%d].pt_table.version 0x%08x\r\n", i, pt_stuff[i].pt_table.version); - MSG("ptStuff[%d].pt_table.entryCnt 0x%08x\r\n", i, pt_stuff[i].pt_table.entryCnt); - MSG("ptStuff[%d].pt_table.age 0x%08x\r\n", i, pt_stuff[i].pt_table.age); - MSG("ptStuff[%d].pt_table.crc32 0x%08x\r\n", i, pt_stuff[i].pt_table.crc32); - - for (int j = 0; j < pt_stuff[i].pt_table.entryCnt; j++) { - MSG("ptStuff[%d].pt_entries[%d].type 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].type); - MSG("ptStuff[%d].pt_entries[%d].device 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].device); - MSG("ptStuff[%d].pt_entries[%d].active_index 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].active_index); - MSG("ptStuff[%d].pt_entries[%d].Address[0] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].start_address[0]); - MSG("ptStuff[%d].pt_entries[%d].Address[1] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].start_address[1]); - MSG("ptStuff[%d].pt_entries[%d].maxLen[0] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].max_len[0]); - MSG("ptStuff[%d].pt_entries[%d].maxLen[1] 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].max_len[1]); - MSG("ptStuff[%d].pt_entries[%d].len 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].len); - MSG("ptStuff[%d].pt_entries[%d].age 0x%08x\r\n", i, j, pt_stuff[i].pt_entries[j].age); - } - } + active_index = pt_stuff[1].pt_entries[0].active_index; + para->iap_write_addr = para->iap_start_addr = pt_stuff[1].pt_entries[0].start_address[!(active_index & 0x01)]; + para->inactive_index = !(active_index & 0x01); + para->inactive_table_index = 0; } - return PT_ERROR_SUCCESS; + } else if (pt_valid[1] == 1) { + active_index = pt_stuff[1].pt_entries[0].active_index; + para->iap_write_addr = para->iap_start_addr = pt_stuff[1].pt_entries[0].start_address[!(active_index & 0x01)]; + para->inactive_index = !(active_index & 0x01); + para->inactive_table_index = 0; + } else if (pt_valid[0] == 1) { + active_index = pt_stuff[0].pt_entries[0].active_index; + para->iap_write_addr = para->iap_start_addr = pt_stuff[0].pt_entries[0].start_address[!(active_index & 0x01)]; + para->inactive_index = !(active_index & 0x01); + para->inactive_table_index = 1; + } else { + return PT_ERROR_TABLE_NOT_VALID; + } + + MSG("inactive_table_index %d, inactive index %d , IAP start addr %08x \r\n", para->inactive_table_index, para->inactive_index, para->iap_start_addr); + return PT_ERROR_SUCCESS; } -pt_table_error_type pt_table_get_iap_para(pt_table_iap_param_type *para) -{ - uint32_t pt_valid[2] = { 0, 0 }; - pt_table_stuff_config pt_stuff[2]; - uint8_t active_index; - - gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff[0], sizeof(pt_table_stuff_config)); - pt_valid[0] = pt_table_valid(&pt_stuff[0]); - - gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff[1], sizeof(pt_table_stuff_config)); - pt_valid[1] = pt_table_valid(&pt_stuff[1]); - - if ((pt_valid[0] == 1) && (pt_valid[1] == 1)) { - if (pt_stuff[0].pt_table.age >= pt_stuff[1].pt_table.age) { - active_index = pt_stuff[0].pt_entries[0].active_index; - para->iap_write_addr = para->iap_start_addr = pt_stuff[0].pt_entries[0].start_address[!(active_index & 0x01)]; - para->inactive_index = !(active_index & 0x01); - para->inactive_table_index = 1; - - } else { - active_index = pt_stuff[1].pt_entries[0].active_index; - para->iap_write_addr = para->iap_start_addr = pt_stuff[1].pt_entries[0].start_address[!(active_index & 0x01)]; - para->inactive_index = !(active_index & 0x01); - para->inactive_table_index = 0; - } - - } else if (pt_valid[1] == 1) { - active_index = pt_stuff[1].pt_entries[0].active_index; - para->iap_write_addr = para->iap_start_addr = pt_stuff[1].pt_entries[0].start_address[!(active_index & 0x01)]; - para->inactive_index = !(active_index & 0x01); - para->inactive_table_index = 0; - } else if (pt_valid[0] == 1) { - active_index = pt_stuff[0].pt_entries[0].active_index; - para->iap_write_addr = para->iap_start_addr = pt_stuff[0].pt_entries[0].start_address[!(active_index & 0x01)]; - para->inactive_index = !(active_index & 0x01); - para->inactive_table_index = 1; - } else { - return PT_ERROR_TABLE_NOT_VALID; +pt_table_error_type pt_table_set_iap_para(pt_table_iap_param_type *para) { + pt_table_stuff_config pt_stuff, pt_stuff_write; + int32_t ret; + uint32_t *p_crc32; + uint32_t entries_len; + + if (para->inactive_table_index == 1) { + gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff, sizeof(pt_table_stuff_config)); + } else if (para->inactive_table_index == 0) { + gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff, sizeof(pt_table_stuff_config)); + } + + ARCH_MemCpy_Fast((void *)&pt_stuff_write, (void *)&pt_stuff, sizeof(pt_table_stuff_config)); + pt_stuff_write.pt_table.age += 1; + pt_stuff_write.pt_entries[0].active_index = !(pt_stuff_write.pt_entries[0].active_index & 0x01); + pt_stuff_write.pt_table.crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_stuff_write, sizeof(pt_table_config) - 4); + entries_len = sizeof(pt_table_entry_config) * pt_stuff_write.pt_table.entryCnt; + // pt_stuff_write.crc32 = BFLB_Soft_CRC32((uint8_t*)pt_stuff_write.pt_entries,entries_len); + p_crc32 = (uint32_t *)((uintptr_t)pt_stuff_write.pt_entries + entries_len); + *p_crc32 = BFLB_Soft_CRC32((uint8_t *)pt_stuff_write.pt_entries, entries_len); + + if (para->inactive_table_index == 1) { + // ret = gp_pt_table_flash_erase(BFLB_PT_TABLE1_ADDRESS, BFLB_PT_TABLE1_ADDRESS + sizeof(pt_table_stuff_config) - 1); + ret = gp_pt_table_flash_erase(BFLB_PT_TABLE1_ADDRESS, sizeof(pt_table_stuff_config)); + + if (ret != SUCCESS) { + MSG_ERR("Flash Erase error\r\n"); + return PT_ERROR_FALSH_ERASE; } - MSG("inactive_table_index %d, inactive index %d , IAP start addr %08x \r\n", para->inactive_table_index, para->inactive_index, para->iap_start_addr); - return PT_ERROR_SUCCESS; -} + ret = gp_pt_table_flash_write(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff_write, sizeof(pt_table_stuff_config)); + + if (ret != SUCCESS) { + MSG_ERR("Flash Write error\r\n"); + return PT_ERROR_FALSH_WRITE; + } + } else if (para->inactive_table_index == 0) { + // ret = gp_pt_table_flash_erase(BFLB_PT_TABLE0_ADDRESS, BFLB_PT_TABLE0_ADDRESS + sizeof(pt_table_stuff_config) - 1); + ret = gp_pt_table_flash_erase(BFLB_PT_TABLE0_ADDRESS, sizeof(pt_table_stuff_config)); -pt_table_error_type pt_table_set_iap_para(pt_table_iap_param_type *para) -{ - pt_table_stuff_config pt_stuff, pt_stuff_write; - int32_t ret; - uint32_t *p_crc32; - uint32_t entries_len; - - if (para->inactive_table_index == 1) { - gp_pt_table_flash_read(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff, sizeof(pt_table_stuff_config)); - } else if (para->inactive_table_index == 0) { - gp_pt_table_flash_read(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff, sizeof(pt_table_stuff_config)); + if (ret != SUCCESS) { + MSG_ERR("Flash Erase error\r\n"); + return PT_ERROR_FALSH_ERASE; } - ARCH_MemCpy_Fast((void *)&pt_stuff_write, (void *)&pt_stuff, sizeof(pt_table_stuff_config)); - pt_stuff_write.pt_table.age += 1; - pt_stuff_write.pt_entries[0].active_index = !(pt_stuff_write.pt_entries[0].active_index & 0x01); - pt_stuff_write.pt_table.crc32 = BFLB_Soft_CRC32((uint8_t *)&pt_stuff_write, sizeof(pt_table_config) - 4); - entries_len = sizeof(pt_table_entry_config) * pt_stuff_write.pt_table.entryCnt; - //pt_stuff_write.crc32 = BFLB_Soft_CRC32((uint8_t*)pt_stuff_write.pt_entries,entries_len); - p_crc32 = (uint32_t *)((uintptr_t)pt_stuff_write.pt_entries + entries_len); - *p_crc32 = BFLB_Soft_CRC32((uint8_t *)pt_stuff_write.pt_entries, entries_len); - - if (para->inactive_table_index == 1) { - //ret = gp_pt_table_flash_erase(BFLB_PT_TABLE1_ADDRESS, BFLB_PT_TABLE1_ADDRESS + sizeof(pt_table_stuff_config) - 1); - ret = gp_pt_table_flash_erase(BFLB_PT_TABLE1_ADDRESS, sizeof(pt_table_stuff_config)); - - if (ret != SUCCESS) { - MSG_ERR("Flash Erase error\r\n"); - return PT_ERROR_FALSH_ERASE; - } - - ret = gp_pt_table_flash_write(BFLB_PT_TABLE1_ADDRESS, (uint8_t *)&pt_stuff_write, sizeof(pt_table_stuff_config)); - - if (ret != SUCCESS) { - MSG_ERR("Flash Write error\r\n"); - return PT_ERROR_FALSH_WRITE; - } - } else if (para->inactive_table_index == 0) { - //ret = gp_pt_table_flash_erase(BFLB_PT_TABLE0_ADDRESS, BFLB_PT_TABLE0_ADDRESS + sizeof(pt_table_stuff_config) - 1); - ret = gp_pt_table_flash_erase(BFLB_PT_TABLE0_ADDRESS, sizeof(pt_table_stuff_config)); - - if (ret != SUCCESS) { - MSG_ERR("Flash Erase error\r\n"); - return PT_ERROR_FALSH_ERASE; - } - - ret = gp_pt_table_flash_write(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff_write, sizeof(pt_table_stuff_config)); - - if (ret != SUCCESS) { - MSG_ERR("Flash Write error\r\n"); - return PT_ERROR_FALSH_WRITE; - } + ret = gp_pt_table_flash_write(BFLB_PT_TABLE0_ADDRESS, (uint8_t *)&pt_stuff_write, sizeof(pt_table_stuff_config)); + + if (ret != SUCCESS) { + MSG_ERR("Flash Write error\r\n"); + return PT_ERROR_FALSH_WRITE; } + } - MSG("Update pt_table suss\r\n"); - return PT_ERROR_SUCCESS; + MSG("Update pt_table suss\r\n"); + return PT_ERROR_SUCCESS; } /*@} end of group PARTITION_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/pid/pid.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/pid/pid.c index dc0602003..e5534ce93 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/pid/pid.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/pid/pid.c @@ -23,46 +23,43 @@ #include "pid.h" -void pid_init(pid_alg_t *pid) -{ - pid->set_val = 0.0f; - pid->out_val = 0.0f; +void pid_init(pid_alg_t *pid) { + pid->set_val = 0.0f; + pid->out_val = 0.0f; - pid->last_error = 0.0f; - pid->prev_error = 0.0f; + pid->last_error = 0.0f; + pid->prev_error = 0.0f; - pid->kp = 3.0f; - pid->ki = 0.0f; - pid->kd = 0.0f; + pid->kp = 3.0f; + pid->ki = 0.0f; + pid->kd = 0.0f; - pid->i_error = 0.0f; - pid->sum_error = 0.0f; + pid->i_error = 0.0f; + pid->sum_error = 0.0f; - pid->max_val = 32; - pid->min_val = -32; + pid->max_val = 32; + pid->min_val = -32; } // standard pid -float standard_pid_cal(pid_alg_t *pid, float next_val) -{ - pid->set_val = next_val; - pid->i_error = pid->set_val - pid->out_val; - pid->sum_error += pid->i_error; - pid->out_val = pid->kp * pid->i_error + pid->ki * pid->sum_error + pid->kd * (pid->i_error - pid->last_error); - pid->last_error = pid->i_error; +float standard_pid_cal(pid_alg_t *pid, float next_val) { + pid->set_val = next_val; + pid->i_error = pid->set_val - pid->out_val; + pid->sum_error += pid->i_error; + pid->out_val = pid->kp * pid->i_error + pid->ki * pid->sum_error + pid->kd * (pid->i_error - pid->last_error); + pid->last_error = pid->i_error; - return pid->out_val; + return pid->out_val; } // increment pid -float increment_pid_cal(pid_alg_t *pid, float next_val) -{ - pid->set_val = next_val; - pid->i_error = pid->set_val - pid->out_val; - float increment = pid->kp * (pid->i_error - pid->prev_error) + pid->ki * pid->i_error + pid->kd * (pid->i_error - 2 * pid->prev_error + pid->last_error); - pid->out_val += increment; - pid->last_error = pid->prev_error; - pid->prev_error = pid->i_error; +float increment_pid_cal(pid_alg_t *pid, float next_val) { + pid->set_val = next_val; + pid->i_error = pid->set_val - pid->out_val; + float increment = pid->kp * (pid->i_error - pid->prev_error) + pid->ki * pid->i_error + pid->kd * (pid->i_error - 2 * pid->prev_error + pid->last_error); + pid->out_val += increment; + pid->last_error = pid->prev_error; + pid->prev_error = pid->i_error; - return pid->out_val; + return pid->out_val; } diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/ring_buffer/ring_buffer.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/ring_buffer/ring_buffer.c index ec91c7157..4810f819b 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/ring_buffer/ring_buffer.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/ring_buffer/ring_buffer.c @@ -71,605 +71,582 @@ */ /****************************************************************************/ /** - * @brief Ring buffer init function - * - * @param rbType: Ring buffer type structure pointer - * @param buffer: Pointer of ring buffer - * @param size: Size of ring buffer - * @param lockCb: Ring buffer lock callback function pointer - * @param unlockCb: Ring buffer unlock callback function pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Ring_Buffer_Init(Ring_Buffer_Type *rbType, uint8_t *buffer, uint32_t size, ringBuffer_Lock_Callback *lockCb, ringBuffer_Lock_Callback *unlockCb) -{ - /* Init ring buffer pointer */ - rbType->pointer = buffer; - - /* Init read/write mirror and index */ - rbType->readMirror = 0; - rbType->readIndex = 0; - rbType->writeMirror = 0; - rbType->writeIndex = 0; - - /* Set ring buffer size */ - rbType->size = size; - - /* Set lock and unlock callback function */ - rbType->lock = lockCb; - rbType->unlock = unlockCb; - - return SUCCESS; + * @brief Ring buffer init function + * + * @param rbType: Ring buffer type structure pointer + * @param buffer: Pointer of ring buffer + * @param size: Size of ring buffer + * @param lockCb: Ring buffer lock callback function pointer + * @param unlockCb: Ring buffer unlock callback function pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Ring_Buffer_Init(Ring_Buffer_Type *rbType, uint8_t *buffer, uint32_t size, ringBuffer_Lock_Callback *lockCb, ringBuffer_Lock_Callback *unlockCb) { + /* Init ring buffer pointer */ + rbType->pointer = buffer; + + /* Init read/write mirror and index */ + rbType->readMirror = 0; + rbType->readIndex = 0; + rbType->writeMirror = 0; + rbType->writeIndex = 0; + + /* Set ring buffer size */ + rbType->size = size; + + /* Set lock and unlock callback function */ + rbType->lock = lockCb; + rbType->unlock = unlockCb; + + return SUCCESS; } /****************************************************************************/ /** - * @brief Ring buffer reset function - * - * @param rbType: Ring buffer type structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Ring_Buffer_Reset(Ring_Buffer_Type *rbType) -{ - if (rbType->lock != NULL) { - rbType->lock(); - } - - /* Clear read/write mirror and index */ - rbType->readMirror = 0; - rbType->readIndex = 0; - rbType->writeMirror = 0; - rbType->writeIndex = 0; - - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return SUCCESS; + * @brief Ring buffer reset function + * + * @param rbType: Ring buffer type structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Ring_Buffer_Reset(Ring_Buffer_Type *rbType) { + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Clear read/write mirror and index */ + rbType->readMirror = 0; + rbType->readIndex = 0; + rbType->writeMirror = 0; + rbType->writeIndex = 0; + + if (rbType->unlock != NULL) { + rbType->unlock(); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief Use callback function to write ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param length: Length of data want to write - * @param writeCb: Callback function pointer - * @param parameter: Parameter that callback function may use - * - * @return Length of data actually write - * -*******************************************************************************/ -uint32_t Ring_Buffer_Write_Callback(Ring_Buffer_Type *rbType, uint32_t length, ringBuffer_Write_Callback *writeCb, void *parameter) -{ - uint32_t sizeRemained = Ring_Buffer_Get_Empty_Length(rbType); - - if (writeCb == NULL) { - return 0; + * @brief Use callback function to write ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param length: Length of data want to write + * @param writeCb: Callback function pointer + * @param parameter: Parameter that callback function may use + * + * @return Length of data actually write + * + *******************************************************************************/ +uint32_t Ring_Buffer_Write_Callback(Ring_Buffer_Type *rbType, uint32_t length, ringBuffer_Write_Callback *writeCb, void *parameter) { + uint32_t sizeRemained = Ring_Buffer_Get_Empty_Length(rbType); + + if (writeCb == NULL) { + return 0; + } + + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no space for new data */ + if (sizeRemained == 0) { + if (rbType->unlock != NULL) { + rbType->unlock(); } - if (rbType->lock != NULL) { - rbType->lock(); - } + return 0; + } - /* Ring buffer has no space for new data */ - if (sizeRemained == 0) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } + /* Drop part of data when length out of space remained */ + if (length > sizeRemained) { + length = sizeRemained; + } - return 0; - } + /* Get size of space remained in current mirror */ + sizeRemained = rbType->size - rbType->writeIndex; - /* Drop part of data when length out of space remained */ - if (length > sizeRemained) { - length = sizeRemained; - } - - /* Get size of space remained in current mirror */ - sizeRemained = rbType->size - rbType->writeIndex; - - if (sizeRemained > length) { - /* Space remained is enough for data in current mirror */ - writeCb(parameter, &rbType->pointer[rbType->writeIndex], length); - rbType->writeIndex += length; - } else { - /* Data is divided to two parts with different mirror */ - writeCb(parameter, &rbType->pointer[rbType->writeIndex], sizeRemained); - writeCb(parameter, &rbType->pointer[0], length - sizeRemained); - rbType->writeIndex = length - sizeRemained; - rbType->writeMirror = ~rbType->writeMirror; - } + if (sizeRemained > length) { + /* Space remained is enough for data in current mirror */ + writeCb(parameter, &rbType->pointer[rbType->writeIndex], length); + rbType->writeIndex += length; + } else { + /* Data is divided to two parts with different mirror */ + writeCb(parameter, &rbType->pointer[rbType->writeIndex], sizeRemained); + writeCb(parameter, &rbType->pointer[0], length - sizeRemained); + rbType->writeIndex = length - sizeRemained; + rbType->writeMirror = ~rbType->writeMirror; + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return length; + return length; } /****************************************************************************/ /** - * @brief Copy data from data buffer to ring buffer function - * - * @param parameter: Pointer to source pointer - * @param dest: Ring buffer to write - * @param length: Length of data to write - * - * @return None - * -*******************************************************************************/ -static void Ring_Buffer_Write_Copy(void *parameter, uint8_t *dest, uint32_t length) -{ - uint8_t **src = (uint8_t **)parameter; - - ARCH_MemCpy_Fast(dest, *src, length); - *src += length; + * @brief Copy data from data buffer to ring buffer function + * + * @param parameter: Pointer to source pointer + * @param dest: Ring buffer to write + * @param length: Length of data to write + * + * @return None + * + *******************************************************************************/ +static void Ring_Buffer_Write_Copy(void *parameter, uint8_t *dest, uint32_t length) { + uint8_t **src = (uint8_t **)parameter; + + ARCH_MemCpy_Fast(dest, *src, length); + *src += length; } /****************************************************************************/ /** - * @brief Write ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data to write - * @param length: Length of data - * - * @return Length of data writted actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Write(Ring_Buffer_Type *rbType, const uint8_t *data, uint32_t length) -{ - return Ring_Buffer_Write_Callback(rbType, length, Ring_Buffer_Write_Copy, &data); -} + * @brief Write ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data to write + * @param length: Length of data + * + * @return Length of data writted actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Write(Ring_Buffer_Type *rbType, const uint8_t *data, uint32_t length) { return Ring_Buffer_Write_Callback(rbType, length, Ring_Buffer_Write_Copy, &data); } /****************************************************************************/ /** - * @brief Write 1 byte to ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data to write - * - * @return Length of data writted actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Write_Byte(Ring_Buffer_Type *rbType, const uint8_t data) -{ - if (rbType->lock != NULL) { - rbType->lock(); + * @brief Write 1 byte to ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data to write + * + * @return Length of data writted actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Write_Byte(Ring_Buffer_Type *rbType, const uint8_t data) { + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no space for new data */ + if (!Ring_Buffer_Get_Empty_Length(rbType)) { + if (rbType->unlock != NULL) { + rbType->unlock(); } - /* Ring buffer has no space for new data */ - if (!Ring_Buffer_Get_Empty_Length(rbType)) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } + return 0; + } - return 0; - } + rbType->pointer[rbType->writeIndex] = data; - rbType->pointer[rbType->writeIndex] = data; - - /* Judge to change index and mirror */ - if (rbType->writeIndex != (rbType->size - 1)) { - rbType->writeIndex++; - } else { - rbType->writeIndex = 0; - rbType->writeMirror = ~rbType->writeMirror; - } + /* Judge to change index and mirror */ + if (rbType->writeIndex != (rbType->size - 1)) { + rbType->writeIndex++; + } else { + rbType->writeIndex = 0; + rbType->writeMirror = ~rbType->writeMirror; + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return 1; + return 1; } /****************************************************************************/ /** - * @brief Write ring buffer function, old data will be covered by new data when ring buffer is - * full - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data to write - * @param length: Length of data - * - * @return Length of data writted actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Write_Force(Ring_Buffer_Type *rbType, const uint8_t *data, uint32_t length) -{ - uint32_t sizeRemained = Ring_Buffer_Get_Empty_Length(rbType); - uint32_t indexRemained = rbType->size - rbType->writeIndex; - - if (rbType->lock != NULL) { - rbType->lock(); + * @brief Write ring buffer function, old data will be covered by new data when ring buffer is + * full + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data to write + * @param length: Length of data + * + * @return Length of data writted actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Write_Force(Ring_Buffer_Type *rbType, const uint8_t *data, uint32_t length) { + uint32_t sizeRemained = Ring_Buffer_Get_Empty_Length(rbType); + uint32_t indexRemained = rbType->size - rbType->writeIndex; + + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Drop extra data when data length is large than size of ring buffer */ + if (length > rbType->size) { + data = &data[length - rbType->size]; + length = rbType->size; + } + + if (indexRemained > length) { + /* Space remained is enough for data in current mirror */ + ARCH_MemCpy_Fast(&rbType->pointer[rbType->writeIndex], data, length); + rbType->writeIndex += length; + + /* Update read index */ + if (length > sizeRemained) { + rbType->readIndex = rbType->writeIndex; } + } else { + /* Data is divided to two parts with different mirror */ + ARCH_MemCpy_Fast(&rbType->pointer[rbType->writeIndex], data, indexRemained); + ARCH_MemCpy_Fast(&rbType->pointer[0], &data[indexRemained], length - indexRemained); + rbType->writeIndex = length - indexRemained; + rbType->writeMirror = ~rbType->writeMirror; - /* Drop extra data when data length is large than size of ring buffer */ - if (length > rbType->size) { - data = &data[length - rbType->size]; - length = rbType->size; + /* Update read index and mirror */ + if (length > sizeRemained) { + rbType->readIndex = rbType->writeIndex; + rbType->readMirror = ~rbType->readMirror; } + } - if (indexRemained > length) { - /* Space remained is enough for data in current mirror */ - ARCH_MemCpy_Fast(&rbType->pointer[rbType->writeIndex], data, length); - rbType->writeIndex += length; + if (rbType->unlock != NULL) { + rbType->unlock(); + } - /* Update read index */ - if (length > sizeRemained) { - rbType->readIndex = rbType->writeIndex; - } - } else { - /* Data is divided to two parts with different mirror */ - ARCH_MemCpy_Fast(&rbType->pointer[rbType->writeIndex], data, indexRemained); - ARCH_MemCpy_Fast(&rbType->pointer[0], &data[indexRemained], length - indexRemained); - rbType->writeIndex = length - indexRemained; - rbType->writeMirror = ~rbType->writeMirror; - - /* Update read index and mirror */ - if (length > sizeRemained) { - rbType->readIndex = rbType->writeIndex; - rbType->readMirror = ~rbType->readMirror; - } - } - - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return length; + return length; } /****************************************************************************/ /** - * @brief Write 1 byte to ring buffer function, old data will be covered by new data when ring - * buffer is full - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data to write - * - * @return Length of data writted actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Write_Byte_Force(Ring_Buffer_Type *rbType, const uint8_t data) -{ - Ring_Buffer_Status_Type status = Ring_Buffer_Get_Status(rbType); + * @brief Write 1 byte to ring buffer function, old data will be covered by new data when ring + * buffer is full + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data to write + * + * @return Length of data writted actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Write_Byte_Force(Ring_Buffer_Type *rbType, const uint8_t data) { + Ring_Buffer_Status_Type status = Ring_Buffer_Get_Status(rbType); + + if (rbType->lock != NULL) { + rbType->lock(); + } + + rbType->pointer[rbType->writeIndex] = data; + + /* Judge to change index and mirror */ + if (rbType->writeIndex == rbType->size - 1) { + rbType->writeIndex = 0; + rbType->writeMirror = ~rbType->writeMirror; - if (rbType->lock != NULL) { - rbType->lock(); + /* Update read index and mirror */ + if (status == RING_BUFFER_FULL) { + rbType->readIndex = rbType->writeIndex; + rbType->readMirror = ~rbType->readMirror; } + } else { + rbType->writeIndex++; - rbType->pointer[rbType->writeIndex] = data; - - /* Judge to change index and mirror */ - if (rbType->writeIndex == rbType->size - 1) { - rbType->writeIndex = 0; - rbType->writeMirror = ~rbType->writeMirror; - - /* Update read index and mirror */ - if (status == RING_BUFFER_FULL) { - rbType->readIndex = rbType->writeIndex; - rbType->readMirror = ~rbType->readMirror; - } - } else { - rbType->writeIndex++; - - /* Update read index */ - if (status == RING_BUFFER_FULL) { - rbType->readIndex = rbType->writeIndex; - } + /* Update read index */ + if (status == RING_BUFFER_FULL) { + rbType->readIndex = rbType->writeIndex; } + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return 1; + return 1; } /****************************************************************************/ /** - * @brief Use callback function to read ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param length: Length of data want to read - * @param readCb: Callback function pointer - * @param parameter: Parameter that callback function may use - * - * @return Length of data actually read - * -*******************************************************************************/ -uint32_t Ring_Buffer_Read_Callback(Ring_Buffer_Type *rbType, uint32_t length, ringBuffer_Read_Callback *readCb, void *parameter) -{ - uint32_t size = Ring_Buffer_Get_Length(rbType); - - if (readCb == NULL) { - return 0; - } - - if (rbType->lock != NULL) { - rbType->lock(); + * @brief Use callback function to read ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param length: Length of data want to read + * @param readCb: Callback function pointer + * @param parameter: Parameter that callback function may use + * + * @return Length of data actually read + * + *******************************************************************************/ +uint32_t Ring_Buffer_Read_Callback(Ring_Buffer_Type *rbType, uint32_t length, ringBuffer_Read_Callback *readCb, void *parameter) { + uint32_t size = Ring_Buffer_Get_Length(rbType); + + if (readCb == NULL) { + return 0; + } + + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no data */ + if (!size) { + if (rbType->unlock != NULL) { + rbType->unlock(); } - /* Ring buffer has no data */ - if (!size) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } + return 0; + } - return 0; - } + /* Ring buffer do not have enough data */ + if (size < length) { + length = size; + } - /* Ring buffer do not have enough data */ - if (size < length) { - length = size; - } + /* Get size of space remained in current mirror */ + size = rbType->size - rbType->readIndex; - /* Get size of space remained in current mirror */ - size = rbType->size - rbType->readIndex; - - if (size > length) { - /* Read all data needed */ - readCb(parameter, &rbType->pointer[rbType->readIndex], length); - rbType->readIndex += length; - } else { - /* Read two part of data in different mirror */ - readCb(parameter, &rbType->pointer[rbType->readIndex], size); - readCb(parameter, &rbType->pointer[0], length - size); - rbType->readIndex = length - size; - rbType->readMirror = ~rbType->readMirror; - } + if (size > length) { + /* Read all data needed */ + readCb(parameter, &rbType->pointer[rbType->readIndex], length); + rbType->readIndex += length; + } else { + /* Read two part of data in different mirror */ + readCb(parameter, &rbType->pointer[rbType->readIndex], size); + readCb(parameter, &rbType->pointer[0], length - size); + rbType->readIndex = length - size; + rbType->readMirror = ~rbType->readMirror; + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return length; + return length; } /****************************************************************************/ /** - * @brief Copy data from ring buffer to data buffer function - * - * @param parameter: Pointer to destination pointer - * @param data: Data buffer to copy - * @param length: Length of data to copy - * - * @return None - * -*******************************************************************************/ -static void Ring_Buffer_Read_Copy(void *parameter, uint8_t *data, uint32_t length) -{ - uint8_t **dest = (uint8_t **)parameter; - - ARCH_MemCpy_Fast(*dest, data, length); - *dest += length; + * @brief Copy data from ring buffer to data buffer function + * + * @param parameter: Pointer to destination pointer + * @param data: Data buffer to copy + * @param length: Length of data to copy + * + * @return None + * + *******************************************************************************/ +static void Ring_Buffer_Read_Copy(void *parameter, uint8_t *data, uint32_t length) { + uint8_t **dest = (uint8_t **)parameter; + + ARCH_MemCpy_Fast(*dest, data, length); + *dest += length; } /****************************************************************************/ /** - * @brief Read ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param data: Buffer for data read - * @param length: Length of data to read - * - * @return Length of data read actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Read(Ring_Buffer_Type *rbType, uint8_t *data, uint32_t length) -{ - return Ring_Buffer_Read_Callback(rbType, length, Ring_Buffer_Read_Copy, &data); -} + * @brief Read ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param data: Buffer for data read + * @param length: Length of data to read + * + * @return Length of data read actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Read(Ring_Buffer_Type *rbType, uint8_t *data, uint32_t length) { return Ring_Buffer_Read_Callback(rbType, length, Ring_Buffer_Read_Copy, &data); } /****************************************************************************/ /** - * @brief Read 1 byte from ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data read - * - * @return Length of data actually read - * -*******************************************************************************/ -uint32_t Ring_Buffer_Read_Byte(Ring_Buffer_Type *rbType, uint8_t *data) -{ - if (rbType->lock != NULL) { - rbType->lock(); + * @brief Read 1 byte from ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data read + * + * @return Length of data actually read + * + *******************************************************************************/ +uint32_t Ring_Buffer_Read_Byte(Ring_Buffer_Type *rbType, uint8_t *data) { + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no data */ + if (!Ring_Buffer_Get_Length(rbType)) { + if (rbType->unlock != NULL) { + rbType->unlock(); } - /* Ring buffer has no data */ - if (!Ring_Buffer_Get_Length(rbType)) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return 0; - } + return 0; + } - /* Read data */ - *data = rbType->pointer[rbType->readIndex]; + /* Read data */ + *data = rbType->pointer[rbType->readIndex]; - /* Update read index and mirror */ - if (rbType->readIndex == rbType->size - 1) { - rbType->readIndex = 0; - rbType->readMirror = ~rbType->readMirror; - } else { - rbType->readIndex++; - } + /* Update read index and mirror */ + if (rbType->readIndex == rbType->size - 1) { + rbType->readIndex = 0; + rbType->readMirror = ~rbType->readMirror; + } else { + rbType->readIndex++; + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return 1; + return 1; } /****************************************************************************/ /** - * @brief Read ring buffer function, do not remove from buffer actually - * - * @param rbType: Ring buffer type structure pointer - * @param data: Buffer for data read - * @param length: Length of data to read - * - * @return Length of data read actually - * -*******************************************************************************/ -uint32_t Ring_Buffer_Peek(Ring_Buffer_Type *rbType, uint8_t *data, uint32_t length) -{ - uint32_t size = Ring_Buffer_Get_Length(rbType); - - if (rbType->lock != NULL) { - rbType->lock(); + * @brief Read ring buffer function, do not remove from buffer actually + * + * @param rbType: Ring buffer type structure pointer + * @param data: Buffer for data read + * @param length: Length of data to read + * + * @return Length of data read actually + * + *******************************************************************************/ +uint32_t Ring_Buffer_Peek(Ring_Buffer_Type *rbType, uint8_t *data, uint32_t length) { + uint32_t size = Ring_Buffer_Get_Length(rbType); + + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no data */ + if (!size) { + if (rbType->unlock != NULL) { + rbType->unlock(); } - /* Ring buffer has no data */ - if (!size) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } + return 0; + } - return 0; - } + /* Ring buffer do not have enough data */ + if (size < length) { + length = size; + } - /* Ring buffer do not have enough data */ - if (size < length) { - length = size; - } - - /* Get size of space remained in current mirror */ - size = rbType->size - rbType->readIndex; + /* Get size of space remained in current mirror */ + size = rbType->size - rbType->readIndex; - if (size > length) { - /* Read all data needed */ - ARCH_MemCpy_Fast(data, &rbType->pointer[rbType->readIndex], length); - } else { - /* Read two part of data in different mirror */ - ARCH_MemCpy_Fast(data, &rbType->pointer[rbType->readIndex], size); - ARCH_MemCpy_Fast(&data[size], &rbType->pointer[0], length - size); - } + if (size > length) { + /* Read all data needed */ + ARCH_MemCpy_Fast(data, &rbType->pointer[rbType->readIndex], length); + } else { + /* Read two part of data in different mirror */ + ARCH_MemCpy_Fast(data, &rbType->pointer[rbType->readIndex], size); + ARCH_MemCpy_Fast(&data[size], &rbType->pointer[0], length - size); + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return length; + return length; } /****************************************************************************/ /** - * @brief Read 1 byte from ring buffer function, do not remove from buffer actually - * - * @param rbType: Ring buffer type structure pointer - * @param data: Data read - * - * @return Length of data actually read - * -*******************************************************************************/ -uint32_t Ring_Buffer_Peek_Byte(Ring_Buffer_Type *rbType, uint8_t *data) -{ - if (rbType->lock != NULL) { - rbType->lock(); - } - - /* Ring buffer has no data */ - if (!Ring_Buffer_Get_Length(rbType)) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return 0; - } - - /* Read data */ - *data = rbType->pointer[rbType->readIndex]; - + * @brief Read 1 byte from ring buffer function, do not remove from buffer actually + * + * @param rbType: Ring buffer type structure pointer + * @param data: Data read + * + * @return Length of data actually read + * + *******************************************************************************/ +uint32_t Ring_Buffer_Peek_Byte(Ring_Buffer_Type *rbType, uint8_t *data) { + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Ring buffer has no data */ + if (!Ring_Buffer_Get_Length(rbType)) { if (rbType->unlock != NULL) { - rbType->unlock(); + rbType->unlock(); } - return 1; -} + return 0; + } -/****************************************************************************/ /** - * @brief Get length of data in ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * - * @return Length of data - * -*******************************************************************************/ -uint32_t Ring_Buffer_Get_Length(Ring_Buffer_Type *rbType) -{ - uint32_t readMirror = 0; - uint32_t writeMirror = 0; - uint32_t readIndex = 0; - uint32_t writeIndex = 0; - uint32_t size = 0; - - if (rbType->lock != NULL) { - rbType->lock(); - } + /* Read data */ + *data = rbType->pointer[rbType->readIndex]; - readMirror = rbType->readMirror; - writeMirror = rbType->writeMirror; - readIndex = rbType->readIndex; - writeIndex = rbType->writeIndex; - size = rbType->size; + if (rbType->unlock != NULL) { + rbType->unlock(); + } - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - if (readMirror == writeMirror) { - return writeIndex - readIndex; - } else { - return size - (readIndex - writeIndex); - } + return 1; } /****************************************************************************/ /** - * @brief Get space remained in ring buffer function - * - * @param rbType: Ring buffer type structure pointer - * - * @return Length of space remained - * -*******************************************************************************/ -uint32_t Ring_Buffer_Get_Empty_Length(Ring_Buffer_Type *rbType) -{ - return (rbType->size - Ring_Buffer_Get_Length(rbType)); + * @brief Get length of data in ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * + * @return Length of data + * + *******************************************************************************/ +uint32_t Ring_Buffer_Get_Length(Ring_Buffer_Type *rbType) { + uint32_t readMirror = 0; + uint32_t writeMirror = 0; + uint32_t readIndex = 0; + uint32_t writeIndex = 0; + uint32_t size = 0; + + if (rbType->lock != NULL) { + rbType->lock(); + } + + readMirror = rbType->readMirror; + writeMirror = rbType->writeMirror; + readIndex = rbType->readIndex; + writeIndex = rbType->writeIndex; + size = rbType->size; + + if (rbType->unlock != NULL) { + rbType->unlock(); + } + + if (readMirror == writeMirror) { + return writeIndex - readIndex; + } else { + return size - (readIndex - writeIndex); + } } /****************************************************************************/ /** - * @brief Get ring buffer status function - * - * @param rbType: Ring buffer type structure pointer - * - * @return Status of ring buffer - * -*******************************************************************************/ -Ring_Buffer_Status_Type Ring_Buffer_Get_Status(Ring_Buffer_Type *rbType) -{ - if (rbType->lock != NULL) { - rbType->lock(); - } + * @brief Get space remained in ring buffer function + * + * @param rbType: Ring buffer type structure pointer + * + * @return Length of space remained + * + *******************************************************************************/ +uint32_t Ring_Buffer_Get_Empty_Length(Ring_Buffer_Type *rbType) { return (rbType->size - Ring_Buffer_Get_Length(rbType)); } - /* Judge empty or full */ - if (rbType->readIndex == rbType->writeIndex) { - if (rbType->readMirror == rbType->writeMirror) { - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return RING_BUFFER_EMPTY; - } else { - if (rbType->unlock != NULL) { - rbType->unlock(); - } - - return RING_BUFFER_FULL; - } - } +/****************************************************************************/ /** + * @brief Get ring buffer status function + * + * @param rbType: Ring buffer type structure pointer + * + * @return Status of ring buffer + * + *******************************************************************************/ +Ring_Buffer_Status_Type Ring_Buffer_Get_Status(Ring_Buffer_Type *rbType) { + if (rbType->lock != NULL) { + rbType->lock(); + } + + /* Judge empty or full */ + if (rbType->readIndex == rbType->writeIndex) { + if (rbType->readMirror == rbType->writeMirror) { + if (rbType->unlock != NULL) { + rbType->unlock(); + } - if (rbType->unlock != NULL) { + return RING_BUFFER_EMPTY; + } else { + if (rbType->unlock != NULL) { rbType->unlock(); + } + + return RING_BUFFER_FULL; } + } + + if (rbType->unlock != NULL) { + rbType->unlock(); + } - return RING_BUFFER_PARTIAL; + return RING_BUFFER_PARTIAL; } /*@} end of group RING_BUFFER_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c index 4c4cbe55c..cf45bff63 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/soft_crc/softcrc.c @@ -28,167 +28,103 @@ // we use 0x8005 here and const uint8_t chCRCHTalbe[] = { - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40 -}; + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40}; const uint8_t chCRCLTalbe[] = { - 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, - 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, - 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, - 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, - 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, - 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, - 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, - 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, - 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, - 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, - 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, - 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, - 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, - 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, - 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, - 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, - 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, - 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, - 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, - 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, - 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, - 0x41, 0x81, 0x80, 0x40 -}; + 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, + 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10, + 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, + 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, + 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, + 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, + 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, + 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40}; -uint16_t BFLB_Soft_CRC16(void *dataIn, uint32_t len) -{ - uint8_t chCRCHi = 0xFF; - uint8_t chCRCLo = 0xFF; - uint16_t wIndex; - uint8_t *data = (uint8_t *)dataIn; +uint16_t BFLB_Soft_CRC16(void *dataIn, uint32_t len) { + uint8_t chCRCHi = 0xFF; + uint8_t chCRCLo = 0xFF; + uint16_t wIndex; + uint8_t *data = (uint8_t *)dataIn; - while (len--) { - wIndex = chCRCLo ^ *data++; - chCRCLo = chCRCHi ^ chCRCHTalbe[wIndex]; - chCRCHi = chCRCLTalbe[wIndex]; - } + while (len--) { + wIndex = chCRCLo ^ *data++; + chCRCLo = chCRCHi ^ chCRCHTalbe[wIndex]; + chCRCHi = chCRCLTalbe[wIndex]; + } - return ((chCRCHi << 8) | chCRCLo); + return ((chCRCHi << 8) | chCRCLo); } /* x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1 */ const uint32_t crc32Tab[256] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d -}; + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, + 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, + 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, + 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, + 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, + 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, + 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, + 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, + 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d}; -uint32_t BFLB_Soft_CRC32_Table(void *dataIn, uint32_t len) -{ - uint32_t crc = 0; - uint8_t *data = (uint8_t *)dataIn; +uint32_t BFLB_Soft_CRC32_Table(void *dataIn, uint32_t len) { + uint32_t crc = 0; + uint8_t *data = (uint8_t *)dataIn; - crc = crc ^ 0xffffffff; + crc = crc ^ 0xffffffff; - while (len--) { - crc = crc32Tab[(crc ^ *data++) & 0xFF] ^ (crc >> 8); - } + while (len--) { + crc = crc32Tab[(crc ^ *data++) & 0xFF] ^ (crc >> 8); + } - return crc ^ 0xffffffff; + return crc ^ 0xffffffff; } /****************************************************************************** -* Name: CRC-32 x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1 -* Poly: 0x4C11DB7 -* Init: 0xFFFFFFF -* Refin: True -* Refout: True -* Xorout: 0xFFFFFFF -* Alias: CRC_32/ADCCP -* Use: WinRAR,ect. -*****************************************************************************/ -uint32_t ATTR_TCM_SECTION BFLB_Soft_CRC32_Ex(uint32_t initial, void *dataIn, uint32_t len) -{ - uint8_t i; - uint32_t crc = ~initial; // Initial value - uint8_t *data=(uint8_t *)dataIn; - - while(len--){ - crc ^= *data++; // crc ^= *data; data++; - for (i = 0; i < 8; ++i){ - if (crc & 1){ - crc = (crc >> 1) ^ 0xEDB88320;// 0xEDB88320= reverse 0x04C11DB7 - }else{ - crc = (crc >> 1); - } - } + * Name: CRC-32 x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1 + * Poly: 0x4C11DB7 + * Init: 0xFFFFFFF + * Refin: True + * Refout: True + * Xorout: 0xFFFFFFF + * Alias: CRC_32/ADCCP + * Use: WinRAR,ect. + *****************************************************************************/ +uint32_t ATTR_TCM_SECTION BFLB_Soft_CRC32_Ex(uint32_t initial, void *dataIn, uint32_t len) { + uint8_t i; + uint32_t crc = ~initial; // Initial value + uint8_t *data = (uint8_t *)dataIn; + + while (len--) { + crc ^= *data++; // crc ^= *data; data++; + for (i = 0; i < 8; ++i) { + if (crc & 1) { + crc = (crc >> 1) ^ 0xEDB88320; // 0xEDB88320= reverse 0x04C11DB7 + } else { + crc = (crc >> 1); + } } - return ~crc; + } + return ~crc; } #ifndef BFLB_USE_ROM_DRIVER __WEAK__ -uint32_t ATTR_TCM_SECTION BFLB_Soft_CRC32(void *dataIn, uint32_t len) -{ - return BFLB_Soft_CRC32_Ex(0,dataIn,len); -} +uint32_t ATTR_TCM_SECTION BFLB_Soft_CRC32(void *dataIn, uint32_t len) { return BFLB_Soft_CRC32_Ex(0, dataIn, len); } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c index 3454ff47a..e74475d41 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/timestamp/timestamp.c @@ -23,114 +23,107 @@ #include "timestamp.h" -#define FOUR_YEAR_DAY ((365 << 2) + 1) //The total number of days in a 4-year cycle -#define TIMEZONE (8) //Beijing time Zone adjustment +#define FOUR_YEAR_DAY ((365 << 2) + 1) // The total number of days in a 4-year cycle +#define TIMEZONE (8) // Beijing time Zone adjustment #define SEC_NUM_PER_DAY (24 * 60 * 60) #define SEC_NUM_PER_HOUR (60 * 60) #define SEC_NUM_PER_MINUTE (60) -static uint8_t month_day[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; //平年 -static uint8_t Leap_month_day[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; //闰年 +static uint8_t month_day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 平年 +static uint8_t Leap_month_day[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 闰年 /** -* @bref judge if it is a leap year -* @para year to be judge -* @return 1:leap year 0: nonleap year -*/ -bool check_leap_year(uint16_t year) -{ - if (year % 4) { - return false; + * @bref judge if it is a leap year + * @para year to be judge + * @return 1:leap year 0: nonleap year + */ +bool check_leap_year(uint16_t year) { + if (year % 4) { + return false; + } else { + if ((year % 100 == 0) && (year % 400 != 0)) { + return false; } else { - if ((year % 100 == 0) && (year % 400 != 0)) { - return false; - } else { - return true; - } + return true; } + } } -void cal_weekday(rtc_time *beijing_time) -{ - uint32_t y,m,d,w; - - y=beijing_time->year; - m=beijing_time->month; - d=beijing_time->day; - - if((m==1)||(m==2)) - { - m+=12; - y--; - } - /* - 把一月和二月看成是上一年的十三月和十四月,例:如果是2004-1-10则换算成:2003-13-10来代入公式计算。 - 以公元元年为参考,公元元年1月1日为星期一
程序如下:
-	利用基姆拉尔森计算日期公式  w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)
-	*/
-	w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400+1)%7;
-
-	beijing_time->week=(uint8_t)w;
+void cal_weekday(rtc_time *beijing_time) {
+  uint32_t y, m, d, w;
+
+  y = beijing_time->year;
+  m = beijing_time->month;
+  d = beijing_time->day;
+
+  if ((m == 1) || (m == 2)) {
+    m += 12;
+    y--;
+  }
+  /*
+  把一月和二月看成是上一年的十三月和十四月,例:如果是2004-1-10则换算成:2003-13-10来代入公式计算。
+  以公元元年为参考,公元元年1月1日为星期一
程序如下:
+  利用基姆拉尔森计算日期公式  w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)
+  */
+  w = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400 + 1) % 7;
+
+  beijing_time->week = (uint8_t)w;
 }
 
-void unixtime2bejingtime(uint32_t unixtime, rtc_time *beijing_time)
-{
-    uint32_t totle_day_num;
-    uint32_t current_sec_num;
-
-    uint16_t remain_day;
+void unixtime2bejingtime(uint32_t unixtime, rtc_time *beijing_time) {
+  uint32_t totle_day_num;
+  uint32_t current_sec_num;
 
-    uint16_t temp_year;
+  uint16_t remain_day;
 
-    uint8_t *p = NULL;
+  uint16_t temp_year;
 
-    totle_day_num = unixtime / SEC_NUM_PER_DAY;   //The total number of days
-    current_sec_num = unixtime % SEC_NUM_PER_DAY; //The number of seconds this day
+  uint8_t *p = NULL;
 
-    /* use the number of seconds this day, To calculate hour\minute\second */
-    beijing_time->hour = current_sec_num / SEC_NUM_PER_HOUR;
-    beijing_time->minute = (current_sec_num % SEC_NUM_PER_HOUR) / SEC_NUM_PER_MINUTE;
-    beijing_time->second = (current_sec_num % SEC_NUM_PER_HOUR) % SEC_NUM_PER_MINUTE;
+  totle_day_num   = unixtime / SEC_NUM_PER_DAY; // The total number of days
+  current_sec_num = unixtime % SEC_NUM_PER_DAY; // The number of seconds this day
 
-    /* Adjust the time zone and check whether the date is +1 */
-    beijing_time->hour += 8;
-    if (beijing_time->hour > 23) {
-        beijing_time->hour -= 24;
-        totle_day_num++;
-    }
+  /* use the number of seconds this day, To calculate hour\minute\second */
+  beijing_time->hour   = current_sec_num / SEC_NUM_PER_HOUR;
+  beijing_time->minute = (current_sec_num % SEC_NUM_PER_HOUR) / SEC_NUM_PER_MINUTE;
+  beijing_time->second = (current_sec_num % SEC_NUM_PER_HOUR) % SEC_NUM_PER_MINUTE;
 
+  /* Adjust the time zone and check whether the date is +1 */
+  beijing_time->hour += 8;
+  if (beijing_time->hour > 23) {
+    beijing_time->hour -= 24;
+    totle_day_num++;
+  }
 
-    /* calculate year */
-    beijing_time->year = 1970 + (totle_day_num / FOUR_YEAR_DAY) * 4; // 4-year as a cycle
-    remain_day = totle_day_num % FOUR_YEAR_DAY;                      //remaining day nym( < 4 year )
+  /* calculate year */
+  beijing_time->year = 1970 + (totle_day_num / FOUR_YEAR_DAY) * 4; // 4-year as a cycle
+  remain_day         = totle_day_num % FOUR_YEAR_DAY;              // remaining day nym( < 4 year )
 
-    /* calculate year & day */
+  /* calculate year & day */
+  temp_year = check_leap_year(beijing_time->year) ? 366 : 365;
+  while (remain_day >= temp_year) {
+    beijing_time->year++;
+    remain_day -= temp_year;
     temp_year = check_leap_year(beijing_time->year) ? 366 : 365;
-    while (remain_day >= temp_year) {
-        beijing_time->year++;
-        remain_day -= temp_year;
-        temp_year = check_leap_year(beijing_time->year) ? 366 : 365;
-    }
-
-    /* Calculate specific dates(month\day)*/
-    p = check_leap_year(beijing_time->year) ? Leap_month_day : month_day;
-    remain_day++; //The actual day starts at 1
-    beijing_time->month = 0;
-    while (remain_day > *(p + beijing_time->month)) {
-        remain_day -= *(p + beijing_time->month);
-        beijing_time->month++;
-    }
-
-    beijing_time->month++; //The actual month starts at 1
-    beijing_time->day = remain_day;
+  }
 
+  /* Calculate specific dates(month\day)*/
+  p = check_leap_year(beijing_time->year) ? Leap_month_day : month_day;
+  remain_day++; // The actual day starts at 1
+  beijing_time->month = 0;
+  while (remain_day > *(p + beijing_time->month)) {
+    remain_day -= *(p + beijing_time->month);
+    beijing_time->month++;
+  }
 
+  beijing_time->month++; // The actual month starts at 1
+  beijing_time->day = remain_day;
 
-	/*利用基姆拉尔森计算日期公式  w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)*/
+  /*利用基姆拉尔森计算日期公式  w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)*/
 
-	beijing_time->week = beijing_time->day + 2*beijing_time->month + 3*(beijing_time->month+1)/5 + \
-	beijing_time->year + beijing_time->year/4 - beijing_time->year/100 +beijing_time->year/400 ;
+  beijing_time->week =
+      beijing_time->day + 2 * beijing_time->month + 3 * (beijing_time->month + 1) / 5 + beijing_time->year + beijing_time->year / 4 - beijing_time->year / 100 + beijing_time->year / 400;
 
-	cal_weekday(beijing_time);
+  cal_weekday(beijing_time);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/bl702_rf/lib/libbl702_rf.a b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/bl702_rf/lib/libbl702_rf.a
index eb99532e4..dc37ffcdb 100644
Binary files a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/bl702_rf/lib/libbl702_rf.a and b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/bl702_rf/lib/libbl702_rf.a differ
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c
index 238b9b202..81a1c69ac 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.c
@@ -1,323 +1,326 @@
 /*****************************************************************************************
-*
-* @file bl_hci_wrapper.c
-*
-* @brief Bouffalo Lab hci wrapper functions
-*
-* Copyright (C) Bouffalo Lab 2018
-*
-* History: 2018-08 crealted by llgong @ Shanghai
-*
-*****************************************************************************************/
+ *
+ * @file bl_hci_wrapper.c
+ *
+ * @brief Bouffalo Lab hci wrapper functions
+ *
+ * Copyright (C) Bouffalo Lab 2018
+ *
+ * History: 2018-08 crealted by llgong @ Shanghai
+ *
+ *****************************************************************************************/
 
-#include 
-#include 
-#include "hci_host.h"
 #include "bl_hci_wrapper.h"
-#include "hci_driver.h"
-#include "../common/include/errno.h"
 #include "byteorder.h"
+#include "errno.h"
+#include "hci_driver.h"
+#include "hci_host.h"
 #include "hci_onchip.h"
+#include 
+#include 
 
 #define DATA_MSG_CNT 10
 
 struct rx_msg_struct data_msg[DATA_MSG_CNT];
-struct k_queue msg_queue;
+struct k_queue       msg_queue;
 #if defined(BFLB_BLE_NOTIFY_ADV_DISCARDED)
 extern void ble_controller_notify_adv_discarded(uint8_t *adv_bd_addr, uint8_t adv_type);
 #endif
 
-struct rx_msg_struct *bl_find_valid_data_msg()
-{
-    struct rx_msg_struct empty_msg;
-    memset(&empty_msg, 0, sizeof(struct rx_msg_struct));
+struct rx_msg_struct *bl_find_valid_data_msg() {
+  struct rx_msg_struct empty_msg;
+  memset(&empty_msg, 0, sizeof(struct rx_msg_struct));
 
-    for (int i = 0; i < DATA_MSG_CNT; i++) {
-        if (!memcmp(&data_msg[i], &empty_msg, sizeof(struct rx_msg_struct))) {
-            return (data_msg + i);
-        }
+  for (int i = 0; i < DATA_MSG_CNT; i++) {
+    if (!memcmp(&data_msg[i], &empty_msg, sizeof(struct rx_msg_struct))) {
+      return (data_msg + i);
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-int bl_onchiphci_send_2_controller(struct net_buf *buf)
-{
-    uint16_t opcode;
-    uint16_t dest_id = 0x00;
-    uint8_t buf_type;
-    uint8_t pkt_type;
-    hci_pkt_struct pkt;
-
-    buf_type = bt_buf_get_type(buf);
-    switch (buf_type) {
-        case BT_BUF_CMD: {
-            struct bt_hci_cmd_hdr *chdr;
-
-            if (buf->len < sizeof(struct bt_hci_cmd_hdr)) {
-                return -EINVAL;
-            }
-
-            chdr = (void *)buf->data;
-
-            if (buf->len < chdr->param_len) {
-                return -EINVAL;
-            }
-
-            pkt_type = BT_HCI_CMD;
-            opcode = sys_le16_to_cpu(chdr->opcode);
-            //move buf to the payload
-            net_buf_pull(buf, sizeof(struct bt_hci_cmd_hdr));
-            switch (opcode) {
-                //ble refer to hci_cmd_desc_tab_le, for the ones of which dest_ll is BLE_CTRL
-                case BT_HCI_OP_LE_CONN_UPDATE:
-                case BT_HCI_OP_LE_READ_CHAN_MAP:
-                case BT_HCI_OP_LE_READ_REMOTE_FEATURES:
-                case BT_HCI_OP_LE_START_ENCRYPTION:
-                case BT_HCI_OP_LE_LTK_REQ_REPLY:
-                case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY:
-                case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY:
-                case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY:
-                case BT_HCI_OP_LE_SET_DATA_LEN:
-                case BT_HCI_OP_LE_READ_PHY:
-                case BT_HCI_OP_LE_SET_PHY:
-                //bredr identify link id, according to dest_id
-                case BT_HCI_OP_READ_REMOTE_FEATURES:
-                case BT_HCI_OP_READ_REMOTE_EXT_FEATURES:
-                case BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE: {
-                    //dest_id is connectin handle
-                    dest_id = buf->data[0];
-                }
-                default:
-                    break;
-            }
-            pkt.p.hci_cmd.opcode = opcode;
-            pkt.p.hci_cmd.param_len = chdr->param_len;
-            pkt.p.hci_cmd.params = buf->data;
-
-            break;
-        }
-
-        case BT_BUF_ACL_OUT: {
-            struct bt_hci_acl_hdr *acl;
-            //connhandle +l2cap field
-            uint16_t connhdl_l2cf, tlt_len;
-
-            if (buf->len < sizeof(struct bt_hci_acl_hdr)) {
-                return -EINVAL;
-            }
-
-            pkt_type = BT_HCI_ACL_DATA;
-            acl = (void *)buf->data;
-            tlt_len = sys_le16_to_cpu(acl->len);
-            connhdl_l2cf = sys_le16_to_cpu(acl->handle);
-            //move buf to the payload
-            net_buf_pull(buf, sizeof(struct bt_hci_acl_hdr));
-
-            if (buf->len < tlt_len) {
-                return -EINVAL;
-            }
-
-            //get connection_handle
-            dest_id = bt_acl_handle(connhdl_l2cf);
-            pkt.p.acl_data.conhdl = dest_id;
-            pkt.p.acl_data.pb_bc_flag = bt_acl_flags(connhdl_l2cf);
-            pkt.p.acl_data.len = tlt_len;
-            pkt.p.acl_data.buffer = (uint8_t *)buf->data;
-
-            break;
-        }
-
-        default:
-            return -EINVAL;
+int bl_onchiphci_send_2_controller(struct net_buf *buf) {
+  uint16_t       opcode;
+  uint16_t       dest_id = 0x00;
+  uint8_t        buf_type;
+  uint8_t        pkt_type;
+  hci_pkt_struct pkt;
+
+  buf_type = bt_buf_get_type(buf);
+  switch (buf_type) {
+  case BT_BUF_CMD: {
+    struct bt_hci_cmd_hdr *chdr;
+
+    if (buf->len < sizeof(struct bt_hci_cmd_hdr)) {
+      return -EINVAL;
     }
 
-    return bt_onchiphci_send(pkt_type, dest_id, &pkt);
-}
+    chdr = (void *)buf->data;
 
-void bl_packet_to_host(uint8_t pkt_type, uint16_t src_id, uint8_t *param, uint8_t param_len, struct net_buf *buf)
-{
-    uint16_t tlt_len;
-    bool prio = true;
-    uint8_t nb_h2c_cmd_pkts = 0x01;
-
-    uint8_t *buf_data = net_buf_tail(buf);
-    bt_buf_set_rx_adv(buf, false);
-
-    switch (pkt_type) {
-        case BT_HCI_CMD_CMP_EVT: {
-            tlt_len = BT_HCI_EVT_CC_PARAM_OFFSET + param_len;
-            *buf_data++ = BT_HCI_EVT_CMD_COMPLETE;
-            *buf_data++ = BT_HCI_CCEVT_HDR_PARLEN + param_len;
-            *buf_data++ = nb_h2c_cmd_pkts;
-            sys_put_le16(src_id, buf_data);
-            buf_data += 2;
-            memcpy(buf_data, param, param_len);
-            break;
-        }
-        case BT_HCI_CMD_STAT_EVT: {
-            tlt_len = BT_HCI_CSEVT_LEN;
-            *buf_data++ = BT_HCI_EVT_CMD_STATUS;
-            *buf_data++ = BT_HCI_CSVT_PARLEN;
-            *buf_data++ = *(uint8_t *)param;
-            *buf_data++ = nb_h2c_cmd_pkts;
-            sys_put_le16(src_id, buf_data);
-            break;
-        }
-        case BT_HCI_LE_EVT: {
-            prio = false;
-            bt_buf_set_type(buf, BT_BUF_EVT);
-            if (param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) {
-                bt_buf_set_rx_adv(buf, true);
-            }
-            tlt_len = BT_HCI_EVT_LE_PARAM_OFFSET + param_len;
-            *buf_data++ = BT_HCI_EVT_LE_META_EVENT;
-            *buf_data++ = param_len;
-            memcpy(buf_data, param, param_len);
-            break;
-        }
-        case BT_HCI_EVT: {
-            if (src_id != BT_HCI_EVT_NUM_COMPLETED_PACKETS) {
-                prio = false;
-            }
-            bt_buf_set_type(buf, BT_BUF_EVT);
-            tlt_len = BT_HCI_EVT_LE_PARAM_OFFSET + param_len;
-            *buf_data++ = src_id;
-            *buf_data++ = param_len;
-            memcpy(buf_data, param, param_len);
-            break;
-        }
-        case BT_HCI_ACL_DATA: {
-            prio = false;
-            bt_buf_set_type(buf, BT_BUF_ACL_IN);
-            tlt_len = bt_onchiphci_hanlde_rx_acl(param, buf_data);
-            break;
-        }
-        default: {
-            net_buf_unref(buf);
-            return;
-        }
+    if (buf->len < chdr->param_len) {
+      return -EINVAL;
     }
 
-    net_buf_add(buf, tlt_len);
+    pkt_type = BT_HCI_CMD;
+    opcode   = sys_le16_to_cpu(chdr->opcode);
+    // move buf to the payload
+    net_buf_pull(buf, sizeof(struct bt_hci_cmd_hdr));
+    switch (opcode) {
+    // ble refer to hci_cmd_desc_tab_le, for the ones of which dest_ll is BLE_CTRL
+    case BT_HCI_OP_LE_CONN_UPDATE:
+    case BT_HCI_OP_LE_READ_CHAN_MAP:
+    case BT_HCI_OP_LE_READ_REMOTE_FEATURES:
+    case BT_HCI_OP_LE_START_ENCRYPTION:
+    case BT_HCI_OP_LE_LTK_REQ_REPLY:
+    case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY:
+    case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY:
+    case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY:
+    case BT_HCI_OP_LE_SET_DATA_LEN:
+    case BT_HCI_OP_LE_READ_PHY:
+    case BT_HCI_OP_LE_SET_PHY:
+    // bredr identify link id, according to dest_id
+    case BT_HCI_OP_READ_REMOTE_FEATURES:
+    case BT_HCI_OP_READ_REMOTE_EXT_FEATURES:
+    case BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE: {
+      // dest_id is connectin handle
+      dest_id = buf->data[0];
+    }
+    default:
+      break;
+    }
+    pkt.p.hci_cmd.opcode    = opcode;
+    pkt.p.hci_cmd.param_len = chdr->param_len;
+    pkt.p.hci_cmd.params    = buf->data;
 
-    if (prio) {
-        bt_recv_prio(buf);
-    } else {
-        hci_driver_enque_recvq(buf);
+    break;
+  }
+
+  case BT_BUF_ACL_OUT: {
+    struct bt_hci_acl_hdr *acl;
+    // connhandle +l2cap field
+    uint16_t connhdl_l2cf, tlt_len;
+
+    if (buf->len < sizeof(struct bt_hci_acl_hdr)) {
+      return -EINVAL;
     }
+
+    pkt_type     = BT_HCI_ACL_DATA;
+    acl          = (void *)buf->data;
+    tlt_len      = sys_le16_to_cpu(acl->len);
+    connhdl_l2cf = sys_le16_to_cpu(acl->handle);
+    // move buf to the payload
+    net_buf_pull(buf, sizeof(struct bt_hci_acl_hdr));
+
+    if (buf->len < tlt_len) {
+      return -EINVAL;
+    }
+
+    // get connection_handle
+    dest_id                   = bt_acl_handle(connhdl_l2cf);
+    pkt.p.acl_data.conhdl     = dest_id;
+    pkt.p.acl_data.pb_bc_flag = bt_acl_flags(connhdl_l2cf);
+    pkt.p.acl_data.len        = tlt_len;
+    pkt.p.acl_data.buffer     = (uint8_t *)buf->data;
+
+    break;
+  }
+
+  default:
+    return -EINVAL;
+  }
+
+  return bt_onchiphci_send(pkt_type, dest_id, &pkt);
 }
 
-void bl_trigger_queued_msg()
-{
-    struct net_buf *buf = NULL;
-    struct rx_msg_struct *msg = NULL;
+void bl_packet_to_host(uint8_t pkt_type, uint16_t src_id, uint8_t *param, uint8_t param_len, struct net_buf *buf) {
+  uint16_t tlt_len;
+  bool     prio            = true;
+  uint8_t  nb_h2c_cmd_pkts = 0x01;
+
+  uint8_t *buf_data = net_buf_tail(buf);
+  bt_buf_set_rx_adv(buf, false);
+
+  switch (pkt_type) {
+  case BT_HCI_CMD_CMP_EVT: {
+    tlt_len     = BT_HCI_EVT_CC_PARAM_OFFSET + param_len;
+    *buf_data++ = BT_HCI_EVT_CMD_COMPLETE;
+    *buf_data++ = BT_HCI_CCEVT_HDR_PARLEN + param_len;
+    *buf_data++ = nb_h2c_cmd_pkts;
+    sys_put_le16(src_id, buf_data);
+    buf_data += 2;
+    memcpy(buf_data, param, param_len);
+    break;
+  }
+  case BT_HCI_CMD_STAT_EVT: {
+    tlt_len     = BT_HCI_CSEVT_LEN;
+    *buf_data++ = BT_HCI_EVT_CMD_STATUS;
+    *buf_data++ = BT_HCI_CSVT_PARLEN;
+    *buf_data++ = *(uint8_t *)param;
+    *buf_data++ = nb_h2c_cmd_pkts;
+    sys_put_le16(src_id, buf_data);
+    break;
+  }
+  case BT_HCI_LE_EVT: {
+    prio = false;
+    bt_buf_set_type(buf, BT_BUF_EVT);
+    if (param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) {
+      bt_buf_set_rx_adv(buf, true);
+    }
+    tlt_len     = BT_HCI_EVT_LE_PARAM_OFFSET + param_len;
+    *buf_data++ = BT_HCI_EVT_LE_META_EVENT;
+    *buf_data++ = param_len;
+    memcpy(buf_data, param, param_len);
+    break;
+  }
+  case BT_HCI_EVT: {
+    if (src_id != BT_HCI_EVT_NUM_COMPLETED_PACKETS) {
+      prio = false;
+    }
+    bt_buf_set_type(buf, BT_BUF_EVT);
+    tlt_len     = BT_HCI_EVT_LE_PARAM_OFFSET + param_len;
+    *buf_data++ = src_id;
+    *buf_data++ = param_len;
+    memcpy(buf_data, param, param_len);
+    break;
+  }
+#if defined(CONFIG_BT_CONN)
+  case BT_HCI_ACL_DATA: {
+    prio = false;
+    bt_buf_set_type(buf, BT_BUF_ACL_IN);
+    tlt_len = bt_onchiphci_hanlde_rx_acl(param, buf_data);
+    break;
+  }
+#endif
+  default: {
+    net_buf_unref(buf);
+    return;
+  }
+  }
+
+  net_buf_add(buf, tlt_len);
+
+  if (prio) {
+    bt_recv_prio(buf);
+  } else {
+    hci_driver_enque_recvq(buf);
+  }
+}
 
-    do {
-        unsigned int lock = irq_lock();
+void bl_trigger_queued_msg() {
+  struct net_buf       *buf = NULL;
+  struct rx_msg_struct *msg = NULL;
 
-        if (k_queue_is_empty(&msg_queue)) {
-            break;
-        }
+  do {
+    unsigned int lock = irq_lock();
 
-        if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT)
-            break;
+    if (k_queue_is_empty(&msg_queue)) {
+      irq_unlock(lock);
+      break;
+    }
 
-        buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
-        if (!buf) {
-            break;
-        }
+    if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT) {
+      irq_unlock(lock);
+      break;
+    }
 
-        msg = k_fifo_get(&msg_queue, K_NO_WAIT);
+    buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
+    if (!buf) {
+      irq_unlock(lock);
+      break;
+    }
 
-        BT_ASSERT(msg);
+    msg = k_fifo_get(&msg_queue, K_NO_WAIT);
 
-        bl_packet_to_host(msg->pkt_type, msg->src_id, msg->param, msg->param_len, buf);
+    BT_ASSERT(msg);
 
-        irq_unlock(lock);
+    bl_packet_to_host(msg->pkt_type, msg->src_id, msg->param, msg->param_len, buf);
 
-        if (msg->param) {
-            k_free(msg->param);
-        }
-        memset(msg, 0, sizeof(struct rx_msg_struct));
+    irq_unlock(lock);
 
-    } while (buf);
-}
+    if (msg->param) {
+      k_free(msg->param);
+    }
+    memset(msg, 0, sizeof(struct rx_msg_struct));
 
-static void bl_onchiphci_rx_packet_handler(uint8_t pkt_type, uint16_t src_id, uint8_t *param, uint8_t param_len)
-{
-    struct net_buf *buf = NULL;
-    struct rx_msg_struct *rx_msg = NULL;
+  } while (buf);
+}
 
-    if (pkt_type == BT_HCI_CMD_CMP_EVT || pkt_type == BT_HCI_CMD_STAT_EVT) {
-        buf = bt_buf_get_cmd_complete(K_FOREVER);
-        bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
-        return;
-    } else if (pkt_type == BT_HCI_LE_EVT && param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) {
-        if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT) {
-            BT_INFO("Discard adv report.");
+static void bl_onchiphci_rx_packet_handler(uint8_t pkt_type, uint16_t src_id, uint8_t *param, uint8_t param_len) {
+  struct net_buf       *buf    = NULL;
+  struct rx_msg_struct *rx_msg = NULL;
+
+  if (pkt_type == BT_HCI_CMD_CMP_EVT || pkt_type == BT_HCI_CMD_STAT_EVT) {
+    buf = bt_buf_get_cmd_complete(K_FOREVER);
+    bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
+    return;
+  }
+#if defined(CONFIG_BT_OBSERVER) || defined(CONFIG_BT_CENTRAL) || defined(CONFIG_BT_ALLROLES)
+  else if (pkt_type == BT_HCI_LE_EVT && param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) {
+    if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT) {
+      BT_INFO("Discard adv report.");
 #if defined(BFLB_BLE_NOTIFY_ADV_DISCARDED)
-            ble_controller_notify_adv_discarded(¶m[4], param[2]);
+      ble_controller_notify_adv_discarded(¶m[4], param[2]);
 #endif
-            return;
-        }
-        buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
-        if (buf)
-            bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
+      return;
+    }
+    buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
+    if (buf)
+      bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
+    return;
+  }
+#endif /*(CONFIG_BT_OBSERVER || CONFIG_BT_CENTRAL || CONFIG_BT_ALLROLES)*/
+  else {
+    if (pkt_type != BT_HCI_ACL_DATA) {
+      /* Using the reserved buf (CONFIG_BT_RX_BUF_RSV_COUNT) firstly. */
+      buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
+      if (buf) {
+        bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
         return;
-    } else {
-        if (pkt_type != BT_HCI_ACL_DATA) {
-            /* Using the reserved buf (CONFIG_BT_RX_BUF_RSV_COUNT) firstly. */
-            buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
-            if (buf) {
-                bl_packet_to_host(pkt_type, src_id, param, param_len, buf);
-                return;
-            }
-        }
-
-        rx_msg = bl_find_valid_data_msg();
+      }
     }
 
-    BT_ASSERT(rx_msg);
+    rx_msg = bl_find_valid_data_msg();
+  }
 
-    rx_msg->pkt_type = pkt_type;
-    rx_msg->src_id = src_id;
-    rx_msg->param_len = param_len;
-    if (param_len) {
-        rx_msg->param = k_malloc(param_len);
-        memcpy(rx_msg->param, param, param_len);
-    }
+  BT_ASSERT(rx_msg);
+
+  rx_msg->pkt_type  = pkt_type;
+  rx_msg->src_id    = src_id;
+  rx_msg->param_len = param_len;
+  if (param_len) {
+    rx_msg->param = k_malloc(param_len);
+    memcpy(rx_msg->param, param, param_len);
+  }
 
-    k_fifo_put(&msg_queue, rx_msg);
+  k_fifo_put(&msg_queue, rx_msg);
 
-    bl_trigger_queued_msg();
+  bl_trigger_queued_msg();
 }
 
-uint8_t bl_onchiphci_interface_init(void)
-{
-    for (int i = 0; i < DATA_MSG_CNT; i++) {
-        memset(data_msg + i, 0, sizeof(struct rx_msg_struct));
-    }
+uint8_t bl_onchiphci_interface_init(void) {
+  for (int i = 0; i < DATA_MSG_CNT; i++) {
+    memset(data_msg + i, 0, sizeof(struct rx_msg_struct));
+  }
 
-    k_queue_init(&msg_queue, DATA_MSG_CNT);
+  k_queue_init(&msg_queue, DATA_MSG_CNT);
 
-    return bt_onchiphci_interface_init(bl_onchiphci_rx_packet_handler);
+  return bt_onchiphci_interface_init(bl_onchiphci_rx_packet_handler);
 }
 
-void bl_onchiphci_interface_deinit(void)
-{
-    struct rx_msg_struct *msg;
-
-    do {
-        msg = k_fifo_get(&msg_queue, K_NO_WAIT);
-        if (msg) {
-            if (msg->param) {
-                k_free(msg->param);
-            }
-        } else {
-            break;
-        }
-    } while (1);
-
-    k_queue_free(&msg_queue);
+void bl_onchiphci_interface_deinit(void) {
+  struct rx_msg_struct *msg;
+
+  do {
+    msg = k_fifo_get(&msg_queue, K_NO_WAIT);
+    if (msg) {
+      if (msg->param) {
+        k_free(msg->param);
+      }
+    } else {
+      break;
+    }
+  } while (1);
+
+  k_queue_free(&msg_queue);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.h
index 6d13fa9a0..7f97f4d8f 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/bl_hci_wrapper/bl_hci_wrapper.h
@@ -1,26 +1,21 @@
 #ifndef __BL_HCI_WRAPPER_H__
 #define __BL_HCI_WRAPPER_H__
 
-#include "net/buf.h"
 #include "bluetooth.h"
+#include "net/buf.h"
 
 struct rx_msg_struct {
-    uint8_t pkt_type;
-    uint16_t src_id;
-    uint8_t *param;
-    uint8_t param_len;
+  uint8_t  pkt_type;
+  uint16_t src_id;
+  uint8_t *param;
+  uint8_t  param_len;
 } __packed;
 
-typedef enum {
-    DATA_TYPE_COMMAND = 1,
-    DATA_TYPE_ACL = 2,
-    DATA_TYPE_SCO = 3,
-    DATA_TYPE_EVENT = 4
-} serial_data_type_t;
+typedef enum { DATA_TYPE_COMMAND = 1, DATA_TYPE_ACL = 2, DATA_TYPE_SCO = 3, DATA_TYPE_EVENT = 4 } serial_data_type_t;
 
 uint8_t bl_onchiphci_interface_init(void);
-void bl_onchiphci_interface_deinit(void);
-void bl_trigger_queued_msg(void);
-int bl_onchiphci_send_2_controller(struct net_buf *buf);
+void    bl_onchiphci_interface_deinit(void);
+void    bl_trigger_queued_msg(void);
+int     bl_onchiphci_send_2_controller(struct net_buf *buf);
 
 #endif //__BL_CONTROLLER_H__
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/atomic_c.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/atomic_c.c
index 25c27fb66..9f46a6e6a 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/atomic_c.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/atomic_c.c
@@ -17,11 +17,11 @@
  *
  * (originally from x86's atomic.c)
  */
-#include 
-#include 
+
 #include "bl_port.h"
-//#include 
-//#include 
+#include 
+// #include 
+// #include 
 
 /**
  *
@@ -43,22 +43,20 @@
  * @param new_value value to compare against
  * @return Returns 1 if  is written, 0 otherwise.
  */
-int atomic_cas(atomic_t *target, atomic_val_t old_value,
-               atomic_val_t new_value)
-{
-    unsigned int key;
-    int ret = 0;
+int atomic_cas(atomic_t *target, atomic_val_t old_value, atomic_val_t new_value) {
+  unsigned int key;
+  int          ret = 0;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    if (*target == old_value) {
-        *target = new_value;
-        ret = 1;
-    }
+  if (*target == old_value) {
+    *target = new_value;
+    ret     = 1;
+  }
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -74,19 +72,18 @@ int atomic_cas(atomic_t *target, atomic_val_t old_value,
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_add(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_add(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target += value;
+  ret = *target;
+  *target += value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -102,19 +99,18 @@ atomic_val_t atomic_add(atomic_t *target, atomic_val_t value)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target -= value;
+  ret = *target;
+  *target -= value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -128,19 +124,18 @@ atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value)
  *
  * @return The value from  before the increment
  */
-atomic_val_t atomic_inc(atomic_t *target)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_inc(atomic_t *target) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    (*target)++;
+  ret = *target;
+  (*target)++;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -154,19 +149,18 @@ atomic_val_t atomic_inc(atomic_t *target)
  *
  * @return The value from  prior to the decrement
  */
-atomic_val_t atomic_dec(atomic_t *target)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_dec(atomic_t *target) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    (*target)--;
+  ret = *target;
+  (*target)--;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -181,10 +175,7 @@ atomic_val_t atomic_dec(atomic_t *target)
  *
  * @return The value read from 
  */
-atomic_val_t atomic_get(const atomic_t *target)
-{
-    return *target;
-}
+atomic_val_t atomic_get(const atomic_t *target) { return *target; }
 
 /**
  *
@@ -198,19 +189,18 @@ atomic_val_t atomic_get(const atomic_t *target)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_set(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_set(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target = value;
+  ret     = *target;
+  *target = value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -225,19 +215,18 @@ atomic_val_t atomic_set(atomic_t *target, atomic_val_t value)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_clear(atomic_t *target)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_clear(atomic_t *target) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target = 0;
+  ret     = *target;
+  *target = 0;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -253,19 +242,18 @@ atomic_val_t atomic_clear(atomic_t *target)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_or(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_or(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target |= value;
+  ret = *target;
+  *target |= value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -281,19 +269,18 @@ atomic_val_t atomic_or(atomic_t *target, atomic_val_t value)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target ^= value;
+  ret = *target;
+  *target ^= value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -309,19 +296,18 @@ atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_and(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_and(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target &= value;
+  ret = *target;
+  *target &= value;
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -337,17 +323,16 @@ atomic_val_t atomic_and(atomic_t *target, atomic_val_t value)
  *
  * @return The previous value from 
  */
-atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value)
-{
-    unsigned int key;
-    atomic_val_t ret;
+atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value) {
+  unsigned int key;
+  atomic_val_t ret;
 
-    key = irq_lock();
+  key = irq_lock();
 
-    ret = *target;
-    *target = ~(*target & value);
+  ret     = *target;
+  *target = ~(*target & value);
 
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return ret;
+  return ret;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c
index 44bdbda0d..f9ded7d6d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/buf.c
@@ -13,14 +13,14 @@
 #endif
 
 #include 
-//LOG_MODULE_REGISTER(LOG_MODULE_NAME);
+// LOG_MODULE_REGISTER(LOG_MODULE_NAME);
 
-#include 
 #include 
-#include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
 #if defined(BFLB_BLE)
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
 #include "bl_port.h"
@@ -28,18 +28,21 @@
 #include "bl_hci_wrapper.h"
 #endif
 
+#if (BFLB_STATIC_ALLOC_MEM)
+#include "l2cap.h"
+#endif
+
 #if defined(CONFIG_NET_BUF_LOG)
-#define NET_BUF_DBG(fmt, ...) LOG_DBG("(%p) " fmt, k_current_get(), \
-                                      ##__VA_ARGS__)
+#define NET_BUF_DBG(fmt, ...)  LOG_DBG("(%p) " fmt, k_current_get(), ##__VA_ARGS__)
 #define NET_BUF_ERR(fmt, ...)  LOG_ERR(fmt, ##__VA_ARGS__)
 #define NET_BUF_WARN(fmt, ...) LOG_WRN(fmt, ##__VA_ARGS__)
 #define NET_BUF_INFO(fmt, ...) LOG_INF(fmt, ##__VA_ARGS__)
-#define NET_BUF_ASSERT(cond)                           \
-    do {                                               \
-        if (!(cond)) {                                 \
-            NET_BUF_ERR("assert: '" #cond "' failed"); \
-        }                                              \
-    } while (0)
+#define NET_BUF_ASSERT(cond)                                                                                                                                                                           \
+  do {                                                                                                                                                                                                 \
+    if (!(cond)) {                                                                                                                                                                                     \
+      NET_BUF_ERR("assert: '" #cond "' failed");                                                                                                                                                       \
+    }                                                                                                                                                                                                  \
+  } while (0)
 #else
 
 #define NET_BUF_DBG(fmt, ...)
@@ -50,7 +53,7 @@
 #endif /* CONFIG_NET_BUF_LOG */
 
 #if defined(CONFIG_NET_BUF_WARN_ALLOC_INTERVAL) && (CONFIG_NET_BUF_WARN_ALLOC_INTERVAL > 0)
-//#if CONFIG_NET_BUF_WARN_ALLOC_INTERVAL > 0
+// #if CONFIG_NET_BUF_WARN_ALLOC_INTERVAL > 0
 #define WARN_ALLOC_INTERVAL K_SECONDS(CONFIG_NET_BUF_WARN_ALLOC_INTERVAL)
 #else
 #define WARN_ALLOC_INTERVAL K_FOREVER
@@ -59,28 +62,48 @@
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
 extern struct net_buf_pool hci_cmd_pool;
 extern struct net_buf_pool hci_rx_pool;
+#if (BFLB_STATIC_ALLOC_MEM)
+__attribute__((section(".tcm_data"))) u8_t hci_cmd_data_pool[CONFIG_BT_HCI_CMD_COUNT * BT_BUF_RX_SIZE];
+__attribute__((section(".tcm_data"))) u8_t hci_rx_data_pool[CONFIG_BT_RX_BUF_COUNT * BT_BUF_RX_SIZE];
+#endif
 #if defined(CONFIG_BT_CONN)
 extern struct net_buf_pool acl_tx_pool;
 extern struct net_buf_pool num_complete_pool;
+#if (BFLB_STATIC_ALLOC_MEM)
+__attribute__((section(".tcm_data"))) u8_t acl_tx_data_pool[CONFIG_BT_L2CAP_TX_BUF_COUNT * BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU)];
+__attribute__((section(".tcm_data"))) u8_t num_complete_data_pool[1 * BT_BUF_RX_SIZE];
+#endif
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
 extern struct net_buf_pool prep_pool;
+#if (BFLB_STATIC_ALLOC_MEM)
+__attribute__((section(".tcm_data"))) u8_t prep_data_pool[CONFIG_BT_ATT_PREPARE_COUNT * BT_ATT_MTU];
+#endif
 #endif
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
 extern struct net_buf_pool acl_in_pool;
+#if (BFLB_STATIC_ALLOC_MEM)
+__attribute__((section(".tcm_data"))) u8_t acl_in_data_pool[CONFIG_BT_ACL_RX_COUNT * ACL_IN_SIZE];
+#endif
 #endif
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
 extern struct net_buf_pool frag_pool;
+#if (BFLB_STATIC_ALLOC_MEM)
+__attribute__((section(".tcm_data"))) u8_t frag_data_pool[CONFIG_BT_L2CAP_TX_FRAG_COUNT * FRAG_SIZE];
+#endif
 #endif
-#endif //CONFIG_BT_CONN
+#endif // CONFIG_BT_CONN
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
 extern struct net_buf_pool discardable_pool;
+#if (BFLB_STATIC_ALLOC_MEM)
+__attribute__((section(".tcm_data"))) u8_t discardable_data_pool[CONFIG_BT_DISCARDABLE_BUF_COUNT * BT_BUF_RX_SIZE];
+#endif
 #endif
 #ifdef CONFIG_BT_MESH
 extern struct net_buf_pool adv_buf_pool;
 extern struct net_buf_pool loopback_buf_pool;
 #if defined(CONFIG_BT_MESH_FRIEND)
 extern struct net_buf_pool friend_buf_pool;
-#endif //CONFIG_BT_MESH_FRIEND
+#endif // CONFIG_BT_MESH_FRIEND
 #endif
 #if defined(CONFIG_BT_BREDR)
 extern struct net_buf_pool br_sig_pool;
@@ -95,12 +118,10 @@ extern struct net_buf_pool data_pool;
 #endif
 
 struct net_buf_pool *_net_buf_pool_list[] = {
-    &hci_cmd_pool,
-    &hci_rx_pool,
+    &hci_cmd_pool,    &hci_rx_pool,
 
 #if defined(CONFIG_BT_CONN)
-    &acl_tx_pool,
-    &num_complete_pool,
+    &acl_tx_pool,     &num_complete_pool,
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
     &prep_pool,
 #endif
@@ -110,194 +131,219 @@ struct net_buf_pool *_net_buf_pool_list[] = {
 #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
     &frag_pool,
 #endif
-#endif //defined(CONFIG_BT_CONN)
+#endif // defined(CONFIG_BT_CONN)
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
     discardable_pool,
 #endif
 #ifdef CONFIG_BT_MESH
-    &adv_buf_pool,
-    &loopback_buf_pool,
+    &adv_buf_pool,    &loopback_buf_pool,
 #if defined(CONFIG_BT_MESH_FRIEND)
     &friend_buf_pool,
 #endif
 #endif
 #if defined(CONFIG_BT_BREDR)
-    &sdp_pool,
-    &br_sig_pool,
-    &hf_pool,
-    &dummy_pool,
+    &sdp_pool,        &br_sig_pool,       &hf_pool, &dummy_pool,
 #endif
 #if defined(CONFIG_AUTO_PTS)
-    &server_pool,
-    &data_pool,
+    &server_pool,     &data_pool,
 #endif
 };
 
 #else
 extern struct net_buf_pool _net_buf_pool_list[];
-#endif //BFLB_DYNAMIC_ALLOC_MEM
+#endif // BFLB_DYNAMIC_ALLOC_MEM
 
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
+#if (BFLB_STATIC_ALLOC_MEM)
+void net_buf_init(u8_t buf_type, struct net_buf_pool *buf_pool, u16_t buf_count, size_t data_size, destroy_cb_t destroy)
+#else
 void net_buf_init(struct net_buf_pool *buf_pool, u16_t buf_count, size_t data_size, destroy_cb_t destroy)
+#endif
 {
-    struct net_buf_pool_fixed *buf_fixed;
-    buf_pool->alloc = (struct net_buf_data_alloc *)k_malloc(sizeof(void *));
-    buf_pool->alloc->alloc_data = (struct net_buf_pool_fixed *)k_malloc(sizeof(void *));
-
-    buf_fixed = (struct net_buf_pool_fixed *)buf_pool->alloc->alloc_data;
-
-    buf_pool->alloc->cb = &net_buf_fixed_cb;
-    buf_fixed->data_size = data_size;
-    buf_fixed->data_pool = (u8_t *)k_malloc(buf_count * data_size);
-    buf_pool->__bufs = (struct net_buf *)k_malloc(buf_count * sizeof(struct net_buf));
-    buf_pool->buf_count = buf_count;
-    buf_pool->uninit_count = buf_count;
+  struct net_buf_pool_fixed *buf_fixed;
+  buf_pool->alloc             = (struct net_buf_data_alloc *)k_malloc(sizeof(struct net_buf_data_alloc));
+  buf_pool->alloc->alloc_data = (struct net_buf_pool_fixed *)k_malloc(sizeof(struct net_buf_pool_fixed));
+
+  buf_fixed = (struct net_buf_pool_fixed *)buf_pool->alloc->alloc_data;
+
+  buf_pool->alloc->cb  = &net_buf_fixed_cb;
+  buf_fixed->data_size = data_size;
+#if (BFLB_STATIC_ALLOC_MEM)
+  switch (buf_type) {
+  case HCI_CMD:
+    buf_fixed->data_pool = hci_cmd_data_pool;
+    break;
+  case HCI_RX:
+    buf_fixed->data_pool = hci_rx_data_pool;
+    break;
+#if defined(CONFIG_BT_CONN)
+  case ACL_TX:
+    buf_fixed->data_pool = acl_tx_data_pool;
+    break;
+  case NUM_COMPLETE:
+    buf_fixed->data_pool = num_complete_data_pool;
+    break;
+#if CONFIG_BT_ATT_PREPARE_COUNT > 0
+  case PREP:
+    buf_fixed->data_pool = prep_data_pool;
+    break;
+#endif
+#if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
+  case ACL_IN:
+    buf_fixed->data_pool = acl_in_data_pool;
+    break;
+#endif
+#if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
+  case FRAG:
+    buf_fixed->data_pool = frag_data_pool;
+    break;
+#endif
+#endif
+#if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
+  case DISCARDABLE:
+    buf_fixed->data_pool = discardable_data_pool;
+    break;
+#endif
+  default:
+    break;
+  }
+#else
+  buf_fixed->data_pool = (u8_t *)k_malloc(buf_count * data_size);
+#endif
+  buf_pool->__bufs       = (struct net_buf *)k_malloc(buf_count * sizeof(struct net_buf));
+  buf_pool->buf_count    = buf_count;
+  buf_pool->uninit_count = buf_count;
 #if defined(CONFIG_NET_BUF_POOL_USAGE)
-    buf_pool->avail_count = buf_count;
+  buf_pool->avail_count = buf_count;
 #endif
-    buf_pool->destroy = destroy;
+  buf_pool->destroy = destroy;
 
-    k_lifo_init(&(buf_pool->free), buf_count);
+  k_lifo_init(&(buf_pool->free), buf_count);
 }
 
-void net_buf_deinit(struct net_buf_pool *buf_pool)
-{
-    extern void bt_delete_queue(struct k_fifo * queue_to_del);
-    bt_delete_queue((struct k_fifo *)(&(buf_pool->free)));
-
-    struct net_buf_pool_fixed *buf_fixed = (struct net_buf_pool_fixed *)buf_pool->alloc->alloc_data;
-    k_free(buf_fixed->data_pool);
-    k_free(buf_pool->__bufs);
-    k_free(buf_pool->alloc->alloc_data);
-    k_free(buf_pool->alloc);
+void net_buf_deinit(struct net_buf_pool *buf_pool) {
+  extern void bt_delete_queue(struct k_fifo * queue_to_del);
+  bt_delete_queue((struct k_fifo *)(&(buf_pool->free)));
+
+  struct net_buf_pool_fixed *buf_fixed = (struct net_buf_pool_fixed *)buf_pool->alloc->alloc_data;
+#if !(BFLB_STATIC_ALLOC_MEM)
+  k_free(buf_fixed->data_pool);
+#endif
+  k_free(buf_pool->__bufs);
+  k_free(buf_pool->alloc->alloc_data);
+  k_free(buf_pool->alloc);
 }
 #endif
 
-struct net_buf_pool *net_buf_pool_get(int id)
-{
+struct net_buf_pool *net_buf_pool_get(int id) {
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    return _net_buf_pool_list[id];
+  return _net_buf_pool_list[id];
 #else
-    return &_net_buf_pool_list[id];
+  return &_net_buf_pool_list[id];
 #endif
 }
 
-static int pool_id(struct net_buf_pool *pool)
-{
+static int pool_id(struct net_buf_pool *pool) {
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    int index;
+  int index;
 
-    for (index = 0; index < (sizeof(_net_buf_pool_list) / 4); index++) {
-        if (_net_buf_pool_list[index] == pool) {
-            break;
-        }
+  for (index = 0; index < (sizeof(_net_buf_pool_list) / 4); index++) {
+    if (_net_buf_pool_list[index] == pool) {
+      break;
     }
-    NET_BUF_ASSERT(index < (sizeof(_net_buf_pool_list) / 4));
-    return index;
+  }
+  NET_BUF_ASSERT(index < (sizeof(_net_buf_pool_list) / 4));
+  return index;
 #else
-    return pool - _net_buf_pool_list;
+  return pool - _net_buf_pool_list;
 #endif
 }
 
-int net_buf_id(struct net_buf *buf)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
+int net_buf_id(struct net_buf *buf) {
+  struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
 
-    return buf - pool->__bufs;
+  return buf - pool->__bufs;
 }
 
-static inline struct net_buf *pool_get_uninit(struct net_buf_pool *pool,
-                                              u16_t uninit_count)
-{
-    struct net_buf *buf;
+static inline struct net_buf *pool_get_uninit(struct net_buf_pool *pool, u16_t uninit_count) {
+  struct net_buf *buf;
 
-    buf = &pool->__bufs[pool->buf_count - uninit_count];
+  buf = &pool->__bufs[pool->buf_count - uninit_count];
 
-    buf->pool_id = pool_id(pool);
+  buf->pool_id = pool_id(pool);
 
-    return buf;
+  return buf;
 }
 
-void net_buf_reset(struct net_buf *buf)
-{
-    NET_BUF_ASSERT(buf->flags == 0U);
-    NET_BUF_ASSERT(buf->frags == NULL);
+void net_buf_reset(struct net_buf *buf) {
+  NET_BUF_ASSERT(buf->flags == 0U);
+  NET_BUF_ASSERT(buf->frags == NULL);
 
-    net_buf_simple_reset(&buf->b);
+  net_buf_simple_reset(&buf->b);
 }
 
 #if !defined(BFLB_BLE)
-static u8_t *generic_data_ref(struct net_buf *buf, u8_t *data)
-{
-    u8_t *ref_count;
+static u8_t *generic_data_ref(struct net_buf *buf, u8_t *data) {
+  u8_t *ref_count;
 
-    ref_count = data - 1;
-    (*ref_count)++;
+  ref_count = data - 1;
+  (*ref_count)++;
 
-    return data;
+  return data;
 }
 
-static u8_t *mem_pool_data_alloc(struct net_buf *buf, size_t *size,
-                                 s32_t timeout)
-{
-    struct net_buf_pool *buf_pool = net_buf_pool_get(buf->pool_id);
-    struct k_mem_pool *pool = buf_pool->alloc->alloc_data;
-    struct k_mem_block block;
-    u8_t *ref_count;
-
-    /* Reserve extra space for k_mem_block_id and ref-count (u8_t) */
-    if (k_mem_pool_alloc(pool, &block,
-                         sizeof(struct k_mem_block_id) + 1 + *size,
-                         timeout)) {
-        return NULL;
-    }
+static u8_t *mem_pool_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) {
+  struct net_buf_pool *buf_pool = net_buf_pool_get(buf->pool_id);
+  struct k_mem_pool   *pool     = buf_pool->alloc->alloc_data;
+  struct k_mem_block   block;
+  u8_t                *ref_count;
+
+  /* Reserve extra space for k_mem_block_id and ref-count (u8_t) */
+  if (k_mem_pool_alloc(pool, &block, sizeof(struct k_mem_block_id) + 1 + *size, timeout)) {
+    return NULL;
+  }
 
-    /* save the block descriptor info at the start of the actual block */
-    memcpy(block.data, &block.id, sizeof(block.id));
+  /* save the block descriptor info at the start of the actual block */
+  memcpy(block.data, &block.id, sizeof(block.id));
 
-    ref_count = (u8_t *)block.data + sizeof(block.id);
-    *ref_count = 1U;
+  ref_count  = (u8_t *)block.data + sizeof(block.id);
+  *ref_count = 1U;
 
-    /* Return pointer to the byte following the ref count */
-    return ref_count + 1;
+  /* Return pointer to the byte following the ref count */
+  return ref_count + 1;
 }
 
-static void mem_pool_data_unref(struct net_buf *buf, u8_t *data)
-{
-    struct k_mem_block_id id;
-    u8_t *ref_count;
+static void mem_pool_data_unref(struct net_buf *buf, u8_t *data) {
+  struct k_mem_block_id id;
+  u8_t                 *ref_count;
 
-    ref_count = data - 1;
-    if (--(*ref_count)) {
-        return;
-    }
+  ref_count = data - 1;
+  if (--(*ref_count)) {
+    return;
+  }
 
-    /* Need to copy to local variable due to alignment */
-    memcpy(&id, ref_count - sizeof(id), sizeof(id));
-    k_mem_pool_free_id(&id);
+  /* Need to copy to local variable due to alignment */
+  memcpy(&id, ref_count - sizeof(id), sizeof(id));
+  k_mem_pool_free_id(&id);
 }
 
 const struct net_buf_data_cb net_buf_var_cb = {
     .alloc = mem_pool_data_alloc,
-    .ref = generic_data_ref,
+    .ref   = generic_data_ref,
     .unref = mem_pool_data_unref,
 };
 #endif
 
-static u8_t *fixed_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
-    const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
+static u8_t *fixed_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) {
+  struct net_buf_pool             *pool  = net_buf_pool_get(buf->pool_id);
+  const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
 
-    *size = MIN(fixed->data_size, *size);
+  *size = MIN(fixed->data_size, *size);
 
-    return fixed->data_pool + fixed->data_size * net_buf_id(buf);
+  return fixed->data_pool + fixed->data_size * net_buf_id(buf);
 }
 
-static void fixed_data_unref(struct net_buf *buf, u8_t *data)
-{
-    /* Nothing needed for fixed-size data pools */
-}
+static void fixed_data_unref(struct net_buf *buf, u8_t *data) { /* Nothing needed for fixed-size data pools */ }
 
 const struct net_buf_data_cb net_buf_fixed_cb = {
     .alloc = fixed_data_alloc,
@@ -306,35 +352,33 @@ const struct net_buf_data_cb net_buf_fixed_cb = {
 
 #if defined(CONFIG_HEAP_MEM_POOL_SIZE) && (CONFIG_HEAP_MEM_POOL_SIZE > 0)
 
-static u8_t *heap_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout)
-{
-    u8_t *ref_count;
+static u8_t *heap_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) {
+  u8_t *ref_count;
 
-    ref_count = k_malloc(1 + *size);
-    if (!ref_count) {
-        return NULL;
-    }
+  ref_count = k_malloc(1 + *size);
+  if (!ref_count) {
+    return NULL;
+  }
 
-    *ref_count = 1U;
+  *ref_count = 1U;
 
-    return ref_count + 1;
+  return ref_count + 1;
 }
 
-static void heap_data_unref(struct net_buf *buf, u8_t *data)
-{
-    u8_t *ref_count;
+static void heap_data_unref(struct net_buf *buf, u8_t *data) {
+  u8_t *ref_count;
 
-    ref_count = data - 1;
-    if (--(*ref_count)) {
-        return;
-    }
+  ref_count = data - 1;
+  if (--(*ref_count)) {
+    return;
+  }
 
-    k_free(ref_count);
+  k_free(ref_count);
 }
 
 static const struct net_buf_data_cb net_buf_heap_cb = {
     .alloc = heap_data_alloc,
-    .ref = generic_data_ref,
+    .ref   = generic_data_ref,
     .unref = heap_data_unref,
 };
 
@@ -344,313 +388,288 @@ const struct net_buf_data_alloc net_buf_heap_alloc = {
 
 #endif /* CONFIG_HEAP_MEM_POOL_SIZE > 0 */
 
-static u8_t *data_alloc(struct net_buf *buf, size_t *size, s32_t timeout)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
+static u8_t *data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) {
+  struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
 
-    return pool->alloc->cb->alloc(buf, size, timeout);
+  return pool->alloc->cb->alloc(buf, size, timeout);
 }
 
-static u8_t *data_ref(struct net_buf *buf, u8_t *data)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
+static u8_t *data_ref(struct net_buf *buf, u8_t *data) {
+  struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
 
-    return pool->alloc->cb->ref(buf, data);
+  return pool->alloc->cb->ref(buf, data);
 }
 
-static void data_unref(struct net_buf *buf, u8_t *data)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
+static void data_unref(struct net_buf *buf, u8_t *data) {
+  struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
 
-    if (buf->flags & NET_BUF_EXTERNAL_DATA) {
-        return;
-    }
+  if (buf->flags & NET_BUF_EXTERNAL_DATA) {
+    return;
+  }
 
-    pool->alloc->cb->unref(buf, data);
+  pool->alloc->cb->unref(buf, data);
 }
 
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *net_buf_alloc_len_debug(struct net_buf_pool *pool, size_t size,
-                                        s32_t timeout, const char *func,
-                                        int line)
+struct net_buf *net_buf_alloc_len_debug(struct net_buf_pool *pool, size_t size, s32_t timeout, const char *func, int line)
 #else
-struct net_buf *net_buf_alloc_len(struct net_buf_pool *pool, size_t size,
-                                  s32_t timeout)
+struct net_buf *net_buf_alloc_len(struct net_buf_pool *pool, size_t size, s32_t timeout)
 #endif
 {
-    u32_t alloc_start = k_uptime_get_32();
-    struct net_buf *buf;
-    unsigned int key;
-
-    NET_BUF_ASSERT(pool);
-
-    NET_BUF_DBG("%s():%d: pool %p size %zu timeout %d", func, line, pool,
-                size, timeout);
-
-    /* We need to lock interrupts temporarily to prevent race conditions
-	 * when accessing pool->uninit_count.
-	 */
-    key = irq_lock();
-
-    /* If there are uninitialized buffers we're guaranteed to succeed
-	 * with the allocation one way or another.
-	 */
-    if (pool->uninit_count) {
-        u16_t uninit_count;
-
-        /* If this is not the first access to the pool, we can
-		 * be opportunistic and try to fetch a previously used
-		 * buffer from the LIFO with K_NO_WAIT.
-		 */
-        if (pool->uninit_count < pool->buf_count) {
-            buf = k_lifo_get(&pool->free, K_NO_WAIT);
-            if (buf) {
-                irq_unlock(key);
-                goto success;
-            }
-        }
-
-        uninit_count = pool->uninit_count--;
-        irq_unlock(key);
+  u32_t           alloc_start = k_uptime_get_32();
+  struct net_buf *buf;
+  unsigned int    key;
+
+  NET_BUF_ASSERT(pool);
+
+  NET_BUF_DBG("%s():%d: pool %p size %zu timeout %d", func, line, pool, size, timeout);
+
+#if (BFLB_BT_CO_THREAD)
+  extern struct k_thread co_thread_data;
+  if (k_is_current_thread(&co_thread_data))
+    timeout = K_NO_WAIT;
+#endif
 
-        buf = pool_get_uninit(pool, uninit_count);
+  /* We need to lock interrupts temporarily to prevent race conditions
+   * when accessing pool->uninit_count.
+   */
+  key = irq_lock();
+
+  /* If there are uninitialized buffers we're guaranteed to succeed
+   * with the allocation one way or another.
+   */
+  if (pool->uninit_count) {
+    u16_t uninit_count;
+
+    /* If this is not the first access to the pool, we can
+     * be opportunistic and try to fetch a previously used
+     * buffer from the LIFO with K_NO_WAIT.
+     */
+    if (pool->uninit_count < pool->buf_count) {
+      buf = k_lifo_get(&pool->free, K_NO_WAIT);
+      if (buf) {
+        irq_unlock(key);
         goto success;
+      }
     }
 
+    uninit_count = pool->uninit_count--;
     irq_unlock(key);
 
+    buf = pool_get_uninit(pool, uninit_count);
+    goto success;
+  }
+
+  irq_unlock(key);
+
 #if defined(CONFIG_NET_BUF_LOG) && (CONFIG_NET_BUF_LOG_LEVEL >= LOG_LEVEL_WRN)
-    if (timeout == K_FOREVER) {
-        u32_t ref = k_uptime_get_32();
-        buf = k_lifo_get(&pool->free, K_NO_WAIT);
-        while (!buf) {
+  if (timeout == K_FOREVER) {
+    u32_t ref = k_uptime_get_32();
+    buf       = k_lifo_get(&pool->free, K_NO_WAIT);
+    while (!buf) {
 #if defined(CONFIG_NET_BUF_POOL_USAGE)
-            NET_BUF_WARN("%s():%d: Pool %s low on buffers.",
-                         func, line, pool->name);
+      NET_BUF_WARN("%s():%d: Pool %s low on buffers.", func, line, pool->name);
 #else
-            NET_BUF_WARN("%s():%d: Pool %p low on buffers.",
-                         func, line, pool);
+      NET_BUF_WARN("%s():%d: Pool %p low on buffers.", func, line, pool);
 #endif
-            buf = k_lifo_get(&pool->free, WARN_ALLOC_INTERVAL);
+      buf = k_lifo_get(&pool->free, WARN_ALLOC_INTERVAL);
 #if defined(CONFIG_NET_BUF_POOL_USAGE)
-            NET_BUF_WARN("%s():%d: Pool %s blocked for %u secs",
-                         func, line, pool->name,
-                         (k_uptime_get_32() - ref) / MSEC_PER_SEC);
+      NET_BUF_WARN("%s():%d: Pool %s blocked for %u secs", func, line, pool->name, (k_uptime_get_32() - ref) / MSEC_PER_SEC);
 #else
-            NET_BUF_WARN("%s():%d: Pool %p blocked for %u secs",
-                         func, line, pool,
-                         (k_uptime_get_32() - ref) / MSEC_PER_SEC);
+      NET_BUF_WARN("%s():%d: Pool %p blocked for %u secs", func, line, pool, (k_uptime_get_32() - ref) / MSEC_PER_SEC);
 #endif
-        }
-    } else {
-        buf = k_lifo_get(&pool->free, timeout);
     }
-#else
+  } else {
     buf = k_lifo_get(&pool->free, timeout);
+  }
+#else
+  buf = k_lifo_get(&pool->free, timeout);
 #endif
-    if (!buf) {
-        NET_BUF_ERR("%s():%d: Failed to get free buffer", func, line);
-        return NULL;
-    }
+  if (!buf) {
+    NET_BUF_ERR("%s():%d: Failed to get free buffer", func, line);
+    return NULL;
+  }
 
 success:
-    NET_BUF_DBG("allocated buf %p", buf);
-
-    if (size) {
-        if (timeout != K_NO_WAIT && timeout != K_FOREVER) {
-            u32_t diff = k_uptime_get_32() - alloc_start;
-
-            timeout -= MIN(timeout, diff);
-        }
-
-        buf->__buf = data_alloc(buf, &size, timeout);
-        if (!buf->__buf) {
-            NET_BUF_ERR("%s():%d: Failed to allocate data",
-                        func, line);
-            net_buf_destroy(buf);
-            return NULL;
-        }
-    } else {
-        buf->__buf = NULL;
+  NET_BUF_DBG("allocated buf %p", buf);
+
+  if (size) {
+    if (timeout != K_NO_WAIT && timeout != K_FOREVER) {
+      u32_t diff = k_uptime_get_32() - alloc_start;
+
+      timeout -= MIN(timeout, diff);
     }
 
-    buf->ref = 1U;
-    buf->flags = 0U;
-    buf->frags = NULL;
-    buf->size = size;
-    net_buf_reset(buf);
+    buf->__buf = data_alloc(buf, &size, timeout);
+    if (!buf->__buf) {
+      NET_BUF_ERR("%s():%d: Failed to allocate data", func, line);
+      net_buf_destroy(buf);
+      return NULL;
+    }
+  } else {
+    buf->__buf = NULL;
+  }
+
+  buf->ref   = 1U;
+  buf->flags = 0U;
+  buf->frags = NULL;
+  buf->size  = size;
+  net_buf_reset(buf);
 
 #if defined(CONFIG_NET_BUF_POOL_USAGE)
-    pool->avail_count--;
-    NET_BUF_ASSERT(pool->avail_count >= 0);
+  pool->avail_count--;
+  NET_BUF_ASSERT(pool->avail_count >= 0);
 #endif
 
-    return buf;
+  return buf;
 }
 
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *net_buf_alloc_fixed_debug(struct net_buf_pool *pool,
-                                          s32_t timeout, const char *func,
-                                          int line)
-{
-    const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
+struct net_buf *net_buf_alloc_fixed_debug(struct net_buf_pool *pool, s32_t timeout, const char *func, int line) {
+  const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
 
-    return net_buf_alloc_len_debug(pool, fixed->data_size, timeout, func,
-                                   line);
+  return net_buf_alloc_len_debug(pool, fixed->data_size, timeout, func, line);
 }
 #else
-struct net_buf *net_buf_alloc_fixed(struct net_buf_pool *pool, s32_t timeout)
-{
-    const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
+struct net_buf *net_buf_alloc_fixed(struct net_buf_pool *pool, s32_t timeout) {
+  const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data;
 
-    return net_buf_alloc_len(pool, fixed->data_size, timeout);
+  return net_buf_alloc_len(pool, fixed->data_size, timeout);
 }
 #endif
 
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *net_buf_alloc_with_data_debug(struct net_buf_pool *pool,
-                                              void *data, size_t size,
-                                              s32_t timeout, const char *func,
-                                              int line)
+struct net_buf *net_buf_alloc_with_data_debug(struct net_buf_pool *pool, void *data, size_t size, s32_t timeout, const char *func, int line)
 #else
-struct net_buf *net_buf_alloc_with_data(struct net_buf_pool *pool,
-                                        void *data, size_t size,
-                                        s32_t timeout)
+struct net_buf *net_buf_alloc_with_data(struct net_buf_pool *pool, void *data, size_t size, s32_t timeout)
 #endif
 {
-    struct net_buf *buf;
+  struct net_buf *buf;
 
 #if defined(CONFIG_NET_BUF_LOG)
-    buf = net_buf_alloc_len_debug(pool, 0, timeout, func, line);
+  buf = net_buf_alloc_len_debug(pool, 0, timeout, func, line);
 #else
-    buf = net_buf_alloc_len(pool, 0, timeout);
+  buf = net_buf_alloc_len(pool, 0, timeout);
 #endif
-    if (!buf) {
-        return NULL;
-    }
+  if (!buf) {
+    return NULL;
+  }
 
-    buf->__buf = data;
-    buf->data = data;
-    buf->size = size;
-    buf->len = size;
-    buf->flags = NET_BUF_EXTERNAL_DATA;
+  buf->__buf = data;
+  buf->data  = data;
+  buf->size  = size;
+  buf->len   = size;
+  buf->flags = NET_BUF_EXTERNAL_DATA;
 
-    return buf;
+  return buf;
 }
 
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *net_buf_get_debug(struct k_fifo *fifo, s32_t timeout,
-                                  const char *func, int line)
+struct net_buf *net_buf_get_debug(struct k_fifo *fifo, s32_t timeout, const char *func, int line)
 #else
 struct net_buf *net_buf_get(struct k_fifo *fifo, s32_t timeout)
 #endif
 {
-    struct net_buf *buf, *frag;
+  struct net_buf *buf, *frag;
 
-    NET_BUF_DBG("%s():%d: fifo %p timeout %d", func, line, fifo, timeout);
+  NET_BUF_DBG("%s():%d: fifo %p timeout %d", func, line, fifo, timeout);
 
-    buf = k_fifo_get(fifo, timeout);
-    if (!buf) {
-        return NULL;
-    }
+  buf = k_fifo_get(fifo, timeout);
+  if (!buf) {
+    return NULL;
+  }
 
-    NET_BUF_DBG("%s():%d: buf %p fifo %p", func, line, buf, fifo);
+  NET_BUF_DBG("%s():%d: buf %p fifo %p", func, line, buf, fifo);
 
-    /* Get any fragments belonging to this buffer */
-    for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) {
-        frag->frags = k_fifo_get(fifo, K_NO_WAIT);
-        NET_BUF_ASSERT(frag->frags);
+  /* Get any fragments belonging to this buffer */
+  for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) {
+    frag->frags = k_fifo_get(fifo, K_NO_WAIT);
+    NET_BUF_ASSERT(frag->frags);
 
-        /* The fragments flag is only for FIFO-internal usage */
-        frag->flags &= ~NET_BUF_FRAGS;
-    }
+    /* The fragments flag is only for FIFO-internal usage */
+    frag->flags &= ~NET_BUF_FRAGS;
+  }
 
-    /* Mark the end of the fragment list */
-    frag->frags = NULL;
+  /* Mark the end of the fragment list */
+  frag->frags = NULL;
 
-    return buf;
+  return buf;
 }
 
-void net_buf_simple_init_with_data(struct net_buf_simple *buf,
-                                   void *data, size_t size)
-{
-    buf->__buf = data;
-    buf->data = data;
-    buf->size = size;
-    buf->len = size;
+void net_buf_simple_init_with_data(struct net_buf_simple *buf, void *data, size_t size) {
+  buf->__buf = data;
+  buf->data  = data;
+  buf->size  = size;
+  buf->len   = size;
 }
 
-void net_buf_simple_reserve(struct net_buf_simple *buf, size_t reserve)
-{
-    NET_BUF_ASSERT(buf);
-    NET_BUF_ASSERT(buf->len == 0U);
-    NET_BUF_DBG("buf %p reserve %zu", buf, reserve);
+void net_buf_simple_reserve(struct net_buf_simple *buf, size_t reserve) {
+  NET_BUF_ASSERT(buf);
+  NET_BUF_ASSERT(buf->len == 0U);
+  NET_BUF_DBG("buf %p reserve %zu", buf, reserve);
 
-    buf->data = buf->__buf + reserve;
+  buf->data = buf->__buf + reserve;
 }
 
-void net_buf_slist_put(sys_slist_t *list, struct net_buf *buf)
-{
-    struct net_buf *tail;
-    unsigned int key;
+void net_buf_slist_put(sys_slist_t *list, struct net_buf *buf) {
+  struct net_buf *tail;
+  unsigned int    key;
 
-    NET_BUF_ASSERT(list);
-    NET_BUF_ASSERT(buf);
+  NET_BUF_ASSERT(list);
+  NET_BUF_ASSERT(buf);
 
-    for (tail = buf; tail->frags; tail = tail->frags) {
-        tail->flags |= NET_BUF_FRAGS;
-    }
+  for (tail = buf; tail->frags; tail = tail->frags) {
+    tail->flags |= NET_BUF_FRAGS;
+  }
 
-    key = irq_lock();
-    sys_slist_append_list(list, &buf->node, &tail->node);
-    irq_unlock(key);
+  key = irq_lock();
+  sys_slist_append_list(list, &buf->node, &tail->node);
+  irq_unlock(key);
 }
 
-struct net_buf *net_buf_slist_get(sys_slist_t *list)
-{
-    struct net_buf *buf, *frag;
-    unsigned int key;
+struct net_buf *net_buf_slist_get(sys_slist_t *list) {
+  struct net_buf *buf, *frag;
+  unsigned int    key;
 
-    NET_BUF_ASSERT(list);
+  NET_BUF_ASSERT(list);
 
-    key = irq_lock();
-    buf = (void *)sys_slist_get(list);
-    irq_unlock(key);
+  key = irq_lock();
+  buf = (void *)sys_slist_get(list);
+  irq_unlock(key);
 
-    if (!buf) {
-        return NULL;
-    }
+  if (!buf) {
+    return NULL;
+  }
 
-    /* Get any fragments belonging to this buffer */
-    for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) {
-        key = irq_lock();
-        frag->frags = (void *)sys_slist_get(list);
-        irq_unlock(key);
+  /* Get any fragments belonging to this buffer */
+  for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) {
+    key         = irq_lock();
+    frag->frags = (void *)sys_slist_get(list);
+    irq_unlock(key);
 
-        NET_BUF_ASSERT(frag->frags);
+    NET_BUF_ASSERT(frag->frags);
 
-        /* The fragments flag is only for list-internal usage */
-        frag->flags &= ~NET_BUF_FRAGS;
-    }
+    /* The fragments flag is only for list-internal usage */
+    frag->flags &= ~NET_BUF_FRAGS;
+  }
 
-    /* Mark the end of the fragment list */
-    frag->frags = NULL;
+  /* Mark the end of the fragment list */
+  frag->frags = NULL;
 
-    return buf;
+  return buf;
 }
 
-void net_buf_put(struct k_fifo *fifo, struct net_buf *buf)
-{
-    struct net_buf *tail;
+void net_buf_put(struct k_fifo *fifo, struct net_buf *buf) {
+  struct net_buf *tail;
 
-    NET_BUF_ASSERT(fifo);
-    NET_BUF_ASSERT(buf);
+  NET_BUF_ASSERT(fifo);
+  NET_BUF_ASSERT(buf);
 
-    for (tail = buf; tail->frags; tail = tail->frags) {
-        tail->flags |= NET_BUF_FRAGS;
-    }
+  for (tail = buf; tail->frags; tail = tail->frags) {
+    tail->flags |= NET_BUF_FRAGS;
+  }
 
-    k_fifo_put_list(fifo, buf, tail);
+  k_fifo_put_list(fifo, buf, tail);
 }
 
 #if defined(CONFIG_NET_BUF_LOG)
@@ -659,257 +678,242 @@ void net_buf_unref_debug(struct net_buf *buf, const char *func, int line)
 void net_buf_unref(struct net_buf *buf)
 #endif
 {
-    NET_BUF_ASSERT(buf);
+  NET_BUF_ASSERT(buf);
 
-    while (buf) {
-        struct net_buf *frags = buf->frags;
-        struct net_buf_pool *pool;
+  while (buf) {
+    struct net_buf      *frags = buf->frags;
+    struct net_buf_pool *pool;
 
 #if defined(CONFIG_NET_BUF_LOG)
-        if (!buf->ref) {
-            NET_BUF_ERR("%s():%d: buf %p double free", func, line,
-                        buf);
-            return;
-        }
+    if (!buf->ref) {
+      NET_BUF_ERR("%s():%d: buf %p double free", func, line, buf);
+      return;
+    }
 #endif
-        NET_BUF_DBG("buf %p ref %u pool_id %u frags %p", buf, buf->ref,
-                    buf->pool_id, buf->frags);
+    NET_BUF_DBG("buf %p ref %u pool_id %u frags %p", buf, buf->ref, buf->pool_id, buf->frags);
 
-        unsigned int key = irq_lock(); /* Added by bouffalo lab, to protect ref decrease */
-        if (--buf->ref > 0) {
-            irq_unlock(key); /* Added by bouffalo lab */
-            return;
-        }
-        irq_unlock(key); /* Added by bouffalo lab */
+    unsigned int key = irq_lock(); /* Added by bouffalo lab, to protect ref decrease */
+    if (--buf->ref > 0) {
+      irq_unlock(key); /* Added by bouffalo lab */
+      return;
+    }
+    irq_unlock(key); /* Added by bouffalo lab */
 
-        if (buf->__buf) {
-            data_unref(buf, buf->__buf);
-            buf->__buf = NULL;
-        }
+    if (buf->__buf) {
+      data_unref(buf, buf->__buf);
+      buf->__buf = NULL;
+    }
 
-        buf->data = NULL;
-        buf->frags = NULL;
+    buf->data  = NULL;
+    buf->frags = NULL;
 
-        pool = net_buf_pool_get(buf->pool_id);
+    pool = net_buf_pool_get(buf->pool_id);
 
 #if defined(CONFIG_NET_BUF_POOL_USAGE)
-        pool->avail_count++;
-        NET_BUF_ASSERT(pool->avail_count <= pool->buf_count);
+    pool->avail_count++;
+    NET_BUF_ASSERT(pool->avail_count <= pool->buf_count);
 #endif
 
-        if (pool->destroy) {
-            pool->destroy(buf);
-        } else {
-            net_buf_destroy(buf);
-        }
+    if (pool->destroy) {
+      pool->destroy(buf);
+    } else {
+      net_buf_destroy(buf);
+    }
 
-        buf = frags;
+    buf = frags;
 
 #if defined(BFLB_BLE)
-        if (pool == &hci_rx_pool) {
-            bl_trigger_queued_msg();
-            return;
-        }
-#endif
+    if (pool == &hci_rx_pool) {
+      bl_trigger_queued_msg();
+      return;
     }
+#endif
+  }
 }
 
-struct net_buf *net_buf_ref(struct net_buf *buf)
-{
-    NET_BUF_ASSERT(buf);
+struct net_buf *net_buf_ref(struct net_buf *buf) {
+  NET_BUF_ASSERT(buf);
 
-    NET_BUF_DBG("buf %p (old) ref %u pool_id %u",
-                buf, buf->ref, buf->pool_id);
+  NET_BUF_DBG("buf %p (old) ref %u pool_id %u", buf, buf->ref, buf->pool_id);
 
-    unsigned int key = irq_lock(); /* Added by bouffalo lab,  to protect ref increase */
-    buf->ref++;
-    irq_unlock(key); /* Added by bouffalo lab */
-    return buf;
+  unsigned int key = irq_lock(); /* Added by bouffalo lab,  to protect ref increase */
+  buf->ref++;
+  irq_unlock(key); /* Added by bouffalo lab */
+  return buf;
 }
 
-struct net_buf *net_buf_clone(struct net_buf *buf, s32_t timeout)
-{
-    u32_t alloc_start = k_uptime_get_32();
-    struct net_buf_pool *pool;
-    struct net_buf *clone;
+struct net_buf *net_buf_clone(struct net_buf *buf, s32_t timeout) {
+  u32_t                alloc_start = k_uptime_get_32();
+  struct net_buf_pool *pool;
+  struct net_buf      *clone;
 
-    NET_BUF_ASSERT(buf);
+  NET_BUF_ASSERT(buf);
 
-    pool = net_buf_pool_get(buf->pool_id);
+  pool = net_buf_pool_get(buf->pool_id);
 
-    clone = net_buf_alloc_len(pool, 0, timeout);
-    if (!clone) {
-        return NULL;
-    }
-
-    /* If the pool supports data referencing use that. Otherwise
-	 * we need to allocate new data and make a copy.
-	 */
-    if (pool->alloc->cb->ref && !(buf->flags & NET_BUF_EXTERNAL_DATA)) {
-        clone->__buf = data_ref(buf, buf->__buf);
-        clone->data = buf->data;
-        clone->len = buf->len;
-        clone->size = buf->size;
-    } else {
-        size_t size = buf->size;
+  clone = net_buf_alloc_len(pool, 0, timeout);
+  if (!clone) {
+    return NULL;
+  }
 
-        if (timeout != K_NO_WAIT && timeout != K_FOREVER) {
-            u32_t diff = k_uptime_get_32() - alloc_start;
+  /* If the pool supports data referencing use that. Otherwise
+   * we need to allocate new data and make a copy.
+   */
+  if (pool->alloc->cb->ref && !(buf->flags & NET_BUF_EXTERNAL_DATA)) {
+    clone->__buf = data_ref(buf, buf->__buf);
+    clone->data  = buf->data;
+    clone->len   = buf->len;
+    clone->size  = buf->size;
+  } else {
+    size_t size = buf->size;
 
-            timeout -= MIN(timeout, diff);
-        }
+    if (timeout != K_NO_WAIT && timeout != K_FOREVER) {
+      u32_t diff = k_uptime_get_32() - alloc_start;
 
-        clone->__buf = data_alloc(clone, &size, timeout);
-        if (!clone->__buf || size < buf->size) {
-            net_buf_destroy(clone);
-            return NULL;
-        }
+      timeout -= MIN(timeout, diff);
+    }
 
-        clone->size = size;
-        clone->data = clone->__buf + net_buf_headroom(buf);
-        net_buf_add_mem(clone, buf->data, buf->len);
+    clone->__buf = data_alloc(clone, &size, timeout);
+    if (!clone->__buf || size < buf->size) {
+      net_buf_destroy(clone);
+      return NULL;
     }
 
-    return clone;
+    clone->size = size;
+    clone->data = clone->__buf + net_buf_headroom(buf);
+    net_buf_add_mem(clone, buf->data, buf->len);
+  }
+
+  return clone;
 }
 
-struct net_buf *net_buf_frag_last(struct net_buf *buf)
-{
-    NET_BUF_ASSERT(buf);
+struct net_buf *net_buf_frag_last(struct net_buf *buf) {
+  NET_BUF_ASSERT(buf);
 
-    while (buf->frags) {
-        buf = buf->frags;
-    }
+  while (buf->frags) {
+    buf = buf->frags;
+  }
 
-    return buf;
+  return buf;
 }
 
-void net_buf_frag_insert(struct net_buf *parent, struct net_buf *frag)
-{
-    NET_BUF_ASSERT(parent);
-    NET_BUF_ASSERT(frag);
+void net_buf_frag_insert(struct net_buf *parent, struct net_buf *frag) {
+  NET_BUF_ASSERT(parent);
+  NET_BUF_ASSERT(frag);
 
-    if (parent->frags) {
-        net_buf_frag_last(frag)->frags = parent->frags;
-    }
-    /* Take ownership of the fragment reference */
-    parent->frags = frag;
+  if (parent->frags) {
+    net_buf_frag_last(frag)->frags = parent->frags;
+  }
+  /* Take ownership of the fragment reference */
+  parent->frags = frag;
 }
 
-struct net_buf *net_buf_frag_add(struct net_buf *head, struct net_buf *frag)
-{
-    NET_BUF_ASSERT(frag);
+struct net_buf *net_buf_frag_add(struct net_buf *head, struct net_buf *frag) {
+  NET_BUF_ASSERT(frag);
 
-    if (!head) {
-        return net_buf_ref(frag);
-    }
+  if (!head) {
+    return net_buf_ref(frag);
+  }
 
-    net_buf_frag_insert(net_buf_frag_last(head), frag);
+  net_buf_frag_insert(net_buf_frag_last(head), frag);
 
-    return head;
+  return head;
 }
 
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *net_buf_frag_del_debug(struct net_buf *parent,
-                                       struct net_buf *frag,
-                                       const char *func, int line)
+struct net_buf *net_buf_frag_del_debug(struct net_buf *parent, struct net_buf *frag, const char *func, int line)
 #else
 struct net_buf *net_buf_frag_del(struct net_buf *parent, struct net_buf *frag)
 #endif
 {
-    struct net_buf *next_frag;
+  struct net_buf *next_frag;
 
-    NET_BUF_ASSERT(frag);
+  NET_BUF_ASSERT(frag);
 
-    if (parent) {
-        NET_BUF_ASSERT(parent->frags);
-        NET_BUF_ASSERT(parent->frags == frag);
-        parent->frags = frag->frags;
-    }
+  if (parent) {
+    NET_BUF_ASSERT(parent->frags);
+    NET_BUF_ASSERT(parent->frags == frag);
+    parent->frags = frag->frags;
+  }
 
-    next_frag = frag->frags;
+  next_frag = frag->frags;
 
-    frag->frags = NULL;
+  frag->frags = NULL;
 
 #if defined(CONFIG_NET_BUF_LOG)
-    net_buf_unref_debug(frag, func, line);
+  net_buf_unref_debug(frag, func, line);
 #else
-    net_buf_unref(frag);
+  net_buf_unref(frag);
 #endif
 
-    return next_frag;
+  return next_frag;
 }
 
-size_t net_buf_linearize(void *dst, size_t dst_len, struct net_buf *src,
-                         size_t offset, size_t len)
-{
-    struct net_buf *frag;
-    size_t to_copy;
-    size_t copied;
+size_t net_buf_linearize(void *dst, size_t dst_len, struct net_buf *src, size_t offset, size_t len) {
+  struct net_buf *frag;
+  size_t          to_copy;
+  size_t          copied;
 
-    len = MIN(len, dst_len);
+  len = MIN(len, dst_len);
 
-    frag = src;
+  frag = src;
 
-    /* find the right fragment to start copying from */
-    while (frag && offset >= frag->len) {
-        offset -= frag->len;
-        frag = frag->frags;
-    }
+  /* find the right fragment to start copying from */
+  while (frag && offset >= frag->len) {
+    offset -= frag->len;
+    frag = frag->frags;
+  }
 
-    /* traverse the fragment chain until len bytes are copied */
-    copied = 0;
-    while (frag && len > 0) {
-        to_copy = MIN(len, frag->len - offset);
-        memcpy((u8_t *)dst + copied, frag->data + offset, to_copy);
+  /* traverse the fragment chain until len bytes are copied */
+  copied = 0;
+  while (frag && len > 0) {
+    to_copy = MIN(len, frag->len - offset);
+    memcpy((u8_t *)dst + copied, frag->data + offset, to_copy);
 
-        copied += to_copy;
+    copied += to_copy;
 
-        /* to_copy is always <= len */
-        len -= to_copy;
-        frag = frag->frags;
+    /* to_copy is always <= len */
+    len -= to_copy;
+    frag = frag->frags;
 
-        /* after the first iteration, this value will be 0 */
-        offset = 0;
-    }
+    /* after the first iteration, this value will be 0 */
+    offset = 0;
+  }
 
-    return copied;
+  return copied;
 }
 
 /* This helper routine will append multiple bytes, if there is no place for
  * the data in current fragment then create new fragment and add it to
  * the buffer. It assumes that the buffer has at least one fragment.
  */
-size_t net_buf_append_bytes(struct net_buf *buf, size_t len,
-                            const void *value, s32_t timeout,
-                            net_buf_allocator_cb allocate_cb, void *user_data)
-{
-    struct net_buf *frag = net_buf_frag_last(buf);
-    size_t added_len = 0;
-    const u8_t *value8 = value;
+size_t net_buf_append_bytes(struct net_buf *buf, size_t len, const void *value, s32_t timeout, net_buf_allocator_cb allocate_cb, void *user_data) {
+  struct net_buf *frag      = net_buf_frag_last(buf);
+  size_t          added_len = 0;
+  const u8_t     *value8    = value;
 
-    do {
-        u16_t count = MIN(len, net_buf_tailroom(frag));
+  do {
+    u16_t count = MIN(len, net_buf_tailroom(frag));
 
-        net_buf_add_mem(frag, value8, count);
-        len -= count;
-        added_len += count;
-        value8 += count;
+    net_buf_add_mem(frag, value8, count);
+    len -= count;
+    added_len += count;
+    value8 += count;
 
-        if (len == 0) {
-            return added_len;
-        }
+    if (len == 0) {
+      return added_len;
+    }
 
-        frag = allocate_cb(timeout, user_data);
-        if (!frag) {
-            return added_len;
-        }
+    frag = allocate_cb(timeout, user_data);
+    if (!frag) {
+      return added_len;
+    }
 
-        net_buf_frag_add(buf, frag);
-    } while (1);
+    net_buf_frag_add(buf, frag);
+  } while (1);
 
-    /* Unreachable */
-    return 0;
+  /* Unreachable */
+  return 0;
 }
 
 #if defined(CONFIG_NET_BUF_SIMPLE_LOG)
@@ -926,212 +930,179 @@ size_t net_buf_append_bytes(struct net_buf *buf, size_t len,
 #define NET_BUF_SIMPLE_ASSERT(cond)
 #endif /* CONFIG_NET_BUF_SIMPLE_LOG */
 
-void net_buf_simple_clone(const struct net_buf_simple *original,
-                          struct net_buf_simple *clone)
-{
-    memcpy(clone, original, sizeof(struct net_buf_simple));
-}
+void net_buf_simple_clone(const struct net_buf_simple *original, struct net_buf_simple *clone) { memcpy(clone, original, sizeof(struct net_buf_simple)); }
 
-void *net_buf_simple_add(struct net_buf_simple *buf, size_t len)
-{
-    u8_t *tail = net_buf_simple_tail(buf);
+void *net_buf_simple_add(struct net_buf_simple *buf, size_t len) {
+  u8_t *tail = net_buf_simple_tail(buf);
 
-    NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+  NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
 
-    NET_BUF_SIMPLE_ASSERT(net_buf_simple_tailroom(buf) >= len);
+  NET_BUF_SIMPLE_ASSERT(net_buf_simple_tailroom(buf) >= len);
 
-    buf->len += len;
-    return tail;
+  buf->len += len;
+  return tail;
 }
 
-void *net_buf_simple_add_mem(struct net_buf_simple *buf, const void *mem,
-                             size_t len)
-{
-    NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+void *net_buf_simple_add_mem(struct net_buf_simple *buf, const void *mem, size_t len) {
+  NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
 
-    return memcpy(net_buf_simple_add(buf, len), mem, len);
+  return memcpy(net_buf_simple_add(buf, len), mem, len);
 }
 
-u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val)
-{
-    u8_t *u8;
+u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val) {
+  u8_t *u8;
 
-    NET_BUF_SIMPLE_DBG("buf %p val 0x%02x", buf, val);
+  NET_BUF_SIMPLE_DBG("buf %p val 0x%02x", buf, val);
 
-    u8 = net_buf_simple_add(buf, 1);
-    *u8 = val;
+  u8  = net_buf_simple_add(buf, 1);
+  *u8 = val;
 
-    return u8;
+  return u8;
 }
 
-void net_buf_simple_add_le16(struct net_buf_simple *buf, u16_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_le16(struct net_buf_simple *buf, u16_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_le16(val, net_buf_simple_add(buf, sizeof(val)));
+  sys_put_le16(val, net_buf_simple_add(buf, sizeof(val)));
 }
 
-void net_buf_simple_add_be16(struct net_buf_simple *buf, u16_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_be16(struct net_buf_simple *buf, u16_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_be16(val, net_buf_simple_add(buf, sizeof(val)));
+  sys_put_be16(val, net_buf_simple_add(buf, sizeof(val)));
 }
 
-void net_buf_simple_add_le24(struct net_buf_simple *buf, uint32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_le24(struct net_buf_simple *buf, uint32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_le24(val, net_buf_simple_add(buf, 3));
+  sys_put_le24(val, net_buf_simple_add(buf, 3));
 }
 
-void net_buf_simple_add_be24(struct net_buf_simple *buf, uint32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_be24(struct net_buf_simple *buf, uint32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_be24(val, net_buf_simple_add(buf, 3));
+  sys_put_be24(val, net_buf_simple_add(buf, 3));
 }
 
-void net_buf_simple_add_le32(struct net_buf_simple *buf, u32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_le32(struct net_buf_simple *buf, u32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_le32(val, net_buf_simple_add(buf, sizeof(val)));
+  sys_put_le32(val, net_buf_simple_add(buf, sizeof(val)));
 }
 
-void net_buf_simple_add_be32(struct net_buf_simple *buf, u32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_add_be32(struct net_buf_simple *buf, u32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_be32(val, net_buf_simple_add(buf, sizeof(val)));
+  sys_put_be32(val, net_buf_simple_add(buf, sizeof(val)));
 }
 
-void *net_buf_simple_push(struct net_buf_simple *buf, size_t len)
-{
-    NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+void *net_buf_simple_push(struct net_buf_simple *buf, size_t len) {
+  NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
 
-    NET_BUF_SIMPLE_ASSERT(net_buf_simple_headroom(buf) >= len);
+  NET_BUF_SIMPLE_ASSERT(net_buf_simple_headroom(buf) >= len);
 
-    buf->data -= len;
-    buf->len += len;
-    return buf->data;
+  buf->data -= len;
+  buf->len += len;
+  return buf->data;
 }
 
-void net_buf_simple_push_le16(struct net_buf_simple *buf, u16_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_push_le16(struct net_buf_simple *buf, u16_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_le16(val, net_buf_simple_push(buf, sizeof(val)));
+  sys_put_le16(val, net_buf_simple_push(buf, sizeof(val)));
 }
 
-void net_buf_simple_push_be16(struct net_buf_simple *buf, u16_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_push_be16(struct net_buf_simple *buf, u16_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_be16(val, net_buf_simple_push(buf, sizeof(val)));
+  sys_put_be16(val, net_buf_simple_push(buf, sizeof(val)));
 }
 
-void net_buf_simple_push_u8(struct net_buf_simple *buf, u8_t val)
-{
-    u8_t *data = net_buf_simple_push(buf, 1);
+void net_buf_simple_push_u8(struct net_buf_simple *buf, u8_t val) {
+  u8_t *data = net_buf_simple_push(buf, 1);
 
-    *data = val;
+  *data = val;
 }
 
-void net_buf_simple_push_le24(struct net_buf_simple *buf, uint32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_push_le24(struct net_buf_simple *buf, uint32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_le24(val, net_buf_simple_push(buf, 3));
+  sys_put_le24(val, net_buf_simple_push(buf, 3));
 }
 
-void net_buf_simple_push_be24(struct net_buf_simple *buf, uint32_t val)
-{
-    NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
+void net_buf_simple_push_be24(struct net_buf_simple *buf, uint32_t val) {
+  NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
 
-    sys_put_be24(val, net_buf_simple_push(buf, 3));
+  sys_put_be24(val, net_buf_simple_push(buf, 3));
 }
 
-void *net_buf_simple_pull(struct net_buf_simple *buf, size_t len)
-{
-    NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+void *net_buf_simple_pull(struct net_buf_simple *buf, size_t len) {
+  NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
 
-    NET_BUF_SIMPLE_ASSERT(buf->len >= len);
+  NET_BUF_SIMPLE_ASSERT(buf->len >= len);
 
-    buf->len -= len;
-    return buf->data += len;
+  buf->len -= len;
+  return buf->data += len;
 }
 
-void *net_buf_simple_pull_mem(struct net_buf_simple *buf, size_t len)
-{
-    void *data = buf->data;
+void *net_buf_simple_pull_mem(struct net_buf_simple *buf, size_t len) {
+  void *data = buf->data;
 
-    NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+  NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
 
-    NET_BUF_SIMPLE_ASSERT(buf->len >= len);
+  NET_BUF_SIMPLE_ASSERT(buf->len >= len);
 
-    buf->len -= len;
-    buf->data += len;
+  buf->len -= len;
+  buf->data += len;
 
-    return data;
+  return data;
 }
 
-u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf)
-{
-    u8_t val;
+u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf) {
+  u8_t val;
 
-    val = buf->data[0];
-    net_buf_simple_pull(buf, 1);
+  val = buf->data[0];
+  net_buf_simple_pull(buf, 1);
 
-    return val;
+  return val;
 }
 
-u16_t net_buf_simple_pull_le16(struct net_buf_simple *buf)
-{
-    u16_t val;
+u16_t net_buf_simple_pull_le16(struct net_buf_simple *buf) {
+  u16_t val;
 
-    val = UNALIGNED_GET((u16_t *)buf->data);
-    net_buf_simple_pull(buf, sizeof(val));
+  val = UNALIGNED_GET((u16_t *)buf->data);
+  net_buf_simple_pull(buf, sizeof(val));
 
-    return sys_le16_to_cpu(val);
+  return sys_le16_to_cpu(val);
 }
 
-u16_t net_buf_simple_pull_be16(struct net_buf_simple *buf)
-{
-    u16_t val;
+u16_t net_buf_simple_pull_be16(struct net_buf_simple *buf) {
+  u16_t val;
 
-    val = UNALIGNED_GET((u16_t *)buf->data);
-    net_buf_simple_pull(buf, sizeof(val));
+  val = UNALIGNED_GET((u16_t *)buf->data);
+  net_buf_simple_pull(buf, sizeof(val));
 
-    return sys_be16_to_cpu(val);
+  return sys_be16_to_cpu(val);
 }
 
-u32_t net_buf_simple_pull_le32(struct net_buf_simple *buf)
-{
-    u32_t val;
+u32_t net_buf_simple_pull_le32(struct net_buf_simple *buf) {
+  u32_t val;
 
-    val = UNALIGNED_GET((u32_t *)buf->data);
-    net_buf_simple_pull(buf, sizeof(val));
+  val = UNALIGNED_GET((u32_t *)buf->data);
+  net_buf_simple_pull(buf, sizeof(val));
 
-    return sys_le32_to_cpu(val);
+  return sys_le32_to_cpu(val);
 }
 
-u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf)
-{
-    u32_t val;
+u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf) {
+  u32_t val;
 
-    val = UNALIGNED_GET((u32_t *)buf->data);
-    net_buf_simple_pull(buf, sizeof(val));
+  val = UNALIGNED_GET((u32_t *)buf->data);
+  net_buf_simple_pull(buf, sizeof(val));
 
-    return sys_be32_to_cpu(val);
+  return sys_be32_to_cpu(val);
 }
 
-size_t net_buf_simple_headroom(struct net_buf_simple *buf)
-{
-    return buf->data - buf->__buf;
-}
+size_t net_buf_simple_headroom(struct net_buf_simple *buf) { return buf->data - buf->__buf; }
 
-size_t net_buf_simple_tailroom(struct net_buf_simple *buf)
-{
-    return buf->size - net_buf_simple_headroom(buf) - buf->len;
-}
+size_t net_buf_simple_tailroom(struct net_buf_simple *buf) { return buf->size - net_buf_simple_headroom(buf) - buf->len; }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dec.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dec.c
index 7c7f30c0a..e0fd7b794 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dec.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dec.c
@@ -6,28 +6,27 @@
 
 #include 
 
-u8_t u8_to_dec(char *buf, u8_t buflen, u8_t value)
-{
-    u8_t divisor = 100;
-    u8_t num_digits = 0;
-    u8_t digit;
+u8_t u8_to_dec(char *buf, u8_t buflen, u8_t value) {
+  u8_t divisor    = 100;
+  u8_t num_digits = 0;
+  u8_t digit;
 
-    while (buflen > 0 && divisor > 0) {
-        digit = value / divisor;
-        if (digit != 0 || divisor == 1 || num_digits != 0) {
-            *buf = (char)digit + '0';
-            buf++;
-            buflen--;
-            num_digits++;
-        }
-
-        value -= digit * divisor;
-        divisor /= 10;
+  while (buflen > 0 && divisor > 0) {
+    digit = value / divisor;
+    if (digit != 0 || divisor == 1 || num_digits != 0) {
+      *buf = (char)digit + '0';
+      buf++;
+      buflen--;
+      num_digits++;
     }
 
-    if (buflen) {
-        *buf = '\0';
-    }
+    value -= digit * divisor;
+    divisor /= 10;
+  }
+
+  if (buflen) {
+    *buf = '\0';
+  }
 
-    return num_digits;
+  return num_digits;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dummy.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dummy.c
index db90bb43c..30184dcba 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dummy.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/dummy.c
@@ -33,8 +33,7 @@ BUILD_ASSERT(CONFIG_BT_CTLR_RX_PRIO < CONFIG_BT_HCI_TX_PRIO);
  * since it introduces ISR latency due to outputting log messages with
  * interrupts disabled.
  */
-#if !defined(CONFIG_TEST) && !defined(CONFIG_ARCH_POSIX) && \
-    (defined(CONFIG_BT_LL_SW_SPLIT) || defined(CONFIG_BT_LL_SW_LEGACY))
+#if !defined(CONFIG_TEST) && !defined(CONFIG_ARCH_POSIX) && (defined(CONFIG_BT_LL_SW_SPLIT) || defined(CONFIG_BT_LL_SW_LEGACY))
 BUILD_ASSERT_MSG(!IS_ENABLED(CONFIG_LOG_IMMEDIATE), "Immediate logging not "
                                                     "supported with the software Link Layer");
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/hex.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/hex.c
index 2d2425c06..316170205 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/hex.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/hex.c
@@ -4,8 +4,7 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
+#include 
 #include 
 #include 
-#include 
 // #include 
-
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/include/net/buf.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/include/net/buf.h
index b1b58fba7..b6e4f774c 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/include/net/buf.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/include/net/buf.h
@@ -14,7 +14,7 @@
 #include 
 #include 
 #include 
-#include "ble_config.h"
+#include "../../port/include/ble_config.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -66,6 +66,19 @@ extern "C" {
         .__buf = net_buf_data_##_name,                    \
     }
 
+#if (BFLB_STATIC_ALLOC_MEM)
+enum {
+    HCI_CMD = 0,
+    HCI_RX,
+    NUM_COMPLETE,
+    ACL_IN,
+    DISCARDABLE,
+    ACL_TX,
+    FRAG,
+    PREP,
+
+};
+#endif
 /** @brief Simple network buffer representation.
  *
  *  This is a simpler variant of the net_buf object (in fact net_buf uses
@@ -827,7 +840,11 @@ extern const struct net_buf_data_cb net_buf_var_cb;
 #endif
 
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
+#if (BFLB_STATIC_ALLOC_MEM)
+void net_buf_init(u8_t buf_type, struct net_buf_pool *buf_pool, u16_t buf_count, size_t data_size, destroy_cb_t destroy);
+#else
 void net_buf_init(struct net_buf_pool *buf_pool, u16_t buf_count, size_t data_size, destroy_cb_t destroy);
+#endif
 void net_buf_deinit(struct net_buf_pool *buf_pool);
 #endif
 /**
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/include/zephyr/types.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/include/zephyr/types.h
index 3b07e3b1c..ac12b55ba 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/include/zephyr/types.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/include/zephyr/types.h
@@ -15,12 +15,12 @@ extern "C" {
 
 typedef signed char s8_t;
 typedef signed short s16_t;
-typedef signed int s32_t;
+typedef int32_t s32_t;
 typedef signed long long s64_t;
 
 typedef unsigned char u8_t;
 typedef unsigned short u16_t;
-typedef unsigned int u32_t;
+typedef uint32_t u32_t;
 typedef unsigned long long u64_t;
 
 #ifdef __cplusplus
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.c
index 3a5790792..d81239ea0 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.c
@@ -12,50 +12,47 @@
  * in a single printk call.
  */
 
-#include 
-#include 
-#include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
 
-const char *bt_hex_real(const void *buf, size_t len)
-{
-    static const char hex[] = "0123456789abcdef";
+const char *bt_hex_real(const void *buf, size_t len) {
+  static const char hex[] = "0123456789abcdef";
 #if defined(CONFIG_BT_DEBUG_MONITOR)
-    static char str[255];
+  static char str[512];
 #else
-    static char str[128];
+  static char str[128];
 #endif
-    const u8_t *b = buf;
-    int i;
+  const u8_t *b = buf;
+  int         i;
 
-    len = MIN(len, (sizeof(str) - 1) / 2);
+  len = MIN(len, (sizeof(str) - 1) / 2);
 
-    for (i = 0; i < len; i++) {
-        str[i * 2] = hex[b[i] >> 4];
-        str[i * 2 + 1] = hex[b[i] & 0xf];
-    }
+  for (i = 0; i < len; i++) {
+    str[i * 2]     = hex[b[i] >> 4];
+    str[i * 2 + 1] = hex[b[i] & 0xf];
+  }
 
-    str[i * 2] = '\0';
+  str[i * 2] = '\0';
 
-    return str;
+  return str;
 }
 
-const char *bt_addr_str_real(const bt_addr_t *addr)
-{
-    static char str[BT_ADDR_STR_LEN];
+const char *bt_addr_str_real(const bt_addr_t *addr) {
+  static char str[BT_ADDR_STR_LEN];
 
-    bt_addr_to_str(addr, str, sizeof(str));
+  bt_addr_to_str(addr, str, sizeof(str));
 
-    return str;
+  return str;
 }
 
-const char *bt_addr_le_str_real(const bt_addr_le_t *addr)
-{
-    static char str[BT_ADDR_LE_STR_LEN];
+const char *bt_addr_le_str_real(const bt_addr_le_t *addr) {
+  static char str[BT_ADDR_LE_STR_LEN];
 
-    bt_addr_le_to_str(addr, str, sizeof(str));
+  bt_addr_le_to_str(addr, str, sizeof(str));
 
-    return str;
+  return str;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.h
index 74f9ec723..0ff18b6a6 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.h
@@ -21,8 +21,8 @@
 #include 
 
 #include "FreeRTOS.h"
-#include "task.h"
 #include "FreeRTOSConfig.h"
+#include "task.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -38,16 +38,20 @@ extern "C" {
 #define LOG_LEVEL CONFIG_BT_LOG_LEVEL
 #endif
 
-//LOG_MODULE_REGISTER(LOG_MODULE_NAME, LOG_LEVEL);
+// LOG_MODULE_REGISTER(LOG_MODULE_NAME, LOG_LEVEL);
 
 #if defined(BFLB_BLE)
 
 #if defined(BL_MCU_SDK)
-#define BT_DBG(fmt, ...) //bflb_platform_printf(fmt", %s\r\n", ##__VA_ARGS__, __func__)
-#define BT_ERR(fmt, ...) bflb_platform_printf(fmt ", %s\r\n", ##__VA_ARGS__, __func__)
+#define BT_DBG(fmt, ...)  // bflb_platform_printf(fmt", %s\r\n", ##__VA_ARGS__, __func__)
+#define BT_ERR(fmt, ...)  bflb_platform_printf(fmt ", %s\r\n", ##__VA_ARGS__, __func__)
+#define BT_WARN(fmt, ...) bflb_platform_printf(fmt ", %s\r\n", ##__VA_ARGS__, __func__)
+#define BT_INFO(fmt, ...) // bflb_platform_printf(fmt", %s\r\n", ##__VA_ARGS__, __func__)
 #else
-#define BT_DBG(fmt, ...) //printf(fmt", %s\r\n", ##__VA_ARGS__, __func__)
-#define BT_ERR(fmt, ...) printf(fmt ", %s\r\n", ##__VA_ARGS__, __func__)
+#define BT_DBG(fmt, ...)  // printf(fmt", %s\r\n", ##__VA_ARGS__, __func__)
+#define BT_ERR(fmt, ...)  printf(fmt ", %s\r\n", ##__VA_ARGS__, __func__)
+#define BT_WARN(fmt, ...) printf(fmt ", %s\r\n", ##__VA_ARGS__, __func__)
+#define BT_INFO(fmt, ...) // printf(fmt", %s\r\n", ##__VA_ARGS__, __func__)
 #endif
 
 #if defined(CONFIG_BT_STACK_PTS) || defined(CONFIG_BT_MESH_PTS)
@@ -56,14 +60,6 @@ extern "C" {
 #else
 #define BT_PTS(fmt, ...) printf(fmt "\r\n", ##__VA_ARGS__)
 #endif
-
-#endif
-#if defined(BL_MCU_SDK)
-#define BT_WARN(fmt, ...) bflb_platform_printf(fmt ", %s\r\n", ##__VA_ARGS__, __func__)
-#define BT_INFO(fmt, ...) //bflb_platform_printf(fmt", %s\r\n", ##__VA_ARGS__, __func__)
-#else
-#define BT_WARN(fmt, ...) printf(fmt ", %s\r\n", ##__VA_ARGS__, __func__)
-#define BT_INFO(fmt, ...) //printf(fmt", %s\r\n", ##__VA_ARGS__, __func__)
 #endif
 
 #else /*BFLB_BLE*/
@@ -89,17 +85,16 @@ extern "C" {
 
 #if defined(CONFIG_BT_ASSERT)
 #if defined(BFLB_BLE)
-extern void vAssertCalled(void);
-#define BT_ASSERT(cond) \
-    if ((cond) == 0)    \
-    vAssertCalled()
+extern void user_vAssertCalled(void);
+#define BT_ASSERT(cond)                                                                                                                                                                                \
+  if ((cond) == 0)                                                                                                                                                                                     \
+  user_vAssertCalled()
 #else
-#define BT_ASSERT(cond)                   \
-    if (!(cond)) {                        \
-        BT_ASSERT_PRINT("assert: '" #cond \
-                        "' failed\n");    \
-        BT_ASSERT_DIE();                  \
-    }
+#define BT_ASSERT(cond)                                                                                                                                                                                \
+  if (!(cond)) {                                                                                                                                                                                       \
+    BT_ASSERT_PRINT("assert: '" #cond "' failed\n");                                                                                                                                                   \
+    BT_ASSERT_DIE();                                                                                                                                                                                   \
+  }
 #endif /*BFLB_BLE*/
 #else
 #if defined(BFLB_BLE)
@@ -109,14 +104,10 @@ extern void vAssertCalled(void);
 #endif /*BFLB_BLE*/
 #endif /* CONFIG_BT_ASSERT*/
 
-#define BT_HEXDUMP_DBG(_data, _length, _str) \
-    LOG_HEXDUMP_DBG((const u8_t *)_data, _length, _str)
+#define BT_HEXDUMP_DBG(_data, _length, _str) LOG_HEXDUMP_DBG((const u8_t *)_data, _length, _str)
 
 #if defined(BFLB_BLE)
-static inline char *log_strdup(const char *str)
-{
-    return (char *)str;
-}
+static inline char *log_strdup(const char *str) { return (char *)str; }
 #endif
 
 /* NOTE: These helper functions always encodes into the same buffer storage.
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/poll.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/poll.c
index b97a4f798..40fe5dd9d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/poll.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/poll.c
@@ -16,225 +16,235 @@
 
 #include 
 
+#include 
+#include 
+#include 
 #include 
 #include 
-#include 
-#include 
-#include 
 
 struct k_sem g_poll_sem;
 
-void k_poll_event_init(struct k_poll_event *event, u32_t type,
-                       int mode, void *obj)
-{
-    __ASSERT(mode == K_POLL_MODE_NOTIFY_ONLY,
-             "only NOTIFY_ONLY mode is supported\n");
-    __ASSERT(type < (1 << _POLL_NUM_TYPES), "invalid type\n");
-    __ASSERT(obj, "must provide an object\n");
-
-    event->poller = NULL;
-    /* event->tag is left uninitialized: the user will set it if needed */
-    event->type = type;
-    event->state = K_POLL_STATE_NOT_READY;
-    event->mode = mode;
-    event->unused = 0;
-    event->obj = obj;
+void k_poll_event_init(struct k_poll_event *event, u32_t type, int mode, void *obj) {
+  __ASSERT(mode == K_POLL_MODE_NOTIFY_ONLY, "only NOTIFY_ONLY mode is supported\n");
+  __ASSERT(type < (1 << _POLL_NUM_TYPES), "invalid type\n");
+  __ASSERT(obj, "must provide an object\n");
+
+  event->poller = NULL;
+  /* event->tag is left uninitialized: the user will set it if needed */
+  event->type   = type;
+  event->state  = K_POLL_STATE_NOT_READY;
+  event->mode   = mode;
+  event->unused = 0;
+  event->obj    = obj;
 }
 
 /* must be called with interrupts locked */
-static inline int is_condition_met(struct k_poll_event *event, u32_t *state)
-{
-    switch (event->type) {
-        case K_POLL_TYPE_SEM_AVAILABLE:
-            if (k_sem_count_get(event->sem) > 0) {
-                *state = K_POLL_STATE_SEM_AVAILABLE;
-                return 1;
-            }
-            break;
-        case K_POLL_TYPE_DATA_AVAILABLE:
-            if (!k_queue_is_empty(event->queue)) {
-                *state = K_POLL_STATE_FIFO_DATA_AVAILABLE;
-                return 1;
-            }
-            break;
-        case K_POLL_TYPE_SIGNAL:
-            if (event->signal->signaled) {
-                *state = K_POLL_STATE_SIGNALED;
-                return 1;
-            }
-            break;
-        case K_POLL_TYPE_IGNORE:
-            return 0;
-        default:
-            __ASSERT(0, "invalid event type (0x%x)\n", event->type);
-            break;
+static inline int is_condition_met(struct k_poll_event *event, u32_t *state) {
+  switch (event->type) {
+  case K_POLL_TYPE_SEM_AVAILABLE:
+    if (k_sem_count_get(event->sem) > 0) {
+      *state = K_POLL_STATE_SEM_AVAILABLE;
+      return 1;
     }
-
+    break;
+  case K_POLL_TYPE_DATA_AVAILABLE:
+    if (!k_queue_is_empty(event->queue)) {
+      *state = K_POLL_STATE_FIFO_DATA_AVAILABLE;
+      return 1;
+    }
+    break;
+  case K_POLL_TYPE_SIGNAL:
+    if (event->signal->signaled) {
+      *state = K_POLL_STATE_SIGNALED;
+      return 1;
+    }
+    break;
+  case K_POLL_TYPE_IGNORE:
     return 0;
-}
+  default:
+    __ASSERT(0, "invalid event type (0x%x)\n", event->type);
+    break;
+  }
 
-static inline void add_event(sys_dlist_t *events, struct k_poll_event *event,
-                             struct _poller *poller)
-{
-    sys_dlist_append(events, &event->_node);
+  return 0;
 }
 
-/* must be called with interrupts locked */
-static inline int register_event(struct k_poll_event *event,
-                                 struct _poller *poller)
-{
-    switch (event->type) {
-        case K_POLL_TYPE_SEM_AVAILABLE:
-            __ASSERT(event->sem, "invalid semaphore\n");
-            add_event(&event->sem->poll_events, event, poller);
-            break;
-        case K_POLL_TYPE_DATA_AVAILABLE:
-            __ASSERT(event->queue, "invalid queue\n");
-            add_event(&event->queue->poll_events, event, poller);
-            break;
-        case K_POLL_TYPE_SIGNAL:
-            __ASSERT(event->signal, "invalid poll signal\n");
-            add_event(&event->signal->poll_events, event, poller);
-            break;
-        case K_POLL_TYPE_IGNORE:
-            /* nothing to do */
-            break;
-        default:
-            __ASSERT(0, "invalid event type\n");
-            break;
-    }
-
-    event->poller = poller;
+static inline void add_event(sys_dlist_t *events, struct k_poll_event *event, struct _poller *poller) { sys_dlist_append(events, &event->_node); }
 
-    return 0;
+/* must be called with interrupts locked */
+static inline int register_event(struct k_poll_event *event, struct _poller *poller) {
+  switch (event->type) {
+  case K_POLL_TYPE_SEM_AVAILABLE:
+    __ASSERT(event->sem, "invalid semaphore\n");
+    add_event(&event->sem->poll_events, event, poller);
+    break;
+  case K_POLL_TYPE_DATA_AVAILABLE:
+    __ASSERT(event->queue, "invalid queue\n");
+    add_event(&event->queue->poll_events, event, poller);
+    break;
+  case K_POLL_TYPE_SIGNAL:
+    __ASSERT(event->signal, "invalid poll signal\n");
+    add_event(&event->signal->poll_events, event, poller);
+    break;
+  case K_POLL_TYPE_IGNORE:
+    /* nothing to do */
+    break;
+  default:
+    __ASSERT(0, "invalid event type\n");
+    break;
+  }
+
+  event->poller = poller;
+
+  return 0;
 }
 
 /* must be called with interrupts locked */
-static inline void clear_event_registration(struct k_poll_event *event)
-{
-    event->poller = NULL;
-
-    switch (event->type) {
-        case K_POLL_TYPE_SEM_AVAILABLE:
-            __ASSERT(event->sem, "invalid semaphore\n");
-            sys_dlist_remove(&event->_node);
-            break;
-        case K_POLL_TYPE_DATA_AVAILABLE:
-            __ASSERT(event->queue, "invalid queue\n");
-            sys_dlist_remove(&event->_node);
-            break;
-        case K_POLL_TYPE_SIGNAL:
-            __ASSERT(event->signal, "invalid poll signal\n");
-            sys_dlist_remove(&event->_node);
-            break;
-        case K_POLL_TYPE_IGNORE:
-            /* nothing to do */
-            break;
-        default:
-            __ASSERT(0, "invalid event type\n");
-            break;
-    }
+static inline void clear_event_registration(struct k_poll_event *event) {
+  event->poller = NULL;
+
+  switch (event->type) {
+  case K_POLL_TYPE_SEM_AVAILABLE:
+    __ASSERT(event->sem, "invalid semaphore\n");
+    sys_dlist_remove(&event->_node);
+    break;
+  case K_POLL_TYPE_DATA_AVAILABLE:
+    __ASSERT(event->queue, "invalid queue\n");
+    sys_dlist_remove(&event->_node);
+    break;
+  case K_POLL_TYPE_SIGNAL:
+    __ASSERT(event->signal, "invalid poll signal\n");
+    sys_dlist_remove(&event->_node);
+    break;
+  case K_POLL_TYPE_IGNORE:
+    /* nothing to do */
+    break;
+  default:
+    __ASSERT(0, "invalid event type\n");
+    break;
+  }
 }
 
 /* must be called with interrupts locked */
-static inline void clear_event_registrations(struct k_poll_event *events,
-                                             int last_registered,
-                                             unsigned int key)
-{
-    for (; last_registered >= 0; last_registered--) {
-        clear_event_registration(&events[last_registered]);
-        irq_unlock(key);
-        key = irq_lock();
-    }
+static inline void clear_event_registrations(struct k_poll_event *events, int last_registered, unsigned int key) {
+  for (; last_registered >= 0; last_registered--) {
+    clear_event_registration(&events[last_registered]);
+    irq_unlock(key);
+    key = irq_lock();
+  }
 }
 
-static inline void set_event_ready(struct k_poll_event *event, u32_t state)
-{
-    event->poller = NULL;
-    event->state |= state;
+static inline void set_event_ready(struct k_poll_event *event, u32_t state) {
+  event->poller = NULL;
+  event->state |= state;
 }
 
-static bool polling_events(struct k_poll_event *events, int num_events,
-                           s32_t timeout, int *last_registered)
+#if (BFLB_BT_CO_THREAD)
+static bool polling_events(struct k_poll_event *events, int num_events, int total_evt_array_cnt, s32_t timeout, int *last_registered)
+#else
+static bool polling_events(struct k_poll_event *events, int num_events, s32_t timeout, int *last_registered)
+#endif
 {
-    int rc;
-    bool polling = true;
-    unsigned int key;
-
-    for (int ii = 0; ii < num_events; ii++) {
-        u32_t state;
-        key = irq_lock();
-        if (is_condition_met(&events[ii], &state)) {
-            set_event_ready(&events[ii], state);
-            polling = false;
-        } else if (timeout != K_NO_WAIT && polling) {
-            rc = register_event(&events[ii], NULL);
-            if (rc == 0) {
-                ++(*last_registered);
-            } else {
-                __ASSERT(0, "unexpected return code\n");
-            }
-        }
-        irq_unlock(key);
+  int          rc;
+  bool         polling = true;
+  unsigned int key;
+
+#if (BFLB_BT_CO_THREAD)
+  for (int ii = 0; ii < total_evt_array_cnt; ii++) {
+    if (ii >= num_events && ii != total_evt_array_cnt - 1)
+      continue;
+#else
+  for (int ii = 0; ii < num_events; ii++) {
+#endif
+    u32_t state;
+    key = irq_lock();
+    if (is_condition_met(&events[ii], &state)) {
+      set_event_ready(&events[ii], state);
+      polling = false;
+    } else if (timeout != K_NO_WAIT && polling) {
+      rc = register_event(&events[ii], NULL);
+      if (rc == 0) {
+        ++(*last_registered);
+      } else {
+        __ASSERT(0, "unexpected return code\n");
+      }
     }
-    return polling;
+    irq_unlock(key);
+  }
+  return polling;
 }
 
+#if (BFLB_BT_CO_THREAD)
+int k_poll(struct k_poll_event *events, int num_events, int total_evt_array_cnt, s32_t timeout, u8_t *to_process)
+#else
 int k_poll(struct k_poll_event *events, int num_events, s32_t timeout)
+#endif
 {
-    __ASSERT(events, "NULL events\n");
-    __ASSERT(num_events > 0, "zero events\n");
-
-    int last_registered = -1;
-    unsigned int key;
-    bool polling = true;
-
-    /* find events whose condition is already fulfilled */
-    polling = polling_events(events, num_events, timeout, &last_registered);
-
-    if (polling == false) {
-        goto exit;
-    }
-
+  __ASSERT(events, "NULL events\n");
+  __ASSERT(num_events > 0, "zero events\n");
+
+  int          last_registered = -1;
+  unsigned int key;
+  bool         polling = true;
+
+  /* find events whose condition is already fulfilled */
+#if (BFLB_BT_CO_THREAD)
+  polling = polling_events(events, num_events, total_evt_array_cnt, timeout, &last_registered);
+#else
+  polling = polling_events(events, num_events, timeout, &last_registered);
+#endif
+
+  if (polling == false) {
+    goto exit;
+  }
+#if (BFLB_BT_CO_THREAD)
+  if (timeout != K_NO_WAIT)
+#endif
+  {
     k_sem_take(&g_poll_sem, timeout);
-
     last_registered = -1;
+#if (BFLB_BT_CO_THREAD)
+    polling = polling_events(events, num_events, total_evt_array_cnt, timeout, &last_registered);
+#else
     polling_events(events, num_events, timeout, &last_registered);
+#endif
+  }
+
+#if (BFLB_BT_CO_THREAD)
+  if (to_process)
+    *to_process = polling ? 0 : 1;
+#endif
 exit:
-    key = irq_lock();
-    clear_event_registrations(events, last_registered, key);
-    irq_unlock(key);
-    return 0;
+  key = irq_lock();
+  clear_event_registrations(events, last_registered, key);
+  irq_unlock(key);
+  return 0;
 }
 
 /* must be called with interrupts locked */
-static int _signal_poll_event(struct k_poll_event *event, u32_t state,
-                              int *must_reschedule)
-{
-    *must_reschedule = 0;
-    set_event_ready(event, state);
-    return 0;
+static int _signal_poll_event(struct k_poll_event *event, u32_t state, int *must_reschedule) {
+  *must_reschedule = 0;
+  set_event_ready(event, state);
+  return 0;
 }
 
-int k_poll_signal_raise(struct k_poll_signal *signal, int result)
-{
-    unsigned int key = irq_lock();
-    struct k_poll_event *poll_event;
-    int must_reschedule;
+int k_poll_signal_raise(struct k_poll_signal *signal, int result) {
+  unsigned int         key = irq_lock();
+  struct k_poll_event *poll_event;
+  int                  must_reschedule;
 
-    signal->result = result;
-    signal->signaled = 1;
+  signal->result   = result;
+  signal->signaled = 1;
 
-    poll_event = (struct k_poll_event *)sys_dlist_get(&signal->poll_events);
-    if (!poll_event) {
-        irq_unlock(key);
-        return 0;
-    }
+  poll_event = (struct k_poll_event *)sys_dlist_get(&signal->poll_events);
+  if (!poll_event) {
+    irq_unlock(key);
+    return 0;
+  }
 
-    int rc = _signal_poll_event(poll_event, K_POLL_STATE_SIGNALED,
-                                &must_reschedule);
+  int rc = _signal_poll_event(poll_event, K_POLL_STATE_SIGNALED, &must_reschedule);
 
-    k_sem_give(&g_poll_sem);
-    irq_unlock(key);
-    return rc;
+  k_sem_give(&g_poll_sem);
+  irq_unlock(key);
+  return rc;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.c
index 231ca2215..fab3edea1 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.c
@@ -10,97 +10,90 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
+#include 
 #include 
-#include 
-#include 
-#include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
 
-#include 
+#include <../include/bluetooth/crypto.h>
 #include 
-#include 
 #include 
-#include <../include/bluetooth/crypto.h>
+#include 
+#include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_RPA)
 #define LOG_MODULE_NAME bt_rpa
 #include "log.h"
 
 #if defined(CONFIG_BT_CTLR_PRIVACY) || defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_SMP)
-static int ah(const u8_t irk[16], const u8_t r[3], u8_t out[3])
-{
-    u8_t res[16];
-    int err;
-
-    BT_DBG("irk %s", bt_hex(irk, 16));
-    BT_DBG("r %s", bt_hex(r, 3));
-
-    /* r' = padding || r */
-    memcpy(res, r, 3);
-    (void)memset(res + 3, 0, 13);
-
-    err = bt_encrypt_le(irk, res, res);
-    if (err) {
-        return err;
-    }
-
-    /* The output of the random address function ah is:
-	 *      ah(h, r) = e(k, r') mod 2^24
-	 * The output of the security function e is then truncated to 24 bits
-	 * by taking the least significant 24 bits of the output of e as the
-	 * result of ah.
-	 */
-    memcpy(out, res, 3);
-
-    return 0;
+static int ah(const u8_t irk[16], const u8_t r[3], u8_t out[3]) {
+  u8_t res[16];
+  int  err;
+
+  BT_DBG("irk %s", bt_hex(irk, 16));
+  BT_DBG("r %s", bt_hex(r, 3));
+
+  /* r' = padding || r */
+  memcpy(res, r, 3);
+  (void)memset(res + 3, 0, 13);
+
+  err = bt_encrypt_le(irk, res, res);
+  if (err) {
+    return err;
+  }
+
+  /* The output of the random address function ah is:
+   *      ah(h, r) = e(k, r') mod 2^24
+   * The output of the security function e is then truncated to 24 bits
+   * by taking the least significant 24 bits of the output of e as the
+   * result of ah.
+   */
+  memcpy(out, res, 3);
+
+  return 0;
 }
 #endif
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_CTLR_PRIVACY)
-bool bt_rpa_irk_matches(const u8_t irk[16], const bt_addr_t *addr)
-{
-    u8_t hash[3];
-    int err;
+bool bt_rpa_irk_matches(const u8_t irk[16], const bt_addr_t *addr) {
+  u8_t hash[3];
+  int  err;
 
-    BT_DBG("IRK %s bdaddr %s", bt_hex(irk, 16), bt_addr_str(addr));
+  BT_DBG("IRK %s bdaddr %s", bt_hex(irk, 16), bt_addr_str(addr));
 
-    err = ah(irk, addr->val + 3, hash);
-    if (err) {
-        return false;
-    }
+  err = ah(irk, addr->val + 3, hash);
+  if (err) {
+    return false;
+  }
 
-    return !memcmp(addr->val, hash, 3);
+  return !memcmp(addr->val, hash, 3);
 }
 #endif
 
 #if defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_CTLR_PRIVACY)
-int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa)
-{
-    int err;
+int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa) {
+  int err;
 
-    err = bt_rand(rpa->val + 3, 3);
-    if (err) {
-        return err;
-    }
+  err = bt_rand(rpa->val + 3, 3);
+  if (err) {
+    return err;
+  }
 
-    BT_ADDR_SET_RPA(rpa);
+  BT_ADDR_SET_RPA(rpa);
 
-    err = ah(irk, rpa->val + 3, rpa->val);
-    if (err) {
-        return err;
-    }
+  err = ah(irk, rpa->val + 3, rpa->val);
+  if (err) {
+    return err;
+  }
 
-    BT_DBG("Created RPA %s", bt_addr_str((bt_addr_t *)rpa->val));
+  BT_DBG("Created RPA %s", bt_addr_str((bt_addr_t *)rpa->val));
 
-    return 0;
+  return 0;
 }
 #else
-int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa)
-{
-    return -ENOTSUP;
-}
+int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa) { return -ENOTSUP; }
 #endif /* CONFIG_BT_PRIVACY */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.h
index dca68f155..148afc0bd 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/rpa.h
@@ -13,4 +13,4 @@
 #include "hci_host.h"
 
 bool bt_rpa_irk_matches(const u8_t irk[16], const bt_addr_t *addr);
-int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa);
+int  bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa);
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c
index 83719acc8..a0ea2b814 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c
@@ -35,34 +35,16 @@
 #include 
 
 static const uint8_t inv_sbox[256] = {
-    0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e,
-    0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
-    0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32,
-    0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
-    0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49,
-    0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
-    0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50,
-    0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
-    0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05,
-    0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
-    0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
-    0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
-    0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
-    0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
-    0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b,
-    0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
-    0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59,
-    0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
-    0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d,
-    0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
-    0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63,
-    0x55, 0x21, 0x0c, 0x7d
-};
-
-int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k)
-{
-    return tc_aes128_set_encrypt_key(s, k);
-}
+    0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
+    0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
+    0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
+    0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
+    0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
+    0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
+    0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
+    0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d};
+
+int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k) { return tc_aes128_set_encrypt_key(s, k); }
 
 #define mult8(a) (_double_byte(_double_byte(_double_byte(a))))
 #define mult9(a) (mult8(a) ^ (a))
@@ -70,52 +52,48 @@ int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k)
 #define multd(a) (mult8(a) ^ _double_byte(_double_byte(a)) ^ (a))
 #define multe(a) (mult8(a) ^ _double_byte(_double_byte(a)) ^ _double_byte(a))
 
-static inline void mult_row_column(uint8_t *out, const uint8_t *in)
-{
-    out[0] = multe(in[0]) ^ multb(in[1]) ^ multd(in[2]) ^ mult9(in[3]);
-    out[1] = mult9(in[0]) ^ multe(in[1]) ^ multb(in[2]) ^ multd(in[3]);
-    out[2] = multd(in[0]) ^ mult9(in[1]) ^ multe(in[2]) ^ multb(in[3]);
-    out[3] = multb(in[0]) ^ multd(in[1]) ^ mult9(in[2]) ^ multe(in[3]);
+static inline void mult_row_column(uint8_t *out, const uint8_t *in) {
+  out[0] = multe(in[0]) ^ multb(in[1]) ^ multd(in[2]) ^ mult9(in[3]);
+  out[1] = mult9(in[0]) ^ multe(in[1]) ^ multb(in[2]) ^ multd(in[3]);
+  out[2] = multd(in[0]) ^ mult9(in[1]) ^ multe(in[2]) ^ multb(in[3]);
+  out[3] = multb(in[0]) ^ multd(in[1]) ^ mult9(in[2]) ^ multe(in[3]);
 }
 
-static inline void inv_mix_columns(uint8_t *s)
-{
-    uint8_t t[Nb * Nk];
+static inline void inv_mix_columns(uint8_t *s) {
+  uint8_t t[Nb * Nk];
 
-    mult_row_column(t, s);
-    mult_row_column(&t[Nb], s + Nb);
-    mult_row_column(&t[2 * Nb], s + (2 * Nb));
-    mult_row_column(&t[3 * Nb], s + (3 * Nb));
-    (void)_copy(s, sizeof(t), t, sizeof(t));
+  mult_row_column(t, s);
+  mult_row_column(&t[Nb], s + Nb);
+  mult_row_column(&t[2 * Nb], s + (2 * Nb));
+  mult_row_column(&t[3 * Nb], s + (3 * Nb));
+  (void)_copy(s, sizeof(t), t, sizeof(t));
 }
 
-static inline void add_round_key(uint8_t *s, const unsigned int *k)
-{
-    s[0] ^= (uint8_t)(k[0] >> 24);
-    s[1] ^= (uint8_t)(k[0] >> 16);
-    s[2] ^= (uint8_t)(k[0] >> 8);
-    s[3] ^= (uint8_t)(k[0]);
-    s[4] ^= (uint8_t)(k[1] >> 24);
-    s[5] ^= (uint8_t)(k[1] >> 16);
-    s[6] ^= (uint8_t)(k[1] >> 8);
-    s[7] ^= (uint8_t)(k[1]);
-    s[8] ^= (uint8_t)(k[2] >> 24);
-    s[9] ^= (uint8_t)(k[2] >> 16);
-    s[10] ^= (uint8_t)(k[2] >> 8);
-    s[11] ^= (uint8_t)(k[2]);
-    s[12] ^= (uint8_t)(k[3] >> 24);
-    s[13] ^= (uint8_t)(k[3] >> 16);
-    s[14] ^= (uint8_t)(k[3] >> 8);
-    s[15] ^= (uint8_t)(k[3]);
+static inline void add_round_key(uint8_t *s, const unsigned int *k) {
+  s[0] ^= (uint8_t)(k[0] >> 24);
+  s[1] ^= (uint8_t)(k[0] >> 16);
+  s[2] ^= (uint8_t)(k[0] >> 8);
+  s[3] ^= (uint8_t)(k[0]);
+  s[4] ^= (uint8_t)(k[1] >> 24);
+  s[5] ^= (uint8_t)(k[1] >> 16);
+  s[6] ^= (uint8_t)(k[1] >> 8);
+  s[7] ^= (uint8_t)(k[1]);
+  s[8] ^= (uint8_t)(k[2] >> 24);
+  s[9] ^= (uint8_t)(k[2] >> 16);
+  s[10] ^= (uint8_t)(k[2] >> 8);
+  s[11] ^= (uint8_t)(k[2]);
+  s[12] ^= (uint8_t)(k[3] >> 24);
+  s[13] ^= (uint8_t)(k[3] >> 16);
+  s[14] ^= (uint8_t)(k[3] >> 8);
+  s[15] ^= (uint8_t)(k[3]);
 }
 
-static inline void inv_sub_bytes(uint8_t *s)
-{
-    unsigned int i;
+static inline void inv_sub_bytes(uint8_t *s) {
+  unsigned int i;
 
-    for (i = 0; i < (Nb * Nk); ++i) {
-        s[i] = inv_sbox[s[i]];
-    }
+  for (i = 0; i < (Nb * Nk); ++i) {
+    s[i] = inv_sbox[s[i]];
+  }
 }
 
 /*
@@ -123,61 +101,59 @@ static inline void inv_sub_bytes(uint8_t *s)
  * inv_mix_columns, but performs it here to reduce the number of memory
  * operations.
  */
-static inline void inv_shift_rows(uint8_t *s)
-{
-    uint8_t t[Nb * Nk];
-
-    t[0] = s[0];
-    t[1] = s[13];
-    t[2] = s[10];
-    t[3] = s[7];
-    t[4] = s[4];
-    t[5] = s[1];
-    t[6] = s[14];
-    t[7] = s[11];
-    t[8] = s[8];
-    t[9] = s[5];
-    t[10] = s[2];
-    t[11] = s[15];
-    t[12] = s[12];
-    t[13] = s[9];
-    t[14] = s[6];
-    t[15] = s[3];
-    (void)_copy(s, sizeof(t), t, sizeof(t));
+static inline void inv_shift_rows(uint8_t *s) {
+  uint8_t t[Nb * Nk];
+
+  t[0]  = s[0];
+  t[1]  = s[13];
+  t[2]  = s[10];
+  t[3]  = s[7];
+  t[4]  = s[4];
+  t[5]  = s[1];
+  t[6]  = s[14];
+  t[7]  = s[11];
+  t[8]  = s[8];
+  t[9]  = s[5];
+  t[10] = s[2];
+  t[11] = s[15];
+  t[12] = s[12];
+  t[13] = s[9];
+  t[14] = s[6];
+  t[15] = s[3];
+  (void)_copy(s, sizeof(t), t, sizeof(t));
 }
 
-int tc_aes_decrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s)
-{
-    uint8_t state[Nk * Nb];
-    unsigned int i;
+int tc_aes_decrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s) {
+  uint8_t      state[Nk * Nb];
+  unsigned int i;
 
-    if (out == (uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (in == (const uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (s == (TCAesKeySched_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+  if (out == (uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (in == (const uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (s == (TCAesKeySched_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    (void)_copy(state, sizeof(state), in, sizeof(state));
+  (void)_copy(state, sizeof(state), in, sizeof(state));
 
-    add_round_key(state, s->words + Nb * Nr);
-
-    for (i = Nr - 1; i > 0; --i) {
-        inv_shift_rows(state);
-        inv_sub_bytes(state);
-        add_round_key(state, s->words + Nb * i);
-        inv_mix_columns(state);
-    }
+  add_round_key(state, s->words + Nb * Nr);
 
+  for (i = Nr - 1; i > 0; --i) {
     inv_shift_rows(state);
     inv_sub_bytes(state);
-    add_round_key(state, s->words);
+    add_round_key(state, s->words + Nb * i);
+    inv_mix_columns(state);
+  }
+
+  inv_shift_rows(state);
+  inv_sub_bytes(state);
+  add_round_key(state, s->words);
 
-    (void)_copy(out, sizeof(state), state, sizeof(state));
+  (void)_copy(out, sizeof(state), state, sizeof(state));
 
-    /*zeroing out the state buffer */
-    _set(state, TC_ZERO_BYTE, sizeof(state));
+  /*zeroing out the state buffer */
+  _set(state, TC_ZERO_BYTE, sizeof(state));
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c
index 0cb47b84d..9d20d1c2a 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_encrypt.c
@@ -31,181 +31,152 @@
  */
 
 #include "aes.h"
-#include "utils.h"
 #include "constants.h"
+#include "utils.h"
 
 static const uint8_t sbox[256] = {
-    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b,
-    0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
-    0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26,
-    0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
-    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2,
-    0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
-    0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed,
-    0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
-    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f,
-    0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
-    0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
-    0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
-    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
-    0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
-    0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d,
-    0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
-    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f,
-    0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
-    0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11,
-    0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
-    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f,
-    0xb0, 0x54, 0xbb, 0x16
-};
-
-static inline unsigned int rotword(unsigned int a)
-{
-    return (((a) >> 24) | ((a) << 8));
-}
+    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
+    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
+    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
+    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
+    0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
+    0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
+    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
+    0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16};
+
+static inline unsigned int rotword(unsigned int a) { return (((a) >> 24) | ((a) << 8)); }
 
 #define subbyte(a, o) (sbox[((a) >> (o)) & 0xff] << (o))
 #define subword(a)    (subbyte(a, 24) | subbyte(a, 16) | subbyte(a, 8) | subbyte(a, 0))
 
-int tc_aes128_set_encrypt_key(TCAesKeySched_t s, const uint8_t *k)
-{
-    const unsigned int rconst[11] = {
-        0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000,
-        0x20000000, 0x40000000, 0x80000000, 0x1b000000, 0x36000000
-    };
-    unsigned int i;
-    unsigned int t;
-
-    if (s == (TCAesKeySched_t)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (k == (const uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    }
-
-    for (i = 0; i < Nk; ++i) {
-        s->words[i] = (k[Nb * i] << 24) | (k[Nb * i + 1] << 16) |
-                      (k[Nb * i + 2] << 8) | (k[Nb * i + 3]);
+int tc_aes128_set_encrypt_key(TCAesKeySched_t s, const uint8_t *k) {
+  const unsigned int rconst[11] = {0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1b000000, 0x36000000};
+  unsigned int       i;
+  unsigned int       t;
+
+  if (s == (TCAesKeySched_t)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (k == (const uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  for (i = 0; i < Nk; ++i) {
+    s->words[i] = (k[Nb * i] << 24) | (k[Nb * i + 1] << 16) | (k[Nb * i + 2] << 8) | (k[Nb * i + 3]);
+  }
+
+  for (; i < (Nb * (Nr + 1)); ++i) {
+    t = s->words[i - 1];
+    if ((i % Nk) == 0) {
+      t = subword(rotword(t)) ^ rconst[i / Nk];
     }
+    s->words[i] = s->words[i - Nk] ^ t;
+  }
 
-    for (; i < (Nb * (Nr + 1)); ++i) {
-        t = s->words[i - 1];
-        if ((i % Nk) == 0) {
-            t = subword(rotword(t)) ^ rconst[i / Nk];
-        }
-        s->words[i] = s->words[i - Nk] ^ t;
-    }
-
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-static inline void add_round_key(uint8_t *s, const unsigned int *k)
-{
-    s[0] ^= (uint8_t)(k[0] >> 24);
-    s[1] ^= (uint8_t)(k[0] >> 16);
-    s[2] ^= (uint8_t)(k[0] >> 8);
-    s[3] ^= (uint8_t)(k[0]);
-    s[4] ^= (uint8_t)(k[1] >> 24);
-    s[5] ^= (uint8_t)(k[1] >> 16);
-    s[6] ^= (uint8_t)(k[1] >> 8);
-    s[7] ^= (uint8_t)(k[1]);
-    s[8] ^= (uint8_t)(k[2] >> 24);
-    s[9] ^= (uint8_t)(k[2] >> 16);
-    s[10] ^= (uint8_t)(k[2] >> 8);
-    s[11] ^= (uint8_t)(k[2]);
-    s[12] ^= (uint8_t)(k[3] >> 24);
-    s[13] ^= (uint8_t)(k[3] >> 16);
-    s[14] ^= (uint8_t)(k[3] >> 8);
-    s[15] ^= (uint8_t)(k[3]);
+static inline void add_round_key(uint8_t *s, const unsigned int *k) {
+  s[0] ^= (uint8_t)(k[0] >> 24);
+  s[1] ^= (uint8_t)(k[0] >> 16);
+  s[2] ^= (uint8_t)(k[0] >> 8);
+  s[3] ^= (uint8_t)(k[0]);
+  s[4] ^= (uint8_t)(k[1] >> 24);
+  s[5] ^= (uint8_t)(k[1] >> 16);
+  s[6] ^= (uint8_t)(k[1] >> 8);
+  s[7] ^= (uint8_t)(k[1]);
+  s[8] ^= (uint8_t)(k[2] >> 24);
+  s[9] ^= (uint8_t)(k[2] >> 16);
+  s[10] ^= (uint8_t)(k[2] >> 8);
+  s[11] ^= (uint8_t)(k[2]);
+  s[12] ^= (uint8_t)(k[3] >> 24);
+  s[13] ^= (uint8_t)(k[3] >> 16);
+  s[14] ^= (uint8_t)(k[3] >> 8);
+  s[15] ^= (uint8_t)(k[3]);
 }
 
-static inline void sub_bytes(uint8_t *s)
-{
-    unsigned int i;
+static inline void sub_bytes(uint8_t *s) {
+  unsigned int i;
 
-    for (i = 0; i < (Nb * Nk); ++i) {
-        s[i] = sbox[s[i]];
-    }
+  for (i = 0; i < (Nb * Nk); ++i) {
+    s[i] = sbox[s[i]];
+  }
 }
 
 #define triple(a) (_double_byte(a) ^ (a))
 
-static inline void mult_row_column(uint8_t *out, const uint8_t *in)
-{
-    out[0] = _double_byte(in[0]) ^ triple(in[1]) ^ in[2] ^ in[3];
-    out[1] = in[0] ^ _double_byte(in[1]) ^ triple(in[2]) ^ in[3];
-    out[2] = in[0] ^ in[1] ^ _double_byte(in[2]) ^ triple(in[3]);
-    out[3] = triple(in[0]) ^ in[1] ^ in[2] ^ _double_byte(in[3]);
+static inline void mult_row_column(uint8_t *out, const uint8_t *in) {
+  out[0] = _double_byte(in[0]) ^ triple(in[1]) ^ in[2] ^ in[3];
+  out[1] = in[0] ^ _double_byte(in[1]) ^ triple(in[2]) ^ in[3];
+  out[2] = in[0] ^ in[1] ^ _double_byte(in[2]) ^ triple(in[3]);
+  out[3] = triple(in[0]) ^ in[1] ^ in[2] ^ _double_byte(in[3]);
 }
 
-static inline void mix_columns(uint8_t *s)
-{
-    uint8_t t[Nb * Nk];
+static inline void mix_columns(uint8_t *s) {
+  uint8_t t[Nb * Nk];
 
-    mult_row_column(t, s);
-    mult_row_column(&t[Nb], s + Nb);
-    mult_row_column(&t[2 * Nb], s + (2 * Nb));
-    mult_row_column(&t[3 * Nb], s + (3 * Nb));
-    (void)_copy(s, sizeof(t), t, sizeof(t));
+  mult_row_column(t, s);
+  mult_row_column(&t[Nb], s + Nb);
+  mult_row_column(&t[2 * Nb], s + (2 * Nb));
+  mult_row_column(&t[3 * Nb], s + (3 * Nb));
+  (void)_copy(s, sizeof(t), t, sizeof(t));
 }
 
 /*
  * This shift_rows also implements the matrix flip required for mix_columns, but
  * performs it here to reduce the number of memory operations.
  */
-static inline void shift_rows(uint8_t *s)
-{
-    uint8_t t[Nb * Nk];
-
-    t[0] = s[0];
-    t[1] = s[5];
-    t[2] = s[10];
-    t[3] = s[15];
-    t[4] = s[4];
-    t[5] = s[9];
-    t[6] = s[14];
-    t[7] = s[3];
-    t[8] = s[8];
-    t[9] = s[13];
-    t[10] = s[2];
-    t[11] = s[7];
-    t[12] = s[12];
-    t[13] = s[1];
-    t[14] = s[6];
-    t[15] = s[11];
-    (void)_copy(s, sizeof(t), t, sizeof(t));
+static inline void shift_rows(uint8_t *s) {
+  uint8_t t[Nb * Nk];
+
+  t[0]  = s[0];
+  t[1]  = s[5];
+  t[2]  = s[10];
+  t[3]  = s[15];
+  t[4]  = s[4];
+  t[5]  = s[9];
+  t[6]  = s[14];
+  t[7]  = s[3];
+  t[8]  = s[8];
+  t[9]  = s[13];
+  t[10] = s[2];
+  t[11] = s[7];
+  t[12] = s[12];
+  t[13] = s[1];
+  t[14] = s[6];
+  t[15] = s[11];
+  (void)_copy(s, sizeof(t), t, sizeof(t));
 }
 
-int tc_aes_encrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s)
-{
-    uint8_t state[Nk * Nb];
-    unsigned int i;
-
-    if (out == (uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (in == (const uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (s == (TCAesKeySched_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_aes_encrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s) {
+  uint8_t      state[Nk * Nb];
+  unsigned int i;
 
-    (void)_copy(state, sizeof(state), in, sizeof(state));
-    add_round_key(state, s->words);
+  if (out == (uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (in == (const uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (s == (TCAesKeySched_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    for (i = 0; i < (Nr - 1); ++i) {
-        sub_bytes(state);
-        shift_rows(state);
-        mix_columns(state);
-        add_round_key(state, s->words + Nb * (i + 1));
-    }
+  (void)_copy(state, sizeof(state), in, sizeof(state));
+  add_round_key(state, s->words);
 
+  for (i = 0; i < (Nr - 1); ++i) {
     sub_bytes(state);
     shift_rows(state);
+    mix_columns(state);
     add_round_key(state, s->words + Nb * (i + 1));
+  }
+
+  sub_bytes(state);
+  shift_rows(state);
+  add_round_key(state, s->words + Nb * (i + 1));
 
-    (void)_copy(out, sizeof(state), state, sizeof(state));
+  (void)_copy(out, sizeof(state), state, sizeof(state));
 
-    /* zeroing out the state buffer */
-    _set(state, TC_ZERO_BYTE, sizeof(state));
+  /* zeroing out the state buffer */
+  _set(state, TC_ZERO_BYTE, sizeof(state));
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c
index b405d7d29..8c30104f8 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cbc_mode.c
@@ -34,79 +34,60 @@
 #include "constants.h"
 #include "utils.h"
 
-int tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in,
-                        unsigned int inlen, const uint8_t *iv,
-                        const TCAesKeySched_t sched)
-{
-    uint8_t buffer[TC_AES_BLOCK_SIZE];
-    unsigned int n, m;
+int tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched) {
+  uint8_t      buffer[TC_AES_BLOCK_SIZE];
+  unsigned int n, m;
 
-    /* input sanity check: */
-    if (out == (uint8_t *)0 ||
-        in == (const uint8_t *)0 ||
-        sched == (TCAesKeySched_t)0 ||
-        inlen == 0 ||
-        outlen == 0 ||
-        (inlen % TC_AES_BLOCK_SIZE) != 0 ||
-        (outlen % TC_AES_BLOCK_SIZE) != 0 ||
-        outlen != inlen + TC_AES_BLOCK_SIZE) {
-        return TC_CRYPTO_FAIL;
-    }
+  /* input sanity check: */
+  if (out == (uint8_t *)0 || in == (const uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0 ||
+      outlen != inlen + TC_AES_BLOCK_SIZE) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* copy iv to the buffer */
-    (void)_copy(buffer, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE);
-    /* copy iv to the output buffer */
-    (void)_copy(out, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE);
-    out += TC_AES_BLOCK_SIZE;
+  /* copy iv to the buffer */
+  (void)_copy(buffer, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE);
+  /* copy iv to the output buffer */
+  (void)_copy(out, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE);
+  out += TC_AES_BLOCK_SIZE;
 
-    for (n = m = 0; n < inlen; ++n) {
-        buffer[m++] ^= *in++;
-        if (m == TC_AES_BLOCK_SIZE) {
-            (void)tc_aes_encrypt(buffer, buffer, sched);
-            (void)_copy(out, TC_AES_BLOCK_SIZE,
-                        buffer, TC_AES_BLOCK_SIZE);
-            out += TC_AES_BLOCK_SIZE;
-            m = 0;
-        }
+  for (n = m = 0; n < inlen; ++n) {
+    buffer[m++] ^= *in++;
+    if (m == TC_AES_BLOCK_SIZE) {
+      (void)tc_aes_encrypt(buffer, buffer, sched);
+      (void)_copy(out, TC_AES_BLOCK_SIZE, buffer, TC_AES_BLOCK_SIZE);
+      out += TC_AES_BLOCK_SIZE;
+      m = 0;
     }
+  }
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in,
-                        unsigned int inlen, const uint8_t *iv,
-                        const TCAesKeySched_t sched)
-{
-    uint8_t buffer[TC_AES_BLOCK_SIZE];
-    const uint8_t *p;
-    unsigned int n, m;
+int tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, const uint8_t *iv, const TCAesKeySched_t sched) {
+  uint8_t        buffer[TC_AES_BLOCK_SIZE];
+  const uint8_t *p;
+  unsigned int   n, m;
 
-    /* sanity check the inputs */
-    if (out == (uint8_t *)0 ||
-        in == (const uint8_t *)0 ||
-        sched == (TCAesKeySched_t)0 ||
-        inlen == 0 ||
-        outlen == 0 ||
-        (inlen % TC_AES_BLOCK_SIZE) != 0 ||
-        (outlen % TC_AES_BLOCK_SIZE) != 0 ||
-        outlen != inlen) {
-        return TC_CRYPTO_FAIL;
-    }
+  /* sanity check the inputs */
+  if (out == (uint8_t *)0 || in == (const uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || (inlen % TC_AES_BLOCK_SIZE) != 0 || (outlen % TC_AES_BLOCK_SIZE) != 0 ||
+      outlen != inlen) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /*
-	 * Note that in == iv + ciphertext, i.e. the iv and the ciphertext are
-	 * contiguous. This allows for a very efficient decryption algorithm
-	 * that would not otherwise be possible.
-	 */
-    p = iv;
-    for (n = m = 0; n < outlen; ++n) {
-        if ((n % TC_AES_BLOCK_SIZE) == 0) {
-            (void)tc_aes_decrypt(buffer, in, sched);
-            in += TC_AES_BLOCK_SIZE;
-            m = 0;
-        }
-        *out++ = buffer[m++] ^ *p++;
+  /*
+   * Note that in == iv + ciphertext, i.e. the iv and the ciphertext are
+   * contiguous. This allows for a very efficient decryption algorithm
+   * that would not otherwise be possible.
+   */
+  p = iv;
+  for (n = m = 0; n < outlen; ++n) {
+    if ((n % TC_AES_BLOCK_SIZE) == 0) {
+      (void)tc_aes_decrypt(buffer, in, sched);
+      in += TC_AES_BLOCK_SIZE;
+      m = 0;
     }
+    *out++ = buffer[m++] ^ *p++;
+  }
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c
index ed94e75bb..e102957e7 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ccm_mode.c
@@ -36,50 +36,44 @@
 
 #include 
 
-int tc_ccm_config(TCCcmMode_t c, TCAesKeySched_t sched, uint8_t *nonce,
-                  unsigned int nlen, unsigned int mlen)
-{
-    /* input sanity check: */
-    if (c == (TCCcmMode_t)0 ||
-        sched == (TCAesKeySched_t)0 ||
-        nonce == (uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (nlen != 13) {
-        return TC_CRYPTO_FAIL; /* The allowed nonce size is: 13. See documentation.*/
-    } else if ((mlen < 4) || (mlen > 16) || (mlen & 1)) {
-        return TC_CRYPTO_FAIL; /* The allowed mac sizes are: 4, 6, 8, 10, 12, 14, 16.*/
-    }
-
-    c->mlen = mlen;
-    c->sched = sched;
-    c->nonce = nonce;
-
-    return TC_CRYPTO_SUCCESS;
+int tc_ccm_config(TCCcmMode_t c, TCAesKeySched_t sched, uint8_t *nonce, unsigned int nlen, unsigned int mlen) {
+  /* input sanity check: */
+  if (c == (TCCcmMode_t)0 || sched == (TCAesKeySched_t)0 || nonce == (uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (nlen != 13) {
+    return TC_CRYPTO_FAIL; /* The allowed nonce size is: 13. See documentation.*/
+  } else if ((mlen < 4) || (mlen > 16) || (mlen & 1)) {
+    return TC_CRYPTO_FAIL; /* The allowed mac sizes are: 4, 6, 8, 10, 12, 14, 16.*/
+  }
+
+  c->mlen  = mlen;
+  c->sched = sched;
+  c->nonce = nonce;
+
+  return TC_CRYPTO_SUCCESS;
 }
 
 /**
  * Variation of CBC-MAC mode used in CCM.
  */
-static void ccm_cbc_mac(uint8_t *T, const uint8_t *data, unsigned int dlen,
-                        unsigned int flag, TCAesKeySched_t sched)
-{
-    unsigned int i;
-
-    if (flag > 0) {
-        T[0] ^= (uint8_t)(dlen >> 8);
-        T[1] ^= (uint8_t)(dlen);
-        dlen += 2;
-        i = 2;
-    } else {
-        i = 0;
-    }
-
-    while (i < dlen) {
-        T[i++ % (Nb * Nk)] ^= *data++;
-        if (((i % (Nb * Nk)) == 0) || dlen == i) {
-            (void)tc_aes_encrypt(T, T, sched);
-        }
-    }
+static void ccm_cbc_mac(uint8_t *T, const uint8_t *data, unsigned int dlen, unsigned int flag, TCAesKeySched_t sched) {
+  unsigned int i;
+
+  if (flag > 0) {
+    T[0] ^= (uint8_t)(dlen >> 8);
+    T[1] ^= (uint8_t)(dlen);
+    dlen += 2;
+    i = 2;
+  } else {
+    i = 0;
+  }
+
+  while (i < dlen) {
+    T[i++ % (Nb * Nk)] ^= *data++;
+    if (((i % (Nb * Nk)) == 0) || dlen == i) {
+      (void)tc_aes_encrypt(T, T, sched);
+    }
+  }
 }
 
 /**
@@ -89,175 +83,153 @@ static void ccm_cbc_mac(uint8_t *T, const uint8_t *data, unsigned int dlen,
  * encryption). Besides, it is assumed that the counter is stored in the last
  * 2 bytes of the nonce.
  */
-static int ccm_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in,
-                        unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched)
-{
-    uint8_t buffer[TC_AES_BLOCK_SIZE];
-    uint8_t nonce[TC_AES_BLOCK_SIZE];
-    uint16_t block_num;
-    unsigned int i;
-
-    /* input sanity check: */
-    if (out == (uint8_t *)0 ||
-        in == (uint8_t *)0 ||
-        ctr == (uint8_t *)0 ||
-        sched == (TCAesKeySched_t)0 ||
-        inlen == 0 ||
-        outlen == 0 ||
-        outlen != inlen) {
+static int ccm_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched) {
+  uint8_t      buffer[TC_AES_BLOCK_SIZE];
+  uint8_t      nonce[TC_AES_BLOCK_SIZE];
+  uint16_t     block_num;
+  unsigned int i;
+
+  /* input sanity check: */
+  if (out == (uint8_t *)0 || in == (uint8_t *)0 || ctr == (uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || outlen != inlen) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  /* copy the counter to the nonce */
+  (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce));
+
+  /* select the last 2 bytes of the nonce to be incremented */
+  block_num = (uint16_t)((nonce[14] << 8) | (nonce[15]));
+  for (i = 0; i < inlen; ++i) {
+    if ((i % (TC_AES_BLOCK_SIZE)) == 0) {
+      block_num++;
+      nonce[14] = (uint8_t)(block_num >> 8);
+      nonce[15] = (uint8_t)(block_num);
+      if (!tc_aes_encrypt(buffer, nonce, sched)) {
         return TC_CRYPTO_FAIL;
+      }
     }
+    /* update the output */
+    *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++;
+  }
 
-    /* copy the counter to the nonce */
-    (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce));
-
-    /* select the last 2 bytes of the nonce to be incremented */
-    block_num = (uint16_t)((nonce[14] << 8) | (nonce[15]));
-    for (i = 0; i < inlen; ++i) {
-        if ((i % (TC_AES_BLOCK_SIZE)) == 0) {
-            block_num++;
-            nonce[14] = (uint8_t)(block_num >> 8);
-            nonce[15] = (uint8_t)(block_num);
-            if (!tc_aes_encrypt(buffer, nonce, sched)) {
-                return TC_CRYPTO_FAIL;
-            }
-        }
-        /* update the output */
-        *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++;
-    }
-
-    /* update the counter */
-    ctr[14] = nonce[14];
-    ctr[15] = nonce[15];
+  /* update the counter */
+  ctr[14] = nonce[14];
+  ctr[15] = nonce[15];
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen,
-                                 const uint8_t *associated_data,
-                                 unsigned int alen, const uint8_t *payload,
-                                 unsigned int plen, TCCcmMode_t c)
-{
-    /* input sanity check: */
-    if ((out == (uint8_t *)0) ||
-        (c == (TCCcmMode_t)0) ||
-        ((plen > 0) && (payload == (uint8_t *)0)) ||
-        ((alen > 0) && (associated_data == (uint8_t *)0)) ||
-        (alen >= TC_CCM_AAD_MAX_BYTES) ||     /* associated data size unsupported */
-        (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */
-        (olen < (plen + c->mlen))) {          /* invalid output buffer size */
-        return TC_CRYPTO_FAIL;
-    }
-
-    uint8_t b[Nb * Nk];
-    uint8_t tag[Nb * Nk];
-    unsigned int i;
-
-    /* GENERATING THE AUTHENTICATION TAG: */
-
-    /* formatting the sequence b for authentication: */
-    b[0] = ((alen > 0) ? 0x40 : 0) | (((c->mlen - 2) / 2 << 3)) | (1);
-    for (i = 1; i <= 13; ++i) {
-        b[i] = c->nonce[i - 1];
-    }
-    b[14] = (uint8_t)(plen >> 8);
-    b[15] = (uint8_t)(plen);
-
-    /* computing the authentication tag using cbc-mac: */
-    (void)tc_aes_encrypt(tag, b, c->sched);
-    if (alen > 0) {
-        ccm_cbc_mac(tag, associated_data, alen, 1, c->sched);
-    }
-    if (plen > 0) {
-        ccm_cbc_mac(tag, payload, plen, 0, c->sched);
-    }
-
-    /* ENCRYPTION: */
-
-    /* formatting the sequence b for encryption: */
-    b[0] = 1; /* q - 1 = 2 - 1 = 1 */
-    b[14] = b[15] = TC_ZERO_BYTE;
-
-    /* encrypting payload using ctr mode: */
-    ccm_ctr_mode(out, plen, payload, plen, b, c->sched);
-
-    b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter for ctr_mode (0):*/
-
-    /* encrypting b and adding the tag to the output: */
-    (void)tc_aes_encrypt(b, b, c->sched);
-    out += plen;
-    for (i = 0; i < c->mlen; ++i) {
-        *out++ = tag[i] ^ b[i];
-    }
-
-    return TC_CRYPTO_SUCCESS;
+int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen, const uint8_t *associated_data, unsigned int alen, const uint8_t *payload, unsigned int plen, TCCcmMode_t c) {
+  /* input sanity check: */
+  if ((out == (uint8_t *)0) || (c == (TCCcmMode_t)0) || ((plen > 0) && (payload == (uint8_t *)0)) || ((alen > 0) && (associated_data == (uint8_t *)0)) ||
+      (alen >= TC_CCM_AAD_MAX_BYTES) ||     /* associated data size unsupported */
+      (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */
+      (olen < (plen + c->mlen))) {          /* invalid output buffer size */
+    return TC_CRYPTO_FAIL;
+  }
+
+  uint8_t      b[Nb * Nk];
+  uint8_t      tag[Nb * Nk];
+  unsigned int i;
+
+  /* GENERATING THE AUTHENTICATION TAG: */
+
+  /* formatting the sequence b for authentication: */
+  b[0] = ((alen > 0) ? 0x40 : 0) | (((c->mlen - 2) / 2 << 3)) | (1);
+  for (i = 1; i <= 13; ++i) {
+    b[i] = c->nonce[i - 1];
+  }
+  b[14] = (uint8_t)(plen >> 8);
+  b[15] = (uint8_t)(plen);
+
+  /* computing the authentication tag using cbc-mac: */
+  (void)tc_aes_encrypt(tag, b, c->sched);
+  if (alen > 0) {
+    ccm_cbc_mac(tag, associated_data, alen, 1, c->sched);
+  }
+  if (plen > 0) {
+    ccm_cbc_mac(tag, payload, plen, 0, c->sched);
+  }
+
+  /* ENCRYPTION: */
+
+  /* formatting the sequence b for encryption: */
+  b[0]  = 1; /* q - 1 = 2 - 1 = 1 */
+  b[14] = b[15] = TC_ZERO_BYTE;
+
+  /* encrypting payload using ctr mode: */
+  ccm_ctr_mode(out, plen, payload, plen, b, c->sched);
+
+  b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter for ctr_mode (0):*/
+
+  /* encrypting b and adding the tag to the output: */
+  (void)tc_aes_encrypt(b, b, c->sched);
+  out += plen;
+  for (i = 0; i < c->mlen; ++i) {
+    *out++ = tag[i] ^ b[i];
+  }
+
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_ccm_decryption_verification(uint8_t *out, unsigned int olen,
-                                   const uint8_t *associated_data,
-                                   unsigned int alen, const uint8_t *payload,
-                                   unsigned int plen, TCCcmMode_t c)
-{
-    /* input sanity check: */
-    if ((out == (uint8_t *)0) ||
-        (c == (TCCcmMode_t)0) ||
-        ((plen > 0) && (payload == (uint8_t *)0)) ||
-        ((alen > 0) && (associated_data == (uint8_t *)0)) ||
-        (alen >= TC_CCM_AAD_MAX_BYTES) ||     /* associated data size unsupported */
-        (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */
-        (olen < plen - c->mlen)) {            /* invalid output buffer size */
-        return TC_CRYPTO_FAIL;
-    }
-
-    uint8_t b[Nb * Nk];
-    uint8_t tag[Nb * Nk];
-    unsigned int i;
-
-    /* DECRYPTION: */
-
-    /* formatting the sequence b for decryption: */
-    b[0] = 1; /* q - 1 = 2 - 1 = 1 */
-    for (i = 1; i < 14; ++i) {
-        b[i] = c->nonce[i - 1];
-    }
-    b[14] = b[15] = TC_ZERO_BYTE; /* initial counter value is 0 */
-
-    /* decrypting payload using ctr mode: */
-    ccm_ctr_mode(out, plen - c->mlen, payload, plen - c->mlen, b, c->sched);
-
-    b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter value (0) */
-
-    /* encrypting b and restoring the tag from input: */
-    (void)tc_aes_encrypt(b, b, c->sched);
-    for (i = 0; i < c->mlen; ++i) {
-        tag[i] = *(payload + plen - c->mlen + i) ^ b[i];
-    }
-
-    /* VERIFYING THE AUTHENTICATION TAG: */
-
-    /* formatting the sequence b for authentication: */
-    b[0] = ((alen > 0) ? 0x40 : 0) | (((c->mlen - 2) / 2 << 3)) | (1);
-    for (i = 1; i < 14; ++i) {
-        b[i] = c->nonce[i - 1];
-    }
-    b[14] = (uint8_t)((plen - c->mlen) >> 8);
-    b[15] = (uint8_t)(plen - c->mlen);
-
-    /* computing the authentication tag using cbc-mac: */
-    (void)tc_aes_encrypt(b, b, c->sched);
-    if (alen > 0) {
-        ccm_cbc_mac(b, associated_data, alen, 1, c->sched);
-    }
-    if (plen > 0) {
-        ccm_cbc_mac(b, out, plen - c->mlen, 0, c->sched);
-    }
-
-    /* comparing the received tag and the computed one: */
-    if (_compare(b, tag, c->mlen) == 0) {
-        return TC_CRYPTO_SUCCESS;
-    } else {
-        /* erase the decrypted buffer in case of mac validation failure: */
-        _set(out, 0, plen - c->mlen);
-        return TC_CRYPTO_FAIL;
-    }
+int tc_ccm_decryption_verification(uint8_t *out, unsigned int olen, const uint8_t *associated_data, unsigned int alen, const uint8_t *payload, unsigned int plen, TCCcmMode_t c) {
+  /* input sanity check: */
+  if ((out == (uint8_t *)0) || (c == (TCCcmMode_t)0) || ((plen > 0) && (payload == (uint8_t *)0)) || ((alen > 0) && (associated_data == (uint8_t *)0)) ||
+      (alen >= TC_CCM_AAD_MAX_BYTES) ||     /* associated data size unsupported */
+      (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */
+      (olen < plen - c->mlen)) {            /* invalid output buffer size */
+    return TC_CRYPTO_FAIL;
+  }
+
+  uint8_t      b[Nb * Nk];
+  uint8_t      tag[Nb * Nk];
+  unsigned int i;
+
+  /* DECRYPTION: */
+
+  /* formatting the sequence b for decryption: */
+  b[0] = 1; /* q - 1 = 2 - 1 = 1 */
+  for (i = 1; i < 14; ++i) {
+    b[i] = c->nonce[i - 1];
+  }
+  b[14] = b[15] = TC_ZERO_BYTE; /* initial counter value is 0 */
+
+  /* decrypting payload using ctr mode: */
+  ccm_ctr_mode(out, plen - c->mlen, payload, plen - c->mlen, b, c->sched);
+
+  b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter value (0) */
+
+  /* encrypting b and restoring the tag from input: */
+  (void)tc_aes_encrypt(b, b, c->sched);
+  for (i = 0; i < c->mlen; ++i) {
+    tag[i] = *(payload + plen - c->mlen + i) ^ b[i];
+  }
+
+  /* VERIFYING THE AUTHENTICATION TAG: */
+
+  /* formatting the sequence b for authentication: */
+  b[0] = ((alen > 0) ? 0x40 : 0) | (((c->mlen - 2) / 2 << 3)) | (1);
+  for (i = 1; i < 14; ++i) {
+    b[i] = c->nonce[i - 1];
+  }
+  b[14] = (uint8_t)((plen - c->mlen) >> 8);
+  b[15] = (uint8_t)(plen - c->mlen);
+
+  /* computing the authentication tag using cbc-mac: */
+  (void)tc_aes_encrypt(b, b, c->sched);
+  if (alen > 0) {
+    ccm_cbc_mac(b, associated_data, alen, 1, c->sched);
+  }
+  if (plen > 0) {
+    ccm_cbc_mac(b, out, plen - c->mlen, 0, c->sched);
+  }
+
+  /* comparing the received tag and the computed one: */
+  if (_compare(b, tag, c->mlen) == 0) {
+    return TC_CRYPTO_SUCCESS;
+  } else {
+    /* erase the decrypted buffer in case of mac validation failure: */
+    _set(out, 0, plen - c->mlen);
+    return TC_CRYPTO_FAIL;
+  }
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cmac_mode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cmac_mode.c
index 97e7dd34c..fa517db9b 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cmac_mode.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/cmac_mode.c
@@ -30,8 +30,8 @@
  *  POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "aes.h"
 #include "cmac_mode.h"
+#include "aes.h"
 #include "constants.h"
 #include "utils.h"
 
@@ -75,178 +75,167 @@ const unsigned char gf_wrap = 0x87;
  *  effects: doubles the GF(2^n) value pointed to by "in" and places
  *           the result in the GF(2^n) value pointed to by "out."
  */
-void gf_double(uint8_t *out, uint8_t *in)
-{
-    /* start with low order byte */
-    uint8_t *x = in + (TC_AES_BLOCK_SIZE - 1);
-
-    /* if msb == 1, we need to add the gf_wrap value, otherwise add 0 */
-    uint8_t carry = (in[0] >> 7) ? gf_wrap : 0;
-
-    out += (TC_AES_BLOCK_SIZE - 1);
-    for (;;) {
-        *out-- = (*x << 1) ^ carry;
-        if (x == in) {
-            break;
-        }
-        carry = *x-- >> 7;
+void gf_double(uint8_t *out, uint8_t *in) {
+  /* start with low order byte */
+  uint8_t *x = in + (TC_AES_BLOCK_SIZE - 1);
+
+  /* if msb == 1, we need to add the gf_wrap value, otherwise add 0 */
+  uint8_t carry = (in[0] >> 7) ? gf_wrap : 0;
+
+  out += (TC_AES_BLOCK_SIZE - 1);
+  for (;;) {
+    *out-- = (*x << 1) ^ carry;
+    if (x == in) {
+      break;
     }
+    carry = *x-- >> 7;
+  }
 }
 
-int tc_cmac_setup(TCCmacState_t s, const uint8_t *key, TCAesKeySched_t sched)
-{
-    /* input sanity check: */
-    if (s == (TCCmacState_t)0 ||
-        key == (const uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_cmac_setup(TCCmacState_t s, const uint8_t *key, TCAesKeySched_t sched) {
+  /* input sanity check: */
+  if (s == (TCCmacState_t)0 || key == (const uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* put s into a known state */
-    _set(s, 0, sizeof(*s));
-    s->sched = sched;
+  /* put s into a known state */
+  _set(s, 0, sizeof(*s));
+  s->sched = sched;
 
-    /* configure the encryption key used by the underlying block cipher */
-    tc_aes128_set_encrypt_key(s->sched, key);
+  /* configure the encryption key used by the underlying block cipher */
+  tc_aes128_set_encrypt_key(s->sched, key);
 
-    /* compute s->K1 and s->K2 from s->iv using s->keyid */
-    _set(s->iv, 0, TC_AES_BLOCK_SIZE);
-    tc_aes_encrypt(s->iv, s->iv, s->sched);
-    gf_double(s->K1, s->iv);
-    gf_double(s->K2, s->K1);
+  /* compute s->K1 and s->K2 from s->iv using s->keyid */
+  _set(s->iv, 0, TC_AES_BLOCK_SIZE);
+  tc_aes_encrypt(s->iv, s->iv, s->sched);
+  gf_double(s->K1, s->iv);
+  gf_double(s->K2, s->K1);
 
-    /* reset s->iv to 0 in case someone wants to compute now */
-    tc_cmac_init(s);
+  /* reset s->iv to 0 in case someone wants to compute now */
+  tc_cmac_init(s);
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_cmac_erase(TCCmacState_t s)
-{
-    if (s == (TCCmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_cmac_erase(TCCmacState_t s) {
+  if (s == (TCCmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* destroy the current state */
-    _set(s, 0, sizeof(*s));
+  /* destroy the current state */
+  _set(s, 0, sizeof(*s));
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_cmac_init(TCCmacState_t s)
-{
-    /* input sanity check: */
-    if (s == (TCCmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_cmac_init(TCCmacState_t s) {
+  /* input sanity check: */
+  if (s == (TCCmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* CMAC starts with an all zero initialization vector */
-    _set(s->iv, 0, TC_AES_BLOCK_SIZE);
+  /* CMAC starts with an all zero initialization vector */
+  _set(s->iv, 0, TC_AES_BLOCK_SIZE);
 
-    /* and the leftover buffer is empty */
-    _set(s->leftover, 0, TC_AES_BLOCK_SIZE);
-    s->leftover_offset = 0;
+  /* and the leftover buffer is empty */
+  _set(s->leftover, 0, TC_AES_BLOCK_SIZE);
+  s->leftover_offset = 0;
 
-    /* Set countdown to max number of calls allowed before re-keying: */
-    s->countdown = MAX_CALLS;
+  /* Set countdown to max number of calls allowed before re-keying: */
+  s->countdown = MAX_CALLS;
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_cmac_update(TCCmacState_t s, const uint8_t *data, size_t data_length)
-{
-    unsigned int i;
-
-    /* input sanity check: */
-    if (s == (TCCmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
-    if (data_length == 0) {
-        return TC_CRYPTO_SUCCESS;
-    }
-    if (data == (const uint8_t *)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_cmac_update(TCCmacState_t s, const uint8_t *data, size_t data_length) {
+  unsigned int i;
 
-    if (s->countdown == 0) {
-        return TC_CRYPTO_FAIL;
+  /* input sanity check: */
+  if (s == (TCCmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
+  if (data_length == 0) {
+    return TC_CRYPTO_SUCCESS;
+  }
+  if (data == (const uint8_t *)0) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  if (s->countdown == 0) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  s->countdown--;
+
+  if (s->leftover_offset > 0) {
+    /* last data added to s didn't end on a TC_AES_BLOCK_SIZE byte boundary */
+    size_t remaining_space = TC_AES_BLOCK_SIZE - s->leftover_offset;
+
+    if (data_length < remaining_space) {
+      /* still not enough data to encrypt this time either */
+      _copy(&s->leftover[s->leftover_offset], data_length, data, data_length);
+      s->leftover_offset += data_length;
+      return TC_CRYPTO_SUCCESS;
     }
+    /* leftover block is now full; encrypt it first */
+    _copy(&s->leftover[s->leftover_offset], remaining_space, data, remaining_space);
+    data_length -= remaining_space;
+    data += remaining_space;
+    s->leftover_offset = 0;
 
-    s->countdown--;
-
-    if (s->leftover_offset > 0) {
-        /* last data added to s didn't end on a TC_AES_BLOCK_SIZE byte boundary */
-        size_t remaining_space = TC_AES_BLOCK_SIZE - s->leftover_offset;
-
-        if (data_length < remaining_space) {
-            /* still not enough data to encrypt this time either */
-            _copy(&s->leftover[s->leftover_offset], data_length, data, data_length);
-            s->leftover_offset += data_length;
-            return TC_CRYPTO_SUCCESS;
-        }
-        /* leftover block is now full; encrypt it first */
-        _copy(&s->leftover[s->leftover_offset],
-              remaining_space,
-              data,
-              remaining_space);
-        data_length -= remaining_space;
-        data += remaining_space;
-        s->leftover_offset = 0;
-
-        for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
-            s->iv[i] ^= s->leftover[i];
-        }
-        tc_aes_encrypt(s->iv, s->iv, s->sched);
+    for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
+      s->iv[i] ^= s->leftover[i];
     }
+    tc_aes_encrypt(s->iv, s->iv, s->sched);
+  }
 
-    /* CBC encrypt each (except the last) of the data blocks */
-    while (data_length > TC_AES_BLOCK_SIZE) {
-        for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
-            s->iv[i] ^= data[i];
-        }
-        tc_aes_encrypt(s->iv, s->iv, s->sched);
-        data += TC_AES_BLOCK_SIZE;
-        data_length -= TC_AES_BLOCK_SIZE;
+  /* CBC encrypt each (except the last) of the data blocks */
+  while (data_length > TC_AES_BLOCK_SIZE) {
+    for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
+      s->iv[i] ^= data[i];
     }
+    tc_aes_encrypt(s->iv, s->iv, s->sched);
+    data += TC_AES_BLOCK_SIZE;
+    data_length -= TC_AES_BLOCK_SIZE;
+  }
 
-    if (data_length > 0) {
-        /* save leftover data for next time */
-        _copy(s->leftover, data_length, data, data_length);
-        s->leftover_offset = data_length;
-    }
+  if (data_length > 0) {
+    /* save leftover data for next time */
+    _copy(s->leftover, data_length, data, data_length);
+    s->leftover_offset = data_length;
+  }
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_cmac_final(uint8_t *tag, TCCmacState_t s)
-{
-    uint8_t *k;
-    unsigned int i;
+int tc_cmac_final(uint8_t *tag, TCCmacState_t s) {
+  uint8_t     *k;
+  unsigned int i;
 
-    /* input sanity check: */
-    if (tag == (uint8_t *)0 ||
-        s == (TCCmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+  /* input sanity check: */
+  if (tag == (uint8_t *)0 || s == (TCCmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    if (s->leftover_offset == TC_AES_BLOCK_SIZE) {
-        /* the last message block is a full-sized block */
-        k = (uint8_t *)s->K1;
-    } else {
-        /* the final message block is not a full-sized  block */
-        size_t remaining = TC_AES_BLOCK_SIZE - s->leftover_offset;
+  if (s->leftover_offset == TC_AES_BLOCK_SIZE) {
+    /* the last message block is a full-sized block */
+    k = (uint8_t *)s->K1;
+  } else {
+    /* the final message block is not a full-sized  block */
+    size_t remaining = TC_AES_BLOCK_SIZE - s->leftover_offset;
 
-        _set(&s->leftover[s->leftover_offset], 0, remaining);
-        s->leftover[s->leftover_offset] = TC_CMAC_PADDING;
-        k = (uint8_t *)s->K2;
-    }
-    for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
-        s->iv[i] ^= s->leftover[i] ^ k[i];
-    }
+    _set(&s->leftover[s->leftover_offset], 0, remaining);
+    s->leftover[s->leftover_offset] = TC_CMAC_PADDING;
+    k                               = (uint8_t *)s->K2;
+  }
+  for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) {
+    s->iv[i] ^= s->leftover[i] ^ k[i];
+  }
 
-    tc_aes_encrypt(tag, s->iv, s->sched);
+  tc_aes_encrypt(tag, s->iv, s->sched);
 
-    /* erasing state: */
-    tc_cmac_erase(s);
+  /* erasing state: */
+  tc_cmac_erase(s);
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_mode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_mode.c
index c9808338b..eaa14bc5e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_mode.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_mode.c
@@ -30,57 +30,48 @@
  *  POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "constants.h"
 #include "ctr_mode.h"
+#include "constants.h"
 #include "utils.h"
 
-int tc_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in,
-                unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched)
-{
-    uint8_t buffer[TC_AES_BLOCK_SIZE];
-    uint8_t nonce[TC_AES_BLOCK_SIZE];
-    unsigned int block_num;
-    unsigned int i;
+int tc_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched) {
+  uint8_t      buffer[TC_AES_BLOCK_SIZE];
+  uint8_t      nonce[TC_AES_BLOCK_SIZE];
+  unsigned int block_num;
+  unsigned int i;
 
-    /* input sanity check: */
-    if (out == (uint8_t *)0 ||
-        in == (uint8_t *)0 ||
-        ctr == (uint8_t *)0 ||
-        sched == (TCAesKeySched_t)0 ||
-        inlen == 0 ||
-        outlen == 0 ||
-        outlen != inlen) {
-        return TC_CRYPTO_FAIL;
-    }
+  /* input sanity check: */
+  if (out == (uint8_t *)0 || in == (uint8_t *)0 || ctr == (uint8_t *)0 || sched == (TCAesKeySched_t)0 || inlen == 0 || outlen == 0 || outlen != inlen) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* copy the ctr to the nonce */
-    (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce));
+  /* copy the ctr to the nonce */
+  (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce));
 
-    /* select the last 4 bytes of the nonce to be incremented */
-    block_num = (nonce[12] << 24) | (nonce[13] << 16) |
-                (nonce[14] << 8) | (nonce[15]);
-    for (i = 0; i < inlen; ++i) {
-        if ((i % (TC_AES_BLOCK_SIZE)) == 0) {
-            /* encrypt data using the current nonce */
-            if (tc_aes_encrypt(buffer, nonce, sched)) {
-                block_num++;
-                nonce[12] = (uint8_t)(block_num >> 24);
-                nonce[13] = (uint8_t)(block_num >> 16);
-                nonce[14] = (uint8_t)(block_num >> 8);
-                nonce[15] = (uint8_t)(block_num);
-            } else {
-                return TC_CRYPTO_FAIL;
-            }
-        }
-        /* update the output */
-        *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++;
+  /* select the last 4 bytes of the nonce to be incremented */
+  block_num = (nonce[12] << 24) | (nonce[13] << 16) | (nonce[14] << 8) | (nonce[15]);
+  for (i = 0; i < inlen; ++i) {
+    if ((i % (TC_AES_BLOCK_SIZE)) == 0) {
+      /* encrypt data using the current nonce */
+      if (tc_aes_encrypt(buffer, nonce, sched)) {
+        block_num++;
+        nonce[12] = (uint8_t)(block_num >> 24);
+        nonce[13] = (uint8_t)(block_num >> 16);
+        nonce[14] = (uint8_t)(block_num >> 8);
+        nonce[15] = (uint8_t)(block_num);
+      } else {
+        return TC_CRYPTO_FAIL;
+      }
     }
+    /* update the output */
+    *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++;
+  }
 
-    /* update the counter */
-    ctr[12] = nonce[12];
-    ctr[13] = nonce[13];
-    ctr[14] = nonce[14];
-    ctr[15] = nonce[15];
+  /* update the counter */
+  ctr[12] = nonce[12];
+  ctr[13] = nonce[13];
+  ctr[14] = nonce[14];
+  ctr[15] = nonce[15];
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_prng.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_prng.c
index d3410bc57..e53f550bf 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_prng.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ctr_prng.c
@@ -28,8 +28,8 @@
  */
 
 #include "ctr_prng.h"
-#include "utils.h"
 #include "constants.h"
+#include "utils.h"
 #include 
 
 /*
@@ -50,16 +50,15 @@
  *  @param arr IN/OUT -- array to be incremented
  *  @param len IN -- size of arr in bytes
  */
-static void arrInc(uint8_t arr[], unsigned int len)
-{
-    unsigned int i;
-    if (0 != arr) {
-        for (i = len; i > 0U; i--) {
-            if (++arr[i - 1] != 0U) {
-                break;
-            }
-        }
+static void arrInc(uint8_t arr[], unsigned int len) {
+  unsigned int i;
+  if (0 != arr) {
+    for (i = len; i > 0U; i--) {
+      if (++arr[i - 1] != 0U) {
+        break;
+      }
     }
+  }
 }
 
 /**
@@ -71,209 +70,192 @@ static void arrInc(uint8_t arr[], unsigned int len)
  *  @param ctx IN/OUT -- CTR PRNG state
  *  @param providedData IN -- data used when updating the internal state
  */
-static void tc_ctr_prng_update(TCCtrPrng_t *const ctx, uint8_t const *const providedData)
-{
-    if (0 != ctx) {
-        /* 10.2.1.2 step 1 */
-        uint8_t temp[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
-        unsigned int len = 0U;
-
-        /* 10.2.1.2 step 2 */
-        while (len < sizeof temp) {
-            unsigned int blocklen = sizeof(temp) - len;
-            uint8_t output_block[TC_AES_BLOCK_SIZE];
-
-            /* 10.2.1.2 step 2.1 */
-            arrInc(ctx->V, sizeof ctx->V);
-
-            /* 10.2.1.2 step 2.2 */
-            if (blocklen > TC_AES_BLOCK_SIZE) {
-                blocklen = TC_AES_BLOCK_SIZE;
-            }
-            (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key);
-
-            /* 10.2.1.2 step 2.3/step 3 */
-            memcpy(&(temp[len]), output_block, blocklen);
-
-            len += blocklen;
-        }
+static void tc_ctr_prng_update(TCCtrPrng_t *const ctx, uint8_t const *const providedData) {
+  if (0 != ctx) {
+    /* 10.2.1.2 step 1 */
+    uint8_t      temp[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
+    unsigned int len = 0U;
+
+    /* 10.2.1.2 step 2 */
+    while (len < sizeof temp) {
+      unsigned int blocklen = sizeof(temp) - len;
+      uint8_t      output_block[TC_AES_BLOCK_SIZE];
+
+      /* 10.2.1.2 step 2.1 */
+      arrInc(ctx->V, sizeof ctx->V);
+
+      /* 10.2.1.2 step 2.2 */
+      if (blocklen > TC_AES_BLOCK_SIZE) {
+        blocklen = TC_AES_BLOCK_SIZE;
+      }
+      (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key);
+
+      /* 10.2.1.2 step 2.3/step 3 */
+      memcpy(&(temp[len]), output_block, blocklen);
+
+      len += blocklen;
+    }
 
-        /* 10.2.1.2 step 4 */
-        if (0 != providedData) {
-            unsigned int i;
-            for (i = 0U; i < sizeof temp; i++) {
-                temp[i] ^= providedData[i];
-            }
-        }
+    /* 10.2.1.2 step 4 */
+    if (0 != providedData) {
+      unsigned int i;
+      for (i = 0U; i < sizeof temp; i++) {
+        temp[i] ^= providedData[i];
+      }
+    }
 
-        /* 10.2.1.2 step 5 */
-        (void)tc_aes128_set_encrypt_key(&ctx->key, temp);
+    /* 10.2.1.2 step 5 */
+    (void)tc_aes128_set_encrypt_key(&ctx->key, temp);
 
-        /* 10.2.1.2 step 6 */
-        memcpy(ctx->V, &(temp[TC_AES_KEY_SIZE]), TC_AES_BLOCK_SIZE);
-    }
+    /* 10.2.1.2 step 6 */
+    memcpy(ctx->V, &(temp[TC_AES_KEY_SIZE]), TC_AES_BLOCK_SIZE);
+  }
 }
 
-int tc_ctr_prng_init(TCCtrPrng_t *const ctx,
-                     uint8_t const *const entropy,
-                     unsigned int entropyLen,
-                     uint8_t const *const personalization,
-                     unsigned int pLen)
-{
-    int result = TC_CRYPTO_FAIL;
-    unsigned int i;
-    uint8_t personalization_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = { 0U };
-    uint8_t seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
-    uint8_t zeroArr[TC_AES_BLOCK_SIZE] = { 0U };
-
-    if (0 != personalization) {
-        /* 10.2.1.3.1 step 1 */
-        unsigned int len = pLen;
-        if (len > sizeof personalization_buf) {
-            len = sizeof personalization_buf;
-        }
+int tc_ctr_prng_init(TCCtrPrng_t *const ctx, uint8_t const *const entropy, unsigned int entropyLen, uint8_t const *const personalization, unsigned int pLen) {
+  int          result = TC_CRYPTO_FAIL;
+  unsigned int i;
+  uint8_t      personalization_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U};
+  uint8_t      seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
+  uint8_t      zeroArr[TC_AES_BLOCK_SIZE] = {0U};
+
+  if (0 != personalization) {
+    /* 10.2.1.3.1 step 1 */
+    unsigned int len = pLen;
+    if (len > sizeof personalization_buf) {
+      len = sizeof personalization_buf;
+    }
 
-        /* 10.2.1.3.1 step 2 */
-        memcpy(personalization_buf, personalization, len);
+    /* 10.2.1.3.1 step 2 */
+    memcpy(personalization_buf, personalization, len);
+  }
+
+  if ((0 != ctx) && (0 != entropy) && (entropyLen >= sizeof seed_material)) {
+    /* 10.2.1.3.1 step 3 */
+    memcpy(seed_material, entropy, sizeof seed_material);
+    for (i = 0U; i < sizeof seed_material; i++) {
+      seed_material[i] ^= personalization_buf[i];
     }
 
-    if ((0 != ctx) && (0 != entropy) && (entropyLen >= sizeof seed_material)) {
-        /* 10.2.1.3.1 step 3 */
-        memcpy(seed_material, entropy, sizeof seed_material);
-        for (i = 0U; i < sizeof seed_material; i++) {
-            seed_material[i] ^= personalization_buf[i];
-        }
+    /* 10.2.1.3.1 step 4 */
+    (void)tc_aes128_set_encrypt_key(&ctx->key, zeroArr);
 
-        /* 10.2.1.3.1 step 4 */
-        (void)tc_aes128_set_encrypt_key(&ctx->key, zeroArr);
+    /* 10.2.1.3.1 step 5 */
+    memset(ctx->V, 0x00, sizeof ctx->V);
 
-        /* 10.2.1.3.1 step 5 */
-        memset(ctx->V, 0x00, sizeof ctx->V);
+    /* 10.2.1.3.1 step 6 */
+    tc_ctr_prng_update(ctx, seed_material);
 
-        /* 10.2.1.3.1 step 6 */
-        tc_ctr_prng_update(ctx, seed_material);
+    /* 10.2.1.3.1 step 7 */
+    ctx->reseedCount = 1U;
+
+    result = TC_CRYPTO_SUCCESS;
+  }
+  return result;
+}
+
+int tc_ctr_prng_reseed(TCCtrPrng_t *const ctx, uint8_t const *const entropy, unsigned int entropyLen, uint8_t const *const additional_input, unsigned int additionallen) {
+  unsigned int i;
+  int          result                                                    = TC_CRYPTO_FAIL;
+  uint8_t      additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U};
+  uint8_t      seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
+
+  if (0 != additional_input) {
+    /* 10.2.1.4.1 step 1 */
+    unsigned int len = additionallen;
+    if (len > sizeof additional_input_buf) {
+      len = sizeof additional_input_buf;
+    }
 
-        /* 10.2.1.3.1 step 7 */
-        ctx->reseedCount = 1U;
+    /* 10.2.1.4.1 step 2 */
+    memcpy(additional_input_buf, additional_input, len);
+  }
 
-        result = TC_CRYPTO_SUCCESS;
+  unsigned int seedlen = (unsigned int)TC_AES_KEY_SIZE + (unsigned int)TC_AES_BLOCK_SIZE;
+  if ((0 != ctx) && (entropyLen >= seedlen)) {
+    /* 10.2.1.4.1 step 3 */
+    memcpy(seed_material, entropy, sizeof seed_material);
+    for (i = 0U; i < sizeof seed_material; i++) {
+      seed_material[i] ^= additional_input_buf[i];
     }
-    return result;
+
+    /* 10.2.1.4.1 step 4 */
+    tc_ctr_prng_update(ctx, seed_material);
+
+    /* 10.2.1.4.1 step 5 */
+    ctx->reseedCount = 1U;
+
+    result = TC_CRYPTO_SUCCESS;
+  }
+  return result;
 }
 
-int tc_ctr_prng_reseed(TCCtrPrng_t *const ctx,
-                       uint8_t const *const entropy,
-                       unsigned int entropyLen,
-                       uint8_t const *const additional_input,
-                       unsigned int additionallen)
-{
-    unsigned int i;
-    int result = TC_CRYPTO_FAIL;
-    uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = { 0U };
-    uint8_t seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE];
-
-    if (0 != additional_input) {
-        /* 10.2.1.4.1 step 1 */
+int tc_ctr_prng_generate(TCCtrPrng_t *const ctx, uint8_t const *const additional_input, unsigned int additionallen, uint8_t *const out, unsigned int outlen) {
+  /* 2^48 - see section 10.2.1 */
+  static const uint64_t MAX_REQS_BEFORE_RESEED = 0x1000000000000ULL;
+
+  /* 2^19 bits - see section 10.2.1 */
+  static const unsigned int MAX_BYTES_PER_REQ = 65536U;
+
+  unsigned int result = TC_CRYPTO_FAIL;
+
+  if ((0 != ctx) && (0 != out) && (outlen < MAX_BYTES_PER_REQ)) {
+    /* 10.2.1.5.1 step 1 */
+    if (ctx->reseedCount > MAX_REQS_BEFORE_RESEED) {
+      result = TC_CTR_PRNG_RESEED_REQ;
+    } else {
+      uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U};
+      if (0 != additional_input) {
+        /* 10.2.1.5.1 step 2  */
         unsigned int len = additionallen;
         if (len > sizeof additional_input_buf) {
-            len = sizeof additional_input_buf;
+          len = sizeof additional_input_buf;
         }
-
-        /* 10.2.1.4.1 step 2 */
         memcpy(additional_input_buf, additional_input, len);
-    }
+        tc_ctr_prng_update(ctx, additional_input_buf);
+      }
 
-    unsigned int seedlen = (unsigned int)TC_AES_KEY_SIZE + (unsigned int)TC_AES_BLOCK_SIZE;
-    if ((0 != ctx) && (entropyLen >= seedlen)) {
-        /* 10.2.1.4.1 step 3 */
-        memcpy(seed_material, entropy, sizeof seed_material);
-        for (i = 0U; i < sizeof seed_material; i++) {
-            seed_material[i] ^= additional_input_buf[i];
-        }
+      /* 10.2.1.5.1 step 3 - implicit */
 
-        /* 10.2.1.4.1 step 4 */
-        tc_ctr_prng_update(ctx, seed_material);
+      /* 10.2.1.5.1 step 4 */
+      unsigned int len = 0U;
+      while (len < outlen) {
+        unsigned int blocklen = outlen - len;
+        uint8_t      output_block[TC_AES_BLOCK_SIZE];
 
-        /* 10.2.1.4.1 step 5 */
-        ctx->reseedCount = 1U;
+        /* 10.2.1.5.1 step 4.1 */
+        arrInc(ctx->V, sizeof ctx->V);
 
-        result = TC_CRYPTO_SUCCESS;
-    }
-    return result;
-}
+        /* 10.2.1.5.1 step 4.2 */
+        (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key);
 
-int tc_ctr_prng_generate(TCCtrPrng_t *const ctx,
-                         uint8_t const *const additional_input,
-                         unsigned int additionallen,
-                         uint8_t *const out,
-                         unsigned int outlen)
-{
-    /* 2^48 - see section 10.2.1 */
-    static const uint64_t MAX_REQS_BEFORE_RESEED = 0x1000000000000ULL;
-
-    /* 2^19 bits - see section 10.2.1 */
-    static const unsigned int MAX_BYTES_PER_REQ = 65536U;
-
-    unsigned int result = TC_CRYPTO_FAIL;
-
-    if ((0 != ctx) && (0 != out) && (outlen < MAX_BYTES_PER_REQ)) {
-        /* 10.2.1.5.1 step 1 */
-        if (ctx->reseedCount > MAX_REQS_BEFORE_RESEED) {
-            result = TC_CTR_PRNG_RESEED_REQ;
-        } else {
-            uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = { 0U };
-            if (0 != additional_input) {
-                /* 10.2.1.5.1 step 2  */
-                unsigned int len = additionallen;
-                if (len > sizeof additional_input_buf) {
-                    len = sizeof additional_input_buf;
-                }
-                memcpy(additional_input_buf, additional_input, len);
-                tc_ctr_prng_update(ctx, additional_input_buf);
-            }
-
-            /* 10.2.1.5.1 step 3 - implicit */
-
-            /* 10.2.1.5.1 step 4 */
-            unsigned int len = 0U;
-            while (len < outlen) {
-                unsigned int blocklen = outlen - len;
-                uint8_t output_block[TC_AES_BLOCK_SIZE];
-
-                /* 10.2.1.5.1 step 4.1 */
-                arrInc(ctx->V, sizeof ctx->V);
-
-                /* 10.2.1.5.1 step 4.2 */
-                (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key);
-
-                /* 10.2.1.5.1 step 4.3/step 5 */
-                if (blocklen > TC_AES_BLOCK_SIZE) {
-                    blocklen = TC_AES_BLOCK_SIZE;
-                }
-                memcpy(&(out[len]), output_block, blocklen);
-
-                len += blocklen;
-            }
-
-            /* 10.2.1.5.1 step 6 */
-            tc_ctr_prng_update(ctx, additional_input_buf);
-
-            /* 10.2.1.5.1 step 7 */
-            ctx->reseedCount++;
-
-            /* 10.2.1.5.1 step 8 */
-            result = TC_CRYPTO_SUCCESS;
+        /* 10.2.1.5.1 step 4.3/step 5 */
+        if (blocklen > TC_AES_BLOCK_SIZE) {
+          blocklen = TC_AES_BLOCK_SIZE;
         }
+        memcpy(&(out[len]), output_block, blocklen);
+
+        len += blocklen;
+      }
+
+      /* 10.2.1.5.1 step 6 */
+      tc_ctr_prng_update(ctx, additional_input_buf);
+
+      /* 10.2.1.5.1 step 7 */
+      ctx->reseedCount++;
+
+      /* 10.2.1.5.1 step 8 */
+      result = TC_CRYPTO_SUCCESS;
     }
+  }
 
-    return result;
+  return result;
 }
 
-void tc_ctr_prng_uninstantiate(TCCtrPrng_t *const ctx)
-{
-    if (0 != ctx) {
-        memset(ctx->key.words, 0x00, sizeof ctx->key.words);
-        memset(ctx->V, 0x00, sizeof ctx->V);
-        ctx->reseedCount = 0U;
-    }
+void tc_ctr_prng_uninstantiate(TCCtrPrng_t *const ctx) {
+  if (0 != ctx) {
+    memset(ctx->key.words, 0x00, sizeof ctx->key.words);
+    memset(ctx->V, 0x00, sizeof ctx->V);
+    ctx->reseedCount = 0U;
+  }
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c
index eb3fa2238..c7b86bce5 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc.c
@@ -53,6 +53,7 @@
  */
 
 #include "ecc.h"
+#include "../include/tinycrypt/ecc.h"
 #include "ecc_platform_specific.h"
 #include 
 
@@ -64,860 +65,734 @@ static uECC_RNG_Function g_rng_function = &default_CSPRNG;
 static uECC_RNG_Function g_rng_function = 0;
 #endif
 
-void uECC_set_rng(uECC_RNG_Function rng_function)
-{
-    g_rng_function = rng_function;
-}
+void uECC_set_rng(uECC_RNG_Function rng_function) { g_rng_function = rng_function; }
 
-uECC_RNG_Function uECC_get_rng(void)
-{
-    return g_rng_function;
-}
+uECC_RNG_Function uECC_get_rng(void) { return g_rng_function; }
 
-int uECC_curve_private_key_size(uECC_Curve curve)
-{
-    return BITS_TO_BYTES(curve->num_n_bits);
-}
+int uECC_curve_private_key_size(uECC_Curve curve) { return BITS_TO_BYTES(curve->num_n_bits); }
 
-int uECC_curve_public_key_size(uECC_Curve curve)
-{
-    return 2 * curve->num_bytes;
-}
+int uECC_curve_public_key_size(uECC_Curve curve) { return 2 * curve->num_bytes; }
 
-void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words)
-{
-    wordcount_t i;
-    for (i = 0; i < num_words; ++i) {
-        vli[i] = 0;
-    }
+void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words) {
+  wordcount_t i;
+  for (i = 0; i < num_words; ++i) {
+    vli[i] = 0;
+  }
 }
 
-uECC_word_t uECC_vli_isZero(const uECC_word_t *vli, wordcount_t num_words)
-{
-    uECC_word_t bits = 0;
-    wordcount_t i;
-    for (i = 0; i < num_words; ++i) {
-        bits |= vli[i];
-    }
-    return (bits == 0);
+uECC_word_t uECC_vli_isZero(const uECC_word_t *vli, wordcount_t num_words) {
+  uECC_word_t bits = 0;
+  wordcount_t i;
+  for (i = 0; i < num_words; ++i) {
+    bits |= vli[i];
+  }
+  return (bits == 0);
 }
 
-uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit)
-{
-    return (vli[bit >> uECC_WORD_BITS_SHIFT] &
-            ((uECC_word_t)1 << (bit & uECC_WORD_BITS_MASK)));
-}
+uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit) { return (vli[bit >> uECC_WORD_BITS_SHIFT] & ((uECC_word_t)1 << (bit & uECC_WORD_BITS_MASK))); }
 
 /* Counts the number of words in vli. */
-static wordcount_t vli_numDigits(const uECC_word_t *vli,
-                                 const wordcount_t max_words)
-{
-    wordcount_t i;
-    /* Search from the end until we find a non-zero digit. We do it in reverse
-	 * because we expect that most digits will be nonzero. */
-    for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
-    }
+static wordcount_t vli_numDigits(const uECC_word_t *vli, const wordcount_t max_words) {
+  wordcount_t i;
+  /* Search from the end until we find a non-zero digit. We do it in reverse
+   * because we expect that most digits will be nonzero. */
+  for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
+  }
 
-    return (i + 1);
+  return (i + 1);
 }
 
-bitcount_t uECC_vli_numBits(const uECC_word_t *vli,
-                            const wordcount_t max_words)
-{
-    uECC_word_t i;
-    uECC_word_t digit;
+bitcount_t uECC_vli_numBits(const uECC_word_t *vli, const wordcount_t max_words) {
+  uECC_word_t i;
+  uECC_word_t digit;
 
-    wordcount_t num_digits = vli_numDigits(vli, max_words);
-    if (num_digits == 0) {
-        return 0;
-    }
+  wordcount_t num_digits = vli_numDigits(vli, max_words);
+  if (num_digits == 0) {
+    return 0;
+  }
 
-    digit = vli[num_digits - 1];
-    for (i = 0; digit; ++i) {
-        digit >>= 1;
-    }
+  digit = vli[num_digits - 1];
+  for (i = 0; digit; ++i) {
+    digit >>= 1;
+  }
 
-    return (((bitcount_t)(num_digits - 1) << uECC_WORD_BITS_SHIFT) + i);
+  return (((bitcount_t)(num_digits - 1) << uECC_WORD_BITS_SHIFT) + i);
 }
 
-void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src,
-                  wordcount_t num_words)
-{
-    wordcount_t i;
+void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src, wordcount_t num_words) {
+  wordcount_t i;
 
-    for (i = 0; i < num_words; ++i) {
-        dest[i] = src[i];
-    }
+  for (i = 0; i < num_words; ++i) {
+    dest[i] = src[i];
+  }
 }
 
-cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left,
-                                const uECC_word_t *right,
-                                wordcount_t num_words)
-{
-    wordcount_t i;
+cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  wordcount_t i;
 
-    for (i = num_words - 1; i >= 0; --i) {
-        if (left[i] > right[i]) {
-            return 1;
-        } else if (left[i] < right[i]) {
-            return -1;
-        }
+  for (i = num_words - 1; i >= 0; --i) {
+    if (left[i] > right[i]) {
+      return 1;
+    } else if (left[i] < right[i]) {
+      return -1;
     }
-    return 0;
+  }
+  return 0;
 }
 
-uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right,
-                           wordcount_t num_words)
-{
-    uECC_word_t diff = 0;
-    wordcount_t i;
+uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  uECC_word_t diff = 0;
+  wordcount_t i;
 
-    for (i = num_words - 1; i >= 0; --i) {
-        diff |= (left[i] ^ right[i]);
-    }
-    return !(diff == 0);
+  for (i = num_words - 1; i >= 0; --i) {
+    diff |= (left[i] ^ right[i]);
+  }
+  return !(diff == 0);
 }
 
-uECC_word_t cond_set(uECC_word_t p_true, uECC_word_t p_false, unsigned int cond)
-{
-    return (p_true * (cond)) | (p_false * (!cond));
-}
+uECC_word_t cond_set(uECC_word_t p_true, uECC_word_t p_false, unsigned int cond) { return (p_true * (cond)) | (p_false * (!cond)); }
 
 /* Computes result = left - right, returning borrow, in constant time.
  * Can modify in place. */
-uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left,
-                         const uECC_word_t *right, wordcount_t num_words)
-{
-    uECC_word_t borrow = 0;
-    wordcount_t i;
-    for (i = 0; i < num_words; ++i) {
-        uECC_word_t diff = left[i] - right[i] - borrow;
-        uECC_word_t val = (diff > left[i]);
-        borrow = cond_set(val, borrow, (diff != left[i]));
+uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  uECC_word_t borrow = 0;
+  wordcount_t i;
+  for (i = 0; i < num_words; ++i) {
+    uECC_word_t diff = left[i] - right[i] - borrow;
+    uECC_word_t val  = (diff > left[i]);
+    borrow           = cond_set(val, borrow, (diff != left[i]));
 
-        result[i] = diff;
-    }
-    return borrow;
+    result[i] = diff;
+  }
+  return borrow;
 }
 
 /* Computes result = left + right, returning carry, in constant time.
  * Can modify in place. */
-static uECC_word_t uECC_vli_add(uECC_word_t *result, const uECC_word_t *left,
-                                const uECC_word_t *right, wordcount_t num_words)
-{
-    uECC_word_t carry = 0;
-    wordcount_t i;
-    for (i = 0; i < num_words; ++i) {
-        uECC_word_t sum = left[i] + right[i] + carry;
-        uECC_word_t val = (sum < left[i]);
-        carry = cond_set(val, carry, (sum != left[i]));
-        result[i] = sum;
-    }
-    return carry;
+static uECC_word_t uECC_vli_add(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  uECC_word_t carry = 0;
+  wordcount_t i;
+  for (i = 0; i < num_words; ++i) {
+    uECC_word_t sum = left[i] + right[i] + carry;
+    uECC_word_t val = (sum < left[i]);
+    carry           = cond_set(val, carry, (sum != left[i]));
+    result[i]       = sum;
+  }
+  return carry;
 }
 
-cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right,
-                         wordcount_t num_words)
-{
-    uECC_word_t tmp[NUM_ECC_WORDS];
-    uECC_word_t neg = !!uECC_vli_sub(tmp, left, right, num_words);
-    uECC_word_t equal = uECC_vli_isZero(tmp, num_words);
-    return (!equal - 2 * neg);
+cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  uECC_word_t tmp[NUM_ECC_WORDS];
+  uECC_word_t neg   = !!uECC_vli_sub(tmp, left, right, num_words);
+  uECC_word_t equal = uECC_vli_isZero(tmp, num_words);
+  return (!equal - 2 * neg);
 }
 
 /* Computes vli = vli >> 1. */
-static void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words)
-{
-    uECC_word_t *end = vli;
-    uECC_word_t carry = 0;
-
-    vli += num_words;
-    while (vli-- > end) {
-        uECC_word_t temp = *vli;
-        *vli = (temp >> 1) | carry;
-        carry = temp << (uECC_WORD_BITS - 1);
-    }
-}
+static void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words) {
+  uECC_word_t *end   = vli;
+  uECC_word_t  carry = 0;
 
-static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0,
-                   uECC_word_t *r1, uECC_word_t *r2)
-{
-    uECC_dword_t p = (uECC_dword_t)a * b;
-    uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0;
-    r01 += p;
-    *r2 += (r01 < p);
-    *r1 = r01 >> uECC_WORD_BITS;
-    *r0 = (uECC_word_t)r01;
+  vli += num_words;
+  while (vli-- > end) {
+    uECC_word_t temp = *vli;
+    *vli             = (temp >> 1) | carry;
+    carry            = temp << (uECC_WORD_BITS - 1);
+  }
 }
 
-/* Computes result = left * right. Result must be 2 * num_words long. */
-static void uECC_vli_mult(uECC_word_t *result, const uECC_word_t *left,
-                          const uECC_word_t *right, wordcount_t num_words)
-{
-    uECC_word_t r0 = 0;
-    uECC_word_t r1 = 0;
-    uECC_word_t r2 = 0;
-    wordcount_t i, k;
-
-    /* Compute each digit of result in sequence, maintaining the carries. */
-    for (k = 0; k < num_words; ++k) {
-        for (i = 0; i <= k; ++i) {
-            muladd(left[i], right[k - i], &r0, &r1, &r2);
-        }
-
-        result[k] = r0;
-        r0 = r1;
-        r1 = r2;
-        r2 = 0;
-    }
-
-    for (k = num_words; k < num_words * 2 - 1; ++k) {
-        for (i = (k + 1) - num_words; i < num_words; ++i) {
-            muladd(left[i], right[k - i], &r0, &r1, &r2);
-        }
-        result[k] = r0;
-        r0 = r1;
-        r1 = r2;
-        r2 = 0;
-    }
-    result[num_words * 2 - 1] = r0;
-}
-
-void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left,
-                     const uECC_word_t *right, const uECC_word_t *mod,
-                     wordcount_t num_words)
-{
-    uECC_word_t carry = uECC_vli_add(result, left, right, num_words);
-    if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) {
-        /* result > mod (result = mod + remainder), so subtract mod to get
-	 * remainder. */
-        uECC_vli_sub(result, result, mod, num_words);
-    }
+static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0, uECC_word_t *r1, uECC_word_t *r2) {
+  uECC_dword_t p   = (uECC_dword_t)a * b;
+  uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0;
+  r01 += p;
+  *r2 += (r01 < p);
+  *r1 = r01 >> uECC_WORD_BITS;
+  *r0 = (uECC_word_t)r01;
 }
 
-void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left,
-                     const uECC_word_t *right, const uECC_word_t *mod,
-                     wordcount_t num_words)
-{
-    uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words);
-    if (l_borrow) {
-        /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
-		 * we can get the correct result from result + mod (with overflow). */
-        uECC_vli_add(result, result, mod, num_words);
-    }
+/* Computes result = left * right. Result must be 2 * num_words long. */
+static void uECC_vli_mult(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, wordcount_t num_words) {
+  uECC_word_t r0 = 0;
+  uECC_word_t r1 = 0;
+  uECC_word_t r2 = 0;
+  wordcount_t i, k;
+
+  /* Compute each digit of result in sequence, maintaining the carries. */
+  for (k = 0; k < num_words; ++k) {
+    for (i = 0; i <= k; ++i) {
+      muladd(left[i], right[k - i], &r0, &r1, &r2);
+    }
+
+    result[k] = r0;
+    r0        = r1;
+    r1        = r2;
+    r2        = 0;
+  }
+
+  for (k = num_words; k < num_words * 2 - 1; ++k) {
+    for (i = (k + 1) - num_words; i < num_words; ++i) {
+      muladd(left[i], right[k - i], &r0, &r1, &r2);
+    }
+    result[k] = r0;
+    r0        = r1;
+    r1        = r2;
+    r2        = 0;
+  }
+  result[num_words * 2 - 1] = r0;
+}
+
+void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t carry = uECC_vli_add(result, left, right, num_words);
+  if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) {
+    /* result > mod (result = mod + remainder), so subtract mod to get
+     * remainder. */
+    uECC_vli_sub(result, result, mod, num_words);
+  }
+}
+
+void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words);
+  if (l_borrow) {
+    /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
+     * we can get the correct result from result + mod (with overflow). */
+    uECC_vli_add(result, result, mod, num_words);
+  }
 }
 
 /* Computes result = product % mod, where product is 2N words long. */
 /* Currently only designed to work for curve_p or curve_n. */
-void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product,
-                   const uECC_word_t *mod, wordcount_t num_words)
-{
-    uECC_word_t mod_multiple[2 * NUM_ECC_WORDS];
-    uECC_word_t tmp[2 * NUM_ECC_WORDS];
-    uECC_word_t *v[2] = { tmp, product };
-    uECC_word_t index;
-
-    /* Shift mod so its highest set bit is at the maximum position. */
-    bitcount_t shift = (num_words * 2 * uECC_WORD_BITS) -
-                       uECC_vli_numBits(mod, num_words);
-    wordcount_t word_shift = shift / uECC_WORD_BITS;
-    wordcount_t bit_shift = shift % uECC_WORD_BITS;
-    uECC_word_t carry = 0;
-    uECC_vli_clear(mod_multiple, word_shift);
-    if (bit_shift > 0) {
-        for (index = 0; index < (uECC_word_t)num_words; ++index) {
-            mod_multiple[word_shift + index] = (mod[index] << bit_shift) | carry;
-            carry = mod[index] >> (uECC_WORD_BITS - bit_shift);
-        }
-    } else {
-        uECC_vli_set(mod_multiple + word_shift, mod, num_words);
-    }
-
-    for (index = 1; shift >= 0; --shift) {
-        uECC_word_t borrow = 0;
-        wordcount_t i;
-        for (i = 0; i < num_words * 2; ++i) {
-            uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow;
-            if (diff != v[index][i]) {
-                borrow = (diff > v[index][i]);
-            }
-            v[1 - index][i] = diff;
-        }
-        /* Swap the index if there was no borrow */
-        index = !(index ^ borrow);
-        uECC_vli_rshift1(mod_multiple, num_words);
-        mod_multiple[num_words - 1] |= mod_multiple[num_words] << (uECC_WORD_BITS - 1);
-        uECC_vli_rshift1(mod_multiple + num_words, num_words);
+void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t  mod_multiple[2 * NUM_ECC_WORDS];
+  uECC_word_t  tmp[2 * NUM_ECC_WORDS];
+  uECC_word_t *v[2] = {tmp, product};
+  uECC_word_t  index;
+
+  /* Shift mod so its highest set bit is at the maximum position. */
+  bitcount_t  shift      = (num_words * 2 * uECC_WORD_BITS) - uECC_vli_numBits(mod, num_words);
+  wordcount_t word_shift = shift / uECC_WORD_BITS;
+  wordcount_t bit_shift  = shift % uECC_WORD_BITS;
+  uECC_word_t carry      = 0;
+  uECC_vli_clear(mod_multiple, word_shift);
+  if (bit_shift > 0) {
+    for (index = 0; index < (uECC_word_t)num_words; ++index) {
+      mod_multiple[word_shift + index] = (mod[index] << bit_shift) | carry;
+      carry                            = mod[index] >> (uECC_WORD_BITS - bit_shift);
+    }
+  } else {
+    uECC_vli_set(mod_multiple + word_shift, mod, num_words);
+  }
+
+  for (index = 1; shift >= 0; --shift) {
+    uECC_word_t borrow = 0;
+    wordcount_t i;
+    for (i = 0; i < num_words * 2; ++i) {
+      uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow;
+      if (diff != v[index][i]) {
+        borrow = (diff > v[index][i]);
+      }
+      v[1 - index][i] = diff;
     }
-    uECC_vli_set(result, v[index], num_words);
+    /* Swap the index if there was no borrow */
+    index = !(index ^ borrow);
+    uECC_vli_rshift1(mod_multiple, num_words);
+    mod_multiple[num_words - 1] |= mod_multiple[num_words] << (uECC_WORD_BITS - 1);
+    uECC_vli_rshift1(mod_multiple + num_words, num_words);
+  }
+  uECC_vli_set(result, v[index], num_words);
 }
 
-void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left,
-                      const uECC_word_t *right, const uECC_word_t *mod,
-                      wordcount_t num_words)
-{
-    uECC_word_t product[2 * NUM_ECC_WORDS];
-    uECC_vli_mult(product, left, right, num_words);
-    uECC_vli_mmod(result, product, mod, num_words);
+void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t product[2 * NUM_ECC_WORDS];
+  uECC_vli_mult(product, left, right, num_words);
+  uECC_vli_mmod(result, product, mod, num_words);
 }
 
-void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left,
-                           const uECC_word_t *right, uECC_Curve curve)
-{
-    uECC_word_t product[2 * NUM_ECC_WORDS];
-    uECC_vli_mult(product, left, right, curve->num_words);
+void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left, const uECC_word_t *right, uECC_Curve curve) {
+  uECC_word_t product[2 * NUM_ECC_WORDS];
+  uECC_vli_mult(product, left, right, curve->num_words);
 
-    curve->mmod_fast(result, product);
+  curve->mmod_fast(result, product);
 }
 
-static void uECC_vli_modSquare_fast(uECC_word_t *result,
-                                    const uECC_word_t *left,
-                                    uECC_Curve curve)
-{
-    uECC_vli_modMult_fast(result, left, left, curve);
-}
+static void uECC_vli_modSquare_fast(uECC_word_t *result, const uECC_word_t *left, uECC_Curve curve) { uECC_vli_modMult_fast(result, left, left, curve); }
 
 #define EVEN(vli) (!(vli[0] & 1))
 
-static void vli_modInv_update(uECC_word_t *uv,
-                              const uECC_word_t *mod,
-                              wordcount_t num_words)
-{
-    uECC_word_t carry = 0;
-
-    if (!EVEN(uv)) {
-        carry = uECC_vli_add(uv, uv, mod, num_words);
-    }
-    uECC_vli_rshift1(uv, num_words);
-    if (carry) {
-        uv[num_words - 1] |= HIGH_BIT_SET;
-    }
-}
-
-void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input,
-                     const uECC_word_t *mod, wordcount_t num_words)
-{
-    uECC_word_t a[NUM_ECC_WORDS], b[NUM_ECC_WORDS];
-    uECC_word_t u[NUM_ECC_WORDS], v[NUM_ECC_WORDS];
-    cmpresult_t cmpResult;
-
-    if (uECC_vli_isZero(input, num_words)) {
-        uECC_vli_clear(result, num_words);
-        return;
-    }
-
-    uECC_vli_set(a, input, num_words);
-    uECC_vli_set(b, mod, num_words);
-    uECC_vli_clear(u, num_words);
-    u[0] = 1;
-    uECC_vli_clear(v, num_words);
-    while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) {
-        if (EVEN(a)) {
-            uECC_vli_rshift1(a, num_words);
-            vli_modInv_update(u, mod, num_words);
-        } else if (EVEN(b)) {
-            uECC_vli_rshift1(b, num_words);
-            vli_modInv_update(v, mod, num_words);
-        } else if (cmpResult > 0) {
-            uECC_vli_sub(a, a, b, num_words);
-            uECC_vli_rshift1(a, num_words);
-            if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) {
-                uECC_vli_add(u, u, mod, num_words);
-            }
-            uECC_vli_sub(u, u, v, num_words);
-            vli_modInv_update(u, mod, num_words);
-        } else {
-            uECC_vli_sub(b, b, a, num_words);
-            uECC_vli_rshift1(b, num_words);
-            if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) {
-                uECC_vli_add(v, v, mod, num_words);
-            }
-            uECC_vli_sub(v, v, u, num_words);
-            vli_modInv_update(v, mod, num_words);
-        }
-    }
-    uECC_vli_set(result, u, num_words);
-}
-
-/* ------ Point operations ------ */
-
-void double_jacobian_default(uECC_word_t *X1, uECC_word_t *Y1,
-                             uECC_word_t *Z1, uECC_Curve curve)
-{
-    /* t1 = X, t2 = Y, t3 = Z */
-    uECC_word_t t4[NUM_ECC_WORDS];
-    uECC_word_t t5[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
-
-    if (uECC_vli_isZero(Z1, num_words)) {
-        return;
-    }
-
-    uECC_vli_modSquare_fast(t4, Y1, curve);   /* t4 = y1^2 */
-    uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
-    uECC_vli_modSquare_fast(t4, t4, curve);   /* t4 = y1^4 */
-    uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
-    uECC_vli_modSquare_fast(Z1, Z1, curve);   /* t3 = z1^2 */
-
-    uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
-    uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
-    uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
-    uECC_vli_modMult_fast(X1, X1, Z1, curve);         /* t1 = x1^2 - z1^4 */
-
-    uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */
-    uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */
-    if (uECC_vli_testBit(X1, 0)) {
-        uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words);
-        uECC_vli_rshift1(X1, num_words);
-        X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1);
-    } else {
-        uECC_vli_rshift1(X1, num_words);
-    }
-
-    /* t1 = 3/2*(x1^2 - z1^4) = B */
-    uECC_vli_modSquare_fast(Z1, X1, curve);           /* t3 = B^2 */
-    uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
-    uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
-    uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
-    uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = B * (A - x3) */
-    /* t4 = B * (A - x3) - y1^4 = y3: */
-    uECC_vli_modSub(t4, X1, t4, curve->p, num_words);
-
-    uECC_vli_set(X1, Z1, num_words);
-    uECC_vli_set(Z1, Y1, num_words);
-    uECC_vli_set(Y1, t4, num_words);
-}
-
-void x_side_default(uECC_word_t *result,
-                    const uECC_word_t *x,
-                    uECC_Curve curve)
-{
-    uECC_word_t _3[NUM_ECC_WORDS] = { 3 }; /* -a = 3 */
-    wordcount_t num_words = curve->num_words;
-
-    uECC_vli_modSquare_fast(result, x, curve);                /* r = x^2 */
-    uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
-    uECC_vli_modMult_fast(result, result, x, curve);          /* r = x^3 - 3x */
-    /* r = x^3 - 3x + b: */
-    uECC_vli_modAdd(result, result, curve->b, curve->p, num_words);
-}
-
-uECC_Curve uECC_secp256r1(void)
-{
-    return &curve_secp256r1;
-}
-
-void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int *product)
-{
-    unsigned int tmp[NUM_ECC_WORDS];
-    int carry;
-
-    /* t */
-    uECC_vli_set(result, product, NUM_ECC_WORDS);
-
-    /* s1 */
-    tmp[0] = tmp[1] = tmp[2] = 0;
-    tmp[3] = product[11];
-    tmp[4] = product[12];
-    tmp[5] = product[13];
-    tmp[6] = product[14];
-    tmp[7] = product[15];
-    carry = uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS);
-    carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
-
-    /* s2 */
-    tmp[3] = product[12];
-    tmp[4] = product[13];
-    tmp[5] = product[14];
-    tmp[6] = product[15];
-    tmp[7] = 0;
-    carry += uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS);
-    carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
-
-    /* s3 */
-    tmp[0] = product[8];
-    tmp[1] = product[9];
-    tmp[2] = product[10];
-    tmp[3] = tmp[4] = tmp[5] = 0;
-    tmp[6] = product[14];
-    tmp[7] = product[15];
-    carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
-
-    /* s4 */
-    tmp[0] = product[9];
-    tmp[1] = product[10];
-    tmp[2] = product[11];
-    tmp[3] = product[13];
-    tmp[4] = product[14];
-    tmp[5] = product[15];
-    tmp[6] = product[13];
-    tmp[7] = product[8];
-    carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
-
-    /* d1 */
-    tmp[0] = product[11];
-    tmp[1] = product[12];
-    tmp[2] = product[13];
-    tmp[3] = tmp[4] = tmp[5] = 0;
-    tmp[6] = product[8];
-    tmp[7] = product[10];
-    carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
-
-    /* d2 */
-    tmp[0] = product[12];
-    tmp[1] = product[13];
-    tmp[2] = product[14];
-    tmp[3] = product[15];
-    tmp[4] = tmp[5] = 0;
-    tmp[6] = product[9];
-    tmp[7] = product[11];
-    carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
-
-    /* d3 */
-    tmp[0] = product[13];
-    tmp[1] = product[14];
-    tmp[2] = product[15];
-    tmp[3] = product[8];
-    tmp[4] = product[9];
-    tmp[5] = product[10];
-    tmp[6] = 0;
-    tmp[7] = product[12];
-    carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
-
-    /* d4 */
-    tmp[0] = product[14];
-    tmp[1] = product[15];
-    tmp[2] = 0;
-    tmp[3] = product[9];
-    tmp[4] = product[10];
-    tmp[5] = product[11];
-    tmp[6] = 0;
-    tmp[7] = product[13];
-    carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
-
-    if (carry < 0) {
-        do {
-            carry += uECC_vli_add(result, result, curve_secp256r1.p, NUM_ECC_WORDS);
-        } while (carry < 0);
+static void vli_modInv_update(uECC_word_t *uv, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t carry = 0;
+
+  if (!EVEN(uv)) {
+    carry = uECC_vli_add(uv, uv, mod, num_words);
+  }
+  uECC_vli_rshift1(uv, num_words);
+  if (carry) {
+    uv[num_words - 1] |= HIGH_BIT_SET;
+  }
+}
+
+void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input, const uECC_word_t *mod, wordcount_t num_words) {
+  uECC_word_t a[NUM_ECC_WORDS], b[NUM_ECC_WORDS];
+  uECC_word_t u[NUM_ECC_WORDS], v[NUM_ECC_WORDS];
+  cmpresult_t cmpResult;
+
+  if (uECC_vli_isZero(input, num_words)) {
+    uECC_vli_clear(result, num_words);
+    return;
+  }
+
+  uECC_vli_set(a, input, num_words);
+  uECC_vli_set(b, mod, num_words);
+  uECC_vli_clear(u, num_words);
+  u[0] = 1;
+  uECC_vli_clear(v, num_words);
+  while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) {
+    if (EVEN(a)) {
+      uECC_vli_rshift1(a, num_words);
+      vli_modInv_update(u, mod, num_words);
+    } else if (EVEN(b)) {
+      uECC_vli_rshift1(b, num_words);
+      vli_modInv_update(v, mod, num_words);
+    } else if (cmpResult > 0) {
+      uECC_vli_sub(a, a, b, num_words);
+      uECC_vli_rshift1(a, num_words);
+      if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) {
+        uECC_vli_add(u, u, mod, num_words);
+      }
+      uECC_vli_sub(u, u, v, num_words);
+      vli_modInv_update(u, mod, num_words);
     } else {
-        while (carry ||
-               uECC_vli_cmp_unsafe(curve_secp256r1.p, result, NUM_ECC_WORDS) != 1) {
-            carry -= uECC_vli_sub(result, result, curve_secp256r1.p, NUM_ECC_WORDS);
-        }
+      uECC_vli_sub(b, b, a, num_words);
+      uECC_vli_rshift1(b, num_words);
+      if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) {
+        uECC_vli_add(v, v, mod, num_words);
+      }
+      uECC_vli_sub(v, v, u, num_words);
+      vli_modInv_update(v, mod, num_words);
     }
+  }
+  uECC_vli_set(result, u, num_words);
 }
 
-uECC_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve)
-{
-    return uECC_vli_isZero(point, curve->num_words * 2);
-}
-
-void apply_z(uECC_word_t *X1, uECC_word_t *Y1, const uECC_word_t *const Z,
-             uECC_Curve curve)
-{
-    uECC_word_t t1[NUM_ECC_WORDS];
+/* ------ Point operations ------ */
 
-    uECC_vli_modSquare_fast(t1, Z, curve);    /* z^2 */
-    uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
-    uECC_vli_modMult_fast(t1, t1, Z, curve);  /* z^3 */
-    uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
+void double_jacobian_default(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *Z1, uECC_Curve curve) {
+  /* t1 = X, t2 = Y, t3 = Z */
+  uECC_word_t t4[NUM_ECC_WORDS];
+  uECC_word_t t5[NUM_ECC_WORDS];
+  wordcount_t num_words = curve->num_words;
+
+  if (uECC_vli_isZero(Z1, num_words)) {
+    return;
+  }
+
+  uECC_vli_modSquare_fast(t4, Y1, curve);   /* t4 = y1^2 */
+  uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
+  uECC_vli_modSquare_fast(t4, t4, curve);   /* t4 = y1^4 */
+  uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
+  uECC_vli_modSquare_fast(Z1, Z1, curve);   /* t3 = z1^2 */
+
+  uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
+  uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
+  uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
+  uECC_vli_modMult_fast(X1, X1, Z1, curve);         /* t1 = x1^2 - z1^4 */
+
+  uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */
+  uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */
+  if (uECC_vli_testBit(X1, 0)) {
+    uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words);
+    uECC_vli_rshift1(X1, num_words);
+    X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1);
+  } else {
+    uECC_vli_rshift1(X1, num_words);
+  }
+
+  /* t1 = 3/2*(x1^2 - z1^4) = B */
+  uECC_vli_modSquare_fast(Z1, X1, curve);           /* t3 = B^2 */
+  uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
+  uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
+  uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
+  uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = B * (A - x3) */
+  /* t4 = B * (A - x3) - y1^4 = y3: */
+  uECC_vli_modSub(t4, X1, t4, curve->p, num_words);
+
+  uECC_vli_set(X1, Z1, num_words);
+  uECC_vli_set(Z1, Y1, num_words);
+  uECC_vli_set(Y1, t4, num_words);
+}
+
+void x_side_default(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve) {
+  uECC_word_t _3[NUM_ECC_WORDS] = {3}; /* -a = 3 */
+  wordcount_t num_words         = curve->num_words;
+
+  uECC_vli_modSquare_fast(result, x, curve);                /* r = x^2 */
+  uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
+  uECC_vli_modMult_fast(result, result, x, curve);          /* r = x^3 - 3x */
+  /* r = x^3 - 3x + b: */
+  uECC_vli_modAdd(result, result, curve->b, curve->p, num_words);
+}
+
+uECC_Curve uECC_secp256r1(void) { return &curve_secp256r1; }
+
+void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int *product) {
+  unsigned int tmp[NUM_ECC_WORDS];
+  int          carry;
+
+  /* t */
+  uECC_vli_set(result, product, NUM_ECC_WORDS);
+
+  /* s1 */
+  tmp[0] = tmp[1] = tmp[2] = 0;
+  tmp[3]                   = product[11];
+  tmp[4]                   = product[12];
+  tmp[5]                   = product[13];
+  tmp[6]                   = product[14];
+  tmp[7]                   = product[15];
+  carry                    = uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS);
+  carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+  /* s2 */
+  tmp[3] = product[12];
+  tmp[4] = product[13];
+  tmp[5] = product[14];
+  tmp[6] = product[15];
+  tmp[7] = 0;
+  carry += uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS);
+  carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+  /* s3 */
+  tmp[0] = product[8];
+  tmp[1] = product[9];
+  tmp[2] = product[10];
+  tmp[3] = tmp[4] = tmp[5] = 0;
+  tmp[6]                   = product[14];
+  tmp[7]                   = product[15];
+  carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+  /* s4 */
+  tmp[0] = product[9];
+  tmp[1] = product[10];
+  tmp[2] = product[11];
+  tmp[3] = product[13];
+  tmp[4] = product[14];
+  tmp[5] = product[15];
+  tmp[6] = product[13];
+  tmp[7] = product[8];
+  carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS);
+
+  /* d1 */
+  tmp[0] = product[11];
+  tmp[1] = product[12];
+  tmp[2] = product[13];
+  tmp[3] = tmp[4] = tmp[5] = 0;
+  tmp[6]                   = product[8];
+  tmp[7]                   = product[10];
+  carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+  /* d2 */
+  tmp[0] = product[12];
+  tmp[1] = product[13];
+  tmp[2] = product[14];
+  tmp[3] = product[15];
+  tmp[4] = tmp[5] = 0;
+  tmp[6]          = product[9];
+  tmp[7]          = product[11];
+  carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+  /* d3 */
+  tmp[0] = product[13];
+  tmp[1] = product[14];
+  tmp[2] = product[15];
+  tmp[3] = product[8];
+  tmp[4] = product[9];
+  tmp[5] = product[10];
+  tmp[6] = 0;
+  tmp[7] = product[12];
+  carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+  /* d4 */
+  tmp[0] = product[14];
+  tmp[1] = product[15];
+  tmp[2] = 0;
+  tmp[3] = product[9];
+  tmp[4] = product[10];
+  tmp[5] = product[11];
+  tmp[6] = 0;
+  tmp[7] = product[13];
+  carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS);
+
+  if (carry < 0) {
+    do {
+      carry += uECC_vli_add(result, result, curve_secp256r1.p, NUM_ECC_WORDS);
+    } while (carry < 0);
+  } else {
+    while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result, NUM_ECC_WORDS) != 1) {
+      carry -= uECC_vli_sub(result, result, curve_secp256r1.p, NUM_ECC_WORDS);
+    }
+  }
+}
+
+uECC_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve) { return uECC_vli_isZero(point, curve->num_words * 2); }
+
+void apply_z(uECC_word_t *X1, uECC_word_t *Y1, const uECC_word_t *const Z, uECC_Curve curve) {
+  uECC_word_t t1[NUM_ECC_WORDS];
+
+  uECC_vli_modSquare_fast(t1, Z, curve);    /* z^2 */
+  uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
+  uECC_vli_modMult_fast(t1, t1, Z, curve);  /* z^3 */
+  uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
 }
 
 /* P = (x1, y1) => 2P, (x2, y2) => P' */
-static void XYcZ_initial_double(uECC_word_t *X1, uECC_word_t *Y1,
-                                uECC_word_t *X2, uECC_word_t *Y2,
-                                const uECC_word_t *const initial_Z,
-                                uECC_Curve curve)
-{
-    uECC_word_t z[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
-    if (initial_Z) {
-        uECC_vli_set(z, initial_Z, num_words);
-    } else {
-        uECC_vli_clear(z, num_words);
-        z[0] = 1;
-    }
-
-    uECC_vli_set(X2, X1, num_words);
-    uECC_vli_set(Y2, Y1, num_words);
-
-    apply_z(X1, Y1, z, curve);
-    curve->double_jacobian(X1, Y1, z, curve);
-    apply_z(X2, Y2, z, curve);
-}
-
-void XYcZ_add(uECC_word_t *X1, uECC_word_t *Y1,
-              uECC_word_t *X2, uECC_word_t *Y2,
-              uECC_Curve curve)
-{
-    /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
-    uECC_word_t t5[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
-
-    uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
-    uECC_vli_modSquare_fast(t5, t5, curve);           /* t5 = (x2 - x1)^2 = A */
-    uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = x1*A = B */
-    uECC_vli_modMult_fast(X2, X2, t5, curve);         /* t3 = x2*A = C */
-    uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
-    uECC_vli_modSquare_fast(t5, Y2, curve);           /* t5 = (y2 - y1)^2 = D */
-
-    uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
-    uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
-    uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
-    uECC_vli_modMult_fast(Y1, Y1, X2, curve);         /* t2 = y1*(C - B) */
-    uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
-    uECC_vli_modMult_fast(Y2, Y2, X2, curve);         /* t4 = (y2 - y1)*(B - x3) */
-    uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
-
-    uECC_vli_set(X2, t5, num_words);
+static void XYcZ_initial_double(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2, uECC_word_t *Y2, const uECC_word_t *const initial_Z, uECC_Curve curve) {
+  uECC_word_t z[NUM_ECC_WORDS];
+  wordcount_t num_words = curve->num_words;
+  if (initial_Z) {
+    uECC_vli_set(z, initial_Z, num_words);
+  } else {
+    uECC_vli_clear(z, num_words);
+    z[0] = 1;
+  }
+
+  uECC_vli_set(X2, X1, num_words);
+  uECC_vli_set(Y2, Y1, num_words);
+
+  apply_z(X1, Y1, z, curve);
+  curve->double_jacobian(X1, Y1, z, curve);
+  apply_z(X2, Y2, z, curve);
+}
+
+void XYcZ_add(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2, uECC_word_t *Y2, uECC_Curve curve) {
+  /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
+  uECC_word_t t5[NUM_ECC_WORDS];
+  wordcount_t num_words = curve->num_words;
+
+  uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
+  uECC_vli_modSquare_fast(t5, t5, curve);           /* t5 = (x2 - x1)^2 = A */
+  uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = x1*A = B */
+  uECC_vli_modMult_fast(X2, X2, t5, curve);         /* t3 = x2*A = C */
+  uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
+  uECC_vli_modSquare_fast(t5, Y2, curve);           /* t5 = (y2 - y1)^2 = D */
+
+  uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
+  uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
+  uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
+  uECC_vli_modMult_fast(Y1, Y1, X2, curve);         /* t2 = y1*(C - B) */
+  uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
+  uECC_vli_modMult_fast(Y2, Y2, X2, curve);         /* t4 = (y2 - y1)*(B - x3) */
+  uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
+
+  uECC_vli_set(X2, t5, num_words);
 }
 
 /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
    Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
    or P => P - Q, Q => P + Q
  */
-static void XYcZ_addC(uECC_word_t *X1, uECC_word_t *Y1,
-                      uECC_word_t *X2, uECC_word_t *Y2,
-                      uECC_Curve curve)
-{
-    /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
-    uECC_word_t t5[NUM_ECC_WORDS];
-    uECC_word_t t6[NUM_ECC_WORDS];
-    uECC_word_t t7[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
-
-    uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
-    uECC_vli_modSquare_fast(t5, t5, curve);           /* t5 = (x2 - x1)^2 = A */
-    uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = x1*A = B */
-    uECC_vli_modMult_fast(X2, X2, t5, curve);         /* t3 = x2*A = C */
-    uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
-    uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
-
-    uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
-    uECC_vli_modMult_fast(Y1, Y1, t6, curve);         /* t2 = y1 * (C - B) = E */
-    uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
-    uECC_vli_modSquare_fast(X2, Y2, curve);           /* t3 = (y2 - y1)^2 = D */
-    uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */
-
-    uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
-    uECC_vli_modMult_fast(Y2, Y2, t7, curve);         /* t4 = (y2 - y1)*(B - x3) */
-    /* t4 = (y2 - y1)*(B - x3) - E = y3: */
-    uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words);
-
-    uECC_vli_modSquare_fast(t7, t5, curve);           /* t7 = (y2 + y1)^2 = F */
-    uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */
-    uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
-    uECC_vli_modMult_fast(t6, t6, t5, curve);         /* t6 = (y2+y1)*(x3' - B) */
-    /* t2 = (y2+y1)*(x3' - B) - E = y3': */
-    uECC_vli_modSub(Y1, t6, Y1, curve->p, num_words);
-
-    uECC_vli_set(X1, t7, num_words);
-}
-
-void EccPoint_mult(uECC_word_t *result, const uECC_word_t *point,
-                   const uECC_word_t *scalar,
-                   const uECC_word_t *initial_Z,
-                   bitcount_t num_bits, uECC_Curve curve)
-{
-    /* R0 and R1 */
-    uECC_word_t Rx[2][NUM_ECC_WORDS];
-    uECC_word_t Ry[2][NUM_ECC_WORDS];
-    uECC_word_t z[NUM_ECC_WORDS];
-    bitcount_t i;
-    uECC_word_t nb;
-    wordcount_t num_words = curve->num_words;
-
-    uECC_vli_set(Rx[1], point, num_words);
-    uECC_vli_set(Ry[1], point + num_words, num_words);
-
-    XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
-
-    for (i = num_bits - 2; i > 0; --i) {
-        nb = !uECC_vli_testBit(scalar, i);
-        XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
-        XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
-    }
-
-    nb = !uECC_vli_testBit(scalar, 0);
+static void XYcZ_addC(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2, uECC_word_t *Y2, uECC_Curve curve) {
+  /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
+  uECC_word_t t5[NUM_ECC_WORDS];
+  uECC_word_t t6[NUM_ECC_WORDS];
+  uECC_word_t t7[NUM_ECC_WORDS];
+  wordcount_t num_words = curve->num_words;
+
+  uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
+  uECC_vli_modSquare_fast(t5, t5, curve);           /* t5 = (x2 - x1)^2 = A */
+  uECC_vli_modMult_fast(X1, X1, t5, curve);         /* t1 = x1*A = B */
+  uECC_vli_modMult_fast(X2, X2, t5, curve);         /* t3 = x2*A = C */
+  uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
+  uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
+
+  uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
+  uECC_vli_modMult_fast(Y1, Y1, t6, curve);         /* t2 = y1 * (C - B) = E */
+  uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
+  uECC_vli_modSquare_fast(X2, Y2, curve);           /* t3 = (y2 - y1)^2 = D */
+  uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */
+
+  uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
+  uECC_vli_modMult_fast(Y2, Y2, t7, curve);         /* t4 = (y2 - y1)*(B - x3) */
+  /* t4 = (y2 - y1)*(B - x3) - E = y3: */
+  uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words);
+
+  uECC_vli_modSquare_fast(t7, t5, curve);           /* t7 = (y2 + y1)^2 = F */
+  uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */
+  uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
+  uECC_vli_modMult_fast(t6, t6, t5, curve);         /* t6 = (y2+y1)*(x3' - B) */
+  /* t2 = (y2+y1)*(x3' - B) - E = y3': */
+  uECC_vli_modSub(Y1, t6, Y1, curve->p, num_words);
+
+  uECC_vli_set(X1, t7, num_words);
+}
+
+void EccPoint_mult(uECC_word_t *result, const uECC_word_t *point, const uECC_word_t *scalar, const uECC_word_t *initial_Z, bitcount_t num_bits, uECC_Curve curve) {
+  /* R0 and R1 */
+  uECC_word_t Rx[2][NUM_ECC_WORDS];
+  uECC_word_t Ry[2][NUM_ECC_WORDS];
+  uECC_word_t z[NUM_ECC_WORDS];
+  bitcount_t  i;
+  uECC_word_t nb;
+  wordcount_t num_words = curve->num_words;
+
+  uECC_vli_set(Rx[1], point, num_words);
+  uECC_vli_set(Ry[1], point + num_words, num_words);
+
+  XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
+
+  for (i = num_bits - 2; i > 0; --i) {
+    nb = !uECC_vli_testBit(scalar, i);
     XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
+    XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
+  }
 
-    /* Find final 1/Z value. */
-    uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
-    uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve);        /* Yb * (X1 - X0) */
-    uECC_vli_modMult_fast(z, z, point, curve);             /* xP * Yb * (X1 - X0) */
-    uECC_vli_modInv(z, z, curve->p, num_words);            /* 1 / (xP * Yb * (X1 - X0))*/
-    /* yP / (xP * Yb * (X1 - X0)) */
-    uECC_vli_modMult_fast(z, z, point + num_words, curve);
-    /* Xb * yP / (xP * Yb * (X1 - X0)) */
-    uECC_vli_modMult_fast(z, z, Rx[1 - nb], curve);
-    /* End 1/Z calculation */
+  nb = !uECC_vli_testBit(scalar, 0);
+  XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
 
-    XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
-    apply_z(Rx[0], Ry[0], z, curve);
+  /* Find final 1/Z value. */
+  uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
+  uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve);        /* Yb * (X1 - X0) */
+  uECC_vli_modMult_fast(z, z, point, curve);             /* xP * Yb * (X1 - X0) */
+  uECC_vli_modInv(z, z, curve->p, num_words);            /* 1 / (xP * Yb * (X1 - X0))*/
+  /* yP / (xP * Yb * (X1 - X0)) */
+  uECC_vli_modMult_fast(z, z, point + num_words, curve);
+  /* Xb * yP / (xP * Yb * (X1 - X0)) */
+  uECC_vli_modMult_fast(z, z, Rx[1 - nb], curve);
+  /* End 1/Z calculation */
 
-    uECC_vli_set(result, Rx[0], num_words);
-    uECC_vli_set(result + num_words, Ry[0], num_words);
+  XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
+  apply_z(Rx[0], Ry[0], z, curve);
+
+  uECC_vli_set(result, Rx[0], num_words);
+  uECC_vli_set(result + num_words, Ry[0], num_words);
 }
 
-uECC_word_t regularize_k(const uECC_word_t *const k, uECC_word_t *k0,
-                         uECC_word_t *k1, uECC_Curve curve)
-{
-    wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+uECC_word_t regularize_k(const uECC_word_t *const k, uECC_word_t *k0, uECC_word_t *k1, uECC_Curve curve) {
+  wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
 
-    bitcount_t num_n_bits = curve->num_n_bits;
+  bitcount_t num_n_bits = curve->num_n_bits;
 
-    uECC_word_t carry = uECC_vli_add(k0, k, curve->n, num_n_words) ||
-                        (num_n_bits < ((bitcount_t)num_n_words * uECC_WORD_SIZE * 8) &&
-                         uECC_vli_testBit(k0, num_n_bits));
+  uECC_word_t carry = uECC_vli_add(k0, k, curve->n, num_n_words) || (num_n_bits < ((bitcount_t)num_n_words * uECC_WORD_SIZE * 8) && uECC_vli_testBit(k0, num_n_bits));
 
-    uECC_vli_add(k1, k0, curve->n, num_n_words);
+  uECC_vli_add(k1, k0, curve->n, num_n_words);
 
-    return carry;
+  return carry;
 }
 
-uECC_word_t EccPoint_compute_public_key(uECC_word_t *result,
-                                        uECC_word_t *private_key,
-                                        uECC_Curve curve)
-{
-    uECC_word_t tmp1[NUM_ECC_WORDS];
-    uECC_word_t tmp2[NUM_ECC_WORDS];
-    uECC_word_t *p2[2] = { tmp1, tmp2 };
-    uECC_word_t carry;
+uECC_word_t EccPoint_compute_public_key(uECC_word_t *result, uECC_word_t *private_key, uECC_Curve curve) {
+  uECC_word_t  tmp1[NUM_ECC_WORDS];
+  uECC_word_t  tmp2[NUM_ECC_WORDS];
+  uECC_word_t *p2[2] = {tmp1, tmp2};
+  uECC_word_t  carry;
 
-    /* Regularize the bitcount for the private key so that attackers cannot
-	 * use a side channel attack to learn the number of leading zeros. */
-    carry = regularize_k(private_key, tmp1, tmp2, curve);
+  /* Regularize the bitcount for the private key so that attackers cannot
+   * use a side channel attack to learn the number of leading zeros. */
+  carry = regularize_k(private_key, tmp1, tmp2, curve);
 
-    EccPoint_mult(result, curve->G, p2[!carry], 0, curve->num_n_bits + 1, curve);
+  EccPoint_mult(result, curve->G, p2[!carry], 0, curve->num_n_bits + 1, curve);
 
-    if (EccPoint_isZero(result, curve)) {
-        return 0;
-    }
-    return 1;
+  if (EccPoint_isZero(result, curve)) {
+    return 0;
+  }
+  return 1;
 }
 
 /* Converts an integer in uECC native format to big-endian bytes. */
-void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
-                            const unsigned int *native)
-{
-    wordcount_t i;
-    for (i = 0; i < num_bytes; ++i) {
-        unsigned b = num_bytes - 1 - i;
-        bytes[i] = native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE));
-    }
+void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes, const unsigned int *native) {
+  wordcount_t i;
+  for (i = 0; i < num_bytes; ++i) {
+    unsigned b = num_bytes - 1 - i;
+    bytes[i]   = native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE));
+  }
 }
 
 /* Converts big-endian bytes to an integer in uECC native format. */
-void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes,
-                            int num_bytes)
-{
-    wordcount_t i;
-    uECC_vli_clear(native, (num_bytes + (uECC_WORD_SIZE - 1)) / uECC_WORD_SIZE);
-    for (i = 0; i < num_bytes; ++i) {
-        unsigned b = num_bytes - 1 - i;
-        native[b / uECC_WORD_SIZE] |=
-            (uECC_word_t)bytes[i] << (8 * (b % uECC_WORD_SIZE));
-    }
+void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes, int num_bytes) {
+  wordcount_t i;
+  uECC_vli_clear(native, (num_bytes + (uECC_WORD_SIZE - 1)) / uECC_WORD_SIZE);
+  for (i = 0; i < num_bytes; ++i) {
+    unsigned b = num_bytes - 1 - i;
+    native[b / uECC_WORD_SIZE] |= (uECC_word_t)bytes[i] << (8 * (b % uECC_WORD_SIZE));
+  }
 }
 
-int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top,
-                             wordcount_t num_words)
-{
-    uECC_word_t mask = (uECC_word_t)-1;
-    uECC_word_t tries;
-    bitcount_t num_bits = uECC_vli_numBits(top, num_words);
+int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top, wordcount_t num_words) {
+  uECC_word_t mask = (uECC_word_t)-1;
+  uECC_word_t tries;
+  bitcount_t  num_bits = uECC_vli_numBits(top, num_words);
 
-    if (!g_rng_function) {
-        return 0;
-    }
+  if (!g_rng_function) {
+    return 0;
+  }
 
-    for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
-        if (!g_rng_function((uint8_t *)random, num_words * uECC_WORD_SIZE)) {
-            return 0;
-        }
-        random[num_words - 1] &=
-            mask >> ((bitcount_t)(num_words * uECC_WORD_SIZE * 8 - num_bits));
-        if (!uECC_vli_isZero(random, num_words) &&
-            uECC_vli_cmp(top, random, num_words) == 1) {
-            return 1;
-        }
+  for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
+    if (!g_rng_function((uint8_t *)random, num_words * uECC_WORD_SIZE)) {
+      return 0;
     }
-    return 0;
+    random[num_words - 1] &= mask >> ((bitcount_t)(num_words * uECC_WORD_SIZE * 8 - num_bits));
+    if (!uECC_vli_isZero(random, num_words) && uECC_vli_cmp(top, random, num_words) == 1) {
+      return 1;
+    }
+  }
+  return 0;
 }
 
-int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve)
-{
-    uECC_word_t tmp1[NUM_ECC_WORDS];
-    uECC_word_t tmp2[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
+int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve) {
+  uECC_word_t tmp1[NUM_ECC_WORDS];
+  uECC_word_t tmp2[NUM_ECC_WORDS];
+  wordcount_t num_words = curve->num_words;
 
-    /* The point at infinity is invalid. */
-    if (EccPoint_isZero(point, curve)) {
-        return -1;
-    }
+  /* The point at infinity is invalid. */
+  if (EccPoint_isZero(point, curve)) {
+    return -1;
+  }
 
-    /* x and y must be smaller than p. */
-    if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 ||
-        uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
-        return -2;
-    }
+  /* x and y must be smaller than p. */
+  if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 || uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
+    return -2;
+  }
 
-    uECC_vli_modSquare_fast(tmp1, point + num_words, curve);
-    curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
+  uECC_vli_modSquare_fast(tmp1, point + num_words, curve);
+  curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
 
-    /* Make sure that y^2 == x^3 + ax + b */
-    if (uECC_vli_equal(tmp1, tmp2, num_words) != 0)
-        return -3;
+  /* Make sure that y^2 == x^3 + ax + b */
+  if (uECC_vli_equal(tmp1, tmp2, num_words) != 0)
+    return -3;
 
-    return 0;
+  return 0;
 }
 
-int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve)
-{
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
+int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve) {
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
 
-    uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
-    uECC_vli_bytesToNative(
-        _public + curve->num_words,
-        public_key + curve->num_bytes,
-        curve->num_bytes);
+  uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
+  uECC_vli_bytesToNative(_public + curve->num_words, public_key + curve->num_bytes, curve->num_bytes);
 
-    if (uECC_vli_cmp_unsafe(_public, curve->G, NUM_ECC_WORDS * 2) == 0) {
-        return -4;
-    }
+  if (uECC_vli_cmp_unsafe(_public, curve->G, NUM_ECC_WORDS * 2) == 0) {
+    return -4;
+  }
 
-    return uECC_valid_point(_public, curve);
+  return uECC_valid_point(_public, curve);
 }
 
-int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key,
-                            uECC_Curve curve)
-{
-    uECC_word_t _private[NUM_ECC_WORDS];
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
+int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key, uECC_Curve curve) {
+  uECC_word_t _private[NUM_ECC_WORDS];
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
 
-    uECC_vli_bytesToNative(
-        _private,
-        private_key,
-        BITS_TO_BYTES(curve->num_n_bits));
+  uECC_vli_bytesToNative(_private, private_key, BITS_TO_BYTES(curve->num_n_bits));
 
-    /* Make sure the private key is in the range [1, n-1]. */
-    if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
-        return 0;
-    }
+  /* Make sure the private key is in the range [1, n-1]. */
+  if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
+    return 0;
+  }
 
-    if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) {
-        return 0;
-    }
+  if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) {
+    return 0;
+  }
 
-    /* Compute public key. */
-    if (!EccPoint_compute_public_key(_public, _private, curve)) {
-        return 0;
-    }
+  /* Compute public key. */
+  if (!EccPoint_compute_public_key(_public, _private, curve)) {
+    return 0;
+  }
 
-    uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
-    uECC_vli_nativeToBytes(
-        public_key +
-            curve->num_bytes,
-        curve->num_bytes, _public + curve->num_words);
-    return 1;
+  uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
+  uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words);
+  return 1;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dh.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dh.c
index e2995ef2a..e26b15264 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dh.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dh.c
@@ -1,6 +1,6 @@
 /* ec_dh.c - TinyCrypt implementation of EC-DH */
 
-/* 
+/*
  * Copyright (c) 2014, Kenneth MacKay
  * All rights reserved.
  *
@@ -54,9 +54,9 @@
  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  *  POSSIBILITY OF SUCH DAMAGE.
  */
+#include "ecc_dh.h"
 #include "constants.h"
 #include "ecc.h"
-#include "ecc_dh.h"
 #if defined(BFLB_BLE)
 #include "utils.h"
 #endif
@@ -71,128 +71,103 @@ static uECC_RNG_Function g_rng_function = &default_CSPRNG;
 static uECC_RNG_Function g_rng_function = 0;
 #endif
 
-int uECC_make_key_with_d(uint8_t *public_key, uint8_t *private_key,
-                         unsigned int *d, uECC_Curve curve)
-{
-    uECC_word_t _private[NUM_ECC_WORDS];
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
+int uECC_make_key_with_d(uint8_t *public_key, uint8_t *private_key, unsigned int *d, uECC_Curve curve) {
+  uECC_word_t _private[NUM_ECC_WORDS];
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
 
-    /* This function is designed for test purposes-only (such as validating NIST
-	 * test vectors) as it uses a provided value for d instead of generating
-	 * it uniformly at random. */
-    memcpy(_private, d, NUM_ECC_BYTES);
+  /* This function is designed for test purposes-only (such as validating NIST
+   * test vectors) as it uses a provided value for d instead of generating
+   * it uniformly at random. */
+  memcpy(_private, d, NUM_ECC_BYTES);
 
-    /* Computing public-key from private: */
-    if (EccPoint_compute_public_key(_public, _private, curve)) {
-        /* Converting buffers to correct bit order: */
-        uECC_vli_nativeToBytes(private_key,
-                               BITS_TO_BYTES(curve->num_n_bits),
-                               _private);
-        uECC_vli_nativeToBytes(public_key,
-                               curve->num_bytes,
-                               _public);
-        uECC_vli_nativeToBytes(public_key + curve->num_bytes,
-                               curve->num_bytes,
-                               _public + curve->num_words);
-
-        /* erasing temporary buffer used to store secret: */
-        _set_secure(_private, 0, NUM_ECC_BYTES);
-
-        return 1;
-    }
-    return 0;
+  /* Computing public-key from private: */
+  if (EccPoint_compute_public_key(_public, _private, curve)) {
+    /* Converting buffers to correct bit order: */
+    uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits), _private);
+    uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
+    uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words);
+
+    /* erasing temporary buffer used to store secret: */
+    _set_secure(_private, 0, NUM_ECC_BYTES);
+
+    return 1;
+  }
+  return 0;
 }
 
-int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve)
-{
-    uECC_word_t _random[NUM_ECC_WORDS * 2];
-    uECC_word_t _private[NUM_ECC_WORDS];
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
-    uECC_word_t tries;
-
-    for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
-        /* Generating _private uniformly at random: */
-        uECC_RNG_Function rng_function = uECC_get_rng();
-        if (!rng_function ||
-            !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS * uECC_WORD_SIZE)) {
-            return 0;
-        }
-
-        /* computing modular reduction of _random (see FIPS 186.4 B.4.1): */
-        uECC_vli_mmod(_private, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits));
-
-        /* Computing public-key from private: */
-        if (EccPoint_compute_public_key(_public, _private, curve)) {
-            /* Converting buffers to correct bit order: */
-            uECC_vli_nativeToBytes(private_key,
-                                   BITS_TO_BYTES(curve->num_n_bits),
-                                   _private);
-            uECC_vli_nativeToBytes(public_key,
-                                   curve->num_bytes,
-                                   _public);
-            uECC_vli_nativeToBytes(public_key + curve->num_bytes,
-                                   curve->num_bytes,
-                                   _public + curve->num_words);
-
-            /* erasing temporary buffer that stored secret: */
-            _set_secure(_private, 0, NUM_ECC_BYTES);
-
-            return 1;
-        }
+int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve) {
+  uECC_word_t _random[NUM_ECC_WORDS * 2];
+  uECC_word_t _private[NUM_ECC_WORDS];
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
+  uECC_word_t tries;
+
+  for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
+    /* Generating _private uniformly at random: */
+    uECC_RNG_Function rng_function = uECC_get_rng();
+    if (!rng_function || !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS * uECC_WORD_SIZE)) {
+      return 0;
     }
-    return 0;
-}
 
-int uECC_shared_secret(const uint8_t *public_key, const uint8_t *private_key,
-                       uint8_t *secret, uECC_Curve curve)
-{
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
-    uECC_word_t _private[NUM_ECC_WORDS];
+    /* computing modular reduction of _random (see FIPS 186.4 B.4.1): */
+    uECC_vli_mmod(_private, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits));
 
-    uECC_word_t tmp[NUM_ECC_WORDS];
-    uECC_word_t *p2[2] = { _private, tmp };
-    uECC_word_t *initial_Z = 0;
-    uECC_word_t carry;
-    wordcount_t num_words = curve->num_words;
-    wordcount_t num_bytes = curve->num_bytes;
-    int r;
+    /* Computing public-key from private: */
+    if (EccPoint_compute_public_key(_public, _private, curve)) {
+      /* Converting buffers to correct bit order: */
+      uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits), _private);
+      uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
+      uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words);
 
-    /* Converting buffers to correct bit order: */
-    uECC_vli_bytesToNative(_private,
-                           private_key,
-                           BITS_TO_BYTES(curve->num_n_bits));
-    uECC_vli_bytesToNative(_public,
-                           public_key,
-                           num_bytes);
-    uECC_vli_bytesToNative(_public + num_words,
-                           public_key + num_bytes,
-                           num_bytes);
-
-    /* Regularize the bitcount for the private key so that attackers cannot use a
-	 * side channel attack to learn the number of leading zeros. */
-    carry = regularize_k(_private, _private, tmp, curve);
-
-    /* If an RNG function was specified, try to get a random initial Z value to
-	 * improve protection against side-channel attacks. */
-    if (g_rng_function) {
-        if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) {
-            r = 0;
-            goto clear_and_out;
-        }
-        initial_Z = p2[carry];
+      /* erasing temporary buffer that stored secret: */
+      _set_secure(_private, 0, NUM_ECC_BYTES);
+
+      return 1;
     }
+  }
+  return 0;
+}
+
+int uECC_shared_secret(const uint8_t *public_key, const uint8_t *private_key, uint8_t *secret, uECC_Curve curve) {
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
+  uECC_word_t _private[NUM_ECC_WORDS];
+
+  uECC_word_t  tmp[NUM_ECC_WORDS];
+  uECC_word_t *p2[2]     = {_private, tmp};
+  uECC_word_t *initial_Z = 0;
+  uECC_word_t  carry;
+  wordcount_t  num_words = curve->num_words;
+  wordcount_t  num_bytes = curve->num_bytes;
+  int          r;
+
+  /* Converting buffers to correct bit order: */
+  uECC_vli_bytesToNative(_private, private_key, BITS_TO_BYTES(curve->num_n_bits));
+  uECC_vli_bytesToNative(_public, public_key, num_bytes);
+  uECC_vli_bytesToNative(_public + num_words, public_key + num_bytes, num_bytes);
+
+  /* Regularize the bitcount for the private key so that attackers cannot use a
+   * side channel attack to learn the number of leading zeros. */
+  carry = regularize_k(_private, _private, tmp, curve);
+
+  /* If an RNG function was specified, try to get a random initial Z value to
+   * improve protection against side-channel attacks. */
+  if (g_rng_function) {
+    if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) {
+      r = 0;
+      goto clear_and_out;
+    }
+    initial_Z = p2[carry];
+  }
 
-    EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1,
-                  curve);
+  EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1, curve);
 
-    uECC_vli_nativeToBytes(secret, num_bytes, _public);
-    r = !EccPoint_isZero(_public, curve);
+  uECC_vli_nativeToBytes(secret, num_bytes, _public);
+  r = !EccPoint_isZero(_public, curve);
 
 clear_and_out:
-    /* erasing temporary buffer used to store secret: */
-    _set_secure(p2, 0, sizeof(p2));
-    _set_secure(tmp, 0, sizeof(tmp));
-    _set_secure(_private, 0, sizeof(_private));
+  /* erasing temporary buffer used to store secret: */
+  _set_secure(p2, 0, sizeof(p2));
+  _set_secure(tmp, 0, sizeof(tmp));
+  _set_secure(_private, 0, sizeof(_private));
 
-    return r;
+  return r;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dsa.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dsa.c
index 117e3d26d..e729f4faa 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dsa.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_dsa.c
@@ -53,9 +53,9 @@
  *  POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include "ecc_dsa.h"
 #include "constants.h"
 #include "ecc.h"
-#include "ecc_dsa.h"
 #if defined(BL_MCU_SDK)
 #include "ecc_platform_specific.h"
 #endif
@@ -66,229 +66,218 @@ static uECC_RNG_Function g_rng_function = &default_CSPRNG;
 static uECC_RNG_Function g_rng_function = 0;
 #endif
 
-static void bits2int(uECC_word_t *native, const uint8_t *bits,
-                     unsigned bits_size, uECC_Curve curve)
-{
-    unsigned num_n_bytes = BITS_TO_BYTES(curve->num_n_bits);
-    unsigned num_n_words = BITS_TO_WORDS(curve->num_n_bits);
-    int shift;
-    uECC_word_t carry;
-    uECC_word_t *ptr;
-
-    if (bits_size > num_n_bytes) {
-        bits_size = num_n_bytes;
-    }
-
-    uECC_vli_clear(native, num_n_words);
-    uECC_vli_bytesToNative(native, bits, bits_size);
-    if (bits_size * 8 <= (unsigned)curve->num_n_bits) {
-        return;
-    }
-    shift = bits_size * 8 - curve->num_n_bits;
-    carry = 0;
-    ptr = native + num_n_words;
-    while (ptr-- > native) {
-        uECC_word_t temp = *ptr;
-        *ptr = (temp >> shift) | carry;
-        carry = temp << (uECC_WORD_BITS - shift);
-    }
-
-    /* Reduce mod curve_n */
-    if (uECC_vli_cmp_unsafe(curve->n, native, num_n_words) != 1) {
-        uECC_vli_sub(native, native, curve->n, num_n_words);
-    }
+static void bits2int(uECC_word_t *native, const uint8_t *bits, unsigned bits_size, uECC_Curve curve) {
+  unsigned     num_n_bytes = BITS_TO_BYTES(curve->num_n_bits);
+  unsigned     num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+  int          shift;
+  uECC_word_t  carry;
+  uECC_word_t *ptr;
+
+  if (bits_size > num_n_bytes) {
+    bits_size = num_n_bytes;
+  }
+
+  uECC_vli_clear(native, num_n_words);
+  uECC_vli_bytesToNative(native, bits, bits_size);
+  if (bits_size * 8 <= (unsigned)curve->num_n_bits) {
+    return;
+  }
+  shift = bits_size * 8 - curve->num_n_bits;
+  carry = 0;
+  ptr   = native + num_n_words;
+  while (ptr-- > native) {
+    uECC_word_t temp = *ptr;
+    *ptr             = (temp >> shift) | carry;
+    carry            = temp << (uECC_WORD_BITS - shift);
+  }
+
+  /* Reduce mod curve_n */
+  if (uECC_vli_cmp_unsafe(curve->n, native, num_n_words) != 1) {
+    uECC_vli_sub(native, native, curve->n, num_n_words);
+  }
 }
 
-int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
-                     unsigned hash_size, uECC_word_t *k, uint8_t *signature,
-                     uECC_Curve curve)
-{
-    uECC_word_t tmp[NUM_ECC_WORDS];
-    uECC_word_t s[NUM_ECC_WORDS];
-    uECC_word_t *k2[2] = { tmp, s };
-    uECC_word_t p[NUM_ECC_WORDS * 2];
-    uECC_word_t carry;
-    wordcount_t num_words = curve->num_words;
-    wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
-    bitcount_t num_n_bits = curve->num_n_bits;
-
-    /* Make sure 0 < k < curve_n */
-    if (uECC_vli_isZero(k, num_words) ||
-        uECC_vli_cmp(curve->n, k, num_n_words) != 1) {
-        return 0;
-    }
-
-    carry = regularize_k(k, tmp, s, curve);
-    EccPoint_mult(p, curve->G, k2[!carry], 0, num_n_bits + 1, curve);
-    if (uECC_vli_isZero(p, num_words)) {
-        return 0;
-    }
-
-    /* If an RNG function was specified, get a random number
-	to prevent side channel analysis of k. */
-    if (!g_rng_function) {
-        uECC_vli_clear(tmp, num_n_words);
-        tmp[0] = 1;
-    } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) {
-        return 0;
+int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash, unsigned hash_size, uECC_word_t *k, uint8_t *signature, uECC_Curve curve) {
+  uECC_word_t  tmp[NUM_ECC_WORDS];
+  uECC_word_t  s[NUM_ECC_WORDS];
+  uECC_word_t *k2[2]     = {tmp, s};
+  uECC_word_t *initial_Z = 0;
+  uECC_word_t  p[NUM_ECC_WORDS * 2];
+  uECC_word_t  carry;
+  wordcount_t  num_words   = curve->num_words;
+  wordcount_t  num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+  bitcount_t   num_n_bits  = curve->num_n_bits;
+
+  /* Make sure 0 < k < curve_n */
+  if (uECC_vli_isZero(k, num_words) || uECC_vli_cmp(curve->n, k, num_n_words) != 1) {
+    return 0;
+  }
+
+  carry = regularize_k(k, tmp, s, curve);
+  /* If an RNG function was specified, try to get a random initial Z value to improve
+     protection against side-channel attacks. */
+  if (g_rng_function) {
+    if (!uECC_generate_random_int(k2[carry], curve->p, num_words)) {
+      return 0;
     }
+    initial_Z = k2[carry];
+  }
+  EccPoint_mult(p, curve->G, k2[!carry], initial_Z, num_n_bits + 1, curve);
+  if (uECC_vli_isZero(p, num_words)) {
+    return 0;
+  }
+
+  /* If an RNG function was specified, get a random number
+      to prevent side channel analysis of k. */
+  if (!g_rng_function) {
+    uECC_vli_clear(tmp, num_n_words);
+    tmp[0] = 1;
+  } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) {
+    return 0;
+  }
 
-    /* Prevent side channel analysis of uECC_vli_modInv() to determine
-	bits of k / the private key by premultiplying by a random number */
-    uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
-    uECC_vli_modInv(k, k, curve->n, num_n_words);       /* k = 1 / k' */
-    uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
+  /* Prevent side channel analysis of uECC_vli_modInv() to determine
+      bits of k / the private key by premultiplying by a random number */
+  uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
+  uECC_vli_modInv(k, k, curve->n, num_n_words);       /* k = 1 / k' */
+  uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
 
-    uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
+  uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
 
-    /* tmp = d: */
-    uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
+  /* tmp = d: */
+  uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
 
-    s[num_n_words - 1] = 0;
-    uECC_vli_set(s, p, num_words);
-    uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
+  s[num_n_words - 1] = 0;
+  uECC_vli_set(s, p, num_words);
+  uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
 
-    bits2int(tmp, message_hash, hash_size, curve);
-    uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
-    uECC_vli_modMult(s, s, k, curve->n, num_n_words);  /* s = (e + r*d) / k */
-    if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) {
-        return 0;
-    }
+  bits2int(tmp, message_hash, hash_size, curve);
+  uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
+  uECC_vli_modMult(s, s, k, curve->n, num_n_words);  /* s = (e + r*d) / k */
+  if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) {
+    return 0;
+  }
 
-    uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
-    return 1;
+  uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
+  return 1;
 }
 
-int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash,
-              unsigned hash_size, uint8_t *signature, uECC_Curve curve)
-{
-    uECC_word_t _random[2 * NUM_ECC_WORDS];
-    uECC_word_t k[NUM_ECC_WORDS];
-    uECC_word_t tries;
-
-    for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
-        /* Generating _random uniformly at random: */
-        uECC_RNG_Function rng_function = uECC_get_rng();
-        if (!rng_function ||
-            !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS * uECC_WORD_SIZE)) {
-            return 0;
-        }
-
-        // computing k as modular reduction of _random (see FIPS 186.4 B.5.1):
-        uECC_vli_mmod(k, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits));
-
-        if (uECC_sign_with_k(private_key, message_hash, hash_size, k, signature,
-                             curve)) {
-            return 1;
-        }
+int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash, unsigned hash_size, uint8_t *signature, uECC_Curve curve) {
+  uECC_word_t _random[2 * NUM_ECC_WORDS];
+  uECC_word_t k[NUM_ECC_WORDS];
+  uECC_word_t tries;
+
+  for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
+    /* Generating _random uniformly at random: */
+    uECC_RNG_Function rng_function = uECC_get_rng();
+    if (!rng_function || !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS * uECC_WORD_SIZE)) {
+      return 0;
     }
-    return 0;
-}
 
-static bitcount_t smax(bitcount_t a, bitcount_t b)
-{
-    return (a > b ? a : b);
-}
+    // computing k as modular reduction of _random (see FIPS 186.4 B.5.1):
+    uECC_vli_mmod(k, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits));
 
-int uECC_verify(const uint8_t *public_key, const uint8_t *message_hash,
-                unsigned hash_size, const uint8_t *signature,
-                uECC_Curve curve)
-{
-    uECC_word_t u1[NUM_ECC_WORDS], u2[NUM_ECC_WORDS];
-    uECC_word_t z[NUM_ECC_WORDS];
-    uECC_word_t sum[NUM_ECC_WORDS * 2];
-    uECC_word_t rx[NUM_ECC_WORDS];
-    uECC_word_t ry[NUM_ECC_WORDS];
-    uECC_word_t tx[NUM_ECC_WORDS];
-    uECC_word_t ty[NUM_ECC_WORDS];
-    uECC_word_t tz[NUM_ECC_WORDS];
-    const uECC_word_t *points[4];
-    const uECC_word_t *point;
-    bitcount_t num_bits;
-    bitcount_t i;
-
-    uECC_word_t _public[NUM_ECC_WORDS * 2];
-    uECC_word_t r[NUM_ECC_WORDS], s[NUM_ECC_WORDS];
-    wordcount_t num_words = curve->num_words;
-    wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
-
-    rx[num_n_words - 1] = 0;
-    r[num_n_words - 1] = 0;
-    s[num_n_words - 1] = 0;
-
-    uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
-    uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes,
-                           curve->num_bytes);
-    uECC_vli_bytesToNative(r, signature, curve->num_bytes);
-    uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
-
-    /* r, s must not be 0. */
-    if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) {
-        return 0;
+    if (uECC_sign_with_k(private_key, message_hash, hash_size, k, signature, curve)) {
+      return 1;
     }
+  }
+  return 0;
+}
 
-    /* r, s must be < n. */
-    if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 ||
-        uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
-        return 0;
-    }
+static bitcount_t smax(bitcount_t a, bitcount_t b) { return (a > b ? a : b); }
+
+int uECC_verify(const uint8_t *public_key, const uint8_t *message_hash, unsigned hash_size, const uint8_t *signature, uECC_Curve curve) {
+  uECC_word_t        u1[NUM_ECC_WORDS], u2[NUM_ECC_WORDS];
+  uECC_word_t        z[NUM_ECC_WORDS];
+  uECC_word_t        sum[NUM_ECC_WORDS * 2];
+  uECC_word_t        rx[NUM_ECC_WORDS];
+  uECC_word_t        ry[NUM_ECC_WORDS];
+  uECC_word_t        tx[NUM_ECC_WORDS];
+  uECC_word_t        ty[NUM_ECC_WORDS];
+  uECC_word_t        tz[NUM_ECC_WORDS];
+  const uECC_word_t *points[4];
+  const uECC_word_t *point;
+  bitcount_t         num_bits;
+  bitcount_t         i;
+
+  uECC_word_t _public[NUM_ECC_WORDS * 2];
+  uECC_word_t r[NUM_ECC_WORDS], s[NUM_ECC_WORDS];
+  wordcount_t num_words   = curve->num_words;
+  wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
+
+  rx[num_n_words - 1] = 0;
+  r[num_n_words - 1]  = 0;
+  s[num_n_words - 1]  = 0;
+
+  uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
+  uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes, curve->num_bytes);
+  uECC_vli_bytesToNative(r, signature, curve->num_bytes);
+  uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
+
+  /* r, s must not be 0. */
+  if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) {
+    return 0;
+  }
 
-    /* Calculate u1 and u2. */
-    uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
-    u1[num_n_words - 1] = 0;
-    bits2int(u1, message_hash, hash_size, curve);
-    uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
-    uECC_vli_modMult(u2, r, z, curve->n, num_n_words);  /* u2 = r/s */
-
-    /* Calculate sum = G + Q. */
-    uECC_vli_set(sum, _public, num_words);
-    uECC_vli_set(sum + num_words, _public + num_words, num_words);
-    uECC_vli_set(tx, curve->G, num_words);
-    uECC_vli_set(ty, curve->G + num_words, num_words);
-    uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
-    XYcZ_add(tx, ty, sum, sum + num_words, curve);
-    uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
-    apply_z(sum, sum + num_words, z, curve);
-
-    /* Use Shamir's trick to calculate u1*G + u2*Q */
-    points[0] = 0;
-    points[1] = curve->G;
-    points[2] = _public;
-    points[3] = sum;
-    num_bits = smax(uECC_vli_numBits(u1, num_n_words),
-                    uECC_vli_numBits(u2, num_n_words));
-
-    point = points[(!!uECC_vli_testBit(u1, num_bits - 1)) |
-                   ((!!uECC_vli_testBit(u2, num_bits - 1)) << 1)];
-    uECC_vli_set(rx, point, num_words);
-    uECC_vli_set(ry, point + num_words, num_words);
-    uECC_vli_clear(z, num_words);
-    z[0] = 1;
-
-    for (i = num_bits - 2; i >= 0; --i) {
-        uECC_word_t index;
-        curve->double_jacobian(rx, ry, z, curve);
-
-        index = (!!uECC_vli_testBit(u1, i)) | ((!!uECC_vli_testBit(u2, i)) << 1);
-        point = points[index];
-        if (point) {
-            uECC_vli_set(tx, point, num_words);
-            uECC_vli_set(ty, point + num_words, num_words);
-            apply_z(tx, ty, z, curve);
-            uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
-            XYcZ_add(tx, ty, rx, ry, curve);
-            uECC_vli_modMult_fast(z, z, tz, curve);
-        }
+  /* r, s must be < n. */
+  if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 || uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
+    return 0;
+  }
+
+  /* Calculate u1 and u2. */
+  uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
+  u1[num_n_words - 1] = 0;
+  bits2int(u1, message_hash, hash_size, curve);
+  uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
+  uECC_vli_modMult(u2, r, z, curve->n, num_n_words);  /* u2 = r/s */
+
+  /* Calculate sum = G + Q. */
+  uECC_vli_set(sum, _public, num_words);
+  uECC_vli_set(sum + num_words, _public + num_words, num_words);
+  uECC_vli_set(tx, curve->G, num_words);
+  uECC_vli_set(ty, curve->G + num_words, num_words);
+  uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
+  XYcZ_add(tx, ty, sum, sum + num_words, curve);
+  uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
+  apply_z(sum, sum + num_words, z, curve);
+
+  /* Use Shamir's trick to calculate u1*G + u2*Q */
+  points[0] = 0;
+  points[1] = curve->G;
+  points[2] = _public;
+  points[3] = sum;
+  num_bits  = smax(uECC_vli_numBits(u1, num_n_words), uECC_vli_numBits(u2, num_n_words));
+
+  point = points[(!!uECC_vli_testBit(u1, num_bits - 1)) | ((!!uECC_vli_testBit(u2, num_bits - 1)) << 1)];
+  uECC_vli_set(rx, point, num_words);
+  uECC_vli_set(ry, point + num_words, num_words);
+  uECC_vli_clear(z, num_words);
+  z[0] = 1;
+
+  for (i = num_bits - 2; i >= 0; --i) {
+    uECC_word_t index;
+    curve->double_jacobian(rx, ry, z, curve);
+
+    index = (!!uECC_vli_testBit(u1, i)) | ((!!uECC_vli_testBit(u2, i)) << 1);
+    point = points[index];
+    if (point) {
+      uECC_vli_set(tx, point, num_words);
+      uECC_vli_set(ty, point + num_words, num_words);
+      apply_z(tx, ty, z, curve);
+      uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
+      XYcZ_add(tx, ty, rx, ry, curve);
+      uECC_vli_modMult_fast(z, z, tz, curve);
     }
+  }
 
-    uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
-    apply_z(rx, ry, z, curve);
+  uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
+  apply_z(rx, ry, z, curve);
 
-    /* v = x1 (mod n) */
-    if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
-        uECC_vli_sub(rx, rx, curve->n, num_n_words);
-    }
+  /* v = x1 (mod n) */
+  if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
+    uECC_vli_sub(rx, rx, curve->n, num_n_words);
+  }
 
-    /* Accept only if v == r. */
-    return (int)(uECC_vli_equal(rx, r, num_words) == 0);
+  /* Accept only if v == r. */
+  return (int)(uECC_vli_equal(rx, r, num_words) == 0);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c
index 42dfee828..261ca747f 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/ecc_platform_specific.c
@@ -55,13 +55,11 @@
  *  uECC_platform_specific.c -- Implementation of platform specific functions
  */
 
-#if defined(unix) || defined(__linux__) || defined(__unix__) ||    \
-    defined(__unix) | (defined(__APPLE__) && defined(__MACH__)) || \
-    defined(uECC_POSIX)
+#if defined(unix) || defined(__linux__) || defined(__unix__) || defined(__unix) | (defined(__APPLE__) && defined(__MACH__)) || defined(uECC_POSIX)
 
 /* Some POSIX-like system with /dev/urandom or /dev/random. */
-#include 
 #include 
+#include 
 #include 
 
 #include 
@@ -70,34 +68,33 @@
 #define O_CLOEXEC 0
 #endif
 
-int default_CSPRNG(uint8_t *dest, unsigned int size)
-{
-    /* input sanity check: */
-    if (dest == (uint8_t *)0 || (size <= 0))
-        return 0;
+int default_CSPRNG(uint8_t *dest, unsigned int size) {
+  /* input sanity check: */
+  if (dest == (uint8_t *)0 || (size <= 0))
+    return 0;
 
-    int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
+  int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
+  if (fd == -1) {
+    fd = open("/dev/random", O_RDONLY | O_CLOEXEC);
     if (fd == -1) {
-        fd = open("/dev/random", O_RDONLY | O_CLOEXEC);
-        if (fd == -1) {
-            return 0;
-        }
+      return 0;
     }
+  }
 
-    char *ptr = (char *)dest;
-    size_t left = (size_t)size;
-    while (left > 0) {
-        ssize_t bytes_read = read(fd, ptr, left);
-        if (bytes_read <= 0) { // read failed
-            close(fd);
-            return 0;
-        }
-        left -= bytes_read;
-        ptr += bytes_read;
+  char  *ptr  = (char *)dest;
+  size_t left = (size_t)size;
+  while (left > 0) {
+    ssize_t bytes_read = read(fd, ptr, left);
+    if (bytes_read <= 0) { // read failed
+      close(fd);
+      return 0;
     }
+    left -= bytes_read;
+    ptr += bytes_read;
+  }
 
-    close(fd);
-    return 1;
+  close(fd);
+  return 1;
 }
 
 #endif /* platform */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac.c
index aee8a44e2..287c323e9 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac.c
@@ -34,112 +34,92 @@
 #include "constants.h"
 #include "utils.h"
 
-static void rekey(uint8_t *key, const uint8_t *new_key, unsigned int key_size)
-{
-    const uint8_t inner_pad = (uint8_t)0x36;
-    const uint8_t outer_pad = (uint8_t)0x5c;
-    unsigned int i;
-
-    for (i = 0; i < key_size; ++i) {
-        key[i] = inner_pad ^ new_key[i];
-        key[i + TC_SHA256_BLOCK_SIZE] = outer_pad ^ new_key[i];
-    }
-    for (; i < TC_SHA256_BLOCK_SIZE; ++i) {
-        key[i] = inner_pad;
-        key[i + TC_SHA256_BLOCK_SIZE] = outer_pad;
-    }
+static void rekey(uint8_t *key, const uint8_t *new_key, unsigned int key_size) {
+  const uint8_t inner_pad = (uint8_t)0x36;
+  const uint8_t outer_pad = (uint8_t)0x5c;
+  unsigned int  i;
+
+  for (i = 0; i < key_size; ++i) {
+    key[i]                        = inner_pad ^ new_key[i];
+    key[i + TC_SHA256_BLOCK_SIZE] = outer_pad ^ new_key[i];
+  }
+  for (; i < TC_SHA256_BLOCK_SIZE; ++i) {
+    key[i]                        = inner_pad;
+    key[i + TC_SHA256_BLOCK_SIZE] = outer_pad;
+  }
 }
 
-int tc_hmac_set_key(TCHmacState_t ctx, const uint8_t *key,
-                    unsigned int key_size)
-{
-    /* Input sanity check */
-    if (ctx == (TCHmacState_t)0 ||
-        key == (const uint8_t *)0 ||
-        key_size == 0) {
-        return TC_CRYPTO_FAIL;
-    }
-
-    const uint8_t dummy_key[TC_SHA256_BLOCK_SIZE];
-    struct tc_hmac_state_struct dummy_state;
-
-    if (key_size <= TC_SHA256_BLOCK_SIZE) {
-        /*
-		 * The next three calls are dummy calls just to avoid
-		 * certain timing attacks. Without these dummy calls,
-		 * adversaries would be able to learn whether the key_size is
-		 * greater than TC_SHA256_BLOCK_SIZE by measuring the time
-		 * consumed in this process.
-		 */
-        (void)tc_sha256_init(&dummy_state.hash_state);
-        (void)tc_sha256_update(&dummy_state.hash_state,
-                               dummy_key,
-                               key_size);
-        (void)tc_sha256_final(&dummy_state.key[TC_SHA256_DIGEST_SIZE],
-                              &dummy_state.hash_state);
-
-        /* Actual code for when key_size <= TC_SHA256_BLOCK_SIZE: */
-        rekey(ctx->key, key, key_size);
-    } else {
-        (void)tc_sha256_init(&ctx->hash_state);
-        (void)tc_sha256_update(&ctx->hash_state, key, key_size);
-        (void)tc_sha256_final(&ctx->key[TC_SHA256_DIGEST_SIZE],
-                              &ctx->hash_state);
-        rekey(ctx->key,
-              &ctx->key[TC_SHA256_DIGEST_SIZE],
-              TC_SHA256_DIGEST_SIZE);
-    }
-
-    return TC_CRYPTO_SUCCESS;
+int tc_hmac_set_key(TCHmacState_t ctx, const uint8_t *key, unsigned int key_size) {
+  /* Input sanity check */
+  if (ctx == (TCHmacState_t)0 || key == (const uint8_t *)0 || key_size == 0) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  const uint8_t               dummy_key[TC_SHA256_BLOCK_SIZE];
+  struct tc_hmac_state_struct dummy_state;
+
+  if (key_size <= TC_SHA256_BLOCK_SIZE) {
+    /*
+     * The next three calls are dummy calls just to avoid
+     * certain timing attacks. Without these dummy calls,
+     * adversaries would be able to learn whether the key_size is
+     * greater than TC_SHA256_BLOCK_SIZE by measuring the time
+     * consumed in this process.
+     */
+    (void)tc_sha256_init(&dummy_state.hash_state);
+    (void)tc_sha256_update(&dummy_state.hash_state, dummy_key, key_size);
+    (void)tc_sha256_final(&dummy_state.key[TC_SHA256_DIGEST_SIZE], &dummy_state.hash_state);
+
+    /* Actual code for when key_size <= TC_SHA256_BLOCK_SIZE: */
+    rekey(ctx->key, key, key_size);
+  } else {
+    (void)tc_sha256_init(&ctx->hash_state);
+    (void)tc_sha256_update(&ctx->hash_state, key, key_size);
+    (void)tc_sha256_final(&ctx->key[TC_SHA256_DIGEST_SIZE], &ctx->hash_state);
+    rekey(ctx->key, &ctx->key[TC_SHA256_DIGEST_SIZE], TC_SHA256_DIGEST_SIZE);
+  }
+
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_hmac_init(TCHmacState_t ctx)
-{
-    /* input sanity check: */
-    if (ctx == (TCHmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_hmac_init(TCHmacState_t ctx) {
+  /* input sanity check: */
+  if (ctx == (TCHmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    (void)tc_sha256_init(&ctx->hash_state);
-    (void)tc_sha256_update(&ctx->hash_state, ctx->key, TC_SHA256_BLOCK_SIZE);
+  (void)tc_sha256_init(&ctx->hash_state);
+  (void)tc_sha256_update(&ctx->hash_state, ctx->key, TC_SHA256_BLOCK_SIZE);
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_hmac_update(TCHmacState_t ctx,
-                   const void *data,
-                   unsigned int data_length)
-{
-    /* input sanity check: */
-    if (ctx == (TCHmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_hmac_update(TCHmacState_t ctx, const void *data, unsigned int data_length) {
+  /* input sanity check: */
+  if (ctx == (TCHmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    (void)tc_sha256_update(&ctx->hash_state, data, data_length);
+  (void)tc_sha256_update(&ctx->hash_state, data, data_length);
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_hmac_final(uint8_t *tag, unsigned int taglen, TCHmacState_t ctx)
-{
-    /* input sanity check: */
-    if (tag == (uint8_t *)0 ||
-        taglen != TC_SHA256_DIGEST_SIZE ||
-        ctx == (TCHmacState_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_hmac_final(uint8_t *tag, unsigned int taglen, TCHmacState_t ctx) {
+  /* input sanity check: */
+  if (tag == (uint8_t *)0 || taglen != TC_SHA256_DIGEST_SIZE || ctx == (TCHmacState_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    (void)tc_sha256_final(tag, &ctx->hash_state);
+  (void)tc_sha256_final(tag, &ctx->hash_state);
 
-    (void)tc_sha256_init(&ctx->hash_state);
-    (void)tc_sha256_update(&ctx->hash_state,
-                           &ctx->key[TC_SHA256_BLOCK_SIZE],
-                           TC_SHA256_BLOCK_SIZE);
-    (void)tc_sha256_update(&ctx->hash_state, tag, TC_SHA256_DIGEST_SIZE);
-    (void)tc_sha256_final(tag, &ctx->hash_state);
+  (void)tc_sha256_init(&ctx->hash_state);
+  (void)tc_sha256_update(&ctx->hash_state, &ctx->key[TC_SHA256_BLOCK_SIZE], TC_SHA256_BLOCK_SIZE);
+  (void)tc_sha256_update(&ctx->hash_state, tag, TC_SHA256_DIGEST_SIZE);
+  (void)tc_sha256_final(tag, &ctx->hash_state);
 
-    /* destroy the current state */
-    _set(ctx, 0, sizeof(*ctx));
+  /* destroy the current state */
+  _set(ctx, 0, sizeof(*ctx));
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c
index 8ef3c0c2b..3fe120442 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/hmac_prng.c
@@ -31,8 +31,8 @@
  */
 
 #include "hmac_prng.h"
-#include "hmac.h"
 #include "constants.h"
+#include "hmac.h"
 #include "utils.h"
 
 /*
@@ -75,156 +75,133 @@ static const unsigned int MAX_OUT = (1 << 19);
 /*
  * Assumes: prng != NULL
  */
-static void update(TCHmacPrng_t prng, const uint8_t *data, unsigned int datalen, const uint8_t *additional_data, unsigned int additional_datalen)
-{
-    const uint8_t separator0 = 0x00;
-    const uint8_t separator1 = 0x01;
+static void update(TCHmacPrng_t prng, const uint8_t *data, unsigned int datalen, const uint8_t *additional_data, unsigned int additional_datalen) {
+  const uint8_t separator0 = 0x00;
+  const uint8_t separator1 = 0x01;
 
-    /* configure the new prng key into the prng's instance of hmac */
-    tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+  /* configure the new prng key into the prng's instance of hmac */
+  tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
 
-    /* use current state, e and separator 0 to compute a new prng key: */
-    (void)tc_hmac_init(&prng->h);
-    (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
-    (void)tc_hmac_update(&prng->h, &separator0, sizeof(separator0));
+  /* use current state, e and separator 0 to compute a new prng key: */
+  (void)tc_hmac_init(&prng->h);
+  (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
+  (void)tc_hmac_update(&prng->h, &separator0, sizeof(separator0));
 
-    if (data && datalen)
-        (void)tc_hmac_update(&prng->h, data, datalen);
-    if (additional_data && additional_datalen)
-        (void)tc_hmac_update(&prng->h, additional_data, additional_datalen);
+  if (data && datalen)
+    (void)tc_hmac_update(&prng->h, data, datalen);
+  if (additional_data && additional_datalen)
+    (void)tc_hmac_update(&prng->h, additional_data, additional_datalen);
 
-    (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h);
+  (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h);
 
-    /* configure the new prng key into the prng's instance of hmac */
-    (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+  /* configure the new prng key into the prng's instance of hmac */
+  (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
 
-    /* use the new key to compute a new state variable v */
-    (void)tc_hmac_init(&prng->h);
-    (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
-    (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
+  /* use the new key to compute a new state variable v */
+  (void)tc_hmac_init(&prng->h);
+  (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
+  (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
 
-    if (data == 0 || datalen == 0)
-        return;
+  if (data == 0 || datalen == 0)
+    return;
 
-    /* configure the new prng key into the prng's instance of hmac */
-    tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+  /* configure the new prng key into the prng's instance of hmac */
+  tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
 
-    /* use current state, e and separator 1 to compute a new prng key: */
-    (void)tc_hmac_init(&prng->h);
-    (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
-    (void)tc_hmac_update(&prng->h, &separator1, sizeof(separator1));
-    (void)tc_hmac_update(&prng->h, data, datalen);
-    if (additional_data && additional_datalen)
-        (void)tc_hmac_update(&prng->h, additional_data, additional_datalen);
-    (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h);
+  /* use current state, e and separator 1 to compute a new prng key: */
+  (void)tc_hmac_init(&prng->h);
+  (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
+  (void)tc_hmac_update(&prng->h, &separator1, sizeof(separator1));
+  (void)tc_hmac_update(&prng->h, data, datalen);
+  if (additional_data && additional_datalen)
+    (void)tc_hmac_update(&prng->h, additional_data, additional_datalen);
+  (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h);
 
-    /* configure the new prng key into the prng's instance of hmac */
-    (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+  /* configure the new prng key into the prng's instance of hmac */
+  (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
 
-    /* use the new key to compute a new state variable v */
-    (void)tc_hmac_init(&prng->h);
-    (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
-    (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
+  /* use the new key to compute a new state variable v */
+  (void)tc_hmac_init(&prng->h);
+  (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
+  (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
 }
 
-int tc_hmac_prng_init(TCHmacPrng_t prng,
-                      const uint8_t *personalization,
-                      unsigned int plen)
-{
-    /* input sanity check: */
-    if (prng == (TCHmacPrng_t)0 ||
-        personalization == (uint8_t *)0 ||
-        plen > MAX_PLEN) {
-        return TC_CRYPTO_FAIL;
-    }
+int tc_hmac_prng_init(TCHmacPrng_t prng, const uint8_t *personalization, unsigned int plen) {
+  /* input sanity check: */
+  if (prng == (TCHmacPrng_t)0 || personalization == (uint8_t *)0 || plen > MAX_PLEN) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    /* put the generator into a known state: */
-    _set(prng->key, 0x00, sizeof(prng->key));
-    _set(prng->v, 0x01, sizeof(prng->v));
+  /* put the generator into a known state: */
+  _set(prng->key, 0x00, sizeof(prng->key));
+  _set(prng->v, 0x01, sizeof(prng->v));
 
-    update(prng, personalization, plen, 0, 0);
+  update(prng, personalization, plen, 0, 0);
 
-    /* force a reseed before allowing tc_hmac_prng_generate to succeed: */
-    prng->countdown = 0;
+  /* force a reseed before allowing tc_hmac_prng_generate to succeed: */
+  prng->countdown = 0;
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_hmac_prng_reseed(TCHmacPrng_t prng,
-                        const uint8_t *seed,
-                        unsigned int seedlen,
-                        const uint8_t *additional_input,
-                        unsigned int additionallen)
-{
-    /* input sanity check: */
-    if (prng == (TCHmacPrng_t)0 ||
-        seed == (const uint8_t *)0 ||
-        seedlen < MIN_SLEN ||
-        seedlen > MAX_SLEN) {
-        return TC_CRYPTO_FAIL;
-    }
-
-    if (additional_input != (const uint8_t *)0) {
-        /*
-		 * Abort if additional_input is provided but has inappropriate
-		 * length
-		 */
-        if (additionallen == 0 ||
-            additionallen > MAX_ALEN) {
-            return TC_CRYPTO_FAIL;
-        } else {
-            /* call update for the seed and additional_input */
-            update(prng, seed, seedlen, additional_input, additionallen);
-        }
+int tc_hmac_prng_reseed(TCHmacPrng_t prng, const uint8_t *seed, unsigned int seedlen, const uint8_t *additional_input, unsigned int additionallen) {
+  /* input sanity check: */
+  if (prng == (TCHmacPrng_t)0 || seed == (const uint8_t *)0 || seedlen < MIN_SLEN || seedlen > MAX_SLEN) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  if (additional_input != (const uint8_t *)0) {
+    /*
+     * Abort if additional_input is provided but has inappropriate
+     * length
+     */
+    if (additionallen == 0 || additionallen > MAX_ALEN) {
+      return TC_CRYPTO_FAIL;
     } else {
-        /* call update only for the seed */
-        update(prng, seed, seedlen, 0, 0);
+      /* call update for the seed and additional_input */
+      update(prng, seed, seedlen, additional_input, additionallen);
     }
+  } else {
+    /* call update only for the seed */
+    update(prng, seed, seedlen, 0, 0);
+  }
 
-    /* ... and enable hmac_prng_generate */
-    prng->countdown = MAX_GENS;
+  /* ... and enable hmac_prng_generate */
+  prng->countdown = MAX_GENS;
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_hmac_prng_generate(uint8_t *out, unsigned int outlen, TCHmacPrng_t prng)
-{
-    unsigned int bufferlen;
-
-    /* input sanity check: */
-    if (out == (uint8_t *)0 ||
-        prng == (TCHmacPrng_t)0 ||
-        outlen == 0 ||
-        outlen > MAX_OUT) {
-        return TC_CRYPTO_FAIL;
-    } else if (prng->countdown == 0) {
-        return TC_HMAC_PRNG_RESEED_REQ;
-    }
+int tc_hmac_prng_generate(uint8_t *out, unsigned int outlen, TCHmacPrng_t prng) {
+  unsigned int bufferlen;
 
-    prng->countdown--;
+  /* input sanity check: */
+  if (out == (uint8_t *)0 || prng == (TCHmacPrng_t)0 || outlen == 0 || outlen > MAX_OUT) {
+    return TC_CRYPTO_FAIL;
+  } else if (prng->countdown == 0) {
+    return TC_HMAC_PRNG_RESEED_REQ;
+  }
 
-    while (outlen != 0) {
-        /* configure the new prng key into the prng's instance of hmac */
-        tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+  prng->countdown--;
 
-        /* operate HMAC in OFB mode to create "random" outputs */
-        (void)tc_hmac_init(&prng->h);
-        (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
-        (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
+  while (outlen != 0) {
+    /* configure the new prng key into the prng's instance of hmac */
+    tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
 
-        bufferlen = (TC_SHA256_DIGEST_SIZE > outlen) ?
-                        outlen :
-                        TC_SHA256_DIGEST_SIZE;
-        (void)_copy(out, bufferlen, prng->v, bufferlen);
+    /* operate HMAC in OFB mode to create "random" outputs */
+    (void)tc_hmac_init(&prng->h);
+    (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v));
+    (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h);
 
-        out += bufferlen;
-        outlen = (outlen > TC_SHA256_DIGEST_SIZE) ?
-                     (outlen - TC_SHA256_DIGEST_SIZE) :
-                     0;
-    }
+    bufferlen = (TC_SHA256_DIGEST_SIZE > outlen) ? outlen : TC_SHA256_DIGEST_SIZE;
+    (void)_copy(out, bufferlen, prng->v, bufferlen);
+
+    out += bufferlen;
+    outlen = (outlen > TC_SHA256_DIGEST_SIZE) ? (outlen - TC_SHA256_DIGEST_SIZE) : 0;
+  }
 
-    /* block future PRNG compromises from revealing past state */
-    update(prng, 0, 0, 0, 0);
+  /* block future PRNG compromises from revealing past state */
+  update(prng, 0, 0, 0, 0);
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c
index 57952104c..1dab36071 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/sha256.c
@@ -36,103 +36,96 @@
 
 static void compress(unsigned int *iv, const uint8_t *data);
 
-int tc_sha256_init(TCSha256State_t s)
-{
-    /* input sanity check: */
-    if (s == (TCSha256State_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
-
-    /*
-	 * Setting the initial state values.
-	 * These values correspond to the first 32 bits of the fractional parts
-	 * of the square roots of the first 8 primes: 2, 3, 5, 7, 11, 13, 17
-	 * and 19.
-	 */
-    _set((uint8_t *)s, 0x00, sizeof(*s));
-    s->iv[0] = 0x6a09e667;
-    s->iv[1] = 0xbb67ae85;
-    s->iv[2] = 0x3c6ef372;
-    s->iv[3] = 0xa54ff53a;
-    s->iv[4] = 0x510e527f;
-    s->iv[5] = 0x9b05688c;
-    s->iv[6] = 0x1f83d9ab;
-    s->iv[7] = 0x5be0cd19;
-
-    return TC_CRYPTO_SUCCESS;
+int tc_sha256_init(TCSha256State_t s) {
+  /* input sanity check: */
+  if (s == (TCSha256State_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
+
+  /*
+   * Setting the initial state values.
+   * These values correspond to the first 32 bits of the fractional parts
+   * of the square roots of the first 8 primes: 2, 3, 5, 7, 11, 13, 17
+   * and 19.
+   */
+  _set((uint8_t *)s, 0x00, sizeof(*s));
+  s->iv[0] = 0x6a09e667;
+  s->iv[1] = 0xbb67ae85;
+  s->iv[2] = 0x3c6ef372;
+  s->iv[3] = 0xa54ff53a;
+  s->iv[4] = 0x510e527f;
+  s->iv[5] = 0x9b05688c;
+  s->iv[6] = 0x1f83d9ab;
+  s->iv[7] = 0x5be0cd19;
+
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_sha256_update(TCSha256State_t s, const uint8_t *data, size_t datalen)
-{
-    /* input sanity check: */
-    if (s == (TCSha256State_t)0 ||
-        data == (void *)0) {
-        return TC_CRYPTO_FAIL;
-    } else if (datalen == 0) {
-        return TC_CRYPTO_SUCCESS;
-    }
-
-    while (datalen-- > 0) {
-        s->leftover[s->leftover_offset++] = *(data++);
-        if (s->leftover_offset >= TC_SHA256_BLOCK_SIZE) {
-            compress(s->iv, s->leftover);
-            s->leftover_offset = 0;
-            s->bits_hashed += (TC_SHA256_BLOCK_SIZE << 3);
-        }
+int tc_sha256_update(TCSha256State_t s, const uint8_t *data, size_t datalen) {
+  /* input sanity check: */
+  if (s == (TCSha256State_t)0 || data == (void *)0) {
+    return TC_CRYPTO_FAIL;
+  } else if (datalen == 0) {
+    return TC_CRYPTO_SUCCESS;
+  }
+
+  while (datalen-- > 0) {
+    s->leftover[s->leftover_offset++] = *(data++);
+    if (s->leftover_offset >= TC_SHA256_BLOCK_SIZE) {
+      compress(s->iv, s->leftover);
+      s->leftover_offset = 0;
+      s->bits_hashed += (TC_SHA256_BLOCK_SIZE << 3);
     }
+  }
 
-    return TC_CRYPTO_SUCCESS;
+  return TC_CRYPTO_SUCCESS;
 }
 
-int tc_sha256_final(uint8_t *digest, TCSha256State_t s)
-{
-    unsigned int i;
+int tc_sha256_final(uint8_t *digest, TCSha256State_t s) {
+  unsigned int i;
 
-    /* input sanity check: */
-    if (digest == (uint8_t *)0 ||
-        s == (TCSha256State_t)0) {
-        return TC_CRYPTO_FAIL;
-    }
+  /* input sanity check: */
+  if (digest == (uint8_t *)0 || s == (TCSha256State_t)0) {
+    return TC_CRYPTO_FAIL;
+  }
 
-    s->bits_hashed += (s->leftover_offset << 3);
-
-    s->leftover[s->leftover_offset++] = 0x80; /* always room for one byte */
-    if (s->leftover_offset > (sizeof(s->leftover) - 8)) {
-        /* there is not room for all the padding in this block */
-        _set(s->leftover + s->leftover_offset, 0x00,
-             sizeof(s->leftover) - s->leftover_offset);
-        compress(s->iv, s->leftover);
-        s->leftover_offset = 0;
-    }
+  s->bits_hashed += (s->leftover_offset << 3);
 
-    /* add the padding and the length in big-Endian format */
-    _set(s->leftover + s->leftover_offset, 0x00,
-         sizeof(s->leftover) - 8 - s->leftover_offset);
-    s->leftover[sizeof(s->leftover) - 1] = (uint8_t)(s->bits_hashed);
-    s->leftover[sizeof(s->leftover) - 2] = (uint8_t)(s->bits_hashed >> 8);
-    s->leftover[sizeof(s->leftover) - 3] = (uint8_t)(s->bits_hashed >> 16);
-    s->leftover[sizeof(s->leftover) - 4] = (uint8_t)(s->bits_hashed >> 24);
-    s->leftover[sizeof(s->leftover) - 5] = (uint8_t)(s->bits_hashed >> 32);
-    s->leftover[sizeof(s->leftover) - 6] = (uint8_t)(s->bits_hashed >> 40);
-    s->leftover[sizeof(s->leftover) - 7] = (uint8_t)(s->bits_hashed >> 48);
-    s->leftover[sizeof(s->leftover) - 8] = (uint8_t)(s->bits_hashed >> 56);
-
-    /* hash the padding and length */
+  s->leftover[s->leftover_offset++] = 0x80; /* always room for one byte */
+  if (s->leftover_offset > (sizeof(s->leftover) - 8)) {
+    /* there is not room for all the padding in this block */
+    _set(s->leftover + s->leftover_offset, 0x00, sizeof(s->leftover) - s->leftover_offset);
     compress(s->iv, s->leftover);
-
-    /* copy the iv out to digest */
-    for (i = 0; i < TC_SHA256_STATE_BLOCKS; ++i) {
-        unsigned int t = *((unsigned int *)&s->iv[i]);
-        *digest++ = (uint8_t)(t >> 24);
-        *digest++ = (uint8_t)(t >> 16);
-        *digest++ = (uint8_t)(t >> 8);
-        *digest++ = (uint8_t)(t);
-    }
-
-    /* destroy the current state */
-    _set(s, 0, sizeof(*s));
-
-    return TC_CRYPTO_SUCCESS;
+    s->leftover_offset = 0;
+  }
+
+  /* add the padding and the length in big-Endian format */
+  _set(s->leftover + s->leftover_offset, 0x00, sizeof(s->leftover) - 8 - s->leftover_offset);
+  s->leftover[sizeof(s->leftover) - 1] = (uint8_t)(s->bits_hashed);
+  s->leftover[sizeof(s->leftover) - 2] = (uint8_t)(s->bits_hashed >> 8);
+  s->leftover[sizeof(s->leftover) - 3] = (uint8_t)(s->bits_hashed >> 16);
+  s->leftover[sizeof(s->leftover) - 4] = (uint8_t)(s->bits_hashed >> 24);
+  s->leftover[sizeof(s->leftover) - 5] = (uint8_t)(s->bits_hashed >> 32);
+  s->leftover[sizeof(s->leftover) - 6] = (uint8_t)(s->bits_hashed >> 40);
+  s->leftover[sizeof(s->leftover) - 7] = (uint8_t)(s->bits_hashed >> 48);
+  s->leftover[sizeof(s->leftover) - 8] = (uint8_t)(s->bits_hashed >> 56);
+
+  /* hash the padding and length */
+  compress(s->iv, s->leftover);
+
+  /* copy the iv out to digest */
+  for (i = 0; i < TC_SHA256_STATE_BLOCKS; ++i) {
+    unsigned int t = *((unsigned int *)&s->iv[i]);
+    *digest++      = (uint8_t)(t >> 24);
+    *digest++      = (uint8_t)(t >> 16);
+    *digest++      = (uint8_t)(t >> 8);
+    *digest++      = (uint8_t)(t);
+  }
+
+  /* destroy the current state */
+  _set(s, 0, sizeof(*s));
+
+  return TC_CRYPTO_SUCCESS;
 }
 
 /*
@@ -140,24 +133,13 @@ int tc_sha256_final(uint8_t *digest, TCSha256State_t s)
  * These values correspond to the first 32 bits of the fractional parts of the
  * cube roots of the first 64 primes between 2 and 311.
  */
-static const unsigned int k256[64] = {
-    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
-    0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
-    0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
-    0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
-    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
-    0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
-    0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
-    0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
-    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
-    0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
-    0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
-};
-
-static inline unsigned int ROTR(unsigned int a, unsigned int n)
-{
-    return (((a) >> n) | ((a) << (32 - n)));
-}
+static const unsigned int k256[64] = {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74,
+                                      0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d,
+                                      0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e,
+                                      0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
+                                      0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
+
+static inline unsigned int ROTR(unsigned int a, unsigned int n) { return (((a) >> n) | ((a) << (32 - n))); }
 
 #define Sigma0(a) (ROTR((a), 2) ^ ROTR((a), 13) ^ ROTR((a), 22))
 #define Sigma1(a) (ROTR((a), 6) ^ ROTR((a), 11) ^ ROTR((a), 25))
@@ -167,75 +149,73 @@ static inline unsigned int ROTR(unsigned int a, unsigned int n)
 #define Ch(a, b, c)  (((a) & (b)) ^ ((~(a)) & (c)))
 #define Maj(a, b, c) (((a) & (b)) ^ ((a) & (c)) ^ ((b) & (c)))
 
-static inline unsigned int BigEndian(const uint8_t **c)
-{
-    unsigned int n = 0;
+static inline unsigned int BigEndian(const uint8_t **c) {
+  unsigned int n = 0;
 
-    n = (((unsigned int)(*((*c)++))) << 24);
-    n |= ((unsigned int)(*((*c)++)) << 16);
-    n |= ((unsigned int)(*((*c)++)) << 8);
-    n |= ((unsigned int)(*((*c)++)));
-    return n;
+  n = (((unsigned int)(*((*c)++))) << 24);
+  n |= ((unsigned int)(*((*c)++)) << 16);
+  n |= ((unsigned int)(*((*c)++)) << 8);
+  n |= ((unsigned int)(*((*c)++)));
+  return n;
 }
 
-static void compress(unsigned int *iv, const uint8_t *data)
-{
-    unsigned int a, b, c, d, e, f, g, h;
-    unsigned int s0, s1;
-    unsigned int t1, t2;
-    unsigned int work_space[16];
-    unsigned int n;
-    unsigned int i;
-
-    a = iv[0];
-    b = iv[1];
-    c = iv[2];
-    d = iv[3];
-    e = iv[4];
-    f = iv[5];
-    g = iv[6];
-    h = iv[7];
-
-    for (i = 0; i < 16; ++i) {
-        n = BigEndian(&data);
-        t1 = work_space[i] = n;
-        t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i];
-        t2 = Sigma0(a) + Maj(a, b, c);
-        h = g;
-        g = f;
-        f = e;
-        e = d + t1;
-        d = c;
-        c = b;
-        b = a;
-        a = t1 + t2;
-    }
-
-    for (; i < 64; ++i) {
-        s0 = work_space[(i + 1) & 0x0f];
-        s0 = sigma0(s0);
-        s1 = work_space[(i + 14) & 0x0f];
-        s1 = sigma1(s1);
-
-        t1 = work_space[i & 0xf] += s0 + s1 + work_space[(i + 9) & 0xf];
-        t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i];
-        t2 = Sigma0(a) + Maj(a, b, c);
-        h = g;
-        g = f;
-        f = e;
-        e = d + t1;
-        d = c;
-        c = b;
-        b = a;
-        a = t1 + t2;
-    }
-
-    iv[0] += a;
-    iv[1] += b;
-    iv[2] += c;
-    iv[3] += d;
-    iv[4] += e;
-    iv[5] += f;
-    iv[6] += g;
-    iv[7] += h;
+static void compress(unsigned int *iv, const uint8_t *data) {
+  unsigned int a, b, c, d, e, f, g, h;
+  unsigned int s0, s1;
+  unsigned int t1, t2;
+  unsigned int work_space[16];
+  unsigned int n;
+  unsigned int i;
+
+  a = iv[0];
+  b = iv[1];
+  c = iv[2];
+  d = iv[3];
+  e = iv[4];
+  f = iv[5];
+  g = iv[6];
+  h = iv[7];
+
+  for (i = 0; i < 16; ++i) {
+    n  = BigEndian(&data);
+    t1 = work_space[i] = n;
+    t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i];
+    t2 = Sigma0(a) + Maj(a, b, c);
+    h  = g;
+    g  = f;
+    f  = e;
+    e  = d + t1;
+    d  = c;
+    c  = b;
+    b  = a;
+    a  = t1 + t2;
+  }
+
+  for (; i < 64; ++i) {
+    s0 = work_space[(i + 1) & 0x0f];
+    s0 = sigma0(s0);
+    s1 = work_space[(i + 14) & 0x0f];
+    s1 = sigma1(s1);
+
+    t1 = work_space[i & 0xf] += s0 + s1 + work_space[(i + 9) & 0xf];
+    t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i];
+    t2 = Sigma0(a) + Maj(a, b, c);
+    h  = g;
+    g  = f;
+    f  = e;
+    e  = d + t1;
+    d  = c;
+    c  = b;
+    b  = a;
+    a  = t1 + t2;
+  }
+
+  iv[0] += a;
+  iv[1] += b;
+  iv[2] += c;
+  iv[3] += d;
+  iv[4] += e;
+  iv[5] += f;
+  iv[6] += g;
+  iv[7] += h;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/utils.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/utils.c
index 137702a86..2cef6b05b 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/utils.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/utils.c
@@ -37,38 +37,29 @@
 
 #define MASK_TWENTY_SEVEN 0x1b
 
-unsigned int _copy(uint8_t *to, unsigned int to_len,
-                   const uint8_t *from, unsigned int from_len)
-{
-    if (from_len <= to_len) {
-        (void)memcpy(to, from, from_len);
-        return from_len;
-    } else {
-        return TC_CRYPTO_FAIL;
-    }
+unsigned int _copy(uint8_t *to, unsigned int to_len, const uint8_t *from, unsigned int from_len) {
+  if (from_len <= to_len) {
+    (void)memcpy(to, from, from_len);
+    return from_len;
+  } else {
+    return TC_CRYPTO_FAIL;
+  }
 }
 
-void _set(void *to, uint8_t val, unsigned int len)
-{
-    (void)memset(to, val, len);
-}
+void _set(void *to, uint8_t val, unsigned int len) { (void)memset(to, val, len); }
 
 /*
  * Doubles the value of a byte for values up to 127.
  */
-uint8_t _double_byte(uint8_t a)
-{
-    return ((a << 1) ^ ((a >> 7) * MASK_TWENTY_SEVEN));
-}
+uint8_t _double_byte(uint8_t a) { return ((a << 1) ^ ((a >> 7) * MASK_TWENTY_SEVEN)); }
 
-int _compare(const uint8_t *a, const uint8_t *b, size_t size)
-{
-    const uint8_t *tempa = a;
-    const uint8_t *tempb = b;
-    uint8_t result = 0;
+int _compare(const uint8_t *a, const uint8_t *b, size_t size) {
+  const uint8_t *tempa  = a;
+  const uint8_t *tempb  = b;
+  uint8_t        result = 0;
 
-    for (unsigned int i = 0; i < size; i++) {
-        result |= tempa[i] ^ tempb[i];
-    }
-    return result;
+  for (unsigned int i = 0; i < size; i++) {
+    result |= tempa[i] ^ tempb[i];
+  }
+  return result;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/utils.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/utils.c
index bde339265..76071e3f3 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/utils.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/utils.c
@@ -1,132 +1,125 @@
 /*****************************************************************************************
-*
-* @file utils.c
-*
-* @brief entry
-*
-* Copyright (C) Bouffalo Lab 2019
-*
-* History: 2019-11 crealted by Lanlan Gong @ Shanghai
-*
-*****************************************************************************************/
-#include 
+ *
+ * @file utils.c
+ *
+ * @brief entry
+ *
+ * Copyright (C) Bouffalo Lab 2019
+ *
+ * History: 2019-11 crealted by Lanlan Gong @ Shanghai
+ *
+ *****************************************************************************************/
 #include 
+#include 
 #include 
 
-void reverse_bytearray(uint8_t *src, uint8_t *result, int array_size)
-{
-    for (int i = 0; i < array_size; i++) {
-        result[array_size - i - 1] = src[i];
-    }
+void reverse_bytearray(uint8_t *src, uint8_t *result, int array_size) {
+  for (int i = 0; i < array_size; i++) {
+    result[array_size - i - 1] = src[i];
+  }
 }
 
-unsigned int find_msb_set(uint32_t data)
-{
-    uint32_t count = 0;
-    uint32_t mask = 0x80000000;
+unsigned int find_msb_set(uint32_t data) {
+  uint32_t count = 0;
+  uint32_t mask  = 0x80000000;
 
-    if (!data) {
-        return 0;
-    }
-    while ((data & mask) == 0) {
-        count += 1u;
-        mask = mask >> 1u;
-    }
-    return (32 - count);
+  if (!data) {
+    return 0;
+  }
+  while ((data & mask) == 0) {
+    count += 1u;
+    mask = mask >> 1u;
+  }
+  return (32 - count);
 }
 
-unsigned int find_lsb_set(uint32_t data)
-{
-    uint32_t count = 0;
-    uint32_t mask = 0x00000001;
+unsigned int find_lsb_set(uint32_t data) {
+  uint32_t count = 0;
+  uint32_t mask  = 0x00000001;
 
-    if (!data) {
-        return 0;
-    }
-    while ((data & mask) == 0) {
-        count += 1u;
-        mask = mask << 1u;
-    }
-    return (1 + count);
+  if (!data) {
+    return 0;
+  }
+  while ((data & mask) == 0) {
+    count += 1u;
+    mask = mask << 1u;
+  }
+  return (1 + count);
 }
 
-int char2hex(char c, uint8_t *x)
-{
-    if (c >= '0' && c <= '9') {
-        *x = c - '0';
-    } else if (c >= 'a' && c <= 'f') {
-        *x = c - 'a' + 10;
-    } else if (c >= 'A' && c <= 'F') {
-        *x = c - 'A' + 10;
-    } else {
-        return -1;
-    }
-
-    return 0;
+int char2hex(char c, uint8_t *x) {
+  if (c >= '0' && c <= '9') {
+    *x = c - '0';
+  } else if (c >= 'a' && c <= 'f') {
+    *x = c - 'a' + 10;
+  } else if (c >= 'A' && c <= 'F') {
+    *x = c - 'A' + 10;
+  } else {
+    return -1;
+  }
+
+  return 0;
 }
 
-int hex2char(uint8_t x, char *c)
-{
-    if (x <= 9) {
-        *c = x + '0';
-    } else if (x <= 15) {
-        *c = x - 10 + 'a';
-    } else {
-        return -1;
-    }
+int hex2char(uint8_t x, char *c) {
+  if (x <= 9) {
+    *c = x + '0';
+  } else if (x <= 15) {
+    *c = x - 10 + 'a';
+  } else {
+    return -1;
+  }
 
-    return 0;
+  return 0;
 }
 
-size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen)
-{
-    if ((hexlen + 1) < buflen * 2) {
-        return 0;
-    }
+size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen) {
+  if ((hexlen + 1) < buflen * 2) {
+    return 0;
+  }
 
-    for (size_t i = 0; i < buflen; i++) {
-        if (hex2char(buf[i] >> 4, &hex[2 * i]) < 0) {
-            return 0;
-        }
-        if (hex2char(buf[i] & 0xf, &hex[2 * i + 1]) < 0) {
-            return 0;
-        }
+  for (size_t i = 0; i < buflen; i++) {
+    if (hex2char(buf[i] >> 4, &hex[2 * i]) < 0) {
+      return 0;
+    }
+    if (hex2char(buf[i] & 0xf, &hex[2 * i + 1]) < 0) {
+      return 0;
     }
+  }
 
-    hex[2 * buflen] = '\0';
-    return 2 * buflen;
+  hex[2 * buflen] = '\0';
+  return 2 * buflen;
 }
 
-size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen)
-{
-    uint8_t dec;
+size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen) {
+  uint8_t dec;
 
-    if (buflen < hexlen / 2 + hexlen % 2) {
-        return 0;
-    }
+  if (buflen < hexlen / 2 + hexlen % 2) {
+    return 0;
+  }
 
-    /* if hexlen is uneven, insert leading zero nibble */
-    if (hexlen % 2) {
-        if (char2hex(hex[0], &dec) < 0) {
-            return 0;
-        }
-        buf[0] = dec;
-        hex++;
-        buf++;
+  /* if hexlen is uneven, insert leading zero nibble */
+  if (hexlen % 2) {
+    if (char2hex(hex[0], &dec) < 0) {
+      return 0;
+    }
+    buf[0] = dec;
+    hex++;
+    buf++;
+  }
+
+  /* regular hex conversion */
+  for (size_t i = 0; i < hexlen / 2; i++) {
+    if (char2hex(hex[2 * i], &dec) < 0) {
+      return 0;
     }
+    buf[i] = dec << 4;
 
-    /* regular hex conversion */
-    for (size_t i = 0; i < hexlen / 2; i++) {
-        if (char2hex(hex[2 * i], &dec) < 0) {
-            return 0;
-        }
-        buf[i] = dec << 4;
-
-        if (char2hex(hex[2 * i + 1], &dec) < 0) {
-            return 0;
-        }
-        buf[i] += dec;
+    if (char2hex(hex[2 * i + 1], &dec) < 0) {
+      return 0;
     }
+    buf[i] += dec;
+  }
 
-    return hexlen / 2 + hexlen % 2;
+  return hexlen / 2 + hexlen % 2;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c
index f8f72ad6f..722c6f035 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/work_q.c
@@ -11,9 +11,9 @@
  * Workqueue support functions
  */
 
-#include 
-#include 
 #include "errno.h"
+#include 
+#include 
 
 struct k_thread work_q_thread;
 #if !defined(BFLB_BLE)
@@ -21,328 +21,309 @@ static BT_STACK_NOINIT(work_q_stack, CONFIG_BT_WORK_QUEUE_STACK_SIZE);
 #endif
 struct k_work_q g_work_queue_main;
 
-static void k_work_submit_to_queue(struct k_work_q *work_q,
-                                   struct k_work *work)
-{
-    if (!atomic_test_and_set_bit(work->flags, K_WORK_STATE_PENDING)) {
-        k_fifo_put(&work_q->fifo, work);
-    }
+static void k_work_submit_to_queue(struct k_work_q *work_q, struct k_work *work) {
+  if (!atomic_test_and_set_bit(work->flags, K_WORK_STATE_PENDING)) {
+    k_fifo_put(&work_q->fifo, work);
+#if (BFLB_BT_CO_THREAD)
+    extern struct k_sem g_poll_sem;
+    k_sem_give(&g_poll_sem);
+#endif
+  }
 }
 
 #if defined(BFLB_BLE)
-static void work_queue_main(void *p1)
-{
-    struct k_work *work;
-    UNUSED(p1);
-
-    while (1) {
-        work = k_fifo_get(&g_work_queue_main.fifo, K_FOREVER);
+#if (BFLB_BT_CO_THREAD)
+void handle_work_queue(void) {
+  struct k_work *work;
+  work = k_fifo_get(&g_work_queue_main.fifo, K_NO_WAIT);
+
+  if (atomic_test_and_clear_bit(work->flags, K_WORK_STATE_PENDING)) {
+    work->handler(work);
+  }
+}
+#else
+static void work_queue_main(void *p1) {
+  struct k_work *work;
+  UNUSED(p1);
 
-        if (atomic_test_and_clear_bit(work->flags, K_WORK_STATE_PENDING)) {
-            work->handler(work);
-        }
+  while (1) {
+    work = k_fifo_get(&g_work_queue_main.fifo, K_FOREVER);
 
-        k_yield();
+    if (atomic_test_and_clear_bit(work->flags, K_WORK_STATE_PENDING)) {
+      work->handler(work);
     }
+
+    k_yield();
+  }
 }
 
-int k_work_q_start(void)
-{
-    k_fifo_init(&g_work_queue_main.fifo, 20);
-    return k_thread_create(&work_q_thread, "work_q_thread",
-                           CONFIG_BT_WORK_QUEUE_STACK_SIZE,
-                           work_queue_main, CONFIG_BT_WORK_QUEUE_PRIO);
+int k_work_q_start(void) {
+  k_fifo_init(&g_work_queue_main.fifo, 20);
+  return k_thread_create(&work_q_thread, "work_q_thread", CONFIG_BT_WORK_QUEUE_STACK_SIZE, work_queue_main, CONFIG_BT_WORK_QUEUE_PRIO);
 }
+#endif
 
-int k_work_init(struct k_work *work, k_work_handler_t handler)
-{
-    ASSERT(work, "work is NULL");
+int k_work_init(struct k_work *work, k_work_handler_t handler) {
+  ASSERT(work, "work is NULL");
 
-    atomic_clear(work->flags);
-    work->handler = handler;
-    return 0;
+  atomic_clear(work->flags);
+  work->handler = handler;
+  return 0;
 }
 
-void k_work_submit(struct k_work *work)
-{
-    k_work_submit_to_queue(&g_work_queue_main, work);
-}
+void k_work_submit(struct k_work *work) { k_work_submit_to_queue(&g_work_queue_main, work); }
 
-static void work_timeout(void *timer)
-{
-    /* Parameter timer type is */
-    struct k_delayed_work *w = (struct k_delayed_work *)k_timer_get_id(timer);
-    if (w->work_q == NULL) {
-        return;
-    }
+static void work_timeout(void *timer) {
+  /* Parameter timer type is */
+  struct k_delayed_work *w = (struct k_delayed_work *)k_timer_get_id(timer);
+  if (w->work_q == NULL) {
+    return;
+  }
 
-    /* submit work to workqueue */
-    if (!atomic_test_bit(w->work.flags, K_WORK_STATE_PERIODIC)) {
-        k_work_submit_to_queue(w->work_q, &w->work);
-        /* detach from workqueue, for cancel to return appropriate status */
-        w->work_q = NULL;
-    } else {
-        /* For periodic timer, restart it.*/
-        k_timer_reset(&w->timer);
-        k_work_submit_to_queue(w->work_q, &w->work);
-    }
+  /* submit work to workqueue */
+  if (!atomic_test_bit(w->work.flags, K_WORK_STATE_PERIODIC)) {
+    k_work_submit_to_queue(w->work_q, &w->work);
+    /* detach from workqueue, for cancel to return appropriate status */
+    w->work_q = NULL;
+  } else {
+    /* For periodic timer, restart it.*/
+    k_timer_reset(&w->timer);
+    k_work_submit_to_queue(w->work_q, &w->work);
+  }
 }
 
-void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler)
-{
-    ASSERT(work, "delay work is NULL");
-    /* Added by bouffalolab */
-    k_work_init(&work->work, handler);
-    k_timer_init(&work->timer, work_timeout, work);
-    work->work_q = NULL;
+void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler) {
+  ASSERT(work, "delay work is NULL");
+  /* Added by bouffalolab */
+  k_work_init(&work->work, handler);
+  k_timer_init(&work->timer, work_timeout, work);
+  work->work_q = NULL;
 }
 
-static int k_delayed_work_submit_to_queue(struct k_work_q *work_q,
-                                          struct k_delayed_work *work,
-                                          uint32_t delay)
-{
-    int err;
+static int k_delayed_work_submit_to_queue(struct k_work_q *work_q, struct k_delayed_work *work, uint32_t delay) {
+  int err;
 
-    /* Work cannot be active in multiple queues */
-    if (work->work_q && work->work_q != work_q) {
-        err = -EADDRINUSE;
-        goto done;
-    }
+  /* Work cannot be active in multiple queues */
+  if (work->work_q && work->work_q != work_q) {
+    err = -EADDRINUSE;
+    goto done;
+  }
 
-    /* Cancel if work has been submitted */
-    if (work->work_q == work_q) {
-        err = k_delayed_work_cancel(work);
+  /* Cancel if work has been submitted */
+  if (work->work_q == work_q) {
+    err = k_delayed_work_cancel(work);
 
-        if (err < 0) {
-            goto done;
-        }
+    if (err < 0) {
+      goto done;
     }
+  }
 
-    if (!delay) {
-        /* Submit work if no ticks is 0 */
-        k_work_submit_to_queue(work_q, &work->work);
-        work->work_q = NULL;
-    } else {
-        /* Add timeout */
-        /* Attach workqueue so the timeout callback can submit it */
-        k_timer_start(&work->timer, delay);
-        work->work_q = work_q;
-    }
+  if (!delay) {
+    /* Submit work if no ticks is 0 */
+    k_work_submit_to_queue(work_q, &work->work);
+    work->work_q = NULL;
+  } else {
+    /* Add timeout */
+    /* Attach workqueue so the timeout callback can submit it */
+    k_timer_start(&work->timer, delay);
+    work->work_q = work_q;
+  }
 
-    err = 0;
+  err = 0;
 
 done:
-    return err;
+  return err;
 }
 
-int k_delayed_work_submit(struct k_delayed_work *work, uint32_t delay)
-{
-    atomic_clear_bit(work->work.flags, K_WORK_STATE_PERIODIC);
-    return k_delayed_work_submit_to_queue(&g_work_queue_main, work, delay);
+int k_delayed_work_submit(struct k_delayed_work *work, uint32_t delay) {
+  atomic_clear_bit(work->work.flags, K_WORK_STATE_PERIODIC);
+  return k_delayed_work_submit_to_queue(&g_work_queue_main, work, delay);
 }
 
 /* Added by bouffalolab */
-int k_delayed_work_submit_periodic(struct k_delayed_work *work, s32_t period)
-{
-    atomic_set_bit(work->work.flags, K_WORK_STATE_PERIODIC);
-    return k_delayed_work_submit_to_queue(&g_work_queue_main, work, period);
+int k_delayed_work_submit_periodic(struct k_delayed_work *work, s32_t period) {
+  atomic_set_bit(work->work.flags, K_WORK_STATE_PERIODIC);
+  return k_delayed_work_submit_to_queue(&g_work_queue_main, work, period);
 }
 
-int k_delayed_work_cancel(struct k_delayed_work *work)
-{
-    int err = 0;
+int k_delayed_work_cancel(struct k_delayed_work *work) {
+  int err = 0;
 
-    if (atomic_test_bit(work->work.flags, K_WORK_STATE_PENDING)) {
-        err = -EINPROGRESS;
-        goto exit;
-    }
+  if (atomic_test_bit(work->work.flags, K_WORK_STATE_PENDING)) {
+    err = -EINPROGRESS;
+    goto exit;
+  }
 
-    if (!work->work_q) {
-        err = -EINVAL;
-        goto exit;
-    }
+  if (!work->work_q) {
+    err = -EINVAL;
+    goto exit;
+  }
 
-    k_timer_stop(&work->timer);
-    work->work_q = NULL;
-    work->timer.timeout = 0;
-    work->timer.start_ms = 0;
+  k_timer_stop(&work->timer);
+  work->work_q         = NULL;
+  work->timer.timeout  = 0;
+  work->timer.start_ms = 0;
 
 exit:
-    return err;
+  return err;
 }
 
-s32_t k_delayed_work_remaining_get(struct k_delayed_work *work)
-{
-    int32_t remain;
-    k_timer_t *timer;
+s32_t k_delayed_work_remaining_get(struct k_delayed_work *work) {
+  int32_t    remain;
+  k_timer_t *timer;
 
-    if (work == NULL) {
-        return 0;
-    }
-
-    timer = &work->timer;
-    remain = timer->timeout - (k_now_ms() - timer->start_ms);
-    if (remain < 0) {
-        remain = 0;
-    }
-    return remain;
+  if (work == NULL) {
+    return 0;
+  }
+
+  timer  = &work->timer;
+  remain = timer->timeout - (k_now_ms() - timer->start_ms);
+  if (remain < 0) {
+    remain = 0;
+  }
+  return remain;
 }
 
-void k_delayed_work_del_timer(struct k_delayed_work *work)
-{
-    if (NULL == work || NULL == work->timer.timer.hdl)
-        return;
+void k_delayed_work_del_timer(struct k_delayed_work *work) {
+  if (NULL == work || NULL == work->timer.timer.hdl)
+    return;
 
-    k_timer_delete(&work->timer);
-    work->timer.timer.hdl = NULL;
+  k_timer_delete(&work->timer);
+  work->timer.timer.hdl = NULL;
 }
 
 /* Added by bouffalolab */
-int k_delayed_work_free(struct k_delayed_work *work)
-{
-    int err = 0;
+int k_delayed_work_free(struct k_delayed_work *work) {
+  int err = 0;
 
-    if (atomic_test_bit(work->work.flags, K_WORK_STATE_PENDING)) {
-        err = -EINPROGRESS;
-        goto exit;
-    }
+  if (atomic_test_bit(work->work.flags, K_WORK_STATE_PENDING)) {
+    err = -EINPROGRESS;
+    goto exit;
+  }
 
-    k_delayed_work_del_timer(work);
-    work->work_q = NULL;
-    work->timer.timeout = 0;
-    work->timer.start_ms = 0;
+  k_delayed_work_del_timer(work);
+  work->work_q         = NULL;
+  work->timer.timeout  = 0;
+  work->timer.start_ms = 0;
 
 exit:
-    return err;
+  return err;
 }
 
 #else
-static void work_q_main(void *work_q_ptr, void *p2, void *p3)
-{
-    struct k_work_q *work_q = work_q_ptr;
-
-    ARG_UNUSED(p2);
-    ARG_UNUSED(p3);
-
-    while (1) {
-        struct k_work *work;
-        k_work_handler_t handler;
-
-        work = k_queue_get(&work_q->queue, K_FOREVER);
-        if (!work) {
-            continue;
-        }
-
-        handler = work->handler;
-
-        /* Reset pending state so it can be resubmitted by handler */
-        if (atomic_test_and_clear_bit(work->flags,
-                                      K_WORK_STATE_PENDING)) {
-            handler(work);
-        }
-
-        /* Make sure we don't hog up the CPU if the FIFO never (or
-		 * very rarely) gets empty.
-		 */
-        k_yield();
+static void work_q_main(void *work_q_ptr, void *p2, void *p3) {
+  struct k_work_q *work_q = work_q_ptr;
+
+  ARG_UNUSED(p2);
+  ARG_UNUSED(p3);
+
+  while (1) {
+    struct k_work   *work;
+    k_work_handler_t handler;
+
+    work = k_queue_get(&work_q->queue, K_FOREVER);
+    if (!work) {
+      continue;
+    }
+
+    handler = work->handler;
+
+    /* Reset pending state so it can be resubmitted by handler */
+    if (atomic_test_and_clear_bit(work->flags, K_WORK_STATE_PENDING)) {
+      handler(work);
     }
+
+    /* Make sure we don't hog up the CPU if the FIFO never (or
+     * very rarely) gets empty.
+     */
+    k_yield();
+  }
 }
 
-void k_work_q_start(struct k_work_q *work_q, k_thread_stack_t *stack,
-                    size_t stack_size, int prio)
-{
-    k_queue_init(&work_q->queue, 20);
-    k_thread_create(&work_q->thread, stack, stack_size, work_q_main,
-                    work_q, 0, 0, prio, 0, 0);
-    _k_object_init(work_q);
+void k_work_q_start(struct k_work_q *work_q, k_thread_stack_t *stack, size_t stack_size, int prio) {
+  k_queue_init(&work_q->queue, 20);
+  k_thread_create(&work_q->thread, stack, stack_size, work_q_main, work_q, 0, 0, prio, 0, 0);
+  _k_object_init(work_q);
 }
 
 #ifdef CONFIG_SYS_CLOCK_EXISTS
-static void work_timeout(struct _timeout *t)
-{
-    struct k_delayed_work *w = CONTAINER_OF(t, struct k_delayed_work,
-                                            timeout);
+static void work_timeout(struct _timeout *t) {
+  struct k_delayed_work *w = CONTAINER_OF(t, struct k_delayed_work, timeout);
 
-    /* submit work to workqueue */
-    k_work_submit_to_queue(w->work_q, &w->work);
+  /* submit work to workqueue */
+  k_work_submit_to_queue(w->work_q, &w->work);
 }
 
-void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler)
-{
-    k_work_init(&work->work, handler);
-    _init_timeout(&work->timeout, work_timeout);
-    work->work_q = NULL;
+void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler) {
+  k_work_init(&work->work, handler);
+  _init_timeout(&work->timeout, work_timeout);
+  work->work_q = NULL;
 
-    _k_object_init(work);
+  _k_object_init(work);
 }
 
-int k_delayed_work_submit_to_queue(struct k_work_q *work_q,
-                                   struct k_delayed_work *work,
-                                   s32_t delay)
-{
-    unsigned int key = irq_lock();
-    int err;
-
-    /* Work cannot be active in multiple queues */
-    if (work->work_q && work->work_q != work_q) {
-        err = -EADDRINUSE;
-        goto done;
+int k_delayed_work_submit_to_queue(struct k_work_q *work_q, struct k_delayed_work *work, s32_t delay) {
+  unsigned int key = irq_lock();
+  int          err;
+
+  /* Work cannot be active in multiple queues */
+  if (work->work_q && work->work_q != work_q) {
+    err = -EADDRINUSE;
+    goto done;
+  }
+
+  /* Cancel if work has been submitted */
+  if (work->work_q == work_q) {
+    err = k_delayed_work_cancel(work);
+    if (err < 0) {
+      goto done;
     }
+  }
 
-    /* Cancel if work has been submitted */
-    if (work->work_q == work_q) {
-        err = k_delayed_work_cancel(work);
-        if (err < 0) {
-            goto done;
-        }
-    }
+  /* Attach workqueue so the timeout callback can submit it */
+  work->work_q = work_q;
 
-    /* Attach workqueue so the timeout callback can submit it */
-    work->work_q = work_q;
+  if (!delay) {
+    /* Submit work if no ticks is 0 */
+    k_work_submit_to_queue(work_q, &work->work);
+  } else {
+    /* Add timeout */
+    _add_timeout(NULL, &work->timeout, NULL, _TICK_ALIGN + _ms_to_ticks(delay));
+  }
 
-    if (!delay) {
-        /* Submit work if no ticks is 0 */
-        k_work_submit_to_queue(work_q, &work->work);
-    } else {
-        /* Add timeout */
-        _add_timeout(NULL, &work->timeout, NULL,
-                     _TICK_ALIGN + _ms_to_ticks(delay));
-    }
-
-    err = 0;
+  err = 0;
 
 done:
-    irq_unlock(key);
+  irq_unlock(key);
 
-    return err;
+  return err;
 }
 
-int k_delayed_work_cancel(struct k_delayed_work *work)
-{
-    unsigned int key = irq_lock();
+int k_delayed_work_cancel(struct k_delayed_work *work) {
+  unsigned int key = irq_lock();
 
-    if (!work->work_q) {
-        irq_unlock(key);
-        return -EINVAL;
-    }
-
-    if (k_work_pending(&work->work)) {
-        /* Remove from the queue if already submitted */
-        if (!k_queue_remove(&work->work_q->queue, &work->work)) {
-            irq_unlock(key);
-            return -EINVAL;
-        }
-    } else {
-        _abort_timeout(&work->timeout);
+  if (!work->work_q) {
+    irq_unlock(key);
+    return -EINVAL;
+  }
+
+  if (k_work_pending(&work->work)) {
+    /* Remove from the queue if already submitted */
+    if (!k_queue_remove(&work->work_q->queue, &work->work)) {
+      irq_unlock(key);
+      return -EINVAL;
     }
+  } else {
+    _abort_timeout(&work->timeout);
+  }
 
-    /* Detach from workqueue */
-    work->work_q = NULL;
+  /* Detach from workqueue */
+  work->work_q = NULL;
 
-    atomic_clear_bit(work->work.flags, K_WORK_STATE_PENDING);
-    irq_unlock(key);
+  atomic_clear_bit(work->work.flags, K_WORK_STATE_PENDING);
+  irq_unlock(key);
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_SYS_CLOCK_EXISTS */
 #endif /* BFLB_BLE */
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/hci_onchip/hci_driver.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/hci_onchip/hci_driver.c
index a992c5d1c..7cc42b9ba 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/hci_onchip/hci_driver.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/hci_onchip/hci_driver.c
@@ -10,20 +10,19 @@
 #include 
 
 #include 
-//#include 
-//#include 
-//#include 
-//#include 
-#include 
-#include 
+// #include 
+// #include 
+// #include 
+// #include 
+#include 
 
-#include 
-#include 
 #include 
+#include 
+#include 
 
 #include 
-#include 
 #include 
+#include 
 
 #ifdef CONFIG_CLOCK_CONTROL_NRF5
 #include 
@@ -32,35 +31,28 @@
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_DRIVER)
 #include "log.h"
 
-//#include "util/util.h"
-//#include "hal/ccm.h"
-//#include "hal/radio.h"
-//#include "ll_sw/pdu.h"
-//#include "ll_sw/ctrl.h"
+// #include "util/util.h"
+// #include "hal/ccm.h"
+// #include "hal/radio.h"
+// #include "ll_sw/pdu.h"
+// #include "ll_sw/ctrl.h"
 #include "hci_internal.h"
-//#include "init.h"
-//#include "hal/debug.h"
+// #include "init.h"
+// #include "hal/debug.h"
 #if defined(BFLB_BLE)
 #include "bl_hci_wrapper.h"
 #endif
 
-#define NODE_RX(_node) CONTAINER_OF(_node, struct radio_pdu_node_rx, \
-                                    hdr.onion.node)
+#define NODE_RX(_node) CONTAINER_OF(_node, struct radio_pdu_node_rx, hdr.onion.node)
 
 #if !defined(BFLB_BLE)
 static K_SEM_DEFINE(sem_prio_recv, 0, BT_UINT_MAX);
 #endif
 
 K_FIFO_DEFINE(recv_fifo);
-#if (BFLB_BLE_CO_THREAD)
-extern struct k_sem g_poll_sem;
-static int recv_fifo_count = 0;
-#endif
-
 #if !defined(BFLB_BLE)
 struct k_thread prio_recv_thread_data;
-static BT_STACK_NOINIT(prio_recv_thread_stack,
-                       CONFIG_BT_CTLR_RX_PRIO_STACK_SIZE);
+static BT_STACK_NOINIT(prio_recv_thread_stack, CONFIG_BT_CTLR_RX_PRIO_STACK_SIZE);
 #endif
 
 struct k_thread recv_thread_data;
@@ -74,487 +66,422 @@ static u32_t rx_ts;
 #endif
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-static struct k_poll_signal hbuf_signal =
-    K_POLL_SIGNAL_INITIALIZER(hbuf_signal);
-static sys_slist_t hbuf_pend;
-static s32_t hbuf_count;
+static struct k_poll_signal hbuf_signal = K_POLL_SIGNAL_INITIALIZER(hbuf_signal);
+static sys_slist_t          hbuf_pend;
+static s32_t                hbuf_count;
 #endif
 
 #if !defined(BFLB_BLE)
-static void prio_recv_thread(void *p1, void *p2, void *p3)
-{
-    while (1) {
-        struct radio_pdu_node_rx *node_rx;
-        u8_t num_cmplt;
-        u16_t handle;
-
-        while ((num_cmplt = radio_rx_get(&node_rx, &handle))) {
+static void prio_recv_thread(void *p1, void *p2, void *p3) {
+  while (1) {
+    struct radio_pdu_node_rx *node_rx;
+    u8_t                      num_cmplt;
+    u16_t                     handle;
+
+    while ((num_cmplt = radio_rx_get(&node_rx, &handle))) {
 #if defined(CONFIG_BT_CONN)
-            struct net_buf *buf;
+      struct net_buf *buf;
 
-            buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
-            hci_num_cmplt_encode(buf, handle, num_cmplt);
-            BT_DBG("Num Complete: 0x%04x:%u", handle, num_cmplt);
-            bt_recv_prio(buf);
-            k_yield();
+      buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
+      hci_num_cmplt_encode(buf, handle, num_cmplt);
+      BT_DBG("Num Complete: 0x%04x:%u", handle, num_cmplt);
+      bt_recv_prio(buf);
+      k_yield();
 #endif
-        }
+    }
 
-        if (node_rx) {
-            radio_rx_dequeue();
+    if (node_rx) {
+      radio_rx_dequeue();
 
-            BT_DBG("RX node enqueue");
-            k_fifo_put(&recv_fifo, node_rx);
+      BT_DBG("RX node enqueue");
+      k_fifo_put(&recv_fifo, node_rx);
 
-            continue;
-        }
+      continue;
+    }
 
-        BT_DBG("sem take...");
-        k_sem_take(&sem_prio_recv, K_FOREVER);
-        BT_DBG("sem taken");
+    BT_DBG("sem take...");
+    k_sem_take(&sem_prio_recv, K_FOREVER);
+    BT_DBG("sem taken");
 
 #if defined(CONFIG_INIT_STACKS)
-        if (k_uptime_get_32() - prio_ts > K_SECONDS(5)) {
-            STACK_ANALYZE("prio recv thread stack",
-                          prio_recv_thread_stack);
-            prio_ts = k_uptime_get_32();
-        }
-#endif
+    if (k_uptime_get_32() - prio_ts > K_SECONDS(5)) {
+      STACK_ANALYZE("prio recv thread stack", prio_recv_thread_stack);
+      prio_ts = k_uptime_get_32();
     }
+#endif
+  }
 }
 
-static inline struct net_buf *encode_node(struct radio_pdu_node_rx *node_rx,
-                                          s8_t class)
-{
-    struct net_buf *buf = NULL;
+static inline struct net_buf *encode_node(struct radio_pdu_node_rx *node_rx, s8_t class) {
+  struct net_buf *buf = NULL;
 
-    /* Check if we need to generate an HCI event or ACL data */
-    switch (class) {
-        case HCI_CLASS_EVT_DISCARDABLE:
-        case HCI_CLASS_EVT_REQUIRED:
-        case HCI_CLASS_EVT_CONNECTION:
-            if (class == HCI_CLASS_EVT_DISCARDABLE) {
-                buf = bt_buf_get_rx(BT_BUF_EVT, K_NO_WAIT);
-            } else {
-                buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
-            }
-            if (buf) {
-                hci_evt_encode(node_rx, buf);
-            }
-            break;
+  /* Check if we need to generate an HCI event or ACL data */
+  switch (class) {
+  case HCI_CLASS_EVT_DISCARDABLE:
+  case HCI_CLASS_EVT_REQUIRED:
+  case HCI_CLASS_EVT_CONNECTION:
+    if (class == HCI_CLASS_EVT_DISCARDABLE) {
+      buf = bt_buf_get_rx(BT_BUF_EVT, K_NO_WAIT);
+    } else {
+      buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
+    }
+    if (buf) {
+      hci_evt_encode(node_rx, buf);
+    }
+    break;
 #if defined(CONFIG_BT_CONN)
-        case HCI_CLASS_ACL_DATA:
-            /* generate ACL data */
-            buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_FOREVER);
-            hci_acl_encode(node_rx, buf);
-            break;
+  case HCI_CLASS_ACL_DATA:
+    /* generate ACL data */
+    buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_FOREVER);
+    hci_acl_encode(node_rx, buf);
+    break;
 #endif
-        default:
-            LL_ASSERT(0);
-            break;
-    }
+  default:
+    LL_ASSERT(0);
+    break;
+  }
 
-    radio_rx_fc_set(node_rx->hdr.handle, 0);
-    node_rx->hdr.onion.next = 0;
-    radio_rx_mem_release(&node_rx);
+  radio_rx_fc_set(node_rx->hdr.handle, 0);
+  node_rx->hdr.onion.next = 0;
+  radio_rx_mem_release(&node_rx);
 
-    return buf;
+  return buf;
 }
 
-static inline struct net_buf *process_node(struct radio_pdu_node_rx *node_rx)
-{
-    s8_t class = hci_get_class(node_rx);
-    struct net_buf *buf = NULL;
+static inline struct net_buf *process_node(struct radio_pdu_node_rx *node_rx) {
+  s8_t class          = hci_get_class(node_rx);
+  struct net_buf *buf = NULL;
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    if (hbuf_count != -1) {
-        bool pend = !sys_slist_is_empty(&hbuf_pend);
-
-        /* controller to host flow control enabled */
-        switch (class) {
-            case HCI_CLASS_EVT_DISCARDABLE:
-            case HCI_CLASS_EVT_REQUIRED:
-                break;
-            case HCI_CLASS_EVT_CONNECTION:
-                /* for conn-related events, only pend is relevant */
-                hbuf_count = 1;
-                /* fallthrough */
-            case HCI_CLASS_ACL_DATA:
-                if (pend || !hbuf_count) {
-                    sys_slist_append(&hbuf_pend,
-                                     &node_rx->hdr.onion.node);
-                    BT_DBG("FC: Queuing item: %d", class);
-                    return NULL;
-                }
-                break;
-            default:
-                LL_ASSERT(0);
-                break;
-        }
+  if (hbuf_count != -1) {
+    bool pend = !sys_slist_is_empty(&hbuf_pend);
+
+    /* controller to host flow control enabled */
+    switch (class) {
+    case HCI_CLASS_EVT_DISCARDABLE:
+    case HCI_CLASS_EVT_REQUIRED:
+      break;
+    case HCI_CLASS_EVT_CONNECTION:
+      /* for conn-related events, only pend is relevant */
+      hbuf_count = 1;
+      /* fallthrough */
+    case HCI_CLASS_ACL_DATA:
+      if (pend || !hbuf_count) {
+        sys_slist_append(&hbuf_pend, &node_rx->hdr.onion.node);
+        BT_DBG("FC: Queuing item: %d", class);
+        return NULL;
+      }
+      break;
+    default:
+      LL_ASSERT(0);
+      break;
     }
+  }
 #endif
 
-    /* process regular node from radio */
-    buf = encode_node(node_rx, class);
+  /* process regular node from radio */
+  buf = encode_node(node_rx, class);
 
-    return buf;
+  return buf;
 }
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-static inline struct net_buf *process_hbuf(struct radio_pdu_node_rx *n)
-{
-    /* shadow total count in case of preemption */
-    struct radio_pdu_node_rx *node_rx = NULL;
-    s32_t hbuf_total = hci_hbuf_total;
-    struct net_buf *buf = NULL;
-    sys_snode_t *node = NULL;
-    s8_t class;
-    int reset;
-
-    reset = atomic_test_and_clear_bit(&hci_state_mask, HCI_STATE_BIT_RESET);
-    if (reset) {
-        /* flush queue, no need to free, the LL has already done it */
-        sys_slist_init(&hbuf_pend);
+static inline struct net_buf *process_hbuf(struct radio_pdu_node_rx *n) {
+  /* shadow total count in case of preemption */
+  struct radio_pdu_node_rx *node_rx    = NULL;
+  s32_t                     hbuf_total = hci_hbuf_total;
+  struct net_buf           *buf        = NULL;
+  sys_snode_t              *node       = NULL;
+  s8_t class;
+  int reset;
+
+  reset = atomic_test_and_clear_bit(&hci_state_mask, HCI_STATE_BIT_RESET);
+  if (reset) {
+    /* flush queue, no need to free, the LL has already done it */
+    sys_slist_init(&hbuf_pend);
+  }
+
+  if (hbuf_total <= 0) {
+    hbuf_count = -1;
+    return NULL;
+  }
+
+  /* available host buffers */
+  hbuf_count = hbuf_total - (hci_hbuf_sent - hci_hbuf_acked);
+
+  /* host acked ACL packets, try to dequeue from hbuf */
+  node = sys_slist_peek_head(&hbuf_pend);
+  if (!node) {
+    return NULL;
+  }
+
+  /* Return early if this iteration already has a node to process */
+  node_rx = NODE_RX(node);
+  class   = hci_get_class(node_rx);
+  if (n) {
+    if (class == HCI_CLASS_EVT_CONNECTION || (class == HCI_CLASS_ACL_DATA && hbuf_count)) {
+      /* node to process later, schedule an iteration */
+      BT_DBG("FC: signalling");
+      k_poll_signal_raise(&hbuf_signal, 0x0);
     }
-
-    if (hbuf_total <= 0) {
-        hbuf_count = -1;
-        return NULL;
+    return NULL;
+  }
+
+  switch (class) {
+  case HCI_CLASS_EVT_CONNECTION:
+    BT_DBG("FC: dequeueing event");
+    (void)sys_slist_get(&hbuf_pend);
+    break;
+  case HCI_CLASS_ACL_DATA:
+    if (hbuf_count) {
+      BT_DBG("FC: dequeueing ACL data");
+      (void)sys_slist_get(&hbuf_pend);
+    } else {
+      /* no buffers, HCI will signal */
+      node = NULL;
     }
-
-    /* available host buffers */
+    break;
+  case HCI_CLASS_EVT_DISCARDABLE:
+  case HCI_CLASS_EVT_REQUIRED:
+  default:
+    LL_ASSERT(0);
+    break;
+  }
+
+  if (node) {
+    buf = encode_node(node_rx, class);
+    /* Update host buffers after encoding */
     hbuf_count = hbuf_total - (hci_hbuf_sent - hci_hbuf_acked);
-
-    /* host acked ACL packets, try to dequeue from hbuf */
+    /* next node */
     node = sys_slist_peek_head(&hbuf_pend);
-    if (!node) {
-        return NULL;
-    }
-
-    /* Return early if this iteration already has a node to process */
-    node_rx = NODE_RX(node);
-    class = hci_get_class(node_rx);
-    if (n) {
-        if (class == HCI_CLASS_EVT_CONNECTION ||
-            (class == HCI_CLASS_ACL_DATA && hbuf_count)) {
-            /* node to process later, schedule an iteration */
-            BT_DBG("FC: signalling");
-            k_poll_signal_raise(&hbuf_signal, 0x0);
-        }
-        return NULL;
-    }
-
-    switch (class) {
-        case HCI_CLASS_EVT_CONNECTION:
-            BT_DBG("FC: dequeueing event");
-            (void)sys_slist_get(&hbuf_pend);
-            break;
-        case HCI_CLASS_ACL_DATA:
-            if (hbuf_count) {
-                BT_DBG("FC: dequeueing ACL data");
-                (void)sys_slist_get(&hbuf_pend);
-            } else {
-                /* no buffers, HCI will signal */
-                node = NULL;
-            }
-            break;
-        case HCI_CLASS_EVT_DISCARDABLE:
-        case HCI_CLASS_EVT_REQUIRED:
-        default:
-            LL_ASSERT(0);
-            break;
-    }
-
     if (node) {
-        buf = encode_node(node_rx, class);
-        /* Update host buffers after encoding */
-        hbuf_count = hbuf_total - (hci_hbuf_sent - hci_hbuf_acked);
-        /* next node */
-        node = sys_slist_peek_head(&hbuf_pend);
-        if (node) {
-            node_rx = NODE_RX(node);
-            class = hci_get_class(node_rx);
-
-            if (class == HCI_CLASS_EVT_CONNECTION ||
-                (class == HCI_CLASS_ACL_DATA && hbuf_count)) {
-                /* more to process, schedule an
-				 * iteration
-				 */
-                BT_DBG("FC: signalling");
-                k_poll_signal_raise(&hbuf_signal, 0x0);
-            }
-        }
+      node_rx = NODE_RX(node);
+      class   = hci_get_class(node_rx);
+
+      if (class == HCI_CLASS_EVT_CONNECTION || (class == HCI_CLASS_ACL_DATA && hbuf_count)) {
+        /* more to process, schedule an
+         * iteration
+         */
+        BT_DBG("FC: signalling");
+        k_poll_signal_raise(&hbuf_signal, 0x0);
+      }
     }
+  }
 
-    return buf;
+  return buf;
 }
 #endif
 #endif
 
 #if defined(BFLB_BLE)
-#if (BFLB_BLE_CO_THREAD)
-void co_rx_thread()
-{
-    struct net_buf *buf = NULL;
-    buf = net_buf_get(&recv_fifo, K_NO_WAIT);
-    if (buf) {
-        BT_DBG("Calling bt_recv(%p)", buf);
-        bt_recv(buf);
-    }
-}
-
-void co_tx_rx_thread(void *p1)
-{
-    UNUSED(p1);
-    BT_DBG("using %s\n", __func__);
-    while (1) {
-        if (k_sem_count_get(&g_poll_sem) > 0) {
-            co_tx_thread();
-        }
-
-        if (recv_fifo_count > 0) {
-            recv_fifo_count--;
-            co_rx_thread();
-        }
-
-        k_sleep(portTICK_PERIOD_MS);
-        k_yield();
-    }
-}
-
-#else
-static void recv_thread(void *p1)
-{
-    UNUSED(p1);
+static void recv_thread(void *p1) {
+  UNUSED(p1);
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    /* @todo: check if the events structure really needs to be static */
-    static struct k_poll_event events[2] = {
-        K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_SIGNAL,
-                                        K_POLL_MODE_NOTIFY_ONLY,
-                                        &hbuf_signal, 0),
-        K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE,
-                                        K_POLL_MODE_NOTIFY_ONLY,
-                                        &recv_fifo, 0),
-    };
+  /* @todo: check if the events structure really needs to be static */
+  static struct k_poll_event events[2] = {
+      K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &hbuf_signal, 0),
+      K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &recv_fifo, 0),
+  };
 #endif
 
-    while (1) {
+  while (1) {
 #if defined(BFLB_BLE)
-        struct net_buf *buf = NULL;
-        buf = net_buf_get(&recv_fifo, K_FOREVER);
-        if (buf) {
-            BT_DBG("Calling bt_recv(%p)", buf);
-            bt_recv(buf);
-        }
+    struct net_buf *buf = NULL;
+    buf                 = net_buf_get(&recv_fifo, K_FOREVER);
+    if (buf) {
+      BT_DBG("Calling bt_recv(%p)", buf);
+      bt_recv(buf);
+    }
 #else
-        struct radio_pdu_node_rx *node_rx = NULL;
-        struct net_buf *buf = NULL;
+    struct radio_pdu_node_rx *node_rx = NULL;
+    struct net_buf           *buf     = NULL;
 
-        BT_DBG("blocking");
+    BT_DBG("blocking");
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-        int err;
+    int err;
 
-        err = k_poll(events, 2, K_FOREVER);
-        LL_ASSERT(err == 0);
-        if (events[0].state == K_POLL_STATE_SIGNALED) {
-            events[0].signal->signaled = 0;
-        } else if (events[1].state ==
-                   K_POLL_STATE_FIFO_DATA_AVAILABLE) {
-            node_rx = k_fifo_get(events[1].fifo, 0);
-        }
+    err = k_poll(events, 2, K_FOREVER);
+    LL_ASSERT(err == 0);
+    if (events[0].state == K_POLL_STATE_SIGNALED) {
+      events[0].signal->signaled = 0;
+    } else if (events[1].state == K_POLL_STATE_FIFO_DATA_AVAILABLE) {
+      node_rx = k_fifo_get(events[1].fifo, 0);
+    }
 
-        events[0].state = K_POLL_STATE_NOT_READY;
-        events[1].state = K_POLL_STATE_NOT_READY;
+    events[0].state = K_POLL_STATE_NOT_READY;
+    events[1].state = K_POLL_STATE_NOT_READY;
 
-        /* process host buffers first if any */
-        buf = process_hbuf(node_rx);
+    /* process host buffers first if any */
+    buf = process_hbuf(node_rx);
 
 #else
-        node_rx = k_fifo_get(&recv_fifo, K_FOREVER);
+    node_rx = k_fifo_get(&recv_fifo, K_FOREVER);
 #endif
-        BT_DBG("unblocked");
-
-        if (node_rx && !buf) {
-            /* process regular node from radio */
-            buf = process_node(node_rx);
-        }
-
-        if (buf) {
-            if (buf->len) {
-                BT_DBG("Packet in: type:%u len:%u",
-                       bt_buf_get_type(buf), buf->len);
-                bt_recv(buf);
-            } else {
-                net_buf_unref(buf);
-            }
-        }
+    BT_DBG("unblocked");
+
+    if (node_rx && !buf) {
+      /* process regular node from radio */
+      buf = process_node(node_rx);
+    }
+
+    if (buf) {
+      if (buf->len) {
+        BT_DBG("Packet in: type:%u len:%u", bt_buf_get_type(buf), buf->len);
+        bt_recv(buf);
+      } else {
+        net_buf_unref(buf);
+      }
+    }
 #endif
-        k_yield();
+    k_yield();
 
 #if defined(CONFIG_INIT_STACKS)
-        if (k_uptime_get_32() - rx_ts > K_SECONDS(5)) {
-            STACK_ANALYZE("recv thread stack", recv_thread_stack);
-            rx_ts = k_uptime_get_32();
-        }
-#endif
+    if (k_uptime_get_32() - rx_ts > K_SECONDS(5)) {
+      STACK_ANALYZE("recv thread stack", recv_thread_stack);
+      rx_ts = k_uptime_get_32();
     }
-}
 #endif
+  }
+}
 #endif
 
 #if !defined(BFLB_BLE)
-static int cmd_handle(struct net_buf *buf)
-{
-    struct net_buf *evt;
-
-    evt = hci_cmd_handle(buf);
-    if (evt) {
-        BT_DBG("Replying with event of %u bytes", evt->len);
-        bt_recv_prio(evt);
-    }
+static int cmd_handle(struct net_buf *buf) {
+  struct net_buf *evt;
+
+  evt = hci_cmd_handle(buf);
+  if (evt) {
+    BT_DBG("Replying with event of %u bytes", evt->len);
+    bt_recv_prio(evt);
+  }
 }
 
 #if defined(CONFIG_BT_CONN)
-static int acl_handle(struct net_buf *buf)
-{
-    struct net_buf *evt;
-    int err;
+static int acl_handle(struct net_buf *buf) {
+  struct net_buf *evt;
+  int             err;
 
-    err = hci_acl_handle(buf, &evt);
-    if (evt) {
-        BT_DBG("Replying with event of %u bytes", evt->len);
-        bt_recv_prio(evt);
-    }
+  err = hci_acl_handle(buf, &evt);
+  if (evt) {
+    BT_DBG("Replying with event of %u bytes", evt->len);
+    bt_recv_prio(evt);
+  }
 
-    return err;
+  return err;
 }
 #endif /* CONFIG_BT_CONN */
 #endif
 
-static int hci_driver_send(struct net_buf *buf)
-{
+static int hci_driver_send(struct net_buf *buf) {
 #if !defined(BFLB_BLE)
-    u8_t type;
+  u8_t type;
 #endif
-    int err;
+  int err;
 
-    BT_DBG("enter");
+  BT_DBG("enter");
 
-    if (!buf->len) {
-        BT_ERR("Empty HCI packet");
-        return -EINVAL;
-    }
+  if (!buf->len) {
+    BT_ERR("Empty HCI packet");
+    return -EINVAL;
+  }
 
 #if defined(BFLB_BLE)
-    err = bl_onchiphci_send_2_controller(buf);
-    net_buf_unref(buf);
-    return err;
+  err = bl_onchiphci_send_2_controller(buf);
+  net_buf_unref(buf);
+  return err;
 #else
-    type = bt_buf_get_type(buf);
-    switch (type) {
+  type = bt_buf_get_type(buf);
+  switch (type) {
 #if defined(CONFIG_BT_CONN)
-        case BT_BUF_ACL_OUT:
-            err = acl_handle(buf);
-            break;
+  case BT_BUF_ACL_OUT:
+    err = acl_handle(buf);
+    break;
 #endif /* CONFIG_BT_CONN */
-        case BT_BUF_CMD:
-            err = cmd_handle(buf);
+  case BT_BUF_CMD:
+    err = cmd_handle(buf);
 
-            break;
-        default:
-            BT_ERR("Unknown HCI type %u", type);
-            return -EINVAL;
-    }
+    break;
+  default:
+    BT_ERR("Unknown HCI type %u", type);
+    return -EINVAL;
+  }
 
-    if (!err) {
-        net_buf_unref(buf);
-    } else {
-    }
+  if (!err) {
+    net_buf_unref(buf);
+  } else {
+  }
 
-    BT_DBG("exit: %d", err);
+  BT_DBG("exit: %d", err);
 #endif
-    return err;
+  return err;
 }
 
-static int hci_driver_open(void)
-{
+static int hci_driver_open(void) {
 #if !defined(BFLB_BLE)
-    u32_t err;
+  u32_t err;
 
-    DEBUG_INIT();
-    k_sem_init(&sem_prio_recv, 0, BT_UINT_MAX);
+  DEBUG_INIT();
+  k_sem_init(&sem_prio_recv, 0, BT_UINT_MAX);
 
-    err = ll_init(&sem_prio_recv);
+  err = ll_init(&sem_prio_recv);
 
-    if (err) {
-        BT_ERR("LL initialization failed: %u", err);
-        return err;
-    }
+  if (err) {
+    BT_ERR("LL initialization failed: %u", err);
+    return err;
+  }
 #endif
 
 #if !defined(BFLB_BLE)
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    hci_init(&hbuf_signal);
+  hci_init(&hbuf_signal);
 #else
-    hci_init(NULL);
+  hci_init(NULL);
 #endif
 #endif
-    k_fifo_init(&recv_fifo, 20);
-
+#if (!BFLB_BT_CO_THREAD)
+  k_fifo_init(&recv_fifo, 20);
+#endif
 #if defined(BFLB_BLE)
-#if (BFLB_BLE_CO_THREAD)
-    k_thread_create(&recv_thread_data, "co_tx_rx_thread",
-                    CONFIG_BT_RX_STACK_SIZE,
-                    co_tx_rx_thread,
-                    K_PRIO_COOP(CONFIG_BT_RX_PRIO));
-#else
-    k_thread_create(&recv_thread_data, "recv_thread",
-                    CONFIG_BT_RX_STACK_SIZE /*K_THREAD_STACK_SIZEOF(recv_thread_stack)*/,
-                    recv_thread,
-                    K_PRIO_COOP(CONFIG_BT_RX_PRIO));
+#if (!BFLB_BT_CO_THREAD)
+  k_thread_create(&recv_thread_data, "recv_thread", CONFIG_BT_RX_STACK_SIZE /*K_THREAD_STACK_SIZEOF(recv_thread_stack)*/, recv_thread, K_PRIO_COOP(CONFIG_BT_RX_PRIO));
 #endif
 #else
-    k_thread_create(&prio_recv_thread_data, prio_recv_thread_stack,
-                    K_THREAD_STACK_SIZEOF(prio_recv_thread_stack),
-                    prio_recv_thread, NULL, NULL, NULL,
-                    K_PRIO_COOP(CONFIG_BT_CTLR_RX_PRIO), 0, K_NO_WAIT);
+  k_thread_create(&prio_recv_thread_data, prio_recv_thread_stack, K_THREAD_STACK_SIZEOF(prio_recv_thread_stack), prio_recv_thread, NULL, NULL, NULL, K_PRIO_COOP(CONFIG_BT_CTLR_RX_PRIO), 0, K_NO_WAIT);
 #endif
 
-    BT_DBG("Success.");
+  BT_DBG("Success.");
 
-    return 0;
+  return 0;
 }
 
-void hci_driver_enque_recvq(struct net_buf *buf)
-{
-    net_buf_put(&recv_fifo, buf);
-#if (BFLB_BLE_CO_THREAD)
-    recv_fifo_count++;
+void hci_driver_enque_recvq(struct net_buf *buf) {
+  net_buf_put(&recv_fifo, buf);
+#if (BFLB_BT_CO_THREAD)
+  extern struct k_sem g_poll_sem;
+  k_sem_give(&g_poll_sem);
 #endif
 }
 
 static const struct bt_hci_driver drv = {
     .name = "Controller",
-    .bus = BT_HCI_DRIVER_BUS_VIRTUAL,
+    .bus  = BT_HCI_DRIVER_BUS_VIRTUAL,
     .open = hci_driver_open,
     .send = hci_driver_send,
 };
 
 #if defined(BFLB_BLE)
-int hci_driver_init(void)
-{
-    bt_hci_driver_register(&drv);
+int hci_driver_init(void) {
+  bt_hci_driver_register(&drv);
 
-    return 0;
+  return 0;
 }
 #else
-static int _hci_driver_init(struct device *unused)
-{
-    ARG_UNUSED(unused);
+static int _hci_driver_init(struct device *unused) {
+  ARG_UNUSED(unused);
 
-    bt_hci_driver_register(&drv);
+  bt_hci_driver_register(&drv);
 
-    return 0;
+  return 0;
 }
-//SYS_INIT(_hci_driver_init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);
+// SYS_INIT(_hci_driver_init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/a2dp.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/a2dp.c
deleted file mode 100644
index 82901ed23..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/a2dp.c
+++ /dev/null
@@ -1,343 +0,0 @@
-/** @file
- * @brief Advance Audio Distribution Profile.
- */
-
-/*
- * Copyright (c) 2015-2016 Intel Corporation
- *
- * SPDX-License-Identifier: Apache-2.0
- */
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_A2DP)
-#define LOG_MODULE_NAME bt_a2dp
-#include "log.h"
-
-#include "hci_core.h"
-#include "conn_internal.h"
-#include "avdtp_internal.h"
-#include "a2dp_internal.h"
-#include "a2dp-codec.h"
-#include "oi_codec_sbc.h"
-
-#define A2DP_NO_SPACE (-1)
-
-struct bt_a2dp {
-    struct bt_avdtp session;
-};
-
-typedef struct {
-    OI_CODEC_SBC_DECODER_CONTEXT decoder_context;
-    uint32_t context_data[CODEC_DATA_WORDS(SBC_MAX_CHANNELS, SBC_CODEC_FAST_FILTER_BUFFERS)];
-    int16_t decode_buf[15 * SBC_MAX_SAMPLES_PER_FRAME * SBC_MAX_CHANNELS];
-} A2DP_SBC_DECODER;
-
-static A2DP_SBC_DECODER sbc_decoder;
-
-/* Connections */
-static struct bt_a2dp connection[CONFIG_BT_MAX_CONN];
-static struct bt_avdtp_stream stream[CONFIG_BT_MAX_CONN];
-
-static struct bt_sdp_attribute a2dp_attrs[] = {
-    BT_SDP_NEW_SERVICE,
-    BT_SDP_LIST(
-        BT_SDP_ATTR_SVCLASS_ID_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-              BT_SDP_ARRAY_16(BT_SDP_AUDIO_SINK_SVCLASS) }, )),
-    BT_SDP_LIST(
-        BT_SDP_ATTR_PROTO_DESC_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 16),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_PROTO_L2CAP) },
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UINT16),
-                    BT_SDP_ARRAY_16(BT_L2CAP_PSM_AVDTP) }, ) },
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_L2CAP_PSM_AVDTP) },
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UINT16),
-                    BT_SDP_ARRAY_16(0x0102) }, ) }, )),
-    BT_SDP_LIST(
-        BT_SDP_ATTR_PROFILE_DESC_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 8),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_ADVANCED_AUDIO_SVCLASS) },
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UINT16),
-                    BT_SDP_ARRAY_16(0x0102) }, ) }, )),
-    BT_SDP_SERVICE_NAME("A2DP sink"),
-};
-
-static struct bt_sdp_record a2dp_rec = BT_SDP_RECORD(a2dp_attrs);
-
-struct bt_a2dp_endpoint endpoint_1;
-struct bt_a2dp_endpoint endpoint_2;
-
-struct bt_a2dp_codec_sbc_params sbc_info;
-
-void bt_a2dp_set_sbc_codec_info()
-{
-    sbc_info.config[0] =
-        //Sampling Frequency
-        A2DP_SBC_SAMP_FREQ_48000 |
-        A2DP_SBC_SAMP_FREQ_44100 |
-        A2DP_SBC_SAMP_FREQ_32000 |
-        A2DP_SBC_SAMP_FREQ_16000 |
-        //Channel Mode
-        A2DP_SBC_CH_MODE_JOINT |
-        A2DP_SBC_CH_MODE_STREO |
-        A2DP_SBC_CH_MODE_DUAL |
-        A2DP_SBC_CH_MODE_MONO;
-    sbc_info.config[1] =
-        //Block Length
-        A2DP_SBC_BLK_LEN_16 |
-        A2DP_SBC_BLK_LEN_12 |
-        A2DP_SBC_BLK_LEN_8 |
-        A2DP_SBC_BLK_LEN_4 |
-        //Subbands
-        A2DP_SBC_SUBBAND_8 |
-        A2DP_SBC_SUBBAND_4 |
-        //Allocation Method
-        A2DP_SBC_ALLOC_MTHD_SNR |
-        A2DP_SBC_ALLOC_MTHD_LOUDNESS;
-    sbc_info.min_bitpool = 2;
-    sbc_info.max_bitpool = 53;
-}
-
-void a2d_reset(struct bt_a2dp *a2dp_conn)
-{
-    (void)memset(a2dp_conn, 0, sizeof(struct bt_a2dp));
-}
-
-void stream_reset(struct bt_avdtp_stream *stream_conn)
-{
-    (void)memset(stream_conn, 0, sizeof(struct bt_avdtp_stream));
-}
-
-struct bt_a2dp *get_new_connection(struct bt_conn *conn)
-{
-    int8_t i, free;
-
-    free = A2DP_NO_SPACE;
-
-    if (!conn) {
-        BT_ERR("Invalid Input (err: %d)", -EINVAL);
-        return NULL;
-    }
-
-    /* Find a space */
-    for (i = 0; i < CONFIG_BT_MAX_CONN; i++) {
-        if (connection[i].session.br_chan.chan.conn == conn) {
-            BT_DBG("Conn already exists");
-            if (!connection[i].session.streams->chan.chan.conn) {
-                BT_DBG("Create AV stream");
-                return &connection[i];
-            } else {
-                BT_DBG("A2DP signal stream and AV stream already exists");
-                return NULL;
-            }
-        }
-
-        if (!connection[i].session.br_chan.chan.conn &&
-            free == A2DP_NO_SPACE) {
-            BT_DBG("Create signal stream");
-            free = i;
-        }
-    }
-
-    if (free == A2DP_NO_SPACE) {
-        BT_DBG("More connection cannot be supported");
-        return NULL;
-    }
-
-    /* Clean the memory area before returning */
-    a2d_reset(&connection[free]);
-    stream_reset(&stream[free]);
-    connection[free].session.streams = &stream[free];
-
-    return &connection[free];
-}
-
-int a2dp_accept(struct bt_conn *conn, struct bt_avdtp **session)
-{
-    struct bt_a2dp *a2dp_conn;
-
-    a2dp_conn = get_new_connection(conn);
-    if (!a2dp_conn) {
-        return -ENOMEM;
-    }
-
-    *session = &(a2dp_conn->session);
-    BT_DBG("session: %p", &(a2dp_conn->session));
-
-    return 0;
-}
-
-int a2dp_sbc_decode_init()
-{
-    OI_STATUS status = OI_CODEC_SBC_DecoderReset(&sbc_decoder.decoder_context,
-                                                 sbc_decoder.context_data,
-                                                 sizeof(sbc_decoder.context_data),
-                                                 2,
-                                                 2,
-                                                 false,
-                                                 false);
-    if (!OI_SUCCESS(status)) {
-        BT_ERR("decode init failed with error: %d\n", status);
-        return status;
-    }
-
-    return 0;
-}
-
-#if PCM_PRINTF
-extern int16_t cool_edit[];
-extern uint32_t byte_index;
-#endif
-int a2dp_sbc_decode_process(uint8_t media_data[], uint16_t data_len)
-{
-    //remove media header, expose sbc frame
-    const OI_BYTE *data = media_data + 12 + 1;
-    OI_UINT32 data_size = data_len - 12 - 1;
-
-    if (data_size <= 0) {
-        BT_ERR("empty packet\n");
-        return -1;
-    }
-
-    if (data[0] != 0x9c) {
-        BT_ERR("sbc frame syncword error \n");
-    }
-
-    OI_INT16 *pcm = sbc_decoder.decode_buf;
-    OI_UINT32 pcm_size = sizeof(sbc_decoder.decode_buf);
-
-    OI_INT16 frame_count = OI_CODEC_SBC_FrameCount((OI_BYTE *)data, data_size);
-    BT_DBG("frame_count: %d\n", frame_count);
-
-    for (int i = 0; i < frame_count; i++) {
-        OI_STATUS status = OI_CODEC_SBC_DecodeFrame(&sbc_decoder.decoder_context,
-                                                    &data,
-                                                    &data_size,
-                                                    pcm,
-                                                    &pcm_size);
-        if (!OI_SUCCESS(status)) {
-            BT_ERR("decoding failure with error: %d \n", status);
-            return -1;
-        }
-
-#if PCM_PRINTF
-        memcpy((OI_INT8 *)cool_edit + byte_index, pcm, pcm_size);
-        byte_index += pcm_size;
-#endif
-    }
-
-    return 0;
-}
-
-/* Callback for incoming requests */
-static struct bt_avdtp_ind_cb cb_ind = {
-    /*TODO*/
-};
-
-/* The above callback structures need to be packed and passed to AVDTP */
-static struct bt_avdtp_event_cb avdtp_cb = {
-    .ind = &cb_ind,
-    .accept = a2dp_accept
-};
-
-int bt_a2dp_init(void)
-{
-    int err;
-
-    /* Register event handlers with AVDTP */
-    err = bt_avdtp_register(&avdtp_cb);
-    if (err < 0) {
-        BT_ERR("A2DP registration failed");
-        return err;
-    }
-
-    /* Register SDP record */
-    err = bt_sdp_register_service(&a2dp_rec);
-    if (err < 0) {
-        BT_ERR("A2DP regist sdp record failed");
-        return err;
-    }
-
-    int reg_1 = bt_a2dp_register_endpoint(&endpoint_1, BT_A2DP_AUDIO, BT_A2DP_SINK);
-    int reg_2 = bt_a2dp_register_endpoint(&endpoint_2, BT_A2DP_AUDIO, BT_A2DP_SINK);
-    if (reg_1 || reg_2) {
-        BT_ERR("A2DP registration endpoint 1 failed");
-        return err;
-    }
-
-    bt_a2dp_set_sbc_codec_info();
-
-    err = a2dp_sbc_decode_init();
-    if (err < 0) {
-        BT_ERR("sbc codec init failed");
-        return err;
-    }
-
-    BT_DBG("A2DP Initialized successfully.");
-    return 0;
-}
-
-struct bt_a2dp *bt_a2dp_connect(struct bt_conn *conn)
-{
-    struct bt_a2dp *a2dp_conn;
-    int err;
-
-    a2dp_conn = get_new_connection(conn);
-    if (!a2dp_conn) {
-        BT_ERR("Cannot allocate memory");
-        return NULL;
-    }
-
-    err = bt_avdtp_connect(conn, &(a2dp_conn->session));
-    if (err < 0) {
-        /* If error occurs, undo the saving and return the error */
-        a2d_reset(a2dp_conn);
-        BT_DBG("AVDTP Connect failed");
-        return NULL;
-    }
-
-    BT_DBG("Connect request sent");
-    return a2dp_conn;
-}
-
-int bt_a2dp_register_endpoint(struct bt_a2dp_endpoint *endpoint,
-                              uint8_t media_type, uint8_t role)
-{
-    int err;
-
-    BT_ASSERT(endpoint);
-
-    err = bt_avdtp_register_sep(media_type, role, &(endpoint->info));
-    if (err < 0) {
-        return err;
-    }
-
-    return 0;
-}
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/a2dp_internal.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/a2dp_internal.h
deleted file mode 100644
index 08e8b76b4..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/a2dp_internal.h
+++ /dev/null
@@ -1,12 +0,0 @@
-/** @file
- * @brief Advance Audio Distribution Profile Internal header.
- */
-
-/*
- * Copyright (c) 2015-2016 Intel Corporation
- *
- * SPDX-License-Identifier: Apache-2.0
- */
-
-/* To be called when first SEP is being registered */
-int bt_a2dp_init(void);
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/at.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/at.c
index 189ff4b2a..0f1feaf49 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/at.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/at.c
@@ -9,295 +9,264 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
 #include 
-#include 
-#include 
+#include 
 #include 
+#include 
+#include 
 
 #include "at.h"
 
-static void next_list(struct at_client *at)
-{
-    if (at->buf[at->pos] == ',') {
-        at->pos++;
-    }
+static void next_list(struct at_client *at) {
+  if (at->buf[at->pos] == ',') {
+    at->pos++;
+  }
 }
 
-int at_check_byte(struct net_buf *buf, char check_byte)
-{
-    const unsigned char *str = buf->data;
+int at_check_byte(struct net_buf *buf, char check_byte) {
+  const unsigned char *str = buf->data;
 
-    if (*str != check_byte) {
-        return -EINVAL;
-    }
-    net_buf_pull(buf, 1);
+  if (*str != check_byte) {
+    return -EINVAL;
+  }
+  net_buf_pull(buf, 1);
 
-    return 0;
+  return 0;
 }
 
-static void skip_space(struct at_client *at)
-{
-    while (at->buf[at->pos] == ' ') {
-        at->pos++;
-    }
+static void skip_space(struct at_client *at) {
+  while (at->buf[at->pos] == ' ') {
+    at->pos++;
+  }
 }
 
-int at_get_number(struct at_client *at, uint32_t *val)
-{
-    uint32_t i;
+int at_get_number(struct at_client *at, uint32_t *val) {
+  uint32_t i;
 
-    skip_space(at);
+  skip_space(at);
 
-    for (i = 0U, *val = 0U;
-         isdigit((unsigned char)at->buf[at->pos]);
-         at->pos++, i++) {
-        *val = *val * 10U + at->buf[at->pos] - '0';
-    }
+  for (i = 0U, *val = 0U; isdigit((unsigned char)at->buf[at->pos]); at->pos++, i++) {
+    *val = *val * 10U + at->buf[at->pos] - '0';
+  }
 
-    if (i == 0U) {
-        return -ENODATA;
-    }
+  if (i == 0U) {
+    return -ENODATA;
+  }
 
-    next_list(at);
-    return 0;
+  next_list(at);
+  return 0;
 }
 
-static bool str_has_prefix(const char *str, const char *prefix)
-{
-    if (strncmp(str, prefix, strlen(prefix)) != 0) {
-        return false;
-    }
+static bool str_has_prefix(const char *str, const char *prefix) {
+  if (strncmp(str, prefix, strlen(prefix)) != 0) {
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
-static int at_parse_result(const char *str, struct net_buf *buf,
-                           enum at_result *result)
-{
-    /* Map the result and check for end lf */
-    if ((!strncmp(str, "OK", 2)) && (at_check_byte(buf, '\n') == 0)) {
-        *result = AT_RESULT_OK;
-        return 0;
-    }
+static int at_parse_result(const char *str, struct net_buf *buf, enum at_result *result) {
+  /* Map the result and check for end lf */
+  if ((!strncmp(str, "OK", 2)) && (at_check_byte(buf, '\n') == 0)) {
+    *result = AT_RESULT_OK;
+    return 0;
+  }
 
-    if ((!strncmp(str, "ERROR", 5)) && (at_check_byte(buf, '\n')) == 0) {
-        *result = AT_RESULT_ERROR;
-        return 0;
-    }
+  if ((!strncmp(str, "ERROR", 5)) && (at_check_byte(buf, '\n')) == 0) {
+    *result = AT_RESULT_ERROR;
+    return 0;
+  }
 
-    return -ENOMSG;
+  return -ENOMSG;
 }
 
-static int get_cmd_value(struct at_client *at, struct net_buf *buf,
-                         char stop_byte, enum at_cmd_state cmd_state)
-{
-    int cmd_len = 0;
-    uint8_t pos = at->pos;
-    const char *str = (char *)buf->data;
-
-    while (cmd_len < buf->len && at->pos != at->buf_max_len) {
-        if (*str != stop_byte) {
-            at->buf[at->pos++] = *str;
-            cmd_len++;
-            str++;
-            pos = at->pos;
-        } else {
-            cmd_len++;
-            at->buf[at->pos] = '\0';
-            at->pos = 0U;
-            at->cmd_state = cmd_state;
-            break;
-        }
-    }
-    net_buf_pull(buf, cmd_len);
+static int get_cmd_value(struct at_client *at, struct net_buf *buf, char stop_byte, enum at_cmd_state cmd_state) {
+  int         cmd_len = 0;
+  uint8_t     pos     = at->pos;
+  const char *str     = (char *)buf->data;
 
-    if (pos == at->buf_max_len) {
-        return -ENOBUFS;
+  while (cmd_len < buf->len && at->pos != at->buf_max_len) {
+    if (*str != stop_byte) {
+      at->buf[at->pos++] = *str;
+      cmd_len++;
+      str++;
+      pos = at->pos;
+    } else {
+      cmd_len++;
+      at->buf[at->pos] = '\0';
+      at->pos          = 0U;
+      at->cmd_state    = cmd_state;
+      break;
     }
+  }
+  net_buf_pull(buf, cmd_len);
 
-    return 0;
+  if (pos == at->buf_max_len) {
+    return -ENOBUFS;
+  }
+
+  return 0;
 }
 
-static int get_response_string(struct at_client *at, struct net_buf *buf,
-                               char stop_byte, enum at_state state)
-{
-    int cmd_len = 0;
-    uint8_t pos = at->pos;
-    const char *str = (char *)buf->data;
-
-    while (cmd_len < buf->len && at->pos != at->buf_max_len) {
-        if (*str != stop_byte) {
-            at->buf[at->pos++] = *str;
-            cmd_len++;
-            str++;
-            pos = at->pos;
-        } else {
-            cmd_len++;
-            at->buf[at->pos] = '\0';
-            at->pos = 0U;
-            at->state = state;
-            break;
-        }
-    }
-    net_buf_pull(buf, cmd_len);
+static int get_response_string(struct at_client *at, struct net_buf *buf, char stop_byte, enum at_state state) {
+  int         cmd_len = 0;
+  uint8_t     pos     = at->pos;
+  const char *str     = (char *)buf->data;
 
-    if (pos == at->buf_max_len) {
-        return -ENOBUFS;
+  while (cmd_len < buf->len && at->pos != at->buf_max_len) {
+    if (*str != stop_byte) {
+      at->buf[at->pos++] = *str;
+      cmd_len++;
+      str++;
+      pos = at->pos;
+    } else {
+      cmd_len++;
+      at->buf[at->pos] = '\0';
+      at->pos          = 0U;
+      at->state        = state;
+      break;
     }
+  }
+  net_buf_pull(buf, cmd_len);
 
-    return 0;
+  if (pos == at->buf_max_len) {
+    return -ENOBUFS;
+  }
+
+  return 0;
 }
 
-static void reset_buffer(struct at_client *at)
-{
-    (void)memset(at->buf, 0, at->buf_max_len);
-    at->pos = 0U;
+static void reset_buffer(struct at_client *at) {
+  (void)memset(at->buf, 0, at->buf_max_len);
+  at->pos = 0U;
 }
 
-static int at_state_start(struct at_client *at, struct net_buf *buf)
-{
-    int err;
+static int at_state_start(struct at_client *at, struct net_buf *buf) {
+  int err;
 
-    err = at_check_byte(buf, '\r');
-    if (err < 0) {
-        return err;
-    }
-    at->state = AT_STATE_START_CR;
+  err = at_check_byte(buf, '\r');
+  if (err < 0) {
+    return err;
+  }
+  at->state = AT_STATE_START_CR;
 
-    return 0;
+  return 0;
 }
 
-static int at_state_start_cr(struct at_client *at, struct net_buf *buf)
-{
-    int err;
+static int at_state_start_cr(struct at_client *at, struct net_buf *buf) {
+  int err;
 
-    err = at_check_byte(buf, '\n');
-    if (err < 0) {
-        return err;
-    }
-    at->state = AT_STATE_START_LF;
+  err = at_check_byte(buf, '\n');
+  if (err < 0) {
+    return err;
+  }
+  at->state = AT_STATE_START_LF;
 
-    return 0;
+  return 0;
 }
 
-static int at_state_start_lf(struct at_client *at, struct net_buf *buf)
-{
-    reset_buffer(at);
-    if (at_check_byte(buf, '+') == 0) {
-        at->state = AT_STATE_GET_CMD_STRING;
-        return 0;
-    } else if (isalpha(*buf->data)) {
-        at->state = AT_STATE_GET_RESULT_STRING;
-        return 0;
-    }
+static int at_state_start_lf(struct at_client *at, struct net_buf *buf) {
+  reset_buffer(at);
+  if (at_check_byte(buf, '+') == 0) {
+    at->state = AT_STATE_GET_CMD_STRING;
+    return 0;
+  } else if (isalpha(*buf->data)) {
+    at->state = AT_STATE_GET_RESULT_STRING;
+    return 0;
+  }
 
-    return -ENODATA;
+  return -ENODATA;
 }
 
-static int at_state_get_cmd_string(struct at_client *at, struct net_buf *buf)
-{
-    return get_response_string(at, buf, ':', AT_STATE_PROCESS_CMD);
-}
+static int at_state_get_cmd_string(struct at_client *at, struct net_buf *buf) { return get_response_string(at, buf, ':', AT_STATE_PROCESS_CMD); }
 
-static bool is_cmer(struct at_client *at)
-{
-    if (strncmp(at->buf, "CME ERROR", 9) == 0) {
-        return true;
-    }
+static bool is_cmer(struct at_client *at) {
+  if (strncmp(at->buf, "CME ERROR", 9) == 0) {
+    return true;
+  }
 
-    return false;
+  return false;
 }
 
-static int at_state_process_cmd(struct at_client *at, struct net_buf *buf)
-{
-    if (is_cmer(at)) {
-        at->state = AT_STATE_PROCESS_AG_NW_ERR;
-        return 0;
-    }
+static int at_state_process_cmd(struct at_client *at, struct net_buf *buf) {
+  if (is_cmer(at)) {
+    at->state = AT_STATE_PROCESS_AG_NW_ERR;
+    return 0;
+  }
 
-    if (at->resp) {
-        at->resp(at, buf);
-        at->resp = NULL;
-        return 0;
-    }
-    at->state = AT_STATE_UNSOLICITED_CMD;
+  if (at->resp) {
+    at->resp(at, buf);
+    at->resp = NULL;
     return 0;
+  }
+  at->state = AT_STATE_UNSOLICITED_CMD;
+  return 0;
 }
 
-static int at_state_get_result_string(struct at_client *at, struct net_buf *buf)
-{
-    return get_response_string(at, buf, '\r', AT_STATE_PROCESS_RESULT);
-}
+static int at_state_get_result_string(struct at_client *at, struct net_buf *buf) { return get_response_string(at, buf, '\r', AT_STATE_PROCESS_RESULT); }
 
-static bool is_ring(struct at_client *at)
-{
-    if (strncmp(at->buf, "RING", 4) == 0) {
-        return true;
-    }
+static bool is_ring(struct at_client *at) {
+  if (strncmp(at->buf, "RING", 4) == 0) {
+    return true;
+  }
 
-    return false;
+  return false;
 }
 
-static int at_state_process_result(struct at_client *at, struct net_buf *buf)
-{
-    enum at_cme cme_err;
-    enum at_result result;
+static int at_state_process_result(struct at_client *at, struct net_buf *buf) {
+  enum at_cme    cme_err;
+  enum at_result result;
 
-    if (is_ring(at)) {
-        at->state = AT_STATE_UNSOLICITED_CMD;
-        return 0;
-    }
+  if (is_ring(at)) {
+    at->state = AT_STATE_UNSOLICITED_CMD;
+    return 0;
+  }
 
-    if (at_parse_result(at->buf, buf, &result) == 0) {
-        if (at->finish) {
-            /* cme_err is 0 - Is invalid until result is
-			 * AT_RESULT_CME_ERROR
-			 */
-            cme_err = 0;
-            at->finish(at, result, cme_err);
-        }
+  if (at_parse_result(at->buf, buf, &result) == 0) {
+    if (at->finish) {
+      /* cme_err is 0 - Is invalid until result is
+       * AT_RESULT_CME_ERROR
+       */
+      cme_err = 0;
+      at->finish(at, result, cme_err);
     }
+  }
 
-    /* Reset the state to process unsolicited response */
-    at->cmd_state = AT_CMD_START;
-    at->state = AT_STATE_START;
+  /* Reset the state to process unsolicited response */
+  at->cmd_state = AT_CMD_START;
+  at->state     = AT_STATE_START;
 
-    return 0;
+  return 0;
 }
 
-int cme_handle(struct at_client *at)
-{
-    enum at_cme cme_err;
-    uint32_t val;
+int cme_handle(struct at_client *at) {
+  enum at_cme cme_err;
+  uint32_t    val;
 
-    if (!at_get_number(at, &val) && val <= CME_ERROR_NETWORK_NOT_ALLOWED) {
-        cme_err = val;
-    } else {
-        cme_err = CME_ERROR_UNKNOWN;
-    }
+  if (!at_get_number(at, &val) && val <= CME_ERROR_NETWORK_NOT_ALLOWED) {
+    cme_err = val;
+  } else {
+    cme_err = CME_ERROR_UNKNOWN;
+  }
 
-    if (at->finish) {
-        at->finish(at, AT_RESULT_CME_ERROR, cme_err);
-    }
+  if (at->finish) {
+    at->finish(at, AT_RESULT_CME_ERROR, cme_err);
+  }
 
-    return 0;
+  return 0;
 }
 
-static int at_state_process_ag_nw_err(struct at_client *at, struct net_buf *buf)
-{
-    at->cmd_state = AT_CMD_GET_VALUE;
-    return at_parse_cmd_input(at, buf, NULL, cme_handle,
-                              AT_CMD_TYPE_NORMAL);
+static int at_state_process_ag_nw_err(struct at_client *at, struct net_buf *buf) {
+  at->cmd_state = AT_CMD_GET_VALUE;
+  return at_parse_cmd_input(at, buf, NULL, cme_handle, AT_CMD_TYPE_NORMAL);
 }
 
-static int at_state_unsolicited_cmd(struct at_client *at, struct net_buf *buf)
-{
-    if (at->unsolicited) {
-        return at->unsolicited(at, buf);
-    }
+static int at_state_unsolicited_cmd(struct at_client *at, struct net_buf *buf) {
+  if (at->unsolicited) {
+    return at->unsolicited(at, buf);
+  }
 
-    return -ENODATA;
+  return -ENODATA;
 }
 
 /* The order of handler function should match the enum at_state */
@@ -313,84 +282,71 @@ static handle_parse_input_t parser_cb[] = {
     at_state_unsolicited_cmd    /* AT_STATE_UNSOLICITED_CMD */
 };
 
-int at_parse_input(struct at_client *at, struct net_buf *buf)
-{
-    int ret;
-
-    while (buf->len) {
-        if (at->state < AT_STATE_START || at->state >= AT_STATE_END) {
-            return -EINVAL;
-        }
-        ret = parser_cb[at->state](at, buf);
-        if (ret < 0) {
-            /* Reset the state in case of error */
-            at->cmd_state = AT_CMD_START;
-            at->state = AT_STATE_START;
-            return ret;
-        }
+int at_parse_input(struct at_client *at, struct net_buf *buf) {
+  int ret;
+
+  while (buf->len) {
+    if (at->state < AT_STATE_START || at->state >= AT_STATE_END) {
+      return -EINVAL;
     }
+    ret = parser_cb[at->state](at, buf);
+    if (ret < 0) {
+      /* Reset the state in case of error */
+      at->cmd_state = AT_CMD_START;
+      at->state     = AT_STATE_START;
+      return ret;
+    }
+  }
 
-    return 0;
+  return 0;
 }
 
-static int at_cmd_start(struct at_client *at, struct net_buf *buf,
-                        const char *prefix, parse_val_t func,
-                        enum at_cmd_type type)
-{
-    if (!str_has_prefix(at->buf, prefix)) {
-        if (type == AT_CMD_TYPE_NORMAL) {
-            at->state = AT_STATE_UNSOLICITED_CMD;
-        }
-        return -ENODATA;
-    }
-
-    if (type == AT_CMD_TYPE_OTHER) {
-        /* Skip for Other type such as ..RING.. which does not have
-		 * values to get processed.
-		 */
-        at->cmd_state = AT_CMD_PROCESS_VALUE;
-    } else {
-        at->cmd_state = AT_CMD_GET_VALUE;
+static int at_cmd_start(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) {
+  if (!str_has_prefix(at->buf, prefix)) {
+    if (type == AT_CMD_TYPE_NORMAL) {
+      at->state = AT_STATE_UNSOLICITED_CMD;
     }
+    return -ENODATA;
+  }
+
+  if (type == AT_CMD_TYPE_OTHER) {
+    /* Skip for Other type such as ..RING.. which does not have
+     * values to get processed.
+     */
+    at->cmd_state = AT_CMD_PROCESS_VALUE;
+  } else {
+    at->cmd_state = AT_CMD_GET_VALUE;
+  }
 
-    return 0;
+  return 0;
 }
 
-static int at_cmd_get_value(struct at_client *at, struct net_buf *buf,
-                            const char *prefix, parse_val_t func,
-                            enum at_cmd_type type)
-{
-    /* Reset buffer before getting the values */
-    reset_buffer(at);
-    return get_cmd_value(at, buf, '\r', AT_CMD_PROCESS_VALUE);
+static int at_cmd_get_value(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) {
+  /* Reset buffer before getting the values */
+  reset_buffer(at);
+  return get_cmd_value(at, buf, '\r', AT_CMD_PROCESS_VALUE);
 }
 
-static int at_cmd_process_value(struct at_client *at, struct net_buf *buf,
-                                const char *prefix, parse_val_t func,
-                                enum at_cmd_type type)
-{
-    int ret;
+static int at_cmd_process_value(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) {
+  int ret;
 
-    ret = func(at);
-    at->cmd_state = AT_CMD_STATE_END_LF;
+  ret           = func(at);
+  at->cmd_state = AT_CMD_STATE_END_LF;
 
-    return ret;
+  return ret;
 }
 
-static int at_cmd_state_end_lf(struct at_client *at, struct net_buf *buf,
-                               const char *prefix, parse_val_t func,
-                               enum at_cmd_type type)
-{
-    int err;
+static int at_cmd_state_end_lf(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) {
+  int err;
 
-    err = at_check_byte(buf, '\n');
-    if (err < 0) {
-        return err;
-    }
+  err = at_check_byte(buf, '\n');
+  if (err < 0) {
+    return err;
+  }
 
-    at->cmd_state = AT_CMD_START;
-    at->state = AT_STATE_START;
-    return 0;
+  at->cmd_state = AT_CMD_START;
+  at->state     = AT_STATE_START;
+  return 0;
 }
 
 /* The order of handler function should match the enum at_cmd_state */
@@ -401,137 +357,122 @@ static handle_cmd_input_t cmd_parser_cb[] = {
     at_cmd_state_end_lf   /* AT_CMD_STATE_END_LF */
 };
 
-int at_parse_cmd_input(struct at_client *at, struct net_buf *buf,
-                       const char *prefix, parse_val_t func,
-                       enum at_cmd_type type)
-{
-    int ret;
-
-    while (buf->len) {
-        if (at->cmd_state < AT_CMD_START ||
-            at->cmd_state >= AT_CMD_STATE_END) {
-            return -EINVAL;
-        }
-        ret = cmd_parser_cb[at->cmd_state](at, buf, prefix, func, type);
-        if (ret < 0) {
-            return ret;
-        }
-        /* Check for main state, the end of cmd parsing and return. */
-        if (at->state == AT_STATE_START) {
-            return 0;
-        }
+int at_parse_cmd_input(struct at_client *at, struct net_buf *buf, const char *prefix, parse_val_t func, enum at_cmd_type type) {
+  int ret;
+
+  while (buf->len) {
+    if (at->cmd_state < AT_CMD_START || at->cmd_state >= AT_CMD_STATE_END) {
+      return -EINVAL;
+    }
+    ret = cmd_parser_cb[at->cmd_state](at, buf, prefix, func, type);
+    if (ret < 0) {
+      return ret;
+    }
+    /* Check for main state, the end of cmd parsing and return. */
+    if (at->state == AT_STATE_START) {
+      return 0;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
-int at_has_next_list(struct at_client *at)
-{
-    return at->buf[at->pos] != '\0';
-}
+int at_has_next_list(struct at_client *at) { return at->buf[at->pos] != '\0'; }
 
-int at_open_list(struct at_client *at)
-{
-    skip_space(at);
+int at_open_list(struct at_client *at) {
+  skip_space(at);
 
-    /* The list shall start with '(' open parenthesis */
-    if (at->buf[at->pos] != '(') {
-        return -ENODATA;
-    }
-    at->pos++;
+  /* The list shall start with '(' open parenthesis */
+  if (at->buf[at->pos] != '(') {
+    return -ENODATA;
+  }
+  at->pos++;
 
-    return 0;
+  return 0;
 }
 
-int at_close_list(struct at_client *at)
-{
-    skip_space(at);
+int at_close_list(struct at_client *at) {
+  skip_space(at);
 
-    if (at->buf[at->pos] != ')') {
-        return -ENODATA;
-    }
-    at->pos++;
+  if (at->buf[at->pos] != ')') {
+    return -ENODATA;
+  }
+  at->pos++;
 
-    next_list(at);
+  next_list(at);
 
-    return 0;
+  return 0;
 }
 
-int at_list_get_string(struct at_client *at, char *name, uint8_t len)
-{
-    int i = 0;
-
-    skip_space(at);
+int at_list_get_string(struct at_client *at, char *name, uint8_t len) {
+  int i = 0;
 
-    if (at->buf[at->pos] != '"') {
-        return -ENODATA;
-    }
-    at->pos++;
+  skip_space(at);
 
-    while (at->buf[at->pos] != '\0' && at->buf[at->pos] != '"') {
-        if (i == len) {
-            return -ENODATA;
-        }
-        name[i++] = at->buf[at->pos++];
-    }
+  if (at->buf[at->pos] != '"') {
+    return -ENODATA;
+  }
+  at->pos++;
 
+  while (at->buf[at->pos] != '\0' && at->buf[at->pos] != '"') {
     if (i == len) {
-        return -ENODATA;
+      return -ENODATA;
     }
+    name[i++] = at->buf[at->pos++];
+  }
 
-    name[i] = '\0';
+  if (i == len) {
+    return -ENODATA;
+  }
 
-    if (at->buf[at->pos] != '"') {
-        return -ENODATA;
-    }
-    at->pos++;
+  name[i] = '\0';
+
+  if (at->buf[at->pos] != '"') {
+    return -ENODATA;
+  }
+  at->pos++;
 
-    skip_space(at);
-    next_list(at);
+  skip_space(at);
+  next_list(at);
 
-    return 0;
+  return 0;
 }
 
-int at_list_get_range(struct at_client *at, uint32_t *min, uint32_t *max)
-{
-    uint32_t low, high;
-    int ret;
+int at_list_get_range(struct at_client *at, uint32_t *min, uint32_t *max) {
+  uint32_t low, high;
+  int      ret;
 
-    ret = at_get_number(at, &low);
-    if (ret < 0) {
-        return ret;
-    }
+  ret = at_get_number(at, &low);
+  if (ret < 0) {
+    return ret;
+  }
 
-    if (at->buf[at->pos] == '-') {
-        at->pos++;
-        goto out;
-    }
+  if (at->buf[at->pos] == '-') {
+    at->pos++;
+    goto out;
+  }
 
-    if (!isdigit((unsigned char)at->buf[at->pos])) {
-        return -ENODATA;
-    }
+  if (!isdigit((unsigned char)at->buf[at->pos])) {
+    return -ENODATA;
+  }
 out:
-    ret = at_get_number(at, &high);
-    if (ret < 0) {
-        return ret;
-    }
+  ret = at_get_number(at, &high);
+  if (ret < 0) {
+    return ret;
+  }
 
-    *min = low;
-    *max = high;
+  *min = low;
+  *max = high;
 
-    next_list(at);
+  next_list(at);
 
-    return 0;
+  return 0;
 }
 
-void at_register_unsolicited(struct at_client *at, at_resp_cb_t unsolicited)
-{
-    at->unsolicited = unsolicited;
-}
+void at_register_unsolicited(struct at_client *at, at_resp_cb_t unsolicited) { at->unsolicited = unsolicited; }
 
-void at_register(struct at_client *at, at_resp_cb_t resp, at_finish_cb_t finish)
-{
-    at->resp = resp;
-    at->finish = finish;
-    at->state = AT_STATE_START;
+void at_register(struct at_client *at, at_resp_cb_t resp, at_finish_cb_t finish) {
+  at->resp   = resp;
+  at->finish = finish;
+  at->state  = AT_STATE_START;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c
index d792f0b6e..c2915c551 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att.c
@@ -6,27 +6,30 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
+#include 
 #include 
 #include 
-#include 
+#include 
+#include 
+
 #include 
 #include 
 
-#include 
 #include 
-#include 
 #include 
 #include 
+#include 
+#include 
 
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_ATT)
 #include "log.h"
 
 #include "hci_core.h"
+
 #include "conn_internal.h"
 #include "l2cap_internal.h"
 #include "smp.h"
+
 #include "att_internal.h"
 #include "gatt_internal.h"
 
@@ -38,53 +41,52 @@
 #define ATT_TIMEOUT K_SECONDS(30)
 
 typedef enum __packed {
-    ATT_COMMAND,
-    ATT_REQUEST,
-    ATT_RESPONSE,
-    ATT_NOTIFICATION,
-    ATT_CONFIRMATION,
-    ATT_INDICATION,
-    ATT_UNKNOWN,
+  ATT_COMMAND,
+  ATT_REQUEST,
+  ATT_RESPONSE,
+  ATT_NOTIFICATION,
+  ATT_CONFIRMATION,
+  ATT_INDICATION,
+  ATT_UNKNOWN,
 } att_type_t;
 
 static att_type_t att_op_get_type(u8_t op);
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
 struct bt_attr_data {
-    u16_t handle;
-    u16_t offset;
+  u16_t handle;
+  u16_t offset;
 };
 
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
 /* Pool for incoming ATT packets */
-NET_BUF_POOL_DEFINE(prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU,
-                    sizeof(struct bt_attr_data), NULL);
+NET_BUF_POOL_DEFINE(prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU, sizeof(struct bt_attr_data), NULL);
 #else
 struct net_buf_pool prep_pool;
 #endif
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT */
 
 enum {
-    ATT_PENDING_RSP,
-    ATT_PENDING_CFM,
-    ATT_DISCONNECTED,
+  ATT_PENDING_RSP,
+  ATT_PENDING_CFM,
+  ATT_DISCONNECTED,
 
-    /* Total number of flags - must be at the end of the enum */
-    ATT_NUM_FLAGS,
+  /* Total number of flags - must be at the end of the enum */
+  ATT_NUM_FLAGS,
 };
 
 /* ATT channel specific context */
 struct bt_att {
-    /* The channel this context is associated with */
-    struct bt_l2cap_le_chan chan;
-    ATOMIC_DEFINE(flags, ATT_NUM_FLAGS);
-    struct bt_att_req *req;
-    sys_slist_t reqs;
-    struct k_delayed_work timeout_work;
-    struct k_sem tx_sem;
-    struct k_fifo tx_queue;
+  /* The channel this context is associated with */
+  struct bt_l2cap_le_chan chan;
+  ATOMIC_DEFINE(flags, ATT_NUM_FLAGS);
+  struct bt_att_req    *req;
+  sys_slist_t           reqs;
+  struct k_delayed_work timeout_work;
+  struct k_sem          tx_sem;
+  struct k_fifo         tx_queue;
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-    struct k_fifo prep_queue;
+  struct k_fifo prep_queue;
 #endif
 };
 
@@ -92,2359 +94,2121 @@ struct bt_att {
 extern volatile u8_t event_flag;
 #endif
 
-static struct bt_att bt_req_pool[CONFIG_BT_MAX_CONN];
+static struct bt_att     bt_req_pool[CONFIG_BT_MAX_CONN];
 static struct bt_att_req cancel;
 
 #if defined(CONFIG_BLE_AT_CMD)
 static u16_t mtu_size = BT_ATT_MTU;
-void set_mtu_size(u16_t size)
-{
-    mtu_size = size;
-}
+void         set_mtu_size(u16_t size) { mtu_size = size; }
 #endif
 
-static void att_req_destroy(struct bt_att_req *req)
-{
-    BT_DBG("req %p", req);
+static void att_req_destroy(struct bt_att_req *req) {
+  BT_DBG("req %p", req);
 
-    if (req->buf) {
-        net_buf_unref(req->buf);
-    }
+  if (req->buf) {
+    net_buf_unref(req->buf);
+  }
 
-    if (req->destroy) {
-        req->destroy(req);
-    }
+  if (req->destroy) {
+    req->destroy(req);
+  }
 
-    (void)memset(req, 0, sizeof(*req));
+  (void)memset(req, 0, sizeof(*req));
 }
 
-static struct bt_att *att_get(struct bt_conn *conn)
-{
-    struct bt_l2cap_chan *chan;
+static struct bt_att *att_get(struct bt_conn *conn) {
+  struct bt_l2cap_chan *chan;
 
-    chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_ATT);
-    __ASSERT(chan, "No ATT channel found");
+  chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_ATT);
+  __ASSERT(chan, "No ATT channel found");
 
-    return CONTAINER_OF(chan, struct bt_att, chan);
+  return CONTAINER_OF(chan, struct bt_att, chan);
 }
 
 static bt_conn_tx_cb_t att_cb(struct net_buf *buf);
 
-static int att_send(struct bt_conn *conn, struct net_buf *buf,
-                    bt_conn_tx_cb_t cb, void *user_data)
-{
-    struct bt_att_hdr *hdr;
+static int att_send(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) {
+  struct bt_att_hdr *hdr;
 
-    hdr = (void *)buf->data;
+  hdr = (void *)buf->data;
 
-    BT_DBG("code 0x%02x", hdr->code);
+  BT_DBG("code 0x%02x", hdr->code);
 
 #if defined(CONFIG_BT_SMP) && defined(CONFIG_BT_SIGNING)
-    if (hdr->code == BT_ATT_OP_SIGNED_WRITE_CMD) {
-        int err;
-
-        err = bt_smp_sign(conn, buf);
-        if (err) {
-            BT_ERR("Error signing data");
-            net_buf_unref(buf);
-            return err;
-        }
+  if (hdr->code == BT_ATT_OP_SIGNED_WRITE_CMD) {
+    int err;
+
+    err = bt_smp_sign(conn, buf);
+    if (err) {
+      BT_ERR("Error signing data");
+      net_buf_unref(buf);
+      return err;
     }
+  }
 #endif
-    return bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf,
-                            cb ? cb : att_cb(buf),
-                            user_data);
+  return bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, cb ? cb : att_cb(buf), user_data);
 }
 
-void att_pdu_sent(struct bt_conn *conn, void *user_data)
-{
-    struct bt_att *att = att_get(conn);
-    struct net_buf *buf;
+void att_pdu_sent(struct bt_conn *conn, void *user_data) {
+  struct bt_att  *att = att_get(conn);
+  struct net_buf *buf;
 
-    BT_DBG("conn %p att %p", conn, att);
+  BT_DBG("conn %p att %p", conn, att);
 
-    while ((buf = net_buf_get(&att->tx_queue, K_NO_WAIT))) {
-        /* Check if the queued buf is a request */
-        if (att->req && att->req->buf == buf) {
-            /* Save request state so it can be resent */
-            net_buf_simple_save(&att->req->buf->b,
-                                &att->req->state);
-        }
+  while ((buf = net_buf_get(&att->tx_queue, K_NO_WAIT))) {
+    /* Check if the queued buf is a request */
+    if (att->req && att->req->buf == buf) {
+      /* Save request state so it can be resent */
+      net_buf_simple_save(&att->req->buf->b, &att->req->state);
+    }
 
-        if (!att_send(conn, buf, NULL, NULL)) {
-            return;
-        }
+    if (!att_send(conn, buf, NULL, NULL)) {
+      return;
     }
+  }
 
-    k_sem_give(&att->tx_sem);
+  k_sem_give(&att->tx_sem);
 }
 
-void att_cfm_sent(struct bt_conn *conn, void *user_data)
-{
-    struct bt_att *att = att_get(conn);
+void att_cfm_sent(struct bt_conn *conn, void *user_data) {
+  struct bt_att *att = att_get(conn);
 
-    BT_DBG("conn %p att %p", conn, att);
+  BT_DBG("conn %p att %p", conn, att);
 
-    if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
-        atomic_clear_bit(att->flags, ATT_PENDING_CFM);
-    }
+  if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
+    atomic_clear_bit(att->flags, ATT_PENDING_CFM);
+  }
 
-    att_pdu_sent(conn, user_data);
+  att_pdu_sent(conn, user_data);
 }
 
-void att_rsp_sent(struct bt_conn *conn, void *user_data)
-{
-    struct bt_att *att = att_get(conn);
+void att_rsp_sent(struct bt_conn *conn, void *user_data) {
+  struct bt_att *att = att_get(conn);
 
-    BT_DBG("conn %p att %p", conn, att);
+  BT_DBG("conn %p att %p", conn, att);
 
-    if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
-        atomic_clear_bit(att->flags, ATT_PENDING_RSP);
-    }
+  if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
+    atomic_clear_bit(att->flags, ATT_PENDING_RSP);
+  }
 
-    att_pdu_sent(conn, user_data);
+  att_pdu_sent(conn, user_data);
 }
 
-void att_req_sent(struct bt_conn *conn, void *user_data)
-{
-    struct bt_att *att = att_get(conn);
+void att_req_sent(struct bt_conn *conn, void *user_data) {
+  struct bt_att *att = att_get(conn);
 
-    BT_DBG("conn %p att %p att->req %p", conn, att, att->req);
+  BT_DBG("conn %p att %p att->req %p", conn, att, att->req);
 
-    /* Start timeout work */
-    if (att->req) {
-        k_delayed_work_submit(&att->timeout_work, ATT_TIMEOUT);
-    }
+  /* Start timeout work */
+  if (att->req) {
+    k_delayed_work_submit(&att->timeout_work, ATT_TIMEOUT);
+  }
 
-    att_pdu_sent(conn, user_data);
-}
-
-static bt_conn_tx_cb_t att_cb(struct net_buf *buf)
-{
-    switch (att_op_get_type(buf->data[0])) {
-        case ATT_RESPONSE:
-            return att_rsp_sent;
-        case ATT_CONFIRMATION:
-            return att_cfm_sent;
-        case ATT_REQUEST:
-        case ATT_INDICATION:
-            return att_req_sent;
-        default:
-            return att_pdu_sent;
-    }
+  att_pdu_sent(conn, user_data);
 }
 
-static void send_err_rsp(struct bt_conn *conn, u8_t req, u16_t handle,
-                         u8_t err)
-{
-    struct bt_att_error_rsp *rsp;
-    struct net_buf *buf;
+static bt_conn_tx_cb_t att_cb(struct net_buf *buf) {
+  switch (att_op_get_type(buf->data[0])) {
+  case ATT_RESPONSE:
+    return att_rsp_sent;
+  case ATT_CONFIRMATION:
+    return att_cfm_sent;
+  case ATT_REQUEST:
+  case ATT_INDICATION:
+    return att_req_sent;
+  default:
+    return att_pdu_sent;
+  }
+}
 
-    /* Ignore opcode 0x00 */
-    if (!req) {
-        return;
-    }
+static void send_err_rsp(struct bt_conn *conn, u8_t req, u16_t handle, u8_t err) {
+  struct bt_att_error_rsp *rsp;
+  struct net_buf          *buf;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_ERROR_RSP, sizeof(*rsp));
-    if (!buf) {
-        return;
-    }
+  /* Ignore opcode 0x00 */
+  if (!req) {
+    return;
+  }
 
-    rsp = net_buf_add(buf, sizeof(*rsp));
-    rsp->request = req;
-    rsp->handle = sys_cpu_to_le16(handle);
-    rsp->error = err;
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_ERROR_RSP, sizeof(*rsp));
+  if (!buf) {
+    return;
+  }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL);
+  rsp          = net_buf_add(buf, sizeof(*rsp));
+  rsp->request = req;
+  rsp->handle  = sys_cpu_to_le16(handle);
+  rsp->error   = err;
+
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL);
 }
 
-static u8_t att_mtu_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_exchange_mtu_req *req;
-    struct bt_att_exchange_mtu_rsp *rsp;
-    struct net_buf *pdu;
-    u16_t mtu_client, mtu_server;
+static u8_t att_mtu_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn                 *conn = att->chan.chan.conn;
+  struct bt_att_exchange_mtu_req *req;
+  struct bt_att_exchange_mtu_rsp *rsp;
+  struct net_buf                 *pdu;
+  u16_t                           mtu_client, mtu_server;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    mtu_client = sys_le16_to_cpu(req->mtu);
+  mtu_client = sys_le16_to_cpu(req->mtu);
 
-    BT_DBG("Client MTU %u", mtu_client);
+  BT_DBG("Client MTU %u", mtu_client);
 
-    /* Check if MTU is valid */
-    if (mtu_client < BT_ATT_DEFAULT_LE_MTU) {
-        return BT_ATT_ERR_INVALID_PDU;
-    }
+  /* Check if MTU is valid */
+  if (mtu_client < BT_ATT_DEFAULT_LE_MTU) {
+    return BT_ATT_ERR_INVALID_PDU;
+  }
 
-    pdu = bt_att_create_pdu(conn, BT_ATT_OP_MTU_RSP, sizeof(*rsp));
-    if (!pdu) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  pdu = bt_att_create_pdu(conn, BT_ATT_OP_MTU_RSP, sizeof(*rsp));
+  if (!pdu) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    mtu_server = BT_ATT_MTU;
+  mtu_server = BT_ATT_MTU;
 
-    BT_DBG("Server MTU %u", mtu_server);
+  BT_DBG("Server MTU %u", mtu_server);
 
-    rsp = net_buf_add(pdu, sizeof(*rsp));
-    rsp->mtu = sys_cpu_to_le16(mtu_server);
+  rsp      = net_buf_add(pdu, sizeof(*rsp));
+  rsp->mtu = sys_cpu_to_le16(mtu_server);
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, pdu, att_rsp_sent, NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, pdu, att_rsp_sent, NULL);
 
-    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484:
-	 *
-	 * A device's Exchange MTU Request shall contain the same MTU as the
-	 * device's Exchange MTU Response (i.e. the MTU shall be symmetric).
-	 */
-    att->chan.rx.mtu = MIN(mtu_client, mtu_server);
-    att->chan.tx.mtu = att->chan.rx.mtu;
+  /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484:
+   *
+   * A device's Exchange MTU Request shall contain the same MTU as the
+   * device's Exchange MTU Response (i.e. the MTU shall be symmetric).
+   */
+  att->chan.rx.mtu = MIN(mtu_client, mtu_server);
+  att->chan.tx.mtu = att->chan.rx.mtu;
 
-    BT_DBG("Negotiated MTU %u", att->chan.rx.mtu);
+  BT_DBG("Negotiated MTU %u", att->chan.rx.mtu);
 
 #if defined(BFLB_BLE_MTU_CHANGE_CB)
-    if (att->chan.chan.ops->mtu_changed)
-        att->chan.chan.ops->mtu_changed(&(att->chan.chan), att->chan.rx.mtu);
+  if (att->chan.chan.ops->mtu_changed)
+    att->chan.chan.ops->mtu_changed(&(att->chan.chan), att->chan.rx.mtu);
 #endif
 
-    return 0;
+  return 0;
 }
 
-static inline bool att_is_connected(struct bt_att *att)
-{
-    return (att->chan.chan.conn->state != BT_CONN_CONNECTED ||
-            !atomic_test_bit(att->flags, ATT_DISCONNECTED));
-}
+static inline bool att_is_connected(struct bt_att *att) { return (att->chan.chan.conn->state != BT_CONN_CONNECTED || !atomic_test_bit(att->flags, ATT_DISCONNECTED)); }
 
-static int att_send_req(struct bt_att *att, struct bt_att_req *req)
-{
-    int err;
+static int att_send_req(struct bt_att *att, struct bt_att_req *req) {
+  int err;
 
-    __ASSERT_NO_MSG(req);
-    __ASSERT_NO_MSG(req->func);
-    __ASSERT_NO_MSG(!att->req);
+  __ASSERT_NO_MSG(req);
+  __ASSERT_NO_MSG(req->func);
+  __ASSERT_NO_MSG(!att->req);
 
-    BT_DBG("req %p", req);
+  BT_DBG("req %p", req);
 
-    att->req = req;
+  att->req = req;
 
-    if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) {
-        k_fifo_put(&att->tx_queue, req->buf);
-        return 0;
-    }
+  if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) {
+    k_fifo_put(&att->tx_queue, req->buf);
+    return 0;
+  }
 
-    /* Save request state so it can be resent */
-    net_buf_simple_save(&req->buf->b, &req->state);
+  /* Save request state so it can be resent */
+  net_buf_simple_save(&req->buf->b, &req->state);
 
-    /* Keep a reference for resending in case of an error */
-    err = bt_l2cap_send_cb(att->chan.chan.conn, BT_L2CAP_CID_ATT,
-                           net_buf_ref(req->buf), att_cb(req->buf), NULL);
-    if (err) {
-        net_buf_unref(req->buf);
-        req->buf = NULL;
-        return err;
-    }
+  /* Keep a reference for resending in case of an error */
+  err = bt_l2cap_send_cb(att->chan.chan.conn, BT_L2CAP_CID_ATT, net_buf_ref(req->buf), att_cb(req->buf), NULL);
+  if (err) {
+    net_buf_unref(req->buf);
+    req->buf = NULL;
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-static void att_process(struct bt_att *att)
-{
-    sys_snode_t *node;
+static void att_process(struct bt_att *att) {
+  sys_snode_t *node;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    /* Pull next request from the list */
-    node = sys_slist_get(&att->reqs);
-    if (!node) {
-        return;
-    }
+  /* Pull next request from the list */
+  node = sys_slist_get(&att->reqs);
+  if (!node) {
+    return;
+  }
 
-    att_send_req(att, ATT_REQ(node));
+  att_send_req(att, ATT_REQ(node));
 }
 
-static u8_t att_handle_rsp(struct bt_att *att, void *pdu, u16_t len, u8_t err)
-{
-    bt_att_func_t func;
+static u8_t att_handle_rsp(struct bt_att *att, void *pdu, u16_t len, u8_t err) {
+  bt_att_func_t func;
 
-    BT_DBG("err 0x%02x len %u: %s", err, len, bt_hex(pdu, len));
+  BT_DBG("err 0x%02x len %u: %s", err, len, bt_hex(pdu, len));
 
-    /* Cancel timeout if ongoing */
-    k_delayed_work_cancel(&att->timeout_work);
+  /* Cancel timeout if ongoing */
+  k_delayed_work_cancel(&att->timeout_work);
 
-    if (!att->req) {
-        BT_WARN("No pending ATT request");
-        goto process;
-    }
+  if (!att->req) {
+    BT_WARN("No pending ATT request");
+    goto process;
+  }
 
-    /* Check if request has been cancelled */
-    if (att->req == &cancel) {
-        att->req = NULL;
-        goto process;
-    }
+  /* Check if request has been cancelled */
+  if (att->req == &cancel) {
+    att->req = NULL;
+    goto process;
+  }
 
-    /* Release original buffer */
-    if (att->req->buf) {
-        net_buf_unref(att->req->buf);
-        att->req->buf = NULL;
-    }
+  /* Release original buffer */
+  if (att->req->buf) {
+    net_buf_unref(att->req->buf);
+    att->req->buf = NULL;
+  }
 
-    /* Reset func so it can be reused by the callback */
-    func = att->req->func;
-    att->req->func = NULL;
+  /* Reset func so it can be reused by the callback */
+  func           = att->req->func;
+  att->req->func = NULL;
 
+  if (func) {
     func(att->chan.chan.conn, err, pdu, len, att->req);
+  }
 
-    /* Don't destroy if callback had reused the request */
-    if (!att->req->func) {
-        att_req_destroy(att->req);
-    }
+  /* Don't destroy if callback had reused the request */
+  if (!att->req->func) {
+    att_req_destroy(att->req);
+  }
 
-    att->req = NULL;
+  att->req = NULL;
 
 process:
-    /* Process pending requests */
-    att_process(att);
+  /* Process pending requests */
+  att_process(att);
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_GATT_CLIENT)
-static u8_t att_mtu_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_att_exchange_mtu_rsp *rsp;
-    u16_t mtu;
+static u8_t att_mtu_rsp(struct bt_att *att, struct net_buf *buf) {
+  struct bt_att_exchange_mtu_rsp *rsp;
+  u16_t                           mtu;
 
-    if (!att) {
-        return 0;
-    }
+  if (!att) {
+    return 0;
+  }
 
-    rsp = (void *)buf->data;
+  rsp = (void *)buf->data;
 
-    mtu = sys_le16_to_cpu(rsp->mtu);
+  mtu = sys_le16_to_cpu(rsp->mtu);
 
-    BT_DBG("Server MTU %u", mtu);
+  BT_DBG("Server MTU %u", mtu);
 
-    /* Check if MTU is valid */
-    if (mtu < BT_ATT_DEFAULT_LE_MTU) {
-        return att_handle_rsp(att, NULL, 0, BT_ATT_ERR_INVALID_PDU);
-    }
+  /* Check if MTU is valid */
+  if (mtu < BT_ATT_DEFAULT_LE_MTU) {
+    return att_handle_rsp(att, NULL, 0, BT_ATT_ERR_INVALID_PDU);
+  }
 
-    att->chan.rx.mtu = MIN(mtu, BT_ATT_MTU);
+  att->chan.rx.mtu = MIN(mtu, BT_ATT_MTU);
 
-    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484:
-	 *
-	 * A device's Exchange MTU Request shall contain the same MTU as the
-	 * device's Exchange MTU Response (i.e. the MTU shall be symmetric).
-	 */
-    att->chan.tx.mtu = att->chan.rx.mtu;
+  /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484:
+   *
+   * A device's Exchange MTU Request shall contain the same MTU as the
+   * device's Exchange MTU Response (i.e. the MTU shall be symmetric).
+   */
+  att->chan.tx.mtu = att->chan.rx.mtu;
 
-    BT_DBG("Negotiated MTU %u", att->chan.rx.mtu);
+  BT_DBG("Negotiated MTU %u", att->chan.rx.mtu);
 
-    return att_handle_rsp(att, rsp, buf->len, 0);
+  return att_handle_rsp(att, rsp, buf->len, 0);
 }
 #endif /* CONFIG_BT_GATT_CLIENT */
 
-static bool range_is_valid(u16_t start, u16_t end, u16_t *err)
-{
-    /* Handle 0 is invalid */
-    if (!start || !end) {
-        if (err) {
-            *err = 0U;
-        }
-        return false;
+static bool range_is_valid(u16_t start, u16_t end, u16_t *err) {
+  /* Handle 0 is invalid */
+  if (!start || !end) {
+    if (err) {
+      *err = 0U;
     }
+    return false;
+  }
 
-    /* Check if range is valid */
-    if (start > end) {
-        if (err) {
-            *err = start;
-        }
-        return false;
+  /* Check if range is valid */
+  if (start > end) {
+    if (err) {
+      *err = start;
     }
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
 struct find_info_data {
-    struct bt_att *att;
-    struct net_buf *buf;
-    struct bt_att_find_info_rsp *rsp;
-    union {
-        struct bt_att_info_16 *info16;
-        struct bt_att_info_128 *info128;
-    };
+  struct bt_att               *att;
+  struct net_buf              *buf;
+  struct bt_att_find_info_rsp *rsp;
+  union {
+    struct bt_att_info_16  *info16;
+    struct bt_att_info_128 *info128;
+  };
 };
 
-static u8_t find_info_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct find_info_data *data = user_data;
-    struct bt_att *att = data->att;
+static u8_t find_info_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct find_info_data *data = user_data;
+  struct bt_att         *att  = data->att;
 
-    BT_DBG("handle 0x%04x", attr->handle);
+  BT_DBG("handle 0x%04x", attr->handle);
 
-    /* Initialize rsp at first entry */
-    if (!data->rsp) {
-        data->rsp = net_buf_add(data->buf, sizeof(*data->rsp));
-        data->rsp->format = (attr->uuid->type == BT_UUID_TYPE_16) ?
-                                BT_ATT_INFO_16 :
-                                BT_ATT_INFO_128;
-    }
+  /* Initialize rsp at first entry */
+  if (!data->rsp) {
+    data->rsp         = net_buf_add(data->buf, sizeof(*data->rsp));
+    data->rsp->format = (attr->uuid->type == BT_UUID_TYPE_16) ? BT_ATT_INFO_16 : BT_ATT_INFO_128;
+  }
 
-    switch (data->rsp->format) {
-        case BT_ATT_INFO_16:
-            if (attr->uuid->type != BT_UUID_TYPE_16) {
-                return BT_GATT_ITER_STOP;
-            }
-
-            /* Fast forward to next item position */
-            data->info16 = net_buf_add(data->buf, sizeof(*data->info16));
-            data->info16->handle = sys_cpu_to_le16(attr->handle);
-            data->info16->uuid = sys_cpu_to_le16(BT_UUID_16(attr->uuid)->val);
-
-            if (att->chan.tx.mtu - data->buf->len >
-                sizeof(*data->info16)) {
-                return BT_GATT_ITER_CONTINUE;
-            }
-
-            break;
-        case BT_ATT_INFO_128:
-            if (attr->uuid->type != BT_UUID_TYPE_128) {
-                return BT_GATT_ITER_STOP;
-            }
-
-            /* Fast forward to next item position */
-            data->info128 = net_buf_add(data->buf, sizeof(*data->info128));
-            data->info128->handle = sys_cpu_to_le16(attr->handle);
-            memcpy(data->info128->uuid, BT_UUID_128(attr->uuid)->val,
-                   sizeof(data->info128->uuid));
-
-            if (att->chan.tx.mtu - data->buf->len >
-                sizeof(*data->info128)) {
-                return BT_GATT_ITER_CONTINUE;
-            }
+  switch (data->rsp->format) {
+  case BT_ATT_INFO_16:
+    if (attr->uuid->type != BT_UUID_TYPE_16) {
+      return BT_GATT_ITER_STOP;
     }
 
-    return BT_GATT_ITER_STOP;
-}
-
-static u8_t att_find_info_rsp(struct bt_att *att, u16_t start_handle,
-                              u16_t end_handle)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct find_info_data data;
+    /* Fast forward to next item position */
+    data->info16         = net_buf_add(data->buf, sizeof(*data->info16));
+    data->info16->handle = sys_cpu_to_le16(attr->handle);
+    data->info16->uuid   = sys_cpu_to_le16(BT_UUID_16(attr->uuid)->val);
 
-    (void)memset(&data, 0, sizeof(data));
+    if (att->chan.tx.mtu - data->buf->len > sizeof(*data->info16)) {
+      return BT_GATT_ITER_CONTINUE;
+    }
 
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_RSP, 0);
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
+    break;
+  case BT_ATT_INFO_128:
+    if (attr->uuid->type != BT_UUID_TYPE_128) {
+      return BT_GATT_ITER_STOP;
     }
 
-    data.att = att;
-    bt_gatt_foreach_attr(start_handle, end_handle, find_info_cb, &data);
+    /* Fast forward to next item position */
+    data->info128         = net_buf_add(data->buf, sizeof(*data->info128));
+    data->info128->handle = sys_cpu_to_le16(attr->handle);
+    memcpy(data->info128->uuid, BT_UUID_128(attr->uuid)->val, sizeof(data->info128->uuid));
 
-    if (!data.rsp) {
-        net_buf_unref(data.buf);
-        /* Respond since handle is set */
-        send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, start_handle,
-                     BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
-        return 0;
+    if (att->chan.tx.mtu - data->buf->len > sizeof(*data->info128)) {
+      return BT_GATT_ITER_CONTINUE;
     }
+  }
+
+  return BT_GATT_ITER_STOP;
+}
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+static u8_t att_find_info_rsp(struct bt_att *att, u16_t start_handle, u16_t end_handle) {
+  struct bt_conn       *conn = att->chan.chan.conn;
+  struct find_info_data data;
 
+  (void)memset(&data, 0, sizeof(data));
+
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_RSP, 0);
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
+
+  data.att = att;
+  bt_gatt_foreach_attr(start_handle, end_handle, find_info_cb, &data);
+
+  if (!data.rsp) {
+    net_buf_unref(data.buf);
+    /* Respond since handle is set */
+    send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
     return 0;
+  }
+
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
+
+  return 0;
 }
 
-static u8_t att_find_info_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_find_info_req *req;
-    u16_t start_handle, end_handle, err_handle;
+static u8_t att_find_info_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn              *conn = att->chan.chan.conn;
+  struct bt_att_find_info_req *req;
+  u16_t                        start_handle, end_handle, err_handle;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    start_handle = sys_le16_to_cpu(req->start_handle);
-    end_handle = sys_le16_to_cpu(req->end_handle);
+  start_handle = sys_le16_to_cpu(req->start_handle);
+  end_handle   = sys_le16_to_cpu(req->end_handle);
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle,
-           end_handle);
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, end_handle);
 
-    if (!range_is_valid(start_handle, end_handle, &err_handle)) {
-        send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, err_handle,
-                     BT_ATT_ERR_INVALID_HANDLE);
-        return 0;
-    }
+  if (!range_is_valid(start_handle, end_handle, &err_handle)) {
+    send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE);
+    return 0;
+  }
 
-    return att_find_info_rsp(att, start_handle, end_handle);
+  return att_find_info_rsp(att, start_handle, end_handle);
 }
 
 struct find_type_data {
-    struct bt_att *att;
-    struct net_buf *buf;
-    struct bt_att_handle_group *group;
-    const void *value;
-    u8_t value_len;
-    u8_t err;
+  struct bt_att              *att;
+  struct net_buf             *buf;
+  struct bt_att_handle_group *group;
+  const void                 *value;
+  u8_t                        value_len;
+  u8_t                        err;
 };
 
-static u8_t find_type_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct find_type_data *data = user_data;
-    struct bt_att *att = data->att;
-    struct bt_conn *conn = att->chan.chan.conn;
-    int read;
-    u8_t uuid[16];
-
-    /* Skip secondary services */
-    if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
-        goto skip;
-    }
+static u8_t find_type_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct find_type_data *data = user_data;
+  struct bt_att         *att  = data->att;
+  struct bt_conn        *conn = att->chan.chan.conn;
+  int                    read;
+  u8_t                   uuid[16];
 
-    /* Update group end_handle if not a primary service */
-    if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY)) {
-        if (data->group &&
-            attr->handle > sys_le16_to_cpu(data->group->end_handle)) {
-            data->group->end_handle = sys_cpu_to_le16(attr->handle);
-        }
-        return BT_GATT_ITER_CONTINUE;
+  /* Skip secondary services */
+  if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
+    goto skip;
+  }
+
+  /* Update group end_handle if not a primary service */
+  if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY)) {
+    if (data->group && attr->handle > sys_le16_to_cpu(data->group->end_handle)) {
+      data->group->end_handle = sys_cpu_to_le16(attr->handle);
     }
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    BT_DBG("handle 0x%04x", attr->handle);
+  BT_DBG("handle 0x%04x", attr->handle);
 
-    /* stop if there is no space left */
-    if (att->chan.tx.mtu - data->buf->len < sizeof(*data->group)) {
-        return BT_GATT_ITER_STOP;
-    }
+  /* stop if there is no space left */
+  if (att->chan.tx.mtu - data->buf->len < sizeof(*data->group)) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    /* Read attribute value and store in the buffer */
-    read = attr->read(conn, attr, uuid, sizeof(uuid), 0);
-    if (read < 0) {
-        /*
-		 * Since we don't know if it is the service with requested UUID,
-		 * we cannot respond with an error to this request.
-		 */
-        goto skip;
-    }
+  /* Read attribute value and store in the buffer */
+  read = attr->read(conn, attr, uuid, sizeof(uuid), 0);
+  if (read < 0) {
+    /*
+     * Since we don't know if it is the service with requested UUID,
+     * we cannot respond with an error to this request.
+     */
+    goto skip;
+  }
+
+  /* Check if data matches */
+  if (read != data->value_len) {
+    /* Use bt_uuid_cmp() to compare UUIDs of different form. */
+    struct bt_uuid_128 ref_uuid;
+    struct bt_uuid_128 recvd_uuid;
 
-    /* Check if data matches */
-    if (read != data->value_len) {
-        /* Use bt_uuid_cmp() to compare UUIDs of different form. */
-        struct bt_uuid_128 ref_uuid;
-        struct bt_uuid_128 recvd_uuid;
-
-        if (!bt_uuid_create(&recvd_uuid.uuid, data->value, data->value_len)) {
-            BT_WARN("Unable to create UUID: size %u", data->value_len);
-            goto skip;
-        }
-        if (!bt_uuid_create(&ref_uuid.uuid, uuid, read)) {
-            BT_WARN("Unable to create UUID: size %d", read);
-            goto skip;
-        }
-        if (bt_uuid_cmp(&recvd_uuid.uuid, &ref_uuid.uuid)) {
-            goto skip;
-        }
-    } else if (memcmp(data->value, uuid, read)) {
-        goto skip;
+    if (!bt_uuid_create(&recvd_uuid.uuid, data->value, data->value_len)) {
+      BT_WARN("Unable to create UUID: size %u", data->value_len);
+      goto skip;
     }
+    if (!bt_uuid_create(&ref_uuid.uuid, uuid, read)) {
+      BT_WARN("Unable to create UUID: size %d", read);
+      goto skip;
+    }
+    if (bt_uuid_cmp(&recvd_uuid.uuid, &ref_uuid.uuid)) {
+      goto skip;
+    }
+  } else if (memcmp(data->value, uuid, read)) {
+    goto skip;
+  }
 
-    /* If service has been found, error should be cleared */
-    data->err = 0x00;
+  /* If service has been found, error should be cleared */
+  data->err = 0x00;
 
-    /* Fast forward to next item position */
-    data->group = net_buf_add(data->buf, sizeof(*data->group));
-    data->group->start_handle = sys_cpu_to_le16(attr->handle);
-    data->group->end_handle = sys_cpu_to_le16(attr->handle);
+  /* Fast forward to next item position */
+  data->group               = net_buf_add(data->buf, sizeof(*data->group));
+  data->group->start_handle = sys_cpu_to_le16(attr->handle);
+  data->group->end_handle   = sys_cpu_to_le16(attr->handle);
 
-    /* continue to find the end_handle */
-    return BT_GATT_ITER_CONTINUE;
+  /* continue to find the end_handle */
+  return BT_GATT_ITER_CONTINUE;
 
 skip:
-    data->group = NULL;
-    return BT_GATT_ITER_CONTINUE;
+  data->group = NULL;
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t att_find_type_rsp(struct bt_att *att, u16_t start_handle,
-                              u16_t end_handle, const void *value,
-                              u8_t value_len)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct find_type_data data;
+static u8_t att_find_type_rsp(struct bt_att *att, u16_t start_handle, u16_t end_handle, const void *value, u8_t value_len) {
+  struct bt_conn       *conn = att->chan.chan.conn;
+  struct find_type_data data;
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_RSP, 0);
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_RSP, 0);
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    data.att = att;
-    data.group = NULL;
-    data.value = value;
-    data.value_len = value_len;
+  data.att       = att;
+  data.group     = NULL;
+  data.value     = value;
+  data.value_len = value_len;
 
-    /* Pre-set error in case no service will be found */
-    data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND;
+  /* Pre-set error in case no service will be found */
+  data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND;
 
-    bt_gatt_foreach_attr(start_handle, end_handle, find_type_cb, &data);
+  bt_gatt_foreach_attr(start_handle, end_handle, find_type_cb, &data);
 
-    /* If error has not been cleared, no service has been found */
-    if (data.err) {
-        net_buf_unref(data.buf);
-        /* Respond since handle is set */
-        send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle,
-                     data.err);
+  /* If error has not been cleared, no service has been found */
+  if (data.err) {
+    net_buf_unref(data.buf);
+    /* Respond since handle is set */
+    send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle, data.err);
 
 #if defined(CONFIG_BT_STACK_PTS)
-        /*PTS sends a request to the iut discover all primary services it contains */
-        if (event_flag == att_find_by_type_value_ind) {
-            BT_PTS("rsp err : [%d] start_handle = [0x%04x]\r\n", data.err, start_handle);
-        }
-#endif
-        return 0;
+    /*PTS sends a request to the iut discover all primary services it contains */
+    if (event_flag == att_find_by_type_value_ind) {
+      BT_PTS("rsp err : [%d] start_handle = [0x%04x]\r\n", data.err, start_handle);
     }
+#endif
+    return 0;
+  }
 
 #if defined(CONFIG_BT_STACK_PTS)
-    /*when PTS sends a request to the iut discover all primary services it contains, set event flag 
-	 * to @att_find_by_type_value_ind make it easy for the user to check whether the messages is correct in the console.
-	 */
-    if (event_flag == att_find_by_type_value_ind) {
-        u8_t i = 0;
-        u8_t *req_val = (u8_t *)data.value;
-        u8_t src[20];
-
-        (void)memcpy(src, req_val, data.value_len);
+  /*when PTS sends a request to the iut discover all primary services it contains, set event flag
+   * to @att_find_by_type_value_ind make it easy for the user to check whether the messages is correct in the console.
+   */
+  if (event_flag == att_find_by_type_value_ind) {
+    u8_t  i       = 0;
+    u8_t *req_val = (u8_t *)data.value;
+    u8_t  src[20];
 
-        BT_PTS("uuid = [");
-        for (i = 0; i < value_len; i++) {
-            BT_PTS("%02x", src[value_len - 1 - i]);
-        }
-        BT_PTS("]\r\n");
+    (void)memcpy(src, req_val, data.value_len);
 
-        BT_PTS("start_handle = [0x%04x] end_handle = [0x%04x]\r\n", data.buf->data[1] | data.buf->data[2] << 8,
-               data.buf->data[3] | data.buf->data[4] << 8);
+    BT_PTS("uuid = [");
+    for (i = 0; i < value_len; i++) {
+      BT_PTS("%02x", src[value_len - 1 - i]);
     }
+    BT_PTS("]\r\n");
+
+    BT_PTS("start_handle = [0x%04x] end_handle = [0x%04x]\r\n", data.buf->data[1] | data.buf->data[2] << 8, data.buf->data[3] | data.buf->data[4] << 8);
+  }
 #endif
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 
-static u8_t att_find_type_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_find_type_req *req;
-    u16_t start_handle, end_handle, err_handle, type;
-    u8_t *value;
-
-    req = net_buf_pull_mem(buf, sizeof(*req));
+static u8_t att_find_type_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn              *conn = att->chan.chan.conn;
+  struct bt_att_find_type_req *req;
+  u16_t                        start_handle, end_handle, err_handle, type;
+  u8_t                        *value;
 
-    start_handle = sys_le16_to_cpu(req->start_handle);
-    end_handle = sys_le16_to_cpu(req->end_handle);
-    type = sys_le16_to_cpu(req->type);
-    value = buf->data;
+  req = net_buf_pull_mem(buf, sizeof(*req));
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x type %u", start_handle,
-           end_handle, type);
+  start_handle = sys_le16_to_cpu(req->start_handle);
+  end_handle   = sys_le16_to_cpu(req->end_handle);
+  type         = sys_le16_to_cpu(req->type);
+  value        = buf->data;
 
-    if (!range_is_valid(start_handle, end_handle, &err_handle)) {
-        send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, err_handle,
-                     BT_ATT_ERR_INVALID_HANDLE);
-        return 0;
-    }
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x type %u", start_handle, end_handle, type);
 
-    /* The Attribute Protocol Find By Type Value Request shall be used with
-	 * the Attribute Type parameter set to the UUID for "Primary Service"
-	 * and the Attribute Value set to the 16-bit Bluetooth UUID or 128-bit
-	 * UUID for the specific primary service.
-	 */
-    if (bt_uuid_cmp(BT_UUID_DECLARE_16(type), BT_UUID_GATT_PRIMARY)) {
-        send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle,
-                     BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
-        return 0;
-    }
+  if (!range_is_valid(start_handle, end_handle, &err_handle)) {
+    send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE);
+    return 0;
+  }
+
+  /* The Attribute Protocol Find By Type Value Request shall be used with
+   * the Attribute Type parameter set to the UUID for "Primary Service"
+   * and the Attribute Value set to the 16-bit Bluetooth UUID or 128-bit
+   * UUID for the specific primary service.
+   */
+  if (bt_uuid_cmp(BT_UUID_DECLARE_16(type), BT_UUID_GATT_PRIMARY)) {
+    send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
+    return 0;
+  }
 
-    return att_find_type_rsp(att, start_handle, end_handle, value,
-                             buf->len);
+  return att_find_type_rsp(att, start_handle, end_handle, value, buf->len);
 }
 
-static u8_t err_to_att(int err)
-{
-    BT_DBG("%d", err);
+static u8_t err_to_att(int err) {
+  BT_DBG("%d", err);
 
-    if (err < 0 && err >= -0xff) {
-        return -err;
-    }
+  if (err < 0 && err >= -0xff) {
+    return -err;
+  }
 
-    return BT_ATT_ERR_UNLIKELY;
+  return BT_ATT_ERR_UNLIKELY;
 }
 
 struct read_type_data {
-    struct bt_att *att;
-    struct bt_uuid *uuid;
-    struct net_buf *buf;
-    struct bt_att_read_type_rsp *rsp;
-    struct bt_att_data *item;
-    u8_t err;
+  struct bt_att               *att;
+  struct bt_uuid              *uuid;
+  struct net_buf              *buf;
+  struct bt_att_read_type_rsp *rsp;
+  struct bt_att_data          *item;
+  u8_t                         err;
 };
 
-static u8_t read_type_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct read_type_data *data = user_data;
-    struct bt_att *att = data->att;
-    struct bt_conn *conn = att->chan.chan.conn;
-    int read;
-
-    /* Skip if doesn't match */
-    if (bt_uuid_cmp(attr->uuid, data->uuid)) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+static u8_t read_type_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct read_type_data *data = user_data;
+  struct bt_att         *att  = data->att;
+  struct bt_conn        *conn = att->chan.chan.conn;
+  int                    read;
 
-    BT_DBG("handle 0x%04x", attr->handle);
-
-    /*
-	 * If an attribute in the set of requested attributes would cause an
-	 * Error Response then this attribute cannot be included in a
-	 * Read By Type Response and the attributes before this attribute
-	 * shall be returned
-	 *
-	 * If the first attribute in the set of requested attributes would
-	 * cause an Error Response then no other attributes in the requested
-	 * attributes can be considered.
-	 */
-    data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK);
-    if (data->err) {
-        if (data->rsp->len) {
-            data->err = 0x00;
-        }
-        return BT_GATT_ITER_STOP;
-    }
-
-    /*
-	 * If any attribute is founded in handle range it means that error
-	 * should be changed from pre-set: attr not found error to no error.
-	 */
-    data->err = 0x00;
-
-    /* Fast forward to next item position */
-    data->item = net_buf_add(data->buf, sizeof(*data->item));
-    data->item->handle = sys_cpu_to_le16(attr->handle);
-
-    /* Read attribute value and store in the buffer */
-    read = attr->read(conn, attr, data->buf->data + data->buf->len,
-                      att->chan.tx.mtu - data->buf->len, 0);
-    if (read < 0) {
-        data->err = err_to_att(read);
-        return BT_GATT_ITER_STOP;
-    }
-
-    if (!data->rsp->len) {
-        /* Set len to be the first item found */
-        data->rsp->len = read + sizeof(*data->item);
-    } else if (data->rsp->len != read + sizeof(*data->item)) {
-        /* All items should have the same size */
-        data->buf->len -= sizeof(*data->item);
-        return BT_GATT_ITER_STOP;
+  /* Skip if doesn't match */
+  if (bt_uuid_cmp(attr->uuid, data->uuid)) {
+    return BT_GATT_ITER_CONTINUE;
+  }
+
+  BT_DBG("handle 0x%04x", attr->handle);
+
+  /*
+   * If an attribute in the set of requested attributes would cause an
+   * Error Response then this attribute cannot be included in a
+   * Read By Type Response and the attributes before this attribute
+   * shall be returned
+   *
+   * If the first attribute in the set of requested attributes would
+   * cause an Error Response then no other attributes in the requested
+   * attributes can be considered.
+   */
+  data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK);
+  if (data->err) {
+    if (data->rsp->len) {
+      data->err = 0x00;
     }
+    return BT_GATT_ITER_STOP;
+  }
+
+  /*
+   * If any attribute is founded in handle range it means that error
+   * should be changed from pre-set: attr not found error to no error.
+   */
+  data->err = 0x00;
+
+  /* Fast forward to next item position */
+  data->item         = net_buf_add(data->buf, sizeof(*data->item));
+  data->item->handle = sys_cpu_to_le16(attr->handle);
+
+  /* Read attribute value and store in the buffer */
+  read = attr->read(conn, attr, data->buf->data + data->buf->len, att->chan.tx.mtu - data->buf->len, 0);
+  if (read < 0) {
+    data->err = err_to_att(read);
+    return BT_GATT_ITER_STOP;
+  }
+
+  if (!data->rsp->len) {
+    /* Set len to be the first item found */
+    data->rsp->len = read + sizeof(*data->item);
+  } else if (data->rsp->len != read + sizeof(*data->item)) {
+    /* All items should have the same size */
+    data->buf->len -= sizeof(*data->item);
+    return BT_GATT_ITER_STOP;
+  }
 
-    net_buf_add(data->buf, read);
+  net_buf_add(data->buf, read);
 
-    /* return true only if there are still space for more items */
-    return att->chan.tx.mtu - data->buf->len > data->rsp->len ?
-               BT_GATT_ITER_CONTINUE :
-               BT_GATT_ITER_STOP;
+  /* return true only if there are still space for more items */
+  return att->chan.tx.mtu - data->buf->len > data->rsp->len ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP;
 }
 
-static u8_t att_read_type_rsp(struct bt_att *att, struct bt_uuid *uuid,
-                              u16_t start_handle, u16_t end_handle)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct read_type_data data;
+static u8_t att_read_type_rsp(struct bt_att *att, struct bt_uuid *uuid, u16_t start_handle, u16_t end_handle) {
+  struct bt_conn       *conn = att->chan.chan.conn;
+  struct read_type_data data;
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_RSP,
-                                 sizeof(*data.rsp));
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_RSP, sizeof(*data.rsp));
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    data.att = att;
-    data.uuid = uuid;
-    data.rsp = net_buf_add(data.buf, sizeof(*data.rsp));
-    data.rsp->len = 0U;
+  data.att      = att;
+  data.uuid     = uuid;
+  data.rsp      = net_buf_add(data.buf, sizeof(*data.rsp));
+  data.rsp->len = 0U;
 
-    /* Pre-set error if no attr will be found in handle */
-    data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND;
+  /* Pre-set error if no attr will be found in handle */
+  data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND;
 
-    bt_gatt_foreach_attr(start_handle, end_handle, read_type_cb, &data);
+  bt_gatt_foreach_attr(start_handle, end_handle, read_type_cb, &data);
 
-    if (data.err) {
-        net_buf_unref(data.buf);
-        /* Response here since handle is set */
-        send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, start_handle,
-                     data.err);
-        return 0;
-    }
+  if (data.err) {
+    net_buf_unref(data.buf);
+    /* Response here since handle is set */
+    send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, start_handle, data.err);
+    return 0;
+  }
 
 #if defined(CONFIG_BT_STACK_PTS)
-    if (event_flag == att_read_by_type_ind)
-        BT_PTS("handle : [0x%04x]\r\n", data.rsp->data->handle);
+  if (event_flag == att_read_by_type_ind)
+    BT_PTS("handle : [0x%04x]\r\n", data.rsp->data->handle);
 #endif
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 
-static u8_t att_read_type_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_read_type_req *req;
-    u16_t start_handle, end_handle, err_handle;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-    u8_t uuid_len = buf->len - sizeof(*req);
-
-    /* Type can only be UUID16 or UUID128 */
-    if (uuid_len != 2 && uuid_len != 16) {
-        return BT_ATT_ERR_INVALID_PDU;
-    }
+static u8_t att_read_type_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn              *conn = att->chan.chan.conn;
+  struct bt_att_read_type_req *req;
+  u16_t                        start_handle, end_handle, err_handle;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
+  u8_t uuid_len = buf->len - sizeof(*req);
 
-    req = net_buf_pull_mem(buf, sizeof(*req));
+  /* Type can only be UUID16 or UUID128 */
+  if (uuid_len != 2 && uuid_len != 16) {
+    return BT_ATT_ERR_INVALID_PDU;
+  }
 
-    start_handle = sys_le16_to_cpu(req->start_handle);
-    end_handle = sys_le16_to_cpu(req->end_handle);
-    if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  req = net_buf_pull_mem(buf, sizeof(*req));
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s",
-           start_handle, end_handle, bt_uuid_str(&u.uuid));
+  start_handle = sys_le16_to_cpu(req->start_handle);
+  end_handle   = sys_le16_to_cpu(req->end_handle);
+  if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    if (!range_is_valid(start_handle, end_handle, &err_handle)) {
-        send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, err_handle,
-                     BT_ATT_ERR_INVALID_HANDLE);
-        return 0;
-    }
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", start_handle, end_handle, bt_uuid_str(&u.uuid));
 
-    return att_read_type_rsp(att, &u.uuid, start_handle, end_handle);
+  if (!range_is_valid(start_handle, end_handle, &err_handle)) {
+    send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE);
+    return 0;
+  }
+
+  return att_read_type_rsp(att, &u.uuid, start_handle, end_handle);
 }
 
 struct read_data {
-    struct bt_att *att;
-    u16_t offset;
-    struct net_buf *buf;
-    struct bt_att_read_rsp *rsp;
-    u8_t err;
+  struct bt_att          *att;
+  u16_t                   offset;
+  struct net_buf         *buf;
+  struct bt_att_read_rsp *rsp;
+  u8_t                    err;
 };
 
-static u8_t read_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct read_data *data = user_data;
-    struct bt_att *att = data->att;
-    struct bt_conn *conn = att->chan.chan.conn;
-    int read;
+static u8_t read_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct read_data *data = user_data;
+  struct bt_att    *att  = data->att;
+  struct bt_conn   *conn = att->chan.chan.conn;
+  int               read;
 
-    BT_DBG("handle 0x%04x", attr->handle);
+  BT_DBG("handle 0x%04x", attr->handle);
 
-    data->rsp = net_buf_add(data->buf, sizeof(*data->rsp));
+  data->rsp = net_buf_add(data->buf, sizeof(*data->rsp));
 
-    /*
-	 * If any attribute is founded in handle range it means that error
-	 * should be changed from pre-set: invalid handle error to no error.
-	 */
-    data->err = 0x00;
-
-    /* Check attribute permissions */
-    data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK);
-    if (data->err) {
-        return BT_GATT_ITER_STOP;
-    }
+  /*
+   * If any attribute is founded in handle range it means that error
+   * should be changed from pre-set: invalid handle error to no error.
+   */
+  data->err = 0x00;
 
-    /* Read attribute value and store in the buffer */
-    read = attr->read(conn, attr, data->buf->data + data->buf->len,
-                      att->chan.tx.mtu - data->buf->len, data->offset);
-    if (read < 0) {
-        data->err = err_to_att(read);
-        return BT_GATT_ITER_STOP;
-    }
+  /* Check attribute permissions */
+  data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK);
+  if (data->err) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    net_buf_add(data->buf, read);
+  /* Read attribute value and store in the buffer */
+  read = attr->read(conn, attr, data->buf->data + data->buf->len, att->chan.tx.mtu - data->buf->len, data->offset);
+  if (read < 0) {
+    data->err = err_to_att(read);
+    return BT_GATT_ITER_STOP;
+  }
 
-    return BT_GATT_ITER_CONTINUE;
+  net_buf_add(data->buf, read);
+
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t att_read_rsp(struct bt_att *att, u8_t op, u8_t rsp, u16_t handle,
-                         u16_t offset)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct read_data data;
+static u8_t att_read_rsp(struct bt_att *att, u8_t op, u8_t rsp, u16_t handle, u16_t offset) {
+  struct bt_conn  *conn = att->chan.chan.conn;
+  struct read_data data;
 
-    if (!bt_gatt_change_aware(conn, true)) {
-        return BT_ATT_ERR_DB_OUT_OF_SYNC;
-    }
+  if (!bt_gatt_change_aware(conn, true)) {
+    return BT_ATT_ERR_DB_OUT_OF_SYNC;
+  }
 
-    if (!handle) {
-        return BT_ATT_ERR_INVALID_HANDLE;
-    }
+  if (!handle) {
+    return BT_ATT_ERR_INVALID_HANDLE;
+  }
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.buf = bt_att_create_pdu(conn, rsp, 0);
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  data.buf = bt_att_create_pdu(conn, rsp, 0);
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    data.att = att;
-    data.offset = offset;
+  data.att    = att;
+  data.offset = offset;
 
-    /* Pre-set error if no attr will be found in handle */
-    data.err = BT_ATT_ERR_INVALID_HANDLE;
+  /* Pre-set error if no attr will be found in handle */
+  data.err = BT_ATT_ERR_INVALID_HANDLE;
 
-    bt_gatt_foreach_attr(handle, handle, read_cb, &data);
+  bt_gatt_foreach_attr(handle, handle, read_cb, &data);
 
-    /* In case of error discard data and respond with an error */
-    if (data.err) {
-        net_buf_unref(data.buf);
-        /* Respond here since handle is set */
-        send_err_rsp(conn, op, handle, data.err);
-        return 0;
-    }
+  /* In case of error discard data and respond with an error */
+  if (data.err) {
+    net_buf_unref(data.buf);
+    /* Respond here since handle is set */
+    send_err_rsp(conn, op, handle, data.err);
+    return 0;
+  }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 
-static u8_t att_read_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_att_read_req *req;
-    u16_t handle;
+static u8_t att_read_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_att_read_req *req;
+  u16_t                   handle;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    handle = sys_le16_to_cpu(req->handle);
+  handle = sys_le16_to_cpu(req->handle);
 
-    BT_DBG("handle 0x%04x", handle);
+  BT_DBG("handle 0x%04x", handle);
 
-    return att_read_rsp(att, BT_ATT_OP_READ_REQ, BT_ATT_OP_READ_RSP,
-                        handle, 0);
+  return att_read_rsp(att, BT_ATT_OP_READ_REQ, BT_ATT_OP_READ_RSP, handle, 0);
 }
 
-static u8_t att_read_blob_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_att_read_blob_req *req;
-    u16_t handle, offset;
+static u8_t att_read_blob_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_att_read_blob_req *req;
+  u16_t                        handle, offset;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    handle = sys_le16_to_cpu(req->handle);
-    offset = sys_le16_to_cpu(req->offset);
+  handle = sys_le16_to_cpu(req->handle);
+  offset = sys_le16_to_cpu(req->offset);
 
-    BT_DBG("handle 0x%04x offset %u", handle, offset);
+  BT_DBG("handle 0x%04x offset %u", handle, offset);
 
-    return att_read_rsp(att, BT_ATT_OP_READ_BLOB_REQ,
-                        BT_ATT_OP_READ_BLOB_RSP, handle, offset);
+  return att_read_rsp(att, BT_ATT_OP_READ_BLOB_REQ, BT_ATT_OP_READ_BLOB_RSP, handle, offset);
 }
 
 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
-static u8_t att_read_mult_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct read_data data;
-    u16_t handle;
+static u8_t att_read_mult_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn  *conn = att->chan.chan.conn;
+  struct read_data data;
+  u16_t            handle;
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_RSP, 0);
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_RSP, 0);
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    data.att = att;
+  data.att = att;
 
-    while (buf->len >= sizeof(u16_t)) {
-        handle = net_buf_pull_le16(buf);
+  while (buf->len >= sizeof(u16_t)) {
+    handle = net_buf_pull_le16(buf);
 
-        BT_DBG("handle 0x%04x ", handle);
+    BT_DBG("handle 0x%04x ", handle);
 
-        /* An Error Response shall be sent by the server in response to
-		 * the Read Multiple Request [....] if a read operation is not
-		 * permitted on any of the Characteristic Values.
-		 *
-		 * If handle is not valid then return invalid handle error.
-		 * If handle is found error will be cleared by read_cb.
-		 */
-        data.err = BT_ATT_ERR_INVALID_HANDLE;
+    /* An Error Response shall be sent by the server in response to
+     * the Read Multiple Request [....] if a read operation is not
+     * permitted on any of the Characteristic Values.
+     *
+     * If handle is not valid then return invalid handle error.
+     * If handle is found error will be cleared by read_cb.
+     */
+    data.err = BT_ATT_ERR_INVALID_HANDLE;
 
-        bt_gatt_foreach_attr(handle, handle, read_cb, &data);
+    bt_gatt_foreach_attr(handle, handle, read_cb, &data);
 
-        /* Stop reading in case of error */
-        if (data.err) {
-            net_buf_unref(data.buf);
-            /* Respond here since handle is set */
-            send_err_rsp(conn, BT_ATT_OP_READ_MULT_REQ, handle,
-                         data.err);
-            return 0;
-        }
+    /* Stop reading in case of error */
+    if (data.err) {
+      net_buf_unref(data.buf);
+      /* Respond here since handle is set */
+      send_err_rsp(conn, BT_ATT_OP_READ_MULT_REQ, handle, data.err);
+      return 0;
     }
+  }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_GATT_READ_MULTIPLE */
 
 struct read_group_data {
-    struct bt_att *att;
-    struct bt_uuid *uuid;
-    struct net_buf *buf;
-    struct bt_att_read_group_rsp *rsp;
-    struct bt_att_group_data *group;
+  struct bt_att                *att;
+  struct bt_uuid               *uuid;
+  struct net_buf               *buf;
+  struct bt_att_read_group_rsp *rsp;
+  struct bt_att_group_data     *group;
 };
 
-static u8_t read_group_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct read_group_data *data = user_data;
-    struct bt_att *att = data->att;
-    struct bt_conn *conn = att->chan.chan.conn;
-    int read;
-
-    /* Update group end_handle if attribute is not a service */
-    if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) &&
-        bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
-        if (data->group &&
-            attr->handle > sys_le16_to_cpu(data->group->end_handle)) {
-            data->group->end_handle = sys_cpu_to_le16(attr->handle);
-        }
-        return BT_GATT_ITER_CONTINUE;
-    }
+static u8_t read_group_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct read_group_data *data = user_data;
+  struct bt_att          *att  = data->att;
+  struct bt_conn         *conn = att->chan.chan.conn;
+  int                     read;
 
-    /* If Group Type don't match skip */
-    if (bt_uuid_cmp(attr->uuid, data->uuid)) {
-        data->group = NULL;
-        return BT_GATT_ITER_CONTINUE;
+  /* Update group end_handle if attribute is not a service */
+  if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) && bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
+    if (data->group && attr->handle > sys_le16_to_cpu(data->group->end_handle)) {
+      data->group->end_handle = sys_cpu_to_le16(attr->handle);
     }
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    BT_DBG("handle 0x%04x", attr->handle);
+  /* If Group Type don't match skip */
+  if (bt_uuid_cmp(attr->uuid, data->uuid)) {
+    data->group = NULL;
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    /* Stop if there is no space left */
-    if (data->rsp->len &&
-        att->chan.tx.mtu - data->buf->len < data->rsp->len) {
-        return BT_GATT_ITER_STOP;
-    }
+  BT_DBG("handle 0x%04x", attr->handle);
 
-    /* Fast forward to next group position */
-    data->group = net_buf_add(data->buf, sizeof(*data->group));
+  /* Stop if there is no space left */
+  if (data->rsp->len && att->chan.tx.mtu - data->buf->len < data->rsp->len) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    /* Initialize group handle range */
-    data->group->start_handle = sys_cpu_to_le16(attr->handle);
-    data->group->end_handle = sys_cpu_to_le16(attr->handle);
+  /* Fast forward to next group position */
+  data->group = net_buf_add(data->buf, sizeof(*data->group));
 
-    /* Read attribute value and store in the buffer */
-    read = attr->read(conn, attr, data->buf->data + data->buf->len,
-                      att->chan.tx.mtu - data->buf->len, 0);
-    if (read < 0) {
-        /* TODO: Handle read errors */
-        return BT_GATT_ITER_STOP;
-    }
+  /* Initialize group handle range */
+  data->group->start_handle = sys_cpu_to_le16(attr->handle);
+  data->group->end_handle   = sys_cpu_to_le16(attr->handle);
 
-    if (!data->rsp->len) {
-        /* Set len to be the first group found */
-        data->rsp->len = read + sizeof(*data->group);
-    } else if (data->rsp->len != read + sizeof(*data->group)) {
-        /* All groups entries should have the same size */
-        data->buf->len -= sizeof(*data->group);
-        return false;
-    }
+  /* Read attribute value and store in the buffer */
+  read = attr->read(conn, attr, data->buf->data + data->buf->len, att->chan.tx.mtu - data->buf->len, 0);
+  if (read < 0) {
+    /* TODO: Handle read errors */
+    return BT_GATT_ITER_STOP;
+  }
 
-    net_buf_add(data->buf, read);
+  if (!data->rsp->len) {
+    /* Set len to be the first group found */
+    data->rsp->len = read + sizeof(*data->group);
+  } else if (data->rsp->len != read + sizeof(*data->group)) {
+    /* All groups entries should have the same size */
+    data->buf->len -= sizeof(*data->group);
+    return false;
+  }
 
-    /* Continue to find the end handle */
-    return BT_GATT_ITER_CONTINUE;
+  net_buf_add(data->buf, read);
+
+  /* Continue to find the end handle */
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t att_read_group_rsp(struct bt_att *att, struct bt_uuid *uuid,
-                               u16_t start_handle, u16_t end_handle)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct read_group_data data;
+static u8_t att_read_group_rsp(struct bt_att *att, struct bt_uuid *uuid, u16_t start_handle, u16_t end_handle) {
+  struct bt_conn        *conn = att->chan.chan.conn;
+  struct read_group_data data;
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_RSP,
-                                 sizeof(*data.rsp));
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_RSP, sizeof(*data.rsp));
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    data.att = att;
-    data.uuid = uuid;
-    data.rsp = net_buf_add(data.buf, sizeof(*data.rsp));
-    data.rsp->len = 0U;
-    data.group = NULL;
+  data.att      = att;
+  data.uuid     = uuid;
+  data.rsp      = net_buf_add(data.buf, sizeof(*data.rsp));
+  data.rsp->len = 0U;
+  data.group    = NULL;
 
-    bt_gatt_foreach_attr(start_handle, end_handle, read_group_cb, &data);
+  bt_gatt_foreach_attr(start_handle, end_handle, read_group_cb, &data);
 
-    if (!data.rsp->len) {
-        net_buf_unref(data.buf);
-        /* Respond here since handle is set */
-        send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle,
-                     BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
-        return 0;
-    }
+  if (!data.rsp->len) {
+    net_buf_unref(data.buf);
+    /* Respond here since handle is set */
+    send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND);
+    return 0;
+  }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 
-static u8_t att_read_group_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_read_group_req *req;
-    u16_t start_handle, end_handle, err_handle;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-    u8_t uuid_len = buf->len - sizeof(*req);
-
-    /* Type can only be UUID16 or UUID128 */
-    if (uuid_len != 2 && uuid_len != 16) {
-        return BT_ATT_ERR_INVALID_PDU;
-    }
+static u8_t att_read_group_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn               *conn = att->chan.chan.conn;
+  struct bt_att_read_group_req *req;
+  u16_t                         start_handle, end_handle, err_handle;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
+  u8_t uuid_len = buf->len - sizeof(*req);
 
-    req = net_buf_pull_mem(buf, sizeof(*req));
+  /* Type can only be UUID16 or UUID128 */
+  if (uuid_len != 2 && uuid_len != 16) {
+    return BT_ATT_ERR_INVALID_PDU;
+  }
 
-    start_handle = sys_le16_to_cpu(req->start_handle);
-    end_handle = sys_le16_to_cpu(req->end_handle);
+  req = net_buf_pull_mem(buf, sizeof(*req));
 
-    if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  start_handle = sys_le16_to_cpu(req->start_handle);
+  end_handle   = sys_le16_to_cpu(req->end_handle);
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s",
-           start_handle, end_handle, bt_uuid_str(&u.uuid));
+  if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    if (!range_is_valid(start_handle, end_handle, &err_handle)) {
-        send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, err_handle,
-                     BT_ATT_ERR_INVALID_HANDLE);
-        return 0;
-    }
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", start_handle, end_handle, bt_uuid_str(&u.uuid));
 
-    /* Core v4.2, Vol 3, sec 2.5.3 Attribute Grouping:
-	 * Not all of the grouping attributes can be used in the ATT
-	 * Read By Group Type Request. The "Primary Service" and "Secondary
-	 * Service" grouping types may be used in the Read By Group Type
-	 * Request. The "Characteristic" grouping type shall not be used in
-	 * the ATT Read By Group Type Request.
-	 */
-    if (bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) &&
-        bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY)) {
-        send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle,
-                     BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE);
-        return 0;
-    }
+  if (!range_is_valid(start_handle, end_handle, &err_handle)) {
+    send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, err_handle, BT_ATT_ERR_INVALID_HANDLE);
+    return 0;
+  }
+
+  /* Core v4.2, Vol 3, sec 2.5.3 Attribute Grouping:
+   * Not all of the grouping attributes can be used in the ATT
+   * Read By Group Type Request. The "Primary Service" and "Secondary
+   * Service" grouping types may be used in the Read By Group Type
+   * Request. The "Characteristic" grouping type shall not be used in
+   * the ATT Read By Group Type Request.
+   */
+  if (bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) && bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY)) {
+    send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle, BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE);
+    return 0;
+  }
 
-    return att_read_group_rsp(att, &u.uuid, start_handle, end_handle);
+  return att_read_group_rsp(att, &u.uuid, start_handle, end_handle);
 }
 
 struct write_data {
-    struct bt_conn *conn;
-    struct net_buf *buf;
-    u8_t req;
-    const void *value;
-    u16_t len;
-    u16_t offset;
-    u8_t err;
+  struct bt_conn *conn;
+  struct net_buf *buf;
+  u8_t            req;
+  const void     *value;
+  u16_t           len;
+  u16_t           offset;
+  u8_t            err;
 };
 
-static u8_t write_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct write_data *data = user_data;
-    int write;
-    u8_t flags = 0U;
+static u8_t write_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct write_data *data = user_data;
+  int                write;
+  u8_t               flags = 0U;
 
-    BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset);
+  BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset);
 
-    /* Check attribute permissions */
-    data->err = bt_gatt_check_perm(data->conn, attr,
-                                   BT_GATT_PERM_WRITE_MASK);
-    if (data->err) {
-        return BT_GATT_ITER_STOP;
-    }
+  /* Check attribute permissions */
+  data->err = bt_gatt_check_perm(data->conn, attr, BT_GATT_PERM_WRITE_MASK);
+  if (data->err) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    /* Set command flag if not a request */
-    if (!data->req) {
-        flags |= BT_GATT_WRITE_FLAG_CMD;
-    }
+  /* Set command flag if not a request */
+  if (!data->req) {
+    flags |= BT_GATT_WRITE_FLAG_CMD;
+  }
 
-    /* Write attribute value */
-    write = attr->write(data->conn, attr, data->value, data->len,
-                        data->offset, flags);
-    if (write < 0 || write != data->len) {
-        data->err = err_to_att(write);
-        return BT_GATT_ITER_STOP;
-    }
+  /* Write attribute value */
+  write = attr->write(data->conn, attr, data->value, data->len, data->offset, flags);
+  if (write < 0 || write != data->len) {
+    data->err = err_to_att(write);
+    return BT_GATT_ITER_STOP;
+  }
 
-    data->err = 0U;
+  data->err = 0U;
 
-    return BT_GATT_ITER_CONTINUE;
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t att_write_rsp(struct bt_conn *conn, u8_t req, u8_t rsp,
-                          u16_t handle, u16_t offset, const void *value,
-                          u16_t len)
-{
-    struct write_data data;
+static u8_t att_write_rsp(struct bt_conn *conn, u8_t req, u8_t rsp, u16_t handle, u16_t offset, const void *value, u16_t len) {
+  struct write_data data;
 
-    if (!bt_gatt_change_aware(conn, req ? true : false)) {
-        return BT_ATT_ERR_DB_OUT_OF_SYNC;
-    }
+  if (!bt_gatt_change_aware(conn, req ? true : false)) {
+    return BT_ATT_ERR_DB_OUT_OF_SYNC;
+  }
 
-    if (!handle) {
-        return BT_ATT_ERR_INVALID_HANDLE;
-    }
+  if (!handle) {
+    return BT_ATT_ERR_INVALID_HANDLE;
+  }
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    /* Only allocate buf if required to respond */
-    if (rsp) {
-        data.buf = bt_att_create_pdu(conn, rsp, 0);
-        if (!data.buf) {
-            return BT_ATT_ERR_UNLIKELY;
-        }
+  /* Only allocate buf if required to respond */
+  if (rsp) {
+    data.buf = bt_att_create_pdu(conn, rsp, 0);
+    if (!data.buf) {
+      return BT_ATT_ERR_UNLIKELY;
     }
+  }
 
-    data.conn = conn;
-    data.req = req;
-    data.offset = offset;
-    data.value = value;
-    data.len = len;
-    data.err = BT_ATT_ERR_INVALID_HANDLE;
+  data.conn   = conn;
+  data.req    = req;
+  data.offset = offset;
+  data.value  = value;
+  data.len    = len;
+  data.err    = BT_ATT_ERR_INVALID_HANDLE;
 
-    bt_gatt_foreach_attr(handle, handle, write_cb, &data);
+  bt_gatt_foreach_attr(handle, handle, write_cb, &data);
 
-    if (data.err) {
-        /* In case of error discard data and respond with an error */
-        if (rsp) {
-            net_buf_unref(data.buf);
-            /* Respond here since handle is set */
-            send_err_rsp(conn, req, handle, data.err);
-        }
-        return req == BT_ATT_OP_EXEC_WRITE_REQ ? data.err : 0;
+  if (data.err) {
+    /* In case of error discard data and respond with an error */
+    if (rsp) {
+      net_buf_unref(data.buf);
+      /* Respond here since handle is set */
+      send_err_rsp(conn, req, handle, data.err);
     }
+    return req == BT_ATT_OP_EXEC_WRITE_REQ ? data.err : 0;
+  }
 
-    if (data.buf) {
-        (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf,
-                               att_rsp_sent, NULL);
-    }
+  if (data.buf) {
+    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
+  }
 
-    return 0;
+  return 0;
 }
 
-static u8_t att_write_req(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    u16_t handle;
+static u8_t att_write_req(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn *conn = att->chan.chan.conn;
+  u16_t           handle;
 
-    handle = net_buf_pull_le16(buf);
+  handle = net_buf_pull_le16(buf);
 
-    BT_DBG("handle 0x%04x", handle);
+  BT_DBG("handle 0x%04x", handle);
 
-    return att_write_rsp(conn, BT_ATT_OP_WRITE_REQ, BT_ATT_OP_WRITE_RSP,
-                         handle, 0, buf->data, buf->len);
+  return att_write_rsp(conn, BT_ATT_OP_WRITE_REQ, BT_ATT_OP_WRITE_RSP, handle, 0, buf->data, buf->len);
 }
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
 struct prep_data {
-    struct bt_conn *conn;
-    struct net_buf *buf;
-    const void *value;
-    u16_t len;
-    u16_t offset;
-    u8_t err;
+  struct bt_conn *conn;
+  struct net_buf *buf;
+  const void     *value;
+  u16_t           len;
+  u16_t           offset;
+  u8_t            err;
 };
 
-static u8_t prep_write_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct prep_data *data = user_data;
-    struct bt_attr_data *attr_data;
-    int write;
+static u8_t prep_write_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct prep_data    *data = user_data;
+  struct bt_attr_data *attr_data;
+  int                  write;
 
-    BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset);
+  BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset);
 
-    /* Check attribute permissions */
-    data->err = bt_gatt_check_perm(data->conn, attr,
-                                   BT_GATT_PERM_WRITE_MASK);
-    if (data->err) {
-        return BT_GATT_ITER_STOP;
-    }
+  /* Check attribute permissions */
+  data->err = bt_gatt_check_perm(data->conn, attr, BT_GATT_PERM_WRITE_MASK);
+  if (data->err) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    /* Check if attribute requires handler to accept the data */
-    if (!(attr->perm & BT_GATT_PERM_PREPARE_WRITE)) {
-        goto append;
-    }
+  /* Check if attribute requires handler to accept the data */
+  if (!(attr->perm & BT_GATT_PERM_PREPARE_WRITE)) {
+    goto append;
+  }
 
-    /* Write attribute value to check if device is authorized */
-    write = attr->write(data->conn, attr, data->value, data->len,
-                        data->offset, BT_GATT_WRITE_FLAG_PREPARE);
-    if (write != 0) {
-        data->err = err_to_att(write);
-        return BT_GATT_ITER_STOP;
-    }
+  /* Write attribute value to check if device is authorized */
+  write = attr->write(data->conn, attr, data->value, data->len, data->offset, BT_GATT_WRITE_FLAG_PREPARE);
+  if (write != 0) {
+    data->err = err_to_att(write);
+    return BT_GATT_ITER_STOP;
+  }
 
 append:
-    /* Copy data into the outstanding queue */
-    data->buf = net_buf_alloc(&prep_pool, K_NO_WAIT);
-    if (!data->buf) {
-        data->err = BT_ATT_ERR_PREPARE_QUEUE_FULL;
-        return BT_GATT_ITER_STOP;
-    }
+  /* Copy data into the outstanding queue */
+  data->buf = net_buf_alloc(&prep_pool, K_NO_WAIT);
+  if (!data->buf) {
+    data->err = BT_ATT_ERR_PREPARE_QUEUE_FULL;
+    return BT_GATT_ITER_STOP;
+  }
 
-    attr_data = net_buf_user_data(data->buf);
-    attr_data->handle = attr->handle;
-    attr_data->offset = data->offset;
+  attr_data         = net_buf_user_data(data->buf);
+  attr_data->handle = attr->handle;
+  attr_data->offset = data->offset;
 
-    net_buf_add_mem(data->buf, data->value, data->len);
+  net_buf_add_mem(data->buf, data->value, data->len);
 
-    data->err = 0U;
+  data->err = 0U;
 
-    return BT_GATT_ITER_CONTINUE;
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t att_prep_write_rsp(struct bt_att *att, u16_t handle, u16_t offset,
-                               const void *value, u16_t len)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct prep_data data;
-    struct bt_att_prepare_write_rsp *rsp;
+static u8_t att_prep_write_rsp(struct bt_att *att, u16_t handle, u16_t offset, const void *value, u16_t len) {
+  struct bt_conn                  *conn = att->chan.chan.conn;
+  struct prep_data                 data;
+  struct bt_att_prepare_write_rsp *rsp;
 
-    if (!bt_gatt_change_aware(conn, true)) {
-        return BT_ATT_ERR_DB_OUT_OF_SYNC;
-    }
+  if (!bt_gatt_change_aware(conn, true)) {
+    return BT_ATT_ERR_DB_OUT_OF_SYNC;
+  }
 
-    if (!handle) {
-        return BT_ATT_ERR_INVALID_HANDLE;
-    }
+  if (!handle) {
+    return BT_ATT_ERR_INVALID_HANDLE;
+  }
 
-    (void)memset(&data, 0, sizeof(data));
+  (void)memset(&data, 0, sizeof(data));
 
-    data.conn = conn;
-    data.offset = offset;
-    data.value = value;
-    data.len = len;
-    data.err = BT_ATT_ERR_INVALID_HANDLE;
+  data.conn   = conn;
+  data.offset = offset;
+  data.value  = value;
+  data.len    = len;
+  data.err    = BT_ATT_ERR_INVALID_HANDLE;
 
-    bt_gatt_foreach_attr(handle, handle, prep_write_cb, &data);
+  bt_gatt_foreach_attr(handle, handle, prep_write_cb, &data);
 
-    if (data.err) {
-        /* Respond here since handle is set */
-        send_err_rsp(conn, BT_ATT_OP_PREPARE_WRITE_REQ, handle,
-                     data.err);
-        return 0;
-    }
+  if (data.err) {
+    /* Respond here since handle is set */
+    send_err_rsp(conn, BT_ATT_OP_PREPARE_WRITE_REQ, handle, data.err);
+    return 0;
+  }
 
-    BT_DBG("buf %p handle 0x%04x offset %u", data.buf, handle, offset);
+  BT_DBG("buf %p handle 0x%04x offset %u", data.buf, handle, offset);
 
-    /* Store buffer in the outstanding queue */
-    net_buf_put(&att->prep_queue, data.buf);
+  /* Store buffer in the outstanding queue */
+  net_buf_put(&att->prep_queue, data.buf);
 
-    /* Generate response */
-    data.buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_RSP, 0);
-    if (!data.buf) {
-        return BT_ATT_ERR_UNLIKELY;
-    }
+  /* Generate response */
+  data.buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_RSP, 0);
+  if (!data.buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
 
-    rsp = net_buf_add(data.buf, sizeof(*rsp));
-    rsp->handle = sys_cpu_to_le16(handle);
-    rsp->offset = sys_cpu_to_le16(offset);
-    net_buf_add(data.buf, len);
-    memcpy(rsp->value, value, len);
+  rsp         = net_buf_add(data.buf, sizeof(*rsp));
+  rsp->handle = sys_cpu_to_le16(handle);
+  rsp->offset = sys_cpu_to_le16(offset);
+  net_buf_add(data.buf, len);
+  memcpy(rsp->value, value, len);
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent,
-                           NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT */
 
-static u8_t att_prepare_write_req(struct bt_att *att, struct net_buf *buf)
-{
+static u8_t att_prepare_write_req(struct bt_att *att, struct net_buf *buf) {
 #if CONFIG_BT_ATT_PREPARE_COUNT == 0
-    return BT_ATT_ERR_NOT_SUPPORTED;
+  return BT_ATT_ERR_NOT_SUPPORTED;
 #else
-    struct bt_att_prepare_write_req *req;
-    u16_t handle, offset;
+  struct bt_att_prepare_write_req *req;
+  u16_t                            handle, offset;
 
-    req = net_buf_pull_mem(buf, sizeof(*req));
+  req = net_buf_pull_mem(buf, sizeof(*req));
 
-    handle = sys_le16_to_cpu(req->handle);
-    offset = sys_le16_to_cpu(req->offset);
+  handle = sys_le16_to_cpu(req->handle);
+  offset = sys_le16_to_cpu(req->offset);
 
-    BT_DBG("handle 0x%04x offset %u", handle, offset);
+  BT_DBG("handle 0x%04x offset %u", handle, offset);
 
-    return att_prep_write_rsp(att, handle, offset, buf->data, buf->len);
+  return att_prep_write_rsp(att, handle, offset, buf->data, buf->len);
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT */
 }
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-static u8_t att_exec_write_rsp(struct bt_att *att, u8_t flags)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct net_buf *buf;
-    u8_t err = 0U;
-
-    while ((buf = net_buf_get(&att->prep_queue, K_NO_WAIT))) {
-        struct bt_attr_data *data = net_buf_user_data(buf);
-
-        BT_DBG("buf %p handle 0x%04x offset %u", buf, data->handle,
-               data->offset);
-
-        /* Just discard the data if an error was set */
-        if (!err && flags == BT_ATT_FLAG_EXEC) {
-            err = att_write_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ, 0,
-                                data->handle, data->offset,
-                                buf->data, buf->len);
-            if (err) {
-                /* Respond here since handle is set */
-                send_err_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ,
-                             data->handle, err);
-            }
-        }
-
-        net_buf_unref(buf);
-    }
+static u8_t att_exec_write_rsp(struct bt_att *att, u8_t flags) {
+  struct bt_conn *conn = att->chan.chan.conn;
+  struct net_buf *buf;
+  u8_t            err = 0U;
 
-    if (err) {
-        return 0;
-    }
+  while ((buf = net_buf_get(&att->prep_queue, K_NO_WAIT))) {
+    struct bt_attr_data *data = net_buf_user_data(buf);
+
+    BT_DBG("buf %p handle 0x%04x offset %u", buf, data->handle, data->offset);
 
-    /* Generate response */
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_RSP, 0);
-    if (!buf) {
-        return BT_ATT_ERR_UNLIKELY;
+    /* Just discard the data if an error was set */
+    if (!err && flags == BT_ATT_FLAG_EXEC) {
+      err = att_write_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ, 0, data->handle, data->offset, buf->data, buf->len);
+      if (err) {
+        /* Respond here since handle is set */
+        send_err_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ, data->handle, err);
+      }
     }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL);
+    net_buf_unref(buf);
+  }
 
+  if (err) {
     return 0;
+  }
+
+  /* Generate response */
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_RSP, 0);
+  if (!buf) {
+    return BT_ATT_ERR_UNLIKELY;
+  }
+
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL);
+
+  return 0;
 }
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT */
 
-static u8_t att_exec_write_req(struct bt_att *att, struct net_buf *buf)
-{
+static u8_t att_exec_write_req(struct bt_att *att, struct net_buf *buf) {
 #if CONFIG_BT_ATT_PREPARE_COUNT == 0
-    return BT_ATT_ERR_NOT_SUPPORTED;
+  return BT_ATT_ERR_NOT_SUPPORTED;
 #else
-    struct bt_att_exec_write_req *req;
+  struct bt_att_exec_write_req *req;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    BT_DBG("flags 0x%02x", req->flags);
+  BT_DBG("flags 0x%02x", req->flags);
 
-    return att_exec_write_rsp(att, req->flags);
+  return att_exec_write_rsp(att, req->flags);
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT */
 }
 
-static u8_t att_write_cmd(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    u16_t handle;
+static u8_t att_write_cmd(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn *conn = att->chan.chan.conn;
+  u16_t           handle;
 
-    handle = net_buf_pull_le16(buf);
+  handle = net_buf_pull_le16(buf);
 
-    BT_DBG("handle 0x%04x", handle);
+  BT_DBG("handle 0x%04x", handle);
 
-    return att_write_rsp(conn, 0, 0, handle, 0, buf->data, buf->len);
+  return att_write_rsp(conn, 0, 0, handle, 0, buf->data, buf->len);
 }
 
 #if defined(CONFIG_BT_SIGNING)
-static u8_t att_signed_write_cmd(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    struct bt_att_signed_write_cmd *req;
-    u16_t handle;
-    int err;
+static u8_t att_signed_write_cmd(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn                 *conn = att->chan.chan.conn;
+  struct bt_att_signed_write_cmd *req;
+  u16_t                           handle;
+  int                             err;
 
-    req = (void *)buf->data;
+  req = (void *)buf->data;
 
-    handle = sys_le16_to_cpu(req->handle);
+  handle = sys_le16_to_cpu(req->handle);
 
-    BT_DBG("handle 0x%04x", handle);
+  BT_DBG("handle 0x%04x", handle);
 
-    /* Verifying data requires full buffer including attribute header */
-    net_buf_push(buf, sizeof(struct bt_att_hdr));
-    err = bt_smp_sign_verify(conn, buf);
-    if (err) {
-        BT_ERR("Error verifying data");
-        /* No response for this command */
-        return 0;
-    }
+  /* Verifying data requires full buffer including attribute header */
+  net_buf_push(buf, sizeof(struct bt_att_hdr));
+  err = bt_smp_sign_verify(conn, buf);
+  if (err) {
+    BT_ERR("Error verifying data");
+    /* No response for this command */
+    return 0;
+  }
 
-    net_buf_pull(buf, sizeof(struct bt_att_hdr));
-    net_buf_pull(buf, sizeof(*req));
+  net_buf_pull(buf, sizeof(struct bt_att_hdr));
+  net_buf_pull(buf, sizeof(*req));
 
-    return att_write_rsp(conn, 0, 0, handle, 0, buf->data,
-                         buf->len - sizeof(struct bt_att_signature));
+  return att_write_rsp(conn, 0, 0, handle, 0, buf->data, buf->len - sizeof(struct bt_att_signature));
 }
 #endif /* CONFIG_BT_SIGNING */
 
 #if defined(CONFIG_BT_GATT_CLIENT)
 #if defined(CONFIG_BT_SMP)
-static int att_change_security(struct bt_conn *conn, u8_t err)
-{
-    bt_security_t sec;
-
-    switch (err) {
-        case BT_ATT_ERR_INSUFFICIENT_ENCRYPTION:
-            if (conn->sec_level >= BT_SECURITY_L2)
-                return -EALREADY;
-            sec = BT_SECURITY_L2;
-            break;
-        case BT_ATT_ERR_AUTHENTICATION:
-            if (conn->sec_level < BT_SECURITY_L2) {
-                /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
-			 * page 375:
-			 *
-			 * If an LTK is not available, the service request
-			 * shall be rejected with the error code 'Insufficient
-			 * Authentication'.
-			 * Note: When the link is not encrypted, the error code
-			 * "Insufficient Authentication" does not indicate that
-			 * MITM protection is required.
-			 */
-                sec = BT_SECURITY_L2;
-            } else if (conn->sec_level < BT_SECURITY_L3) {
-                /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
-			 * page 375:
-			 *
-			 * If an authenticated pairing is required but only an
-			 * unauthenticated pairing has occurred and the link is
-			 * currently encrypted, the service request shall be
-			 * rejected with the error code 'Insufficient
-			 * Authentication'.
-			 * Note: When unauthenticated pairing has occurred and
-			 * the link is currently encrypted, the error code
-			 * 'Insufficient Authentication' indicates that MITM
-			 * protection is required.
-			 */
-                sec = BT_SECURITY_L3;
-            } else if (conn->sec_level < BT_SECURITY_L4) {
-                /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
-			 * page 375:
-			 *
-			 * If LE Secure Connections authenticated pairing is
-			 * required but LE legacy pairing has occurred and the
-			 * link is currently encrypted, the service request
-			 * shall be rejected with the error code ''Insufficient
-			 * Authentication'.
-			 */
-                sec = BT_SECURITY_L4;
-            } else {
-                return -EALREADY;
-            }
-            break;
-        default:
-            return -EINVAL;
+static int att_change_security(struct bt_conn *conn, u8_t err) {
+  bt_security_t sec;
+
+  switch (err) {
+  case BT_ATT_ERR_INSUFFICIENT_ENCRYPTION:
+    if (conn->sec_level >= BT_SECURITY_L2)
+      return -EALREADY;
+    sec = BT_SECURITY_L2;
+    break;
+  case BT_ATT_ERR_AUTHENTICATION:
+    if (conn->sec_level < BT_SECURITY_L2) {
+      /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
+       * page 375:
+       *
+       * If an LTK is not available, the service request
+       * shall be rejected with the error code 'Insufficient
+       * Authentication'.
+       * Note: When the link is not encrypted, the error code
+       * "Insufficient Authentication" does not indicate that
+       * MITM protection is required.
+       */
+      sec = BT_SECURITY_L2;
+    } else if (conn->sec_level < BT_SECURITY_L3) {
+      /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
+       * page 375:
+       *
+       * If an authenticated pairing is required but only an
+       * unauthenticated pairing has occurred and the link is
+       * currently encrypted, the service request shall be
+       * rejected with the error code 'Insufficient
+       * Authentication'.
+       * Note: When unauthenticated pairing has occurred and
+       * the link is currently encrypted, the error code
+       * 'Insufficient Authentication' indicates that MITM
+       * protection is required.
+       */
+      sec = BT_SECURITY_L3;
+    } else if (conn->sec_level < BT_SECURITY_L4) {
+      /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C]
+       * page 375:
+       *
+       * If LE Secure Connections authenticated pairing is
+       * required but LE legacy pairing has occurred and the
+       * link is currently encrypted, the service request
+       * shall be rejected with the error code ''Insufficient
+       * Authentication'.
+       */
+      sec = BT_SECURITY_L4;
+    } else {
+      return -EALREADY;
     }
+    break;
+  default:
+    return -EINVAL;
+  }
 
-    return bt_conn_set_security(conn, sec);
+  return bt_conn_set_security(conn, sec);
 }
 #endif /* CONFIG_BT_SMP */
 
-static u8_t att_error_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_att_error_rsp *rsp;
-    u8_t err;
+static u8_t att_error_rsp(struct bt_att *att, struct net_buf *buf) {
+  struct bt_att_error_rsp *rsp;
+  u8_t                     err;
 
-    rsp = (void *)buf->data;
+  rsp = (void *)buf->data;
 
-    BT_DBG("request 0x%02x handle 0x%04x error 0x%02x", rsp->request,
-           sys_le16_to_cpu(rsp->handle), rsp->error);
+  BT_DBG("request 0x%02x handle 0x%04x error 0x%02x", rsp->request, sys_le16_to_cpu(rsp->handle), rsp->error);
 
-    /* Don't retry if there is no req pending or it has been cancelled */
-    if (!att->req || att->req == &cancel) {
-        err = BT_ATT_ERR_UNLIKELY;
-        goto done;
-    }
+  /* Don't retry if there is no req pending or it has been cancelled */
+  if (!att->req || att->req == &cancel) {
+    err = BT_ATT_ERR_UNLIKELY;
+    goto done;
+  }
 
-    if (att->req->buf) {
-        /* Restore state to be resent */
-        net_buf_simple_restore(&att->req->buf->b, &att->req->state);
-    }
+  if (att->req->buf) {
+    /* Restore state to be resent */
+    net_buf_simple_restore(&att->req->buf->b, &att->req->state);
+  }
 
-    err = rsp->error;
+  err = rsp->error;
 #if defined(CONFIG_BT_SMP)
-    if (att->req->retrying) {
-        goto done;
-    }
-
-    /* Check if security needs to be changed */
-    if (!att_change_security(att->chan.chan.conn, err)) {
-        att->req->retrying = true;
-        /* Wait security_changed: TODO: Handle fail case */
-        return 0;
-    }
+  if (att->req->retrying) {
+    goto done;
+  }
+
+  /* Check if security needs to be changed */
+  if (!att_change_security(att->chan.chan.conn, err)) {
+    att->req->retrying = true;
+    /* Wait security_changed: TODO: Handle fail case */
+    return 0;
+  }
 #endif /* CONFIG_BT_SMP */
 
 done:
-    return att_handle_rsp(att, NULL, 0, err);
+  return att_handle_rsp(att, NULL, 0, err);
 }
 
-static u8_t att_handle_find_info_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_find_info_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_find_type_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_find_type_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_read_type_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_read_type_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_read_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_read_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_read_blob_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_read_blob_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
-static u8_t att_handle_read_mult_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_read_mult_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 #endif /* CONFIG_BT_GATT_READ_MULTIPLE */
 
-static u8_t att_handle_read_group_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_read_group_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_write_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_write_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_prepare_write_rsp(struct bt_att *att,
-                                         struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_prepare_write_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_handle_exec_write_rsp(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_handle_exec_write_rsp(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
-static u8_t att_notify(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    u16_t handle;
+static u8_t att_notify(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn *conn = att->chan.chan.conn;
+  u16_t           handle;
 
-    handle = net_buf_pull_le16(buf);
-    BT_DBG("handle 0x%04x", handle);
+  handle = net_buf_pull_le16(buf);
+  BT_DBG("handle 0x%04x", handle);
 
-    bt_gatt_notification(conn, handle, buf->data, buf->len);
-    return 0;
+  bt_gatt_notification(conn, handle, buf->data, buf->len);
+  return 0;
 }
 
-static u8_t att_indicate(struct bt_att *att, struct net_buf *buf)
-{
-    struct bt_conn *conn = att->chan.chan.conn;
-    u16_t handle;
+static u8_t att_indicate(struct bt_att *att, struct net_buf *buf) {
+  struct bt_conn *conn = att->chan.chan.conn;
+  u16_t           handle;
 
-    handle = net_buf_pull_le16(buf);
+  handle = net_buf_pull_le16(buf);
 
-    BT_DBG("handle 0x%04x", handle);
+  BT_DBG("handle 0x%04x", handle);
 
-    bt_gatt_notification(conn, handle, buf->data, buf->len);
+  bt_gatt_notification(conn, handle, buf->data, buf->len);
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_CONFIRM, 0);
-    if (!buf) {
-        return 0;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_CONFIRM, 0);
+  if (!buf) {
+    return 0;
+  }
 
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_cfm_sent, NULL);
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_cfm_sent, NULL);
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_GATT_CLIENT */
 
-static u8_t att_confirm(struct bt_att *att, struct net_buf *buf)
-{
-    BT_DBG("");
+static u8_t att_confirm(struct bt_att *att, struct net_buf *buf) {
+  BT_DBG("");
 
-    return att_handle_rsp(att, buf->data, buf->len, 0);
+  return att_handle_rsp(att, buf->data, buf->len, 0);
 }
 
 static const struct att_handler {
-    u8_t op;
-    u8_t expect_len;
-    att_type_t type;
-    u8_t (*func)(struct bt_att *att, struct net_buf *buf);
+  u8_t       op;
+  u8_t       expect_len;
+  att_type_t type;
+  u8_t (*func)(struct bt_att *att, struct net_buf *buf);
 } handlers[] = {
-    { BT_ATT_OP_MTU_REQ,
-      sizeof(struct bt_att_exchange_mtu_req),
-      ATT_REQUEST,
-      att_mtu_req },
-    { BT_ATT_OP_FIND_INFO_REQ,
-      sizeof(struct bt_att_find_info_req),
-      ATT_REQUEST,
-      att_find_info_req },
-    { BT_ATT_OP_FIND_TYPE_REQ,
-      sizeof(struct bt_att_find_type_req),
-      ATT_REQUEST,
-      att_find_type_req },
-    { BT_ATT_OP_READ_TYPE_REQ,
-      sizeof(struct bt_att_read_type_req),
-      ATT_REQUEST,
-      att_read_type_req },
-    { BT_ATT_OP_READ_REQ,
-      sizeof(struct bt_att_read_req),
-      ATT_REQUEST,
-      att_read_req },
-    { BT_ATT_OP_READ_BLOB_REQ,
-      sizeof(struct bt_att_read_blob_req),
-      ATT_REQUEST,
-      att_read_blob_req },
+    {          BT_ATT_OP_MTU_REQ,                              sizeof(struct bt_att_exchange_mtu_req),      ATT_REQUEST,                  att_mtu_req},
+    {    BT_ATT_OP_FIND_INFO_REQ,                                 sizeof(struct bt_att_find_info_req),      ATT_REQUEST,            att_find_info_req},
+    {    BT_ATT_OP_FIND_TYPE_REQ,                                 sizeof(struct bt_att_find_type_req),      ATT_REQUEST,            att_find_type_req},
+    {    BT_ATT_OP_READ_TYPE_REQ,                                 sizeof(struct bt_att_read_type_req),      ATT_REQUEST,            att_read_type_req},
+    {         BT_ATT_OP_READ_REQ,                                      sizeof(struct bt_att_read_req),      ATT_REQUEST,                 att_read_req},
+    {    BT_ATT_OP_READ_BLOB_REQ,                                 sizeof(struct bt_att_read_blob_req),      ATT_REQUEST,            att_read_blob_req},
 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
-    { BT_ATT_OP_READ_MULT_REQ,
-      BT_ATT_READ_MULT_MIN_LEN_REQ,
-      ATT_REQUEST,
-      att_read_mult_req },
-#endif /* CONFIG_BT_GATT_READ_MULTIPLE */
-    { BT_ATT_OP_READ_GROUP_REQ,
-      sizeof(struct bt_att_read_group_req),
-      ATT_REQUEST,
-      att_read_group_req },
-    { BT_ATT_OP_WRITE_REQ,
-      sizeof(struct bt_att_write_req),
-      ATT_REQUEST,
-      att_write_req },
-    { BT_ATT_OP_PREPARE_WRITE_REQ,
-      sizeof(struct bt_att_prepare_write_req),
-      ATT_REQUEST,
-      att_prepare_write_req },
-    { BT_ATT_OP_EXEC_WRITE_REQ,
-      sizeof(struct bt_att_exec_write_req),
-      ATT_REQUEST,
-      att_exec_write_req },
-    { BT_ATT_OP_CONFIRM,
-      0,
-      ATT_CONFIRMATION,
-      att_confirm },
-    { BT_ATT_OP_WRITE_CMD,
-      sizeof(struct bt_att_write_cmd),
-      ATT_COMMAND,
-      att_write_cmd },
+    {    BT_ATT_OP_READ_MULT_REQ,                                        BT_ATT_READ_MULT_MIN_LEN_REQ,      ATT_REQUEST,            att_read_mult_req},
+#endif  /* CONFIG_BT_GATT_READ_MULTIPLE */
+    {   BT_ATT_OP_READ_GROUP_REQ,                                sizeof(struct bt_att_read_group_req),      ATT_REQUEST,           att_read_group_req},
+    {        BT_ATT_OP_WRITE_REQ,                                     sizeof(struct bt_att_write_req),      ATT_REQUEST,                att_write_req},
+    {BT_ATT_OP_PREPARE_WRITE_REQ,                             sizeof(struct bt_att_prepare_write_req),      ATT_REQUEST,        att_prepare_write_req},
+    {   BT_ATT_OP_EXEC_WRITE_REQ,                                sizeof(struct bt_att_exec_write_req),      ATT_REQUEST,           att_exec_write_req},
+    {          BT_ATT_OP_CONFIRM,                                                                   0, ATT_CONFIRMATION,                  att_confirm},
+    {        BT_ATT_OP_WRITE_CMD,                                     sizeof(struct bt_att_write_cmd),      ATT_COMMAND,                att_write_cmd},
 #if defined(CONFIG_BT_SIGNING)
-    { BT_ATT_OP_SIGNED_WRITE_CMD,
-      (sizeof(struct bt_att_write_cmd) +
-       sizeof(struct bt_att_signature)),
-      ATT_COMMAND,
-      att_signed_write_cmd },
-#endif /* CONFIG_BT_SIGNING */
+    { BT_ATT_OP_SIGNED_WRITE_CMD, (sizeof(struct bt_att_write_cmd) + sizeof(struct bt_att_signature)),      ATT_COMMAND,         att_signed_write_cmd},
+#endif  /* CONFIG_BT_SIGNING */
 #if defined(CONFIG_BT_GATT_CLIENT)
-    { BT_ATT_OP_ERROR_RSP,
-      sizeof(struct bt_att_error_rsp),
-      ATT_RESPONSE,
-      att_error_rsp },
-    { BT_ATT_OP_MTU_RSP,
-      sizeof(struct bt_att_exchange_mtu_rsp),
-      ATT_RESPONSE,
-      att_mtu_rsp },
-    { BT_ATT_OP_FIND_INFO_RSP,
-      sizeof(struct bt_att_find_info_rsp),
-      ATT_RESPONSE,
-      att_handle_find_info_rsp },
-    { BT_ATT_OP_FIND_TYPE_RSP,
-      sizeof(struct bt_att_find_type_rsp),
-      ATT_RESPONSE,
-      att_handle_find_type_rsp },
-    { BT_ATT_OP_READ_TYPE_RSP,
-      sizeof(struct bt_att_read_type_rsp),
-      ATT_RESPONSE,
-      att_handle_read_type_rsp },
-    { BT_ATT_OP_READ_RSP,
-      sizeof(struct bt_att_read_rsp),
-      ATT_RESPONSE,
-      att_handle_read_rsp },
-    { BT_ATT_OP_READ_BLOB_RSP,
-      sizeof(struct bt_att_read_blob_rsp),
-      ATT_RESPONSE,
-      att_handle_read_blob_rsp },
+    {        BT_ATT_OP_ERROR_RSP,                                     sizeof(struct bt_att_error_rsp),     ATT_RESPONSE,                att_error_rsp},
+    {          BT_ATT_OP_MTU_RSP,                              sizeof(struct bt_att_exchange_mtu_rsp),     ATT_RESPONSE,                  att_mtu_rsp},
+    {    BT_ATT_OP_FIND_INFO_RSP,                                 sizeof(struct bt_att_find_info_rsp),     ATT_RESPONSE,     att_handle_find_info_rsp},
+    {    BT_ATT_OP_FIND_TYPE_RSP,                                 sizeof(struct bt_att_find_type_rsp),     ATT_RESPONSE,     att_handle_find_type_rsp},
+    {    BT_ATT_OP_READ_TYPE_RSP,                                 sizeof(struct bt_att_read_type_rsp),     ATT_RESPONSE,     att_handle_read_type_rsp},
+    {         BT_ATT_OP_READ_RSP,                                      sizeof(struct bt_att_read_rsp),     ATT_RESPONSE,          att_handle_read_rsp},
+    {    BT_ATT_OP_READ_BLOB_RSP,                                 sizeof(struct bt_att_read_blob_rsp),     ATT_RESPONSE,     att_handle_read_blob_rsp},
 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
-    { BT_ATT_OP_READ_MULT_RSP,
-      sizeof(struct bt_att_read_mult_rsp),
-      ATT_RESPONSE,
-      att_handle_read_mult_rsp },
-#endif /* CONFIG_BT_GATT_READ_MULTIPLE */
-    { BT_ATT_OP_READ_GROUP_RSP,
-      sizeof(struct bt_att_read_group_rsp),
-      ATT_RESPONSE,
-      att_handle_read_group_rsp },
-    { BT_ATT_OP_WRITE_RSP,
-      0,
-      ATT_RESPONSE,
-      att_handle_write_rsp },
-    { BT_ATT_OP_PREPARE_WRITE_RSP,
-      sizeof(struct bt_att_prepare_write_rsp),
-      ATT_RESPONSE,
-      att_handle_prepare_write_rsp },
-    { BT_ATT_OP_EXEC_WRITE_RSP,
-      0,
-      ATT_RESPONSE,
-      att_handle_exec_write_rsp },
-    { BT_ATT_OP_NOTIFY,
-      sizeof(struct bt_att_notify),
-      ATT_NOTIFICATION,
-      att_notify },
-    { BT_ATT_OP_INDICATE,
-      sizeof(struct bt_att_indicate),
-      ATT_INDICATION,
-      att_indicate },
-#endif /* CONFIG_BT_GATT_CLIENT */
+    {    BT_ATT_OP_READ_MULT_RSP,                                 sizeof(struct bt_att_read_mult_rsp),     ATT_RESPONSE,     att_handle_read_mult_rsp},
+#endif  /* CONFIG_BT_GATT_READ_MULTIPLE */
+    {   BT_ATT_OP_READ_GROUP_RSP,                                sizeof(struct bt_att_read_group_rsp),     ATT_RESPONSE,    att_handle_read_group_rsp},
+    {        BT_ATT_OP_WRITE_RSP,                                                                   0,     ATT_RESPONSE,         att_handle_write_rsp},
+    {BT_ATT_OP_PREPARE_WRITE_RSP,                             sizeof(struct bt_att_prepare_write_rsp),     ATT_RESPONSE, att_handle_prepare_write_rsp},
+    {   BT_ATT_OP_EXEC_WRITE_RSP,                                                                   0,     ATT_RESPONSE,    att_handle_exec_write_rsp},
+    {           BT_ATT_OP_NOTIFY,                                        sizeof(struct bt_att_notify), ATT_NOTIFICATION,                   att_notify},
+    {         BT_ATT_OP_INDICATE,                                      sizeof(struct bt_att_indicate),   ATT_INDICATION,                 att_indicate},
+#endif  /* CONFIG_BT_GATT_CLIENT */
 };
 
-static att_type_t att_op_get_type(u8_t op)
-{
-    switch (op) {
-        case BT_ATT_OP_MTU_REQ:
-        case BT_ATT_OP_FIND_INFO_REQ:
-        case BT_ATT_OP_FIND_TYPE_REQ:
-        case BT_ATT_OP_READ_TYPE_REQ:
-        case BT_ATT_OP_READ_REQ:
-        case BT_ATT_OP_READ_BLOB_REQ:
-        case BT_ATT_OP_READ_MULT_REQ:
-        case BT_ATT_OP_READ_GROUP_REQ:
-        case BT_ATT_OP_WRITE_REQ:
-        case BT_ATT_OP_PREPARE_WRITE_REQ:
-        case BT_ATT_OP_EXEC_WRITE_REQ:
-            return ATT_REQUEST;
-        case BT_ATT_OP_CONFIRM:
-            return ATT_CONFIRMATION;
-        case BT_ATT_OP_WRITE_CMD:
-        case BT_ATT_OP_SIGNED_WRITE_CMD:
-            return ATT_COMMAND;
-        case BT_ATT_OP_ERROR_RSP:
-        case BT_ATT_OP_MTU_RSP:
-        case BT_ATT_OP_FIND_INFO_RSP:
-        case BT_ATT_OP_FIND_TYPE_RSP:
-        case BT_ATT_OP_READ_TYPE_RSP:
-        case BT_ATT_OP_READ_RSP:
-        case BT_ATT_OP_READ_BLOB_RSP:
-        case BT_ATT_OP_READ_MULT_RSP:
-        case BT_ATT_OP_READ_GROUP_RSP:
-        case BT_ATT_OP_WRITE_RSP:
-        case BT_ATT_OP_PREPARE_WRITE_RSP:
-        case BT_ATT_OP_EXEC_WRITE_RSP:
-            return ATT_RESPONSE;
-        case BT_ATT_OP_NOTIFY:
-            return ATT_NOTIFICATION;
-        case BT_ATT_OP_INDICATE:
-            return ATT_INDICATION;
-    }
-
-    if (op & ATT_CMD_MASK) {
-        return ATT_COMMAND;
-    }
-
-    return ATT_UNKNOWN;
-}
-
-static int bt_att_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_att *att = ATT_CHAN(chan);
-    struct bt_att_hdr *hdr;
-    const struct att_handler *handler;
-    u8_t err;
-    size_t i;
-
-    if (buf->len < sizeof(*hdr)) {
-        BT_ERR("Too small ATT PDU received");
-        return 0;
-    }
-
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    BT_DBG("Received ATT code 0x%02x len %u", hdr->code, buf->len);
-
-    for (i = 0, handler = NULL; i < ARRAY_SIZE(handlers); i++) {
-        if (hdr->code == handlers[i].op) {
-            handler = &handlers[i];
-            break;
-        }
-    }
-
-    if (!handler) {
-        BT_WARN("Unhandled ATT code 0x%02x", hdr->code);
-        if (att_op_get_type(hdr->code) != ATT_COMMAND) {
-            send_err_rsp(chan->conn, hdr->code, 0,
-                         BT_ATT_ERR_NOT_SUPPORTED);
-        }
-        return 0;
-    }
-
-    if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
-        if (handler->type == ATT_REQUEST &&
-            atomic_test_and_set_bit(att->flags, ATT_PENDING_RSP)) {
-            BT_WARN("Ignoring unexpected request");
-            return 0;
-        } else if (handler->type == ATT_INDICATION &&
-                   atomic_test_and_set_bit(att->flags,
-                                           ATT_PENDING_CFM)) {
-            BT_WARN("Ignoring unexpected indication");
-            return 0;
-        }
-    }
-
-    if (buf->len < handler->expect_len) {
-        BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code);
-        err = BT_ATT_ERR_INVALID_PDU;
-    } else {
-        err = handler->func(att, buf);
-    }
-
-    if (handler->type == ATT_REQUEST && err) {
-        BT_DBG("ATT error 0x%02x", err);
-        send_err_rsp(chan->conn, hdr->code, 0, err);
-    }
-
+static att_type_t att_op_get_type(u8_t op) {
+  switch (op) {
+  case BT_ATT_OP_MTU_REQ:
+  case BT_ATT_OP_FIND_INFO_REQ:
+  case BT_ATT_OP_FIND_TYPE_REQ:
+  case BT_ATT_OP_READ_TYPE_REQ:
+  case BT_ATT_OP_READ_REQ:
+  case BT_ATT_OP_READ_BLOB_REQ:
+  case BT_ATT_OP_READ_MULT_REQ:
+  case BT_ATT_OP_READ_GROUP_REQ:
+  case BT_ATT_OP_WRITE_REQ:
+  case BT_ATT_OP_PREPARE_WRITE_REQ:
+  case BT_ATT_OP_EXEC_WRITE_REQ:
+    return ATT_REQUEST;
+  case BT_ATT_OP_CONFIRM:
+    return ATT_CONFIRMATION;
+  case BT_ATT_OP_WRITE_CMD:
+  case BT_ATT_OP_SIGNED_WRITE_CMD:
+    return ATT_COMMAND;
+  case BT_ATT_OP_ERROR_RSP:
+  case BT_ATT_OP_MTU_RSP:
+  case BT_ATT_OP_FIND_INFO_RSP:
+  case BT_ATT_OP_FIND_TYPE_RSP:
+  case BT_ATT_OP_READ_TYPE_RSP:
+  case BT_ATT_OP_READ_RSP:
+  case BT_ATT_OP_READ_BLOB_RSP:
+  case BT_ATT_OP_READ_MULT_RSP:
+  case BT_ATT_OP_READ_GROUP_RSP:
+  case BT_ATT_OP_WRITE_RSP:
+  case BT_ATT_OP_PREPARE_WRITE_RSP:
+  case BT_ATT_OP_EXEC_WRITE_RSP:
+    return ATT_RESPONSE;
+  case BT_ATT_OP_NOTIFY:
+    return ATT_NOTIFICATION;
+  case BT_ATT_OP_INDICATE:
+    return ATT_INDICATION;
+  }
+
+  if (op & ATT_CMD_MASK) {
+    return ATT_COMMAND;
+  }
+
+  return ATT_UNKNOWN;
+}
+
+static int bt_att_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_att            *att = ATT_CHAN(chan);
+  struct bt_att_hdr        *hdr;
+  const struct att_handler *handler;
+  u8_t                      err;
+  size_t                    i;
+
+  if (buf->len < sizeof(*hdr)) {
+    BT_ERR("Too small ATT PDU received");
     return 0;
-}
+  }
 
-static struct bt_att *att_chan_get(struct bt_conn *conn)
-{
-    struct bt_l2cap_chan *chan;
-    struct bt_att *att;
-
-    if (conn->state != BT_CONN_CONNECTED) {
-        BT_WARN("Not connected");
-        return NULL;
-    }
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  BT_DBG("Received ATT code 0x%02x len %u", hdr->code, buf->len);
 
-    chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_ATT);
-    if (!chan) {
-        BT_ERR("Unable to find ATT channel");
-        return NULL;
+  for (i = 0, handler = NULL; i < ARRAY_SIZE(handlers); i++) {
+    if (hdr->code == handlers[i].op) {
+      handler = &handlers[i];
+      break;
     }
+  }
 
-    att = ATT_CHAN(chan);
-    if (atomic_test_bit(att->flags, ATT_DISCONNECTED)) {
-        BT_WARN("ATT context flagged as disconnected");
-        return NULL;
+  if (!handler) {
+    BT_WARN("Unhandled ATT code 0x%02x", hdr->code);
+    if (att_op_get_type(hdr->code) != ATT_COMMAND) {
+      send_err_rsp(chan->conn, hdr->code, 0, BT_ATT_ERR_NOT_SUPPORTED);
     }
-
-    return att;
-}
-
-struct net_buf *bt_att_create_pdu(struct bt_conn *conn, u8_t op, size_t len)
-{
-    struct bt_att_hdr *hdr;
-    struct net_buf *buf;
-    struct bt_att *att;
-
-    att = att_chan_get(conn);
-    if (!att) {
-        return NULL;
-    }
-
-    if (len + sizeof(op) > att->chan.tx.mtu) {
-        BT_WARN("ATT MTU exceeded, max %u, wanted %zu",
-                att->chan.tx.mtu, len + sizeof(op));
-        return NULL;
-    }
-
-    switch (att_op_get_type(op)) {
-        case ATT_RESPONSE:
-        case ATT_CONFIRMATION:
-            /* Use a timeout only when responding/confirming */
-            buf = bt_l2cap_create_pdu_timeout(NULL, 0, ATT_TIMEOUT);
-            break;
-        default:
-            buf = bt_l2cap_create_pdu(NULL, 0);
-    }
-
-    if (!buf) {
-        BT_ERR("Unable to allocate buffer for op 0x%02x", op);
-        return NULL;
-    }
-
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->code = op;
-
-    return buf;
-}
-
-static void att_reset(struct bt_att *att)
-{
-    struct bt_att_req *req, *tmp;
-    int i;
-    struct net_buf *buf;
+    return 0;
+  }
+
+  if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
+    if (handler->type == ATT_REQUEST && atomic_test_and_set_bit(att->flags, ATT_PENDING_RSP)) {
+      BT_WARN("Ignoring unexpected request");
+      return 0;
+    } else if (handler->type == ATT_INDICATION && atomic_test_and_set_bit(att->flags, ATT_PENDING_CFM)) {
+      BT_WARN("Ignoring unexpected indication");
+      return 0;
+    }
+  }
+
+  if (buf->len < handler->expect_len) {
+    BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code);
+    err = BT_ATT_ERR_INVALID_PDU;
+  } else {
+    err = handler->func(att, buf);
+  }
+
+  if (handler->type == ATT_REQUEST && err) {
+    BT_DBG("ATT error 0x%02x", err);
+    send_err_rsp(chan->conn, hdr->code, 0, err);
+  }
+
+  return 0;
+}
+
+static struct bt_att *att_chan_get(struct bt_conn *conn) {
+  struct bt_l2cap_chan *chan;
+  struct bt_att        *att;
+
+  if (conn->state != BT_CONN_CONNECTED) {
+    BT_WARN("Not connected");
+    return NULL;
+  }
+
+  chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_ATT);
+  if (!chan) {
+    BT_ERR("Unable to find ATT channel");
+    return NULL;
+  }
+
+  att = ATT_CHAN(chan);
+  if (atomic_test_bit(att->flags, ATT_DISCONNECTED)) {
+    BT_WARN("ATT context flagged as disconnected");
+    return NULL;
+  }
+
+  return att;
+}
+
+struct net_buf *bt_att_create_pdu(struct bt_conn *conn, u8_t op, size_t len) {
+  struct bt_att_hdr *hdr;
+  struct net_buf    *buf;
+  struct bt_att     *att;
+
+  att = att_chan_get(conn);
+  if (!att) {
+    return NULL;
+  }
+
+  if (len + sizeof(op) > att->chan.tx.mtu) {
+    BT_WARN("ATT MTU exceeded, max %u, wanted %zu", att->chan.tx.mtu, len + sizeof(op));
+    return NULL;
+  }
+
+  switch (att_op_get_type(op)) {
+  case ATT_RESPONSE:
+  case ATT_CONFIRMATION:
+    /* Use a timeout only when responding/confirming */
+    buf = bt_l2cap_create_pdu_timeout(NULL, 0, ATT_TIMEOUT);
+    break;
+  default:
+    buf = bt_l2cap_create_pdu(NULL, 0);
+  }
+
+  if (!buf) {
+    BT_ERR("Unable to allocate buffer for op 0x%02x", op);
+    return NULL;
+  }
+
+  hdr       = net_buf_add(buf, sizeof(*hdr));
+  hdr->code = op;
+
+  return buf;
+}
+
+static void att_reset(struct bt_att *att) {
+  struct bt_att_req *req, *tmp;
+  int                i;
+  struct net_buf    *buf;
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-    /* Discard queued buffers */
-    while ((buf = k_fifo_get(&att->prep_queue, K_NO_WAIT))) {
-        net_buf_unref(buf);
-    }
+  /* Discard queued buffers */
+  while ((buf = k_fifo_get(&att->prep_queue, K_NO_WAIT))) {
+    net_buf_unref(buf);
+  }
 #endif /* CONFIG_BT_ATT_PREPARE_COUNT > 0 */
 
-    while ((buf = k_fifo_get(&att->tx_queue, K_NO_WAIT))) {
-        net_buf_unref(buf);
-    }
+  while ((buf = k_fifo_get(&att->tx_queue, K_NO_WAIT))) {
+    net_buf_unref(buf);
+  }
 
-    atomic_set_bit(att->flags, ATT_DISCONNECTED);
+  atomic_set_bit(att->flags, ATT_DISCONNECTED);
 
-    /* Ensure that any waiters are woken up */
-    for (i = 0; i < CONFIG_BT_ATT_TX_MAX; i++) {
-        k_sem_give(&att->tx_sem);
-    }
-
-    /* Notify pending requests */
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->reqs, req, tmp, node)
-    {
-        if (req->func) {
-            req->func(NULL, BT_ATT_ERR_UNLIKELY, NULL, 0, req);
-        }
+  /* Ensure that any waiters are woken up */
+  for (i = 0; i < CONFIG_BT_ATT_TX_MAX; i++) {
+    k_sem_give(&att->tx_sem);
+  }
 
-        att_req_destroy(req);
+  /* Notify pending requests */
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->reqs, req, tmp, node) {
+    if (req->func) {
+      req->func(NULL, BT_ATT_ERR_UNLIKELY, NULL, 0, req);
     }
 
-    /* Reset list */
-    sys_slist_init(&att->reqs);
+    att_req_destroy(req);
+  }
 
-    if (!att->req) {
-        return;
-    }
+  /* Reset list */
+  sys_slist_init(&att->reqs);
+
+  if (!att->req) {
+    return;
+  }
 
-    /* Notify outstanding request */
-    att_handle_rsp(att, NULL, 0, BT_ATT_ERR_UNLIKELY);
+  /* Notify outstanding request */
+  att_handle_rsp(att, NULL, 0, BT_ATT_ERR_UNLIKELY);
 }
 
-static void att_timeout(struct k_work *work)
-{
-    struct bt_att *att = CONTAINER_OF(work, struct bt_att, timeout_work);
-    struct bt_l2cap_le_chan *ch = &att->chan;
+static void att_timeout(struct k_work *work) {
+  struct bt_att           *att = CONTAINER_OF(work, struct bt_att, timeout_work);
+  struct bt_l2cap_le_chan *ch  = &att->chan;
 
-    BT_ERR("ATT Timeout");
+  BT_ERR("ATT Timeout");
 
-    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 480:
-	 *
-	 * A transaction not completed within 30 seconds shall time out. Such a
-	 * transaction shall be considered to have failed and the local higher
-	 * layers shall be informed of this failure. No more attribute protocol
-	 * requests, commands, indications or notifications shall be sent to the
-	 * target device on this ATT Bearer.
-	 */
-    att_reset(att);
+  /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 480:
+   *
+   * A transaction not completed within 30 seconds shall time out. Such a
+   * transaction shall be considered to have failed and the local higher
+   * layers shall be informed of this failure. No more attribute protocol
+   * requests, commands, indications or notifications shall be sent to the
+   * target device on this ATT Bearer.
+   */
+  att_reset(att);
 
-    /* Consider the channel disconnected */
-    bt_gatt_disconnected(ch->chan.conn);
-    ch->chan.conn = NULL;
+  /* Consider the channel disconnected */
+  bt_gatt_disconnected(ch->chan.conn);
+  ch->chan.conn = NULL;
 }
 
-static void bt_att_connected(struct bt_l2cap_chan *chan)
-{
-    struct bt_att *att = ATT_CHAN(chan);
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
+static void bt_att_connected(struct bt_l2cap_chan *chan) {
+  struct bt_att           *att = ATT_CHAN(chan);
+  struct bt_l2cap_le_chan *ch  = BT_L2CAP_LE_CHAN(chan);
 
-    BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
+  BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
 
-    k_fifo_init(&att->tx_queue, 20);
+  k_fifo_init(&att->tx_queue, 20);
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-    k_fifo_init(&att->prep_queue, 20);
+  k_fifo_init(&att->prep_queue, 20);
 #endif
 
-    ch->tx.mtu = BT_ATT_DEFAULT_LE_MTU;
-    ch->rx.mtu = BT_ATT_DEFAULT_LE_MTU;
+  ch->tx.mtu = BT_ATT_DEFAULT_LE_MTU;
+  ch->rx.mtu = BT_ATT_DEFAULT_LE_MTU;
 
-    k_delayed_work_init(&att->timeout_work, att_timeout);
-    sys_slist_init(&att->reqs);
+  k_delayed_work_init(&att->timeout_work, att_timeout);
+  sys_slist_init(&att->reqs);
 }
 
-static void bt_att_disconnected(struct bt_l2cap_chan *chan)
-{
-    struct bt_att *att = ATT_CHAN(chan);
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
+static void bt_att_disconnected(struct bt_l2cap_chan *chan) {
+  struct bt_att           *att = ATT_CHAN(chan);
+  struct bt_l2cap_le_chan *ch  = BT_L2CAP_LE_CHAN(chan);
 
-    BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
+  BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
 
-    att_reset(att);
+  att_reset(att);
 
-    bt_gatt_disconnected(ch->chan.conn);
+  bt_gatt_disconnected(ch->chan.conn);
 
 #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS
-    if (att->timeout_work.timer.timer.hdl)
-        k_delayed_work_del_timer(&att->timeout_work);
+  if (att->timeout_work.timer.timer.hdl)
+    k_delayed_work_del_timer(&att->timeout_work);
 
-    if (att->tx_queue._queue.hdl) {
-        k_queue_free(&att->tx_queue._queue);
-        att->tx_queue._queue.hdl = NULL;
-    }
+  if (att->tx_queue._queue.hdl) {
+    k_queue_free(&att->tx_queue._queue);
+    att->tx_queue._queue.hdl = NULL;
+  }
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-    if (att->prep_queue._queue.hdl) {
-        k_queue_free(&att->prep_queue._queue);
-        att->prep_queue._queue.hdl = NULL;
-    }
+  if (att->prep_queue._queue.hdl) {
+    k_queue_free(&att->prep_queue._queue);
+    att->prep_queue._queue.hdl = NULL;
+  }
 #endif
 
-    if (att->tx_sem.sem.hdl)
-        k_sem_delete(&att->tx_sem);
+  if (att->tx_sem.sem.hdl)
+    k_sem_delete(&att->tx_sem);
 #endif
 }
 
 #if defined(CONFIG_BT_SMP)
-static void bt_att_encrypt_change(struct bt_l2cap_chan *chan,
-                                  u8_t hci_status)
-{
-    struct bt_att *att = ATT_CHAN(chan);
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
-    struct bt_conn *conn = ch->chan.conn;
-
-    BT_DBG("chan %p conn %p handle %u sec_level 0x%02x status 0x%02x", ch,
-           conn, conn->handle, conn->sec_level, hci_status);
-
-    /*
-	 * If status (HCI status of security procedure) is non-zero, notify
-	 * outstanding request about security failure.
-	 */
-    if (hci_status) {
-        att_handle_rsp(att, NULL, 0, BT_ATT_ERR_AUTHENTICATION);
-        return;
-    }
-
-    bt_gatt_encrypt_change(conn);
-
-    if (conn->sec_level == BT_SECURITY_L1) {
-        return;
-    }
-
-    if (!att->req || !att->req->retrying) {
-        return;
-    }
-
-    k_sem_take(&att->tx_sem, K_FOREVER);
-    if (!att_is_connected(att)) {
-        BT_WARN("Disconnected");
-        k_sem_give(&att->tx_sem);
-        return;
-    }
+static void bt_att_encrypt_change(struct bt_l2cap_chan *chan, u8_t hci_status) {
+  struct bt_att           *att  = ATT_CHAN(chan);
+  struct bt_l2cap_le_chan *ch   = BT_L2CAP_LE_CHAN(chan);
+  struct bt_conn          *conn = ch->chan.conn;
+
+  BT_DBG("chan %p conn %p handle %u sec_level 0x%02x status 0x%02x", ch, conn, conn->handle, conn->sec_level, hci_status);
+
+  /*
+   * If status (HCI status of security procedure) is non-zero, notify
+   * outstanding request about security failure.
+   */
+  if (hci_status) {
+    att_handle_rsp(att, NULL, 0, BT_ATT_ERR_AUTHENTICATION);
+    return;
+  }
+
+  bt_gatt_encrypt_change(conn);
+
+  if (conn->sec_level == BT_SECURITY_L1) {
+    return;
+  }
+
+  if (!att->req || !att->req->retrying) {
+    return;
+  }
+
+#if (BFLB_BT_CO_THREAD)
+  if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) {
+    k_fifo_put(&att->tx_queue, att->req->buf);
+    return;
+  }
+#else
+  k_sem_take(&att->tx_sem, K_FOREVER);
+#endif
+  if (!att_is_connected(att)) {
+    BT_WARN("Disconnected");
+    k_sem_give(&att->tx_sem);
+    return;
+  }
 
-    BT_DBG("Retrying");
+  BT_DBG("Retrying");
 
-    /* Resend buffer */
-    (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, att->req->buf,
-                           att_cb(att->req->buf), NULL);
-    att->req->buf = NULL;
+  /* Resend buffer */
+  (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, att->req->buf, att_cb(att->req->buf), NULL);
+  att->req->buf = NULL;
 }
 #endif /* CONFIG_BT_SMP */
 
 #if defined(BFLB_BLE_MTU_CHANGE_CB)
-void bt_att_mtu_changed(struct bt_l2cap_chan *chan, u16_t mtu)
-{
-    bt_gatt_mtu_changed(chan->conn, mtu);
-}
+void bt_att_mtu_changed(struct bt_l2cap_chan *chan, u16_t mtu) { bt_gatt_mtu_changed(chan->conn, mtu); }
 #endif
 
-static int bt_att_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
-{
-    int i;
-    static struct bt_l2cap_chan_ops ops = {
-        .connected = bt_att_connected,
-        .disconnected = bt_att_disconnected,
-        .recv = bt_att_recv,
+static int bt_att_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) {
+  int                             i;
+  static struct bt_l2cap_chan_ops ops = {
+      .connected    = bt_att_connected,
+      .disconnected = bt_att_disconnected,
+      .recv         = bt_att_recv,
 #if defined(CONFIG_BT_SMP)
-        .encrypt_change = bt_att_encrypt_change,
+      .encrypt_change = bt_att_encrypt_change,
 #endif /* CONFIG_BT_SMP */
 #if defined(BFLB_BLE_MTU_CHANGE_CB)
-        .mtu_changed = bt_att_mtu_changed,
+      .mtu_changed = bt_att_mtu_changed,
 #endif
-    };
+  };
 
-    BT_DBG("conn %p handle %u", conn, conn->handle);
+  BT_DBG("conn %p handle %u", conn, conn->handle);
 
-    for (i = 0; i < ARRAY_SIZE(bt_req_pool); i++) {
-        struct bt_att *att = &bt_req_pool[i];
+  for (i = 0; i < ARRAY_SIZE(bt_req_pool); i++) {
+    struct bt_att *att = &bt_req_pool[i];
 
-        if (att->chan.chan.conn) {
-            continue;
-        }
+    if (att->chan.chan.conn) {
+      continue;
+    }
 
-        (void)memset(att, 0, sizeof(*att));
-        att->chan.chan.ops = &ops;
-        k_sem_init(&att->tx_sem, CONFIG_BT_ATT_TX_MAX,
-                   CONFIG_BT_ATT_TX_MAX);
+    (void)memset(att, 0, sizeof(*att));
+    att->chan.chan.ops = &ops;
+    k_sem_init(&att->tx_sem, CONFIG_BT_ATT_TX_MAX, CONFIG_BT_ATT_TX_MAX);
 
-        *chan = &att->chan.chan;
+    *chan = &att->chan.chan;
 
-        return 0;
-    }
+    return 0;
+  }
 
-    BT_ERR("No available ATT context for conn %p", conn);
+  BT_ERR("No available ATT context for conn %p", conn);
 
-    return -ENOMEM;
+  return -ENOMEM;
 }
 
 BT_L2CAP_CHANNEL_DEFINE(att_fixed_chan, BT_L2CAP_CID_ATT, bt_att_accept);
 
-void bt_att_init(void)
-{
+void bt_att_init(void) {
 #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL)
-    static struct bt_l2cap_fixed_chan chan = {
-        .cid = BT_L2CAP_CID_ATT,
-        .accept = bt_att_accept,
-    };
+  static struct bt_l2cap_fixed_chan chan = {
+      .cid    = BT_L2CAP_CID_ATT,
+      .accept = bt_att_accept,
+  };
 
-    bt_l2cap_le_fixed_chan_register(&chan);
+  bt_l2cap_le_fixed_chan_register(&chan);
 #endif
 
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_init(&prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU, NULL);
+#if (BFLB_STATIC_ALLOC_MEM)
+  net_buf_init(PREP, &prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU, NULL);
+#else
+  net_buf_init(&prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU, NULL);
+#endif
 #endif
 #endif
 
-    bt_gatt_init();
+  bt_gatt_init();
 }
 
-u16_t bt_att_get_mtu(struct bt_conn *conn)
-{
-    struct bt_att *att;
+u16_t bt_att_get_mtu(struct bt_conn *conn) {
+  struct bt_att *att;
 
-    att = att_chan_get(conn);
-    if (!att) {
-        return 0;
-    }
+  att = att_chan_get(conn);
+  if (!att) {
+    return 0;
+  }
 
-    /* tx and rx MTU shall be symmetric */
-    return att->chan.tx.mtu;
+  /* tx and rx MTU shall be symmetric */
+  return att->chan.tx.mtu;
 }
 
-int bt_att_send(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb,
-                void *user_data)
-{
-    struct bt_att *att;
-    int err;
+int bt_att_send(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) {
+  struct bt_att *att;
+  int            err;
 
-    __ASSERT_NO_MSG(conn);
-    __ASSERT_NO_MSG(buf);
+  __ASSERT_NO_MSG(conn);
+  __ASSERT_NO_MSG(buf);
 
-    att = att_chan_get(conn);
-    if (!att) {
-        net_buf_unref(buf);
-        return -ENOTCONN;
-    }
+  att = att_chan_get(conn);
+  if (!att) {
+    net_buf_unref(buf);
+    return -ENOTCONN;
+  }
 
-    /* Don't use tx_sem if caller has set it own callback */
-    if (!cb) {
-        /* Queue buffer to be send later */
-        if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) {
-            k_fifo_put(&att->tx_queue, buf);
-            return 0;
-        }
+  /* Don't use tx_sem if caller has set it own callback */
+  if (!cb) {
+    /* Queue buffer to be send later */
+    if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) {
+      k_fifo_put(&att->tx_queue, buf);
+      return 0;
     }
+  }
 
-    err = att_send(conn, buf, cb, user_data);
-    if (err) {
-        if (!cb) {
-            k_sem_give(&att->tx_sem);
-        }
-        return err;
+  err = att_send(conn, buf, cb, user_data);
+  if (err) {
+    if (!cb) {
+      k_sem_give(&att->tx_sem);
     }
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int bt_att_req_send(struct bt_conn *conn, struct bt_att_req *req)
-{
-    struct bt_att *att;
+int bt_att_req_send(struct bt_conn *conn, struct bt_att_req *req) {
+  struct bt_att *att;
 
-    BT_DBG("conn %p req %p", conn, req);
+  BT_DBG("conn %p req %p", conn, req);
 
-    __ASSERT_NO_MSG(conn);
-    __ASSERT_NO_MSG(req);
+  __ASSERT_NO_MSG(conn);
+  __ASSERT_NO_MSG(req);
 
-    att = att_chan_get(conn);
-    if (!att) {
-        net_buf_unref(req->buf);
-        req->buf = NULL;
-        return -ENOTCONN;
-    }
+  att = att_chan_get(conn);
+  if (!att) {
+    net_buf_unref(req->buf);
+    req->buf = NULL;
+    return -ENOTCONN;
+  }
 
-    /* Check if there is a request outstanding */
-    if (att->req) {
-        /* Queue the request to be send later */
-        sys_slist_append(&att->reqs, &req->node);
-        return 0;
-    }
+  /* Check if there is a request outstanding */
+  if (att->req) {
+    /* Queue the request to be send later */
+    sys_slist_append(&att->reqs, &req->node);
+    return 0;
+  }
 
-    return att_send_req(att, req);
+  return att_send_req(att, req);
 }
 
-void bt_att_req_cancel(struct bt_conn *conn, struct bt_att_req *req)
-{
-    struct bt_att *att;
+void bt_att_req_cancel(struct bt_conn *conn, struct bt_att_req *req) {
+  struct bt_att *att;
 
-    BT_DBG("req %p", req);
+  BT_DBG("req %p", req);
 
-    if (!conn || !req) {
-        return;
-    }
+  if (!conn || !req) {
+    return;
+  }
 
-    att = att_chan_get(conn);
-    if (!att) {
-        return;
-    }
+  att = att_chan_get(conn);
+  if (!att) {
+    return;
+  }
 
-    /* Check if request is outstanding */
-    if (att->req == req) {
-        att->req = &cancel;
-    } else {
-        /* Remove request from the list */
-        sys_slist_find_and_remove(&att->reqs, &req->node);
-    }
+  /* Check if request is outstanding */
+  if (att->req == req) {
+    att->req = &cancel;
+  } else {
+    /* Remove request from the list */
+    sys_slist_find_and_remove(&att->reqs, &req->node);
+  }
 
-    att_req_destroy(req);
+  att_req_destroy(req);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c
index 6644abcd1..4e3a54cfb 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn.c
@@ -6,21 +6,23 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
-#include 
 #include 
+#include 
+#include 
 #include 
-#include 
 #include 
 #include 
-#include 
+#include 
+#include 
+#include 
+#include 
 
 #include 
+
 #include 
 #include 
 #include 
+
 #include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_CONN)
@@ -28,10 +30,12 @@
 #include "log.h"
 
 #include "hci_core.h"
+
 #include "conn_internal.h"
-#include "l2cap_internal.h"
 #include "keys.h"
+#include "l2cap_internal.h"
 #include "smp.h"
+
 #include "att_internal.h"
 #include "gatt_internal.h"
 #if defined(BFLB_BLE)
@@ -40,15 +44,13 @@
 extern struct k_sem g_poll_sem;
 #endif
 struct tx_meta {
-    struct bt_conn_tx *tx;
+  struct bt_conn_tx *tx;
 };
 
 #define tx_data(buf) ((struct tx_meta *)net_buf_user_data(buf))
 
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
-NET_BUF_POOL_DEFINE(acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT,
-                    BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU),
-                    sizeof(struct tx_meta), NULL);
+NET_BUF_POOL_DEFINE(acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), sizeof(struct tx_meta), NULL);
 #else
 struct net_buf_pool acl_tx_pool;
 #endif
@@ -68,8 +70,7 @@ struct net_buf_pool acl_tx_pool;
  * are queued up in the TX queue. In such a situation, trying to allocate
  * another buffer from the acl_tx_pool would result in a deadlock.
  */
-NET_BUF_POOL_FIXED_DEFINE(frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE,
-                          NULL);
+NET_BUF_POOL_FIXED_DEFINE(frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE, NULL);
 #else
 struct net_buf_pool frag_pool;
 #endif
@@ -82,7 +83,7 @@ struct net_buf_pool frag_pool;
 const struct bt_conn_auth_cb *bt_auth;
 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
 
-static struct bt_conn conns[CONFIG_BT_MAX_CONN];
+static struct bt_conn     conns[CONFIG_BT_MAX_CONN];
 static struct bt_conn_cb *callback_list;
 
 static struct bt_conn_tx conn_tx[CONFIG_BT_CONN_TX_MAX];
@@ -92,2605 +93,2452 @@ K_FIFO_DEFINE(free_tx);
 static struct bt_conn sco_conns[CONFIG_BT_MAX_SCO_CONN];
 
 enum pairing_method {
-    LEGACY,          /* Legacy (pre-SSP) pairing */
-    JUST_WORKS,      /* JustWorks pairing */
-    PASSKEY_INPUT,   /* Passkey Entry input */
-    PASSKEY_DISPLAY, /* Passkey Entry display */
-    PASSKEY_CONFIRM, /* Passkey confirm */
+  LEGACY,          /* Legacy (pre-SSP) pairing */
+  JUST_WORKS,      /* JustWorks pairing */
+  PASSKEY_INPUT,   /* Passkey Entry input */
+  PASSKEY_DISPLAY, /* Passkey Entry display */
+  PASSKEY_CONFIRM, /* Passkey confirm */
 };
 
 /* based on table 5.7, Core Spec 4.2, Vol.3 Part C, 5.2.2.6 */
 static const u8_t ssp_method[4 /* remote */][4 /* local */] = {
-    { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS },
-    { JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS },
-    { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS },
-    { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS },
+    {     JUST_WORKS,      JUST_WORKS, PASSKEY_INPUT, JUST_WORKS},
+    {     JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS},
+    {PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS},
+    {     JUST_WORKS,      JUST_WORKS,    JUST_WORKS, JUST_WORKS},
 };
 #endif /* CONFIG_BT_BREDR */
 
-struct k_sem *bt_conn_get_pkts(struct bt_conn *conn)
-{
+struct k_sem *bt_conn_get_pkts(struct bt_conn *conn) {
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) {
-        return &bt_dev.br.pkts;
-    }
+  if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) {
+    return &bt_dev.br.pkts;
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    return &bt_dev.le.pkts;
+  return &bt_dev.le.pkts;
 }
 
-static inline const char *state2str(bt_conn_state_t state)
-{
-    switch (state) {
-        case BT_CONN_DISCONNECTED:
-            return "disconnected";
-        case BT_CONN_CONNECT_SCAN:
-            return "connect-scan";
-        case BT_CONN_CONNECT_DIR_ADV:
-            return "connect-dir-adv";
-        case BT_CONN_CONNECT:
-            return "connect";
-        case BT_CONN_CONNECTED:
-            return "connected";
-        case BT_CONN_DISCONNECT:
-            return "disconnect";
-        default:
-            return "(unknown)";
-    }
-}
-
-static void notify_connected(struct bt_conn *conn)
-{
-    struct bt_conn_cb *cb;
+static inline const char *state2str(bt_conn_state_t state) {
+  switch (state) {
+  case BT_CONN_DISCONNECTED:
+    return "disconnected";
+  case BT_CONN_CONNECT_SCAN:
+    return "connect-scan";
+  case BT_CONN_CONNECT_DIR_ADV:
+    return "connect-dir-adv";
+  case BT_CONN_CONNECT:
+    return "connect";
+  case BT_CONN_CONNECTED:
+    return "connected";
+  case BT_CONN_DISCONNECT:
+    return "disconnect";
+  default:
+    return "(unknown)";
+  }
+}
+
+static void notify_connected(struct bt_conn *conn) {
+  struct bt_conn_cb *cb;
 
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR && conn->err) {
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_ISCAN);
-        }
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_PSCAN);
-        }
+  if (conn->type == BT_CONN_TYPE_BR && conn->err) {
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_ISCAN);
+    }
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_PSCAN);
     }
+  }
 #endif
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (cb->connected) {
-            cb->connected(conn, conn->err);
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->connected) {
+      cb->connected(conn, conn->err);
     }
+  }
 
-    if (!conn->err) {
-        bt_gatt_connected(conn);
-    }
+  if (conn->type == BT_CONN_TYPE_LE && !conn->err) {
+    bt_gatt_connected(conn);
+  }
 }
 
-static void notify_disconnected(struct bt_conn *conn)
-{
-    struct bt_conn_cb *cb;
+void notify_disconnected(struct bt_conn *conn) {
+  struct bt_conn_cb *cb;
 
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_ISCAN);
-        }
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_PSCAN);
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_ISCAN);
+    }
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_PSCAN);
     }
+  }
 #endif
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (cb->disconnected) {
-            cb->disconnected(conn, conn->err);
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->disconnected) {
+      cb->disconnected(conn, conn->err);
     }
+  }
 }
 
-void notify_le_param_updated(struct bt_conn *conn)
-{
-    struct bt_conn_cb *cb;
+void notify_le_param_updated(struct bt_conn *conn) {
+  struct bt_conn_cb *cb;
 
-    /* If new connection parameters meet requirement of pending
-	 * parameters don't send slave conn param request anymore on timeout
-	 */
-    if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET) &&
-        conn->le.interval >= conn->le.interval_min &&
-        conn->le.interval <= conn->le.interval_max &&
-        conn->le.latency == conn->le.pending_latency &&
-        conn->le.timeout == conn->le.pending_timeout) {
-        atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
-    }
+  /* If new connection parameters meet requirement of pending
+   * parameters don't send slave conn param request anymore on timeout
+   */
+  if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET) && conn->le.interval >= conn->le.interval_min && conn->le.interval <= conn->le.interval_max &&
+      conn->le.latency == conn->le.pending_latency && conn->le.timeout == conn->le.pending_timeout) {
+    atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
+  }
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (cb->le_param_updated) {
-            cb->le_param_updated(conn, conn->le.interval,
-                                 conn->le.latency,
-                                 conn->le.timeout);
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->le_param_updated) {
+      cb->le_param_updated(conn, conn->le.interval, conn->le.latency, conn->le.timeout);
     }
+  }
 }
 
-bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param)
-{
-    struct bt_conn_cb *cb;
+void notify_le_phy_updated(struct bt_conn *conn, u8_t tx_phy, u8_t rx_phy) {
+  struct bt_conn_cb *cb;
 
-    if (!bt_le_conn_params_valid(param)) {
-        return false;
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->le_phy_updated) {
+      cb->le_phy_updated(conn, tx_phy, rx_phy);
     }
+  }
+}
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (!cb->le_param_req) {
-            continue;
-        }
+bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param) {
+  struct bt_conn_cb *cb;
 
-        if (!cb->le_param_req(conn, param)) {
-            return false;
-        }
+  if (!bt_le_conn_params_valid(param)) {
+    return false;
+  }
 
-        /* The callback may modify the parameters so we need to
-		 * double-check that it returned valid parameters.
-		 */
-        if (!bt_le_conn_params_valid(param)) {
-            return false;
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (!cb->le_param_req) {
+      continue;
     }
 
-    /* Default to accepting if there's no app callback */
-    return true;
-}
+    if (!cb->le_param_req(conn, param)) {
+      return false;
+    }
 
-static int send_conn_le_param_update(struct bt_conn *conn,
-                                     const struct bt_le_conn_param *param)
-{
-    BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn,
-           conn->le.features[0], param->interval_min,
-           param->interval_max, param->latency, param->timeout);
+    /* The callback may modify the parameters so we need to
+     * double-check that it returned valid parameters.
+     */
+    if (!bt_le_conn_params_valid(param)) {
+      return false;
+    }
+  }
+
+  /* Default to accepting if there's no app callback */
+  return true;
+}
 
-    /* Use LE connection parameter request if both local and remote support
-	 * it; or if local role is master then use LE connection update.
-	 */
-    if ((BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features) &&
-         BT_FEAT_LE_CONN_PARAM_REQ_PROC(conn->le.features) &&
-         !atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) ||
-        (conn->role == BT_HCI_ROLE_MASTER)) {
-        int rc;
+static int send_conn_le_param_update(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, conn->le.features[0], param->interval_min, param->interval_max, param->latency, param->timeout);
 
-        rc = bt_conn_le_conn_update(conn, param);
+  /* Use LE connection parameter request if both local and remote support
+   * it; or if local role is master then use LE connection update.
+   */
+  if ((BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features) && BT_FEAT_LE_CONN_PARAM_REQ_PROC(conn->le.features) && !atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) ||
+      (conn->role == BT_HCI_ROLE_MASTER)) {
+    int rc;
 
-        /* store those in case of fallback to L2CAP */
-        if (rc == 0) {
-            conn->le.pending_latency = param->latency;
-            conn->le.pending_timeout = param->timeout;
-        }
+    rc = bt_conn_le_conn_update(conn, param);
 
-        return rc;
+    /* store those in case of fallback to L2CAP */
+    if (rc == 0) {
+      conn->le.pending_latency = param->latency;
+      conn->le.pending_timeout = param->timeout;
     }
 
-    /* If remote master does not support LL Connection Parameters Request
-	 * Procedure
-	 */
-    return bt_l2cap_update_conn_param(conn, param);
+    return rc;
+  }
+
+  /* If remote master does not support LL Connection Parameters Request
+   * Procedure
+   */
+  return bt_l2cap_update_conn_param(conn, param);
 }
 
-static void tx_free(struct bt_conn_tx *tx)
-{
-    tx->cb = NULL;
-    tx->user_data = NULL;
-    tx->pending_no_cb = 0U;
-    k_fifo_put(&free_tx, tx);
+static void tx_free(struct bt_conn_tx *tx) {
+  tx->cb            = NULL;
+  tx->user_data     = NULL;
+  tx->pending_no_cb = 0U;
+  k_fifo_put(&free_tx, tx);
 }
 
-static void tx_notify(struct bt_conn *conn)
-{
-    BT_DBG("conn %p", conn);
+static void tx_notify(struct bt_conn *conn) {
+  BT_DBG("conn %p", conn);
 
-    while (1) {
-        struct bt_conn_tx *tx;
-        unsigned int key;
-        bt_conn_tx_cb_t cb;
-        void *user_data;
+  while (1) {
+    struct bt_conn_tx *tx;
+    unsigned int       key;
+    bt_conn_tx_cb_t    cb;
+    void              *user_data;
 
-        key = irq_lock();
-        if (sys_slist_is_empty(&conn->tx_complete)) {
-            irq_unlock(key);
-            break;
-        }
+    key = irq_lock();
+    if (sys_slist_is_empty(&conn->tx_complete)) {
+      irq_unlock(key);
+      break;
+    }
 
-        tx = (void *)sys_slist_get_not_empty(&conn->tx_complete);
-        irq_unlock(key);
+    tx = (void *)sys_slist_get_not_empty(&conn->tx_complete);
+    irq_unlock(key);
 
-        BT_DBG("tx %p cb %p user_data %p", tx, tx->cb, tx->user_data);
+    BT_DBG("tx %p cb %p user_data %p", tx, tx->cb, tx->user_data);
 
-        /* Copy over the params */
-        cb = tx->cb;
-        user_data = tx->user_data;
+    /* Copy over the params */
+    cb        = tx->cb;
+    user_data = tx->user_data;
 
-        /* Free up TX notify since there may be user waiting */
-        tx_free(tx);
+    /* Free up TX notify since there may be user waiting */
+    tx_free(tx);
 
-        /* Run the callback, at this point it should be safe to
-		 * allocate new buffers since the TX should have been
-		 * unblocked by tx_free.
-		 */
-        cb(conn, user_data);
-    }
+    /* Run the callback, at this point it should be safe to
+     * allocate new buffers since the TX should have been
+     * unblocked by tx_free.
+     */
+    cb(conn, user_data);
+  }
 }
 
-static void tx_complete_work(struct k_work *work)
-{
-    struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn,
-                                        tx_complete_work);
+static void tx_complete_work(struct k_work *work) {
+  struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn, tx_complete_work);
 
-    BT_DBG("conn %p", conn);
+  BT_DBG("conn %p", conn);
 
-    tx_notify(conn);
+  tx_notify(conn);
 }
 
-static void conn_update_timeout(struct k_work *work)
-{
-    struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn, update_work);
-    const struct bt_le_conn_param *param;
-
-    BT_DBG("conn %p", conn);
-
-    if (conn->state == BT_CONN_DISCONNECTED) {
-        bt_l2cap_disconnected(conn);
-        notify_disconnected(conn);
+static void conn_update_timeout(struct k_work *work) {
+  struct bt_conn                *conn = CONTAINER_OF(work, struct bt_conn, update_work);
+  const struct bt_le_conn_param *param;
 
-        /* Release the reference we took for the very first
-		 * state transition.
-		 */
-        bt_conn_unref(conn);
-        return;
-    }
+  BT_DBG("conn %p", conn);
 
-    if (conn->type != BT_CONN_TYPE_LE) {
-        return;
-    }
+  if (conn->state == BT_CONN_DISCONNECTED) {
+    bt_l2cap_disconnected(conn);
+#if !defined(BFLB_BLE)
+    notify_disconnected(conn);
+#endif
 
-    if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-        conn->role == BT_CONN_ROLE_MASTER) {
-        /* we don't call bt_conn_disconnect as it would also clear
-		 * auto connect flag if it was set, instead just cancel
-		 * connection directly
-		 */
-        bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, NULL, NULL);
-        return;
-    }
+    /* Release the reference we took for the very first
+     * state transition.
+     */
+    bt_conn_unref(conn);
+    return;
+  }
+
+  if (conn->type != BT_CONN_TYPE_LE) {
+    return;
+  }
+
+  if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_CONN_ROLE_MASTER) {
+    /* we don't call bt_conn_disconnect as it would also clear
+     * auto connect flag if it was set, instead just cancel
+     * connection directly
+     */
+    bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, NULL, NULL);
+    return;
+  }
 
 #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS)
-    /* if application set own params use those, otherwise use defaults */
-    if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) {
-        param = BT_LE_CONN_PARAM(conn->le.interval_min,
-                                 conn->le.interval_max,
-                                 conn->le.pending_latency,
-                                 conn->le.pending_timeout);
-
-        send_conn_le_param_update(conn, param);
-    } else {
-        param = BT_LE_CONN_PARAM(CONFIG_BT_PERIPHERAL_PREF_MIN_INT,
-                                 CONFIG_BT_PERIPHERAL_PREF_MAX_INT,
-                                 CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY,
-                                 CONFIG_BT_PERIPHERAL_PREF_TIMEOUT);
+  /* if application set own params use those, otherwise use defaults */
+  if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) {
+    param = BT_LE_CONN_PARAM(conn->le.interval_min, conn->le.interval_max, conn->le.pending_latency, conn->le.pending_timeout);
 
-        send_conn_le_param_update(conn, param);
-    }
+    send_conn_le_param_update(conn, param);
+  } else {
+    param = BT_LE_CONN_PARAM(CONFIG_BT_PERIPHERAL_PREF_MIN_INT, CONFIG_BT_PERIPHERAL_PREF_MAX_INT, CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY, CONFIG_BT_PERIPHERAL_PREF_TIMEOUT);
+
+    send_conn_le_param_update(conn, param);
+  }
 #else
-    /* update only if application set own params */
-    if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) {
-        param = BT_LE_CONN_PARAM(conn->le.interval_min,
-                                 conn->le.interval_max,
-                                 conn->le.latency,
-                                 conn->le.timeout);
+  /* update only if application set own params */
+  if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) {
+    param = BT_LE_CONN_PARAM(conn->le.interval_min, conn->le.interval_max, conn->le.latency, conn->le.timeout);
 
-        send_conn_le_param_update(conn, param);
-    }
+    send_conn_le_param_update(conn, param);
+  }
 #endif
 
-    atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE);
+  atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE);
 }
 
 #if defined(CONFIG_BT_AUDIO)
-struct bt_conn *iso_conn_new(struct bt_conn *conns, size_t size)
-{
-    struct bt_conn *conn = NULL;
-    int i;
+struct bt_conn *iso_conn_new(struct bt_conn *conns, size_t size) {
+  struct bt_conn *conn = NULL;
+  int             i;
 
-    for (i = 0; i < size; i++) {
-        if (atomic_cas(&conns[i].ref, 0, 1)) {
-            conn = &conns[i];
-            break;
-        }
+  for (i = 0; i < size; i++) {
+    if (atomic_cas(&conns[i].ref, 0, 1)) {
+      conn = &conns[i];
+      break;
     }
+  }
 
-    if (!conn) {
-        return NULL;
-    }
+  if (!conn) {
+    return NULL;
+  }
 
-    (void)memset(conn, 0, offsetof(struct bt_conn, ref));
+  (void)memset(conn, 0, offsetof(struct bt_conn, ref));
 
-    return conn;
+  return conn;
 }
 #endif
 
-static struct bt_conn *conn_new(void)
-{
-    struct bt_conn *conn = NULL;
-    int i;
+static struct bt_conn *conn_new(void) {
+  struct bt_conn *conn = NULL;
+  int             i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            conn = &conns[i];
-            break;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      conn = &conns[i];
+      break;
     }
+  }
 
-    if (!conn) {
-        return NULL;
-    }
+  if (!conn) {
+    return NULL;
+  }
 
-    (void)memset(conn, 0, sizeof(*conn));
-    k_delayed_work_init(&conn->update_work, conn_update_timeout);
+  (void)memset(conn, 0, sizeof(*conn));
+  k_delayed_work_init(&conn->update_work, conn_update_timeout);
 
-    k_work_init(&conn->tx_complete_work, tx_complete_work);
+  k_work_init(&conn->tx_complete_work, tx_complete_work);
 
-    atomic_set(&conn->ref, 1);
+  atomic_set(&conn->ref, 1);
 
-    return conn;
+  return conn;
 }
 
 #if defined(BFLB_BLE)
-bool le_check_valid_conn(void)
-{
-    int i;
+bool le_check_valid_conn(void) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (atomic_get(&conns[i].ref)) {
-            return true;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (atomic_get(&conns[i].ref)) {
+      return true;
     }
+  }
 
-    return false;
+  return false;
 }
 
 #if defined(BFLB_HOST_ASSISTANT)
-void bt_notify_disconnected(void)
-{
-    int i;
+void bt_notify_disconnected(void) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (atomic_get(&conns[i].ref)) {
-            conns[i].err = BT_HCI_ERR_UNSPECIFIED;
-            notify_disconnected(&conns[i]);
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (atomic_get(&conns[i].ref)) {
+      conns[i].err = BT_HCI_ERR_UNSPECIFIED;
+      notify_disconnected(&conns[i]);
     }
+  }
 }
-#endif //#if defined(BFLB_HOST_ASSISTANT)
+#endif // #if defined(BFLB_HOST_ASSISTANT)
 #endif
 
 #if defined(CONFIG_BT_BREDR)
-void bt_sco_cleanup(struct bt_conn *sco_conn)
-{
-    bt_conn_unref(sco_conn->sco.acl);
-    sco_conn->sco.acl = NULL;
-    bt_conn_unref(sco_conn);
+void bt_sco_cleanup(struct bt_conn *sco_conn) {
+  bt_conn_unref(sco_conn->sco.acl);
+  sco_conn->sco.acl = NULL;
+  bt_conn_unref(sco_conn);
 }
 
-static struct bt_conn *sco_conn_new(void)
-{
-    struct bt_conn *sco_conn = NULL;
-    int i;
+static struct bt_conn *sco_conn_new(void) {
+  struct bt_conn *sco_conn = NULL;
+  int             i;
 
-    for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
-        if (!atomic_get(&sco_conns[i].ref)) {
-            sco_conn = &sco_conns[i];
-            break;
-        }
+  for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
+    if (!atomic_get(&sco_conns[i].ref)) {
+      sco_conn = &sco_conns[i];
+      break;
     }
+  }
 
-    if (!sco_conn) {
-        return NULL;
-    }
+  if (!sco_conn) {
+    return NULL;
+  }
 
-    (void)memset(sco_conn, 0, sizeof(*sco_conn));
+  (void)memset(sco_conn, 0, sizeof(*sco_conn));
 
-    atomic_set(&sco_conn->ref, 1);
+  atomic_set(&sco_conn->ref, 1);
 
-    return sco_conn;
+  return sco_conn;
 }
 
-struct bt_conn *bt_conn_create_br(const bt_addr_t *peer,
-                                  const struct bt_br_conn_param *param)
-{
-    struct bt_hci_cp_connect *cp;
-    struct bt_conn *conn;
-    struct net_buf *buf;
-
-    conn = bt_conn_lookup_addr_br(peer);
-    if (conn) {
-        switch (conn->state) {
-            case BT_CONN_CONNECT:
-            case BT_CONN_CONNECTED:
-                return conn;
-            default:
-                bt_conn_unref(conn);
-                return NULL;
-        }
-    }
-
-    conn = bt_conn_add_br(peer);
-    if (!conn) {
-        return NULL;
-    }
+struct bt_conn *bt_conn_create_br(const bt_addr_t *peer, const struct bt_br_conn_param *param) {
+  struct bt_hci_cp_connect *cp;
+  struct bt_conn           *conn;
+  struct net_buf           *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT, sizeof(*cp));
-    if (!buf) {
-        bt_conn_unref(conn);
-        return NULL;
+  conn = bt_conn_lookup_addr_br(peer);
+  if (conn) {
+    switch (conn->state) {
+    case BT_CONN_CONNECT:
+    case BT_CONN_CONNECTED:
+      return conn;
+    default:
+      bt_conn_unref(conn);
+      return NULL;
     }
+  }
+
+  conn = bt_conn_add_br(peer);
+  if (!conn) {
+    return NULL;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT, sizeof(*cp));
+  if (!buf) {
+    bt_conn_unref(conn);
+    return NULL;
+  }
 
-    (void)memset(cp, 0, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    memcpy(&cp->bdaddr, peer, sizeof(cp->bdaddr));
-    cp->packet_type = sys_cpu_to_le16(0xcc18); /* DM1 DH1 DM3 DH5 DM5 DH5 */
-    cp->pscan_rep_mode = 0x02;                 /* R2 */
-    cp->allow_role_switch = param->allow_role_switch ? 0x01 : 0x00;
-    cp->clock_offset = 0x0000; /* TODO used cached clock offset */
+  (void)memset(cp, 0, sizeof(*cp));
 
-    if (bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT, buf, NULL) < 0) {
-        bt_conn_unref(conn);
-        return NULL;
-    }
+  memcpy(&cp->bdaddr, peer, sizeof(cp->bdaddr));
+  cp->packet_type       = sys_cpu_to_le16(0xcc18); /* DM1 DH1 DM3 DH5 DM5 DH5 */
+  cp->pscan_rep_mode    = 0x02;                    /* R2 */
+  cp->allow_role_switch = param->allow_role_switch ? 0x01 : 0x00;
+  cp->clock_offset      = 0x0000; /* TODO used cached clock offset */
 
-    bt_conn_set_state(conn, BT_CONN_CONNECT);
-    conn->role = BT_CONN_ROLE_MASTER;
+  if (bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT, buf, NULL) < 0) {
+    bt_conn_unref(conn);
+    return NULL;
+  }
 
-    return conn;
+  bt_conn_set_state(conn, BT_CONN_CONNECT);
+  conn->role = BT_CONN_ROLE_MASTER;
+
+  bt_conn_unref(conn);
+  return conn;
 }
 
-struct bt_conn *bt_conn_create_sco(const bt_addr_t *peer)
-{
-    struct bt_hci_cp_setup_sync_conn *cp;
-    struct bt_conn *sco_conn;
-    struct net_buf *buf;
-    int link_type;
-
-    sco_conn = bt_conn_lookup_addr_sco(peer);
-    if (sco_conn) {
-        switch (sco_conn->state) {
-            case BT_CONN_CONNECT:
-            case BT_CONN_CONNECTED:
-                return sco_conn;
-            default:
-                bt_conn_unref(sco_conn);
-                return NULL;
-        }
-    }
+struct bt_conn *bt_conn_create_sco(const bt_addr_t *peer) {
+  struct bt_hci_cp_setup_sync_conn *cp;
+  struct bt_conn                   *sco_conn;
+  struct net_buf                   *buf;
+  int                               link_type;
 
-    if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
-        link_type = BT_HCI_ESCO;
-    } else {
-        link_type = BT_HCI_SCO;
+  sco_conn = bt_conn_lookup_addr_sco(peer);
+  if (sco_conn) {
+    switch (sco_conn->state) {
+    case BT_CONN_CONNECT:
+    case BT_CONN_CONNECTED:
+      return sco_conn;
+    default:
+      bt_conn_unref(sco_conn);
+      return NULL;
     }
+  }
 
-    sco_conn = bt_conn_add_sco(peer, link_type);
-    if (!sco_conn) {
-        return NULL;
-    }
+  if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
+    link_type = BT_HCI_ESCO;
+  } else {
+    link_type = BT_HCI_SCO;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_SETUP_SYNC_CONN, sizeof(*cp));
-    if (!buf) {
-        bt_sco_cleanup(sco_conn);
-        return NULL;
-    }
+  sco_conn = bt_conn_add_sco(peer, link_type);
+  if (!sco_conn) {
+    return NULL;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  buf = bt_hci_cmd_create(BT_HCI_OP_SETUP_SYNC_CONN, sizeof(*cp));
+  if (!buf) {
+    bt_sco_cleanup(sco_conn);
+    return NULL;
+  }
 
-    (void)memset(cp, 0, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    BT_ERR("handle : %x", sco_conn->sco.acl->handle);
+  (void)memset(cp, 0, sizeof(*cp));
 
-    cp->handle = sco_conn->sco.acl->handle;
-    cp->pkt_type = sco_conn->sco.pkt_type;
-    cp->tx_bandwidth = 0x00001f40;
-    cp->rx_bandwidth = 0x00001f40;
-    cp->max_latency = 0x0007;
-    cp->retrans_effort = 0x01;
-    cp->content_format = BT_VOICE_CVSD_16BIT;
+  BT_ERR("handle : %x", sco_conn->sco.acl->handle);
 
-    if (bt_hci_cmd_send_sync(BT_HCI_OP_SETUP_SYNC_CONN, buf,
-                             NULL) < 0) {
-        bt_sco_cleanup(sco_conn);
-        return NULL;
-    }
+  cp->handle         = sco_conn->sco.acl->handle;
+  cp->pkt_type       = sco_conn->sco.pkt_type;
+  cp->tx_bandwidth   = 0x00001f40;
+  cp->rx_bandwidth   = 0x00001f40;
+  cp->max_latency    = 0x0007;
+  cp->retrans_effort = 0x01;
+  cp->content_format = BT_VOICE_CVSD_16BIT;
 
-    bt_conn_set_state(sco_conn, BT_CONN_CONNECT);
+  if (bt_hci_cmd_send_sync(BT_HCI_OP_SETUP_SYNC_CONN, buf, NULL) < 0) {
+    bt_sco_cleanup(sco_conn);
+    return NULL;
+  }
+
+  bt_conn_set_state(sco_conn, BT_CONN_CONNECT);
 
-    return sco_conn;
+  return sco_conn;
 }
 
-struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer)
-{
-    int i;
+struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
-        if (!atomic_get(&sco_conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
+    if (!atomic_get(&sco_conns[i].ref)) {
+      continue;
+    }
 
-        if (sco_conns[i].type != BT_CONN_TYPE_SCO) {
-            continue;
-        }
+    if (sco_conns[i].type != BT_CONN_TYPE_SCO) {
+      continue;
+    }
 
-        if (!bt_addr_cmp(peer, &sco_conns[i].sco.acl->br.dst)) {
-            return bt_conn_ref(&sco_conns[i]);
-        }
+    if (!bt_addr_cmp(peer, &sco_conns[i].sco.acl->br.dst)) {
+      return bt_conn_ref(&sco_conns[i]);
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer)
-{
-    int i;
+struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
+    }
 
-        if (conns[i].type != BT_CONN_TYPE_BR) {
-            continue;
-        }
+    if (conns[i].type != BT_CONN_TYPE_BR) {
+      continue;
+    }
 
-        if (!bt_addr_cmp(peer, &conns[i].br.dst)) {
-            return bt_conn_ref(&conns[i]);
-        }
+    if (!bt_addr_cmp(peer, &conns[i].br.dst)) {
+      return bt_conn_ref(&conns[i]);
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type)
-{
-    struct bt_conn *sco_conn = sco_conn_new();
+struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type) {
+  struct bt_conn *sco_conn = sco_conn_new();
 
-    if (!sco_conn) {
-        return NULL;
-    }
+  if (!sco_conn) {
+    return NULL;
+  }
 
-    sco_conn->sco.acl = bt_conn_lookup_addr_br(peer);
-    sco_conn->type = BT_CONN_TYPE_SCO;
+  sco_conn->sco.acl = bt_conn_lookup_addr_br(peer);
+  sco_conn->type    = BT_CONN_TYPE_SCO;
 
-    if (link_type == BT_HCI_SCO) {
-        if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
-            sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type &
-                                      ESCO_PKT_MASK);
-        } else {
-            sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type &
-                                      SCO_PKT_MASK);
-        }
-    } else if (link_type == BT_HCI_ESCO) {
-        sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type &
-                                  ~EDR_ESCO_PKT_MASK);
+  if (link_type == BT_HCI_SCO) {
+    if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
+      sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & ESCO_PKT_MASK);
+    } else {
+      sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & SCO_PKT_MASK);
     }
+  } else if (link_type == BT_HCI_ESCO) {
+    sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & ~EDR_ESCO_PKT_MASK);
+  }
 
-    return sco_conn;
+  return sco_conn;
 }
 
-struct bt_conn *bt_conn_add_br(const bt_addr_t *peer)
-{
-    struct bt_conn *conn = conn_new();
+struct bt_conn *bt_conn_add_br(const bt_addr_t *peer) {
+  struct bt_conn *conn = conn_new();
 
-    if (!conn) {
-        return NULL;
-    }
+  if (!conn) {
+    return NULL;
+  }
 
-    bt_addr_copy(&conn->br.dst, peer);
-    conn->type = BT_CONN_TYPE_BR;
+  bt_addr_copy(&conn->br.dst, peer);
+  conn->type = BT_CONN_TYPE_BR;
 
-    return conn;
+  return conn;
 }
 
-static int pin_code_neg_reply(const bt_addr_t *bdaddr)
-{
-    struct bt_hci_cp_pin_code_neg_reply *cp;
-    struct net_buf *buf;
+static int pin_code_neg_reply(const bt_addr_t *bdaddr) {
+  struct bt_hci_cp_pin_code_neg_reply *cp;
+  struct net_buf                      *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_NEG_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_NEG_REPLY, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_NEG_REPLY, buf, NULL);
 }
 
-static int pin_code_reply(struct bt_conn *conn, const char *pin, u8_t len)
-{
-    struct bt_hci_cp_pin_code_reply *cp;
-    struct net_buf *buf;
+static int pin_code_reply(struct bt_conn *conn, const char *pin, u8_t len) {
+  struct bt_hci_cp_pin_code_reply *cp;
+  struct net_buf                  *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    bt_addr_copy(&cp->bdaddr, &conn->br.dst);
-    cp->pin_len = len;
-    strncpy((char *)cp->pin_code, pin, sizeof(cp->pin_code));
+  bt_addr_copy(&cp->bdaddr, &conn->br.dst);
+  cp->pin_len = len;
+  strncpy((char *)cp->pin_code, pin, sizeof(cp->pin_code));
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_REPLY, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_REPLY, buf, NULL);
 }
 
-int bt_conn_auth_pincode_entry(struct bt_conn *conn, const char *pin)
-{
-    size_t len;
+int bt_conn_auth_pincode_entry(struct bt_conn *conn, const char *pin) {
+  size_t len;
 
-    if (!bt_auth) {
-        return -EINVAL;
-    }
+  if (!bt_auth) {
+    return -EINVAL;
+  }
 
-    if (conn->type != BT_CONN_TYPE_BR) {
-        return -EINVAL;
-    }
+  if (conn->type != BT_CONN_TYPE_BR) {
+    return -EINVAL;
+  }
 
-    len = strlen(pin);
-    if (len > 16) {
-        return -EINVAL;
-    }
+  len = strlen(pin);
+  if (len > 16) {
+    return -EINVAL;
+  }
 
-    if (conn->required_sec_level == BT_SECURITY_L3 && len < 16) {
-        BT_WARN("PIN code for %s is not 16 bytes wide",
-                bt_addr_str(&conn->br.dst));
-        return -EPERM;
-    }
+  if (conn->required_sec_level == BT_SECURITY_L3 && len < 16) {
+    BT_WARN("PIN code for %s is not 16 bytes wide", bt_addr_str(&conn->br.dst));
+    return -EPERM;
+  }
 
-    /* Allow user send entered PIN to remote, then reset user state. */
-    if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
-        return -EPERM;
-    }
+  /* Allow user send entered PIN to remote, then reset user state. */
+  if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
+    return -EPERM;
+  }
 
-    if (len == 16) {
-        atomic_set_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE);
-    }
+  if (len == 16) {
+    atomic_set_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE);
+  }
 
-    return pin_code_reply(conn, pin, len);
+  return pin_code_reply(conn, pin, len);
 }
 
-void bt_conn_pin_code_req(struct bt_conn *conn)
-{
-    if (bt_auth && bt_auth->pincode_entry) {
-        bool secure = false;
-
-        if (conn->required_sec_level == BT_SECURITY_L3) {
-            secure = true;
-        }
+void bt_conn_pin_code_req(struct bt_conn *conn) {
+  if (bt_auth && bt_auth->pincode_entry) {
+    bool secure = false;
 
-        atomic_set_bit(conn->flags, BT_CONN_USER);
-        atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING);
-        bt_auth->pincode_entry(conn, secure);
-    } else {
-        pin_code_neg_reply(&conn->br.dst);
+    if (conn->required_sec_level == BT_SECURITY_L3) {
+      secure = true;
     }
+
+    atomic_set_bit(conn->flags, BT_CONN_USER);
+    atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING);
+    bt_auth->pincode_entry(conn, secure);
+  } else {
+    pin_code_neg_reply(&conn->br.dst);
+  }
 }
 
-u8_t bt_conn_get_io_capa(void)
-{
-    if (!bt_auth) {
-        return BT_IO_NO_INPUT_OUTPUT;
-    }
+u8_t bt_conn_get_io_capa(void) {
+  if (!bt_auth) {
+    return BT_IO_NO_INPUT_OUTPUT;
+  }
 
-    if (bt_auth->passkey_confirm && bt_auth->passkey_display) {
-        return BT_IO_DISPLAY_YESNO;
-    }
+  if (bt_auth->passkey_confirm && bt_auth->passkey_display) {
+    return BT_IO_DISPLAY_YESNO;
+  }
 
-    if (bt_auth->passkey_entry) {
-        return BT_IO_KEYBOARD_ONLY;
-    }
+  if (bt_auth->passkey_entry) {
+    return BT_IO_KEYBOARD_ONLY;
+  }
 
-    if (bt_auth->passkey_display) {
-        return BT_IO_DISPLAY_ONLY;
-    }
+  if (bt_auth->passkey_display) {
+    return BT_IO_DISPLAY_ONLY;
+  }
 
-    return BT_IO_NO_INPUT_OUTPUT;
+  return BT_IO_NO_INPUT_OUTPUT;
 }
 
-static u8_t ssp_pair_method(const struct bt_conn *conn)
-{
-    return ssp_method[conn->br.remote_io_capa][bt_conn_get_io_capa()];
-}
+static u8_t ssp_pair_method(const struct bt_conn *conn) { return ssp_method[conn->br.remote_io_capa][bt_conn_get_io_capa()]; }
 
-u8_t bt_conn_ssp_get_auth(const struct bt_conn *conn)
-{
-    /* Validate no bond auth request, and if valid use it. */
-    if ((conn->br.remote_auth == BT_HCI_NO_BONDING) ||
-        ((conn->br.remote_auth == BT_HCI_NO_BONDING_MITM) &&
-         (ssp_pair_method(conn) > JUST_WORKS))) {
-        return conn->br.remote_auth;
-    }
+u8_t bt_conn_ssp_get_auth(const struct bt_conn *conn) {
+  /* Validate no bond auth request, and if valid use it. */
+  if ((conn->br.remote_auth == BT_HCI_NO_BONDING) || ((conn->br.remote_auth == BT_HCI_NO_BONDING_MITM) && (ssp_pair_method(conn) > JUST_WORKS))) {
+    return conn->br.remote_auth;
+  }
 
-    /* Local & remote have enough IO capabilities to get MITM protection. */
-    if (ssp_pair_method(conn) > JUST_WORKS) {
-        return conn->br.remote_auth | BT_MITM;
-    }
+  /* Local & remote have enough IO capabilities to get MITM protection. */
+  if (ssp_pair_method(conn) > JUST_WORKS) {
+    return conn->br.remote_auth | BT_MITM;
+  }
 
-    /* No MITM protection possible so ignore remote MITM requirement. */
-    return (conn->br.remote_auth & ~BT_MITM);
+  /* No MITM protection possible so ignore remote MITM requirement. */
+  return (conn->br.remote_auth & ~BT_MITM);
 }
 
-static int ssp_confirm_reply(struct bt_conn *conn)
-{
-    struct bt_hci_cp_user_confirm_reply *cp;
-    struct net_buf *buf;
+static int ssp_confirm_reply(struct bt_conn *conn) {
+  struct bt_hci_cp_user_confirm_reply *cp;
+  struct net_buf                      *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, &conn->br.dst);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, &conn->br.dst);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_REPLY, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_REPLY, buf, NULL);
 }
 
-static int ssp_confirm_neg_reply(struct bt_conn *conn)
-{
-    struct bt_hci_cp_user_confirm_reply *cp;
-    struct net_buf *buf;
+static int ssp_confirm_neg_reply(struct bt_conn *conn) {
+  struct bt_hci_cp_user_confirm_reply *cp;
+  struct net_buf                      *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, &conn->br.dst);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, &conn->br.dst);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, buf,
-                                NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, buf, NULL);
 }
 
-void bt_conn_ssp_auth_complete(struct bt_conn *conn, u8_t status)
-{
-    if (!status) {
-        bool bond = !atomic_test_bit(conn->flags, BT_CONN_BR_NOBOND);
+void bt_conn_ssp_auth_complete(struct bt_conn *conn, u8_t status) {
+  if (!status) {
+    bool bond = !atomic_test_bit(conn->flags, BT_CONN_BR_NOBOND);
 
-        if (bt_auth && bt_auth->pairing_complete) {
-            bt_auth->pairing_complete(conn, bond);
-        }
-    } else {
-        if (bt_auth && bt_auth->pairing_failed) {
-            bt_auth->pairing_failed(conn, status);
-        }
+    if (bt_auth && bt_auth->pairing_complete) {
+      bt_auth->pairing_complete(conn, bond);
     }
+  } else {
+    if (bt_auth && bt_auth->pairing_failed) {
+      bt_auth->pairing_failed(conn, status);
+    }
+  }
 }
 
-void bt_conn_ssp_auth(struct bt_conn *conn, u32_t passkey)
-{
-    conn->br.pairing_method = ssp_pair_method(conn);
+void bt_conn_ssp_auth(struct bt_conn *conn, u32_t passkey) {
+  conn->br.pairing_method = ssp_pair_method(conn);
 
+  /*
+   * If local required security is HIGH then MITM is mandatory.
+   * MITM protection is no achievable when SSP 'justworks' is applied.
+   */
+  if (conn->required_sec_level > BT_SECURITY_L2 && conn->br.pairing_method == JUST_WORKS) {
+    BT_DBG("MITM protection infeasible for required security");
+    ssp_confirm_neg_reply(conn);
+    return;
+  }
+
+  switch (conn->br.pairing_method) {
+  case PASSKEY_CONFIRM:
+    atomic_set_bit(conn->flags, BT_CONN_USER);
+    bt_auth->passkey_confirm(conn, passkey);
+    break;
+  case PASSKEY_DISPLAY:
+    atomic_set_bit(conn->flags, BT_CONN_USER);
+    bt_auth->passkey_display(conn, passkey);
+    break;
+  case PASSKEY_INPUT:
+    atomic_set_bit(conn->flags, BT_CONN_USER);
+    bt_auth->passkey_entry(conn);
+    break;
+  case JUST_WORKS:
     /*
-	 * If local required security is HIGH then MITM is mandatory.
-	 * MITM protection is no achievable when SSP 'justworks' is applied.
-	 */
-    if (conn->required_sec_level > BT_SECURITY_L2 &&
-        conn->br.pairing_method == JUST_WORKS) {
-        BT_DBG("MITM protection infeasible for required security");
-        ssp_confirm_neg_reply(conn);
-        return;
+     * When local host works as pairing acceptor and 'justworks'
+     * model is applied then notify user about such pairing request.
+     * [BT Core 4.2 table 5.7, Vol 3, Part C, 5.2.2.6]
+     */
+    if (bt_auth && bt_auth->pairing_confirm && !atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR)) {
+      atomic_set_bit(conn->flags, BT_CONN_USER);
+      bt_auth->pairing_confirm(conn);
+      break;
     }
+    ssp_confirm_reply(conn);
+    break;
+  default:
+    break;
+  }
+}
 
-    switch (conn->br.pairing_method) {
-        case PASSKEY_CONFIRM:
-            atomic_set_bit(conn->flags, BT_CONN_USER);
-            bt_auth->passkey_confirm(conn, passkey);
-            break;
-        case PASSKEY_DISPLAY:
-            atomic_set_bit(conn->flags, BT_CONN_USER);
-            bt_auth->passkey_display(conn, passkey);
-            break;
-        case PASSKEY_INPUT:
-            atomic_set_bit(conn->flags, BT_CONN_USER);
-            bt_auth->passkey_entry(conn);
-            break;
-        case JUST_WORKS:
-            /*
-		 * When local host works as pairing acceptor and 'justworks'
-		 * model is applied then notify user about such pairing request.
-		 * [BT Core 4.2 table 5.7, Vol 3, Part C, 5.2.2.6]
-		 */
-            if (bt_auth && bt_auth->pairing_confirm &&
-                !atomic_test_bit(conn->flags,
-                                 BT_CONN_BR_PAIRING_INITIATOR)) {
-                atomic_set_bit(conn->flags, BT_CONN_USER);
-                bt_auth->pairing_confirm(conn);
-                break;
-            }
-            ssp_confirm_reply(conn);
-            break;
-        default:
-            break;
-    }
-}
-
-static int ssp_passkey_reply(struct bt_conn *conn, unsigned int passkey)
-{
-    struct bt_hci_cp_user_passkey_reply *cp;
-    struct net_buf *buf;
+static int ssp_passkey_reply(struct bt_conn *conn, unsigned int passkey) {
+  struct bt_hci_cp_user_passkey_reply *cp;
+  struct net_buf                      *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, &conn->br.dst);
-    cp->passkey = sys_cpu_to_le32(passkey);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, &conn->br.dst);
+  cp->passkey = sys_cpu_to_le32(passkey);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_REPLY, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_REPLY, buf, NULL);
 }
 
-static int ssp_passkey_neg_reply(struct bt_conn *conn)
-{
-    struct bt_hci_cp_user_passkey_neg_reply *cp;
-    struct net_buf *buf;
+static int ssp_passkey_neg_reply(struct bt_conn *conn) {
+  struct bt_hci_cp_user_passkey_neg_reply *cp;
+  struct net_buf                          *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, &conn->br.dst);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, &conn->br.dst);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, buf,
-                                NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, buf, NULL);
 }
 
-static int bt_hci_connect_br_cancel(struct bt_conn *conn)
-{
-    struct bt_hci_cp_connect_cancel *cp;
-    struct bt_hci_rp_connect_cancel *rp;
-    struct net_buf *buf, *rsp;
-    int err;
+static int bt_hci_connect_br_cancel(struct bt_conn *conn) {
+  struct bt_hci_cp_connect_cancel *cp;
+  struct bt_hci_rp_connect_cancel *rp;
+  struct net_buf                  *buf, *rsp;
+  int                              err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT_CANCEL, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT_CANCEL, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    memcpy(&cp->bdaddr, &conn->br.dst, sizeof(cp->bdaddr));
+  cp = net_buf_add(buf, sizeof(*cp));
+  memcpy(&cp->bdaddr, &conn->br.dst, sizeof(cp->bdaddr));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT_CANCEL, buf, &rsp);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT_CANCEL, buf, &rsp);
+  if (err) {
+    return err;
+  }
 
-    rp = (void *)rsp->data;
+  rp = (void *)rsp->data;
 
-    err = rp->status ? -EIO : 0;
+  err = rp->status ? -EIO : 0;
 
-    net_buf_unref(rsp);
+  net_buf_unref(rsp);
 
-    return err;
+  return err;
 }
 
-static int conn_auth(struct bt_conn *conn)
-{
-    struct bt_hci_cp_auth_requested *auth;
-    struct net_buf *buf;
+static int conn_auth(struct bt_conn *conn) {
+  struct bt_hci_cp_auth_requested *auth;
+  struct net_buf                  *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_AUTH_REQUESTED, sizeof(*auth));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_AUTH_REQUESTED, sizeof(*auth));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    auth = net_buf_add(buf, sizeof(*auth));
-    auth->handle = sys_cpu_to_le16(conn->handle);
+  auth         = net_buf_add(buf, sizeof(*auth));
+  auth->handle = sys_cpu_to_le16(conn->handle);
 
-    atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR);
+  atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_AUTH_REQUESTED, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_AUTH_REQUESTED, buf, NULL);
 }
 #endif /* CONFIG_BT_BREDR */
 
 #if defined(CONFIG_BT_SMP)
-void bt_conn_identity_resolved(struct bt_conn *conn)
-{
-    const bt_addr_le_t *rpa;
-    struct bt_conn_cb *cb;
+void bt_conn_identity_resolved(struct bt_conn *conn) {
+  const bt_addr_le_t *rpa;
+  struct bt_conn_cb  *cb;
 
-    if (conn->role == BT_HCI_ROLE_MASTER) {
-        rpa = &conn->le.resp_addr;
-    } else {
-        rpa = &conn->le.init_addr;
-    }
+  if (conn->role == BT_HCI_ROLE_MASTER) {
+    rpa = &conn->le.resp_addr;
+  } else {
+    rpa = &conn->le.init_addr;
+  }
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (cb->identity_resolved) {
-            cb->identity_resolved(conn, rpa, &conn->le.dst);
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->identity_resolved) {
+      cb->identity_resolved(conn, rpa, &conn->le.dst);
     }
+  }
 }
 
-int bt_conn_le_start_encryption(struct bt_conn *conn, u8_t rand[8],
-                                u8_t ediv[2], const u8_t *ltk, size_t len)
-{
-    struct bt_hci_cp_le_start_encryption *cp;
-    struct net_buf *buf;
+int bt_conn_le_start_encryption(struct bt_conn *conn, u8_t rand[8], u8_t ediv[2], const u8_t *ltk, size_t len) {
+  struct bt_hci_cp_le_start_encryption *cp;
+  struct net_buf                       *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_START_ENCRYPTION, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_START_ENCRYPTION, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
-    memcpy(&cp->rand, rand, sizeof(cp->rand));
-    memcpy(&cp->ediv, ediv, sizeof(cp->ediv));
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(conn->handle);
+  memcpy(&cp->rand, rand, sizeof(cp->rand));
+  memcpy(&cp->ediv, ediv, sizeof(cp->ediv));
 
-    memcpy(cp->ltk, ltk, len);
-    if (len < sizeof(cp->ltk)) {
-        (void)memset(cp->ltk + len, 0, sizeof(cp->ltk) - len);
-    }
+  memcpy(cp->ltk, ltk, len);
+  if (len < sizeof(cp->ltk)) {
+    (void)memset(cp->ltk + len, 0, sizeof(cp->ltk) - len);
+  }
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_START_ENCRYPTION, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_START_ENCRYPTION, buf, NULL);
 }
 #endif /* CONFIG_BT_SMP */
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-u8_t bt_conn_enc_key_size(struct bt_conn *conn)
-{
-    //GATT/SR/GAR/BV-04-C
-    // if the connection instance is valid
-    if (!conn) {
-        return 0;
-    }
+u8_t bt_conn_enc_key_size(struct bt_conn *conn) {
+  // GATT/SR/GAR/BV-04-C
+  //  if the connection instance is valid
+  if (!conn) {
+    return 0;
+  }
 
-    if (!conn->encrypt) {
-        return 0;
-    }
+  if (!conn->encrypt) {
+    return 0;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        struct bt_hci_cp_read_encryption_key_size *cp;
-        struct bt_hci_rp_read_encryption_key_size *rp;
-        struct net_buf *buf;
-        struct net_buf *rsp;
-        u8_t key_size;
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    struct bt_hci_cp_read_encryption_key_size *cp;
+    struct bt_hci_rp_read_encryption_key_size *rp;
+    struct net_buf                            *buf;
+    struct net_buf                            *rsp;
+    u8_t                                       key_size;
 
-        buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
-                                sizeof(*cp));
-        if (!buf) {
-            return 0;
-        }
+    buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, sizeof(*cp));
+    if (!buf) {
+      return 0;
+    }
 
-        cp = net_buf_add(buf, sizeof(*cp));
-        cp->handle = sys_cpu_to_le16(conn->handle);
+    cp         = net_buf_add(buf, sizeof(*cp));
+    cp->handle = sys_cpu_to_le16(conn->handle);
 
-        if (bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
-                                 buf, &rsp)) {
-            return 0;
-        }
+    if (bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, buf, &rsp)) {
+      return 0;
+    }
 
-        rp = (void *)rsp->data;
+    rp = (void *)rsp->data;
 
-        key_size = rp->status ? 0 : rp->key_size;
+    key_size = rp->status ? 0 : rp->key_size;
 
-        net_buf_unref(rsp);
+    net_buf_unref(rsp);
 
-        return key_size;
-    }
+    return key_size;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        return conn->le.keys ? conn->le.keys->enc_size : 0;
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    return conn->le.keys ? conn->le.keys->enc_size : 0;
+  }
 
-    return 0;
+  return 0;
 }
 
-void bt_conn_security_changed(struct bt_conn *conn, enum bt_security_err err)
-{
-    struct bt_conn_cb *cb;
+void bt_conn_security_changed(struct bt_conn *conn, enum bt_security_err err) {
+  struct bt_conn_cb *cb;
 
-    for (cb = callback_list; cb; cb = cb->_next) {
-        if (cb->security_changed) {
-            cb->security_changed(conn, conn->sec_level, err);
-        }
+  for (cb = callback_list; cb; cb = cb->_next) {
+    if (cb->security_changed) {
+      cb->security_changed(conn, conn->sec_level, err);
     }
+  }
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-    if (!err && conn->sec_level >= BT_SECURITY_L2) {
-        bt_keys_update_usage(conn->id, bt_conn_get_dst(conn));
-    }
+  if (!err && conn->sec_level >= BT_SECURITY_L2) {
+    bt_keys_update_usage(conn->id, bt_conn_get_dst(conn));
+  }
 #endif
 }
 
-static int start_security(struct bt_conn *conn)
-{
+static int start_security(struct bt_conn *conn) {
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING)) {
-            return -EBUSY;
-        }
-
-        if (conn->required_sec_level > BT_SECURITY_L3) {
-            return -ENOTSUP;
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING)) {
+      return -EBUSY;
+    }
 
-        if (bt_conn_get_io_capa() == BT_IO_NO_INPUT_OUTPUT &&
-            conn->required_sec_level > BT_SECURITY_L2) {
-            return -EINVAL;
-        }
+    if (conn->required_sec_level > BT_SECURITY_L3) {
+      return -ENOTSUP;
+    }
 
-        return conn_auth(conn);
+    if (bt_conn_get_io_capa() == BT_IO_NO_INPUT_OUTPUT && conn->required_sec_level > BT_SECURITY_L2) {
+      return -EINVAL;
     }
+
+    return conn_auth(conn);
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        return bt_smp_start_security(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    return bt_smp_start_security(conn);
+  }
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-int bt_conn_set_security(struct bt_conn *conn, bt_security_t sec)
-{
-    int err;
+int bt_conn_set_security(struct bt_conn *conn, bt_security_t sec) {
+  int err;
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) &&
-        sec < BT_SECURITY_L4) {
-        return -EOPNOTSUPP;
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) && sec < BT_SECURITY_L4) {
+    return -EOPNOTSUPP;
+  }
 
-    /* nothing to do */
-    if (conn->sec_level >= sec || conn->required_sec_level >= sec) {
-        return 0;
-    }
+  /* nothing to do */
+  if (conn->sec_level >= sec || conn->required_sec_level >= sec) {
+    return 0;
+  }
 
-    atomic_set_bit_to(conn->flags, BT_CONN_FORCE_PAIR,
-                      sec & BT_SECURITY_FORCE_PAIR);
-    conn->required_sec_level = sec & ~BT_SECURITY_FORCE_PAIR;
+  atomic_set_bit_to(conn->flags, BT_CONN_FORCE_PAIR, sec & BT_SECURITY_FORCE_PAIR);
+  conn->required_sec_level = sec & ~BT_SECURITY_FORCE_PAIR;
 
-    err = start_security(conn);
+  err = start_security(conn);
 
-    /* reset required security level in case of error */
-    if (err) {
-        conn->required_sec_level = conn->sec_level;
-    }
+  /* reset required security level in case of error */
+  if (err) {
+    conn->required_sec_level = conn->sec_level;
+  }
 
-    return err;
+  return err;
 }
 
-bt_security_t bt_conn_get_security(struct bt_conn *conn)
-{
-    return conn->sec_level;
-}
+bt_security_t bt_conn_get_security(struct bt_conn *conn) { return conn->sec_level; }
 #else
-bt_security_t bt_conn_get_security(struct bt_conn *conn)
-{
-    return BT_SECURITY_L1;
-}
+bt_security_t bt_conn_get_security(struct bt_conn *conn) { return BT_SECURITY_L1; }
 #endif /* CONFIG_BT_SMP */
 
-void bt_conn_cb_register(struct bt_conn_cb *cb)
-{
-    cb->_next = callback_list;
-    callback_list = cb;
+void bt_conn_cb_register(struct bt_conn_cb *cb) {
+  cb->_next     = callback_list;
+  callback_list = cb;
 }
 
-void bt_conn_reset_rx_state(struct bt_conn *conn)
-{
-    if (!conn->rx_len) {
-        return;
-    }
+void bt_conn_reset_rx_state(struct bt_conn *conn) {
+  if (!conn->rx_len) {
+    return;
+  }
 
-    net_buf_unref(conn->rx);
-    conn->rx = NULL;
-    conn->rx_len = 0U;
+  net_buf_unref(conn->rx);
+  conn->rx     = NULL;
+  conn->rx_len = 0U;
 }
 
-void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, u8_t flags)
-{
-    struct bt_l2cap_hdr *hdr;
-    u16_t len;
-
-    /* Make sure we notify any pending TX callbacks before processing
-	 * new data for this connection.
-	 */
-    tx_notify(conn);
-
-    BT_DBG("handle %u len %u flags %02x", conn->handle, buf->len, flags);
-
-    /* Check packet boundary flags */
-    switch (flags) {
-        case BT_ACL_START:
-            hdr = (void *)buf->data;
-            len = sys_le16_to_cpu(hdr->len);
-
-            BT_DBG("First, len %u final %u", buf->len, len);
-
-            if (conn->rx_len) {
-                BT_ERR("Unexpected first L2CAP frame");
-                bt_conn_reset_rx_state(conn);
-            }
-
-            conn->rx_len = (sizeof(*hdr) + len) - buf->len;
-            BT_DBG("rx_len %u", conn->rx_len);
-            if (conn->rx_len) {
-                conn->rx = buf;
-                return;
-            }
-
-            break;
-        case BT_ACL_CONT:
-            if (!conn->rx_len) {
-                BT_ERR("Unexpected L2CAP continuation");
-                bt_conn_reset_rx_state(conn);
-                net_buf_unref(buf);
-                return;
-            }
-
-            if (buf->len > conn->rx_len) {
-                BT_ERR("L2CAP data overflow");
-                bt_conn_reset_rx_state(conn);
-                net_buf_unref(buf);
-                return;
-            }
-
-            BT_DBG("Cont, len %u rx_len %u", buf->len, conn->rx_len);
-
-            if (buf->len > net_buf_tailroom(conn->rx)) {
-                BT_ERR("Not enough buffer space for L2CAP data");
-                bt_conn_reset_rx_state(conn);
-                net_buf_unref(buf);
-                return;
-            }
-
-            net_buf_add_mem(conn->rx, buf->data, buf->len);
-            conn->rx_len -= buf->len;
-            net_buf_unref(buf);
-
-            if (conn->rx_len) {
-                return;
-            }
-
-            buf = conn->rx;
-            conn->rx = NULL;
-            conn->rx_len = 0U;
-
-            break;
-        default:
-            BT_ERR("Unexpected ACL flags (0x%02x)", flags);
-            bt_conn_reset_rx_state(conn);
-            net_buf_unref(buf);
-            return;
-    }
+void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, u8_t flags) {
+  struct bt_l2cap_hdr *hdr;
+  u16_t                len;
 
+  /* Make sure we notify any pending TX callbacks before processing
+   * new data for this connection.
+   */
+  tx_notify(conn);
+
+  BT_DBG("handle %u len %u flags %02x", conn->handle, buf->len, flags);
+
+  /* Check packet boundary flags */
+  switch (flags) {
+  case BT_ACL_START:
     hdr = (void *)buf->data;
     len = sys_le16_to_cpu(hdr->len);
 
-    if (sizeof(*hdr) + len != buf->len) {
-        BT_ERR("ACL len mismatch (%u != %u)", len, buf->len);
-        net_buf_unref(buf);
-        return;
+    BT_DBG("First, len %u final %u", buf->len, len);
+
+    if (conn->rx_len) {
+      BT_ERR("Unexpected first L2CAP frame");
+      bt_conn_reset_rx_state(conn);
+    }
+
+    conn->rx_len = (sizeof(*hdr) + len) - buf->len;
+    BT_DBG("rx_len %u", conn->rx_len);
+    if (conn->rx_len) {
+      conn->rx = buf;
+      return;
+    }
+
+    break;
+  case BT_ACL_CONT:
+    if (!conn->rx_len) {
+      BT_ERR("Unexpected L2CAP continuation");
+      bt_conn_reset_rx_state(conn);
+      net_buf_unref(buf);
+      return;
+    }
+
+    if (buf->len > conn->rx_len) {
+      BT_ERR("L2CAP data overflow");
+      bt_conn_reset_rx_state(conn);
+      net_buf_unref(buf);
+      return;
+    }
+
+    BT_DBG("Cont, len %u rx_len %u", buf->len, conn->rx_len);
+
+    if (buf->len > net_buf_tailroom(conn->rx)) {
+      BT_ERR("Not enough buffer space for L2CAP data");
+      bt_conn_reset_rx_state(conn);
+      net_buf_unref(buf);
+      return;
     }
 
-    BT_DBG("Successfully parsed %u byte L2CAP packet", buf->len);
+    net_buf_add_mem(conn->rx, buf->data, buf->len);
+    conn->rx_len -= buf->len;
+    net_buf_unref(buf);
+
+    if (conn->rx_len) {
+      return;
+    }
+
+    buf          = conn->rx;
+    conn->rx     = NULL;
+    conn->rx_len = 0U;
+
+    break;
+  default:
+    BT_ERR("Unexpected ACL flags (0x%02x)", flags);
+    bt_conn_reset_rx_state(conn);
+    net_buf_unref(buf);
+    return;
+  }
 
-    bt_l2cap_recv(conn, buf);
+  hdr = (void *)buf->data;
+  len = sys_le16_to_cpu(hdr->len);
+
+  if (sizeof(*hdr) + len != buf->len) {
+    BT_ERR("ACL len mismatch (%u != %u)", len, buf->len);
+    net_buf_unref(buf);
+    return;
+  }
+
+  BT_DBG("Successfully parsed %u byte L2CAP packet", buf->len);
+
+  bt_l2cap_recv(conn, buf);
 }
 
-static struct bt_conn_tx *conn_tx_alloc(void)
-{
-    /* The TX context always get freed in the system workqueue,
-	 * so if we're in the same workqueue but there are no immediate
-	 * contexts available, there's no chance we'll get one by waiting.
-	 */
+static struct bt_conn_tx *conn_tx_alloc(void) {
+  /* The TX context always get freed in the system workqueue,
+   * so if we're in the same workqueue but there are no immediate
+   * contexts available, there's no chance we'll get one by waiting.
+   */
 #if !defined(BFLB_BLE)
-    if (k_current_get() == &k_sys_work_q.thread) {
-        return k_fifo_get(&free_tx, K_NO_WAIT);
-    }
+  if (k_current_get() == &k_sys_work_q.thread) {
+    return k_fifo_get(&free_tx, K_NO_WAIT);
+  }
 #endif
-    if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) {
-        struct bt_conn_tx *tx = k_fifo_get(&free_tx, K_NO_WAIT);
-
-        if (tx) {
-            return tx;
-        }
+  if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) {
+    struct bt_conn_tx *tx = k_fifo_get(&free_tx, K_NO_WAIT);
 
-        BT_WARN("Unable to get an immediate free conn_tx");
+    if (tx) {
+      return tx;
     }
 
-    return k_fifo_get(&free_tx, K_FOREVER);
+    BT_WARN("Unable to get an immediate free conn_tx");
+  }
+
+  return k_fifo_get(&free_tx, K_FOREVER);
 }
 
-int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf,
-                    bt_conn_tx_cb_t cb, void *user_data)
-{
-    struct bt_conn_tx *tx;
+int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) {
+  struct bt_conn_tx *tx;
+
+  BT_DBG("conn handle %u buf len %u cb %p user_data %p", conn->handle, buf->len, cb, user_data);
 
-    BT_DBG("conn handle %u buf len %u cb %p user_data %p", conn->handle,
-           buf->len, cb, user_data);
+  if (conn->state != BT_CONN_CONNECTED) {
+    BT_ERR("not connected!");
+    net_buf_unref(buf);
+    return -ENOTCONN;
+  }
 
+  if (cb) {
+    tx = conn_tx_alloc();
+    if (!tx) {
+      BT_ERR("Unable to allocate TX context");
+      net_buf_unref(buf);
+      return -ENOBUFS;
+    }
+
+    /* Verify that we're still connected after blocking */
     if (conn->state != BT_CONN_CONNECTED) {
-        BT_ERR("not connected!");
-        net_buf_unref(buf);
-        return -ENOTCONN;
-    }
-
-    if (cb) {
-        tx = conn_tx_alloc();
-        if (!tx) {
-            BT_ERR("Unable to allocate TX context");
-            net_buf_unref(buf);
-            return -ENOBUFS;
-        }
-
-        /* Verify that we're still connected after blocking */
-        if (conn->state != BT_CONN_CONNECTED) {
-            BT_WARN("Disconnected while allocating context");
-            net_buf_unref(buf);
-            tx_free(tx);
-            return -ENOTCONN;
-        }
-
-        tx->cb = cb;
-        tx->user_data = user_data;
-        tx->pending_no_cb = 0U;
-
-        tx_data(buf)->tx = tx;
-    } else {
-        tx_data(buf)->tx = NULL;
+      BT_WARN("Disconnected while allocating context");
+      net_buf_unref(buf);
+      tx_free(tx);
+      return -ENOTCONN;
     }
 
+    tx->cb            = cb;
+    tx->user_data     = user_data;
+    tx->pending_no_cb = 0U;
+
+    tx_data(buf)->tx = tx;
+  } else {
+    tx_data(buf)->tx = NULL;
+  }
+
+#if (BFLB_BT_CO_THREAD)
+  if (k_is_current_thread(bt_get_co_thread()))
+    bt_conn_process_tx(conn, buf);
+  else
     net_buf_put(&conn->tx_queue, buf);
 #if defined(BFLB_BLE)
-    k_sem_give(&g_poll_sem);
+  k_sem_give(&g_poll_sem);
 #endif
-    return 0;
+#else // BFLB_BT_CO_THREAD
+
+  net_buf_put(&conn->tx_queue, buf);
+#if defined(BFLB_BLE)
+  k_sem_give(&g_poll_sem);
+#endif
+#endif // BFLB_BT_CO_THREAD
+  return 0;
 }
 
-static bool send_frag(struct bt_conn *conn, struct net_buf *buf, u8_t flags,
-                      bool always_consume)
-{
-    struct bt_conn_tx *tx = tx_data(buf)->tx;
-    struct bt_hci_acl_hdr *hdr;
-    u32_t *pending_no_cb;
-    unsigned int key;
-    int err;
+static bool send_frag(struct bt_conn *conn, struct net_buf *buf, u8_t flags, bool always_consume) {
+  struct bt_conn_tx     *tx = tx_data(buf)->tx;
+  struct bt_hci_acl_hdr *hdr;
+  u32_t                 *pending_no_cb;
+  unsigned int           key;
+  int                    err;
 
-    BT_DBG("conn %p buf %p len %u flags 0x%02x", conn, buf, buf->len,
-           flags);
+  BT_DBG("conn %p buf %p len %u flags 0x%02x", conn, buf, buf->len, flags);
 
-    /* Wait until the controller can accept ACL packets */
-    k_sem_take(bt_conn_get_pkts(conn), K_FOREVER);
+  /* Wait until the controller can accept ACL packets */
+  k_sem_take(bt_conn_get_pkts(conn), K_FOREVER);
 
-    /* Check for disconnection while waiting for pkts_sem */
-    if (conn->state != BT_CONN_CONNECTED) {
-        goto fail;
+  /* Check for disconnection while waiting for pkts_sem */
+  if (conn->state != BT_CONN_CONNECTED) {
+    goto fail;
+  }
+
+  hdr         = net_buf_push(buf, sizeof(*hdr));
+  hdr->handle = sys_cpu_to_le16(bt_acl_handle_pack(conn->handle, flags));
+  hdr->len    = sys_cpu_to_le16(buf->len - sizeof(*hdr));
+
+  /* Add to pending, it must be done before bt_buf_set_type */
+  key = irq_lock();
+  if (tx) {
+    sys_slist_append(&conn->tx_pending, &tx->node);
+  } else {
+    struct bt_conn_tx *tail_tx;
+
+    tail_tx = (void *)sys_slist_peek_tail(&conn->tx_pending);
+    if (tail_tx) {
+      pending_no_cb = &tail_tx->pending_no_cb;
+    } else {
+      pending_no_cb = &conn->pending_no_cb;
     }
 
-    hdr = net_buf_push(buf, sizeof(*hdr));
-    hdr->handle = sys_cpu_to_le16(bt_acl_handle_pack(conn->handle, flags));
-    hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr));
+    (*pending_no_cb)++;
+  }
+  irq_unlock(key);
 
-    /* Add to pending, it must be done before bt_buf_set_type */
+  bt_buf_set_type(buf, BT_BUF_ACL_OUT);
+
+  err = bt_send(buf);
+  if (err) {
+    BT_ERR("Unable to send to driver (err %d)", err);
     key = irq_lock();
+    /* Roll back the pending TX info */
     if (tx) {
-        sys_slist_append(&conn->tx_pending, &tx->node);
+      sys_slist_find_and_remove(&conn->tx_pending, &tx->node);
     } else {
-        struct bt_conn_tx *tail_tx;
-
-        tail_tx = (void *)sys_slist_peek_tail(&conn->tx_pending);
-        if (tail_tx) {
-            pending_no_cb = &tail_tx->pending_no_cb;
-        } else {
-            pending_no_cb = &conn->pending_no_cb;
-        }
-
-        (*pending_no_cb)++;
+      __ASSERT_NO_MSG(*pending_no_cb > 0);
+      (*pending_no_cb)--;
     }
     irq_unlock(key);
+    goto fail;
+  }
 
-    bt_buf_set_type(buf, BT_BUF_ACL_OUT);
-
-    err = bt_send(buf);
-    if (err) {
-        BT_ERR("Unable to send to driver (err %d)", err);
-        key = irq_lock();
-        /* Roll back the pending TX info */
-        if (tx) {
-            sys_slist_find_and_remove(&conn->tx_pending, &tx->node);
-        } else {
-            __ASSERT_NO_MSG(*pending_no_cb > 0);
-            (*pending_no_cb)--;
-        }
-        irq_unlock(key);
-        goto fail;
-    }
-
-    return true;
+  return true;
 
 fail:
-    k_sem_give(bt_conn_get_pkts(conn));
-    if (tx) {
-        tx_free(tx);
-    }
+  k_sem_give(bt_conn_get_pkts(conn));
+  if (tx) {
+    tx_free(tx);
+  }
 
-    if (always_consume) {
-        net_buf_unref(buf);
-    }
-    return false;
+  if (always_consume) {
+    net_buf_unref(buf);
+  }
+  return false;
 }
 
-static inline u16_t conn_mtu(struct bt_conn *conn)
-{
+static inline u16_t conn_mtu(struct bt_conn *conn) {
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) {
-        return bt_dev.br.mtu;
-    }
+  if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) {
+    return bt_dev.br.mtu;
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    return bt_dev.le.mtu;
+  return bt_dev.le.mtu;
 }
 
-static struct net_buf *create_frag(struct bt_conn *conn, struct net_buf *buf)
-{
-    struct net_buf *frag;
-    u16_t frag_len;
+static struct net_buf *create_frag(struct bt_conn *conn, struct net_buf *buf) {
+  struct net_buf *frag;
+  u16_t           frag_len;
 
 #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
-    frag = bt_conn_create_pdu(&frag_pool, 0);
+  frag = bt_conn_create_pdu(&frag_pool, 0);
 #else
-    frag = bt_conn_create_pdu(NULL, 0);
+  frag = bt_conn_create_pdu(NULL, 0);
 #endif
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        net_buf_unref(frag);
-        return NULL;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    net_buf_unref(frag);
+    return NULL;
+  }
 
-    /* Fragments never have a TX completion callback */
-    tx_data(frag)->tx = NULL;
+  /* Fragments never have a TX completion callback */
+  tx_data(frag)->tx = NULL;
 
-    frag_len = MIN(conn_mtu(conn), net_buf_tailroom(frag));
+  frag_len = MIN(conn_mtu(conn), net_buf_tailroom(frag));
 
-    net_buf_add_mem(frag, buf->data, frag_len);
-    net_buf_pull(buf, frag_len);
+  net_buf_add_mem(frag, buf->data, frag_len);
+  net_buf_pull(buf, frag_len);
 
-    return frag;
+  return frag;
 }
 
-static bool send_buf(struct bt_conn *conn, struct net_buf *buf)
-{
-    struct net_buf *frag;
+static bool send_buf(struct bt_conn *conn, struct net_buf *buf) {
+  struct net_buf *frag;
 
-    BT_DBG("conn %p buf %p len %u", conn, buf, buf->len);
+  BT_DBG("conn %p buf %p len %u", conn, buf, buf->len);
 
-    /* Send directly if the packet fits the ACL MTU */
-    if (buf->len <= conn_mtu(conn)) {
-        return send_frag(conn, buf, BT_ACL_START_NO_FLUSH, false);
-    }
+  /* Send directly if the packet fits the ACL MTU */
+  if (buf->len <= conn_mtu(conn)) {
+    return send_frag(conn, buf, BT_ACL_START_NO_FLUSH, false);
+  }
+
+  /* Create & enqueue first fragment */
+  frag = create_frag(conn, buf);
+  if (!frag) {
+    return false;
+  }
 
-    /* Create & enqueue first fragment */
+  if (!send_frag(conn, frag, BT_ACL_START_NO_FLUSH, true)) {
+    return false;
+  }
+
+  /*
+   * Send the fragments. For the last one simply use the original
+   * buffer (which works since we've used net_buf_pull on it.
+   */
+  while (buf->len > conn_mtu(conn)) {
     frag = create_frag(conn, buf);
     if (!frag) {
-        return false;
+      return false;
     }
 
-    if (!send_frag(conn, frag, BT_ACL_START_NO_FLUSH, true)) {
-        return false;
+    if (!send_frag(conn, frag, BT_ACL_CONT, true)) {
+      return false;
     }
+  }
 
-    /*
-	 * Send the fragments. For the last one simply use the original
-	 * buffer (which works since we've used net_buf_pull on it.
-	 */
-    while (buf->len > conn_mtu(conn)) {
-        frag = create_frag(conn, buf);
-        if (!frag) {
-            return false;
-        }
-
-        if (!send_frag(conn, frag, BT_ACL_CONT, true)) {
-            return false;
-        }
-    }
-
-    return send_frag(conn, buf, BT_ACL_CONT, false);
+  return send_frag(conn, buf, BT_ACL_CONT, false);
 }
 
-static struct k_poll_signal conn_change =
-    K_POLL_SIGNAL_INITIALIZER(conn_change);
-
-static void conn_cleanup(struct bt_conn *conn)
-{
-    struct net_buf *buf;
+static struct k_poll_signal conn_change = K_POLL_SIGNAL_INITIALIZER(conn_change);
 
-    /* Give back any allocated buffers */
-    while ((buf = net_buf_get(&conn->tx_queue, K_NO_WAIT))) {
-        if (tx_data(buf)->tx) {
-            tx_free(tx_data(buf)->tx);
-        }
+static void conn_cleanup(struct bt_conn *conn) {
+  struct net_buf *buf;
 
-        net_buf_unref(buf);
+  /* Give back any allocated buffers */
+  while ((buf = net_buf_get(&conn->tx_queue, K_NO_WAIT))) {
+    if (tx_data(buf)->tx) {
+      tx_free(tx_data(buf)->tx);
     }
 
-    __ASSERT(sys_slist_is_empty(&conn->tx_pending), "Pending TX packets");
-    __ASSERT_NO_MSG(conn->pending_no_cb == 0);
+    net_buf_unref(buf);
+  }
 
-    bt_conn_reset_rx_state(conn);
+  __ASSERT(sys_slist_is_empty(&conn->tx_pending), "Pending TX packets");
+  __ASSERT_NO_MSG(conn->pending_no_cb == 0);
+
+  bt_conn_reset_rx_state(conn);
 
-    k_delayed_work_submit(&conn->update_work, K_NO_WAIT);
+  k_delayed_work_submit(&conn->update_work, K_NO_WAIT);
 
 #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS
-    k_queue_free(&conn->tx_queue._queue);
-    // k_queue_free(&conn->tx_notify._queue);
-    conn->tx_queue._queue.hdl = NULL;
-    //conn->tx_notify._queue.hdl = NULL;
-    if (conn->update_work.timer.timer.hdl)
-        k_delayed_work_del_timer(&conn->update_work);
+  k_queue_free(&conn->tx_queue._queue);
+  // k_queue_free(&conn->tx_notify._queue);
+  conn->tx_queue._queue.hdl = NULL;
+  // conn->tx_notify._queue.hdl = NULL;
+  if (conn->update_work.timer.timer.hdl)
+    k_delayed_work_del_timer(&conn->update_work);
 #endif
 }
 
-int bt_conn_prepare_events(struct k_poll_event events[])
-{
-    int i, ev_count = 0;
+int bt_conn_prepare_events(struct k_poll_event events[]) {
+  int i, ev_count = 0;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    conn_change.signaled = 0U;
-    k_poll_event_init(&events[ev_count++], K_POLL_TYPE_SIGNAL,
-                      K_POLL_MODE_NOTIFY_ONLY, &conn_change);
+  conn_change.signaled = 0U;
+  k_poll_event_init(&events[ev_count++], K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &conn_change);
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        struct bt_conn *conn = &conns[i];
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    struct bt_conn *conn = &conns[i];
 
-        if (!atomic_get(&conn->ref)) {
-            continue;
-        }
+    if (!atomic_get(&conn->ref)) {
+      continue;
+    }
 
-        if (conn->state == BT_CONN_DISCONNECTED &&
-            atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) {
-            conn_cleanup(conn);
-            continue;
-        }
+    if (conn->state == BT_CONN_DISCONNECTED && atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) {
+      conn_cleanup(conn);
+      continue;
+    }
 
-        if (conn->state != BT_CONN_CONNECTED) {
-            continue;
-        }
+    if (conn->state != BT_CONN_CONNECTED) {
+      continue;
+    }
 
-        BT_DBG("Adding conn %p to poll list", conn);
+    BT_DBG("Adding conn %p to poll list", conn);
 
-        k_poll_event_init(&events[ev_count],
-                          K_POLL_TYPE_FIFO_DATA_AVAILABLE,
-                          K_POLL_MODE_NOTIFY_ONLY,
-                          &conn->tx_queue);
-        events[ev_count++].tag = BT_EVENT_CONN_TX_QUEUE;
-    }
+    k_poll_event_init(&events[ev_count], K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &conn->tx_queue);
+    events[ev_count++].tag = BT_EVENT_CONN_TX_QUEUE;
+  }
 
-    return ev_count;
+  return ev_count;
 }
 
+#if (BFLB_BT_CO_THREAD)
+void bt_conn_process_tx(struct bt_conn *conn, struct net_buf *tx_buf)
+#else
 void bt_conn_process_tx(struct bt_conn *conn)
+#endif
 {
-    struct net_buf *buf;
+  struct net_buf *buf;
 
-    BT_DBG("conn %p", conn);
+  BT_DBG("conn %p", conn);
 
-    if (conn->state == BT_CONN_DISCONNECTED &&
-        atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) {
-        BT_DBG("handle %u disconnected - cleaning up", conn->handle);
-        conn_cleanup(conn);
-        return;
-    }
-
-    /* Get next ACL packet for connection */
+  if (conn->state == BT_CONN_DISCONNECTED && atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) {
+    BT_DBG("handle %u disconnected - cleaning up", conn->handle);
+    conn_cleanup(conn);
+    return;
+  }
+#if (BFLB_BT_CO_THREAD)
+  if (tx_buf)
+    buf = tx_buf;
+  else
     buf = net_buf_get(&conn->tx_queue, K_NO_WAIT);
-    BT_ASSERT(buf);
-    if (!send_buf(conn, buf)) {
-        net_buf_unref(buf);
-    }
+#else
+  /* Get next ACL packet for connection */
+  buf = net_buf_get(&conn->tx_queue, K_NO_WAIT);
+#endif
+  BT_ASSERT(buf);
+  if (!send_buf(conn, buf)) {
+    net_buf_unref(buf);
+  }
 }
 
-struct bt_conn *bt_conn_add_le(u8_t id, const bt_addr_le_t *peer)
-{
-    struct bt_conn *conn = conn_new();
+struct bt_conn *bt_conn_add_le(u8_t id, const bt_addr_le_t *peer) {
+  struct bt_conn *conn = conn_new();
 
-    if (!conn) {
-        return NULL;
-    }
+  if (!conn) {
+    return NULL;
+  }
 
-    conn->id = id;
-    bt_addr_le_copy(&conn->le.dst, peer);
+  conn->id = id;
+  bt_addr_le_copy(&conn->le.dst, peer);
 #if defined(CONFIG_BT_SMP)
-    conn->sec_level = BT_SECURITY_L1;
-    conn->required_sec_level = BT_SECURITY_L1;
+  conn->sec_level          = BT_SECURITY_L1;
+  conn->required_sec_level = BT_SECURITY_L1;
 #endif /* CONFIG_BT_SMP */
-    conn->type = BT_CONN_TYPE_LE;
-    conn->le.interval_min = BT_GAP_INIT_CONN_INT_MIN;
-    conn->le.interval_max = BT_GAP_INIT_CONN_INT_MAX;
+  conn->type            = BT_CONN_TYPE_LE;
+  conn->le.interval_min = BT_GAP_INIT_CONN_INT_MIN;
+  conn->le.interval_max = BT_GAP_INIT_CONN_INT_MAX;
 
-    return conn;
+  return conn;
 }
 
-static void process_unack_tx(struct bt_conn *conn)
-{
-    /* Return any unacknowledged packets */
-    while (1) {
-        struct bt_conn_tx *tx;
-        sys_snode_t *node;
-        unsigned int key;
+static void process_unack_tx(struct bt_conn *conn) {
+  /* Return any unacknowledged packets */
+  while (1) {
+    struct bt_conn_tx *tx;
+    sys_snode_t       *node;
+    unsigned int       key;
 
-        key = irq_lock();
+    key = irq_lock();
 
-        if (conn->pending_no_cb) {
-            conn->pending_no_cb--;
-            irq_unlock(key);
-            k_sem_give(bt_conn_get_pkts(conn));
-            continue;
-        }
+    if (conn->pending_no_cb) {
+      conn->pending_no_cb--;
+      irq_unlock(key);
+      k_sem_give(bt_conn_get_pkts(conn));
+      continue;
+    }
 
-        node = sys_slist_get(&conn->tx_pending);
-        irq_unlock(key);
+    node = sys_slist_get(&conn->tx_pending);
+    irq_unlock(key);
 
-        if (!node) {
-            break;
-        }
+    if (!node) {
+      break;
+    }
 
-        tx = CONTAINER_OF(node, struct bt_conn_tx, node);
+    tx = CONTAINER_OF(node, struct bt_conn_tx, node);
 
-        key = irq_lock();
-        conn->pending_no_cb = tx->pending_no_cb;
-        tx->pending_no_cb = 0U;
-        irq_unlock(key);
+    key                 = irq_lock();
+    conn->pending_no_cb = tx->pending_no_cb;
+    tx->pending_no_cb   = 0U;
+    irq_unlock(key);
 
-        tx_free(tx);
+    tx_free(tx);
 
-        k_sem_give(bt_conn_get_pkts(conn));
+    k_sem_give(bt_conn_get_pkts(conn));
+  }
+}
+
+void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state) {
+  bt_conn_state_t old_state;
+
+  BT_DBG("%s -> %s", state2str(conn->state), state2str(state));
+
+  if (conn->state == state) {
+    BT_WARN("no transition");
+    return;
+  }
+
+  old_state   = conn->state;
+  conn->state = state;
+
+  /* Actions needed for exiting the old state */
+  switch (old_state) {
+  case BT_CONN_DISCONNECTED:
+    /* Take a reference for the first state transition after
+     * bt_conn_add_le() and keep it until reaching DISCONNECTED
+     * again.
+     */
+    bt_conn_ref(conn);
+    break;
+  case BT_CONN_CONNECT:
+    if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->type == BT_CONN_TYPE_LE) {
+      k_delayed_work_cancel(&conn->update_work);
+    }
+    break;
+  default:
+    break;
+  }
+
+  /* Actions needed for entering the new state */
+  switch (conn->state) {
+  case BT_CONN_CONNECTED:
+    if (conn->type == BT_CONN_TYPE_SCO) {
+      /* TODO: Notify sco connected */
+      break;
+    }
+    k_fifo_init(&conn->tx_queue, 20);
+    k_poll_signal_raise(&conn_change, 0);
+
+    sys_slist_init(&conn->channels);
+
+    bt_l2cap_connected(conn);
+    notify_connected(conn);
+    break;
+  case BT_CONN_DISCONNECTED:
+    if (conn->type == BT_CONN_TYPE_SCO) {
+      /* TODO: Notify sco disconnected */
+      bt_conn_unref(conn);
+      break;
+    }
+    /* Notify disconnection and queue a dummy buffer to wake
+     * up and stop the tx thread for states where it was
+     * running.
+     */
+    if (old_state == BT_CONN_CONNECTED || old_state == BT_CONN_DISCONNECT) {
+      process_unack_tx(conn);
+      tx_notify(conn);
+
+      /* Cancel Connection Update if it is pending */
+      if (conn->type == BT_CONN_TYPE_LE) {
+        k_delayed_work_cancel(&conn->update_work);
+      }
+
+      atomic_set_bit(conn->flags, BT_CONN_CLEANUP);
+      k_poll_signal_raise(&conn_change, 0);
+      /* The last ref will be dropped during cleanup */
+    } else if (old_state == BT_CONN_CONNECT) {
+      /* conn->err will be set in this case */
+      notify_connected(conn);
+      bt_conn_unref(conn);
+    } else if (old_state == BT_CONN_CONNECT_SCAN) {
+      /* this indicate LE Create Connection failed */
+      if (conn->err) {
+        notify_connected(conn);
+      }
+
+      bt_conn_unref(conn);
+    } else if (old_state == BT_CONN_CONNECT_DIR_ADV) {
+      /* this indicate Directed advertising stopped */
+      if (conn->err) {
+        notify_connected(conn);
+      }
+
+      bt_conn_unref(conn);
+    }
+
+    break;
+  case BT_CONN_CONNECT_SCAN:
+    break;
+  case BT_CONN_CONNECT_DIR_ADV:
+    break;
+  case BT_CONN_CONNECT:
+    if (conn->type == BT_CONN_TYPE_SCO) {
+      break;
+    }
+    /*
+     * Timer is needed only for LE. For other link types controller
+     * will handle connection timeout.
+     */
+    if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->type == BT_CONN_TYPE_LE) {
+      k_delayed_work_submit(&conn->update_work, CONN_TIMEOUT);
     }
+
+    break;
+  case BT_CONN_DISCONNECT:
+    break;
+  default:
+    BT_WARN("no valid (%u) state was set", state);
+
+    break;
+  }
 }
 
-void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state)
-{
-    bt_conn_state_t old_state;
-
-    BT_DBG("%s -> %s", state2str(conn->state), state2str(state));
-
-    if (conn->state == state) {
-        BT_WARN("no transition");
-        return;
-    }
-
-    old_state = conn->state;
-    conn->state = state;
-
-    /* Actions needed for exiting the old state */
-    switch (old_state) {
-        case BT_CONN_DISCONNECTED:
-            /* Take a reference for the first state transition after
-		 * bt_conn_add_le() and keep it until reaching DISCONNECTED
-		 * again.
-		 */
-            bt_conn_ref(conn);
-            break;
-        case BT_CONN_CONNECT:
-            if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-                conn->type == BT_CONN_TYPE_LE) {
-                k_delayed_work_cancel(&conn->update_work);
-            }
-            break;
-        default:
-            break;
-    }
-
-    /* Actions needed for entering the new state */
-    switch (conn->state) {
-        case BT_CONN_CONNECTED:
-            if (conn->type == BT_CONN_TYPE_SCO) {
-                /* TODO: Notify sco connected */
-                break;
-            }
-            k_fifo_init(&conn->tx_queue, 20);
-            k_poll_signal_raise(&conn_change, 0);
-
-            sys_slist_init(&conn->channels);
-
-            bt_l2cap_connected(conn);
-            notify_connected(conn);
-            break;
-        case BT_CONN_DISCONNECTED:
-            if (conn->type == BT_CONN_TYPE_SCO) {
-                /* TODO: Notify sco disconnected */
-                bt_conn_unref(conn);
-                break;
-            }
-            /* Notify disconnection and queue a dummy buffer to wake
-		 * up and stop the tx thread for states where it was
-		 * running.
-		 */
-            if (old_state == BT_CONN_CONNECTED ||
-                old_state == BT_CONN_DISCONNECT) {
-                process_unack_tx(conn);
-                tx_notify(conn);
-
-                /* Cancel Connection Update if it is pending */
-                if (conn->type == BT_CONN_TYPE_LE) {
-                    k_delayed_work_cancel(&conn->update_work);
-                }
-
-                atomic_set_bit(conn->flags, BT_CONN_CLEANUP);
-                k_poll_signal_raise(&conn_change, 0);
-                /* The last ref will be dropped during cleanup */
-            } else if (old_state == BT_CONN_CONNECT) {
-                /* conn->err will be set in this case */
-                notify_connected(conn);
-                bt_conn_unref(conn);
-            } else if (old_state == BT_CONN_CONNECT_SCAN) {
-                /* this indicate LE Create Connection failed */
-                if (conn->err) {
-                    notify_connected(conn);
-                }
-
-                bt_conn_unref(conn);
-            } else if (old_state == BT_CONN_CONNECT_DIR_ADV) {
-                /* this indicate Directed advertising stopped */
-                if (conn->err) {
-                    notify_connected(conn);
-                }
-
-                bt_conn_unref(conn);
-            }
-
-            break;
-        case BT_CONN_CONNECT_SCAN:
-            break;
-        case BT_CONN_CONNECT_DIR_ADV:
-            break;
-        case BT_CONN_CONNECT:
-            if (conn->type == BT_CONN_TYPE_SCO) {
-                break;
-            }
-            /*
-		 * Timer is needed only for LE. For other link types controller
-		 * will handle connection timeout.
-		 */
-            if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-                conn->type == BT_CONN_TYPE_LE) {
-                k_delayed_work_submit(&conn->update_work, CONN_TIMEOUT);
-            }
-
-            break;
-        case BT_CONN_DISCONNECT:
-            break;
-        default:
-            BT_WARN("no valid (%u) state was set", state);
-
-            break;
-    }
-}
-
-struct bt_conn *bt_conn_lookup_handle(u16_t handle)
-{
-    int i;
+struct bt_conn *bt_conn_lookup_handle(u16_t handle) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
+    }
 
-        /* We only care about connections with a valid handle */
-        if (conns[i].state != BT_CONN_CONNECTED &&
-            conns[i].state != BT_CONN_DISCONNECT) {
-            continue;
-        }
+    /* We only care about connections with a valid handle */
+    if (conns[i].state != BT_CONN_CONNECTED && conns[i].state != BT_CONN_DISCONNECT) {
+      continue;
+    }
 
-        if (conns[i].handle == handle) {
-            return bt_conn_ref(&conns[i]);
-        }
+    if (conns[i].handle == handle) {
+      return bt_conn_ref(&conns[i]);
     }
+  }
 
 #if defined(CONFIG_BT_BREDR)
-    for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
-        if (!atomic_get(&sco_conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
+    if (!atomic_get(&sco_conns[i].ref)) {
+      continue;
+    }
 
-        /* We only care about connections with a valid handle */
-        if (sco_conns[i].state != BT_CONN_CONNECTED &&
-            sco_conns[i].state != BT_CONN_DISCONNECT) {
-            continue;
-        }
+    /* We only care about connections with a valid handle */
+    if (sco_conns[i].state != BT_CONN_CONNECTED && sco_conns[i].state != BT_CONN_DISCONNECT) {
+      continue;
+    }
 
-        if (sco_conns[i].handle == handle) {
-            return bt_conn_ref(&sco_conns[i]);
-        }
+    if (sco_conns[i].handle == handle) {
+      return bt_conn_ref(&sco_conns[i]);
     }
+  }
 #endif
 
-    return NULL;
+  return NULL;
 }
 
-int bt_conn_addr_le_cmp(const struct bt_conn *conn, const bt_addr_le_t *peer)
-{
-    /* Check against conn dst address as it may be the identity address */
-    if (!bt_addr_le_cmp(peer, &conn->le.dst)) {
-        return 0;
-    }
+int bt_conn_addr_le_cmp(const struct bt_conn *conn, const bt_addr_le_t *peer) {
+  /* Check against conn dst address as it may be the identity address */
+  if (!bt_addr_le_cmp(peer, &conn->le.dst)) {
+    return 0;
+  }
 
-    /* Check against initial connection address */
-    if (conn->role == BT_HCI_ROLE_MASTER) {
-        return bt_addr_le_cmp(peer, &conn->le.resp_addr);
-    }
+  /* Check against initial connection address */
+  if (conn->role == BT_HCI_ROLE_MASTER) {
+    return bt_addr_le_cmp(peer, &conn->le.resp_addr);
+  }
 
-    return bt_addr_le_cmp(peer, &conn->le.init_addr);
+  return bt_addr_le_cmp(peer, &conn->le.init_addr);
 }
 
-struct bt_conn *bt_conn_lookup_addr_le(u8_t id, const bt_addr_le_t *peer)
-{
-    int i;
+struct bt_conn *bt_conn_lookup_addr_le(u8_t id, const bt_addr_le_t *peer) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
+    }
 
-        if (conns[i].type != BT_CONN_TYPE_LE) {
-            continue;
-        }
+    if (conns[i].type != BT_CONN_TYPE_LE) {
+      continue;
+    }
 
-        if (conns[i].id == id &&
-            !bt_conn_addr_le_cmp(&conns[i], peer)) {
-            return bt_conn_ref(&conns[i]);
-        }
+    if (conns[i].id == id && !bt_conn_addr_le_cmp(&conns[i], peer)) {
+      return bt_conn_ref(&conns[i]);
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_conn *bt_conn_lookup_state_le(const bt_addr_le_t *peer,
-                                        const bt_conn_state_t state)
-{
-    int i;
+struct bt_conn *bt_conn_lookup_state_le(const bt_addr_le_t *peer, const bt_conn_state_t state) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
+    }
 
-        if (conns[i].type != BT_CONN_TYPE_LE) {
-            continue;
-        }
+    if (conns[i].type != BT_CONN_TYPE_LE) {
+      continue;
+    }
 
-        if (peer && bt_conn_addr_le_cmp(&conns[i], peer)) {
-            continue;
-        }
+    if (peer && bt_conn_addr_le_cmp(&conns[i], peer)) {
+      continue;
+    }
 
-        if (conns[i].state == state) {
-            return bt_conn_ref(&conns[i]);
-        }
+    if (conns[i].state == state) {
+      return bt_conn_ref(&conns[i]);
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data),
-                     void *data)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
+void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data), void *data) {
+  int i;
 
-        if (!(conns[i].type & type)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
+    }
 
-        func(&conns[i], data);
+    if (!(conns[i].type & type)) {
+      continue;
     }
+
+    func(&conns[i], data);
+  }
 #if defined(CONFIG_BT_BREDR)
-    if (type & BT_CONN_TYPE_SCO) {
-        for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
-            if (!atomic_get(&sco_conns[i].ref)) {
-                continue;
-            }
+  if (type & BT_CONN_TYPE_SCO) {
+    for (i = 0; i < ARRAY_SIZE(sco_conns); i++) {
+      if (!atomic_get(&sco_conns[i].ref)) {
+        continue;
+      }
 
-            func(&sco_conns[i], data);
-        }
+      func(&sco_conns[i], data);
     }
+  }
 #endif /* defined(CONFIG_BT_BREDR) */
 }
 
-static void disconnect_all(struct bt_conn *conn, void *data)
-{
-    u8_t *id = (u8_t *)data;
+static void disconnect_all(struct bt_conn *conn, void *data) {
+  u8_t *id = (u8_t *)data;
 
-    if (conn->id == *id && conn->state == BT_CONN_CONNECTED) {
-        bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
-    }
+  if (conn->id == *id && conn->state == BT_CONN_CONNECTED) {
+    bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
+  }
 }
 
-void bt_conn_disconnect_all(u8_t id)
-{
-    bt_conn_foreach(BT_CONN_TYPE_ALL, disconnect_all, &id);
-}
+void bt_conn_disconnect_all(u8_t id) { bt_conn_foreach(BT_CONN_TYPE_ALL, disconnect_all, &id); }
 
-struct bt_conn *bt_conn_ref(struct bt_conn *conn)
-{
-    atomic_inc(&conn->ref);
+struct bt_conn *bt_conn_ref(struct bt_conn *conn) {
+  atomic_inc(&conn->ref);
 
-    BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref));
+  BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref));
 
-    return conn;
+  return conn;
 }
 
-void bt_conn_unref(struct bt_conn *conn)
-{
-    atomic_dec(&conn->ref);
+void bt_conn_unref(struct bt_conn *conn) {
+  atomic_dec(&conn->ref);
 
-    BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref));
+  BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref));
 }
 
-const bt_addr_le_t *bt_conn_get_dst(const struct bt_conn *conn)
-{
-    return &conn->le.dst;
-}
+const bt_addr_le_t *bt_conn_get_dst(const struct bt_conn *conn) { return &conn->le.dst; }
 
-int bt_conn_get_info(const struct bt_conn *conn, struct bt_conn_info *info)
-{
-    info->type = conn->type;
-    info->role = conn->role;
-    info->id = conn->id;
-
-    switch (conn->type) {
-        case BT_CONN_TYPE_LE:
-            info->le.dst = &conn->le.dst;
-            info->le.src = &bt_dev.id_addr[conn->id];
-            if (conn->role == BT_HCI_ROLE_MASTER) {
-                info->le.local = &conn->le.init_addr;
-                info->le.remote = &conn->le.resp_addr;
-            } else {
-                info->le.local = &conn->le.resp_addr;
-                info->le.remote = &conn->le.init_addr;
-            }
-            info->le.interval = conn->le.interval;
-            info->le.latency = conn->le.latency;
-            info->le.timeout = conn->le.timeout;
-            return 0;
+int bt_conn_get_info(const struct bt_conn *conn, struct bt_conn_info *info) {
+  info->type = conn->type;
+  info->role = conn->role;
+  info->id   = conn->id;
+
+  switch (conn->type) {
+  case BT_CONN_TYPE_LE:
+    info->le.dst = &conn->le.dst;
+    info->le.src = &bt_dev.id_addr[conn->id];
+    if (conn->role == BT_HCI_ROLE_MASTER) {
+      info->le.local  = &conn->le.init_addr;
+      info->le.remote = &conn->le.resp_addr;
+    } else {
+      info->le.local  = &conn->le.resp_addr;
+      info->le.remote = &conn->le.init_addr;
+    }
+    info->le.interval = conn->le.interval;
+    info->le.latency  = conn->le.latency;
+    info->le.timeout  = conn->le.timeout;
+    return 0;
 #if defined(CONFIG_BT_BREDR)
-        case BT_CONN_TYPE_BR:
-            info->br.dst = &conn->br.dst;
-            return 0;
+  case BT_CONN_TYPE_BR:
+    info->br.dst = &conn->br.dst;
+    return 0;
 #endif
-    }
+  }
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-int bt_conn_get_remote_dev_info(struct bt_conn_info *info)
-{
-    int link_num = 0;
+int bt_conn_get_remote_dev_info(struct bt_conn_info *info) {
+  int link_num = 0;
 
-    for (int i = 0; i < ARRAY_SIZE(conns); i++) {
-        if (!atomic_get(&conns[i].ref)) {
-            continue;
-        }
-        bt_conn_get_info(&conns[i], &info[link_num]);
-        link_num++;
+  for (int i = 0; i < ARRAY_SIZE(conns); i++) {
+    if (!atomic_get(&conns[i].ref)) {
+      continue;
     }
+    bt_conn_get_info(&conns[i], &info[link_num]);
+    link_num++;
+  }
 
-    return link_num;
+  return link_num;
 }
 
-static int bt_hci_disconnect(struct bt_conn *conn, u8_t reason)
-{
-    struct net_buf *buf;
-    struct bt_hci_cp_disconnect *disconn;
-    int err;
+static int bt_hci_disconnect(struct bt_conn *conn, u8_t reason) {
+  struct net_buf              *buf;
+  struct bt_hci_cp_disconnect *disconn;
+  int                          err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_DISCONNECT, sizeof(*disconn));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_DISCONNECT, sizeof(*disconn));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    disconn = net_buf_add(buf, sizeof(*disconn));
-    disconn->handle = sys_cpu_to_le16(conn->handle);
-    disconn->reason = reason;
+  disconn         = net_buf_add(buf, sizeof(*disconn));
+  disconn->handle = sys_cpu_to_le16(conn->handle);
+  disconn->reason = reason;
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_DISCONNECT, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_DISCONNECT, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    bt_conn_set_state(conn, BT_CONN_DISCONNECT);
+  bt_conn_set_state(conn, BT_CONN_DISCONNECT);
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_STACK_PTS)
-int pts_bt_conn_le_param_update(struct bt_conn *conn,
-                                const struct bt_le_conn_param *param)
-{
-    BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn,
-           conn->le.features[0], param->interval_min,
-           param->interval_max, param->latency, param->timeout);
+int pts_bt_conn_le_param_update(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, conn->le.features[0], param->interval_min, param->interval_max, param->latency, param->timeout);
 
-    /* Check if there's a need to update conn params */
-    if (conn->le.interval >= param->interval_min &&
-        conn->le.interval <= param->interval_max &&
-        conn->le.latency == param->latency &&
-        conn->le.timeout == param->timeout) {
-        return -EALREADY;
-    }
+  /* Check if there's a need to update conn params */
+  if (conn->le.interval >= param->interval_min && conn->le.interval <= param->interval_max && conn->le.latency == param->latency && conn->le.timeout == param->timeout) {
+    return -EALREADY;
+  }
 
-    /* Cancel any pending update */
-    k_delayed_work_cancel(&conn->update_work);
+  /* Cancel any pending update */
+  k_delayed_work_cancel(&conn->update_work);
 
-    return bt_l2cap_update_conn_param(conn, param);
+  return bt_l2cap_update_conn_param(conn, param);
 }
 #endif
-int bt_conn_le_param_update(struct bt_conn *conn,
-                            const struct bt_le_conn_param *param)
-{
-    BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn,
-           conn->le.features[0], param->interval_min,
-           param->interval_max, param->latency, param->timeout);
-
-    /* Check if there's a need to update conn params */
-    if (conn->le.interval >= param->interval_min &&
-        conn->le.interval <= param->interval_max &&
-        conn->le.latency == param->latency &&
-        conn->le.timeout == param->timeout) {
-        atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
-        return -EALREADY;
-    }
+int bt_conn_le_param_update(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, conn->le.features[0], param->interval_min, param->interval_max, param->latency, param->timeout);
+
+  /* Check if there's a need to update conn params */
+  if (conn->le.interval >= param->interval_min && conn->le.interval <= param->interval_max && conn->le.latency == param->latency && conn->le.timeout == param->timeout) {
+    atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
+    return -EALREADY;
+  }
+
+  if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_CONN_ROLE_MASTER) {
+    return send_conn_le_param_update(conn, param);
+  }
+
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
+    /* if slave conn param update timer expired just send request */
+    if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) {
+      return send_conn_le_param_update(conn, param);
+    }
+
+    /* store new conn params to be used by update timer */
+    conn->le.interval_min    = param->interval_min;
+    conn->le.interval_max    = param->interval_max;
+    conn->le.pending_latency = param->latency;
+    conn->le.pending_timeout = param->timeout;
+    atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
+  }
+
+  return 0;
+}
+
+int bt_conn_disconnect(struct bt_conn *conn, u8_t reason) {
+  /* Disconnection is initiated by us, so auto connection shall
+   * be disabled. Otherwise the passive scan would be enabled
+   * and we could send LE Create Connection as soon as the remote
+   * starts advertising.
+   */
+#if !defined(CONFIG_BT_WHITELIST)
+  if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->type == BT_CONN_TYPE_LE) {
+    bt_le_set_auto_conn(&conn->le.dst, NULL);
+  }
+#endif /* !defined(CONFIG_BT_WHITELIST) */
 
-    if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-        conn->role == BT_CONN_ROLE_MASTER) {
-        return send_conn_le_param_update(conn, param);
+  switch (conn->state) {
+  case BT_CONN_CONNECT_SCAN:
+    conn->err = reason;
+    bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+      bt_le_scan_update(false);
     }
-
+    return 0;
+  case BT_CONN_CONNECT_DIR_ADV:
+    conn->err = reason;
+    bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
     if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
-        /* if slave conn param update timer expired just send request */
-        if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) {
-            return send_conn_le_param_update(conn, param);
-        }
-
-        /* store new conn params to be used by update timer */
-        conn->le.interval_min = param->interval_min;
-        conn->le.interval_max = param->interval_max;
-        conn->le.pending_latency = param->latency;
-        conn->le.pending_timeout = param->timeout;
-        atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET);
+      /* User should unref connection object when receiving
+       * error in connection callback.
+       */
+      return bt_le_adv_stop();
     }
-
     return 0;
-}
-
-int bt_conn_disconnect(struct bt_conn *conn, u8_t reason)
-{
-    /* Disconnection is initiated by us, so auto connection shall
-	 * be disabled. Otherwise the passive scan would be enabled
-	 * and we could send LE Create Connection as soon as the remote
-	 * starts advertising.
-	 */
-#if !defined(CONFIG_BT_WHITELIST)
-    if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-        conn->type == BT_CONN_TYPE_LE) {
-        bt_le_set_auto_conn(&conn->le.dst, NULL);
-    }
-#endif /* !defined(CONFIG_BT_WHITELIST) */
-
-    switch (conn->state) {
-        case BT_CONN_CONNECT_SCAN:
-            conn->err = reason;
-            bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-            if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-                bt_le_scan_update(false);
-            }
-            return 0;
-        case BT_CONN_CONNECT_DIR_ADV:
-            conn->err = reason;
-            bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-            if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
-                /* User should unref connection object when receiving
-			 * error in connection callback.
-			 */
-                return bt_le_adv_stop();
-            }
-            return 0;
-        case BT_CONN_CONNECT:
+  case BT_CONN_CONNECT:
 #if defined(CONFIG_BT_BREDR)
-            if (conn->type == BT_CONN_TYPE_BR) {
-                return bt_hci_connect_br_cancel(conn);
-            }
+    if (conn->type == BT_CONN_TYPE_BR) {
+      return bt_hci_connect_br_cancel(conn);
+    }
 #endif /* CONFIG_BT_BREDR */
 
-            if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-                k_delayed_work_cancel(&conn->update_work);
-                return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL,
-                                            NULL, NULL);
-            }
-
-            return 0;
-        case BT_CONN_CONNECTED:
-            return bt_hci_disconnect(conn, reason);
-        case BT_CONN_DISCONNECT:
-            return 0;
-        case BT_CONN_DISCONNECTED:
-        default:
-            return -ENOTCONN;
+    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+      k_delayed_work_cancel(&conn->update_work);
+      return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, NULL, NULL);
     }
+
+    return 0;
+  case BT_CONN_CONNECTED:
+    return bt_hci_disconnect(conn, reason);
+  case BT_CONN_DISCONNECT:
+    return 0;
+  case BT_CONN_DISCONNECTED:
+  default:
+    return -ENOTCONN;
+  }
 }
 
 #if defined(CONFIG_BT_CENTRAL)
-static void bt_conn_set_param_le(struct bt_conn *conn,
-                                 const struct bt_le_conn_param *param)
-{
-    conn->le.interval_min = param->interval_min;
-    conn->le.interval_max = param->interval_max;
-    conn->le.latency = param->latency;
-    conn->le.timeout = param->timeout;
+static void bt_conn_set_param_le(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  conn->le.interval_min = param->interval_min;
+  conn->le.interval_max = param->interval_max;
+  conn->le.latency      = param->latency;
+  conn->le.timeout      = param->timeout;
 
 #if defined(CONFIG_BT_STACK_PTS)
-    conn->le.own_adder_type = param->own_address_type;
+  conn->le.own_adder_type = param->own_address_type;
 #endif
 }
 
 #if defined(CONFIG_BT_WHITELIST)
-int bt_conn_create_auto_le(const struct bt_le_conn_param *param)
-{
-    struct bt_conn *conn;
-    int err;
+int bt_conn_create_auto_le(const struct bt_le_conn_param *param) {
+  struct bt_conn *conn;
+  int             err;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EINVAL;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EINVAL;
+  }
 
-    if (!bt_le_conn_params_valid(param)) {
-        return -EINVAL;
-    }
+  if (!bt_le_conn_params_valid(param)) {
+    return -EINVAL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return -EINVAL;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return -EINVAL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
-        return -EALREADY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
+    return -EALREADY;
+  }
 
-    if (!bt_dev.le.wl_entries) {
-        return -EINVAL;
-    }
+  if (!bt_dev.le.wl_entries) {
+    return -EINVAL;
+  }
 
-    /* Don't start initiator if we have general discovery procedure. */
-    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN);
-    if (conn) {
-        bt_conn_unref(conn);
-        return -EINVAL;
-    }
+  /* Don't start initiator if we have general discovery procedure. */
+  conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN);
+  if (conn) {
+    bt_conn_unref(conn);
+    return -EINVAL;
+  }
 
-    /* Don't start initiator if we have direct discovery procedure. */
-    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
-    if (conn) {
-        bt_conn_unref(conn);
-        return -EINVAL;
-    }
+  /* Don't start initiator if we have direct discovery procedure. */
+  conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
+  if (conn) {
+    bt_conn_unref(conn);
+    return -EINVAL;
+  }
 
-    err = bt_le_auto_conn(param);
-    if (err) {
-        BT_ERR("Failed to start whitelist scan");
-        return err;
-    }
+  err = bt_le_auto_conn(param);
+  if (err) {
+    BT_ERR("Failed to start whitelist scan");
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int bt_conn_create_auto_stop(void)
-{
-    int err;
+int bt_conn_create_auto_stop(void) {
+  int err;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EINVAL;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EINVAL;
+  }
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
-        return -EINVAL;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
+    return -EINVAL;
+  }
 
-    err = bt_le_auto_conn_cancel();
-    if (err) {
-        BT_ERR("Failed to stop initiator");
-        return err;
-    }
+  err = bt_le_auto_conn_cancel();
+  if (err) {
+    BT_ERR("Failed to stop initiator");
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-struct bt_conn *bt_conn_create_le(const bt_addr_le_t *peer,
-                                  const struct bt_le_conn_param *param)
-{
-    struct bt_conn *conn;
-    bt_addr_le_t dst;
-
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return NULL;
-    }
+struct bt_conn *bt_conn_create_le(const bt_addr_le_t *peer, const struct bt_le_conn_param *param) {
+  struct bt_conn *conn;
+  bt_addr_le_t    dst;
 
-    if (!bt_le_conn_params_valid(param)) {
-        return NULL;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return NULL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return NULL;
-    }
+  if (!bt_le_conn_params_valid(param)) {
+    return NULL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_WHITELIST) &&
-        atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
-        return NULL;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return NULL;
+  }
 
-    conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, peer);
-    if (conn) {
-        switch (conn->state) {
-            case BT_CONN_CONNECT_SCAN:
-                bt_conn_set_param_le(conn, param);
-                return conn;
-            case BT_CONN_CONNECT:
-            case BT_CONN_CONNECTED:
-                return conn;
-            case BT_CONN_DISCONNECTED:
-                BT_WARN("Found valid but disconnected conn object");
-                goto start_scan;
-            default:
-                bt_conn_unref(conn);
-                return NULL;
-        }
-    }
-
-    if (peer->type == BT_ADDR_LE_PUBLIC_ID ||
-        peer->type == BT_ADDR_LE_RANDOM_ID) {
-        bt_addr_le_copy(&dst, peer);
-        dst.type -= BT_ADDR_LE_PUBLIC_ID;
-    } else {
-        bt_addr_le_copy(&dst, bt_lookup_id_addr(BT_ID_DEFAULT, peer));
-    }
+  if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
+    return NULL;
+  }
 
-    /* Only default identity supported for now */
-    conn = bt_conn_add_le(BT_ID_DEFAULT, &dst);
-    if (!conn) {
-        return NULL;
-    }
+  conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, peer);
+  if (conn) {
+    switch (conn->state) {
+    case BT_CONN_CONNECT_SCAN:
+      bt_conn_set_param_le(conn, param);
+      return conn;
+    case BT_CONN_CONNECT:
+    case BT_CONN_CONNECTED:
+      return conn;
+    case BT_CONN_DISCONNECTED:
+      BT_WARN("Found valid but disconnected conn object");
+      goto start_scan;
+    default:
+      bt_conn_unref(conn);
+      return NULL;
+    }
+  }
+
+  if (peer->type == BT_ADDR_LE_PUBLIC_ID || peer->type == BT_ADDR_LE_RANDOM_ID) {
+    bt_addr_le_copy(&dst, peer);
+    dst.type -= BT_ADDR_LE_PUBLIC_ID;
+  } else {
+    bt_addr_le_copy(&dst, bt_lookup_id_addr(BT_ID_DEFAULT, peer));
+  }
+
+  /* Only default identity supported for now */
+  conn = bt_conn_add_le(BT_ID_DEFAULT, &dst);
+  if (!conn) {
+    return NULL;
+  }
 
 start_scan:
-    bt_conn_set_param_le(conn, param);
+  bt_conn_set_param_le(conn, param);
 
-    bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
+  bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
 
-    bt_le_scan_update(true);
+  bt_le_scan_update(true);
 
-    return conn;
+  return conn;
 }
 
 #if !defined(CONFIG_BT_WHITELIST)
-int bt_le_set_auto_conn(const bt_addr_le_t *addr,
-                        const struct bt_le_conn_param *param)
-{
-    struct bt_conn *conn;
+int bt_le_set_auto_conn(const bt_addr_le_t *addr, const struct bt_le_conn_param *param) {
+  struct bt_conn *conn;
 
-    if (param && !bt_le_conn_params_valid(param)) {
-        return -EINVAL;
-    }
+  if (param && !bt_le_conn_params_valid(param)) {
+    return -EINVAL;
+  }
 
-    /* Only default identity is supported */
-    conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, addr);
+  /* Only default identity is supported */
+  conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, addr);
+  if (!conn) {
+    conn = bt_conn_add_le(BT_ID_DEFAULT, addr);
     if (!conn) {
-        conn = bt_conn_add_le(BT_ID_DEFAULT, addr);
-        if (!conn) {
-            return -ENOMEM;
-        }
+      return -ENOMEM;
     }
+  }
 
-    if (param) {
-        bt_conn_set_param_le(conn, param);
+  if (param) {
+    bt_conn_set_param_le(conn, param);
 
-        if (!atomic_test_and_set_bit(conn->flags,
-                                     BT_CONN_AUTO_CONNECT)) {
-            bt_conn_ref(conn);
-        }
-    } else {
-        if (atomic_test_and_clear_bit(conn->flags,
-                                      BT_CONN_AUTO_CONNECT)) {
-            bt_conn_unref(conn);
-            if (conn->state == BT_CONN_CONNECT_SCAN) {
-                bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-            }
-        }
+    if (!atomic_test_and_set_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
+      bt_conn_ref(conn);
     }
+  } else {
+    if (atomic_test_and_clear_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
+      bt_conn_unref(conn);
+      if (conn->state == BT_CONN_CONNECT_SCAN) {
+        bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+      }
+    }
+  }
 
-    if (conn->state == BT_CONN_DISCONNECTED &&
-        atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        if (param) {
-            bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
-        }
-        bt_le_scan_update(false);
+  if (conn->state == BT_CONN_DISCONNECTED && atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    if (param) {
+      bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
     }
+    bt_le_scan_update(false);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 
-    return 0;
+  return 0;
 }
 #endif /* !defined(CONFIG_BT_WHITELIST) */
 #endif /* CONFIG_BT_CENTRAL */
 
 #if defined(CONFIG_BT_PERIPHERAL)
-struct bt_conn *bt_conn_create_slave_le(const bt_addr_le_t *peer,
-                                        const struct bt_le_adv_param *param)
-{
-    int err;
-    struct bt_conn *conn;
-    struct bt_le_adv_param param_int;
-
-    memcpy(¶m_int, param, sizeof(param_int));
-    param_int.options |= (BT_LE_ADV_OPT_CONNECTABLE |
-                          BT_LE_ADV_OPT_ONE_TIME);
-
-    conn = bt_conn_lookup_addr_le(param->id, peer);
-    if (conn) {
-        switch (conn->state) {
-            case BT_CONN_CONNECT_DIR_ADV:
-                /* Handle the case when advertising is stopped with
-			 * bt_le_adv_stop function
-			 */
-                err = bt_le_adv_start_internal(¶m_int, NULL, 0,
-                                               NULL, 0, peer);
-                if (err && (err != -EALREADY)) {
-                    BT_WARN("Directed advertising could not be"
-                            " started: %d",
-                            err);
-                    bt_conn_unref(conn);
-                    return NULL;
-                }
-                __attribute__((fallthrough));
-            case BT_CONN_CONNECT:
-            case BT_CONN_CONNECTED:
-                return conn;
-            case BT_CONN_DISCONNECTED:
-                BT_WARN("Found valid but disconnected conn object");
-                goto start_adv;
-            default:
-                bt_conn_unref(conn);
-                return NULL;
-        }
-    }
-
-    conn = bt_conn_add_le(param->id, peer);
-    if (!conn) {
+struct bt_conn *bt_conn_create_slave_le(const bt_addr_le_t *peer, const struct bt_le_adv_param *param) {
+  int                    err;
+  struct bt_conn        *conn;
+  struct bt_le_adv_param param_int;
+
+  memcpy(¶m_int, param, sizeof(param_int));
+  param_int.options |= (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME);
+
+  conn = bt_conn_lookup_addr_le(param->id, peer);
+  if (conn) {
+    switch (conn->state) {
+    case BT_CONN_CONNECT_DIR_ADV:
+      /* Handle the case when advertising is stopped with
+       * bt_le_adv_stop function
+       */
+      err = bt_le_adv_start_internal(¶m_int, NULL, 0, NULL, 0, peer);
+      if (err && (err != -EALREADY)) {
+        BT_WARN("Directed advertising could not be"
+                " started: %d",
+                err);
+        bt_conn_unref(conn);
         return NULL;
-    }
+      }
+      __attribute__((fallthrough));
+    case BT_CONN_CONNECT:
+    case BT_CONN_CONNECTED:
+      return conn;
+    case BT_CONN_DISCONNECTED:
+      BT_WARN("Found valid but disconnected conn object");
+      goto start_adv;
+    default:
+      bt_conn_unref(conn);
+      return NULL;
+    }
+  }
+
+  conn = bt_conn_add_le(param->id, peer);
+  if (!conn) {
+    return NULL;
+  }
 
 start_adv:
-    bt_conn_set_state(conn, BT_CONN_CONNECT_DIR_ADV);
+  bt_conn_set_state(conn, BT_CONN_CONNECT_DIR_ADV);
 
-    err = bt_le_adv_start_internal(¶m_int, NULL, 0, NULL, 0, peer);
-    if (err) {
-        BT_WARN("Directed advertising could not be started: %d", err);
+  err = bt_le_adv_start_internal(¶m_int, NULL, 0, NULL, 0, peer);
+  if (err) {
+    BT_WARN("Directed advertising could not be started: %d", err);
 
-        bt_conn_unref(conn);
-        return NULL;
-    }
+    bt_conn_unref(conn);
+    return NULL;
+  }
 
-    return conn;
+  return conn;
 }
 #endif /* CONFIG_BT_PERIPHERAL */
 
-int bt_conn_le_conn_update(struct bt_conn *conn,
-                           const struct bt_le_conn_param *param)
-{
-    struct hci_cp_le_conn_update *conn_update;
-    struct net_buf *buf;
+int bt_conn_le_conn_update(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  struct hci_cp_le_conn_update *conn_update;
+  struct net_buf               *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_UPDATE,
-                            sizeof(*conn_update));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_UPDATE, sizeof(*conn_update));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    conn_update = net_buf_add(buf, sizeof(*conn_update));
-    (void)memset(conn_update, 0, sizeof(*conn_update));
-    conn_update->handle = sys_cpu_to_le16(conn->handle);
-    conn_update->conn_interval_min = sys_cpu_to_le16(param->interval_min);
-    conn_update->conn_interval_max = sys_cpu_to_le16(param->interval_max);
-    conn_update->conn_latency = sys_cpu_to_le16(param->latency);
-    conn_update->supervision_timeout = sys_cpu_to_le16(param->timeout);
+  conn_update = net_buf_add(buf, sizeof(*conn_update));
+  (void)memset(conn_update, 0, sizeof(*conn_update));
+  conn_update->handle              = sys_cpu_to_le16(conn->handle);
+  conn_update->conn_interval_min   = sys_cpu_to_le16(param->interval_min);
+  conn_update->conn_interval_max   = sys_cpu_to_le16(param->interval_max);
+  conn_update->conn_latency        = sys_cpu_to_le16(param->latency);
+  conn_update->supervision_timeout = sys_cpu_to_le16(param->timeout);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CONN_UPDATE, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CONN_UPDATE, buf, NULL);
 }
 
-struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool,
-                                           size_t reserve, s32_t timeout)
-{
-    struct net_buf *buf;
+struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool, size_t reserve, s32_t timeout) {
+  struct net_buf *buf;
 
-    /*
-	 * PDU must not be allocated from ISR as we block with 'K_FOREVER'
-	 * during the allocation
-	 */
-    __ASSERT_NO_MSG(!k_is_in_isr());
+  /*
+   * PDU must not be allocated from ISR as we block with 'K_FOREVER'
+   * during the allocation
+   */
+  __ASSERT_NO_MSG(!k_is_in_isr());
 
-    if (!pool) {
-        pool = &acl_tx_pool;
-    }
-
-    if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) {
-        buf = net_buf_alloc(pool, K_NO_WAIT);
-        if (!buf) {
-            BT_WARN("Unable to allocate buffer with K_NO_WAIT");
-            buf = net_buf_alloc(pool, timeout);
-        }
-    } else {
-        buf = net_buf_alloc(pool, timeout);
-    }
+  if (!pool) {
+    pool = &acl_tx_pool;
+  }
 
+  if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) {
+    buf = net_buf_alloc(pool, K_NO_WAIT);
     if (!buf) {
-        BT_WARN("Unable to allocate buffer: timeout %d", timeout);
-        return NULL;
+      BT_WARN("Unable to allocate buffer with K_NO_WAIT");
+      buf = net_buf_alloc(pool, timeout);
     }
+  } else {
+    buf = net_buf_alloc(pool, timeout);
+  }
 
-    reserve += sizeof(struct bt_hci_acl_hdr) + BT_BUF_RESERVE;
-    net_buf_reserve(buf, reserve);
+  if (!buf) {
+    BT_WARN("Unable to allocate buffer: timeout %d", timeout);
+    return NULL;
+  }
+
+  reserve += sizeof(struct bt_hci_acl_hdr) + BT_BUF_RESERVE;
+  net_buf_reserve(buf, reserve);
 
-    return buf;
+  return buf;
 }
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-int bt_conn_auth_cb_register(const struct bt_conn_auth_cb *cb)
-{
-    if (!cb) {
-        bt_auth = NULL;
-        return 0;
-    }
+int bt_conn_auth_cb_register(const struct bt_conn_auth_cb *cb) {
+  if (!cb) {
+    bt_auth = NULL;
+    return 0;
+  }
 
-    if (bt_auth) {
-        return -EALREADY;
-    }
+  if (bt_auth) {
+    return -EALREADY;
+  }
 
-    /* The cancel callback must always be provided if the app provides
-	 * interactive callbacks.
-	 */
-    if (!cb->cancel &&
-        (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm ||
+  /* The cancel callback must always be provided if the app provides
+   * interactive callbacks.
+   */
+  if (!cb->cancel && (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm ||
 #if defined(CONFIG_BT_BREDR)
-         cb->pincode_entry ||
+                      cb->pincode_entry ||
 #endif
-         cb->pairing_confirm)) {
-        return -EINVAL;
-    }
+                      cb->pairing_confirm)) {
+    return -EINVAL;
+  }
 
-    bt_auth = cb;
-    return 0;
+  bt_auth = cb;
+  return 0;
 }
 
-int bt_conn_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey)
-{
-    if (!bt_auth) {
-        return -EINVAL;
-    }
+int bt_conn_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey) {
+  if (!bt_auth) {
+    return -EINVAL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
-        bt_smp_auth_passkey_entry(conn, passkey);
-        return 0;
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
+    bt_smp_auth_passkey_entry(conn, passkey);
+    return 0;
+  }
 
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        /* User entered passkey, reset user state. */
-        if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
-            return -EPERM;
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    /* User entered passkey, reset user state. */
+    if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
+      return -EPERM;
+    }
 
-        if (conn->br.pairing_method == PASSKEY_INPUT) {
-            return ssp_passkey_reply(conn, passkey);
-        }
+    if (conn->br.pairing_method == PASSKEY_INPUT) {
+      return ssp_passkey_reply(conn, passkey);
     }
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-int bt_conn_auth_passkey_confirm(struct bt_conn *conn)
-{
-    if (!bt_auth) {
-        return -EINVAL;
-    }
+int bt_conn_auth_passkey_confirm(struct bt_conn *conn) {
+  if (!bt_auth) {
+    return -EINVAL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SMP) &&
-        conn->type == BT_CONN_TYPE_LE) {
-        return bt_smp_auth_passkey_confirm(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
+    return bt_smp_auth_passkey_confirm(conn);
+  }
 
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        /* Allow user confirm passkey value, then reset user state. */
-        if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
-            return -EPERM;
-        }
-
-        return ssp_confirm_reply(conn);
+  if (conn->type == BT_CONN_TYPE_BR) {
+    /* Allow user confirm passkey value, then reset user state. */
+    if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
+      return -EPERM;
     }
+
+    return ssp_confirm_reply(conn);
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-int bt_conn_auth_cancel(struct bt_conn *conn)
-{
-    if (!bt_auth) {
-        return -EINVAL;
-    }
+int bt_conn_auth_cancel(struct bt_conn *conn) {
+  if (!bt_auth) {
+    return -EINVAL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
-        return bt_smp_auth_cancel(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) {
+    return bt_smp_auth_cancel(conn);
+  }
 
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        /* Allow user cancel authentication, then reset user state. */
-        if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
-            return -EPERM;
-        }
-
-        switch (conn->br.pairing_method) {
-            case JUST_WORKS:
-            case PASSKEY_CONFIRM:
-                return ssp_confirm_neg_reply(conn);
-            case PASSKEY_INPUT:
-                return ssp_passkey_neg_reply(conn);
-            case PASSKEY_DISPLAY:
-                return bt_conn_disconnect(conn,
-                                          BT_HCI_ERR_AUTH_FAIL);
-            case LEGACY:
-                return pin_code_neg_reply(&conn->br.dst);
-            default:
-                break;
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    /* Allow user cancel authentication, then reset user state. */
+    if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) {
+      return -EPERM;
     }
+
+    switch (conn->br.pairing_method) {
+    case JUST_WORKS:
+    case PASSKEY_CONFIRM:
+      return ssp_confirm_neg_reply(conn);
+    case PASSKEY_INPUT:
+      return ssp_passkey_neg_reply(conn);
+    case PASSKEY_DISPLAY:
+      return bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
+    case LEGACY:
+      return pin_code_neg_reply(&conn->br.dst);
+    default:
+      break;
+    }
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    return -EINVAL;
+  return -EINVAL;
 }
 
-int bt_conn_auth_pairing_confirm(struct bt_conn *conn)
-{
-    if (!bt_auth) {
-        return -EINVAL;
-    }
+int bt_conn_auth_pairing_confirm(struct bt_conn *conn) {
+  if (!bt_auth) {
+    return -EINVAL;
+  }
 
-    switch (conn->type) {
+  switch (conn->type) {
 #if defined(CONFIG_BT_SMP)
-        case BT_CONN_TYPE_LE:
-            return bt_smp_auth_pairing_confirm(conn);
+  case BT_CONN_TYPE_LE:
+    return bt_smp_auth_pairing_confirm(conn);
 #endif /* CONFIG_BT_SMP */
 #if defined(CONFIG_BT_BREDR)
-        case BT_CONN_TYPE_BR:
-            return ssp_confirm_reply(conn);
+  case BT_CONN_TYPE_BR:
+    return ssp_confirm_reply(conn);
 #endif /* CONFIG_BT_BREDR */
-        default:
-            return -EINVAL;
-    }
+  default:
+    return -EINVAL;
+  }
 }
 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
 
-u8_t bt_conn_index(struct bt_conn *conn)
-{
-    u8_t index = conn - conns;
+u8_t bt_conn_index(struct bt_conn *conn) {
+  u8_t index = conn - conns;
 
-    __ASSERT(index < CONFIG_BT_MAX_CONN, "Invalid bt_conn pointer");
-    return index;
+  __ASSERT(index < CONFIG_BT_MAX_CONN, "Invalid bt_conn pointer");
+  return index;
 }
 
-struct bt_conn *bt_conn_lookup_id(u8_t id)
-{
-    struct bt_conn *conn;
+struct bt_conn *bt_conn_lookup_id(u8_t id) {
+  struct bt_conn *conn;
 
-    if (id >= ARRAY_SIZE(conns)) {
-        return NULL;
-    }
+  if (id >= ARRAY_SIZE(conns)) {
+    return NULL;
+  }
 
-    conn = &conns[id];
+  conn = &conns[id];
 
-    if (!atomic_get(&conn->ref)) {
-        return NULL;
-    }
+  if (!atomic_get(&conn->ref)) {
+    return NULL;
+  }
 
-    return bt_conn_ref(conn);
+  return bt_conn_ref(conn);
 }
 
-int bt_conn_init(void)
-{
+int bt_conn_init(void) {
 #if defined(CONFIG_BT_SMP)
-    int err;
+  int err;
 #endif
-    int i;
+  int i;
 
 #if defined(BFLB_BLE)
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_init(&acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), NULL);
+#if (BFLB_STATIC_ALLOC_MEM)
+  net_buf_init(ACL_TX, &acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), NULL);
+#else
+  net_buf_init(&acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), NULL);
+#endif
 #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
-    net_buf_init(&frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE, NULL);
+#if (BFLB_STATIC_ALLOC_MEM)
+  net_buf_init(FRAG, &frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE, NULL);
+#else
+  net_buf_init(&frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE, NULL);
 #endif
-#else //BFLB_DYNAMIC_ALLOC_MEM
-    struct net_buf_pool num_complete_pool;
-    struct net_buf_pool acl_tx_pool;
+#endif
+#else // BFLB_DYNAMIC_ALLOC_MEM
+  struct net_buf_pool num_complete_pool;
+  struct net_buf_pool acl_tx_pool;
 #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
-    struct net_buf_pool frag_pool;
+  struct net_buf_pool frag_pool;
 #endif
-#endif //BFLB_DYNAMIC_ALLOC_MEM
-    k_fifo_init(&free_tx, 20);
+#endif // BFLB_DYNAMIC_ALLOC_MEM
+  k_fifo_init(&free_tx, 20);
 #endif
-    for (i = 0; i < ARRAY_SIZE(conn_tx); i++) {
-        k_fifo_put(&free_tx, &conn_tx[i]);
-    }
+  for (i = 0; i < ARRAY_SIZE(conn_tx); i++) {
+    k_fifo_put(&free_tx, &conn_tx[i]);
+  }
 
-    bt_att_init();
+  bt_att_init();
 
 #if defined(CONFIG_BT_SMP)
-    err = bt_smp_init();
-    if (err) {
-        return err;
-    }
+  err = bt_smp_init();
+  if (err) {
+    return err;
+  }
 #endif
 
-    bt_l2cap_init();
+  bt_l2cap_init();
 
-    /* Initialize background scan */
-    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-        for (i = 0; i < ARRAY_SIZE(conns); i++) {
-            struct bt_conn *conn = &conns[i];
+  /* Initialize background scan */
+  if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+    for (i = 0; i < ARRAY_SIZE(conns); i++) {
+      struct bt_conn *conn = &conns[i];
 
-            if (!atomic_get(&conn->ref)) {
-                continue;
-            }
+      if (!atomic_get(&conn->ref)) {
+        continue;
+      }
 
-            if (atomic_test_bit(conn->flags,
-                                BT_CONN_AUTO_CONNECT)) {
-                /* Only the default identity is supported */
-                conn->id = BT_ID_DEFAULT;
-                bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
-            }
-        }
+      if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
+        /* Only the default identity is supported */
+        conn->id = BT_ID_DEFAULT;
+        bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
+      }
     }
+  }
 
-    return 0;
+  return 0;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h
index 3e6f0fe7b..2ba9a9c8e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/conn_internal.h
@@ -1,71 +1,65 @@
 /** @file
  *  @brief Internal APIs for Bluetooth connection handling.
  */
-#include "addr.h"
-#include "atomic.h"
-#include "slist.h"
-#include "types.h"
-#include "work_q.h"
-#include 
-#include 
+
 /*
  * Copyright (c) 2015 Intel Corporation
  *
  * SPDX-License-Identifier: Apache-2.0
  */
 typedef enum __packed {
-  BT_CONN_DISCONNECTED,
-  BT_CONN_CONNECT_SCAN,
-  BT_CONN_CONNECT_DIR_ADV,
-  BT_CONN_CONNECT,
-  BT_CONN_CONNECTED,
-  BT_CONN_DISCONNECT,
+    BT_CONN_DISCONNECTED,
+    BT_CONN_CONNECT_SCAN,
+    BT_CONN_CONNECT_DIR_ADV,
+    BT_CONN_CONNECT,
+    BT_CONN_CONNECTED,
+    BT_CONN_DISCONNECT,
 } bt_conn_state_t;
 
 /* bt_conn flags: the flags defined here represent connection parameters */
 enum {
-  BT_CONN_AUTO_CONNECT,
-  BT_CONN_BR_LEGACY_SECURE,     /* 16 digits legacy PIN tracker */
-  BT_CONN_USER,                 /* user I/O when pairing */
-  BT_CONN_BR_PAIRING,           /* BR connection in pairing context */
-  BT_CONN_BR_NOBOND,            /* SSP no bond pairing tracker */
-  BT_CONN_BR_PAIRING_INITIATOR, /* local host starts authentication */
-  BT_CONN_CLEANUP,              /* Disconnected, pending cleanup */
-  BT_CONN_AUTO_PHY_UPDATE,      /* Auto-update PHY */
-  BT_CONN_SLAVE_PARAM_UPDATE,   /* If slave param update timer fired */
-  BT_CONN_SLAVE_PARAM_SET,      /* If slave param were set from app */
-  BT_CONN_SLAVE_PARAM_L2CAP,    /* If should force L2CAP for CPUP */
-  BT_CONN_FORCE_PAIR,           /* Pairing even with existing keys. */
-
-  BT_CONN_AUTO_PHY_COMPLETE, /* Auto-initiated PHY procedure done */
-  BT_CONN_AUTO_FEATURE_EXCH, /* Auto-initiated LE Feat done */
-  BT_CONN_AUTO_VERSION_INFO, /* Auto-initiated LE version done */
-
-  /* Total number of flags - must be at the end of the enum */
-  BT_CONN_NUM_FLAGS,
+    BT_CONN_AUTO_CONNECT,
+    BT_CONN_BR_LEGACY_SECURE,     /* 16 digits legacy PIN tracker */
+    BT_CONN_USER,                 /* user I/O when pairing */
+    BT_CONN_BR_PAIRING,           /* BR connection in pairing context */
+    BT_CONN_BR_NOBOND,            /* SSP no bond pairing tracker */
+    BT_CONN_BR_PAIRING_INITIATOR, /* local host starts authentication */
+    BT_CONN_CLEANUP,              /* Disconnected, pending cleanup */
+    BT_CONN_AUTO_PHY_UPDATE,      /* Auto-update PHY */
+    BT_CONN_SLAVE_PARAM_UPDATE,   /* If slave param update timer fired */
+    BT_CONN_SLAVE_PARAM_SET,      /* If slave param were set from app */
+    BT_CONN_SLAVE_PARAM_L2CAP,    /* If should force L2CAP for CPUP */
+    BT_CONN_FORCE_PAIR,           /* Pairing even with existing keys. */
+
+    BT_CONN_AUTO_PHY_COMPLETE, /* Auto-initiated PHY procedure done */
+    BT_CONN_AUTO_FEATURE_EXCH, /* Auto-initiated LE Feat done */
+    BT_CONN_AUTO_VERSION_INFO, /* Auto-initiated LE version done */
+
+    /* Total number of flags - must be at the end of the enum */
+    BT_CONN_NUM_FLAGS,
 };
 
 struct bt_conn_le {
-  bt_addr_le_t dst;
+    bt_addr_le_t dst;
 
-  bt_addr_le_t init_addr;
-  bt_addr_le_t resp_addr;
+    bt_addr_le_t init_addr;
+    bt_addr_le_t resp_addr;
 
-  u16_t interval;
-  u16_t interval_min;
-  u16_t interval_max;
+    u16_t interval;
+    u16_t interval_min;
+    u16_t interval_max;
 
-  u16_t latency;
-  u16_t timeout;
-  u16_t pending_latency;
-  u16_t pending_timeout;
+    u16_t latency;
+    u16_t timeout;
+    u16_t pending_latency;
+    u16_t pending_timeout;
 
-  u8_t features[8];
+    u8_t features[8];
 
-  struct bt_keys *keys;
+    struct bt_keys *keys;
 
 #if defined(CONFIG_BT_STACK_PTS)
-  u8_t own_adder_type;
+    u8_t own_adder_type;
 #endif
 };
 
@@ -74,107 +68,107 @@ struct bt_conn_le {
 #define LMP_MAX_PAGES 2
 
 struct bt_conn_br {
-  bt_addr_t dst;
-  u8_t      remote_io_capa;
-  u8_t      remote_auth;
-  u8_t      pairing_method;
-  /* remote LMP features pages per 8 bytes each */
-  u8_t features[LMP_MAX_PAGES][8];
-
-  struct bt_keys_link_key *link_key;
+    bt_addr_t dst;
+    u8_t remote_io_capa;
+    u8_t remote_auth;
+    u8_t pairing_method;
+    /* remote LMP features pages per 8 bytes each */
+    u8_t features[LMP_MAX_PAGES][8];
+
+    struct bt_keys_link_key *link_key;
 };
 
 struct bt_conn_sco {
-  /* Reference to ACL Connection */
-  struct bt_conn *acl;
-  u16_t           pkt_type;
+    /* Reference to ACL Connection */
+    struct bt_conn *acl;
+    u16_t pkt_type;
 };
 #endif
 
 struct bt_conn_iso {
-  /* Reference to ACL Connection */
-  struct bt_conn *acl;
-  /* CIG ID */
-  uint8_t cig_id;
-  /* CIS ID */
-  uint8_t cis_id;
+    /* Reference to ACL Connection */
+    struct bt_conn *acl;
+    /* CIG ID */
+    uint8_t cig_id;
+    /* CIS ID */
+    uint8_t cis_id;
 };
 
 typedef void (*bt_conn_tx_cb_t)(struct bt_conn *conn, void *user_data);
 
 struct bt_conn_tx {
-  sys_snode_t node;
+    sys_snode_t node;
 
-  bt_conn_tx_cb_t cb;
-  void           *user_data;
+    bt_conn_tx_cb_t cb;
+    void *user_data;
 
-  /* Number of pending packets without a callback after this one */
-  u32_t pending_no_cb;
+    /* Number of pending packets without a callback after this one */
+    u32_t pending_no_cb;
 };
 
 struct bt_conn {
-  u16_t handle;
-  u8_t  type;
-  u8_t  role;
+    u16_t handle;
+    u8_t type;
+    u8_t role;
 
-  ATOMIC_DEFINE(flags, BT_CONN_NUM_FLAGS);
+    ATOMIC_DEFINE(flags, BT_CONN_NUM_FLAGS);
 
-  /* Which local identity address this connection uses */
-  u8_t id;
+    /* Which local identity address this connection uses */
+    u8_t id;
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-  bt_security_t sec_level;
-  bt_security_t required_sec_level;
-  u8_t          encrypt;
+    bt_security_t sec_level;
+    bt_security_t required_sec_level;
+    u8_t encrypt;
 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
 
-  /* Connection error or reason for disconnect */
-  u8_t err;
+    /* Connection error or reason for disconnect */
+    u8_t err;
 
-  bt_conn_state_t state;
+    bt_conn_state_t state;
 
-  u16_t           rx_len;
-  struct net_buf *rx;
+    u16_t rx_len;
+    struct net_buf *rx;
 
-  /* Sent but not acknowledged TX packets with a callback */
-  sys_slist_t tx_pending;
-  /* Sent but not acknowledged TX packets without a callback before
-   * the next packet (if any) in tx_pending.
-   */
-  u32_t pending_no_cb;
+    /* Sent but not acknowledged TX packets with a callback */
+    sys_slist_t tx_pending;
+    /* Sent but not acknowledged TX packets without a callback before
+	 * the next packet (if any) in tx_pending.
+	 */
+    u32_t pending_no_cb;
 
-  /* Completed TX for which we need to call the callback */
-  sys_slist_t   tx_complete;
-  struct k_work tx_complete_work;
+    /* Completed TX for which we need to call the callback */
+    sys_slist_t tx_complete;
+    struct k_work tx_complete_work;
 
-  /* Queue for outgoing ACL data */
-  struct k_fifo tx_queue;
+    /* Queue for outgoing ACL data */
+    struct k_fifo tx_queue;
 
-  /* Active L2CAP channels */
-  sys_slist_t channels;
+    /* Active L2CAP channels */
+    sys_slist_t channels;
 
-  atomic_t ref;
+    atomic_t ref;
 
-  /* Delayed work for connection update and other deferred tasks */
-  struct k_delayed_work update_work;
+    /* Delayed work for connection update and other deferred tasks */
+    struct k_delayed_work update_work;
 
-  union {
-    struct bt_conn_le le;
+    union {
+        struct bt_conn_le le;
 #if defined(CONFIG_BT_BREDR)
-    struct bt_conn_br  br;
-    struct bt_conn_sco sco;
+        struct bt_conn_br br;
+        struct bt_conn_sco sco;
 #endif
 #if defined(CONFIG_BT_AUDIO)
-    struct bt_conn_iso iso;
+        struct bt_conn_iso iso;
 #endif
-  };
+    };
 
 #if defined(CONFIG_BT_REMOTE_VERSION)
-  struct bt_conn_rv {
-    u8_t  version;
-    u16_t manufacturer;
-    u16_t subversion;
-  } rv;
+    struct bt_conn_rv {
+        u8_t version;
+        u16_t manufacturer;
+        u16_t subversion;
+    } rv;
 #endif
 };
 
@@ -184,19 +178,23 @@ void bt_conn_reset_rx_state(struct bt_conn *conn);
 void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, u8_t flags);
 
 /* Send data over a connection */
-int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data);
+int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf,
+                    bt_conn_tx_cb_t cb, void *user_data);
 
-static inline int bt_conn_send(struct bt_conn *conn, struct net_buf *buf) { return bt_conn_send_cb(conn, buf, NULL, NULL); }
+static inline int bt_conn_send(struct bt_conn *conn, struct net_buf *buf)
+{
+    return bt_conn_send_cb(conn, buf, NULL, NULL);
+}
 
 /* Add a new LE connection */
 struct bt_conn *bt_conn_add_le(u8_t id, const bt_addr_le_t *peer);
 
 /** Connection parameters for ISO connections */
 struct bt_iso_create_param {
-  uint8_t              id;
-  uint8_t              num_conns;
-  struct bt_conn     **conns;
-  struct bt_iso_chan **chans;
+    uint8_t id;
+    uint8_t num_conns;
+    struct bt_conn **conns;
+    struct bt_iso_chan **chans;
 };
 
 /* Bind ISO connections parameters */
@@ -253,22 +251,27 @@ struct bt_conn *bt_conn_lookup_id(u8_t id);
 /* Look up a connection state. For BT_ADDR_LE_ANY, returns the first connection
  * with the specific state
  */
-struct bt_conn *bt_conn_lookup_state_le(const bt_addr_le_t *peer, const bt_conn_state_t state);
+struct bt_conn *bt_conn_lookup_state_le(const bt_addr_le_t *peer,
+                                        const bt_conn_state_t state);
 
 /* Set connection object in certain state and perform action related to state */
 void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state);
 
-int bt_conn_le_conn_update(struct bt_conn *conn, const struct bt_le_conn_param *param);
+int bt_conn_le_conn_update(struct bt_conn *conn,
+                           const struct bt_le_conn_param *param);
 
 void notify_remote_info(struct bt_conn *conn);
 
 void notify_le_param_updated(struct bt_conn *conn);
 
+void notify_le_phy_updated(struct bt_conn *conn, u8_t tx_phy, u8_t rx_phy);
+
 bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param);
 
 #if defined(CONFIG_BT_SMP)
 /* rand and ediv should be in BT order */
-int bt_conn_le_start_encryption(struct bt_conn *conn, u8_t rand[8], u8_t ediv[2], const u8_t *ltk, size_t len);
+int bt_conn_le_start_encryption(struct bt_conn *conn, u8_t rand[8],
+                                u8_t ediv[2], const u8_t *ltk, size_t len);
 
 /* Notify higher layers that RPA was resolved */
 void bt_conn_identity_resolved(struct bt_conn *conn);
@@ -281,27 +284,41 @@ void bt_conn_security_changed(struct bt_conn *conn, enum bt_security_err err);
 
 /* Prepare a PDU to be sent over a connection */
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *bt_conn_create_pdu_timeout_debug(struct net_buf_pool *pool, size_t reserve, s32_t timeout, const char *func, int line);
-#define bt_conn_create_pdu_timeout(_pool, _reserve, _timeout) bt_conn_create_pdu_timeout_debug(_pool, _reserve, _timeout, __func__, __LINE__)
-
-#define bt_conn_create_pdu(_pool, _reserve) bt_conn_create_pdu_timeout_debug(_pool, _reserve, K_FOREVER, __func__, __line__)
+struct net_buf *bt_conn_create_pdu_timeout_debug(struct net_buf_pool *pool,
+                                                 size_t reserve, s32_t timeout,
+                                                 const char *func, int line);
+#define bt_conn_create_pdu_timeout(_pool, _reserve, _timeout)   \
+    bt_conn_create_pdu_timeout_debug(_pool, _reserve, _timeout, \
+                                     __func__, __LINE__)
+
+#define bt_conn_create_pdu(_pool, _reserve)                      \
+    bt_conn_create_pdu_timeout_debug(_pool, _reserve, K_FOREVER, \
+                                     __func__, __line__)
 #else
-struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool, size_t reserve, s32_t timeout);
+struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool,
+                                           size_t reserve, s32_t timeout);
 
-#define bt_conn_create_pdu(_pool, _reserve) bt_conn_create_pdu_timeout(_pool, _reserve, K_FOREVER)
+#define bt_conn_create_pdu(_pool, _reserve) \
+    bt_conn_create_pdu_timeout(_pool, _reserve, K_FOREVER)
 #endif
 
 /* Prepare a PDU to be sent over a connection */
 #if defined(CONFIG_NET_BUF_LOG)
-struct net_buf *bt_conn_create_frag_timeout_debug(size_t reserve, s32_t timeout, const char *func, int line);
+struct net_buf *bt_conn_create_frag_timeout_debug(size_t reserve, s32_t timeout,
+                                                  const char *func, int line);
 
-#define bt_conn_create_frag_timeout(_reserve, _timeout) bt_conn_create_frag_timeout_debug(_reserve, _timeout, __func__, __LINE__)
+#define bt_conn_create_frag_timeout(_reserve, _timeout)   \
+    bt_conn_create_frag_timeout_debug(_reserve, _timeout, \
+                                      __func__, __LINE__)
 
-#define bt_conn_create_frag(_reserve) bt_conn_create_frag_timeout_debug(_reserve, K_FOREVER, __func__, __LINE__)
+#define bt_conn_create_frag(_reserve)                      \
+    bt_conn_create_frag_timeout_debug(_reserve, K_FOREVER, \
+                                      __func__, __LINE__)
 #else
 struct net_buf *bt_conn_create_frag_timeout(size_t reserve, s32_t timeout);
 
-#define bt_conn_create_frag(_reserve) bt_conn_create_frag_timeout(_reserve, K_FOREVER)
+#define bt_conn_create_frag(_reserve) \
+    bt_conn_create_frag_timeout(_reserve, K_FOREVER)
 #endif
 
 /* Initialize connection management */
@@ -311,8 +328,13 @@ int bt_conn_init(void);
 struct k_sem *bt_conn_get_pkts(struct bt_conn *conn);
 
 /* k_poll related helpers for the TX thread */
-int  bt_conn_prepare_events(struct k_poll_event events[]);
+int bt_conn_prepare_events(struct k_poll_event events[]);
+
+#if (BFLB_BT_CO_THREAD)
+void bt_conn_process_tx(struct bt_conn *conn, struct net_buf *tx_buf);
+#else
 void bt_conn_process_tx(struct bt_conn *conn);
+#endif
 
 #if defined(BFLB_BLE)
 /** @brief Get connection handle for a connection.
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/crypto.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/crypto.c
index b1eeb8390..5bcf4b2e8 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/crypto.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/crypto.c
@@ -5,19 +5,19 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
 #include 
+#include 
 
-#include 
 #include 
+#include 
 
 #include 
-#include 
 #include 
+#include 
 
+#include 
 #include 
 #include 
-#include 
 #include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE)
@@ -28,140 +28,132 @@
 
 static struct tc_hmac_prng_struct prng;
 
-static int prng_reseed(struct tc_hmac_prng_struct *h)
-{
-    u8_t seed[32];
-    s64_t extra;
-    int ret, i;
+static int prng_reseed(struct tc_hmac_prng_struct *h) {
+  u8_t  seed[32];
+  s64_t extra;
+  int   ret, i;
 
-    for (i = 0; i < (sizeof(seed) / 8); i++) {
-        struct bt_hci_rp_le_rand *rp;
-        struct net_buf *rsp;
+  for (i = 0; i < (sizeof(seed) / 8); i++) {
+    struct bt_hci_rp_le_rand *rp;
+    struct net_buf           *rsp;
 
-        ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
-        if (ret) {
-            return ret;
-        }
+    ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
+    if (ret) {
+      return ret;
+    }
 
-        rp = (void *)rsp->data;
-        memcpy(&seed[i * 8], rp->rand, 8);
+    rp = (void *)rsp->data;
+    memcpy(&seed[i * 8], rp->rand, 8);
 
-        net_buf_unref(rsp);
-    }
+    net_buf_unref(rsp);
+  }
 
-    extra = k_uptime_get();
+  extra = k_uptime_get();
 
-    ret = tc_hmac_prng_reseed(h, seed, sizeof(seed), (u8_t *)&extra,
-                              sizeof(extra));
-    if (ret == TC_CRYPTO_FAIL) {
-        BT_ERR("Failed to re-seed PRNG");
-        return -EIO;
-    }
+  ret = tc_hmac_prng_reseed(h, seed, sizeof(seed), (u8_t *)&extra, sizeof(extra));
+  if (ret == TC_CRYPTO_FAIL) {
+    BT_ERR("Failed to re-seed PRNG");
+    return -EIO;
+  }
 
-    return 0;
+  return 0;
 }
 
-int prng_init(void)
-{
-    struct bt_hci_rp_le_rand *rp;
-    struct net_buf *rsp;
-    int ret;
+int prng_init(void) {
+  struct bt_hci_rp_le_rand *rp;
+  struct net_buf           *rsp;
+  int                       ret;
 
-    /* Check first that HCI_LE_Rand is supported */
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 7)) {
-        return -ENOTSUP;
-    }
+  /* Check first that HCI_LE_Rand is supported */
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 7)) {
+    return -ENOTSUP;
+  }
 
-    ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
-    if (ret) {
-        return ret;
-    }
+  ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
+  if (ret) {
+    return ret;
+  }
 
-    rp = (void *)rsp->data;
+  rp = (void *)rsp->data;
 
-    ret = tc_hmac_prng_init(&prng, rp->rand, sizeof(rp->rand));
+  ret = tc_hmac_prng_init(&prng, rp->rand, sizeof(rp->rand));
 
-    net_buf_unref(rsp);
+  net_buf_unref(rsp);
 
-    if (ret == TC_CRYPTO_FAIL) {
-        BT_ERR("Failed to initialize PRNG");
-        return -EIO;
-    }
+  if (ret == TC_CRYPTO_FAIL) {
+    BT_ERR("Failed to initialize PRNG");
+    return -EIO;
+  }
 
-    /* re-seed is needed after init */
-    return prng_reseed(&prng);
+  /* re-seed is needed after init */
+  return prng_reseed(&prng);
 }
 
-int bt_rand(void *buf, size_t len)
-{
+int bt_rand(void *buf, size_t len) {
 #if !defined(CONFIG_BT_GEN_RANDOM_BY_SW)
-    k_get_random_byte_array(buf, len);
-    return 0;
+  k_get_random_byte_array(buf, len);
+  return 0;
 #else
-    int ret;
-    ret = tc_hmac_prng_generate(buf, len, &prng);
-    if (ret == TC_HMAC_PRNG_RESEED_REQ) {
-        ret = prng_reseed(&prng);
-        if (ret) {
-            return ret;
-        }
-
-        ret = tc_hmac_prng_generate(buf, len, &prng);
+  int ret;
+  ret = tc_hmac_prng_generate(buf, len, &prng);
+  if (ret == TC_HMAC_PRNG_RESEED_REQ) {
+    ret = prng_reseed(&prng);
+    if (ret) {
+      return ret;
     }
 
-    if (ret == TC_CRYPTO_SUCCESS) {
-        return 0;
-    }
+    ret = tc_hmac_prng_generate(buf, len, &prng);
+  }
 
-    return -EIO;
+  if (ret == TC_CRYPTO_SUCCESS) {
+    return 0;
+  }
+
+  return -EIO;
 #endif
 }
 
-int bt_encrypt_le(const u8_t key[16], const u8_t plaintext[16],
-                  u8_t enc_data[16])
-{
-    struct tc_aes_key_sched_struct s;
-    u8_t tmp[16];
+int bt_encrypt_le(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]) {
+  struct tc_aes_key_sched_struct s;
+  u8_t                           tmp[16];
 
-    BT_DBG("key %s", bt_hex(key, 16));
-    BT_DBG("plaintext %s", bt_hex(plaintext, 16));
+  BT_DBG("key %s", bt_hex(key, 16));
+  BT_DBG("plaintext %s", bt_hex(plaintext, 16));
 
-    sys_memcpy_swap(tmp, key, 16);
+  sys_memcpy_swap(tmp, key, 16);
 
-    if (tc_aes128_set_encrypt_key(&s, tmp) == TC_CRYPTO_FAIL) {
-        return -EINVAL;
-    }
+  if (tc_aes128_set_encrypt_key(&s, tmp) == TC_CRYPTO_FAIL) {
+    return -EINVAL;
+  }
 
-    sys_memcpy_swap(tmp, plaintext, 16);
+  sys_memcpy_swap(tmp, plaintext, 16);
 
-    if (tc_aes_encrypt(enc_data, tmp, &s) == TC_CRYPTO_FAIL) {
-        return -EINVAL;
-    }
+  if (tc_aes_encrypt(enc_data, tmp, &s) == TC_CRYPTO_FAIL) {
+    return -EINVAL;
+  }
 
-    sys_mem_swap(enc_data, 16);
+  sys_mem_swap(enc_data, 16);
 
-    BT_DBG("enc_data %s", bt_hex(enc_data, 16));
+  BT_DBG("enc_data %s", bt_hex(enc_data, 16));
 
-    return 0;
+  return 0;
 }
 
-int bt_encrypt_be(const u8_t key[16], const u8_t plaintext[16],
-                  u8_t enc_data[16])
-{
-    struct tc_aes_key_sched_struct s;
+int bt_encrypt_be(const u8_t key[16], const u8_t plaintext[16], u8_t enc_data[16]) {
+  struct tc_aes_key_sched_struct s;
 
-    BT_DBG("key %s", bt_hex(key, 16));
-    BT_DBG("plaintext %s", bt_hex(plaintext, 16));
+  BT_DBG("key %s", bt_hex(key, 16));
+  BT_DBG("plaintext %s", bt_hex(plaintext, 16));
 
-    if (tc_aes128_set_encrypt_key(&s, key) == TC_CRYPTO_FAIL) {
-        return -EINVAL;
-    }
+  if (tc_aes128_set_encrypt_key(&s, key) == TC_CRYPTO_FAIL) {
+    return -EINVAL;
+  }
 
-    if (tc_aes_encrypt(enc_data, plaintext, &s) == TC_CRYPTO_FAIL) {
-        return -EINVAL;
-    }
+  if (tc_aes_encrypt(enc_data, plaintext, &s) == TC_CRYPTO_FAIL) {
+    return -EINVAL;
+  }
 
-    BT_DBG("enc_data %s", bt_hex(enc_data, 16));
+  BT_DBG("enc_data %s", bt_hex(enc_data, 16));
 
-    return 0;
+  return 0;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/ecc.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/ecc.h
index 70908c7fa..2b7f2bbf6 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/ecc.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/ecc.h
@@ -1,5 +1,5 @@
 /* ecc.h - ECDH helpers */
-
+#include "types.h"
 /*
  * Copyright (c) 2016 Intel Corporation
  *
@@ -8,17 +8,17 @@
 
 /*  @brief Container for public key callback */
 struct bt_pub_key_cb {
-    /** @brief Callback type for Public Key generation.
-	 *
-	 *  Used to notify of the local public key or that the local key is not
-	 *  available (either because of a failure to read it or because it is
-	 *  being regenerated).
-	 *
-	 *  @param key The local public key, or NULL in case of no key.
-	 */
-    void (*func)(const u8_t key[64]);
+  /** @brief Callback type for Public Key generation.
+   *
+   *  Used to notify of the local public key or that the local key is not
+   *  available (either because of a failure to read it or because it is
+   *  being regenerated).
+   *
+   *  @param key The local public key, or NULL in case of no key.
+   */
+  void (*func)(const uint8_t key[64]);
 
-    struct bt_pub_key_cb *_next;
+  struct bt_pub_key_cb *_next;
 };
 
 /*  @brief Generate a new Public Key.
@@ -40,7 +40,7 @@ int bt_pub_key_gen(struct bt_pub_key_cb *cb);
  *
  *  @return Current key, or NULL if not available.
  */
-const u8_t *bt_pub_key_get(void);
+const uint8_t *bt_pub_key_get(void);
 
 /*  @typedef bt_dh_key_cb_t
  *  @brief Callback type for DH Key calculation.
@@ -49,7 +49,7 @@ const u8_t *bt_pub_key_get(void);
  *
  *  @param key The DH Key, or NULL in case of failure.
  */
-typedef void (*bt_dh_key_cb_t)(const u8_t key[32]);
+typedef void (*bt_dh_key_cb_t)(const uint8_t key[32]);
 
 /*  @brief Calculate a DH Key from a remote Public Key.
  *
@@ -60,4 +60,4 @@ typedef void (*bt_dh_key_cb_t)(const u8_t key[32]);
  *
  *  @return Zero on success or negative error code otherwise
  */
-int bt_dh_key_gen(const u8_t remote_pk[64], bt_dh_key_cb_t cb);
+int bt_dh_key_gen(const uint8_t remote_pk[64], bt_dh_key_cb_t cb);
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c
index e6ed08ae4..43b82d8e1 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/gatt.c
@@ -6,29 +6,31 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
-#include 
-#include 
 #include 
+#include 
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
 
 #include 
 
 #if defined(CONFIG_BT_GATT_CACHING)
 #include 
 #include 
-#include 
+
 #include 
+
+#include 
 #include 
 #endif /* CONFIG_BT_GATT_CACHING */
-#include 
 #include 
-#include 
 #include 
 #include 
+#include 
+#include 
 #if defined(BFLB_BLE)
 #include "ble_config.h"
 #include 
@@ -49,12 +51,15 @@ extern u8_t event_flag;
 #include "log.h"
 
 #include "hci_core.h"
+
 #include "conn_internal.h"
 #include "keys.h"
 #include "l2cap_internal.h"
-#include "att_internal.h"
-#include "smp.h"
 #include "settings.h"
+#include "smp.h"
+
+#include "att_internal.h"
+
 #include "gatt_internal.h"
 
 #define SC_TIMEOUT      K_MSEC(10)
@@ -66,12 +71,19 @@ static u16_t last_static_handle;
 
 /* Persistent storage format for GATT CCC */
 struct ccc_store {
-    u16_t handle;
-    u16_t value;
+  u16_t handle;
+  u16_t value;
 };
 
 #if defined(CONFIG_BT_GATT_CLIENT)
 static sys_slist_t subscriptions;
+#if defined(BFLB_BLE_NOTIFY_ALL)
+bt_notification_all_cb_t gatt_notify_all_cb;
+#endif
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+uint8_t    discover_ongoing = BT_GATT_ITER_STOP;
+extern int bt_gatt_discover_continue(struct bt_conn *conn, struct bt_gatt_discover_params *params);
+#endif
 #endif /* CONFIG_BT_GATT_CLIENT */
 
 static const u16_t gap_appearance = CONFIG_BT_DEVICE_APPEARANCE;
@@ -86,91 +98,69 @@ static atomic_t init;
 bt_gatt_mtu_changed_cb_t gatt_mtu_changed_cb;
 #endif
 
-static ssize_t read_name(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                         void *buf, u16_t len, u16_t offset)
-{
-    const char *name = bt_get_name();
+static ssize_t read_name(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  const char *name = bt_get_name();
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, name,
-                             strlen(name));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, name, strlen(name));
 }
 
 #if defined(CONFIG_BT_DEVICE_NAME_GATT_WRITABLE)
 
-static ssize_t write_name(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                          const void *buf, u16_t len, u16_t offset,
-                          u8_t flags)
-{
-    char value[CONFIG_BT_DEVICE_NAME_MAX] = {};
+static ssize_t write_name(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) {
+  char value[CONFIG_BT_DEVICE_NAME_MAX] = {};
 
-    if (offset) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
-    }
+  if (offset) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
+  }
 
-    if (len >= sizeof(value)) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
-    }
+  if (len >= sizeof(value)) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
+  }
 
-    memcpy(value, buf, len);
+  memcpy(value, buf, len);
 
-    bt_set_name(value);
+  bt_set_name(value);
 
-    return len;
+  return len;
 }
 
 #endif /* CONFIG_BT_DEVICE_NAME_GATT_WRITABLE */
 
-static ssize_t read_appearance(struct bt_conn *conn,
-                               const struct bt_gatt_attr *attr, void *buf,
-                               u16_t len, u16_t offset)
-{
-    u16_t appearance = sys_cpu_to_le16(gap_appearance);
+static ssize_t read_appearance(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  u16_t appearance = sys_cpu_to_le16(gap_appearance);
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &appearance,
-                             sizeof(appearance));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &appearance, sizeof(appearance));
 }
 
 #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS)
 /* This checks if the range entered is valid */
-BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MIN_INT > 3200 &&
-               CONFIG_BT_PERIPHERAL_PREF_MIN_INT < 0xffff));
-BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MAX_INT > 3200 &&
-               CONFIG_BT_PERIPHERAL_PREF_MAX_INT < 0xffff));
-BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT > 3200 &&
-               CONFIG_BT_PERIPHERAL_PREF_TIMEOUT < 0xffff));
-BUILD_ASSERT((CONFIG_BT_PERIPHERAL_PREF_MIN_INT == 0xffff) ||
-             (CONFIG_BT_PERIPHERAL_PREF_MIN_INT <=
-              CONFIG_BT_PERIPHERAL_PREF_MAX_INT));
-
-static ssize_t read_ppcp(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                         void *buf, u16_t len, u16_t offset)
-{
-    struct __packed {
-        u16_t min_int;
-        u16_t max_int;
-        u16_t latency;
-        u16_t timeout;
-    } ppcp;
-
-    ppcp.min_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MIN_INT);
-    ppcp.max_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MAX_INT);
-    ppcp.latency = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY);
-    ppcp.timeout = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT);
-
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &ppcp,
-                             sizeof(ppcp));
+BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MIN_INT > 3200 && CONFIG_BT_PERIPHERAL_PREF_MIN_INT < 0xffff));
+BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MAX_INT > 3200 && CONFIG_BT_PERIPHERAL_PREF_MAX_INT < 0xffff));
+BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT > 3200 && CONFIG_BT_PERIPHERAL_PREF_TIMEOUT < 0xffff));
+BUILD_ASSERT((CONFIG_BT_PERIPHERAL_PREF_MIN_INT == 0xffff) || (CONFIG_BT_PERIPHERAL_PREF_MIN_INT <= CONFIG_BT_PERIPHERAL_PREF_MAX_INT));
+
+static ssize_t read_ppcp(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct __packed {
+    u16_t min_int;
+    u16_t max_int;
+    u16_t latency;
+    u16_t timeout;
+  } ppcp;
+
+  ppcp.min_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MIN_INT);
+  ppcp.max_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MAX_INT);
+  ppcp.latency = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY);
+  ppcp.timeout = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT);
+
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &ppcp, sizeof(ppcp));
 }
 #endif
 
 #if defined(CONFIG_BT_CENTRAL) && defined(CONFIG_BT_PRIVACY)
-static ssize_t read_central_addr_res(struct bt_conn *conn,
-                                     const struct bt_gatt_attr *attr, void *buf,
-                                     u16_t len, u16_t offset)
-{
-    u8_t central_addr_res = BT_GATT_CENTRAL_ADDR_RES_SUPP;
+static ssize_t read_central_addr_res(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  u8_t central_addr_res = BT_GATT_CENTRAL_ADDR_RES_SUPP;
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset,
-                             ¢ral_addr_res, sizeof(central_addr_res));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, ¢ral_addr_res, sizeof(central_addr_res));
 }
 #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_PRIVACY */
 
@@ -183,24 +173,16 @@ BT_GATT_SERVICE_DEFINE(_2_gap_svc,
 
 #if defined(CONFIG_BT_DEVICE_NAME_GATT_WRITABLE)
     /* Require pairing for writes to device name */
-    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME,
-                           BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
-                           BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
-                           read_name, write_name, bt_dev.name),
+    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, read_name, write_name, bt_dev.name),
 #else
-                       BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ,
-                                              BT_GATT_PERM_READ, read_name, NULL, NULL),
+                       BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_name, NULL, NULL),
 #endif /* CONFIG_BT_DEVICE_NAME_GATT_WRITABLE */
-    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_APPEARANCE, BT_GATT_CHRC_READ,
-                           BT_GATT_PERM_READ, read_appearance, NULL, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_APPEARANCE, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_appearance, NULL, NULL),
 #if defined(CONFIG_BT_CENTRAL) && defined(CONFIG_BT_PRIVACY)
-    BT_GATT_CHARACTERISTIC(BT_UUID_CENTRAL_ADDR_RES,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_central_addr_res, NULL, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_CENTRAL_ADDR_RES, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_central_addr_res, NULL, NULL),
 #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_PRIVACY */
 #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS)
-    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_PPCP, BT_GATT_CHRC_READ,
-                           BT_GATT_PERM_READ, read_ppcp, NULL, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_GAP_PPCP, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_ppcp, NULL, NULL),
 #endif
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
 };
@@ -213,508 +195,458 @@ static struct bt_gatt_service gap_svc = BT_GATT_SERVICE(gap_attrs);
 #endif
 
 struct sc_data {
-    u16_t start;
-    u16_t end;
+  u16_t start;
+  u16_t end;
 } __packed;
 
 struct gatt_sc_cfg {
-    u8_t id;
-    bt_addr_le_t peer;
-    struct {
-        u16_t start;
-        u16_t end;
-    } data;
+  u8_t         id;
+  bt_addr_le_t peer;
+  struct {
+    u16_t start;
+    u16_t end;
+  } data;
 };
 
 #define SC_CFG_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN)
 static struct gatt_sc_cfg sc_cfg[SC_CFG_MAX];
 BUILD_ASSERT(sizeof(struct sc_data) == sizeof(sc_cfg[0].data));
 
-static struct gatt_sc_cfg *find_sc_cfg(u8_t id, bt_addr_le_t *addr)
-{
-    BT_DBG("id: %u, addr: %s", id, bt_addr_le_str(addr));
+static struct gatt_sc_cfg *find_sc_cfg(u8_t id, bt_addr_le_t *addr) {
+  BT_DBG("id: %u, addr: %s", id, bt_addr_le_str(addr));
 
-    for (size_t i = 0; i < ARRAY_SIZE(sc_cfg); i++) {
-        if (id == sc_cfg[i].id &&
-            !bt_addr_le_cmp(&sc_cfg[i].peer, addr)) {
-            return &sc_cfg[i];
-        }
+  for (size_t i = 0; i < ARRAY_SIZE(sc_cfg); i++) {
+    if (id == sc_cfg[i].id && !bt_addr_le_cmp(&sc_cfg[i].peer, addr)) {
+      return &sc_cfg[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-static void sc_store(struct gatt_sc_cfg *cfg)
-{
-    char key[BT_SETTINGS_KEY_MAX];
-    int err;
+static void sc_store(struct gatt_sc_cfg *cfg) {
+  char key[BT_SETTINGS_KEY_MAX];
+  int  err;
 
-    if (cfg->id) {
-        char id_str[4];
+  if (cfg->id) {
+    char id_str[4];
 
-        u8_to_dec(id_str, sizeof(id_str), cfg->id);
-        bt_settings_encode_key(key, sizeof(key), "sc",
-                               &cfg->peer, id_str);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "sc",
-                               &cfg->peer, NULL);
-    }
+    u8_to_dec(id_str, sizeof(id_str), cfg->id);
+    bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, id_str);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, NULL);
+  }
 
-    err = settings_save_one(key, (u8_t *)&cfg->data, sizeof(cfg->data));
-    if (err) {
-        BT_ERR("failed to store SC (err %d)", err);
-        return;
-    }
+  err = settings_save_one(key, (u8_t *)&cfg->data, sizeof(cfg->data));
+  if (err) {
+    BT_ERR("failed to store SC (err %d)", err);
+    return;
+  }
 
-    BT_DBG("stored SC for %s (%s, 0x%04x-0x%04x)",
-           bt_addr_le_str(&cfg->peer), log_strdup(key), cfg->data.start,
-           cfg->data.end);
+  BT_DBG("stored SC for %s (%s, 0x%04x-0x%04x)", bt_addr_le_str(&cfg->peer), log_strdup(key), cfg->data.start, cfg->data.end);
 }
 
-static void sc_clear(struct gatt_sc_cfg *cfg)
-{
-    BT_DBG("peer %s", bt_addr_le_str(&cfg->peer));
+static void sc_clear(struct gatt_sc_cfg *cfg) {
+  BT_DBG("peer %s", bt_addr_le_str(&cfg->peer));
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        bool modified = false;
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    bool modified = false;
 
-        if (cfg->data.start || cfg->data.end) {
-            modified = true;
-        }
+    if (cfg->data.start || cfg->data.end) {
+      modified = true;
+    }
 
-        if (modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) {
-            char key[BT_SETTINGS_KEY_MAX];
-            int err;
-
-            if (cfg->id) {
-                char id_str[4];
-
-                u8_to_dec(id_str, sizeof(id_str), cfg->id);
-                bt_settings_encode_key(key, sizeof(key), "sc",
-                                       &cfg->peer, id_str);
-            } else {
-                bt_settings_encode_key(key, sizeof(key), "sc",
-                                       &cfg->peer, NULL);
-            }
-
-            err = settings_delete(key);
-            if (err) {
-                BT_ERR("failed to delete SC (err %d)", err);
-            } else {
-                BT_DBG("deleted SC for %s (%s)",
-                       bt_addr_le_str(&cfg->peer),
-                       log_strdup(key));
-            }
-        }
+    if (modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) {
+      char key[BT_SETTINGS_KEY_MAX];
+      int  err;
+
+      if (cfg->id) {
+        char id_str[4];
+
+        u8_to_dec(id_str, sizeof(id_str), cfg->id);
+        bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, id_str);
+      } else {
+        bt_settings_encode_key(key, sizeof(key), "sc", &cfg->peer, NULL);
+      }
+
+      err = settings_delete(key);
+      if (err) {
+        BT_ERR("failed to delete SC (err %d)", err);
+      } else {
+        BT_DBG("deleted SC for %s (%s)", bt_addr_le_str(&cfg->peer), log_strdup(key));
+      }
     }
+  }
 
-    memset(cfg, 0, sizeof(*cfg));
+  memset(cfg, 0, sizeof(*cfg));
 }
 
-static void sc_reset(struct gatt_sc_cfg *cfg)
-{
-    BT_DBG("peer %s", bt_addr_le_str(&cfg->peer));
+static void sc_reset(struct gatt_sc_cfg *cfg) {
+  BT_DBG("peer %s", bt_addr_le_str(&cfg->peer));
 
-    memset(&cfg->data, 0, sizeof(cfg->data));
+  memset(&cfg->data, 0, sizeof(cfg->data));
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        sc_store(cfg);
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    sc_store(cfg);
+  }
 }
 
-static bool update_range(u16_t *start, u16_t *end, u16_t new_start,
-                         u16_t new_end)
-{
-    BT_DBG("start 0x%04x end 0x%04x new_start 0x%04x new_end 0x%04x",
-           *start, *end, new_start, new_end);
+static bool update_range(u16_t *start, u16_t *end, u16_t new_start, u16_t new_end) {
+  BT_DBG("start 0x%04x end 0x%04x new_start 0x%04x new_end 0x%04x", *start, *end, new_start, new_end);
 
-    /* Check if inside existing range */
-    if (new_start >= *start && new_end <= *end) {
-        return false;
-    }
+  /* Check if inside existing range */
+  if (new_start >= *start && new_end <= *end) {
+    return false;
+  }
 
-    /* Update range */
-    if (*start > new_start) {
-        *start = new_start;
-    }
+  /* Update range */
+  if (*start > new_start) {
+    *start = new_start;
+  }
 
-    if (*end < new_end) {
-        *end = new_end;
-    }
+  if (*end < new_end) {
+    *end = new_end;
+  }
 
-    return true;
+  return true;
 }
 
-static void sc_save(u8_t id, bt_addr_le_t *peer, u16_t start, u16_t end)
-{
-    struct gatt_sc_cfg *cfg;
-    bool modified = false;
+static void sc_save(u8_t id, bt_addr_le_t *peer, u16_t start, u16_t end) {
+  struct gatt_sc_cfg *cfg;
+  bool                modified = false;
 
-    BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(peer), start,
-           end);
+  BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(peer), start, end);
 
-    cfg = find_sc_cfg(id, peer);
+  cfg = find_sc_cfg(id, peer);
+  if (!cfg) {
+    /* Find and initialize a free sc_cfg entry */
+    cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
     if (!cfg) {
-        /* Find and initialize a free sc_cfg entry */
-        cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
-        if (!cfg) {
-            BT_ERR("unable to save SC: no cfg left");
-            return;
-        }
-
-        cfg->id = id;
-        bt_addr_le_copy(&cfg->peer, peer);
+      BT_ERR("unable to save SC: no cfg left");
+      return;
     }
 
-    /* Check if there is any change stored */
-    if (!(cfg->data.start || cfg->data.end)) {
-        cfg->data.start = start;
-        cfg->data.end = end;
-        modified = true;
-        goto done;
-    }
+    cfg->id = id;
+    bt_addr_le_copy(&cfg->peer, peer);
+  }
 
-    modified = update_range(&cfg->data.start, &cfg->data.end, start, end);
+  /* Check if there is any change stored */
+  if (!(cfg->data.start || cfg->data.end)) {
+    cfg->data.start = start;
+    cfg->data.end   = end;
+    modified        = true;
+    goto done;
+  }
+
+  modified = update_range(&cfg->data.start, &cfg->data.end, start, end);
 
 done:
-    if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
-        modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) {
-        sc_store(cfg);
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS) && modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) {
+    sc_store(cfg);
+  }
 }
 
-static bool sc_ccc_cfg_write(struct bt_conn *conn,
-                             const struct bt_gatt_attr *attr,
-                             u16_t value)
-{
-    BT_DBG("value 0x%04x", value);
+static bool sc_ccc_cfg_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, u16_t value) {
+  BT_DBG("value 0x%04x", value);
 
-    if (value == BT_GATT_CCC_INDICATE) {
-        /* Create a new SC configuration entry if subscribed */
-        sc_save(conn->id, &conn->le.dst, 0, 0);
-    } else {
-        struct gatt_sc_cfg *cfg;
+  if (value == BT_GATT_CCC_INDICATE) {
+    /* Create a new SC configuration entry if subscribed */
+    sc_save(conn->id, &conn->le.dst, 0, 0);
+  } else {
+    struct gatt_sc_cfg *cfg;
 
-        /* Clear SC configuration if unsubscribed */
-        cfg = find_sc_cfg(conn->id, &conn->le.dst);
-        if (cfg) {
-            sc_clear(cfg);
-        }
+    /* Clear SC configuration if unsubscribed */
+    cfg = find_sc_cfg(conn->id, &conn->le.dst);
+    if (cfg) {
+      sc_clear(cfg);
     }
+  }
 
-    return true;
+  return true;
 }
 
-static struct _bt_gatt_ccc sc_ccc = BT_GATT_CCC_INITIALIZER(NULL,
-                                                            sc_ccc_cfg_write,
-                                                            NULL);
+static struct _bt_gatt_ccc sc_ccc = BT_GATT_CCC_INITIALIZER(NULL, sc_ccc_cfg_write, NULL);
 
 #if defined(CONFIG_BT_GATT_CACHING)
 enum {
-    CF_CHANGE_AWARE, /* Client is changed aware */
-    CF_OUT_OF_SYNC,  /* Client is out of sync */
+  CF_CHANGE_AWARE, /* Client is changed aware */
+  CF_OUT_OF_SYNC,  /* Client is out of sync */
 
-    /* Total number of flags - must be at the end of the enum */
-    CF_NUM_FLAGS,
+  /* Total number of flags - must be at the end of the enum */
+  CF_NUM_FLAGS,
 };
 
 #define CF_ROBUST_CACHING(_cfg) (_cfg->data[0] & BIT(0))
 
 struct gatt_cf_cfg {
-    u8_t id;
-    bt_addr_le_t peer;
-    u8_t data[1];
-    ATOMIC_DEFINE(flags, CF_NUM_FLAGS);
+  u8_t         id;
+  bt_addr_le_t peer;
+  u8_t         data[1];
+  ATOMIC_DEFINE(flags, CF_NUM_FLAGS);
 };
 
 #define CF_CFG_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN)
 static struct gatt_cf_cfg cf_cfg[CF_CFG_MAX] = {};
 
-static struct gatt_cf_cfg *find_cf_cfg(struct bt_conn *conn)
-{
-    int i;
-
-    for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
-        if (!conn) {
-            if (!bt_addr_le_cmp(&cf_cfg[i].peer, BT_ADDR_LE_ANY)) {
-                return &cf_cfg[i];
-            }
-        } else if (!bt_conn_addr_le_cmp(conn, &cf_cfg[i].peer)) {
-            return &cf_cfg[i];
-        }
+static struct gatt_cf_cfg *find_cf_cfg(struct bt_conn *conn) {
+  int i;
+
+  for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
+    if (!conn) {
+      if (!bt_addr_le_cmp(&cf_cfg[i].peer, BT_ADDR_LE_ANY)) {
+        return &cf_cfg[i];
+      }
+    } else if (!bt_conn_addr_le_cmp(conn, &cf_cfg[i].peer)) {
+      return &cf_cfg[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-static ssize_t cf_read(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                       void *buf, u16_t len, u16_t offset)
-{
-    struct gatt_cf_cfg *cfg;
-    u8_t data[1] = {};
+static ssize_t cf_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct gatt_cf_cfg *cfg;
+  u8_t                data[1] = {};
 
-    cfg = find_cf_cfg(conn);
-    if (cfg) {
-        memcpy(data, cfg->data, sizeof(data));
-    }
+  cfg = find_cf_cfg(conn);
+  if (cfg) {
+    memcpy(data, cfg->data, sizeof(data));
+  }
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, data,
-                             sizeof(data));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, data, sizeof(data));
 }
 
-static bool cf_set_value(struct gatt_cf_cfg *cfg, const u8_t *value, u16_t len)
-{
-    u16_t i;
-    u8_t last_byte = 1U;
-    u8_t last_bit = 1U;
-
-    /* Validate the bits */
-    for (i = 0U; i < len && i < last_byte; i++) {
-        u8_t chg_bits = value[i] ^ cfg->data[i];
-        u8_t bit;
-
-        for (bit = 0U; bit < last_bit; bit++) {
-            /* A client shall never clear a bit it has set */
-            if ((BIT(bit) & chg_bits) &&
-                (BIT(bit) & cfg->data[i])) {
-                return false;
-            }
-        }
-    }
+static bool cf_set_value(struct gatt_cf_cfg *cfg, const u8_t *value, u16_t len) {
+  u16_t i;
+  u8_t  last_byte = 1U;
+  u8_t  last_bit  = 1U;
 
-    /* Set the bits for each octect */
-    for (i = 0U; i < len && i < last_byte; i++) {
-        cfg->data[i] |= value[i] & ((1 << last_bit) - 1);
-        BT_DBG("byte %u: data 0x%02x value 0x%02x", i, cfg->data[i],
-               value[i]);
+  /* Validate the bits */
+  for (i = 0U; i < len && i < last_byte; i++) {
+    u8_t chg_bits = value[i] ^ cfg->data[i];
+    u8_t bit;
+
+    for (bit = 0U; bit < last_bit; bit++) {
+      /* A client shall never clear a bit it has set */
+      if ((BIT(bit) & chg_bits) && (BIT(bit) & cfg->data[i])) {
+        return false;
+      }
     }
+  }
 
-    return true;
+  /* Set the bits for each octect */
+  for (i = 0U; i < len && i < last_byte; i++) {
+    cfg->data[i] |= value[i] & ((1 << last_bit) - 1);
+    BT_DBG("byte %u: data 0x%02x value 0x%02x", i, cfg->data[i], value[i]);
+  }
+
+  return true;
 }
 
-static ssize_t cf_write(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                        const void *buf, u16_t len, u16_t offset, u8_t flags)
-{
-    struct gatt_cf_cfg *cfg;
-    const u8_t *value = buf;
+static ssize_t cf_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) {
+  struct gatt_cf_cfg *cfg;
+  const u8_t         *value = buf;
 
-    if (offset > sizeof(cfg->data)) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
-    }
+  if (offset > sizeof(cfg->data)) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
+  }
 
-    if (offset + len > sizeof(cfg->data)) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
-    }
+  if (offset + len > sizeof(cfg->data)) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
+  }
 
-    cfg = find_cf_cfg(conn);
-    if (!cfg) {
-        cfg = find_cf_cfg(NULL);
-    }
+  cfg = find_cf_cfg(conn);
+  if (!cfg) {
+    cfg = find_cf_cfg(NULL);
+  }
 
-    if (!cfg) {
-        BT_WARN("No space to store Client Supported Features");
-        return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
-    }
+  if (!cfg) {
+    BT_WARN("No space to store Client Supported Features");
+    return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
+  }
 
-    BT_DBG("handle 0x%04x len %u", attr->handle, len);
+  BT_DBG("handle 0x%04x len %u", attr->handle, len);
 
-    if (!cf_set_value(cfg, value, len)) {
-        return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
-    }
+  if (!cf_set_value(cfg, value, len)) {
+    return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
+  }
 
-    bt_addr_le_copy(&cfg->peer, &conn->le.dst);
-    atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
+  bt_addr_le_copy(&cfg->peer, &conn->le.dst);
+  atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
 
-    return len;
+  return len;
 }
 
-static u8_t db_hash[16];
+static u8_t           db_hash[16];
 struct k_delayed_work db_hash_work;
 
 struct gen_hash_state {
-    struct tc_cmac_struct state;
-    int err;
+  struct tc_cmac_struct state;
+  int                   err;
 };
 
-static u8_t gen_hash_m(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct gen_hash_state *state = user_data;
-    struct bt_uuid_16 *u16;
-    u8_t data[16];
-    ssize_t len;
-    u16_t value;
-
-    if (attr->uuid->type != BT_UUID_TYPE_16)
-        return BT_GATT_ITER_CONTINUE;
-
-    u16 = (struct bt_uuid_16 *)attr->uuid;
-
-    switch (u16->val) {
-        /* Attributes to hash: handle + UUID + value */
-        case 0x2800: /* GATT Primary Service */
-        case 0x2801: /* GATT Secondary Service */
-        case 0x2802: /* GATT Include Service */
-        case 0x2803: /* GATT Characteristic */
-        case 0x2900: /* GATT Characteristic Extended Properties */
-            value = sys_cpu_to_le16(attr->handle);
-            if (tc_cmac_update(&state->state, (uint8_t *)&value,
-                               sizeof(attr->handle)) == TC_CRYPTO_FAIL) {
-                state->err = -EINVAL;
-                return BT_GATT_ITER_STOP;
-            }
-
-            value = sys_cpu_to_le16(u16->val);
-            if (tc_cmac_update(&state->state, (uint8_t *)&value,
-                               sizeof(u16->val)) == TC_CRYPTO_FAIL) {
-                state->err = -EINVAL;
-                return BT_GATT_ITER_STOP;
-            }
-
-            len = attr->read(NULL, attr, data, sizeof(data), 0);
-            if (len < 0) {
-                state->err = len;
-                return BT_GATT_ITER_STOP;
-            }
-
-            if (tc_cmac_update(&state->state, data, len) ==
-                TC_CRYPTO_FAIL) {
-                state->err = -EINVAL;
-                return BT_GATT_ITER_STOP;
-            }
-
-            break;
-        /* Attributes to hash: handle + UUID */
-        case 0x2901: /* GATT Characteristic User Descriptor */
-        case 0x2902: /* GATT Client Characteristic Configuration */
-        case 0x2903: /* GATT Server Characteristic Configuration */
-        case 0x2904: /* GATT Characteristic Presentation Format */
-        case 0x2905: /* GATT Characteristic Aggregated Format */
-            value = sys_cpu_to_le16(attr->handle);
-            if (tc_cmac_update(&state->state, (uint8_t *)&value,
-                               sizeof(attr->handle)) == TC_CRYPTO_FAIL) {
-                state->err = -EINVAL;
-                return BT_GATT_ITER_STOP;
-            }
-
-            value = sys_cpu_to_le16(u16->val);
-            if (tc_cmac_update(&state->state, (uint8_t *)&value,
-                               sizeof(u16->val)) == TC_CRYPTO_FAIL) {
-                state->err = -EINVAL;
-                return BT_GATT_ITER_STOP;
-            }
-            break;
-        default:
-            return BT_GATT_ITER_CONTINUE;
-    }
+static u8_t gen_hash_m(const struct bt_gatt_attr *attr, void *user_data) {
+  struct gen_hash_state *state = user_data;
+  struct bt_uuid_16     *u16;
+  u8_t                   data[16];
+  ssize_t                len;
+  u16_t                  value;
 
+  if (attr->uuid->type != BT_UUID_TYPE_16)
     return BT_GATT_ITER_CONTINUE;
-}
 
-static void db_hash_store(void)
-{
-    int err;
+  u16 = (struct bt_uuid_16 *)attr->uuid;
 
-    err = settings_save_one("bt/hash", &db_hash, sizeof(db_hash));
-    if (err) {
-        BT_ERR("Failed to save Database Hash (err %d)", err);
+  switch (u16->val) {
+  /* Attributes to hash: handle + UUID + value */
+  case 0x2800: /* GATT Primary Service */
+  case 0x2801: /* GATT Secondary Service */
+  case 0x2802: /* GATT Include Service */
+  case 0x2803: /* GATT Characteristic */
+  case 0x2900: /* GATT Characteristic Extended Properties */
+    value = sys_cpu_to_le16(attr->handle);
+    if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(attr->handle)) == TC_CRYPTO_FAIL) {
+      state->err = -EINVAL;
+      return BT_GATT_ITER_STOP;
     }
 
-    BT_DBG("Database Hash stored");
-}
+    value = sys_cpu_to_le16(u16->val);
+    if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(u16->val)) == TC_CRYPTO_FAIL) {
+      state->err = -EINVAL;
+      return BT_GATT_ITER_STOP;
+    }
 
-static void db_hash_gen(bool store)
-{
-    u8_t key[16] = {};
-    struct tc_aes_key_sched_struct sched;
-    struct gen_hash_state state;
+    len = attr->read(NULL, attr, data, sizeof(data), 0);
+    if (len < 0) {
+      state->err = len;
+      return BT_GATT_ITER_STOP;
+    }
 
-    if (tc_cmac_setup(&state.state, key, &sched) == TC_CRYPTO_FAIL) {
-        BT_ERR("Unable to setup AES CMAC");
-        return;
+    if (tc_cmac_update(&state->state, data, len) == TC_CRYPTO_FAIL) {
+      state->err = -EINVAL;
+      return BT_GATT_ITER_STOP;
     }
 
-    bt_gatt_foreach_attr(0x0001, 0xffff, gen_hash_m, &state);
+    break;
+  /* Attributes to hash: handle + UUID */
+  case 0x2901: /* GATT Characteristic User Descriptor */
+  case 0x2902: /* GATT Client Characteristic Configuration */
+  case 0x2903: /* GATT Server Characteristic Configuration */
+  case 0x2904: /* GATT Characteristic Presentation Format */
+  case 0x2905: /* GATT Characteristic Aggregated Format */
+    value = sys_cpu_to_le16(attr->handle);
+    if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(attr->handle)) == TC_CRYPTO_FAIL) {
+      state->err = -EINVAL;
+      return BT_GATT_ITER_STOP;
+    }
 
-    if (tc_cmac_final(db_hash, &state.state) == TC_CRYPTO_FAIL) {
-        BT_ERR("Unable to calculate hash");
-        return;
+    value = sys_cpu_to_le16(u16->val);
+    if (tc_cmac_update(&state->state, (uint8_t *)&value, sizeof(u16->val)) == TC_CRYPTO_FAIL) {
+      state->err = -EINVAL;
+      return BT_GATT_ITER_STOP;
     }
+    break;
+  default:
+    return BT_GATT_ITER_CONTINUE;
+  }
+
+  return BT_GATT_ITER_CONTINUE;
+}
+
+static void db_hash_store(void) {
+  int err;
+
+  err = settings_save_one("bt/hash", &db_hash, sizeof(db_hash));
+  if (err) {
+    BT_ERR("Failed to save Database Hash (err %d)", err);
+  }
+
+  BT_DBG("Database Hash stored");
+}
+
+static void db_hash_gen(bool store) {
+  u8_t                           key[16] = {};
+  struct tc_aes_key_sched_struct sched;
+  struct gen_hash_state          state;
+
+  if (tc_cmac_setup(&state.state, key, &sched) == TC_CRYPTO_FAIL) {
+    BT_ERR("Unable to setup AES CMAC");
+    return;
+  }
 
-    /**
-	 * Core 5.1 does not state the endianess of the hash.
-	 * However Vol 3, Part F, 3.3.1 says that multi-octet Characteristic
-	 * Values shall be LE unless otherwise defined. PTS expects hash to be
-	 * in little endianess as well. bt_smp_aes_cmac calculates the hash in
-	 * big endianess so we have to swap.
-	 */
-    sys_mem_swap(db_hash, sizeof(db_hash));
+  bt_gatt_foreach_attr(0x0001, 0xffff, gen_hash_m, &state);
+
+  if (tc_cmac_final(db_hash, &state.state) == TC_CRYPTO_FAIL) {
+    BT_ERR("Unable to calculate hash");
+    return;
+  }
+
+  /**
+   * Core 5.1 does not state the endianess of the hash.
+   * However Vol 3, Part F, 3.3.1 says that multi-octet Characteristic
+   * Values shall be LE unless otherwise defined. PTS expects hash to be
+   * in little endianess as well. bt_smp_aes_cmac calculates the hash in
+   * big endianess so we have to swap.
+   */
+  sys_mem_swap(db_hash, sizeof(db_hash));
 
 #if !defined(BFLB_BLE)
-    BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "Hash: ");
+  BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "Hash: ");
 #endif
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) {
-        db_hash_store();
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) {
+    db_hash_store();
+  }
 }
 
-static void db_hash_process(struct k_work *work)
-{
-    db_hash_gen(true);
-}
+static void db_hash_process(struct k_work *work) { db_hash_gen(true); }
 
-static ssize_t db_hash_read(struct bt_conn *conn,
-                            const struct bt_gatt_attr *attr,
-                            void *buf, u16_t len, u16_t offset)
-{
-    /* Check if db_hash is already pending in which case it shall be
-	 * generated immediately instead of waiting the work to complete.
-	 */
-    if (k_delayed_work_remaining_get(&db_hash_work)) {
-        k_delayed_work_cancel(&db_hash_work);
-        db_hash_gen(true);
-    }
+static ssize_t db_hash_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  /* Check if db_hash is already pending in which case it shall be
+   * generated immediately instead of waiting the work to complete.
+   */
+  if (k_delayed_work_remaining_get(&db_hash_work)) {
+    k_delayed_work_cancel(&db_hash_work);
+    db_hash_gen(true);
+  }
 
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
-	 * 2.5.2.1 Robust Caching
-	 * A connected client becomes change-aware when...
-	 * The client reads the Database Hash characteristic and then the server
-	 * receives another ATT request from the client.
-	 */
-    bt_gatt_change_aware(conn, true);
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
+   * 2.5.2.1 Robust Caching
+   * A connected client becomes change-aware when...
+   * The client reads the Database Hash characteristic and then the server
+   * receives another ATT request from the client.
+   */
+  bt_gatt_change_aware(conn, true);
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, db_hash,
-                             sizeof(db_hash));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, db_hash, sizeof(db_hash));
 }
 
-static void clear_cf_cfg(struct gatt_cf_cfg *cfg)
-{
-    bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY);
-    memset(cfg->data, 0, sizeof(cfg->data));
-    atomic_set(cfg->flags, 0);
+static void clear_cf_cfg(struct gatt_cf_cfg *cfg) {
+  bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY);
+  memset(cfg->data, 0, sizeof(cfg->data));
+  atomic_set(cfg->flags, 0);
 }
 
-static void remove_cf_cfg(struct bt_conn *conn)
-{
-    struct gatt_cf_cfg *cfg;
-
-    cfg = find_cf_cfg(conn);
-    if (!cfg) {
-        return;
-    }
+static void remove_cf_cfg(struct bt_conn *conn) {
+  struct gatt_cf_cfg *cfg;
 
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2405:
-	 * For clients with a trusted relationship, the characteristic value
-	 * shall be persistent across connections. For clients without a
-	 * trusted relationship the characteristic value shall be set to the
-	 * default value at each connection.
-	 */
-    if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-        clear_cf_cfg(cfg);
-    } else {
-        /* Update address in case it has changed */
-        bt_addr_le_copy(&cfg->peer, &conn->le.dst);
-    }
+  cfg = find_cf_cfg(conn);
+  if (!cfg) {
+    return;
+  }
+
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2405:
+   * For clients with a trusted relationship, the characteristic value
+   * shall be persistent across connections. For clients without a
+   * trusted relationship the characteristic value shall be set to the
+   * default value at each connection.
+   */
+  if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+    clear_cf_cfg(cfg);
+  } else {
+    /* Update address in case it has changed */
+    bt_addr_le_copy(&cfg->peer, &conn->le.dst);
+  }
 }
 #endif /* CONFIG_BT_GATT_CACHING */
 
@@ -727,23 +659,17 @@ BT_GATT_SERVICE_DEFINE(_1_gatt_svc,
 
 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
     /* Bluetooth 5.0, Vol3 Part G:
-	 * The Service Changed characteristic Attribute Handle on the server
-	 * shall not change if the server has a trusted relationship with any
-	 * client.
-	 */
-    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_SC, BT_GATT_CHRC_INDICATE,
-                           BT_GATT_PERM_NONE, NULL, NULL, NULL),
+     * The Service Changed characteristic Attribute Handle on the server
+     * shall not change if the server has a trusted relationship with any
+     * client.
+     */
+    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_SC, BT_GATT_CHRC_INDICATE, BT_GATT_PERM_NONE, NULL, NULL, NULL),
 
     BT_GATT_CCC_MANAGED(&sc_ccc, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
 
 #if defined(CONFIG_BT_GATT_CACHING)
-    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_CLIENT_FEATURES,
-                           BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
-                           BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
-                           cf_read, cf_write, NULL),
-    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_DB_HASH,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           db_hash_read, NULL, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_CLIENT_FEATURES, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, cf_read, cf_write, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_GATT_DB_HASH, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, db_hash_read, NULL, NULL),
 #endif /* CONFIG_BT_GATT_CACHING */
 #endif /* CONFIG_BT_GATT_SERVICE_CHANGED */
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
@@ -757,3233 +683,2947 @@ static struct bt_gatt_service gatt_svc = BT_GATT_SERVICE(gatt_attrs);
 #endif
 
 #if defined(CONFIG_BT_GATT_DYNAMIC_DB)
-static u8_t found_attr(const struct bt_gatt_attr *attr, void *user_data)
-{
-    const struct bt_gatt_attr **found = user_data;
+static u8_t found_attr(const struct bt_gatt_attr *attr, void *user_data) {
+  const struct bt_gatt_attr **found = user_data;
 
-    *found = attr;
+  *found = attr;
 
-    return BT_GATT_ITER_STOP;
+  return BT_GATT_ITER_STOP;
 }
 
-static const struct bt_gatt_attr *find_attr(uint16_t handle)
-{
-    const struct bt_gatt_attr *attr = NULL;
+static const struct bt_gatt_attr *find_attr(uint16_t handle) {
+  const struct bt_gatt_attr *attr = NULL;
 
-    bt_gatt_foreach_attr(handle, handle, found_attr, &attr);
+  bt_gatt_foreach_attr(handle, handle, found_attr, &attr);
 
-    return attr;
+  return attr;
 }
 
-static void gatt_insert(struct bt_gatt_service *svc, u16_t last_handle)
-{
-    struct bt_gatt_service *tmp, *prev = NULL;
-
-    if (last_handle == 0 || svc->attrs[0].handle > last_handle) {
-        sys_slist_append(&db, &svc->node);
-        return;
-    }
+static void gatt_insert(struct bt_gatt_service *svc, u16_t last_handle) {
+  struct bt_gatt_service *tmp, *prev = NULL;
 
-    /* DB shall always have its service in ascending order */
-    SYS_SLIST_FOR_EACH_CONTAINER(&db, tmp, node)
-    {
-        if (tmp->attrs[0].handle > svc->attrs[0].handle) {
-            if (prev) {
-                sys_slist_insert(&db, &prev->node, &svc->node);
-            } else {
-                sys_slist_prepend(&db, &svc->node);
-            }
-            return;
-        }
+  if (last_handle == 0 || svc->attrs[0].handle > last_handle) {
+    sys_slist_append(&db, &svc->node);
+    return;
+  }
 
-        prev = tmp;
+  /* DB shall always have its service in ascending order */
+  SYS_SLIST_FOR_EACH_CONTAINER(&db, tmp, node) {
+    if (tmp->attrs[0].handle > svc->attrs[0].handle) {
+      if (prev) {
+        sys_slist_insert(&db, &prev->node, &svc->node);
+      } else {
+        sys_slist_prepend(&db, &svc->node);
+      }
+      return;
     }
+
+    prev = tmp;
+  }
 }
 
-static int gatt_register(struct bt_gatt_service *svc)
-{
-    struct bt_gatt_service *last;
-    u16_t handle, last_handle;
-    struct bt_gatt_attr *attrs = svc->attrs;
-    u16_t count = svc->attr_count;
-
-    if (sys_slist_is_empty(&db)) {
-        handle = last_static_handle;
-        last_handle = 0;
-        goto populate;
-    }
+static int gatt_register(struct bt_gatt_service *svc) {
+  struct bt_gatt_service *last;
+  u16_t                   handle, last_handle;
+  struct bt_gatt_attr    *attrs = svc->attrs;
+  u16_t                   count = svc->attr_count;
 
-    last = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node);
-    handle = last->attrs[last->attr_count - 1].handle;
-    last_handle = handle;
+  if (sys_slist_is_empty(&db)) {
+    handle      = last_static_handle;
+    last_handle = 0;
+    goto populate;
+  }
 
-populate:
-    /* Populate the handles and append them to the list */
-    for (; attrs && count; attrs++, count--) {
-        if (!attrs->handle) {
-            /* Allocate handle if not set already */
-            attrs->handle = ++handle;
-        } else if (attrs->handle > handle) {
-            /* Use existing handle if valid */
-            handle = attrs->handle;
-        } else if (find_attr(attrs->handle)) {
-            /* Service has conflicting handles */
-            BT_ERR("Unable to register handle 0x%04x",
-                   attrs->handle);
-            return -EINVAL;
-        }
+  last        = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node);
+  handle      = last->attrs[last->attr_count - 1].handle;
+  last_handle = handle;
 
-        BT_DBG("attr %p handle 0x%04x uuid %s perm 0x%02x",
-               attrs, attrs->handle, bt_uuid_str(attrs->uuid),
-               attrs->perm);
+populate:
+  /* Populate the handles and append them to the list */
+  for (; attrs && count; attrs++, count--) {
+    if (!attrs->handle) {
+      /* Allocate handle if not set already */
+      attrs->handle = ++handle;
+    } else if (attrs->handle > handle) {
+      /* Use existing handle if valid */
+      handle = attrs->handle;
+    } else if (find_attr(attrs->handle)) {
+      /* Service has conflicting handles */
+      BT_ERR("Unable to register handle 0x%04x", attrs->handle);
+      return -EINVAL;
     }
 
-    gatt_insert(svc, last_handle);
+    BT_DBG("attr %p handle 0x%04x uuid %s perm 0x%02x", attrs, attrs->handle, bt_uuid_str(attrs->uuid), attrs->perm);
+  }
 
-    return 0;
+  gatt_insert(svc, last_handle);
+
+  return 0;
 }
 #endif /* CONFIG_BT_GATT_DYNAMIC_DB */
 
 enum {
-    SC_RANGE_CHANGED,    /* SC range changed */
-    SC_INDICATE_PENDING, /* SC indicate pending */
+  SC_RANGE_CHANGED,    /* SC range changed */
+  SC_INDICATE_PENDING, /* SC indicate pending */
 
-    /* Total number of flags - must be at the end of the enum */
-    SC_NUM_FLAGS,
+  /* Total number of flags - must be at the end of the enum */
+  SC_NUM_FLAGS,
 };
 
 static struct gatt_sc {
-    struct bt_gatt_indicate_params params;
-    u16_t start;
-    u16_t end;
-    struct k_delayed_work work;
-    ATOMIC_DEFINE(flags, SC_NUM_FLAGS);
+  struct bt_gatt_indicate_params params;
+  u16_t                          start;
+  u16_t                          end;
+  struct k_delayed_work          work;
+  ATOMIC_DEFINE(flags, SC_NUM_FLAGS);
 } gatt_sc;
 
-static void sc_indicate_rsp(struct bt_conn *conn,
-                            const struct bt_gatt_attr *attr, u8_t err)
-{
+static void sc_indicate_rsp(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t err) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    struct gatt_cf_cfg *cfg;
+  struct gatt_cf_cfg *cfg;
 #endif
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING);
+  atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING);
 
-    /* Check if there is new change in the meantime */
-    if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
-        /* Reschedule without any delay since it is waiting already */
-        k_delayed_work_submit(&gatt_sc.work, K_NO_WAIT);
-    }
+  /* Check if there is new change in the meantime */
+  if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
+    /* Reschedule without any delay since it is waiting already */
+    k_delayed_work_submit(&gatt_sc.work, K_NO_WAIT);
+  }
 
 #if defined(CONFIG_BT_GATT_CACHING)
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
-	 * 2.5.2.1 Robust Caching
-	 * A connected client becomes change-aware when...
-	 * The client receives and confirms a Service Changed indication.
-	 */
-    cfg = find_cf_cfg(conn);
-    if (cfg && CF_ROBUST_CACHING(cfg)) {
-        atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
-        BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
-    }
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
+   * 2.5.2.1 Robust Caching
+   * A connected client becomes change-aware when...
+   * The client receives and confirms a Service Changed indication.
+   */
+  cfg = find_cf_cfg(conn);
+  if (cfg && CF_ROBUST_CACHING(cfg)) {
+    atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
+    BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
+  }
 #endif
 }
 
-static void sc_process(struct k_work *work)
-{
-    struct gatt_sc *sc = CONTAINER_OF(work, struct gatt_sc, work);
-    u16_t sc_range[2];
+static void sc_process(struct k_work *work) {
+  struct gatt_sc *sc = CONTAINER_OF(work, struct gatt_sc, work);
+  u16_t           sc_range[2];
 
-    __ASSERT(!atomic_test_bit(sc->flags, SC_INDICATE_PENDING),
-             "Indicate already pending");
+  __ASSERT(!atomic_test_bit(sc->flags, SC_INDICATE_PENDING), "Indicate already pending");
 
-    BT_DBG("start 0x%04x end 0x%04x", sc->start, sc->end);
+  BT_DBG("start 0x%04x end 0x%04x", sc->start, sc->end);
 
-    sc_range[0] = sys_cpu_to_le16(sc->start);
-    sc_range[1] = sys_cpu_to_le16(sc->end);
+  sc_range[0] = sys_cpu_to_le16(sc->start);
+  sc_range[1] = sys_cpu_to_le16(sc->end);
 
-    atomic_clear_bit(sc->flags, SC_RANGE_CHANGED);
-    sc->start = 0U;
-    sc->end = 0U;
+  atomic_clear_bit(sc->flags, SC_RANGE_CHANGED);
+  sc->start = 0U;
+  sc->end   = 0U;
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    sc->params.attr = &gatt_attrs[2];
+  sc->params.attr = &gatt_attrs[2];
 #else
-    sc->params.attr = &_1_gatt_svc.attrs[2];
+  sc->params.attr = &_1_gatt_svc.attrs[2];
 #endif
-    sc->params.func = sc_indicate_rsp;
-    sc->params.data = &sc_range[0];
-    sc->params.len = sizeof(sc_range);
+  sc->params.func = sc_indicate_rsp;
+  sc->params.data = &sc_range[0];
+  sc->params.len  = sizeof(sc_range);
 
-    if (bt_gatt_indicate(NULL, &sc->params)) {
-        /* No connections to indicate */
-        return;
-    }
+  if (bt_gatt_indicate(NULL, &sc->params)) {
+    /* No connections to indicate */
+    return;
+  }
 
-    atomic_set_bit(sc->flags, SC_INDICATE_PENDING);
+  atomic_set_bit(sc->flags, SC_INDICATE_PENDING);
 }
 
 #if defined(CONFIG_BT_STACK_PTS)
-int service_change_test(struct bt_gatt_indicate_params *params, const struct bt_conn *con)
-{
-    u16_t sc_range[2];
+int service_change_test(struct bt_gatt_indicate_params *params, const struct bt_conn *con) {
+  u16_t sc_range[2];
 
-    if (!params->attr) {
+  if (!params->attr) {
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-        params->attr = &gatt_attrs[2];
+    params->attr = &gatt_attrs[2];
 #else
-        params->attr = &_1_gatt_svc.attrs[2];
+    params->attr = &_1_gatt_svc.attrs[2];
 #endif
-    }
-    sc_range[0] = 0x000e;
-    sc_range[1] = 0x001e;
+  }
+  sc_range[0] = 0x000e;
+  sc_range[1] = 0x001e;
 
-    params->data = &sc_range[0];
-    params->len = sizeof(sc_range);
+  params->data = &sc_range[0];
+  params->len  = sizeof(sc_range);
 
-    if (bt_gatt_indicate(con, params)) {
-        /* No connections to indicate */
-        return;
-    }
+  return bt_gatt_indicate(con, params);
 }
+
 #endif
 
 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
 static struct gatt_ccc_store {
-    struct bt_conn *conn_list[CONFIG_BT_MAX_CONN];
-    struct k_delayed_work work;
+  struct bt_conn       *conn_list[CONFIG_BT_MAX_CONN];
+  struct k_delayed_work work;
 } gatt_ccc_store;
 
-static bool gatt_ccc_conn_is_queued(struct bt_conn *conn)
-{
-    return (conn == gatt_ccc_store.conn_list[bt_conn_index(conn)]);
-}
+static bool gatt_ccc_conn_is_queued(struct bt_conn *conn) { return (conn == gatt_ccc_store.conn_list[bt_conn_index(conn)]); }
 
-static void gatt_ccc_conn_unqueue(struct bt_conn *conn)
-{
-    u8_t index = bt_conn_index(conn);
+static void gatt_ccc_conn_unqueue(struct bt_conn *conn) {
+  u8_t index = bt_conn_index(conn);
 
-    if (gatt_ccc_store.conn_list[index] != NULL) {
-        bt_conn_unref(gatt_ccc_store.conn_list[index]);
-        gatt_ccc_store.conn_list[index] = NULL;
-    }
+  if (gatt_ccc_store.conn_list[index] != NULL) {
+    bt_conn_unref(gatt_ccc_store.conn_list[index]);
+    gatt_ccc_store.conn_list[index] = NULL;
+  }
 }
 
-static bool gatt_ccc_conn_queue_is_empty(void)
-{
-    for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) {
-        if (gatt_ccc_store.conn_list[i]) {
-            return false;
-        }
+static bool gatt_ccc_conn_queue_is_empty(void) {
+  for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) {
+    if (gatt_ccc_store.conn_list[i]) {
+      return false;
     }
+  }
 
-    return true;
+  return true;
 }
 
-static void ccc_delayed_store(struct k_work *work)
-{
-    struct gatt_ccc_store *ccc_store =
-        CONTAINER_OF(work, struct gatt_ccc_store, work);
+static void ccc_delayed_store(struct k_work *work) {
+  struct gatt_ccc_store *ccc_store = CONTAINER_OF(work, struct gatt_ccc_store, work);
 
-    for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) {
-        struct bt_conn *conn = ccc_store->conn_list[i];
+  for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) {
+    struct bt_conn *conn = ccc_store->conn_list[i];
 
-        if (!conn) {
-            continue;
-        }
+    if (!conn) {
+      continue;
+    }
 
-        if (bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-            bt_gatt_store_ccc(conn->id, &conn->le.dst);
-            bt_conn_unref(conn);
-            ccc_store->conn_list[i] = NULL;
-        }
+    if (bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+      bt_gatt_store_ccc(conn->id, &conn->le.dst);
+      bt_conn_unref(conn);
+      ccc_store->conn_list[i] = NULL;
     }
+  }
 }
 #endif
 
-void bt_gatt_init(void)
-{
-    if (!atomic_cas(&init, 0, 1)) {
-        return;
-    }
+void bt_gatt_init(void) {
+  if (!atomic_cas(&init, 0, 1)) {
+    return;
+  }
 
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    /* Register mandatory services */
-    gatt_register(&gap_svc);
-    gatt_register(&gatt_svc);
+  /* Register mandatory services */
+  gatt_register(&gap_svc);
+  gatt_register(&gatt_svc);
 
 #else
-    Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, svc)
-    {
-        last_static_handle += svc->attr_count;
-    }
+  Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, svc) { last_static_handle += svc->attr_count; }
 #endif
 
 #if defined(CONFIG_BT_GATT_CACHING)
-    k_delayed_work_init(&db_hash_work, db_hash_process);
+  k_delayed_work_init(&db_hash_work, db_hash_process);
 
-    /* Submit work to Generate initial hash as there could be static
-	 * services already in the database.
-	 */
-    k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT);
+  /* Submit work to Generate initial hash as there could be static
+   * services already in the database.
+   */
+  k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT);
 #endif /* CONFIG_BT_GATT_CACHING */
 
-    if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
-        k_delayed_work_init(&gatt_sc.work, sc_process);
-        if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-            /* Make sure to not send SC indications until SC
-			 * settings are loaded
-			 */
-            atomic_set_bit(gatt_sc.flags, SC_INDICATE_PENDING);
-        }
+  if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
+    k_delayed_work_init(&gatt_sc.work, sc_process);
+    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+      /* Make sure to not send SC indications until SC
+       * settings are loaded
+       */
+      atomic_set_bit(gatt_sc.flags, SC_INDICATE_PENDING);
     }
+  }
 
 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
-    k_delayed_work_init(&gatt_ccc_store.work, ccc_delayed_store);
+  k_delayed_work_init(&gatt_ccc_store.work, ccc_delayed_store);
 #endif
 }
 
 #if defined(BFLB_BLE)
-void bt_gatt_deinit(void)
-{
+void bt_gatt_deinit(void) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    k_delayed_work_del_timer(&db_hash_work);
+  k_delayed_work_del_timer(&db_hash_work);
 #endif
 
-    if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
-        k_delayed_work_del_timer(&gatt_sc.work);
-    }
+  if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
+    k_delayed_work_del_timer(&gatt_sc.work);
+  }
 
 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
-    k_delayed_work_del_timer(&gatt_ccc_store.work);
+  k_delayed_work_del_timer(&gatt_ccc_store.work);
 #endif
 }
 #endif
 
-#if defined(CONFIG_BT_GATT_DYNAMIC_DB) || \
-    (defined(CONFIG_BT_GATT_CACHING) && defined(CONFIG_BT_SETTINGS))
-static void sc_indicate(u16_t start, u16_t end)
-{
-    BT_DBG("start 0x%04x end 0x%04x", start, end);
+#if defined(CONFIG_BT_GATT_DYNAMIC_DB) || (defined(CONFIG_BT_GATT_CACHING) && defined(CONFIG_BT_SETTINGS))
+static void sc_indicate(u16_t start, u16_t end) {
+  BT_DBG("start 0x%04x end 0x%04x", start, end);
 
 #if defined(BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE)
-    struct bt_conn *conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECTED);
-    if (conn) {
+  struct bt_conn *conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECTED);
+  if (conn) {
 #endif
-        if (!atomic_test_and_set_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
-            gatt_sc.start = start;
-            gatt_sc.end = end;
-            goto submit;
-        }
-#if defined(BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE)
+    if (!atomic_test_and_set_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
+      gatt_sc.start = start;
+      gatt_sc.end   = end;
+      goto submit;
     }
+#if defined(BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE)
+  }
 #endif
 
-    if (!update_range(&gatt_sc.start, &gatt_sc.end, start, end)) {
-        return;
-    }
+  if (!update_range(&gatt_sc.start, &gatt_sc.end, start, end)) {
+    return;
+  }
 
 submit:
-    if (atomic_test_bit(gatt_sc.flags, SC_INDICATE_PENDING)) {
-        BT_DBG("indicate pending, waiting until complete...");
-        return;
-    }
+  if (atomic_test_bit(gatt_sc.flags, SC_INDICATE_PENDING)) {
+    BT_DBG("indicate pending, waiting until complete...");
+    return;
+  }
 
 #if defined(BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE)
-    if (conn) {
+  if (conn) {
 #endif
-        /* Reschedule since the range has changed */
-        k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT);
+    /* Reschedule since the range has changed */
+    k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT);
 #if defined(BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE)
-        bt_conn_unref(conn);
-    }
+    bt_conn_unref(conn);
+  }
 #endif
 }
 #endif /* BT_GATT_DYNAMIC_DB || (BT_GATT_CACHING && BT_SETTINGS) */
 
 #if defined(CONFIG_BT_GATT_DYNAMIC_DB)
-static void db_changed(void)
-{
+static void db_changed(void) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    int i;
+  int i;
 
-    k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT);
+  k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT);
 
-    for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
-        struct gatt_cf_cfg *cfg = &cf_cfg[i];
+  for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
+    struct gatt_cf_cfg *cfg = &cf_cfg[i];
 
-        if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) {
-            continue;
-        }
+    if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) {
+      continue;
+    }
 
-        if (CF_ROBUST_CACHING(cfg)) {
-            /* Core Spec 5.1 | Vol 3, Part G, 2.5.2.1 Robust Caching
-			 *... the database changes again before the client
-			 * becomes change-aware in which case the error response
-			 * shall be sent again.
-			 */
-            atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC);
-            if (atomic_test_and_clear_bit(cfg->flags,
-                                          CF_CHANGE_AWARE)) {
-                BT_DBG("%s change-unaware",
-                       bt_addr_le_str(&cfg->peer));
-            }
-        }
+    if (CF_ROBUST_CACHING(cfg)) {
+      /* Core Spec 5.1 | Vol 3, Part G, 2.5.2.1 Robust Caching
+       *... the database changes again before the client
+       * becomes change-aware in which case the error response
+       * shall be sent again.
+       */
+      atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC);
+      if (atomic_test_and_clear_bit(cfg->flags, CF_CHANGE_AWARE)) {
+        BT_DBG("%s change-unaware", bt_addr_le_str(&cfg->peer));
+      }
     }
+  }
 #endif
 }
 
-int bt_gatt_service_register(struct bt_gatt_service *svc)
-{
-    int err;
+int bt_gatt_service_register(struct bt_gatt_service *svc) {
+  int err;
 
-    __ASSERT(svc, "invalid parameters\n");
-    __ASSERT(svc->attrs, "invalid parameters\n");
-    __ASSERT(svc->attr_count, "invalid parameters\n");
+  __ASSERT(svc, "invalid parameters\n");
+  __ASSERT(svc->attrs, "invalid parameters\n");
+  __ASSERT(svc->attr_count, "invalid parameters\n");
 
-    /* Init GATT core services */
-    bt_gatt_init();
+  /* Init GATT core services */
+  bt_gatt_init();
 
-    /* Do no allow to register mandatory services twice */
-    if (!bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GAP) ||
-        !bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GATT)) {
-        return -EALREADY;
-    }
+  /* Do no allow to register mandatory services twice */
+  if (!bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GAP) || !bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GATT)) {
+    return -EALREADY;
+  }
 
-    err = gatt_register(svc);
-    if (err < 0) {
-        return err;
-    }
+  err = gatt_register(svc);
+  if (err < 0) {
+    return err;
+  }
 
-    sc_indicate(svc->attrs[0].handle,
-                svc->attrs[svc->attr_count - 1].handle);
+  sc_indicate(svc->attrs[0].handle, svc->attrs[svc->attr_count - 1].handle);
 
-    db_changed();
+  db_changed();
 
-    return 0;
+  return 0;
 }
 
-int bt_gatt_service_unregister(struct bt_gatt_service *svc)
-{
-    __ASSERT(svc, "invalid parameters\n");
+int bt_gatt_service_unregister(struct bt_gatt_service *svc) {
+  __ASSERT(svc, "invalid parameters\n");
 
-    if (!sys_slist_find_and_remove(&db, &svc->node)) {
-        return -ENOENT;
-    }
+  if (!sys_slist_find_and_remove(&db, &svc->node)) {
+    return -ENOENT;
+  }
 
-    sc_indicate(svc->attrs[0].handle,
-                svc->attrs[svc->attr_count - 1].handle);
+  sc_indicate(svc->attrs[0].handle, svc->attrs[svc->attr_count - 1].handle);
 
-    db_changed();
+  db_changed();
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_GATT_DYNAMIC_DB */
 
-ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                          void *buf, u16_t buf_len, u16_t offset,
-                          const void *value, u16_t value_len)
-{
-    u16_t len;
+ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t buf_len, u16_t offset, const void *value, u16_t value_len) {
+  u16_t len;
 #if defined(CONFIG_BT_STACK_PTS)
-    u8_t *data = NULL;
-    u8_t i = 0;
+  u8_t *data = NULL;
+  u8_t  i    = 0;
 #endif
 
-    if (offset > value_len) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
-    }
+  if (offset > value_len) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
+  }
 
-    len = MIN(buf_len, value_len - offset);
+  len = MIN(buf_len, value_len - offset);
 
-    BT_DBG("handle 0x%04x offset %u length %u", attr->handle, offset,
-           len);
+  BT_DBG("handle 0x%04x offset %u length %u", attr->handle, offset, len);
 
-    memcpy(buf, (u8_t *)value + offset, len);
+  memcpy(buf, (u8_t *)value + offset, len);
 
 #if defined(CONFIG_BT_STACK_PTS)
-    /* PTS sends a request to iut read all primary services it contains.
-	 * Set event flags to avoid comflicts when other test cases need to add reference codes. 
-	 */
-    if (event_flag == att_read_by_group_type_ind) {
-        data = (u8_t *)buf;
-        for (i = 0; i < len; i++) {
-            BT_PTS("%s:handle = [0x%04x], data[%d] = [0x%x]\r\n", __func__,
-                   attr->handle, i, data[i]);
-        }
-    }
+  /* PTS sends a request to iut read all primary services it contains.
+   * Set event flags to avoid comflicts when other test cases need to add reference codes.
+   */
+  if (event_flag == att_read_by_group_type_ind) {
+    data = (u8_t *)buf;
+    for (i = 0; i < len; i++) {
+      BT_PTS("%s:handle = [0x%04x], data[%d] = [0x%x]\r\n", __func__, attr->handle, i, data[i]);
+    }
+  }
 #endif
 
-    return len;
+  return len;
 }
 
-ssize_t bt_gatt_attr_read_service(struct bt_conn *conn,
-                                  const struct bt_gatt_attr *attr,
-                                  void *buf, u16_t len, u16_t offset)
-{
-    struct bt_uuid *uuid = attr->user_data;
+ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct bt_uuid *uuid = attr->user_data;
 
-    if (uuid->type == BT_UUID_TYPE_16) {
-        u16_t uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
+  if (uuid->type == BT_UUID_TYPE_16) {
+    u16_t uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
 
-        return bt_gatt_attr_read(conn, attr, buf, len, offset,
-                                 &uuid16, 2);
-    }
+    return bt_gatt_attr_read(conn, attr, buf, len, offset, &uuid16, 2);
+  }
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset,
-                             BT_UUID_128(uuid)->val, 16);
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, BT_UUID_128(uuid)->val, 16);
 }
 
 struct gatt_incl {
-    u16_t start_handle;
-    u16_t end_handle;
-    u16_t uuid16;
+  u16_t start_handle;
+  u16_t end_handle;
+  u16_t uuid16;
 } __packed;
 
-static u8_t get_service_handles(const struct bt_gatt_attr *attr,
-                                void *user_data)
-{
-    struct gatt_incl *include = user_data;
+static u8_t get_service_handles(const struct bt_gatt_attr *attr, void *user_data) {
+  struct gatt_incl *include = user_data;
 
-    /* Stop if attribute is a service */
-    if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) ||
-        !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
-        return BT_GATT_ITER_STOP;
-    }
+  /* Stop if attribute is a service */
+  if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    include->end_handle = attr->handle;
+  include->end_handle = attr->handle;
 
-    return BT_GATT_ITER_CONTINUE;
+  return BT_GATT_ITER_CONTINUE;
 }
 
 #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-static u16_t find_static_attr(const struct bt_gatt_attr *attr)
-{
-    u16_t handle = 1;
+static u16_t find_static_attr(const struct bt_gatt_attr *attr) {
+  u16_t handle = 1;
 
-    Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc)
-    {
-        for (int i = 0; i < static_svc->attr_count; i++, handle++) {
-            if (attr == &static_svc->attrs[i]) {
-                return handle;
-            }
-        }
+  Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) {
+    for (int i = 0; i < static_svc->attr_count; i++, handle++) {
+      if (attr == &static_svc->attrs[i]) {
+        return handle;
+      }
     }
+  }
 
-    return 0;
+  return 0;
 }
 #endif
 
-ssize_t bt_gatt_attr_read_included(struct bt_conn *conn,
-                                   const struct bt_gatt_attr *attr,
-                                   void *buf, u16_t len, u16_t offset)
-{
-    struct bt_gatt_attr *incl = attr->user_data;
+ssize_t bt_gatt_attr_read_included(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct bt_gatt_attr *incl = attr->user_data;
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    u16_t handle = incl->handle;
+  u16_t handle = incl->handle;
 #else
-    u16_t handle = incl->handle ?: find_static_attr(incl);
+  u16_t handle = incl->handle ?: find_static_attr(incl);
 #endif
-    struct bt_uuid *uuid = incl->user_data;
-    struct gatt_incl pdu;
-    u8_t value_len;
-
-    /* first attr points to the start handle */
-    pdu.start_handle = sys_cpu_to_le16(handle);
-    value_len = sizeof(pdu.start_handle) + sizeof(pdu.end_handle);
-
-    /*
-	 * Core 4.2, Vol 3, Part G, 3.2,
-	 * The Service UUID shall only be present when the UUID is a
-	 * 16-bit Bluetooth UUID.
-	 */
-    if (uuid->type == BT_UUID_TYPE_16) {
-        pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
-        value_len += sizeof(pdu.uuid16);
-    }
+  struct bt_uuid  *uuid = incl->user_data;
+  struct gatt_incl pdu;
+  u8_t             value_len;
+
+  /* first attr points to the start handle */
+  pdu.start_handle = sys_cpu_to_le16(handle);
+  value_len        = sizeof(pdu.start_handle) + sizeof(pdu.end_handle);
+
+  /*
+   * Core 4.2, Vol 3, Part G, 3.2,
+   * The Service UUID shall only be present when the UUID is a
+   * 16-bit Bluetooth UUID.
+   */
+  if (uuid->type == BT_UUID_TYPE_16) {
+    pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
+    value_len += sizeof(pdu.uuid16);
+  }
 
-    /* Lookup for service end handle */
-    bt_gatt_foreach_attr(handle + 1, 0xffff, get_service_handles, &pdu);
+  /* Lookup for service end handle */
+  bt_gatt_foreach_attr(handle + 1, 0xffff, get_service_handles, &pdu);
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
 }
 
 struct gatt_chrc {
-    u8_t properties;
-    u16_t value_handle;
-    union {
-        u16_t uuid16;
-        u8_t uuid[16];
-    };
+  u8_t  properties;
+  u16_t value_handle;
+  union {
+    u16_t uuid16;
+    u8_t  uuid[16];
+  };
 } __packed;
 
-uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr)
-{
-    u16_t handle = 0;
+uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr) {
+  u16_t handle = 0;
 
-    if ((attr != NULL) && (attr->read == bt_gatt_attr_read_chrc)) {
-        struct bt_gatt_chrc *chrc = attr->user_data;
+  if ((attr != NULL) && (attr->read == bt_gatt_attr_read_chrc)) {
+    struct bt_gatt_chrc *chrc = attr->user_data;
 
-        handle = chrc->value_handle;
+    handle = chrc->value_handle;
 #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-        if (handle == 0) {
-            /* Fall back to Zephyr value handle policy */
-            handle = (attr->handle ?: find_static_attr(attr)) + 1U;
-        }
-#endif
+    if (handle == 0) {
+      /* Fall back to Zephyr value handle policy */
+      handle = (attr->handle ?: find_static_attr(attr)) + 1U;
     }
+#endif
+  }
 
-    return handle;
+  return handle;
 }
 
-ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn,
-                               const struct bt_gatt_attr *attr, void *buf,
-                               u16_t len, u16_t offset)
-{
-    struct bt_gatt_chrc *chrc = attr->user_data;
-    struct gatt_chrc pdu;
-    u8_t value_len;
-
-    pdu.properties = chrc->properties;
-    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 534:
-	 * 3.3.2 Characteristic Value Declaration
-	 * The Characteristic Value declaration contains the value of the
-	 * characteristic. It is the first Attribute after the characteristic
-	 * declaration. All characteristic definitions shall have a
-	 * Characteristic Value declaration.
-	 */
-    pdu.value_handle = sys_cpu_to_le16(bt_gatt_attr_value_handle(attr));
-
-    value_len = sizeof(pdu.properties) + sizeof(pdu.value_handle);
-
-    if (chrc->uuid->type == BT_UUID_TYPE_16) {
-        pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(chrc->uuid)->val);
-        value_len += 2U;
-    } else {
-        memcpy(pdu.uuid, BT_UUID_128(chrc->uuid)->val, 16);
-        value_len += 16U;
-    }
+ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct bt_gatt_chrc *chrc = attr->user_data;
+  struct gatt_chrc     pdu;
+  u8_t                 value_len;
+
+  pdu.properties = chrc->properties;
+  /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 534:
+   * 3.3.2 Characteristic Value Declaration
+   * The Characteristic Value declaration contains the value of the
+   * characteristic. It is the first Attribute after the characteristic
+   * declaration. All characteristic definitions shall have a
+   * Characteristic Value declaration.
+   */
+  pdu.value_handle = sys_cpu_to_le16(bt_gatt_attr_value_handle(attr));
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
+  value_len = sizeof(pdu.properties) + sizeof(pdu.value_handle);
+
+  if (chrc->uuid->type == BT_UUID_TYPE_16) {
+    pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(chrc->uuid)->val);
+    value_len += 2U;
+  } else {
+    memcpy(pdu.uuid, BT_UUID_128(chrc->uuid)->val, 16);
+    value_len += 16U;
+  }
+
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
 }
 
-static u8_t gatt_foreach_iter(const struct bt_gatt_attr *attr,
-                              u16_t start_handle, u16_t end_handle,
-                              const struct bt_uuid *uuid,
-                              const void *attr_data, uint16_t *num_matches,
-                              bt_gatt_attr_func_t func, void *user_data)
-{
-    u8_t result;
+static u8_t gatt_foreach_iter(const struct bt_gatt_attr *attr, u16_t start_handle, u16_t end_handle, const struct bt_uuid *uuid, const void *attr_data, uint16_t *num_matches, bt_gatt_attr_func_t func,
+                              void *user_data) {
+  u8_t result;
 
-    /* Stop if over the requested range */
-    if (attr->handle > end_handle) {
-        return BT_GATT_ITER_STOP;
-    }
+  /* Stop if over the requested range */
+  if (attr->handle > end_handle) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    /* Check if attribute handle is within range */
-    if (attr->handle < start_handle) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Check if attribute handle is within range */
+  if (attr->handle < start_handle) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    /* Match attribute UUID if set */
-    if (uuid && bt_uuid_cmp(uuid, attr->uuid)) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Match attribute UUID if set */
+  if (uuid && bt_uuid_cmp(uuid, attr->uuid)) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    /* Match attribute user_data if set */
-    if (attr_data && attr_data != attr->user_data) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Match attribute user_data if set */
+  if (attr_data && attr_data != attr->user_data) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    *num_matches -= 1;
+  *num_matches -= 1;
 
-    result = func(attr, user_data);
+  result = func(attr, user_data);
 
-    if (!*num_matches) {
-        return BT_GATT_ITER_STOP;
-    }
+  if (!*num_matches) {
+    return BT_GATT_ITER_STOP;
+  }
 
-    return result;
+  return result;
 }
 
-static void foreach_attr_type_dyndb(u16_t start_handle, u16_t end_handle,
-                                    const struct bt_uuid *uuid,
-                                    const void *attr_data, uint16_t num_matches,
-                                    bt_gatt_attr_func_t func, void *user_data)
-{
+static void foreach_attr_type_dyndb(u16_t start_handle, u16_t end_handle, const struct bt_uuid *uuid, const void *attr_data, uint16_t num_matches, bt_gatt_attr_func_t func, void *user_data) {
 #if defined(CONFIG_BT_GATT_DYNAMIC_DB)
-    int i;
+  int i;
 
-    struct bt_gatt_service *svc;
+  struct bt_gatt_service *svc;
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&db, svc, node)
-    {
-        struct bt_gatt_service *next;
+  SYS_SLIST_FOR_EACH_CONTAINER(&db, svc, node) {
+    struct bt_gatt_service *next;
 
-        next = SYS_SLIST_PEEK_NEXT_CONTAINER(svc, node);
-        if (next) {
-            /* Skip ahead if start is not within service handles */
-            if (next->attrs[0].handle <= start_handle) {
-                continue;
-            }
-        }
+    next = SYS_SLIST_PEEK_NEXT_CONTAINER(svc, node);
+    if (next) {
+      /* Skip ahead if start is not within service handles */
+      if (next->attrs[0].handle <= start_handle) {
+        continue;
+      }
+    }
 
-        for (i = 0; i < svc->attr_count; i++) {
-            struct bt_gatt_attr *attr = &svc->attrs[i];
-
-            if (gatt_foreach_iter(attr,
-                                  start_handle,
-                                  end_handle,
-                                  uuid, attr_data,
-                                  &num_matches,
-                                  func, user_data) ==
-                BT_GATT_ITER_STOP) {
-                return;
-            }
-        }
+    for (i = 0; i < svc->attr_count; i++) {
+      struct bt_gatt_attr *attr = &svc->attrs[i];
+
+      if (gatt_foreach_iter(attr, start_handle, end_handle, uuid, attr_data, &num_matches, func, user_data) == BT_GATT_ITER_STOP) {
+        return;
+      }
     }
+  }
 #endif /* CONFIG_BT_GATT_DYNAMIC_DB */
 }
 
-void bt_gatt_foreach_attr_type(u16_t start_handle, u16_t end_handle,
-                               const struct bt_uuid *uuid,
-                               const void *attr_data, uint16_t num_matches,
-                               bt_gatt_attr_func_t func, void *user_data)
-{
-    int i;
+void bt_gatt_foreach_attr_type(u16_t start_handle, u16_t end_handle, const struct bt_uuid *uuid, const void *attr_data, uint16_t num_matches, bt_gatt_attr_func_t func, void *user_data) {
+  int i;
 
-    if (!num_matches) {
-        num_matches = UINT16_MAX;
-    }
+  if (!num_matches) {
+    num_matches = UINT16_MAX;
+  }
 #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    if (start_handle <= last_static_handle) {
-        u16_t handle = 1;
-
-        Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc)
-        {
-            /* Skip ahead if start is not within service handles */
-            if (handle + static_svc->attr_count < start_handle) {
-                handle += static_svc->attr_count;
-                continue;
-            }
-
-            for (i = 0; i < static_svc->attr_count; i++, handle++) {
-                struct bt_gatt_attr attr;
-
-                memcpy(&attr, &static_svc->attrs[i],
-                       sizeof(attr));
-
-                attr.handle = handle;
-
-                if (gatt_foreach_iter(&attr, start_handle,
-                                      end_handle, uuid,
-                                      attr_data, &num_matches,
-                                      func, user_data) ==
-                    BT_GATT_ITER_STOP) {
-                    return;
-                }
-            }
+  if (start_handle <= last_static_handle) {
+    u16_t handle = 1;
+
+    Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) {
+      /* Skip ahead if start is not within service handles */
+      if (handle + static_svc->attr_count < start_handle) {
+        handle += static_svc->attr_count;
+        continue;
+      }
+
+      for (i = 0; i < static_svc->attr_count; i++, handle++) {
+        struct bt_gatt_attr attr;
+
+        memcpy(&attr, &static_svc->attrs[i], sizeof(attr));
+
+        attr.handle = handle;
+
+        if (gatt_foreach_iter(&attr, start_handle, end_handle, uuid, attr_data, &num_matches, func, user_data) == BT_GATT_ITER_STOP) {
+          return;
         }
+      }
     }
+  }
 #endif
-    /* Iterate over dynamic db */
-    foreach_attr_type_dyndb(start_handle, end_handle, uuid, attr_data,
-                            num_matches, func, user_data);
+  /* Iterate over dynamic db */
+  foreach_attr_type_dyndb(start_handle, end_handle, uuid, attr_data, num_matches, func, user_data);
 }
 
-static u8_t find_next(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct bt_gatt_attr **next = user_data;
+static u8_t find_next(const struct bt_gatt_attr *attr, void *user_data) {
+  struct bt_gatt_attr **next = user_data;
 
-    *next = (struct bt_gatt_attr *)attr;
+  *next = (struct bt_gatt_attr *)attr;
 
-    return BT_GATT_ITER_STOP;
+  return BT_GATT_ITER_STOP;
 }
 
-struct bt_gatt_attr *bt_gatt_attr_next(const struct bt_gatt_attr *attr)
-{
-    struct bt_gatt_attr *next = NULL;
+struct bt_gatt_attr *bt_gatt_attr_next(const struct bt_gatt_attr *attr) {
+  struct bt_gatt_attr *next = NULL;
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    u16_t handle = attr->handle;
+  u16_t handle = attr->handle;
 #else
-    u16_t handle = attr->handle ?: find_static_attr(attr);
+  u16_t handle = attr->handle ?: find_static_attr(attr);
 #endif
-    bt_gatt_foreach_attr(handle + 1, handle + 1, find_next, &next);
+  bt_gatt_foreach_attr(handle + 1, handle + 1, find_next, &next);
 
-    return next;
+  return next;
 }
 
-static void clear_ccc_cfg(struct bt_gatt_ccc_cfg *cfg)
-{
-    bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY);
-    cfg->id = 0U;
-    cfg->value = 0U;
+static void clear_ccc_cfg(struct bt_gatt_ccc_cfg *cfg) {
+  bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY);
+  cfg->id    = 0U;
+  cfg->value = 0U;
 }
 
-static struct bt_gatt_ccc_cfg *find_ccc_cfg(const struct bt_conn *conn,
-                                            struct _bt_gatt_ccc *ccc)
-{
-    for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        if (conn) {
-            if (conn->id == ccc->cfg[i].id &&
-                !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) {
-                return &ccc->cfg[i];
-            }
-        } else if (!bt_addr_le_cmp(&ccc->cfg[i].peer, BT_ADDR_LE_ANY)) {
-            return &ccc->cfg[i];
-        }
+static struct bt_gatt_ccc_cfg *find_ccc_cfg(const struct bt_conn *conn, struct _bt_gatt_ccc *ccc) {
+  for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    if (conn) {
+      if (conn->id == ccc->cfg[i].id && !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) {
+        return &ccc->cfg[i];
+      }
+    } else if (!bt_addr_le_cmp(&ccc->cfg[i].peer, BT_ADDR_LE_ANY)) {
+      return &ccc->cfg[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn,
-                              const struct bt_gatt_attr *attr, void *buf,
-                              u16_t len, u16_t offset)
-{
-    struct _bt_gatt_ccc *ccc = attr->user_data;
-    const struct bt_gatt_ccc_cfg *cfg;
-    u16_t value;
+ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  struct _bt_gatt_ccc          *ccc = attr->user_data;
+  const struct bt_gatt_ccc_cfg *cfg;
+  u16_t                         value;
 
-    cfg = find_ccc_cfg(conn, ccc);
-    if (cfg) {
-        value = sys_cpu_to_le16(cfg->value);
-    } else {
-        /* Default to disable if there is no cfg for the peer */
-        value = 0x0000;
-    }
+  cfg = find_ccc_cfg(conn, ccc);
+  if (cfg) {
+    value = sys_cpu_to_le16(cfg->value);
+  } else {
+    /* Default to disable if there is no cfg for the peer */
+    value = 0x0000;
+  }
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &value,
-                             sizeof(value));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &value, sizeof(value));
 }
 
-static void gatt_ccc_changed(const struct bt_gatt_attr *attr,
-                             struct _bt_gatt_ccc *ccc)
-{
-    int i;
-    u16_t value = 0x0000;
+static void gatt_ccc_changed(const struct bt_gatt_attr *attr, struct _bt_gatt_ccc *ccc) {
+  int   i;
+  u16_t value = 0x0000;
 
-    for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        if (ccc->cfg[i].value > value) {
-            value = ccc->cfg[i].value;
-        }
+  for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    if (ccc->cfg[i].value > value) {
+      value = ccc->cfg[i].value;
     }
+  }
 
-    BT_DBG("ccc %p value 0x%04x", ccc, value);
+  BT_DBG("ccc %p value 0x%04x", ccc, value);
 
-    if (value != ccc->value) {
-        ccc->value = value;
-        if (ccc->cfg_changed) {
-            ccc->cfg_changed(attr, value);
-        }
+  if (value != ccc->value) {
+    ccc->value = value;
+    if (ccc->cfg_changed) {
+      ccc->cfg_changed(attr, value);
     }
+  }
 }
 
-ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn,
-                               const struct bt_gatt_attr *attr, const void *buf,
-                               u16_t len, u16_t offset, u8_t flags)
-{
-    struct _bt_gatt_ccc *ccc = attr->user_data;
-    struct bt_gatt_ccc_cfg *cfg;
-    u16_t value;
+ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) {
+  struct _bt_gatt_ccc    *ccc = attr->user_data;
+  struct bt_gatt_ccc_cfg *cfg;
+  u16_t                   value;
 
-    if (offset) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
-    }
+  if (offset) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
+  }
 
-    if (!len || len > sizeof(u16_t)) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
-    }
+  if (!len || len > sizeof(u16_t)) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
+  }
 
-    if (len < sizeof(u16_t)) {
-        value = *(u8_t *)buf;
-    } else {
-        value = sys_get_le16(buf);
+  if (len < sizeof(u16_t)) {
+    value = *(u8_t *)buf;
+  } else {
+    value = sys_get_le16(buf);
+  }
+
+  cfg = find_ccc_cfg(conn, ccc);
+  if (!cfg) {
+    /* If there's no existing entry, but the new value is zero,
+     * we don't need to do anything, since a disabled CCC is
+     * behavioraly the same as no written CCC.
+     */
+    if (!value) {
+      return len;
     }
 
-    cfg = find_ccc_cfg(conn, ccc);
+    cfg = find_ccc_cfg(NULL, ccc);
     if (!cfg) {
-        /* If there's no existing entry, but the new value is zero,
-		 * we don't need to do anything, since a disabled CCC is
-		 * behavioraly the same as no written CCC.
-		 */
-        if (!value) {
-            return len;
-        }
-
-        cfg = find_ccc_cfg(NULL, ccc);
-        if (!cfg) {
-            BT_WARN("No space to store CCC cfg");
-            return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
-        }
-
-        bt_addr_le_copy(&cfg->peer, &conn->le.dst);
-        cfg->id = conn->id;
+      BT_WARN("No space to store CCC cfg");
+      return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES);
     }
 
-    /* Confirm write if cfg is managed by application */
-    if (ccc->cfg_write && !ccc->cfg_write(conn, attr, value)) {
-        return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
-    }
+    bt_addr_le_copy(&cfg->peer, &conn->le.dst);
+    cfg->id = conn->id;
+  }
 
-    cfg->value = value;
+  /* Confirm write if cfg is managed by application */
+  if (ccc->cfg_write && !ccc->cfg_write(conn, attr, value)) {
+    return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
+  }
 
-    BT_DBG("handle 0x%04x value %u", attr->handle, cfg->value);
+  cfg->value = value;
 
-    /* Update cfg if don't match */
-    if (cfg->value != ccc->value) {
-        gatt_ccc_changed(attr, ccc);
+  BT_DBG("handle 0x%04x value %u", attr->handle, cfg->value);
+
+  /* Update cfg if don't match */
+  if (cfg->value != ccc->value) {
+    gatt_ccc_changed(attr, ccc);
 
 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
-        if ((!gatt_ccc_conn_is_queued(conn)) &&
-            bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-            /* Store the connection with the same index it has in
-			 * the conns array
-			 */
-            gatt_ccc_store.conn_list[bt_conn_index(conn)] =
-                bt_conn_ref(conn);
-            k_delayed_work_submit(&gatt_ccc_store.work,
-                                  CCC_STORE_DELAY);
-        }
-#endif
+    if ((!gatt_ccc_conn_is_queued(conn)) && bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+      /* Store the connection with the same index it has in
+       * the conns array
+       */
+      gatt_ccc_store.conn_list[bt_conn_index(conn)] = bt_conn_ref(conn);
+      k_delayed_work_submit(&gatt_ccc_store.work, CCC_STORE_DELAY);
     }
+#endif
+  }
 
-    /* Disabled CCC is the same as no configured CCC, so clear the entry */
-    if (!value) {
-        clear_ccc_cfg(cfg);
-    }
+  /* Disabled CCC is the same as no configured CCC, so clear the entry */
+  if (!value) {
+    clear_ccc_cfg(cfg);
+  }
 
-    return len;
+  return len;
 }
 
-ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn,
-                              const struct bt_gatt_attr *attr, void *buf,
-                              u16_t len, u16_t offset)
-{
-    const struct bt_gatt_cep *value = attr->user_data;
-    u16_t props = sys_cpu_to_le16(value->properties);
+ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  const struct bt_gatt_cep *value = attr->user_data;
+  u16_t                     props = sys_cpu_to_le16(value->properties);
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &props,
-                             sizeof(props));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &props, sizeof(props));
 }
 
-ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn,
-                              const struct bt_gatt_attr *attr, void *buf,
-                              u16_t len, u16_t offset)
-{
-    const char *value = attr->user_data;
+ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  const char *value = attr->user_data;
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
-                             strlen(value));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, value, strlen(value));
 }
 
-ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn,
-                              const struct bt_gatt_attr *attr, void *buf,
-                              u16_t len, u16_t offset)
-{
-    const struct bt_gatt_cpf *value = attr->user_data;
+ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  const struct bt_gatt_cpf *value = attr->user_data;
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
-                             sizeof(*value));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, value, sizeof(*value));
 }
 
 struct notify_data {
-    int err;
-    u16_t type;
-    union {
-        struct bt_gatt_notify_params *nfy_params;
-        struct bt_gatt_indicate_params *ind_params;
-    };
+  int   err;
+  u16_t type;
+  union {
+    struct bt_gatt_notify_params   *nfy_params;
+    struct bt_gatt_indicate_params *ind_params;
+  };
 };
 
-static int gatt_notify(struct bt_conn *conn, u16_t handle,
-                       struct bt_gatt_notify_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_notify *nfy;
+static int gatt_notify(struct bt_conn *conn, u16_t handle, struct bt_gatt_notify_params *params) {
+  struct net_buf       *buf;
+  struct bt_att_notify *nfy;
 
 #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE)
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
-	 * Except for the Handle Value indication, the  server shall not send
-	 * notifications and indications to such a client until it becomes
-	 * change-aware.
-	 */
-    if (!bt_gatt_change_aware(conn, false)) {
-        return -EAGAIN;
-    }
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
+   * Except for the Handle Value indication, the  server shall not send
+   * notifications and indications to such a client until it becomes
+   * change-aware.
+   */
+  if (!bt_gatt_change_aware(conn, false)) {
+    return -EAGAIN;
+  }
 #endif
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY,
-                            sizeof(*nfy) + params->len);
-    if (!buf) {
-        BT_WARN("No buffer available to send notification");
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY, sizeof(*nfy) + params->len);
+  if (!buf) {
+    BT_WARN("No buffer available to send notification");
+    return -ENOMEM;
+  }
 
-    BT_DBG("conn %p handle 0x%04x", conn, handle);
+  BT_DBG("conn %p handle 0x%04x", conn, handle);
 
-    nfy = net_buf_add(buf, sizeof(*nfy));
-    nfy->handle = sys_cpu_to_le16(handle);
+  nfy         = net_buf_add(buf, sizeof(*nfy));
+  nfy->handle = sys_cpu_to_le16(handle);
 
-    net_buf_add(buf, params->len);
-    memcpy(nfy->value, params->data, params->len);
+  net_buf_add(buf, params->len);
+  memcpy(nfy->value, params->data, params->len);
 
-    return bt_att_send(conn, buf, params->func, params->user_data);
+  return bt_att_send(conn, buf, params->func, params->user_data);
 }
 
-static void gatt_indicate_rsp(struct bt_conn *conn, u8_t err,
-                              const void *pdu, u16_t length, void *user_data)
-{
-    struct bt_gatt_indicate_params *params = user_data;
+static void gatt_indicate_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_indicate_params *params = user_data;
 
-    params->func(conn, params->attr, err);
+  params->func(conn, params->attr, err);
 }
 
-static int gatt_send(struct bt_conn *conn, struct net_buf *buf,
-                     bt_att_func_t func, void *params,
-                     bt_att_destroy_t destroy)
-{
-    int err;
+static int gatt_send(struct bt_conn *conn, struct net_buf *buf, bt_att_func_t func, void *params, bt_att_destroy_t destroy) {
+  int err;
 
-    if (params) {
-        struct bt_att_req *req = params;
-        req->buf = buf;
-        req->func = func;
-        req->destroy = destroy;
+  if (params) {
+    struct bt_att_req *req = params;
+    req->buf               = buf;
+    req->func              = func;
+    req->destroy           = destroy;
 
-        err = bt_att_req_send(conn, req);
-    } else {
-        err = bt_att_send(conn, buf, NULL, NULL);
-    }
+    err = bt_att_req_send(conn, req);
+  } else {
+    err = bt_att_send(conn, buf, NULL, NULL);
+  }
 
-    if (err) {
-        BT_ERR("Error sending ATT PDU: %d", err);
-    }
+  if (err) {
+    BT_ERR("Error sending ATT PDU: %d", err);
+  }
 
-    return err;
+  return err;
 }
 
-static int gatt_indicate(struct bt_conn *conn, u16_t handle,
-                         struct bt_gatt_indicate_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_indicate *ind;
+static int gatt_indicate(struct bt_conn *conn, u16_t handle, struct bt_gatt_indicate_params *params) {
+  struct net_buf         *buf;
+  struct bt_att_indicate *ind;
 
 #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE)
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
-	 * Except for the Handle Value indication, the  server shall not send
-	 * notifications and indications to such a client until it becomes
-	 * change-aware.
-	 */
-    if (!(params->func && (params->func == sc_indicate_rsp ||
-                           params->func == sc_restore_rsp)) &&
-        !bt_gatt_change_aware(conn, false)) {
-        return -EAGAIN;
-    }
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
+   * Except for the Handle Value indication, the  server shall not send
+   * notifications and indications to such a client until it becomes
+   * change-aware.
+   */
+  if (!(params->func && (params->func == sc_indicate_rsp || params->func == sc_restore_rsp)) && !bt_gatt_change_aware(conn, false)) {
+    return -EAGAIN;
+  }
 #endif
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_INDICATE,
-                            sizeof(*ind) + params->len);
-    if (!buf) {
-        BT_WARN("No buffer available to send indication");
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_INDICATE, sizeof(*ind) + params->len);
+  if (!buf) {
+    BT_WARN("No buffer available to send indication");
+    return -ENOMEM;
+  }
 
-    BT_DBG("conn %p handle 0x%04x", conn, handle);
+  BT_DBG("conn %p handle 0x%04x", conn, handle);
 
-    ind = net_buf_add(buf, sizeof(*ind));
-    ind->handle = sys_cpu_to_le16(handle);
+  ind         = net_buf_add(buf, sizeof(*ind));
+  ind->handle = sys_cpu_to_le16(handle);
 
-    net_buf_add(buf, params->len);
-    memcpy(ind->value, params->data, params->len);
+  net_buf_add(buf, params->len);
+  memcpy(ind->value, params->data, params->len);
 
-    if (!params->func) {
-        return gatt_send(conn, buf, NULL, NULL, NULL);
-    }
+  if (!params->func) {
+    return gatt_send(conn, buf, NULL, NULL, NULL);
+  }
 
-    return gatt_send(conn, buf, gatt_indicate_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_indicate_rsp, params, NULL);
 }
 
-static u8_t notify_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct notify_data *data = user_data;
-    struct _bt_gatt_ccc *ccc;
-    size_t i;
+static u8_t notify_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct notify_data  *data = user_data;
+  struct _bt_gatt_ccc *ccc;
+  size_t               i;
 
-    /* Check attribute user_data must be of type struct _bt_gatt_ccc */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Check attribute user_data must be of type struct _bt_gatt_ccc */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    ccc = attr->user_data;
-
-    /* Save Service Changed data if peer is not connected */
-    if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) {
-        for (i = 0; i < ARRAY_SIZE(sc_cfg); i++) {
-            struct gatt_sc_cfg *cfg = &sc_cfg[i];
-            struct bt_conn *conn;
-
-            if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) {
-                continue;
-            }
-
-            conn = bt_conn_lookup_state_le(&cfg->peer,
-                                           BT_CONN_CONNECTED);
-            if (!conn) {
-                struct sc_data *sc;
-
-                sc = (struct sc_data *)data->ind_params->data;
-                sc_save(cfg->id, &cfg->peer,
-                        sys_le16_to_cpu(sc->start),
-                        sys_le16_to_cpu(sc->end));
-                continue;
-            }
-            bt_conn_unref(conn);
-        }
+  ccc = attr->user_data;
+
+  /* Save Service Changed data if peer is not connected */
+  if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) {
+    for (i = 0; i < ARRAY_SIZE(sc_cfg); i++) {
+      struct gatt_sc_cfg *cfg = &sc_cfg[i];
+      struct bt_conn     *conn;
+
+      if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) {
+        continue;
+      }
+
+      conn = bt_conn_lookup_state_le(&cfg->peer, BT_CONN_CONNECTED);
+      if (!conn) {
+        struct sc_data *sc;
+
+        sc = (struct sc_data *)data->ind_params->data;
+        sc_save(cfg->id, &cfg->peer, sys_le16_to_cpu(sc->start), sys_le16_to_cpu(sc->end));
+        continue;
+      }
+      bt_conn_unref(conn);
     }
+  }
 
-    /* Notify all peers configured */
-    for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
-        struct bt_conn *conn;
-        int err;
-
-        /* Check if config value matches data type since consolidated
-		 * value may be for a different peer.
-		 */
-        if (cfg->value != data->type) {
-            continue;
-        }
+  /* Notify all peers configured */
+  for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
+    struct bt_conn         *conn;
+    int                     err;
 
-        conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
-        if (!conn) {
-            continue;
-        }
+    /* Check if config value matches data type since consolidated
+     * value may be for a different peer.
+     */
+    if (cfg->value != data->type) {
+      continue;
+    }
 
-        if (conn->state != BT_CONN_CONNECTED) {
-            bt_conn_unref(conn);
-            continue;
-        }
+    conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
+    if (!conn) {
+      continue;
+    }
 
-        /* Confirm match if cfg is managed by application */
-        if (ccc->cfg_match && !ccc->cfg_match(conn, attr)) {
-            bt_conn_unref(conn);
-            continue;
-        }
+    if (conn->state != BT_CONN_CONNECTED) {
+      bt_conn_unref(conn);
+      continue;
+    }
 
-        if (data->type == BT_GATT_CCC_INDICATE) {
-            err = gatt_indicate(conn, attr->handle - 1,
-                                data->ind_params);
-        } else {
-            err = gatt_notify(conn, attr->handle - 1,
-                              data->nfy_params);
-        }
+    /* Confirm match if cfg is managed by application */
+    if (ccc->cfg_match && !ccc->cfg_match(conn, attr)) {
+      bt_conn_unref(conn);
+      continue;
+    }
 
-        bt_conn_unref(conn);
+    if (data->type == BT_GATT_CCC_INDICATE) {
+      err = gatt_indicate(conn, attr->handle - 1, data->ind_params);
+    } else {
+      err = gatt_notify(conn, attr->handle - 1, data->nfy_params);
+    }
 
-        if (err < 0) {
-            return BT_GATT_ITER_STOP;
-        }
+    bt_conn_unref(conn);
 
-        data->err = 0;
+    if (err < 0) {
+      return BT_GATT_ITER_STOP;
     }
 
-    return BT_GATT_ITER_CONTINUE;
+    data->err = 0;
+  }
+
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t match_uuid(const struct bt_gatt_attr *attr, void *user_data)
-{
-    const struct bt_gatt_attr **found = user_data;
+static u8_t match_uuid(const struct bt_gatt_attr *attr, void *user_data) {
+  const struct bt_gatt_attr **found = user_data;
 
-    *found = attr;
+  *found = attr;
 
-    return BT_GATT_ITER_STOP;
+  return BT_GATT_ITER_STOP;
 }
 
-int bt_gatt_notify_cb(struct bt_conn *conn,
-                      struct bt_gatt_notify_params *params)
-{
-    struct notify_data data;
-    const struct bt_gatt_attr *attr;
-    u16_t handle;
+int bt_gatt_notify_cb(struct bt_conn *conn, struct bt_gatt_notify_params *params) {
+  struct notify_data         data;
+  const struct bt_gatt_attr *attr;
+  u16_t                      handle;
+
+  __ASSERT(params, "invalid parameters\n");
+  __ASSERT(params->attr, "invalid parameters\n");
 
-    __ASSERT(params, "invalid parameters\n");
-    __ASSERT(params->attr, "invalid parameters\n");
+  attr = params->attr;
+
+  if (conn && conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
+#if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
+  handle = attr->handle ?: find_static_attr(attr);
+#endif
+  if (!handle) {
+    return -ENOENT;
+  }
 
-    attr = params->attr;
+  /* Lookup UUID if it was given */
+  if (params->uuid) {
+    attr = NULL;
 
-    if (conn && conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
+    bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid, NULL, 1, match_uuid, &attr);
+    if (!attr) {
+      return -ENOENT;
     }
 #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
     handle = attr->handle ?: find_static_attr(attr);
 #endif
     if (!handle) {
-        return -ENOENT;
+      return -ENOENT;
     }
+  }
 
-    /* Lookup UUID if it was given */
-    if (params->uuid) {
-        attr = NULL;
+  /* Check if attribute is a characteristic then adjust the handle */
+  if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
+    struct bt_gatt_chrc *chrc = attr->user_data;
 
-        bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid,
-                                  NULL, 1, match_uuid, &attr);
-        if (!attr) {
-            return -ENOENT;
-        }
-#if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-        handle = attr->handle ?: find_static_attr(attr);
-#endif
-        if (!handle) {
-            return -ENOENT;
-        }
+    if (!(chrc->properties & BT_GATT_CHRC_NOTIFY)) {
+      return -EINVAL;
     }
 
-    /* Check if attribute is a characteristic then adjust the handle */
-    if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
-        struct bt_gatt_chrc *chrc = attr->user_data;
+    handle = bt_gatt_attr_value_handle(attr);
+  }
 
-        if (!(chrc->properties & BT_GATT_CHRC_NOTIFY)) {
-            return -EINVAL;
-        }
+  if (conn) {
+    return gatt_notify(conn, handle, params);
+  }
 
-        handle = bt_gatt_attr_value_handle(attr);
-    }
+  data.err        = -ENOTCONN;
+  data.type       = BT_GATT_CCC_NOTIFY;
+  data.nfy_params = params;
 
-    if (conn) {
-        return gatt_notify(conn, handle, params);
-    }
+  bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, notify_cb, &data);
 
-    data.err = -ENOTCONN;
-    data.type = BT_GATT_CCC_NOTIFY;
-    data.nfy_params = params;
+  return data.err;
+}
 
-    bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1,
-                              notify_cb, &data);
+int bt_gatt_indicate(struct bt_conn *conn, struct bt_gatt_indicate_params *params) {
+  struct notify_data         data;
+  const struct bt_gatt_attr *attr;
+  u16_t                      handle;
 
-    return data.err;
-}
+  __ASSERT(params, "invalid parameters\n");
+  __ASSERT(params->attr, "invalid parameters\n");
 
-int bt_gatt_indicate(struct bt_conn *conn,
-                     struct bt_gatt_indicate_params *params)
-{
-    struct notify_data data;
-    const struct bt_gatt_attr *attr;
-    u16_t handle;
+  attr = params->attr;
 
-    __ASSERT(params, "invalid parameters\n");
-    __ASSERT(params->attr, "invalid parameters\n");
+  if (conn && conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
+#if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
+  handle = attr->handle ?: find_static_attr(attr);
+#endif
+  if (!handle) {
+    return -ENOENT;
+  }
 
-    attr = params->attr;
+  /* Lookup UUID if it was given */
+  if (params->uuid) {
+    attr = NULL;
 
-    if (conn && conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
+    bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid, NULL, 1, match_uuid, &attr);
+    if (!attr) {
+      return -ENOENT;
     }
 #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
     handle = attr->handle ?: find_static_attr(attr);
 #endif
     if (!handle) {
-        return -ENOENT;
+      return -ENOENT;
     }
+  }
 
-    /* Lookup UUID if it was given */
-    if (params->uuid) {
-        attr = NULL;
+  /* Check if attribute is a characteristic then adjust the handle */
+  if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
+    struct bt_gatt_chrc *chrc = params->attr->user_data;
 
-        bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid,
-                                  NULL, 1, match_uuid, &attr);
-        if (!attr) {
-            return -ENOENT;
-        }
-#if !defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-        handle = attr->handle ?: find_static_attr(attr);
-#endif
-        if (!handle) {
-            return -ENOENT;
-        }
+    if (!(chrc->properties & BT_GATT_CHRC_INDICATE)) {
+      return -EINVAL;
     }
 
-    /* Check if attribute is a characteristic then adjust the handle */
-    if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
-        struct bt_gatt_chrc *chrc = params->attr->user_data;
-
-        if (!(chrc->properties & BT_GATT_CHRC_INDICATE)) {
-            return -EINVAL;
-        }
-
-        handle = bt_gatt_attr_value_handle(params->attr);
-    }
+    handle = bt_gatt_attr_value_handle(params->attr);
+  }
 
-    if (conn) {
-        return gatt_indicate(conn, handle, params);
-    }
+  if (conn) {
+    return gatt_indicate(conn, handle, params);
+  }
 
-    data.err = -ENOTCONN;
-    data.type = BT_GATT_CCC_INDICATE;
-    data.ind_params = params;
+  data.err        = -ENOTCONN;
+  data.type       = BT_GATT_CCC_INDICATE;
+  data.ind_params = params;
 
-    bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1,
-                              notify_cb, &data);
+  bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, notify_cb, &data);
 
-    return data.err;
+  return data.err;
 }
 
-u16_t bt_gatt_get_mtu(struct bt_conn *conn)
-{
-    return bt_att_get_mtu(conn);
-}
+u16_t bt_gatt_get_mtu(struct bt_conn *conn) { return bt_att_get_mtu(conn); }
 
-u8_t bt_gatt_check_perm(struct bt_conn *conn, const struct bt_gatt_attr *attr,
-                        u8_t mask)
-{
-    if ((mask & BT_GATT_PERM_READ) &&
-        (!(attr->perm & BT_GATT_PERM_READ_MASK) || !attr->read)) {
-        return BT_ATT_ERR_READ_NOT_PERMITTED;
-    }
+u8_t bt_gatt_check_perm(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t mask) {
+  if ((mask & BT_GATT_PERM_READ) && (!(attr->perm & BT_GATT_PERM_READ_MASK) || !attr->read)) {
+    return BT_ATT_ERR_READ_NOT_PERMITTED;
+  }
 
-    if ((mask & BT_GATT_PERM_WRITE) &&
-        (!(attr->perm & BT_GATT_PERM_WRITE_MASK) || !attr->write)) {
-        return BT_ATT_ERR_WRITE_NOT_PERMITTED;
-    }
+  if ((mask & BT_GATT_PERM_WRITE) && (!(attr->perm & BT_GATT_PERM_WRITE_MASK) || !attr->write)) {
+    return BT_ATT_ERR_WRITE_NOT_PERMITTED;
+  }
 
-    mask &= attr->perm;
-    if (mask & BT_GATT_PERM_AUTHEN_MASK) {
-        if (bt_conn_get_security(conn) < BT_SECURITY_L3) {
-            return BT_ATT_ERR_AUTHENTICATION;
-        }
+  mask &= attr->perm;
+  if (mask & BT_GATT_PERM_AUTHEN_MASK) {
+    if (bt_conn_get_security(conn) < BT_SECURITY_L3) {
+      return BT_ATT_ERR_AUTHENTICATION;
     }
+  }
 
-    if ((mask & BT_GATT_PERM_ENCRYPT_MASK)) {
+  if ((mask & BT_GATT_PERM_ENCRYPT_MASK)) {
 #if defined(CONFIG_BT_SMP)
-        if (!conn->encrypt) {
-            return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
-        }
+    if (!conn->encrypt) {
+      return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
+    }
 #else
-        return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
+    return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
 #endif /* CONFIG_BT_SMP */
-    }
+  }
 
-    return 0;
+  return 0;
 }
 
-static void sc_restore_rsp(struct bt_conn *conn,
-                           const struct bt_gatt_attr *attr, u8_t err)
-{
+static void sc_restore_rsp(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t err) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    struct gatt_cf_cfg *cfg;
+  struct gatt_cf_cfg *cfg;
 #endif
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
 #if defined(CONFIG_BT_GATT_CACHING)
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
-	 * 2.5.2.1 Robust Caching
-	 * A connected client becomes change-aware when...
-	 * The client receives and confirms a Service Changed indication.
-	 */
-    cfg = find_cf_cfg(conn);
-    if (cfg && CF_ROBUST_CACHING(cfg)) {
-        atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
-        BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
-    }
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
+   * 2.5.2.1 Robust Caching
+   * A connected client becomes change-aware when...
+   * The client receives and confirms a Service Changed indication.
+   */
+  cfg = find_cf_cfg(conn);
+  if (cfg && CF_ROBUST_CACHING(cfg)) {
+    atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
+    BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
+  }
 #endif
 }
 
 static struct bt_gatt_indicate_params sc_restore_params[CONFIG_BT_MAX_CONN];
 
-static void sc_restore(struct bt_conn *conn)
-{
-    struct gatt_sc_cfg *cfg;
-    u16_t sc_range[2];
-    u8_t index;
+static void sc_restore(struct bt_conn *conn) {
+  struct gatt_sc_cfg *cfg;
+  u16_t               sc_range[2];
+  u8_t                index;
 
-    cfg = find_sc_cfg(conn->id, &conn->le.dst);
-    if (!cfg) {
-        BT_DBG("no SC data found");
-        return;
-    }
+  cfg = find_sc_cfg(conn->id, &conn->le.dst);
+  if (!cfg) {
+    BT_DBG("no SC data found");
+    return;
+  }
 
-    if (!(cfg->data.start || cfg->data.end)) {
-        return;
-    }
+  if (!(cfg->data.start || cfg->data.end)) {
+    return;
+  }
 
-    BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(&cfg->peer),
-           cfg->data.start, cfg->data.end);
+  BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(&cfg->peer), cfg->data.start, cfg->data.end);
 
-    sc_range[0] = sys_cpu_to_le16(cfg->data.start);
-    sc_range[1] = sys_cpu_to_le16(cfg->data.end);
+  sc_range[0] = sys_cpu_to_le16(cfg->data.start);
+  sc_range[1] = sys_cpu_to_le16(cfg->data.end);
 
-    index = bt_conn_index(conn);
+  index = bt_conn_index(conn);
 #if defined(BFLB_BLE_DISABLE_STATIC_ATTR)
-    sc_restore_params[index].attr = &gatt_attrs[2];
+  sc_restore_params[index].attr = &gatt_attrs[2];
 #else
-    sc_restore_params[index].attr = &_1_gatt_svc.attrs[2];
+  sc_restore_params[index].attr = &_1_gatt_svc.attrs[2];
 #endif
-    sc_restore_params[index].func = sc_restore_rsp;
-    sc_restore_params[index].data = &sc_range[0];
-    sc_restore_params[index].len = sizeof(sc_range);
+  sc_restore_params[index].func = sc_restore_rsp;
+  sc_restore_params[index].data = &sc_range[0];
+  sc_restore_params[index].len  = sizeof(sc_range);
 
-    if (bt_gatt_indicate(conn, &sc_restore_params[index])) {
-        BT_ERR("SC restore indication failed");
-    }
+  if (bt_gatt_indicate(conn, &sc_restore_params[index])) {
+    BT_ERR("SC restore indication failed");
+  }
 
-    /* Reset config data */
-    sc_reset(cfg);
+  /* Reset config data */
+  sc_reset(cfg);
 }
 
 struct conn_data {
-    struct bt_conn *conn;
-    bt_security_t sec;
+  struct bt_conn *conn;
+  bt_security_t   sec;
 };
 
-static u8_t update_ccc(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct conn_data *data = user_data;
-    struct bt_conn *conn = data->conn;
-    struct _bt_gatt_ccc *ccc;
-    size_t i;
-    u8_t err;
-
-    /* Check attribute user_data must be of type struct _bt_gatt_ccc */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
+static u8_t update_ccc(const struct bt_gatt_attr *attr, void *user_data) {
+  struct conn_data    *data = user_data;
+  struct bt_conn      *conn = data->conn;
+  struct _bt_gatt_ccc *ccc;
+  size_t               i;
+  u8_t                 err;
+
+  /* Check attribute user_data must be of type struct _bt_gatt_ccc */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
+
+  ccc = attr->user_data;
+
+  for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    /* Ignore configuration for different peer */
+    if (bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) {
+      continue;
     }
 
-    ccc = attr->user_data;
+    /* Check if attribute requires encryption/authentication */
+    err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_WRITE_MASK);
+    if (err) {
+      bt_security_t sec;
 
-    for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        /* Ignore configuration for different peer */
-        if (bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) {
-            continue;
-        }
+      if (err == BT_ATT_ERR_WRITE_NOT_PERMITTED) {
+        BT_WARN("CCC %p not writable", attr);
+        continue;
+      }
 
-        /* Check if attribute requires encryption/authentication */
-        err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_WRITE_MASK);
-        if (err) {
-            bt_security_t sec;
-
-            if (err == BT_ATT_ERR_WRITE_NOT_PERMITTED) {
-                BT_WARN("CCC %p not writable", attr);
-                continue;
-            }
-
-            sec = BT_SECURITY_L2;
-
-            if (err == BT_ATT_ERR_AUTHENTICATION) {
-                sec = BT_SECURITY_L3;
-            }
-
-            /* Check if current security is enough */
-            if (IS_ENABLED(CONFIG_BT_SMP) &&
-                bt_conn_get_security(conn) < sec) {
-                if (data->sec < sec) {
-                    data->sec = sec;
-                }
-                continue;
-            }
-        }
+      sec = BT_SECURITY_L2;
+
+      if (err == BT_ATT_ERR_AUTHENTICATION) {
+        sec = BT_SECURITY_L3;
+      }
 
-        if (ccc->cfg[i].value) {
-            gatt_ccc_changed(attr, ccc);
-            if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) &&
-                ccc == &sc_ccc) {
-                sc_restore(conn);
-            }
-            return BT_GATT_ITER_CONTINUE;
+      /* Check if current security is enough */
+      if (IS_ENABLED(CONFIG_BT_SMP) && bt_conn_get_security(conn) < sec) {
+        if (data->sec < sec) {
+          data->sec = sec;
         }
+        continue;
+      }
     }
 
-    return BT_GATT_ITER_CONTINUE;
+    if (ccc->cfg[i].value) {
+      gatt_ccc_changed(attr, ccc);
+      if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) {
+        sc_restore(conn);
+      }
+      return BT_GATT_ITER_CONTINUE;
+    }
+  }
+
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static u8_t disconnected_cb(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct bt_conn *conn = user_data;
-    struct _bt_gatt_ccc *ccc;
-    bool value_used;
-    size_t i;
-
-    /* Check attribute user_data must be of type struct _bt_gatt_ccc */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+static u8_t disconnected_cb(const struct bt_gatt_attr *attr, void *user_data) {
+  struct bt_conn      *conn = user_data;
+  struct _bt_gatt_ccc *ccc;
+  bool                 value_used;
+  size_t               i;
 
-    ccc = attr->user_data;
+  /* Check attribute user_data must be of type struct _bt_gatt_ccc */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    /* If already disabled skip */
-    if (!ccc->value) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  ccc = attr->user_data;
 
-    /* Checking if all values are disabled */
-    value_used = false;
+  /* If already disabled skip */
+  if (!ccc->value) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
+  /* Checking if all values are disabled */
+  value_used = false;
 
-        /* Ignore configurations with disabled value */
-        if (!cfg->value) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
 
-        if (conn->id != cfg->id ||
-            bt_conn_addr_le_cmp(conn, &cfg->peer)) {
-            struct bt_conn *tmp;
-
-            /* Skip if there is another peer connected */
-            tmp = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
-            if (tmp) {
-                if (tmp->state == BT_CONN_CONNECTED) {
-                    value_used = true;
-                }
-
-                bt_conn_unref(tmp);
-            }
-        } else {
-            /* Clear value if not paired */
-            if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-                clear_ccc_cfg(cfg);
-            } else {
-                /* Update address in case it has changed */
-                bt_addr_le_copy(&cfg->peer, &conn->le.dst);
-            }
-        }
+    /* Ignore configurations with disabled value */
+    if (!cfg->value) {
+      continue;
     }
 
-    /* If all values are now disabled, reset value while disconnected */
-    if (!value_used) {
-        ccc->value = 0U;
-        if (ccc->cfg_changed) {
-            ccc->cfg_changed(attr, ccc->value);
+    if (conn->id != cfg->id || bt_conn_addr_le_cmp(conn, &cfg->peer)) {
+      struct bt_conn *tmp;
+
+      /* Skip if there is another peer connected */
+      tmp = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
+      if (tmp) {
+        if (tmp->state == BT_CONN_CONNECTED) {
+          value_used = true;
         }
 
-        BT_DBG("ccc %p reseted", ccc);
+        bt_conn_unref(tmp);
+      }
+    } else {
+      /* Clear value if not paired */
+      if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+        clear_ccc_cfg(cfg);
+      } else {
+        /* Update address in case it has changed */
+        bt_addr_le_copy(&cfg->peer, &conn->le.dst);
+      }
     }
+  }
 
-    return BT_GATT_ITER_CONTINUE;
-}
+  /* If all values are now disabled, reset value while disconnected */
+  if (!value_used) {
+    ccc->value = 0U;
+    if (ccc->cfg_changed) {
+      ccc->cfg_changed(attr, ccc->value);
+    }
 
-bool bt_gatt_is_subscribed(struct bt_conn *conn,
-                           const struct bt_gatt_attr *attr, u16_t ccc_value)
-{
-    const struct _bt_gatt_ccc *ccc;
+    BT_DBG("ccc %p reseted", ccc);
+  }
 
-    __ASSERT(conn, "invalid parameter\n");
-    __ASSERT(attr, "invalid parameter\n");
+  return BT_GATT_ITER_CONTINUE;
+}
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return false;
-    }
+bool bt_gatt_is_subscribed(struct bt_conn *conn, const struct bt_gatt_attr *attr, u16_t ccc_value) {
+  const struct _bt_gatt_ccc *ccc;
 
-    /* Check if attribute is a characteristic declaration */
-    if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
-        struct bt_gatt_chrc *chrc = attr->user_data;
+  __ASSERT(conn, "invalid parameter\n");
+  __ASSERT(attr, "invalid parameter\n");
 
-        if (!(chrc->properties &
-              (BT_GATT_CHRC_NOTIFY | BT_GATT_CHRC_INDICATE))) {
-            /* Characteristic doesn't support subscription */
-            return false;
-        }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return false;
+  }
 
-        attr = bt_gatt_attr_next(attr);
-    }
+  /* Check if attribute is a characteristic declaration */
+  if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) {
+    struct bt_gatt_chrc *chrc = attr->user_data;
 
-    /* Check if attribute is a characteristic value */
-    if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) {
-        attr = bt_gatt_attr_next(attr);
+    if (!(chrc->properties & (BT_GATT_CHRC_NOTIFY | BT_GATT_CHRC_INDICATE))) {
+      /* Characteristic doesn't support subscription */
+      return false;
     }
 
-    /* Check if the attribute is the CCC Descriptor */
-    if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) {
-        return false;
-    }
+    attr = bt_gatt_attr_next(attr);
+  }
 
-    ccc = attr->user_data;
+  /* Check if attribute is a characteristic value */
+  if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) {
+    attr = bt_gatt_attr_next(attr);
+  }
 
-    /* Check if the connection is subscribed */
-    for (size_t i = 0; i < BT_GATT_CCC_MAX; i++) {
-        if (conn->id == ccc->cfg[i].id &&
-            !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer) &&
-            (ccc_value & ccc->cfg[i].value)) {
-            return true;
-        }
+  /* Check if the attribute is the CCC Descriptor */
+  if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) {
+    return false;
+  }
+
+  ccc = attr->user_data;
+
+  /* Check if the connection is subscribed */
+  for (size_t i = 0; i < BT_GATT_CCC_MAX; i++) {
+    if (conn->id == ccc->cfg[i].id && !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer) && (ccc_value & ccc->cfg[i].value)) {
+      return true;
     }
+  }
 
-    return false;
+  return false;
 }
 
 #if defined(CONFIG_BT_GATT_CLIENT)
-void bt_gatt_notification(struct bt_conn *conn, u16_t handle,
-                          const void *data, u16_t length)
-{
-    struct bt_gatt_subscribe_params *params, *tmp;
-
-    BT_DBG("handle 0x%04x length %u", handle, length);
-
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node)
-    {
-        if (bt_conn_addr_le_cmp(conn, ¶ms->_peer) ||
-            handle != params->value_handle) {
-            continue;
-        }
+#if defined(BFLB_BLE_NOTIFY_ALL)
+void bt_gatt_register_notification_callback(bt_notification_all_cb_t cb) { gatt_notify_all_cb = cb; }
+#endif
+void bt_gatt_notification(struct bt_conn *conn, u16_t handle, const void *data, u16_t length) {
+  struct bt_gatt_subscribe_params *params, *tmp;
+
+  BT_DBG("handle 0x%04x length %u", handle, length);
+#if defined(BFLB_BLE_NOTIFY_ALL)
+  if (gatt_notify_all_cb) {
+    gatt_notify_all_cb(conn, handle, data, length);
+  }
+#endif
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) {
+    if (bt_conn_addr_le_cmp(conn, ¶ms->_peer) || handle != params->value_handle) {
+      continue;
+    }
 
-        if (params->notify(conn, params, data, length) ==
-            BT_GATT_ITER_STOP) {
-            bt_gatt_unsubscribe(conn, params);
-        }
+    if (params->notify(conn, params, data, length) == BT_GATT_ITER_STOP) {
+      bt_gatt_unsubscribe(conn, params);
     }
+  }
 }
 
-static void update_subscription(struct bt_conn *conn,
-                                struct bt_gatt_subscribe_params *params)
-{
-    if (params->_peer.type == BT_ADDR_LE_PUBLIC) {
-        return;
-    }
+static void update_subscription(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) {
+  if (params->_peer.type == BT_ADDR_LE_PUBLIC) {
+    return;
+  }
 
-    /* Update address */
-    bt_addr_le_copy(¶ms->_peer, &conn->le.dst);
+  /* Update address */
+  bt_addr_le_copy(¶ms->_peer, &conn->le.dst);
 }
 
-static void gatt_subscription_remove(struct bt_conn *conn, sys_snode_t *prev,
-                                     struct bt_gatt_subscribe_params *params)
-{
-    /* Remove subscription from the list*/
-    sys_slist_remove(&subscriptions, prev, ¶ms->node);
+static void gatt_subscription_remove(struct bt_conn *conn, sys_snode_t *prev, struct bt_gatt_subscribe_params *params) {
+  /* Remove subscription from the list*/
+  sys_slist_remove(&subscriptions, prev, ¶ms->node);
 
-    params->notify(conn, params, NULL, 0);
+  params->notify(conn, params, NULL, 0);
 }
 
-static void remove_subscriptions(struct bt_conn *conn)
-{
-    struct bt_gatt_subscribe_params *params, *tmp;
-    sys_snode_t *prev = NULL;
-
-    /* Lookup existing subscriptions */
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node)
-    {
-        if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) {
-            prev = ¶ms->node;
-            continue;
-        }
+static void remove_subscriptions(struct bt_conn *conn) {
+  struct bt_gatt_subscribe_params *params, *tmp;
+  sys_snode_t                     *prev = NULL;
 
-        if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst) ||
-            (atomic_test_bit(params->flags,
-                             BT_GATT_SUBSCRIBE_FLAG_VOLATILE))) {
-            /* Remove subscription */
-            params->value = 0U;
-            gatt_subscription_remove(conn, prev, params);
-        } else {
-            update_subscription(conn, params);
-            prev = ¶ms->node;
-        }
+  /* Lookup existing subscriptions */
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) {
+    if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) {
+      prev = ¶ms->node;
+      continue;
+    }
+
+    if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst) || (atomic_test_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_VOLATILE))) {
+      /* Remove subscription */
+      params->value = 0U;
+      gatt_subscription_remove(conn, prev, params);
+    } else {
+      update_subscription(conn, params);
+      prev = ¶ms->node;
     }
+  }
 }
 
-static void gatt_mtu_rsp(struct bt_conn *conn, u8_t err, const void *pdu,
-                         u16_t length, void *user_data)
-{
-    struct bt_gatt_exchange_params *params = user_data;
+static void gatt_mtu_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_exchange_params *params = user_data;
 
-    params->func(conn, err, params);
+  params->func(conn, err, params);
 }
 #if defined(CONFIG_BLE_AT_CMD)
-int bt_at_gatt_exchange_mtu(struct bt_conn *conn, struct bt_gatt_exchange_params *params, u16_t mtu_size)
-{
-    struct bt_att_exchange_mtu_req *req;
-    struct net_buf *buf;
-    u16_t mtu;
+int bt_at_gatt_exchange_mtu(struct bt_conn *conn, struct bt_gatt_exchange_params *params, u16_t mtu_size) {
+  struct bt_att_exchange_mtu_req *req;
+  struct net_buf                 *buf;
+  u16_t                           mtu;
 
-    __ASSERT(conn, "invalid parameter\n");
-    __ASSERT(params && params->func, "invalid parameters\n");
+  __ASSERT(conn, "invalid parameter\n");
+  __ASSERT(params && params->func, "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    mtu = mtu_size;
+  mtu = mtu_size;
 
 #if defined(CONFIG_BLE_AT_CMD)
-    set_mtu_size(mtu);
+  set_mtu_size(mtu);
 #endif
 
-    BT_DBG("Client MTU %u", mtu);
+  BT_DBG("Client MTU %u", mtu);
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->mtu = sys_cpu_to_le16(mtu);
+  req      = net_buf_add(buf, sizeof(*req));
+  req->mtu = sys_cpu_to_le16(mtu);
 
-    return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL);
 }
 #endif
 
-int bt_gatt_exchange_mtu(struct bt_conn *conn,
-                         struct bt_gatt_exchange_params *params)
-{
-    struct bt_att_exchange_mtu_req *req;
-    struct net_buf *buf;
-    u16_t mtu;
+int bt_gatt_exchange_mtu(struct bt_conn *conn, struct bt_gatt_exchange_params *params) {
+  struct bt_att_exchange_mtu_req *req;
+  struct net_buf                 *buf;
+  u16_t                           mtu;
 
-    __ASSERT(conn, "invalid parameter\n");
-    __ASSERT(params && params->func, "invalid parameters\n");
+  __ASSERT(conn, "invalid parameter\n");
+  __ASSERT(params && params->func, "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    mtu = BT_ATT_MTU;
+  mtu = BT_ATT_MTU;
 
-    BT_DBG("Client MTU %u", mtu);
+  BT_DBG("Client MTU %u", mtu);
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->mtu = sys_cpu_to_le16(mtu);
+  req      = net_buf_add(buf, sizeof(*req));
+  req->mtu = sys_cpu_to_le16(mtu);
 
-    return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL);
 }
 
-static void gatt_discover_next(struct bt_conn *conn, u16_t last_handle,
-                               struct bt_gatt_discover_params *params)
-{
-    /* Skip if last_handle is not set */
-    if (!last_handle)
-        goto discover;
-
-    /* Continue from the last found handle */
-    params->start_handle = last_handle;
-    if (params->start_handle < UINT16_MAX) {
-        params->start_handle++;
-    } else {
-        goto done;
-    }
+static void gatt_discover_next(struct bt_conn *conn, u16_t last_handle, struct bt_gatt_discover_params *params) {
+  /* Skip if last_handle is not set */
+  if (!last_handle)
+    goto discover;
 
-    /* Stop if over the range or the requests */
-    if (params->start_handle > params->end_handle) {
-        goto done;
-    }
+  /* Continue from the last found handle */
+  params->start_handle = last_handle;
+  if (params->start_handle < UINT16_MAX) {
+    params->start_handle++;
+  } else {
+    goto done;
+  }
+
+  /* Stop if over the range or the requests */
+  if (params->start_handle > params->end_handle) {
+    goto done;
+  }
 
 discover:
-    /* Discover next range */
-    if (!bt_gatt_discover(conn, params)) {
-        return;
-    }
+  /* Discover next range */
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+  if (!bt_gatt_discover_continue(conn, params)) {
+#else
+  if (!bt_gatt_discover(conn, params)) {
+#endif
+    return;
+  }
 
 done:
-    params->func(conn, NULL, params);
+  params->func(conn, NULL, params);
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+  discover_ongoing = BT_GATT_ITER_STOP;
+#endif
 }
 
-static void gatt_find_type_rsp(struct bt_conn *conn, u8_t err,
-                               const void *pdu, u16_t length,
-                               void *user_data)
-{
-    const struct bt_att_find_type_rsp *rsp = pdu;
-    struct bt_gatt_discover_params *params = user_data;
-    u8_t i;
-    u16_t end_handle = 0U, start_handle;
+static void gatt_find_type_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  const struct bt_att_find_type_rsp *rsp    = pdu;
+  struct bt_gatt_discover_params    *params = user_data;
+  u8_t                               i;
+  u16_t                              end_handle = 0U, start_handle;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    if (err) {
-        goto done;
-    }
+  if (err) {
+    goto done;
+  }
 
-    /* Parse attributes found */
-    for (i = 0U; length >= sizeof(rsp->list[i]);
-         i++, length -= sizeof(rsp->list[i])) {
-        struct bt_gatt_attr attr = {};
-        struct bt_gatt_service_val value;
+  /* Parse attributes found */
+  for (i = 0U; length >= sizeof(rsp->list[i]); i++, length -= sizeof(rsp->list[i])) {
+    struct bt_gatt_attr        attr = {};
+    struct bt_gatt_service_val value;
 
-        start_handle = sys_le16_to_cpu(rsp->list[i].start_handle);
-        end_handle = sys_le16_to_cpu(rsp->list[i].end_handle);
+    start_handle = sys_le16_to_cpu(rsp->list[i].start_handle);
+    end_handle   = sys_le16_to_cpu(rsp->list[i].end_handle);
 
-        BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle,
-               end_handle);
+    BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, end_handle);
 
-        if (params->type == BT_GATT_DISCOVER_PRIMARY) {
-            attr.uuid = BT_UUID_GATT_PRIMARY;
-        } else {
-            attr.uuid = BT_UUID_GATT_SECONDARY;
-        }
+    if (params->type == BT_GATT_DISCOVER_PRIMARY) {
+      attr.uuid = BT_UUID_GATT_PRIMARY;
+    } else {
+      attr.uuid = BT_UUID_GATT_SECONDARY;
+    }
 
-        value.end_handle = end_handle;
-        value.uuid = params->uuid;
+    value.end_handle = end_handle;
+    value.uuid       = params->uuid;
 
-        attr.handle = start_handle;
-        attr.user_data = &value;
+    attr.handle    = start_handle;
+    attr.user_data = &value;
 
-        if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
-            return;
-        }
+    if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+      discover_ongoing = BT_GATT_ITER_STOP;
+#endif
+      return;
     }
+  }
 
-    /* Stop if could not parse the whole PDU */
-    if (length > 0) {
-        goto done;
-    }
+  /* Stop if could not parse the whole PDU */
+  if (length > 0) {
+    goto done;
+  }
 
-    gatt_discover_next(conn, end_handle, params);
+  gatt_discover_next(conn, end_handle, params);
 
-    return;
+  return;
 done:
-    params->func(conn, NULL, params);
+  params->func(conn, NULL, params);
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+  discover_ongoing = BT_GATT_ITER_STOP;
+#endif
 }
 
-static int gatt_find_type(struct bt_conn *conn,
-                          struct bt_gatt_discover_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_find_type_req *req;
-    struct bt_uuid *uuid;
-
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+static int gatt_find_type(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  struct net_buf              *buf;
+  struct bt_att_find_type_req *req;
+  struct bt_uuid              *uuid;
+
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
+
+  req               = net_buf_add(buf, sizeof(*req));
+  req->start_handle = sys_cpu_to_le16(params->start_handle);
+  req->end_handle   = sys_cpu_to_le16(params->end_handle);
+
+  if (params->type == BT_GATT_DISCOVER_PRIMARY) {
+    uuid = BT_UUID_GATT_PRIMARY;
+  } else {
+    uuid = BT_UUID_GATT_SECONDARY;
+  }
+
+  req->type = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
+
+  BT_DBG("uuid %s start_handle 0x%04x end_handle 0x%04x", bt_uuid_str(params->uuid), params->start_handle, params->end_handle);
+
+  switch (params->uuid->type) {
+  case BT_UUID_TYPE_16:
+    net_buf_add_le16(buf, BT_UUID_16(params->uuid)->val);
+    break;
+  case BT_UUID_TYPE_128:
+    net_buf_add_mem(buf, BT_UUID_128(params->uuid)->val, 16);
+    break;
+  default:
+    BT_ERR("Unknown UUID type %u", params->uuid->type);
+    net_buf_unref(buf);
+    return -EINVAL;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->start_handle = sys_cpu_to_le16(params->start_handle);
-    req->end_handle = sys_cpu_to_le16(params->end_handle);
+  return gatt_send(conn, buf, gatt_find_type_rsp, params, NULL);
+}
 
-    if (params->type == BT_GATT_DISCOVER_PRIMARY) {
-        uuid = BT_UUID_GATT_PRIMARY;
-    } else {
-        uuid = BT_UUID_GATT_SECONDARY;
-    }
+static void read_included_uuid_cb(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_discover_params *params = user_data;
+  struct bt_gatt_include          value;
+  struct bt_gatt_attr            *attr;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_128 u128;
+  } u;
 
-    req->type = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
-
-    BT_DBG("uuid %s start_handle 0x%04x end_handle 0x%04x",
-           bt_uuid_str(params->uuid), params->start_handle,
-           params->end_handle);
-
-    switch (params->uuid->type) {
-        case BT_UUID_TYPE_16:
-            net_buf_add_le16(buf, BT_UUID_16(params->uuid)->val);
-            break;
-        case BT_UUID_TYPE_128:
-            net_buf_add_mem(buf, BT_UUID_128(params->uuid)->val, 16);
-            break;
-        default:
-            BT_ERR("Unknown UUID type %u", params->uuid->type);
-            net_buf_unref(buf);
-            return -EINVAL;
-    }
+  if (length != 16U) {
+    BT_ERR("Invalid data len %u", length);
+    params->func(conn, NULL, params);
+    return;
+  }
+
+  value.start_handle = params->_included.start_handle;
+  value.end_handle   = params->_included.end_handle;
+  value.uuid         = &u.uuid;
+  u.uuid.type        = BT_UUID_TYPE_128;
+  memcpy(u.u128.val, pdu, length);
+
+  BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x "
+         "end_handle 0x%04x\n",
+         params->_included.attr_handle, bt_uuid_str(&u.uuid), value.start_handle, value.end_handle);
+
+  /* Skip if UUID is set but doesn't match */
+  if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
+    goto next;
+  }
+
+  attr         = (&(struct bt_gatt_attr){
+              .uuid      = BT_UUID_GATT_INCLUDE,
+              .user_data = &value,
+  });
+  attr->handle = params->_included.attr_handle;
+
+  if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
+    return;
+  }
+next:
+  gatt_discover_next(conn, params->start_handle, params);
 
-    return gatt_send(conn, buf, gatt_find_type_rsp, params, NULL);
+  return;
 }
 
-static void read_included_uuid_cb(struct bt_conn *conn, u8_t err,
-                                  const void *pdu, u16_t length,
-                                  void *user_data)
-{
-    struct bt_gatt_discover_params *params = user_data;
-    struct bt_gatt_include value;
-    struct bt_gatt_attr *attr;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_128 u128;
-    } u;
-
-    if (length != 16U) {
-        BT_ERR("Invalid data len %u", length);
-        params->func(conn, NULL, params);
-        return;
-    }
+static int read_included_uuid(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  struct net_buf         *buf;
+  struct bt_att_read_req *req;
 
-    value.start_handle = params->_included.start_handle;
-    value.end_handle = params->_included.end_handle;
-    value.uuid = &u.uuid;
-    u.uuid.type = BT_UUID_TYPE_128;
-    memcpy(u.u128.val, pdu, length);
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x "
-           "end_handle 0x%04x\n",
-           params->_included.attr_handle,
-           bt_uuid_str(&u.uuid), value.start_handle, value.end_handle);
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(params->_included.start_handle);
 
-    /* Skip if UUID is set but doesn't match */
-    if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
-        goto next;
-    }
+  BT_DBG("handle 0x%04x", params->_included.start_handle);
 
-    attr = (&(struct bt_gatt_attr){
-        .uuid = BT_UUID_GATT_INCLUDE,
-        .user_data = &value,
-    });
-    attr->handle = params->_included.attr_handle;
-
-    if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
-        return;
-    }
-next:
-    gatt_discover_next(conn, params->start_handle, params);
-
-    return;
+  return gatt_send(conn, buf, read_included_uuid_cb, params, NULL);
 }
 
-static int read_included_uuid(struct bt_conn *conn,
-                              struct bt_gatt_discover_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_req *req;
+static u16_t parse_include(struct bt_conn *conn, const void *pdu, struct bt_gatt_discover_params *params, u16_t length) {
+  const struct bt_att_read_type_rsp *rsp    = pdu;
+  u16_t                              handle = 0U;
+  struct bt_gatt_include             value;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
+  /* Data can be either in UUID16 or UUID128 */
+  switch (rsp->len) {
+  case 8: /* UUID16 */
+    u.uuid.type = BT_UUID_TYPE_16;
+    break;
+  case 6: /* UUID128 */
+    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 550
+     * To get the included service UUID when the included service
+     * uses a 128-bit UUID, the Read Request is used.
+     */
+    u.uuid.type = BT_UUID_TYPE_128;
+    break;
+  default:
+    BT_ERR("Invalid data len %u", rsp->len);
+    goto done;
+  }
+
+  /* Parse include found */
+  for (length--, pdu = rsp->data; length >= rsp->len; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
+    struct bt_gatt_attr      *attr;
+    const struct bt_att_data *data = pdu;
+    struct gatt_incl         *incl = (void *)data->value;
+
+    handle = sys_le16_to_cpu(data->handle);
+    /* Handle 0 is invalid */
+    if (!handle) {
+      goto done;
     }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(params->_included.start_handle);
+    /* Convert include data, bt_gatt_incl and gatt_incl
+     * have different formats so the conversion have to be done
+     * field by field.
+     */
+    value.start_handle = sys_le16_to_cpu(incl->start_handle);
+    value.end_handle   = sys_le16_to_cpu(incl->end_handle);
 
-    BT_DBG("handle 0x%04x", params->_included.start_handle);
+    switch (u.uuid.type) {
+    case BT_UUID_TYPE_16:
+      value.uuid = &u.uuid;
+      u.u16.val  = sys_le16_to_cpu(incl->uuid16);
+      break;
+    case BT_UUID_TYPE_128:
+      params->_included.attr_handle  = handle;
+      params->_included.start_handle = value.start_handle;
+      params->_included.end_handle   = value.end_handle;
 
-    return gatt_send(conn, buf, read_included_uuid_cb, params, NULL);
-}
-
-static u16_t parse_include(struct bt_conn *conn, const void *pdu,
-                           struct bt_gatt_discover_params *params,
-                           u16_t length)
-{
-    const struct bt_att_read_type_rsp *rsp = pdu;
-    u16_t handle = 0U;
-    struct bt_gatt_include value;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-
-    /* Data can be either in UUID16 or UUID128 */
-    switch (rsp->len) {
-        case 8: /* UUID16 */
-            u.uuid.type = BT_UUID_TYPE_16;
-            break;
-        case 6: /* UUID128 */
-            /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 550
-		 * To get the included service UUID when the included service
-		 * uses a 128-bit UUID, the Read Request is used.
-		 */
-            u.uuid.type = BT_UUID_TYPE_128;
-            break;
-        default:
-            BT_ERR("Invalid data len %u", rsp->len);
-            goto done;
+      return read_included_uuid(conn, params);
     }
 
-    /* Parse include found */
-    for (length--, pdu = rsp->data; length >= rsp->len;
-         length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
-        struct bt_gatt_attr *attr;
-        const struct bt_att_data *data = pdu;
-        struct gatt_incl *incl = (void *)data->value;
-
-        handle = sys_le16_to_cpu(data->handle);
-        /* Handle 0 is invalid */
-        if (!handle) {
-            goto done;
-        }
-
-        /* Convert include data, bt_gatt_incl and gatt_incl
-		 * have different formats so the conversion have to be done
-		 * field by field.
-		 */
-        value.start_handle = sys_le16_to_cpu(incl->start_handle);
-        value.end_handle = sys_le16_to_cpu(incl->end_handle);
-
-        switch (u.uuid.type) {
-            case BT_UUID_TYPE_16:
-                value.uuid = &u.uuid;
-                u.u16.val = sys_le16_to_cpu(incl->uuid16);
-                break;
-            case BT_UUID_TYPE_128:
-                params->_included.attr_handle = handle;
-                params->_included.start_handle = value.start_handle;
-                params->_included.end_handle = value.end_handle;
-
-                return read_included_uuid(conn, params);
-        }
-
-        BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x "
-               "end_handle 0x%04x\n",
-               handle, bt_uuid_str(&u.uuid),
-               value.start_handle, value.end_handle);
+    BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x "
+           "end_handle 0x%04x\n",
+           handle, bt_uuid_str(&u.uuid), value.start_handle, value.end_handle);
 
-        /* Skip if UUID is set but doesn't match */
-        if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
-            continue;
-        }
+    /* Skip if UUID is set but doesn't match */
+    if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
+      continue;
+    }
 
-        attr = (&(struct bt_gatt_attr){
-            .uuid = BT_UUID_GATT_INCLUDE,
-            .user_data = &value,
-        });
-        attr->handle = handle;
+    attr         = (&(struct bt_gatt_attr){
+                .uuid      = BT_UUID_GATT_INCLUDE,
+                .user_data = &value,
+    });
+    attr->handle = handle;
 
-        if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
-            return 0;
-        }
+    if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
+      return 0;
     }
+  }
 
-    /* Whole PDU read without error */
-    if (length == 0U && handle) {
-        return handle;
-    }
+  /* Whole PDU read without error */
+  if (length == 0U && handle) {
+    return handle;
+  }
 
 done:
-    params->func(conn, NULL, params);
-    return 0;
-}
-
-#define BT_GATT_CHRC(_uuid, _handle, _props)                \
-    BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, \
-                      bt_gatt_attr_read_chrc, NULL,         \
-                      (&(struct bt_gatt_chrc){              \
-                          .uuid = _uuid,                    \
-                          .value_handle = _handle,          \
-                          .properties = _props,             \
-                      }))
-
-static u16_t parse_characteristic(struct bt_conn *conn, const void *pdu,
-                                  struct bt_gatt_discover_params *params,
-                                  u16_t length)
-{
-    const struct bt_att_read_type_rsp *rsp = pdu;
-    u16_t handle = 0U;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-
-    /* Data can be either in UUID16 or UUID128 */
-    switch (rsp->len) {
-        case 7: /* UUID16 */
-            u.uuid.type = BT_UUID_TYPE_16;
-            break;
-        case 21: /* UUID128 */
-            u.uuid.type = BT_UUID_TYPE_128;
-            break;
-        default:
-            BT_ERR("Invalid data len %u", rsp->len);
-            goto done;
+  params->func(conn, NULL, params);
+  return 0;
+}
+
+#define BT_GATT_CHRC(_uuid, _handle, _props)                                                                                                                                                           \
+  BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, bt_gatt_attr_read_chrc, NULL,                                                                                                                \
+                    (&(struct bt_gatt_chrc){                                                                                                                                                           \
+                        .uuid         = _uuid,                                                                                                                                                         \
+                        .value_handle = _handle,                                                                                                                                                       \
+                        .properties   = _props,                                                                                                                                                        \
+                    }))
+
+static u16_t parse_characteristic(struct bt_conn *conn, const void *pdu, struct bt_gatt_discover_params *params, u16_t length) {
+  const struct bt_att_read_type_rsp *rsp    = pdu;
+  u16_t                              handle = 0U;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
+
+  /* Data can be either in UUID16 or UUID128 */
+  switch (rsp->len) {
+  case 7: /* UUID16 */
+    u.uuid.type = BT_UUID_TYPE_16;
+    break;
+  case 21: /* UUID128 */
+    u.uuid.type = BT_UUID_TYPE_128;
+    break;
+  default:
+    BT_ERR("Invalid data len %u", rsp->len);
+    goto done;
+  }
+
+  /* Parse characteristics found */
+  for (length--, pdu = rsp->data; length >= rsp->len; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
+    struct bt_gatt_attr      *attr;
+    const struct bt_att_data *data = pdu;
+    struct gatt_chrc         *chrc = (void *)data->value;
+
+    handle = sys_le16_to_cpu(data->handle);
+    /* Handle 0 is invalid */
+    if (!handle) {
+      goto done;
     }
 
-    /* Parse characteristics found */
-    for (length--, pdu = rsp->data; length >= rsp->len;
-         length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
-        struct bt_gatt_attr *attr;
-        const struct bt_att_data *data = pdu;
-        struct gatt_chrc *chrc = (void *)data->value;
-
-        handle = sys_le16_to_cpu(data->handle);
-        /* Handle 0 is invalid */
-        if (!handle) {
-            goto done;
-        }
-
-        switch (u.uuid.type) {
-            case BT_UUID_TYPE_16:
-                u.u16.val = sys_le16_to_cpu(chrc->uuid16);
-                break;
-            case BT_UUID_TYPE_128:
-                memcpy(u.u128.val, chrc->uuid, sizeof(chrc->uuid));
-                break;
-        }
+    switch (u.uuid.type) {
+    case BT_UUID_TYPE_16:
+      u.u16.val = sys_le16_to_cpu(chrc->uuid16);
+      break;
+    case BT_UUID_TYPE_128:
+      memcpy(u.u128.val, chrc->uuid, sizeof(chrc->uuid));
+      break;
+    }
 
-        BT_DBG("handle 0x%04x uuid %s properties 0x%02x", handle,
-               bt_uuid_str(&u.uuid), chrc->properties);
+    BT_DBG("handle 0x%04x uuid %s properties 0x%02x", handle, bt_uuid_str(&u.uuid), chrc->properties);
 
 #if defined(CONFIG_BT_STACK_PTS)
-        if (event_flag != gatt_discover_chara) {
-            /* Skip if UUID is set but doesn't match */
-            if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid))
-                continue;
-        }
+    if (event_flag != gatt_discover_chara) {
+      /* Skip if UUID is set but doesn't match */
+      if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid))
+        continue;
+    }
 #else
-        /* Skip if UUID is set but doesn't match */
-        if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
-            continue;
-        }
+    /* Skip if UUID is set but doesn't match */
+    if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
+      continue;
+    }
 #endif
 
-        attr = (&(struct bt_gatt_attr)BT_GATT_CHRC(&u.uuid,
-                                                   chrc->value_handle,
-                                                   chrc->properties));
-        attr->handle = handle;
+    attr         = (&(struct bt_gatt_attr)BT_GATT_CHRC(&u.uuid, chrc->value_handle, chrc->properties));
+    attr->handle = handle;
 
-        if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
-            return 0;
-        }
+    if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
+      return 0;
     }
+  }
 
-    /* Whole PDU read without error */
-    if (length == 0U && handle) {
-        return handle;
-    }
+  /* Whole PDU read without error */
+  if (length == 0U && handle) {
+    return handle;
+  }
 
 done:
-    params->func(conn, NULL, params);
-    return 0;
+  params->func(conn, NULL, params);
+  return 0;
 }
 
-static void gatt_read_type_rsp(struct bt_conn *conn, u8_t err,
-                               const void *pdu, u16_t length,
-                               void *user_data)
-{
-    struct bt_gatt_discover_params *params = user_data;
-    u16_t handle;
+static void gatt_read_type_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_discover_params *params = user_data;
+  u16_t                           handle;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    if (err) {
-        params->func(conn, NULL, params);
-        return;
-    }
+  if (err) {
+    params->func(conn, NULL, params);
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+    discover_ongoing = BT_GATT_ITER_STOP;
+#endif
+    return;
+  }
 
-    if (params->type == BT_GATT_DISCOVER_INCLUDE) {
-        handle = parse_include(conn, pdu, params, length);
-    } else {
-        handle = parse_characteristic(conn, pdu, params, length);
-    }
+  if (params->type == BT_GATT_DISCOVER_INCLUDE) {
+    handle = parse_include(conn, pdu, params, length);
+  } else {
+    handle = parse_characteristic(conn, pdu, params, length);
+  }
 
-    if (!handle) {
-        return;
-    }
+  if (!handle) {
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+    discover_ongoing = BT_GATT_ITER_STOP;
+#endif
+    return;
+  }
 
-    gatt_discover_next(conn, handle, params);
+  gatt_discover_next(conn, handle, params);
 }
 
-static int gatt_read_type(struct bt_conn *conn,
-                          struct bt_gatt_discover_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_type_req *req;
+static int gatt_read_type(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  struct net_buf              *buf;
+  struct bt_att_read_type_req *req;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->start_handle = sys_cpu_to_le16(params->start_handle);
-    req->end_handle = sys_cpu_to_le16(params->end_handle);
+  req               = net_buf_add(buf, sizeof(*req));
+  req->start_handle = sys_cpu_to_le16(params->start_handle);
+  req->end_handle   = sys_cpu_to_le16(params->end_handle);
 
-    if (params->type == BT_GATT_DISCOVER_INCLUDE) {
-        net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_INCLUDE)->val);
-    } else {
-        net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_CHRC)->val);
-    }
+  if (params->type == BT_GATT_DISCOVER_INCLUDE) {
+    net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_INCLUDE)->val);
+  } else {
+    net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_CHRC)->val);
+  }
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle,
-           params->end_handle);
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle);
 
-    return gatt_send(conn, buf, gatt_read_type_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_read_type_rsp, params, NULL);
 }
 
-static u16_t parse_service(struct bt_conn *conn, const void *pdu,
-                           struct bt_gatt_discover_params *params,
-                           u16_t length)
-{
-    const struct bt_att_read_group_rsp *rsp = pdu;
-    u16_t start_handle, end_handle = 0U;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-
-    /* Data can be either in UUID16 or UUID128 */
-    switch (rsp->len) {
-        case 6: /* UUID16 */
-            u.uuid.type = BT_UUID_TYPE_16;
-            break;
-        case 20: /* UUID128 */
-            u.uuid.type = BT_UUID_TYPE_128;
-            break;
-        default:
-            BT_ERR("Invalid data len %u", rsp->len);
-            goto done;
-    }
+static u16_t parse_service(struct bt_conn *conn, const void *pdu, struct bt_gatt_discover_params *params, u16_t length) {
+  const struct bt_att_read_group_rsp *rsp = pdu;
+  u16_t                               start_handle, end_handle = 0U;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
 
-    /* Parse services found */
-    for (length--, pdu = rsp->data; length >= rsp->len;
-         length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
-        struct bt_gatt_attr attr = {};
-        struct bt_gatt_service_val value;
-        const struct bt_att_group_data *data = pdu;
-
-        start_handle = sys_le16_to_cpu(data->start_handle);
-        if (!start_handle) {
-            goto done;
-        }
-
-        end_handle = sys_le16_to_cpu(data->end_handle);
-        if (!end_handle || end_handle < start_handle) {
-            goto done;
-        }
-
-        switch (u.uuid.type) {
-            case BT_UUID_TYPE_16:
-                memcpy(&u.u16.val, data->value, sizeof(u.u16.val));
-                u.u16.val = sys_le16_to_cpu(u.u16.val);
-                break;
-            case BT_UUID_TYPE_128:
-                memcpy(u.u128.val, data->value, sizeof(u.u128.val));
-                break;
-        }
-
-        BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s",
-               start_handle, end_handle, bt_uuid_str(&u.uuid));
-
-        if (params->type == BT_GATT_DISCOVER_PRIMARY) {
-            attr.uuid = BT_UUID_GATT_PRIMARY;
-        } else {
-            attr.uuid = BT_UUID_GATT_SECONDARY;
-        }
+  /* Data can be either in UUID16 or UUID128 */
+  switch (rsp->len) {
+  case 6: /* UUID16 */
+    u.uuid.type = BT_UUID_TYPE_16;
+    break;
+  case 20: /* UUID128 */
+    u.uuid.type = BT_UUID_TYPE_128;
+    break;
+  default:
+    BT_ERR("Invalid data len %u", rsp->len);
+    goto done;
+  }
 
-        value.end_handle = end_handle;
-        value.uuid = &u.uuid;
+  /* Parse services found */
+  for (length--, pdu = rsp->data; length >= rsp->len; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
+    struct bt_gatt_attr             attr = {};
+    struct bt_gatt_service_val      value;
+    const struct bt_att_group_data *data = pdu;
 
-        attr.handle = start_handle;
-        attr.user_data = &value;
+    start_handle = sys_le16_to_cpu(data->start_handle);
+    if (!start_handle) {
+      goto done;
+    }
 
-        if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
-            return 0;
-        }
+    end_handle = sys_le16_to_cpu(data->end_handle);
+    if (!end_handle || end_handle < start_handle) {
+      goto done;
     }
 
-    /* Whole PDU read without error */
-    if (length == 0U && end_handle) {
-        return end_handle;
+    switch (u.uuid.type) {
+    case BT_UUID_TYPE_16:
+      memcpy(&u.u16.val, data->value, sizeof(u.u16.val));
+      u.u16.val = sys_le16_to_cpu(u.u16.val);
+      break;
+    case BT_UUID_TYPE_128:
+      memcpy(u.u128.val, data->value, sizeof(u.u128.val));
+      break;
     }
 
-done:
-    params->func(conn, NULL, params);
-    return 0;
-}
+    BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", start_handle, end_handle, bt_uuid_str(&u.uuid));
 
-static void gatt_read_group_rsp(struct bt_conn *conn, u8_t err,
-                                const void *pdu, u16_t length,
-                                void *user_data)
-{
-    struct bt_gatt_discover_params *params = user_data;
-    u16_t handle;
+    if (params->type == BT_GATT_DISCOVER_PRIMARY) {
+      attr.uuid = BT_UUID_GATT_PRIMARY;
+    } else {
+      attr.uuid = BT_UUID_GATT_SECONDARY;
+    }
 
-    BT_DBG("err 0x%02x", err);
+    value.end_handle = end_handle;
+    value.uuid       = &u.uuid;
 
-    if (err) {
-        params->func(conn, NULL, params);
-        return;
-    }
+    attr.handle    = start_handle;
+    attr.user_data = &value;
 
-    handle = parse_service(conn, pdu, params, length);
-    if (!handle) {
-        return;
+    if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
+      return 0;
     }
+  }
 
-    gatt_discover_next(conn, handle, params);
-}
+  /* Whole PDU read without error */
+  if (length == 0U && end_handle) {
+    return end_handle;
+  }
 
-static int gatt_read_group(struct bt_conn *conn,
-                           struct bt_gatt_discover_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_group_req *req;
-
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+done:
+  params->func(conn, NULL, params);
+  return 0;
+}
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->start_handle = sys_cpu_to_le16(params->start_handle);
-    req->end_handle = sys_cpu_to_le16(params->end_handle);
+static void gatt_read_group_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_discover_params *params = user_data;
+  u16_t                           handle;
 
-    if (params->type == BT_GATT_DISCOVER_PRIMARY) {
-        net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_PRIMARY)->val);
-    } else {
-        net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_SECONDARY)->val);
-    }
+  BT_DBG("err 0x%02x", err);
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle,
-           params->end_handle);
+  if (err) {
+    params->func(conn, NULL, params);
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+    discover_ongoing = BT_GATT_ITER_STOP;
+#endif
+    return;
+  }
 
-    return gatt_send(conn, buf, gatt_read_group_rsp, params, NULL);
-}
+  handle = parse_service(conn, pdu, params, length);
+  if (!handle) {
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+    discover_ongoing = BT_GATT_ITER_STOP;
+#endif
+    return;
+  }
+
+  gatt_discover_next(conn, handle, params);
+}
+
+static int gatt_read_group(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  struct net_buf               *buf;
+  struct bt_att_read_group_req *req;
+
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
+
+  req               = net_buf_add(buf, sizeof(*req));
+  req->start_handle = sys_cpu_to_le16(params->start_handle);
+  req->end_handle   = sys_cpu_to_le16(params->end_handle);
+
+  if (params->type == BT_GATT_DISCOVER_PRIMARY) {
+    net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_PRIMARY)->val);
+  } else {
+    net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_SECONDARY)->val);
+  }
+
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle);
+
+  return gatt_send(conn, buf, gatt_read_group_rsp, params, NULL);
+}
+
+static void gatt_find_info_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  const struct bt_att_find_info_rsp *rsp    = pdu;
+  struct bt_gatt_discover_params    *params = user_data;
+  u16_t                              handle = 0U;
+  u16_t                              len;
+  union {
+    const struct bt_att_info_16  *i16;
+    const struct bt_att_info_128 *i128;
+  } info;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_128 u128;
+  } u;
+  int  i;
+  bool skip = false;
+
+  BT_DBG("err 0x%02x", err);
+
+  if (err) {
+    goto done;
+  }
+
+  /* Data can be either in UUID16 or UUID128 */
+  switch (rsp->format) {
+  case BT_ATT_INFO_16:
+    u.uuid.type = BT_UUID_TYPE_16;
+    len         = sizeof(*info.i16);
+    break;
+  case BT_ATT_INFO_128:
+    u.uuid.type = BT_UUID_TYPE_128;
+    len         = sizeof(*info.i128);
+    break;
+  default:
+    BT_ERR("Invalid format %u", rsp->format);
+    goto done;
+  }
+
+  length--;
+
+  /* Check if there is a least one descriptor in the response */
+  if (length < len) {
+    goto done;
+  }
+
+  /* Parse descriptors found */
+  for (i = length / len, pdu = rsp->info; i != 0; i--, pdu = (const u8_t *)pdu + len) {
+    struct bt_gatt_attr *attr;
 
-static void gatt_find_info_rsp(struct bt_conn *conn, u8_t err,
-                               const void *pdu, u16_t length,
-                               void *user_data)
-{
-    const struct bt_att_find_info_rsp *rsp = pdu;
-    struct bt_gatt_discover_params *params = user_data;
-    u16_t handle = 0U;
-    u16_t len;
-    union {
-        const struct bt_att_info_16 *i16;
-        const struct bt_att_info_128 *i128;
-    } info;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_128 u128;
-    } u;
-    int i;
-    bool skip = false;
-
-    BT_DBG("err 0x%02x", err);
+    info.i16 = pdu;
+    handle   = sys_le16_to_cpu(info.i16->handle);
 
-    if (err) {
-        goto done;
+    if (skip) {
+      skip = false;
+      continue;
     }
 
-    /* Data can be either in UUID16 or UUID128 */
-    switch (rsp->format) {
-        case BT_ATT_INFO_16:
-            u.uuid.type = BT_UUID_TYPE_16;
-            len = sizeof(*info.i16);
-            break;
-        case BT_ATT_INFO_128:
-            u.uuid.type = BT_UUID_TYPE_128;
-            len = sizeof(*info.i128);
-            break;
-        default:
-            BT_ERR("Invalid format %u", rsp->format);
-            goto done;
+    switch (u.uuid.type) {
+    case BT_UUID_TYPE_16:
+      u.u16.val = sys_le16_to_cpu(info.i16->uuid);
+      break;
+    case BT_UUID_TYPE_128:
+      memcpy(u.u128.val, info.i128->uuid, 16);
+      break;
     }
 
-    length--;
+    BT_DBG("handle 0x%04x uuid %s", handle, bt_uuid_str(&u.uuid));
 
-    /* Check if there is a least one descriptor in the response */
-    if (length < len) {
-        goto done;
+    /* Skip if UUID is set but doesn't match */
+    if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
+      continue;
     }
 
-    /* Parse descriptors found */
-    for (i = length / len, pdu = rsp->info; i != 0;
-         i--, pdu = (const u8_t *)pdu + len) {
-        struct bt_gatt_attr *attr;
+    if (params->type == BT_GATT_DISCOVER_DESCRIPTOR) {
+      /* Skip attributes that are not considered
+       * descriptors.
+       */
+      if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY) || !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_INCLUDE)) {
+        continue;
+      }
 
-        info.i16 = pdu;
-        handle = sys_le16_to_cpu(info.i16->handle);
-
-        if (skip) {
-            skip = false;
-            continue;
-        }
-
-        switch (u.uuid.type) {
-            case BT_UUID_TYPE_16:
-                u.u16.val = sys_le16_to_cpu(info.i16->uuid);
-                break;
-            case BT_UUID_TYPE_128:
-                memcpy(u.u128.val, info.i128->uuid, 16);
-                break;
-        }
-
-        BT_DBG("handle 0x%04x uuid %s", handle, bt_uuid_str(&u.uuid));
-
-        /* Skip if UUID is set but doesn't match */
-        if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) {
-            continue;
-        }
-
-        if (params->type == BT_GATT_DISCOVER_DESCRIPTOR) {
-            /* Skip attributes that are not considered
-			 * descriptors.
-			 */
-            if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) ||
-                !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY) ||
-                !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_INCLUDE)) {
-                continue;
-            }
-
-            /* If Characteristic Declaration skip ahead as the next
-			 * entry must be its value.
-			 */
-            if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_CHRC)) {
-                skip = true;
-                continue;
-            }
-        }
+      /* If Characteristic Declaration skip ahead as the next
+       * entry must be its value.
+       */
+      if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_CHRC)) {
+        skip = true;
+        continue;
+      }
+    }
 
-        attr = (&(struct bt_gatt_attr)
-                    BT_GATT_DESCRIPTOR(&u.uuid, 0, NULL, NULL, NULL));
-        attr->handle = handle;
+    attr         = (&(struct bt_gatt_attr)BT_GATT_DESCRIPTOR(&u.uuid, 0, NULL, NULL, NULL));
+    attr->handle = handle;
 
-        if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
-            return;
-        }
+    if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+      discover_ongoing = BT_GATT_ITER_STOP;
+#endif
+      return;
     }
+  }
 
-    gatt_discover_next(conn, handle, params);
+  gatt_discover_next(conn, handle, params);
 
-    return;
+  return;
 
 done:
-    params->func(conn, NULL, params);
+  params->func(conn, NULL, params);
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+  discover_ongoing = BT_GATT_ITER_STOP;
+#endif
 }
 
-static int gatt_find_info(struct bt_conn *conn,
-                          struct bt_gatt_discover_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_find_info_req *req;
+static int gatt_find_info(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  struct net_buf              *buf;
+  struct bt_att_find_info_req *req;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->start_handle = sys_cpu_to_le16(params->start_handle);
-    req->end_handle = sys_cpu_to_le16(params->end_handle);
+  req               = net_buf_add(buf, sizeof(*req));
+  req->start_handle = sys_cpu_to_le16(params->start_handle);
+  req->end_handle   = sys_cpu_to_le16(params->end_handle);
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle,
-           params->end_handle);
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle);
 
-    return gatt_send(conn, buf, gatt_find_info_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_find_info_rsp, params, NULL);
 }
 
-int bt_gatt_discover(struct bt_conn *conn,
-                     struct bt_gatt_discover_params *params)
-{
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(params && params->func, "invalid parameters\n");
-    __ASSERT((params->start_handle && params->end_handle),
-             "invalid parameters\n");
-    __ASSERT((params->start_handle <= params->end_handle),
-             "invalid parameters\n");
+int bt_gatt_discover(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(params && params->func, "invalid parameters\n");
+  __ASSERT((params->start_handle && params->end_handle), "invalid parameters\n");
+  __ASSERT((params->start_handle <= params->end_handle), "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    switch (params->type) {
-        case BT_GATT_DISCOVER_PRIMARY:
-        case BT_GATT_DISCOVER_SECONDARY:
-            if (params->uuid) {
-                return gatt_find_type(conn, params);
-            }
-            return gatt_read_group(conn, params);
-        case BT_GATT_DISCOVER_INCLUDE:
-        case BT_GATT_DISCOVER_CHARACTERISTIC:
-            return gatt_read_type(conn, params);
-        case BT_GATT_DISCOVER_DESCRIPTOR:
-            /* Only descriptors can be filtered */
-            if (params->uuid &&
-                (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_PRIMARY) ||
-                 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SECONDARY) ||
-                 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_INCLUDE) ||
-                 !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CHRC))) {
-                return -EINVAL;
-            }
+#if defined(BFLB_BLE_DISCOVER_ONGOING)
+  if (discover_ongoing != BT_GATT_ITER_STOP) {
+    return -EINPROGRESS;
+  }
+  discover_ongoing = BT_GATT_ITER_CONTINUE;
 
-#if defined(BFLB_BLE)
-            __attribute__((fallthrough));
+  return bt_gatt_discover_continue(conn, params);
+}
+int bt_gatt_discover_continue(struct bt_conn *conn, struct bt_gatt_discover_params *params) {
 #endif
-
-            /* Fallthrough. */
-        case BT_GATT_DISCOVER_ATTRIBUTE:
-            return gatt_find_info(conn, params);
-        default:
-            BT_ERR("Invalid discovery type: %u", params->type);
+  switch (params->type) {
+  case BT_GATT_DISCOVER_PRIMARY:
+  case BT_GATT_DISCOVER_SECONDARY:
+    if (params->uuid) {
+      return gatt_find_type(conn, params);
+    }
+    return gatt_read_group(conn, params);
+  case BT_GATT_DISCOVER_INCLUDE:
+  case BT_GATT_DISCOVER_CHARACTERISTIC:
+    return gatt_read_type(conn, params);
+  case BT_GATT_DISCOVER_DESCRIPTOR:
+    /* Only descriptors can be filtered */
+    if (params->uuid && (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_PRIMARY) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SECONDARY) || !bt_uuid_cmp(params->uuid, BT_UUID_GATT_INCLUDE) ||
+                         !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CHRC))) {
+      return -EINVAL;
     }
 
-    return -EINVAL;
-}
+#if defined(BFLB_BLE)
+    __attribute__((fallthrough));
+#endif
 
-static void parse_read_by_uuid(struct bt_conn *conn,
-                               struct bt_gatt_read_params *params,
-                               const void *pdu, u16_t length)
-{
-    const struct bt_att_read_type_rsp *rsp = pdu;
+    /* Fallthrough. */
+  case BT_GATT_DISCOVER_ATTRIBUTE:
+    return gatt_find_info(conn, params);
+  default:
+    BT_ERR("Invalid discovery type: %u", params->type);
+  }
 
-    /* Parse values found */
-    for (length--, pdu = rsp->data; length;
-         length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
-        const struct bt_att_data *data = pdu;
-        u16_t handle;
-        u16_t len;
+  return -EINVAL;
+}
 
-        handle = sys_le16_to_cpu(data->handle);
+static void parse_read_by_uuid(struct bt_conn *conn, struct bt_gatt_read_params *params, const void *pdu, u16_t length) {
+  const struct bt_att_read_type_rsp *rsp = pdu;
 
-        /* Handle 0 is invalid */
-        if (!handle) {
-            BT_ERR("Invalid handle");
-            return;
-        }
+  /* Parse values found */
+  for (length--, pdu = rsp->data; length; length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) {
+    const struct bt_att_data *data = pdu;
+    u16_t                     handle;
+    u16_t                     len;
 
-        len = rsp->len > length ? length - 2 : rsp->len - 2;
+    handle = sys_le16_to_cpu(data->handle);
 
-        BT_DBG("handle 0x%04x len %u value %u", handle, rsp->len, len);
+    /* Handle 0 is invalid */
+    if (!handle) {
+      BT_ERR("Invalid handle");
+      return;
+    }
 
-        /* Update start_handle */
-        params->by_uuid.start_handle = handle;
+    len = rsp->len > length ? length - 2 : rsp->len - 2;
 
-        if (params->func(conn, 0, params, data->value, len) ==
-            BT_GATT_ITER_STOP) {
-            return;
-        }
+    BT_DBG("handle 0x%04x len %u value %u", handle, rsp->len, len);
 
-        /* Check if long attribute */
-        if (rsp->len > length) {
-            break;
-        }
+    /* Update start_handle */
+    params->by_uuid.start_handle = handle;
 
-        /* Stop if it's the last handle to be read */
-        if (params->by_uuid.start_handle == params->by_uuid.end_handle) {
-            params->func(conn, 0, params, NULL, 0);
-            return;
-        }
+    if (params->func(conn, 0, params, data->value, len) == BT_GATT_ITER_STOP) {
+      return;
+    }
 
-        params->by_uuid.start_handle++;
+    /* Check if long attribute */
+    if (rsp->len > length) {
+      break;
     }
 
-    /* Continue reading the attributes */
-    if (bt_gatt_read(conn, params) < 0) {
-        params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
+    /* Stop if it's the last handle to be read */
+    if (params->by_uuid.start_handle == params->by_uuid.end_handle) {
+      params->func(conn, 0, params, NULL, 0);
+      return;
     }
-}
 
-static void gatt_read_rsp(struct bt_conn *conn, u8_t err, const void *pdu,
-                          u16_t length, void *user_data)
-{
-    struct bt_gatt_read_params *params = user_data;
+    params->by_uuid.start_handle++;
+  }
 
-    BT_DBG("err 0x%02x", err);
+  /* Continue reading the attributes */
+  if (bt_gatt_read(conn, params) < 0) {
+    params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
+  }
+}
 
-    if (err || !length) {
-        params->func(conn, err, params, NULL, 0);
-        return;
-    }
+static void gatt_read_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_read_params *params = user_data;
 
-    if (!params->handle_count) {
-        parse_read_by_uuid(conn, params, pdu, length);
-        return;
-    }
+  BT_DBG("err 0x%02x", err);
 
-    if (params->func(conn, 0, params, pdu, length) == BT_GATT_ITER_STOP) {
-        return;
-    }
+  if (err || !length) {
+    params->func(conn, err, params, NULL, 0);
+    return;
+  }
 
-    /*
-	 * Core Spec 4.2, Vol. 3, Part G, 4.8.1
-	 * If the Characteristic Value is greater than (ATT_MTU - 1) octets
-	 * in length, the Read Long Characteristic Value procedure may be used
-	 * if the rest of the Characteristic Value is required.
-	 */
-    if (length < (bt_att_get_mtu(conn) - 1)) {
-        params->func(conn, 0, params, NULL, 0);
-        return;
-    }
+  if (!params->handle_count) {
+    parse_read_by_uuid(conn, params, pdu, length);
+    return;
+  }
 
-    params->single.offset += length;
+  if (params->func(conn, 0, params, pdu, length) == BT_GATT_ITER_STOP) {
+    return;
+  }
+
+  /*
+   * Core Spec 4.2, Vol. 3, Part G, 4.8.1
+   * If the Characteristic Value is greater than (ATT_MTU - 1) octets
+   * in length, the Read Long Characteristic Value procedure may be used
+   * if the rest of the Characteristic Value is required.
+   */
+  if (length < (bt_att_get_mtu(conn) - 1)) {
+    params->func(conn, 0, params, NULL, 0);
+    return;
+  }
 
-    /* Continue reading the attribute */
-    if (bt_gatt_read(conn, params) < 0) {
-        params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
-    }
+  params->single.offset += length;
+
+  /* Continue reading the attribute */
+  if (bt_gatt_read(conn, params) < 0) {
+    params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
+  }
 }
 
-static int gatt_read_blob(struct bt_conn *conn,
-                          struct bt_gatt_read_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_blob_req *req;
+static int gatt_read_blob(struct bt_conn *conn, struct bt_gatt_read_params *params) {
+  struct net_buf              *buf;
+  struct bt_att_read_blob_req *req;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_BLOB_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_BLOB_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(params->single.handle);
-    req->offset = sys_cpu_to_le16(params->single.offset);
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(params->single.handle);
+  req->offset = sys_cpu_to_le16(params->single.offset);
 
-    BT_DBG("handle 0x%04x offset 0x%04x", params->single.handle,
-           params->single.offset);
+  BT_DBG("handle 0x%04x offset 0x%04x", params->single.handle, params->single.offset);
 
-    return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
 }
 
-static int gatt_read_uuid(struct bt_conn *conn,
-                          struct bt_gatt_read_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_type_req *req;
+static int gatt_read_uuid(struct bt_conn *conn, struct bt_gatt_read_params *params) {
+  struct net_buf              *buf;
+  struct bt_att_read_type_req *req;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->start_handle = sys_cpu_to_le16(params->by_uuid.start_handle);
-    req->end_handle = sys_cpu_to_le16(params->by_uuid.end_handle);
+  req               = net_buf_add(buf, sizeof(*req));
+  req->start_handle = sys_cpu_to_le16(params->by_uuid.start_handle);
+  req->end_handle   = sys_cpu_to_le16(params->by_uuid.end_handle);
 
-    if (params->by_uuid.uuid->type == BT_UUID_TYPE_16) {
-        net_buf_add_le16(buf, BT_UUID_16(params->by_uuid.uuid)->val);
-    } else {
-        net_buf_add_mem(buf, BT_UUID_128(params->by_uuid.uuid)->val, 16);
-    }
+  if (params->by_uuid.uuid->type == BT_UUID_TYPE_16) {
+    net_buf_add_le16(buf, BT_UUID_16(params->by_uuid.uuid)->val);
+  } else {
+    net_buf_add_mem(buf, BT_UUID_128(params->by_uuid.uuid)->val, 16);
+  }
 
-    BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s",
-           params->by_uuid.start_handle, params->by_uuid.end_handle,
-           bt_uuid_str(params->by_uuid.uuid));
+  BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", params->by_uuid.start_handle, params->by_uuid.end_handle, bt_uuid_str(params->by_uuid.uuid));
 
-    return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
 }
 
 #if defined(CONFIG_BT_GATT_READ_MULTIPLE)
-static void gatt_read_multiple_rsp(struct bt_conn *conn, u8_t err,
-                                   const void *pdu, u16_t length,
-                                   void *user_data)
-{
-    struct bt_gatt_read_params *params = user_data;
+static void gatt_read_multiple_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_read_params *params = user_data;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    if (err || !length) {
-        params->func(conn, err, params, NULL, 0);
-        return;
-    }
+  if (err || !length) {
+    params->func(conn, err, params, NULL, 0);
+    return;
+  }
 
-    params->func(conn, 0, params, pdu, length);
+  params->func(conn, 0, params, pdu, length);
 
-    /* mark read as complete since read multiple is single response */
-    params->func(conn, 0, params, NULL, 0);
+  /* mark read as complete since read multiple is single response */
+  params->func(conn, 0, params, NULL, 0);
 }
 
-static int gatt_read_multiple(struct bt_conn *conn,
-                              struct bt_gatt_read_params *params)
-{
-    struct net_buf *buf;
-    u8_t i;
+static int gatt_read_multiple(struct bt_conn *conn, struct bt_gatt_read_params *params) {
+  struct net_buf *buf;
+  u8_t            i;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_REQ,
-                            params->handle_count * sizeof(u16_t));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_REQ, params->handle_count * sizeof(u16_t));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    for (i = 0U; i < params->handle_count; i++) {
-        net_buf_add_le16(buf, params->handles[i]);
-    }
+  for (i = 0U; i < params->handle_count; i++) {
+    net_buf_add_le16(buf, params->handles[i]);
+  }
 
-    return gatt_send(conn, buf, gatt_read_multiple_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_read_multiple_rsp, params, NULL);
 }
 #else
-static int gatt_read_multiple(struct bt_conn *conn,
-                              struct bt_gatt_read_params *params)
-{
-    return -ENOTSUP;
-}
+static int gatt_read_multiple(struct bt_conn *conn, struct bt_gatt_read_params *params) { return -ENOTSUP; }
 #endif /* CONFIG_BT_GATT_READ_MULTIPLE */
 
-int bt_gatt_read(struct bt_conn *conn, struct bt_gatt_read_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_read_req *req;
+int bt_gatt_read(struct bt_conn *conn, struct bt_gatt_read_params *params) {
+  struct net_buf         *buf;
+  struct bt_att_read_req *req;
 
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(params && params->func, "invalid parameters\n");
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(params && params->func, "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    if (params->handle_count == 0) {
-        return gatt_read_uuid(conn, params);
-    }
+  if (params->handle_count == 0) {
+    return gatt_read_uuid(conn, params);
+  }
 
-    if (params->handle_count > 1) {
-        return gatt_read_multiple(conn, params);
-    }
+  if (params->handle_count > 1) {
+    return gatt_read_multiple(conn, params);
+  }
 
-    if (params->single.offset) {
-        return gatt_read_blob(conn, params);
-    }
+  if (params->single.offset) {
+    return gatt_read_blob(conn, params);
+  }
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(params->single.handle);
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(params->single.handle);
 
-    BT_DBG("handle 0x%04x", params->single.handle);
+  BT_DBG("handle 0x%04x", params->single.handle);
 
-    return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_read_rsp, params, NULL);
 }
 
-static void gatt_write_rsp(struct bt_conn *conn, u8_t err, const void *pdu,
-                           u16_t length, void *user_data)
-{
-    struct bt_gatt_write_params *params = user_data;
+static void gatt_write_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_write_params *params = user_data;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    params->func(conn, err, params);
+  params->func(conn, err, params);
 }
 
-int bt_gatt_write_without_response_cb(struct bt_conn *conn, u16_t handle,
-                                      const void *data, u16_t length, bool sign,
-                                      bt_gatt_complete_func_t func,
-                                      void *user_data)
-{
-    struct net_buf *buf;
-    struct bt_att_write_cmd *cmd;
+int bt_gatt_write_without_response_cb(struct bt_conn *conn, u16_t handle, const void *data, u16_t length, bool sign, bt_gatt_complete_func_t func, void *user_data) {
+  struct net_buf          *buf;
+  struct bt_att_write_cmd *cmd;
 
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(handle, "invalid parameters\n");
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(handle, "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
 #if defined(CONFIG_BT_SMP)
-    if (conn->encrypt) {
-        /* Don't need to sign if already encrypted */
-        sign = false;
-    }
+  if (conn->encrypt) {
+    /* Don't need to sign if already encrypted */
+    sign = false;
+  }
 #endif
 
-    if (sign) {
-        buf = bt_att_create_pdu(conn, BT_ATT_OP_SIGNED_WRITE_CMD,
-                                sizeof(*cmd) + length + 12);
-    } else {
-        buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_CMD,
-                                sizeof(*cmd) + length);
-    }
-    if (!buf) {
-        return -ENOMEM;
-    }
+  if (sign) {
+    buf = bt_att_create_pdu(conn, BT_ATT_OP_SIGNED_WRITE_CMD, sizeof(*cmd) + length + 12);
+  } else {
+    buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_CMD, sizeof(*cmd) + length);
+  }
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    cmd = net_buf_add(buf, sizeof(*cmd));
-    cmd->handle = sys_cpu_to_le16(handle);
-    memcpy(cmd->value, data, length);
-    net_buf_add(buf, length);
+  cmd         = net_buf_add(buf, sizeof(*cmd));
+  cmd->handle = sys_cpu_to_le16(handle);
+  memcpy(cmd->value, data, length);
+  net_buf_add(buf, length);
 
-    BT_DBG("handle 0x%04x length %u", handle, length);
+  BT_DBG("handle 0x%04x length %u", handle, length);
 
-    return bt_att_send(conn, buf, func, user_data);
+  return bt_att_send(conn, buf, func, user_data);
 }
 
-static int gatt_exec_write(struct bt_conn *conn,
-                           struct bt_gatt_write_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_exec_write_req *req;
+static int gatt_exec_write(struct bt_conn *conn, struct bt_gatt_write_params *params) {
+  struct net_buf               *buf;
+  struct bt_att_exec_write_req *req;
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_REQ, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_REQ, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
+  req = net_buf_add(buf, sizeof(*req));
 #if defined(CONFIG_BT_STACK_PTS)
-    if (event_flag == gatt_cancel_write_req)
-        req->flags = BT_ATT_FLAG_CANCEL;
-    else
-        req->flags = BT_ATT_FLAG_EXEC;
-#else
+  if (event_flag == gatt_cancel_write_req)
+    req->flags = BT_ATT_FLAG_CANCEL;
+  else
     req->flags = BT_ATT_FLAG_EXEC;
+#else
+  req->flags = BT_ATT_FLAG_EXEC;
 #endif
 
-    BT_DBG("");
+  BT_DBG("");
 
-    return gatt_send(conn, buf, gatt_write_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_write_rsp, params, NULL);
 }
 
-static void gatt_prepare_write_rsp(struct bt_conn *conn, u8_t err,
-                                   const void *pdu, u16_t length,
-                                   void *user_data)
-{
-    struct bt_gatt_write_params *params = user_data;
+static void gatt_prepare_write_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_write_params *params = user_data;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    /* Don't continue in case of error */
-    if (err) {
-        params->func(conn, err, params);
-        return;
-    }
-    /* If there is no more data execute */
-    if (!params->length) {
-        gatt_exec_write(conn, params);
-        return;
-    }
+  /* Don't continue in case of error */
+  if (err) {
+    params->func(conn, err, params);
+    return;
+  }
+  /* If there is no more data execute */
+  if (!params->length) {
+    gatt_exec_write(conn, params);
+    return;
+  }
 
-    /* Write next chunk */
-    bt_gatt_write(conn, params);
+  /* Write next chunk */
+  bt_gatt_write(conn, params);
 }
 
-static int gatt_prepare_write(struct bt_conn *conn,
-                              struct bt_gatt_write_params *params)
+static int gatt_prepare_write(struct bt_conn *conn, struct bt_gatt_write_params *params)
 
 {
-    struct net_buf *buf;
-    struct bt_att_prepare_write_req *req;
-    u16_t len;
+  struct net_buf                  *buf;
+  struct bt_att_prepare_write_req *req;
+  u16_t                            len;
 
-    len = MIN(params->length, bt_att_get_mtu(conn) - sizeof(*req) - 1);
+  len = MIN(params->length, bt_att_get_mtu(conn) - sizeof(*req) - 1);
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_REQ,
-                            sizeof(*req) + len);
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_REQ, sizeof(*req) + len);
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(params->handle);
-    req->offset = sys_cpu_to_le16(params->offset);
-    memcpy(req->value, params->data, len);
-    net_buf_add(buf, len);
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(params->handle);
+  req->offset = sys_cpu_to_le16(params->offset);
+  memcpy(req->value, params->data, len);
+  net_buf_add(buf, len);
 
-    /* Update params */
-    params->offset += len;
-    params->data = (const u8_t *)params->data + len;
-    params->length -= len;
+  /* Update params */
+  params->offset += len;
+  params->data = (const u8_t *)params->data + len;
+  params->length -= len;
 
-    BT_DBG("handle 0x%04x offset %u len %u", params->handle, params->offset,
-           params->length);
+  BT_DBG("handle 0x%04x offset %u len %u", params->handle, params->offset, params->length);
 
-    return gatt_send(conn, buf, gatt_prepare_write_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_prepare_write_rsp, params, NULL);
 }
 
 #if defined(CONFIG_BT_STACK_PTS)
-int bt_gatt_prepare_write(struct bt_conn *conn,
-                          struct bt_gatt_write_params *params)
-{
-    return gatt_prepare_write(conn, params);
-}
+int bt_gatt_prepare_write(struct bt_conn *conn, struct bt_gatt_write_params *params) { return gatt_prepare_write(conn, params); }
 #endif
 
-int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_write_req *req;
+int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params) {
+  struct net_buf          *buf;
+  struct bt_att_write_req *req;
 
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(params && params->func, "invalid parameters\n");
-    __ASSERT(params->handle, "invalid parameters\n");
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(params && params->func, "invalid parameters\n");
+  __ASSERT(params->handle, "invalid parameters\n");
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    /* Use Prepare Write if offset is set or Long Write is required */
-    if (params->offset ||
-        params->length > (bt_att_get_mtu(conn) - sizeof(*req) - 1)) {
-        return gatt_prepare_write(conn, params);
-    }
+  /* Use Prepare Write if offset is set or Long Write is required */
+  if (params->offset || params->length > (bt_att_get_mtu(conn) - sizeof(*req) - 1)) {
+    return gatt_prepare_write(conn, params);
+  }
 
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ,
-                            sizeof(*req) + params->length);
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, sizeof(*req) + params->length);
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(params->handle);
-    memcpy(req->value, params->data, params->length);
-    net_buf_add(buf, params->length);
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(params->handle);
+  memcpy(req->value, params->data, params->length);
+  net_buf_add(buf, params->length);
 
-    BT_DBG("handle 0x%04x length %u", params->handle, params->length);
+  BT_DBG("handle 0x%04x length %u", params->handle, params->length);
 
-    return gatt_send(conn, buf, gatt_write_rsp, params, NULL);
+  return gatt_send(conn, buf, gatt_write_rsp, params, NULL);
 }
 
-static void gatt_subscription_add(struct bt_conn *conn,
-                                  struct bt_gatt_subscribe_params *params)
-{
-    bt_addr_le_copy(¶ms->_peer, &conn->le.dst);
+static void gatt_subscription_add(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) {
+  bt_addr_le_copy(¶ms->_peer, &conn->le.dst);
 
-    /* Prepend subscription */
-    sys_slist_prepend(&subscriptions, ¶ms->node);
+  /* Prepend subscription */
+  sys_slist_prepend(&subscriptions, ¶ms->node);
 }
 
-static void gatt_write_ccc_rsp(struct bt_conn *conn, u8_t err,
-                               const void *pdu, u16_t length,
-                               void *user_data)
-{
-    struct bt_gatt_subscribe_params *params = user_data;
+static void gatt_write_ccc_rsp(struct bt_conn *conn, u8_t err, const void *pdu, u16_t length, void *user_data) {
+  struct bt_gatt_subscribe_params *params = user_data;
 
-    BT_DBG("err 0x%02x", err);
+  BT_DBG("err 0x%02x", err);
 
-    atomic_clear_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
+  atomic_clear_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
 
-    /* if write to CCC failed we remove subscription and notify app */
-    if (err) {
-        sys_snode_t *node, *tmp, *prev = NULL;
-        UNUSED(prev);
+  /* if write to CCC failed we remove subscription and notify app */
+  if (err) {
+    sys_snode_t *node, *tmp, *prev = NULL;
+    UNUSED(prev);
 
-        SYS_SLIST_FOR_EACH_NODE_SAFE(&subscriptions, node, tmp)
-        {
-            if (node == ¶ms->node) {
-                gatt_subscription_remove(conn, tmp, params);
-                break;
-            }
+    SYS_SLIST_FOR_EACH_NODE_SAFE(&subscriptions, node, tmp) {
+      if (node == ¶ms->node) {
+        gatt_subscription_remove(conn, tmp, params);
+        break;
+      }
 
-            prev = node;
-        }
-    } else if (!params->value) {
-        /* Notify with NULL data to complete unsubscribe */
-        params->notify(conn, params, NULL, 0);
+      prev = node;
     }
+  } else if (!params->value) {
+    /* Notify with NULL data to complete unsubscribe */
+    params->notify(conn, params, NULL, 0);
+  }
 #if defined(BFLB_BLE_PATCH_NOTIFY_WRITE_CCC_RSP)
-    else {
-        params->notify(conn, params, NULL, 0);
-    }
+  else {
+    params->notify(conn, params, NULL, 0);
+  }
 #endif
 }
 
-static int gatt_write_ccc(struct bt_conn *conn, u16_t handle, u16_t value,
-                          bt_att_func_t func,
-                          struct bt_gatt_subscribe_params *params)
-{
-    struct net_buf *buf;
-    struct bt_att_write_req *req;
-
-    buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ,
-                            sizeof(*req) + sizeof(u16_t));
-    if (!buf) {
-        return -ENOMEM;
-    }
-
-    req = net_buf_add(buf, sizeof(*req));
-    req->handle = sys_cpu_to_le16(handle);
-    net_buf_add_le16(buf, value);
-
-    BT_DBG("handle 0x%04x value 0x%04x", handle, value);
-
-    atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
-
-    return gatt_send(conn, buf, func, params, NULL);
-}
-
-int bt_gatt_subscribe(struct bt_conn *conn,
-                      struct bt_gatt_subscribe_params *params)
-{
-    struct bt_gatt_subscribe_params *tmp;
-    bool has_subscription = false;
-
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(params && params->notify, "invalid parameters\n");
-    __ASSERT(params->value, "invalid parameters\n");
-    __ASSERT(params->ccc_handle, "invalid parameters\n");
+static int gatt_write_ccc(struct bt_conn *conn, u16_t handle, u16_t value, bt_att_func_t func, struct bt_gatt_subscribe_params *params) {
+  struct net_buf          *buf;
+  struct bt_att_write_req *req;
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, sizeof(*req) + sizeof(u16_t));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    /* Lookup existing subscriptions */
-    SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, tmp, node)
-    {
-        /* Fail if entry already exists */
-        if (tmp == params) {
-            return -EALREADY;
-        }
+  req         = net_buf_add(buf, sizeof(*req));
+  req->handle = sys_cpu_to_le16(handle);
+  net_buf_add_le16(buf, value);
 
-        /* Check if another subscription exists */
-        if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) &&
-            tmp->value_handle == params->value_handle &&
-            tmp->value >= params->value) {
-            has_subscription = true;
-        }
-    }
+  BT_DBG("handle 0x%04x value 0x%04x", handle, value);
 
-    /* Skip write if already subscribed */
-    if (!has_subscription) {
-        int err;
+  atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
 
-        err = gatt_write_ccc(conn, params->ccc_handle, params->value,
-                             gatt_write_ccc_rsp, params);
-        if (err) {
-            return err;
-        }
-    }
+  return gatt_send(conn, buf, func, params, NULL);
+}
 
-    /*
-	 * Add subscription before write complete as some implementation were
-	 * reported to send notification before reply to CCC write.
-	 */
-    gatt_subscription_add(conn, params);
+int bt_gatt_subscribe(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) {
+  struct bt_gatt_subscribe_params *tmp;
+  bool                             has_subscription = false;
 
-    return 0;
-}
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(params && params->notify, "invalid parameters\n");
+  __ASSERT(params->value, "invalid parameters\n");
+  __ASSERT(params->ccc_handle, "invalid parameters\n");
 
-int bt_gatt_unsubscribe(struct bt_conn *conn,
-                        struct bt_gatt_subscribe_params *params)
-{
-    struct bt_gatt_subscribe_params *tmp, *next;
-    bool has_subscription = false, found = false;
-    sys_snode_t *prev = NULL;
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    __ASSERT(conn, "invalid parameters\n");
-    __ASSERT(params, "invalid parameters\n");
+  /* Lookup existing subscriptions */
+  SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, tmp, node) {
+    /* Fail if entry already exists */
+    if (tmp == params) {
+      return -EALREADY;
+    }
 
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
+    /* Check if another subscription exists */
+    if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) && tmp->value_handle == params->value_handle && tmp->value >= params->value) {
+      has_subscription = true;
     }
+  }
 
-    /* Lookup existing subscriptions */
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, tmp, next, node)
-    {
-        /* Remove subscription */
-        if (params == tmp) {
-            found = true;
-            sys_slist_remove(&subscriptions, prev, &tmp->node);
-            /* Attempt to cancel if write is pending */
-            if (atomic_test_bit(params->flags,
-                                BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING)) {
-                bt_gatt_cancel(conn, params);
-            }
-            continue;
-        } else {
-            prev = &tmp->node;
-        }
+  /* Skip write if already subscribed */
+  if (!has_subscription) {
+    int err;
 
-        /* Check if there still remains any other subscription */
-        if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) &&
-            tmp->value_handle == params->value_handle) {
-            has_subscription = true;
-        }
+    err = gatt_write_ccc(conn, params->ccc_handle, params->value, gatt_write_ccc_rsp, params);
+    if (err) {
+      return err;
+    }
+  }
+
+  /*
+   * Add subscription before write complete as some implementation were
+   * reported to send notification before reply to CCC write.
+   */
+  gatt_subscription_add(conn, params);
+
+  return 0;
+}
+
+int bt_gatt_unsubscribe(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) {
+  struct bt_gatt_subscribe_params *tmp, *next;
+  bool                             has_subscription = false, found = false;
+  sys_snode_t                     *prev = NULL;
+
+  __ASSERT(conn, "invalid parameters\n");
+  __ASSERT(params, "invalid parameters\n");
+
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
+
+  /* Lookup existing subscriptions */
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, tmp, next, node) {
+    /* Remove subscription */
+    if (params == tmp) {
+      found = true;
+      sys_slist_remove(&subscriptions, prev, &tmp->node);
+      /* Attempt to cancel if write is pending */
+      if (atomic_test_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING)) {
+        bt_gatt_cancel(conn, params);
+      }
+      continue;
+    } else {
+      prev = &tmp->node;
     }
 
-    if (!found) {
-        return -EINVAL;
+    /* Check if there still remains any other subscription */
+    if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) && tmp->value_handle == params->value_handle) {
+      has_subscription = true;
     }
+  }
 
-    if (has_subscription) {
-        /* Notify with NULL data to complete unsubscribe */
-        params->notify(conn, params, NULL, 0);
-        return 0;
-    }
+  if (!found) {
+    return -EINVAL;
+  }
 
-    params->value = 0x0000;
+  if (has_subscription) {
+    /* Notify with NULL data to complete unsubscribe */
+    params->notify(conn, params, NULL, 0);
+    return 0;
+  }
 
-    return gatt_write_ccc(conn, params->ccc_handle, params->value,
-                          gatt_write_ccc_rsp, params);
-}
+  params->value = 0x0000;
 
-void bt_gatt_cancel(struct bt_conn *conn, void *params)
-{
-    bt_att_req_cancel(conn, params);
+  return gatt_write_ccc(conn, params->ccc_handle, params->value, gatt_write_ccc_rsp, params);
 }
 
-static void add_subscriptions(struct bt_conn *conn)
-{
-    struct bt_gatt_subscribe_params *params;
+void bt_gatt_cancel(struct bt_conn *conn, void *params) { bt_att_req_cancel(conn, params); }
 
-    /* Lookup existing subscriptions */
-    SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, params, node)
-    {
-        if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) {
-            continue;
-        }
+static void add_subscriptions(struct bt_conn *conn) {
+  struct bt_gatt_subscribe_params *params;
 
-        /* Force write to CCC to workaround devices that don't track
-		 * it properly.
-		 */
-        gatt_write_ccc(conn, params->ccc_handle, params->value,
-                       gatt_write_ccc_rsp, params);
+  /* Lookup existing subscriptions */
+  SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, params, node) {
+    if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) {
+      continue;
     }
+
+    /* Force write to CCC to workaround devices that don't track
+     * it properly.
+     */
+    gatt_write_ccc(conn, params->ccc_handle, params->value, gatt_write_ccc_rsp, params);
+  }
 }
 
 #endif /* CONFIG_BT_GATT_CLIENT */
 
 #define CCC_STORE_MAX 48
 
-static struct bt_gatt_ccc_cfg *ccc_find_cfg(struct _bt_gatt_ccc *ccc,
-                                            const bt_addr_le_t *addr,
-                                            u8_t id)
-{
-    for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
-        if (id == ccc->cfg[i].id &&
-            !bt_addr_le_cmp(&ccc->cfg[i].peer, addr)) {
-            return &ccc->cfg[i];
-        }
+static struct bt_gatt_ccc_cfg *ccc_find_cfg(struct _bt_gatt_ccc *ccc, const bt_addr_le_t *addr, u8_t id) {
+  for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+    if (id == ccc->cfg[i].id && !bt_addr_le_cmp(&ccc->cfg[i].peer, addr)) {
+      return &ccc->cfg[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
 struct addr_with_id {
-    const bt_addr_le_t *addr;
-    u8_t id;
+  const bt_addr_le_t *addr;
+  u8_t                id;
 };
 
 struct ccc_load {
-    struct addr_with_id addr_with_id;
-    struct ccc_store *entry;
-    size_t count;
+  struct addr_with_id addr_with_id;
+  struct ccc_store   *entry;
+  size_t              count;
 };
 
-static void ccc_clear(struct _bt_gatt_ccc *ccc,
-                      const bt_addr_le_t *addr,
-                      u8_t id)
-{
-    struct bt_gatt_ccc_cfg *cfg;
+static void ccc_clear(struct _bt_gatt_ccc *ccc, const bt_addr_le_t *addr, u8_t id) {
+  struct bt_gatt_ccc_cfg *cfg;
 
-    cfg = ccc_find_cfg(ccc, addr, id);
-    if (!cfg) {
-        BT_DBG("Unable to clear CCC: cfg not found");
-        return;
-    }
+  cfg = ccc_find_cfg(ccc, addr, id);
+  if (!cfg) {
+    BT_DBG("Unable to clear CCC: cfg not found");
+    return;
+  }
 
-    clear_ccc_cfg(cfg);
+  clear_ccc_cfg(cfg);
 }
 
-static u8_t ccc_load(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct ccc_load *load = user_data;
-    struct _bt_gatt_ccc *ccc;
-    struct bt_gatt_ccc_cfg *cfg;
-
-    /* Check if attribute is a CCC */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+static u8_t ccc_load(const struct bt_gatt_attr *attr, void *user_data) {
+  struct ccc_load        *load = user_data;
+  struct _bt_gatt_ccc    *ccc;
+  struct bt_gatt_ccc_cfg *cfg;
 
-    ccc = attr->user_data;
+  /* Check if attribute is a CCC */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    /* Clear if value was invalidated */
-    if (!load->entry) {
-        ccc_clear(ccc, load->addr_with_id.addr, load->addr_with_id.id);
-        return BT_GATT_ITER_CONTINUE;
-    } else if (!load->count) {
-        return BT_GATT_ITER_STOP;
-    }
+  ccc = attr->user_data;
 
-    /* Skip if value is not for the given attribute */
-    if (load->entry->handle != attr->handle) {
-        /* If attribute handle is bigger then it means
-		 * the attribute no longer exists and cannot
-		 * be restored.
-		 */
-        if (load->entry->handle < attr->handle) {
-            BT_DBG("Unable to restore CCC: handle 0x%04x cannot be"
-                   " found",
-                   load->entry->handle);
-            goto next;
-        }
-        return BT_GATT_ITER_CONTINUE;
+  /* Clear if value was invalidated */
+  if (!load->entry) {
+    ccc_clear(ccc, load->addr_with_id.addr, load->addr_with_id.id);
+    return BT_GATT_ITER_CONTINUE;
+  } else if (!load->count) {
+    return BT_GATT_ITER_STOP;
+  }
+
+  /* Skip if value is not for the given attribute */
+  if (load->entry->handle != attr->handle) {
+    /* If attribute handle is bigger then it means
+     * the attribute no longer exists and cannot
+     * be restored.
+     */
+    if (load->entry->handle < attr->handle) {
+      BT_DBG("Unable to restore CCC: handle 0x%04x cannot be"
+             " found",
+             load->entry->handle);
+      goto next;
     }
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    BT_DBG("Restoring CCC: handle 0x%04x value 0x%04x", load->entry->handle,
-           load->entry->value);
+  BT_DBG("Restoring CCC: handle 0x%04x value 0x%04x", load->entry->handle, load->entry->value);
 
-    cfg = ccc_find_cfg(ccc, load->addr_with_id.addr, load->addr_with_id.id);
+  cfg = ccc_find_cfg(ccc, load->addr_with_id.addr, load->addr_with_id.id);
+  if (!cfg) {
+    cfg = ccc_find_cfg(ccc, BT_ADDR_LE_ANY, 0);
     if (!cfg) {
-        cfg = ccc_find_cfg(ccc, BT_ADDR_LE_ANY, 0);
-        if (!cfg) {
-            BT_DBG("Unable to restore CCC: no cfg left");
-            goto next;
-        }
-        bt_addr_le_copy(&cfg->peer, load->addr_with_id.addr);
-        cfg->id = load->addr_with_id.id;
+      BT_DBG("Unable to restore CCC: no cfg left");
+      goto next;
     }
+    bt_addr_le_copy(&cfg->peer, load->addr_with_id.addr);
+    cfg->id = load->addr_with_id.id;
+  }
 
-    cfg->value = load->entry->value;
+  cfg->value = load->entry->value;
 
 next:
-    load->entry++;
-    load->count--;
+  load->entry++;
+  load->count--;
 
-    return load->count ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP;
+  return load->count ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP;
 }
 
 #if defined(BFLB_BLE)
 static int ccc_set(const char *key, u8_t id, bt_addr_le_t *addr)
 #else
-static int ccc_set(const char *name, size_t len_rd, settings_read_cb read_cb,
-                   void *cb_arg)
+static int ccc_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
 #endif
 {
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        struct ccc_store ccc_store[CCC_STORE_MAX];
-        struct ccc_load load;
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    struct ccc_store ccc_store[CCC_STORE_MAX];
+    struct ccc_load  load;
 #if defined(BFLB_BLE)
-        size_t len;
-        int err;
+    size_t len;
+    int    err;
 #else
-        bt_addr_le_t addr;
-        const char *next;
-        int len, err;
+    bt_addr_le_t addr;
+    const char  *next;
+    int          len, err;
 #endif
 
 #if defined(BFLB_BLE)
-        err = bt_settings_get_bin(key, (u8_t *)ccc_store, CCC_STORE_MAX, &len);
-        if (err)
-            return err;
-
-        load.addr_with_id.id = id;
-        load.addr_with_id.addr = addr;
-        load.entry = ccc_store;
-        load.count = len / sizeof(*ccc_store);
+    err = bt_settings_get_bin(key, (u8_t *)ccc_store, CCC_STORE_MAX, &len);
+    if (err)
+      return err;
+
+    load.addr_with_id.id   = id;
+    load.addr_with_id.addr = addr;
+    load.entry             = ccc_store;
+    load.count             = len / sizeof(*ccc_store);
 #else
-        settings_name_next(name, &next);
-
-        if (!name) {
-            BT_ERR("Insufficient number of arguments");
-            return -EINVAL;
-        } else if (!next) {
-            load.addr_with_id.id = BT_ID_DEFAULT;
-        } else {
-            load.addr_with_id.id = strtol(next, NULL, 10);
-        }
+    settings_name_next(name, &next);
 
-        err = bt_settings_decode_key(name, &addr);
-        if (err) {
-            BT_ERR("Unable to decode address %s", log_strdup(name));
-            return -EINVAL;
-        }
+    if (!name) {
+      BT_ERR("Insufficient number of arguments");
+      return -EINVAL;
+    } else if (!next) {
+      load.addr_with_id.id = BT_ID_DEFAULT;
+    } else {
+      load.addr_with_id.id = strtol(next, NULL, 10);
+    }
 
-        load.addr_with_id.addr = &addr;
+    err = bt_settings_decode_key(name, &addr);
+    if (err) {
+      BT_ERR("Unable to decode address %s", log_strdup(name));
+      return -EINVAL;
+    }
+
+    load.addr_with_id.addr = &addr;
 
-        if (len_rd) {
-            len = read_cb(cb_arg, ccc_store, sizeof(ccc_store));
+    if (len_rd) {
+      len = read_cb(cb_arg, ccc_store, sizeof(ccc_store));
 
-            if (len < 0) {
-                BT_ERR("Failed to decode value (err %d)", len);
-                return len;
-            }
+      if (len < 0) {
+        BT_ERR("Failed to decode value (err %d)", len);
+        return len;
+      }
 
-            load.entry = ccc_store;
-            load.count = len / sizeof(*ccc_store);
+      load.entry = ccc_store;
+      load.count = len / sizeof(*ccc_store);
 
-            for (int i = 0; i < load.count; i++) {
-                BT_DBG("Read CCC: handle 0x%04x value 0x%04x",
-                       ccc_store[i].handle, ccc_store[i].value);
-            }
-        } else {
-            load.entry = NULL;
-            load.count = 0;
-        }
+      for (int i = 0; i < load.count; i++) {
+        BT_DBG("Read CCC: handle 0x%04x value 0x%04x", ccc_store[i].handle, ccc_store[i].value);
+      }
+    } else {
+      load.entry = NULL;
+      load.count = 0;
+    }
 #endif
 
-        bt_gatt_foreach_attr(0x0001, 0xffff, ccc_load, &load);
+    bt_gatt_foreach_attr(0x0001, 0xffff, ccc_load, &load);
 
-        BT_DBG("Restored CCC for id:%x"
-               "PRIu8"
-               " addr:%s",
-               load.addr_with_id.id,
-               bt_addr_le_str(load.addr_with_id.addr));
-    }
+    BT_DBG("Restored CCC for id:%x"
+           "PRIu8"
+           " addr:%s",
+           load.addr_with_id.id, bt_addr_le_str(load.addr_with_id.addr));
+  }
 
-    return 0;
+  return 0;
 }
 
 #if !defined(BFLB_BLE)
@@ -3994,23 +3634,21 @@ SETTINGS_STATIC_HANDLER_DEFINE(bt_ccc, "bt/ccc", NULL, ccc_set, NULL, NULL);
 #endif
 
 #if !defined(BFLB_BLE)
-static int ccc_set_direct(const char *key, size_t len, settings_read_cb read_cb,
-                          void *cb_arg, void *param)
-{
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        const char *name;
+static int ccc_set_direct(const char *key, size_t len, settings_read_cb read_cb, void *cb_arg, void *param) {
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    const char *name;
 
-        BT_DBG("key: %s", log_strdup((const char *)param));
-
-        /* Only "bt/ccc" settings should ever come here */
-        if (!settings_name_steq((const char *)param, "bt/ccc", &name)) {
-            BT_ERR("Invalid key");
-            return -EINVAL;
-        }
+    BT_DBG("key: %s", log_strdup((const char *)param));
 
-        return ccc_set(name, len, read_cb, cb_arg);
+    /* Only "bt/ccc" settings should ever come here */
+    if (!settings_name_steq((const char *)param, "bt/ccc", &name)) {
+      BT_ERR("Invalid key");
+      return -EINVAL;
     }
-    return 0;
+
+    return ccc_set(name, len, read_cb, cb_arg);
+  }
+  return 0;
 }
 #endif
 
@@ -4022,566 +3660,525 @@ static int sc_commit(void);
 #endif
 #endif
 #endif
-void bt_gatt_connected(struct bt_conn *conn)
-{
-    struct conn_data data;
+void bt_gatt_connected(struct bt_conn *conn) {
+  struct conn_data data;
 
-    BT_DBG("conn %p", conn);
+  BT_DBG("conn %p", conn);
 
-    data.conn = conn;
-    data.sec = BT_SECURITY_L1;
+  data.conn = conn;
+  data.sec  = BT_SECURITY_L1;
 
-    /* Load CCC settings from backend if bonded */
-    if (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) &&
-        bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-        char key[BT_SETTINGS_KEY_MAX];
+  /* Load CCC settings from backend if bonded */
+  if (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) && bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+    char key[BT_SETTINGS_KEY_MAX];
 
-        if (conn->id) {
-            char id_str[4];
+    if (conn->id) {
+      char id_str[4];
 
-            u8_to_dec(id_str, sizeof(id_str), conn->id);
-            bt_settings_encode_key(key, sizeof(key), "ccc",
-                                   &conn->le.dst, id_str);
-        } else {
-            bt_settings_encode_key(key, sizeof(key), "ccc",
-                                   &conn->le.dst, NULL);
-        }
+      u8_to_dec(id_str, sizeof(id_str), conn->id);
+      bt_settings_encode_key(key, sizeof(key), "ccc", &conn->le.dst, id_str);
+    } else {
+      bt_settings_encode_key(key, sizeof(key), "ccc", &conn->le.dst, NULL);
+    }
 #if defined(BFLB_BLE)
-        ccc_set(key, conn->id, &conn->le.dst);
+    ccc_set(key, conn->id, &conn->le.dst);
 #else
-        settings_load_subtree_direct(key, ccc_set_direct, (void *)key);
+    settings_load_subtree_direct(key, ccc_set_direct, (void *)key);
 #endif
-    }
-
-    bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data);
-
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part C page 2192:
-	 *
-	 * 10.3.1.1 Handling of GATT indications and notifications
-	 *
-	 * A client requests a server to send indications and notifications
-	 * by appropriately configuring the server via a Client Characteristic
-	 * Configuration Descriptor. Since the configuration is persistent
-	 * across a disconnection and reconnection, security requirements must
-	 * be checked against the configuration upon a reconnection before
-	 * sending indications or notifications. When a server reconnects to a
-	 * client to send an indication or notification for which security is
-	 * required, the server shall initiate or request encryption with the
-	 * client prior to sending an indication or notification. If the client
-	 * does not have an LTK indicating that the client has lost the bond,
-	 * enabling encryption will fail.
-	 */
-    if (IS_ENABLED(CONFIG_BT_SMP) &&
-        bt_conn_get_security(conn) < data.sec) {
-        bt_conn_set_security(conn, data.sec);
-    }
+  }
+
+  bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data);
+
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part C page 2192:
+   *
+   * 10.3.1.1 Handling of GATT indications and notifications
+   *
+   * A client requests a server to send indications and notifications
+   * by appropriately configuring the server via a Client Characteristic
+   * Configuration Descriptor. Since the configuration is persistent
+   * across a disconnection and reconnection, security requirements must
+   * be checked against the configuration upon a reconnection before
+   * sending indications or notifications. When a server reconnects to a
+   * client to send an indication or notification for which security is
+   * required, the server shall initiate or request encryption with the
+   * client prior to sending an indication or notification. If the client
+   * does not have an LTK indicating that the client has lost the bond,
+   * enabling encryption will fail.
+   */
+  if (IS_ENABLED(CONFIG_BT_SMP) && bt_conn_get_security(conn) < data.sec) {
+    bt_conn_set_security(conn, data.sec);
+  }
 
 #if defined(CONFIG_BT_GATT_CLIENT)
-    add_subscriptions(conn);
+  add_subscriptions(conn);
 #endif /* CONFIG_BT_GATT_CLIENT */
 
 #if defined(BFLB_BLE)
 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
 #if defined(CONFIG_BT_SETTINGS)
-    sc_set(conn->id, &conn->le.dst);
-    sc_commit();
+  sc_set(conn->id, &conn->le.dst);
+  sc_commit();
 #endif
 #endif
 #endif
 }
 
-void bt_gatt_encrypt_change(struct bt_conn *conn)
-{
-    struct conn_data data;
+void bt_gatt_encrypt_change(struct bt_conn *conn) {
+  struct conn_data data;
 
-    BT_DBG("conn %p", conn);
+  BT_DBG("conn %p", conn);
 
-    data.conn = conn;
-    data.sec = BT_SECURITY_L1;
+  data.conn = conn;
+  data.sec  = BT_SECURITY_L1;
 
-    bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data);
+  bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data);
 }
 
-bool bt_gatt_change_aware(struct bt_conn *conn, bool req)
-{
+bool bt_gatt_change_aware(struct bt_conn *conn, bool req) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    struct gatt_cf_cfg *cfg;
+  struct gatt_cf_cfg *cfg;
 
-    cfg = find_cf_cfg(conn);
-    if (!cfg || !CF_ROBUST_CACHING(cfg)) {
-        return true;
-    }
-
-    if (atomic_test_bit(cfg->flags, CF_CHANGE_AWARE)) {
-        return true;
-    }
+  cfg = find_cf_cfg(conn);
+  if (!cfg || !CF_ROBUST_CACHING(cfg)) {
+    return true;
+  }
 
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
-	 * If a change-unaware client sends an ATT command, the server shall
-	 * ignore it.
-	 */
-    if (!req) {
-        return false;
-    }
+  if (atomic_test_bit(cfg->flags, CF_CHANGE_AWARE)) {
+    return true;
+  }
 
-    /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
-	 * 2.5.2.1 Robust Caching
-	 * A connected client becomes change-aware when...
-	 * The server sends the client a response with the error code set to
-	 * Database Out Of Sync and then the server receives another ATT
-	 * request from the client.
-	 */
-    if (atomic_test_bit(cfg->flags, CF_OUT_OF_SYNC)) {
-        atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC);
-        atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
-        BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
-        return true;
-    }
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350:
+   * If a change-unaware client sends an ATT command, the server shall
+   * ignore it.
+   */
+  if (!req) {
+    return false;
+  }
+
+  /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347:
+   * 2.5.2.1 Robust Caching
+   * A connected client becomes change-aware when...
+   * The server sends the client a response with the error code set to
+   * Database Out Of Sync and then the server receives another ATT
+   * request from the client.
+   */
+  if (atomic_test_bit(cfg->flags, CF_OUT_OF_SYNC)) {
+    atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC);
+    atomic_set_bit(cfg->flags, CF_CHANGE_AWARE);
+    BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer));
+    return true;
+  }
 
-    atomic_set_bit(cfg->flags, CF_OUT_OF_SYNC);
+  atomic_set_bit(cfg->flags, CF_OUT_OF_SYNC);
 
-    return false;
+  return false;
 #else
-    return true;
+  return true;
 #endif
 }
 
-static int bt_gatt_store_cf(struct bt_conn *conn)
-{
+static int bt_gatt_store_cf(struct bt_conn *conn) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    struct gatt_cf_cfg *cfg;
-    char key[BT_SETTINGS_KEY_MAX];
-    char *str;
-    size_t len;
-    int err;
-
-    cfg = find_cf_cfg(conn);
-    if (!cfg) {
-        /* No cfg found, just clear it */
-        BT_DBG("No config for CF");
-        str = NULL;
-        len = 0;
-    } else {
-        str = (char *)cfg->data;
-        len = sizeof(cfg->data);
-
-        if (conn->id) {
-            char id_str[4];
-
-            u8_to_dec(id_str, sizeof(id_str), conn->id);
-            bt_settings_encode_key(key, sizeof(key), "cf",
-                                   &conn->le.dst, id_str);
-        }
-    }
-
-    if (!cfg || !conn->id) {
-        bt_settings_encode_key(key, sizeof(key), "cf",
-                               &conn->le.dst, NULL);
-    }
+  struct gatt_cf_cfg *cfg;
+  char                key[BT_SETTINGS_KEY_MAX];
+  char               *str;
+  size_t              len;
+  int                 err;
+
+  cfg = find_cf_cfg(conn);
+  if (!cfg) {
+    /* No cfg found, just clear it */
+    BT_DBG("No config for CF");
+    str = NULL;
+    len = 0;
+  } else {
+    str = (char *)cfg->data;
+    len = sizeof(cfg->data);
+
+    if (conn->id) {
+      char id_str[4];
+
+      u8_to_dec(id_str, sizeof(id_str), conn->id);
+      bt_settings_encode_key(key, sizeof(key), "cf", &conn->le.dst, id_str);
+    }
+  }
+
+  if (!cfg || !conn->id) {
+    bt_settings_encode_key(key, sizeof(key), "cf", &conn->le.dst, NULL);
+  }
 
 #if defined(BFLB_BLE)
-    err = settings_save_one(key, (u8_t *)str, len);
+  err = settings_save_one(key, (u8_t *)str, len);
 #else
-    err = settings_save_one(key, str, len);
+  err = settings_save_one(key, str, len);
 #endif
-    if (err) {
-        BT_ERR("Failed to store Client Features (err %d)", err);
-        return err;
-    }
+  if (err) {
+    BT_ERR("Failed to store Client Features (err %d)", err);
+    return err;
+  }
 
-    BT_DBG("Stored CF for %s (%s)", bt_addr_le_str(&conn->le.dst), log_strdup(key));
+  BT_DBG("Stored CF for %s (%s)", bt_addr_le_str(&conn->le.dst), log_strdup(key));
 #endif /* CONFIG_BT_GATT_CACHING */
-    return 0;
+  return 0;
 }
 
-void bt_gatt_disconnected(struct bt_conn *conn)
-{
-    BT_DBG("conn %p", conn);
-    bt_gatt_foreach_attr(0x0001, 0xffff, disconnected_cb, conn);
+void bt_gatt_disconnected(struct bt_conn *conn) {
+  BT_DBG("conn %p", conn);
+  bt_gatt_foreach_attr(0x0001, 0xffff, disconnected_cb, conn);
 
 #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE)
-    gatt_ccc_conn_unqueue(conn);
+  gatt_ccc_conn_unqueue(conn);
 
-    if (gatt_ccc_conn_queue_is_empty()) {
-        k_delayed_work_cancel(&gatt_ccc_store.work);
-    }
+  if (gatt_ccc_conn_queue_is_empty()) {
+    k_delayed_work_cancel(&gatt_ccc_store.work);
+  }
 #endif
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
-        bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
-        bt_gatt_store_ccc(conn->id, &conn->le.dst);
-        bt_gatt_store_cf(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS) && bt_addr_le_is_bonded(conn->id, &conn->le.dst)) {
+    bt_gatt_store_ccc(conn->id, &conn->le.dst);
+    bt_gatt_store_cf(conn);
+  }
 
 #if defined(CONFIG_BT_GATT_CLIENT)
-    remove_subscriptions(conn);
+  remove_subscriptions(conn);
 #endif /* CONFIG_BT_GATT_CLIENT */
 
 #if defined(CONFIG_BT_GATT_CACHING)
-    remove_cf_cfg(conn);
+  remove_cf_cfg(conn);
 #endif
 }
 
 #if defined(BFLB_BLE_MTU_CHANGE_CB)
-void bt_gatt_mtu_changed(struct bt_conn *conn, u16_t mtu)
-{
-    if (gatt_mtu_changed_cb)
-        gatt_mtu_changed_cb(conn, (int)mtu);
+void bt_gatt_mtu_changed(struct bt_conn *conn, u16_t mtu) {
+  if (gatt_mtu_changed_cb)
+    gatt_mtu_changed_cb(conn, (int)mtu);
 }
 
-void bt_gatt_register_mtu_callback(bt_gatt_mtu_changed_cb_t cb)
-{
-    gatt_mtu_changed_cb = cb;
-}
+void bt_gatt_register_mtu_callback(bt_gatt_mtu_changed_cb_t cb) { gatt_mtu_changed_cb = cb; }
 #endif
 
 #if defined(CONFIG_BT_SETTINGS)
 
 struct ccc_save {
-    struct addr_with_id addr_with_id;
-    struct ccc_store store[CCC_STORE_MAX];
-    size_t count;
+  struct addr_with_id addr_with_id;
+  struct ccc_store    store[CCC_STORE_MAX];
+  size_t              count;
 };
 
-static u8_t ccc_save(const struct bt_gatt_attr *attr, void *user_data)
-{
-    struct ccc_save *save = user_data;
-    struct _bt_gatt_ccc *ccc;
-    struct bt_gatt_ccc_cfg *cfg;
+static u8_t ccc_save(const struct bt_gatt_attr *attr, void *user_data) {
+  struct ccc_save        *save = user_data;
+  struct _bt_gatt_ccc    *ccc;
+  struct bt_gatt_ccc_cfg *cfg;
 
-    /* Check if attribute is a CCC */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Check if attribute is a CCC */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    ccc = attr->user_data;
+  ccc = attr->user_data;
 
-    /* Check if there is a cfg for the peer */
-    cfg = ccc_find_cfg(ccc, save->addr_with_id.addr, save->addr_with_id.id);
-    if (!cfg) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Check if there is a cfg for the peer */
+  cfg = ccc_find_cfg(ccc, save->addr_with_id.addr, save->addr_with_id.id);
+  if (!cfg) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    BT_DBG("Storing CCCs handle 0x%04x value 0x%04x", attr->handle,
-           cfg->value);
+  BT_DBG("Storing CCCs handle 0x%04x value 0x%04x", attr->handle, cfg->value);
 
-    save->store[save->count].handle = attr->handle;
-    save->store[save->count].value = cfg->value;
-    save->count++;
+  save->store[save->count].handle = attr->handle;
+  save->store[save->count].value  = cfg->value;
+  save->count++;
 
-    return BT_GATT_ITER_CONTINUE;
+  return BT_GATT_ITER_CONTINUE;
 }
 
-int bt_gatt_store_ccc(u8_t id, const bt_addr_le_t *addr)
-{
-    struct ccc_save save;
-    char key[BT_SETTINGS_KEY_MAX];
-    size_t len;
-    char *str;
-    int err;
+int bt_gatt_store_ccc(u8_t id, const bt_addr_le_t *addr) {
+  struct ccc_save save;
+  char            key[BT_SETTINGS_KEY_MAX];
+  size_t          len;
+  char           *str;
+  int             err;
 
-    save.addr_with_id.addr = addr;
-    save.addr_with_id.id = id;
-    save.count = 0;
+  save.addr_with_id.addr = addr;
+  save.addr_with_id.id   = id;
+  save.count             = 0;
 
-    bt_gatt_foreach_attr(0x0001, 0xffff, ccc_save, &save);
+  bt_gatt_foreach_attr(0x0001, 0xffff, ccc_save, &save);
 
-    if (id) {
-        char id_str[4];
+  if (id) {
+    char id_str[4];
 
-        u8_to_dec(id_str, sizeof(id_str), id);
-        bt_settings_encode_key(key, sizeof(key), "ccc",
-                               (bt_addr_le_t *)addr, id_str);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "ccc",
-                               (bt_addr_le_t *)addr, NULL);
-    }
+    u8_to_dec(id_str, sizeof(id_str), id);
+    bt_settings_encode_key(key, sizeof(key), "ccc", (bt_addr_le_t *)addr, id_str);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "ccc", (bt_addr_le_t *)addr, NULL);
+  }
 
-    if (save.count) {
-        str = (char *)save.store;
-        len = save.count * sizeof(*save.store);
-    } else {
-        /* No entries to encode, just clear */
-        str = NULL;
-        len = 0;
-    }
+  if (save.count) {
+    str = (char *)save.store;
+    len = save.count * sizeof(*save.store);
+  } else {
+    /* No entries to encode, just clear */
+    str = NULL;
+    len = 0;
+  }
 
-    err = settings_save_one(key, (const u8_t *)str, len);
-    if (err) {
-        BT_ERR("Failed to store CCCs (err %d)", err);
-        return err;
-    }
+  err = settings_save_one(key, (const u8_t *)str, len);
+  if (err) {
+    BT_ERR("Failed to store CCCs (err %d)", err);
+    return err;
+  }
 
-    BT_DBG("Stored CCCs for %s (%s)", bt_addr_le_str(addr),
-           log_strdup(key));
-    if (len) {
-        for (int i = 0; i < save.count; i++) {
-            BT_DBG("  CCC: handle 0x%04x value 0x%04x",
-                   save.store[i].handle, save.store[i].value);
-        }
-    } else {
-        BT_DBG("  CCC: NULL");
+  BT_DBG("Stored CCCs for %s (%s)", bt_addr_le_str(addr), log_strdup(key));
+  if (len) {
+    for (int i = 0; i < save.count; i++) {
+      BT_DBG("  CCC: handle 0x%04x value 0x%04x", save.store[i].handle, save.store[i].value);
     }
+  } else {
+    BT_DBG("  CCC: NULL");
+  }
 
-    return 0;
+  return 0;
 }
 
-static u8_t remove_peer_from_attr(const struct bt_gatt_attr *attr,
-                                  void *user_data)
-{
-    const struct addr_with_id *addr_with_id = user_data;
-    struct _bt_gatt_ccc *ccc;
-    struct bt_gatt_ccc_cfg *cfg;
+static u8_t remove_peer_from_attr(const struct bt_gatt_attr *attr, void *user_data) {
+  const struct addr_with_id *addr_with_id = user_data;
+  struct _bt_gatt_ccc       *ccc;
+  struct bt_gatt_ccc_cfg    *cfg;
 
-    /* Check if attribute is a CCC */
-    if (attr->write != bt_gatt_attr_write_ccc) {
-        return BT_GATT_ITER_CONTINUE;
-    }
+  /* Check if attribute is a CCC */
+  if (attr->write != bt_gatt_attr_write_ccc) {
+    return BT_GATT_ITER_CONTINUE;
+  }
 
-    ccc = attr->user_data;
+  ccc = attr->user_data;
 
-    /* Check if there is a cfg for the peer */
-    cfg = ccc_find_cfg(ccc, addr_with_id->addr, addr_with_id->id);
-    if (cfg) {
-        memset(cfg, 0, sizeof(*cfg));
-    }
+  /* Check if there is a cfg for the peer */
+  cfg = ccc_find_cfg(ccc, addr_with_id->addr, addr_with_id->id);
+  if (cfg) {
+    memset(cfg, 0, sizeof(*cfg));
+  }
 
-    return BT_GATT_ITER_CONTINUE;
+  return BT_GATT_ITER_CONTINUE;
 }
 
-static int bt_gatt_clear_ccc(u8_t id, const bt_addr_le_t *addr)
-{
-    char key[BT_SETTINGS_KEY_MAX];
-    struct addr_with_id addr_with_id = {
-        .addr = addr,
-        .id = id,
-    };
+static int bt_gatt_clear_ccc(u8_t id, const bt_addr_le_t *addr) {
+  char                key[BT_SETTINGS_KEY_MAX];
+  struct addr_with_id addr_with_id = {
+      .addr = addr,
+      .id   = id,
+  };
 
-    if (id) {
-        char id_str[4];
+  if (id) {
+    char id_str[4];
 
-        u8_to_dec(id_str, sizeof(id_str), id);
-        bt_settings_encode_key(key, sizeof(key), "ccc",
-                               (bt_addr_le_t *)addr, id_str);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "ccc",
-                               (bt_addr_le_t *)addr, NULL);
-    }
+    u8_to_dec(id_str, sizeof(id_str), id);
+    bt_settings_encode_key(key, sizeof(key), "ccc", (bt_addr_le_t *)addr, id_str);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "ccc", (bt_addr_le_t *)addr, NULL);
+  }
 
-    bt_gatt_foreach_attr(0x0001, 0xffff, remove_peer_from_attr,
-                         &addr_with_id);
+  bt_gatt_foreach_attr(0x0001, 0xffff, remove_peer_from_attr, &addr_with_id);
 
-    return settings_delete(key);
+  return settings_delete(key);
 }
 
 #if defined(CONFIG_BT_GATT_CACHING)
-static struct gatt_cf_cfg *find_cf_cfg_by_addr(const bt_addr_le_t *addr)
-{
-    int i;
+static struct gatt_cf_cfg *find_cf_cfg_by_addr(const bt_addr_le_t *addr) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
-        if (!bt_addr_le_cmp(addr, &cf_cfg[i].peer)) {
-            return &cf_cfg[i];
-        }
+  for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) {
+    if (!bt_addr_le_cmp(addr, &cf_cfg[i].peer)) {
+      return &cf_cfg[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 #endif /* CONFIG_BT_GATT_CACHING */
 
-static int bt_gatt_clear_cf(u8_t id, const bt_addr_le_t *addr)
-{
+static int bt_gatt_clear_cf(u8_t id, const bt_addr_le_t *addr) {
 #if defined(CONFIG_BT_GATT_CACHING)
-    char key[BT_SETTINGS_KEY_MAX];
-    struct gatt_cf_cfg *cfg;
+  char                key[BT_SETTINGS_KEY_MAX];
+  struct gatt_cf_cfg *cfg;
 
-    if (id) {
-        char id_str[4];
+  if (id) {
+    char id_str[4];
 
-        u8_to_dec(id_str, sizeof(id_str), id);
-        bt_settings_encode_key(key, sizeof(key), "cf",
-                               (bt_addr_le_t *)addr, id_str);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "cf",
-                               (bt_addr_le_t *)addr, NULL);
-    }
+    u8_to_dec(id_str, sizeof(id_str), id);
+    bt_settings_encode_key(key, sizeof(key), "cf", (bt_addr_le_t *)addr, id_str);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "cf", (bt_addr_le_t *)addr, NULL);
+  }
 
-    cfg = find_cf_cfg_by_addr(addr);
-    if (cfg) {
-        clear_cf_cfg(cfg);
-    }
+  cfg = find_cf_cfg_by_addr(addr);
+  if (cfg) {
+    clear_cf_cfg(cfg);
+  }
 
-    return settings_delete(key);
+  return settings_delete(key);
 #endif /* CONFIG_BT_GATT_CACHING */
-    return 0;
+  return 0;
 }
 
-static int sc_clear_by_addr(u8_t id, const bt_addr_le_t *addr)
-{
-    if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
-        struct gatt_sc_cfg *cfg;
+static int sc_clear_by_addr(u8_t id, const bt_addr_le_t *addr) {
+  if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) {
+    struct gatt_sc_cfg *cfg;
 
-        cfg = find_sc_cfg(id, (bt_addr_le_t *)addr);
-        if (cfg) {
-            sc_clear(cfg);
-        }
+    cfg = find_sc_cfg(id, (bt_addr_le_t *)addr);
+    if (cfg) {
+      sc_clear(cfg);
     }
-    return 0;
+  }
+  return 0;
 }
 
-static void bt_gatt_clear_subscriptions(const bt_addr_le_t *addr)
-{
+static void bt_gatt_clear_subscriptions(const bt_addr_le_t *addr) {
 #if defined(CONFIG_BT_GATT_CLIENT)
-    struct bt_gatt_subscribe_params *params, *tmp;
-    sys_snode_t *prev = NULL;
-
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node)
-    {
-        if (bt_addr_le_cmp(addr, ¶ms->_peer)) {
-            prev = ¶ms->node;
-            continue;
-        }
-        params->value = 0U;
-        gatt_subscription_remove(NULL, prev, params);
+  struct bt_gatt_subscribe_params *params, *tmp;
+  sys_snode_t                     *prev = NULL;
+
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) {
+    if (bt_addr_le_cmp(addr, ¶ms->_peer)) {
+      prev = ¶ms->node;
+      continue;
     }
+    params->value = 0U;
+    gatt_subscription_remove(NULL, prev, params);
+  }
 #endif /* CONFIG_BT_GATT_CLIENT */
 }
 
-int bt_gatt_clear(u8_t id, const bt_addr_le_t *addr)
-{
-    int err;
+int bt_gatt_clear(u8_t id, const bt_addr_le_t *addr) {
+  int err;
 
-    err = bt_gatt_clear_ccc(id, addr);
-    if (err < 0) {
-        return err;
-    }
+  err = bt_gatt_clear_ccc(id, addr);
+  if (err < 0) {
+    return err;
+  }
 
-    err = sc_clear_by_addr(id, addr);
-    if (err < 0) {
-        return err;
-    }
+  err = sc_clear_by_addr(id, addr);
+  if (err < 0) {
+    return err;
+  }
 
-    err = bt_gatt_clear_cf(id, addr);
-    if (err < 0) {
-        return err;
-    }
+  err = bt_gatt_clear_cf(id, addr);
+  if (err < 0) {
+    return err;
+  }
 
-    bt_gatt_clear_subscriptions(addr);
+  bt_gatt_clear_subscriptions(addr);
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_GATT_SERVICE_CHANGED)
 #if defined(BFLB_BLE)
 static int sc_set(u8_t id, bt_addr_le_t *addr)
 #else
-static int sc_set(const char *name, size_t len_rd, settings_read_cb read_cb,
-                  void *cb_arg)
+static int sc_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
 #endif
 {
-    struct gatt_sc_cfg *cfg;
+  struct gatt_sc_cfg *cfg;
 #if !defined(BFLB_BLE)
-    u8_t id;
-    bt_addr_le_t addr;
-    int len, err;
-    const char *next;
+  u8_t         id;
+  bt_addr_le_t addr;
+  int          len, err;
+  const char  *next;
 #endif
 
 #if defined(BFLB_BLE)
-    int err;
-    char key[BT_SETTINGS_KEY_MAX];
+  int  err;
+  char key[BT_SETTINGS_KEY_MAX];
 
-    cfg = find_sc_cfg(id, addr);
+  cfg = find_sc_cfg(id, addr);
+  if (!cfg) {
+    /* Find and initialize a free sc_cfg entry */
+    cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
     if (!cfg) {
-        /* Find and initialize a free sc_cfg entry */
-        cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
-        if (!cfg) {
-            BT_ERR("Unable to restore SC: no cfg left");
-            return -ENOMEM;
-        }
-
-        cfg->id = id;
-        bt_addr_le_copy(&cfg->peer, addr);
+      BT_ERR("Unable to restore SC: no cfg left");
+      return -ENOMEM;
     }
 
-    if (id) {
-        char id_str[4];
+    cfg->id = id;
+    bt_addr_le_copy(&cfg->peer, addr);
+  }
 
-        u8_to_dec(id_str, sizeof(id_str), id);
-        bt_settings_encode_key(key, sizeof(key), "sc",
-                               addr, id_str);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "sc",
-                               addr, NULL);
-    }
+  if (id) {
+    char id_str[4];
 
-    err = bt_settings_get_bin(key, (u8_t *)cfg, sizeof(*cfg), NULL);
-    if (err)
-        memset(cfg, 0, sizeof(*cfg));
-    return err;
+    u8_to_dec(id_str, sizeof(id_str), id);
+    bt_settings_encode_key(key, sizeof(key), "sc", addr, id_str);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "sc", addr, NULL);
+  }
+
+  err = bt_settings_get_bin(key, (u8_t *)cfg, sizeof(*cfg), NULL);
+  if (err)
+    memset(cfg, 0, sizeof(*cfg));
+  return err;
 #else
-    if (!name) {
-        BT_ERR("Insufficient number of arguments");
-        return -EINVAL;
-    }
+  if (!name) {
+    BT_ERR("Insufficient number of arguments");
+    return -EINVAL;
+  }
 
-    err = bt_settings_decode_key(name, &addr);
-    if (err) {
-        BT_ERR("Unable to decode address %s", log_strdup(name));
-        return -EINVAL;
-    }
+  err = bt_settings_decode_key(name, &addr);
+  if (err) {
+    BT_ERR("Unable to decode address %s", log_strdup(name));
+    return -EINVAL;
+  }
 
-    settings_name_next(name, &next);
+  settings_name_next(name, &next);
 
-    if (!next) {
-        id = BT_ID_DEFAULT;
-    } else {
-        id = strtol(next, NULL, 10);
+  if (!next) {
+    id = BT_ID_DEFAULT;
+  } else {
+    id = strtol(next, NULL, 10);
+  }
+
+  cfg = find_sc_cfg(id, &addr);
+  if (!cfg && len_rd) {
+    /* Find and initialize a free sc_cfg entry */
+    cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
+    if (!cfg) {
+      BT_ERR("Unable to restore SC: no cfg left");
+      return -ENOMEM;
     }
 
-    cfg = find_sc_cfg(id, &addr);
-    if (!cfg && len_rd) {
-        /* Find and initialize a free sc_cfg entry */
-        cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY);
-        if (!cfg) {
-            BT_ERR("Unable to restore SC: no cfg left");
-            return -ENOMEM;
-        }
+    cfg->id = id;
+    bt_addr_le_copy(&cfg->peer, &addr);
+  }
 
-        cfg->id = id;
-        bt_addr_le_copy(&cfg->peer, &addr);
+  if (len_rd) {
+    len = read_cb(cb_arg, &cfg->data, sizeof(cfg->data));
+    if (len < 0) {
+      BT_ERR("Failed to decode value (err %d)", len);
+      return len;
     }
+    BT_DBG("Read SC: len %d", len);
 
-    if (len_rd) {
-        len = read_cb(cb_arg, &cfg->data, sizeof(cfg->data));
-        if (len < 0) {
-            BT_ERR("Failed to decode value (err %d)", len);
-            return len;
-        }
-        BT_DBG("Read SC: len %d", len);
-
-        BT_DBG("Restored SC for %s", bt_addr_le_str(&addr));
-    } else if (cfg) {
-        /* Clear configuration */
-        memset(cfg, 0, sizeof(*cfg));
+    BT_DBG("Restored SC for %s", bt_addr_le_str(&addr));
+  } else if (cfg) {
+    /* Clear configuration */
+    memset(cfg, 0, sizeof(*cfg));
 
-        BT_DBG("Removed SC for %s", bt_addr_le_str(&addr));
-    }
+    BT_DBG("Removed SC for %s", bt_addr_le_str(&addr));
+  }
 
-    return 0;
+  return 0;
 #endif
 }
 
-static int sc_commit(void)
-{
-    atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING);
+static int sc_commit(void) {
+  atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING);
 
-    if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
-        /* Schedule SC indication since the range has changed */
-        k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT);
-    }
+  if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) {
+    /* Schedule SC indication since the range has changed */
+    k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT);
+  }
 
-    return 0;
+  return 0;
 }
 
 #if !defined(BFLB_BLE)
@@ -4590,103 +4187,116 @@ SETTINGS_STATIC_HANDLER_DEFINE(bt_sc, "bt/sc", NULL, sc_set, sc_commit, NULL);
 #endif /* CONFIG_BT_GATT_SERVICE_CHANGED */
 
 #if defined(CONFIG_BT_GATT_CACHING)
-static int cf_set(const char *name, size_t len_rd, settings_read_cb read_cb,
-                  void *cb_arg)
-{
-    struct gatt_cf_cfg *cfg;
-    bt_addr_le_t addr;
-    int len, err;
+static int cf_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) {
+  struct gatt_cf_cfg *cfg;
+  bt_addr_le_t        addr;
+  int                 len, err;
 
-    if (!name) {
-        BT_ERR("Insufficient number of arguments");
-        return -EINVAL;
-    }
+  if (!name) {
+    BT_ERR("Insufficient number of arguments");
+    return -EINVAL;
+  }
 
-    err = bt_settings_decode_key(name, &addr);
-    if (err) {
-        BT_ERR("Unable to decode address %s", log_strdup(name));
-        return -EINVAL;
-    }
+  err = bt_settings_decode_key(name, &addr);
+  if (err) {
+    BT_ERR("Unable to decode address %s", log_strdup(name));
+    return -EINVAL;
+  }
 
-    cfg = find_cf_cfg_by_addr(&addr);
+  cfg = find_cf_cfg_by_addr(&addr);
+  if (!cfg) {
+    cfg = find_cf_cfg(NULL);
     if (!cfg) {
-        cfg = find_cf_cfg(NULL);
-        if (!cfg) {
-            BT_ERR("Unable to restore CF: no cfg left");
-            return 0;
-        }
+      BT_ERR("Unable to restore CF: no cfg left");
+      return 0;
     }
+  }
 
-    if (len_rd) {
-        len = read_cb(cb_arg, cfg->data, sizeof(cfg->data));
-        if (len < 0) {
-            BT_ERR("Failed to decode value (err %d)", len);
-            return len;
-        }
-
-        BT_DBG("Read CF: len %d", len);
-    } else {
-        clear_cf_cfg(cfg);
+  if (len_rd) {
+    len = read_cb(cb_arg, cfg->data, sizeof(cfg->data));
+    if (len < 0) {
+      BT_ERR("Failed to decode value (err %d)", len);
+      return len;
     }
 
-    BT_DBG("Restored CF for %s", bt_addr_le_str(&addr));
+    BT_DBG("Read CF: len %d", len);
+  } else {
+    clear_cf_cfg(cfg);
+  }
 
-    return 0;
+  BT_DBG("Restored CF for %s", bt_addr_le_str(&addr));
+
+  return 0;
 }
 
 SETTINGS_STATIC_HANDLER_DEFINE(bt_cf, "bt/cf", NULL, cf_set, NULL, NULL);
 
 static u8_t stored_hash[16];
 
-static int db_hash_set(const char *name, size_t len_rd,
-                       settings_read_cb read_cb, void *cb_arg)
-{
-    int len;
+static int db_hash_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) {
+  int len;
 
-    len = read_cb(cb_arg, stored_hash, sizeof(stored_hash));
-    if (len < 0) {
-        BT_ERR("Failed to decode value (err %d)", len);
-        return len;
-    }
+  len = read_cb(cb_arg, stored_hash, sizeof(stored_hash));
+  if (len < 0) {
+    BT_ERR("Failed to decode value (err %d)", len);
+    return len;
+  }
 
-    BT_HEXDUMP_DBG(stored_hash, sizeof(stored_hash), "Stored Hash: ");
+  BT_HEXDUMP_DBG(stored_hash, sizeof(stored_hash), "Stored Hash: ");
 
-    return 0;
+  return 0;
 }
 
-static int db_hash_commit(void)
-{
-    /* Stop work and generate the hash */
-    if (k_delayed_work_remaining_get(&db_hash_work)) {
-        k_delayed_work_cancel(&db_hash_work);
-        db_hash_gen(false);
-    }
+static int db_hash_commit(void) {
+  /* Stop work and generate the hash */
+  if (k_delayed_work_remaining_get(&db_hash_work)) {
+    k_delayed_work_cancel(&db_hash_work);
+    db_hash_gen(false);
+  }
 
-    /* Check if hash matches then skip SC update */
-    if (!memcmp(stored_hash, db_hash, sizeof(stored_hash))) {
-        BT_DBG("Database Hash matches");
-        k_delayed_work_cancel(&gatt_sc.work);
-        return 0;
-    }
+  /* Check if hash matches then skip SC update */
+  if (!memcmp(stored_hash, db_hash, sizeof(stored_hash))) {
+    BT_DBG("Database Hash matches");
+    k_delayed_work_cancel(&gatt_sc.work);
+    return 0;
+  }
 
-    BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "New Hash: ");
+  BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "New Hash: ");
 
-    /**
-	 * GATT database has been modified since last boot, likely due to
-	 * a firmware update or a dynamic service that was not re-registered on
-	 * boot. Indicate Service Changed to all bonded devices for the full
-	 * database range to invalidate client-side cache and force discovery on
-	 * reconnect.
-	 */
-    sc_indicate(0x0001, 0xffff);
+  /**
+   * GATT database has been modified since last boot, likely due to
+   * a firmware update or a dynamic service that was not re-registered on
+   * boot. Indicate Service Changed to all bonded devices for the full
+   * database range to invalidate client-side cache and force discovery on
+   * reconnect.
+   */
+  sc_indicate(0x0001, 0xffff);
 
-    /* Hash did not match overwrite with current hash */
-    db_hash_store();
+  /* Hash did not match overwrite with current hash */
+  db_hash_store();
 
-    return 0;
+  return 0;
 }
 
-SETTINGS_STATIC_HANDLER_DEFINE(bt_hash, "bt/hash", NULL, db_hash_set,
-                               db_hash_commit, NULL);
+SETTINGS_STATIC_HANDLER_DEFINE(bt_hash, "bt/hash", NULL, db_hash_set, db_hash_commit, NULL);
 #endif /*CONFIG_BT_GATT_CACHING */
 #endif /* CONFIG_BT_SETTINGS */
+
+#if defined(CONFIG_BT_GATT_DYNAMIC_DB)
+uint16_t bt_gatt_get_last_handle(void) {
+  struct bt_gatt_service *last;
+  u16_t                   handle, last_handle;
+
+  if (sys_slist_is_empty(&db)) {
+    handle      = last_static_handle;
+    last_handle = handle;
+    goto last;
+  }
+
+  last        = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node);
+  handle      = last->attrs[last->attr_count - 1].handle;
+  last_handle = handle;
+last:
+  return last_handle;
+}
+#endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c
index f6bbf28ae..bf3b71d00 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.c
@@ -7,50 +7,53 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
-#include 
 #include 
-#include 
-#include 
+#include 
+#include 
 #include 
+#include 
 #include 
-#include 
-//#include 
+#include 
+#include 
+#include 
+#include 
+// #include 
 
 #include 
 #include 
-#include 
+#include 
 #include 
 #include 
-#include 
+#include 
 
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE)
 #include "log.h"
 
-#include "rpa.h"
-#include "keys.h"
-#include "monitor.h"
+#include "ecc.h"
 #include "hci_core.h"
 #include "hci_ecc.h"
-#include "ecc.h"
+#include "keys.h"
+#include "monitor.h"
+#include "rpa.h"
 
+#include "../include/bluetooth/crypto.h"
 #include "conn_internal.h"
-#include "l2cap_internal.h"
-#include "gatt_internal.h"
-#include "smp.h"
 #include "crypto.h"
-#include "../include/bluetooth/crypto.h"
+#include "gatt_internal.h"
+#include "l2cap_internal.h"
 #include "settings.h"
+#include "smp.h"
 #if defined(BFLB_BLE)
 #include "bl_hci_wrapper.h"
+#include "ble_lib_api.h"
 #if defined(BL602)
 #include "bl602_hbn.h"
 #elif defined(BL702)
 #include "bl702_hbn.h"
-#elif defined(BL606p)
+#elif defined(BL606P) || defined(BL616)
 #include "bl606p_hbn.h"
+#elif defined(BL808) // no bl808_hbn.h currently, comment it out temporarily
+#include "bl808_hbn.h"
 #endif
 #include "work_q.h"
 #endif
@@ -64,12 +67,18 @@
 
 #define HCI_CMD_TIMEOUT K_SECONDS(10)
 
+extern struct k_fifo   recv_fifo;
+extern struct k_work_q g_work_queue_main;
 /* Stacks for the threads */
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
 static struct k_thread rx_thread_data;
 static K_THREAD_STACK_DEFINE(rx_thread_stack, CONFIG_BT_RX_STACK_SIZE);
 #endif
-#if (!BFLB_BLE_CO_THREAD)
+#if (BFLB_BT_CO_THREAD)
+struct k_thread co_thread_data;
+static void     process_events(struct k_poll_event *ev, int count, int total_evt_array_cnt);
+static void     send_cmd(struct net_buf *tx_buf);
+#else
 static struct k_thread tx_thread_data;
 #endif
 #if !defined(BFLB_BLE)
@@ -81,9 +90,9 @@ static void init_work(struct k_work *work);
 struct bt_dev bt_dev = {
     .init = _K_WORK_INITIALIZER(init_work),
 /* Give cmd_sem allowing to send first HCI_Reset cmd, the only
-	 * exception is if the controller requests to wait for an
-	 * initial Command Complete for NOP.
-	 */
+ * exception is if the controller requests to wait for an
+ * initial Command Complete for NOP.
+ */
 #if defined(BFLB_BLE)
 #if !defined(CONFIG_BT_WAIT_NOP)
     .ncmd_sem = _K_SEM_INITIALIZER(bt_dev.ncmd_sem, 1, 1),
@@ -94,7 +103,7 @@ struct bt_dev bt_dev = {
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
     .rx_queue = Z_FIFO_INITIALIZER(bt_dev.rx_queue),
 #endif
-#else //BFLB_BLE
+#else // BFLB_BLE
 #if !defined(CONFIG_BT_WAIT_NOP)
     .ncmd_sem = Z_SEM_INITIALIZER(bt_dev.ncmd_sem, 1, 1),
 #else
@@ -118,20 +127,20 @@ static bt_hci_vnd_evt_cb_t *hci_vnd_evt_cb;
 #endif /* CONFIG_BT_HCI_VS_EVT_USER */
 
 #if defined(CONFIG_BT_ECC)
-static u8_t pub_key[64];
+static u8_t                  pub_key[64];
 static struct bt_pub_key_cb *pub_key_cb;
-static bt_dh_key_cb_t dh_key_cb;
+static bt_dh_key_cb_t        dh_key_cb;
 #endif /* CONFIG_BT_ECC */
 
 #if defined(CONFIG_BT_BREDR)
-static bt_br_discovery_cb_t *discovery_cb;
+static bt_br_discovery_cb_t   *discovery_cb;
 struct bt_br_discovery_result *discovery_results;
-static size_t discovery_results_size;
-static size_t discovery_results_count;
+static size_t                  discovery_results_size;
+static size_t                  discovery_results_count;
 #endif /* CONFIG_BT_BREDR */
 
 #if defined(CONFIG_BT_STACK_PTS)
-bt_addr_le_t pts_addr;
+bt_addr_le_t  pts_addr;
 volatile u8_t event_flag = 0;
 #endif
 
@@ -139,54 +148,72 @@ volatile u8_t event_flag = 0;
 struct blhast_cb *host_assist_cb;
 #endif
 
+#if (BFLB_BT_CO_THREAD)
+#if defined(CONFIG_BT_CONN)
+/* command FIFO + conn_change signal +tx queue + rxqueue + workQueue + MAX_CONN */
+#define EV_COUNT (4 + CONFIG_BT_MAX_CONN)
+#else
+/* command FIFO */
+#define EV_COUNT 2
+#endif
+#else
+#if defined(CONFIG_BT_CONN)
+/* command FIFO + conn_change signal + MAX_CONN */
+#define EV_COUNT (2 + CONFIG_BT_MAX_CONN)
+#else
+/* command FIFO */
+#define EV_COUNT 1
+#endif
+#endif // BFLB_BT_CO_THREAD
+
 struct cmd_state_set {
-    atomic_t *target;
-    int bit;
-    bool val;
+  atomic_t *target;
+  int       bit;
+  bool      val;
 };
 
 #if defined(BFLB_RELEASE_CMD_SEM_IF_CONN_DISC)
 void hci_release_conn_related_cmd(void);
 #endif
 
-void cmd_state_set_init(struct cmd_state_set *state, atomic_t *target, int bit,
-                        bool val)
-{
-    state->target = target;
-    state->bit = bit;
-    state->val = val;
+void cmd_state_set_init(struct cmd_state_set *state, atomic_t *target, int bit, bool val) {
+  state->target = target;
+  state->bit    = bit;
+  state->val    = val;
 }
 
 struct cmd_data {
-    /** HCI status of the command completion */
-    u8_t status;
-
-    /** The command OpCode that the buffer contains */
-    u16_t opcode;
+  /** HCI status of the command completion */
+  u8_t status;
 
-    /** The state to update when command completes with success. */
-    struct cmd_state_set *state;
+  /** The command OpCode that the buffer contains */
+  u16_t opcode;
 
-    /** Used by bt_hci_cmd_send_sync. */
-    struct k_sem *sync;
+  /** The state to update when command completes with success. */
+  struct cmd_state_set *state;
+#if (BFLB_BT_CO_THREAD)
+  uint8_t sync_state;
+#endif
+  /** Used by bt_hci_cmd_send_sync. */
+  struct k_sem *sync;
 };
 
 struct acl_data {
-    /** BT_BUF_ACL_IN */
-    u8_t type;
+  /** BT_BUF_ACL_IN */
+  u8_t type;
 
-    /* Index into the bt_conn storage array */
-    u8_t id;
+  /* Index into the bt_conn storage array */
+  u8_t id;
 
-    /** ACL connection handle */
-    u16_t handle;
+  /** ACL connection handle */
+  u16_t handle;
 };
 
 #if defined(BFLB_BLE)
 extern struct k_sem g_poll_sem;
 #endif
 
-static struct cmd_data cmd_data[CONFIG_BT_HCI_CMD_COUNT];
+__attribute__((section(".tcm_data"))) static struct cmd_data cmd_data[CONFIG_BT_HCI_CMD_COUNT];
 
 #define cmd(buf) (&cmd_data[net_buf_id(buf)])
 #define acl(buf) ((struct acl_data *)net_buf_user_data(buf))
@@ -196,11 +223,9 @@ static struct cmd_data cmd_data[CONFIG_BT_HCI_CMD_COUNT];
  */
 #define CMD_BUF_SIZE BT_BUF_RX_SIZE
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
-NET_BUF_POOL_FIXED_DEFINE(hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT,
-                          CMD_BUF_SIZE, NULL);
+NET_BUF_POOL_FIXED_DEFINE(hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, CMD_BUF_SIZE, NULL);
 
-NET_BUF_POOL_FIXED_DEFINE(hci_rx_pool, CONFIG_BT_RX_BUF_COUNT,
-                          BT_BUF_RX_SIZE, NULL);
+NET_BUF_POOL_FIXED_DEFINE(hci_rx_pool, CONFIG_BT_RX_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
 #if defined(CONFIG_BT_CONN)
 /* Dedicated pool for HCI_Number_of_Completed_Packets. This event is always
  * consumed synchronously by bt_recv_prio() so a single buffer is enough.
@@ -211,8 +236,7 @@ NET_BUF_POOL_FIXED_DEFINE(num_complete_pool, 1, BT_BUF_RX_SIZE, NULL);
 #endif /* CONFIG_BT_CONN */
 
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
-NET_BUF_POOL_FIXED_DEFINE(discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT,
-                          BT_BUF_RX_SIZE, NULL);
+NET_BUF_POOL_FIXED_DEFINE(discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
 #endif /* CONFIG_BT_DISCARDABLE_BUF_COUNT */
 #else
 struct net_buf_pool hci_cmd_pool;
@@ -225,205 +249,248 @@ struct net_buf_pool discardable_pool;
 #endif
 #endif /*!defined(BFLB_DYNAMIC_ALLOC_MEM)*/
 
+#if defined CONFIG_BT_HFP
 extern bool hfp_codec_msbc;
+#endif
 
 struct event_handler {
-    u8_t event;
-    u8_t min_len;
-    void (*handler)(struct net_buf *buf);
+  u8_t event;
+  u8_t min_len;
+  void (*handler)(struct net_buf *buf);
 };
 
-#define EVENT_HANDLER(_evt, _handler, _min_len) \
-    {                                           \
-        .event = _evt,                          \
-        .handler = _handler,                    \
-        .min_len = _min_len,                    \
-    }
-
-static inline void handle_event(u8_t event, struct net_buf *buf,
-                                const struct event_handler *handlers,
-                                size_t num_handlers)
-{
-    size_t i;
+#define EVENT_HANDLER(_evt, _handler, _min_len)                                                                                                                                                        \
+  {                                                                                                                                                                                                    \
+      .event   = _evt,                                                                                                                                                                                 \
+      .handler = _handler,                                                                                                                                                                             \
+      .min_len = _min_len,                                                                                                                                                                             \
+  }
 
-    for (i = 0; i < num_handlers; i++) {
-        const struct event_handler *handler = &handlers[i];
+static inline void handle_event(u8_t event, struct net_buf *buf, const struct event_handler *handlers, size_t num_handlers) {
+  size_t i;
 
-        if (handler->event != event) {
-            continue;
-        }
+  for (i = 0; i < num_handlers; i++) {
+    const struct event_handler *handler = &handlers[i];
 
-        if (buf->len < handler->min_len) {
-            BT_ERR("Too small (%u bytes) event 0x%02x",
-                   buf->len, event);
-            return;
-        }
+    if (handler->event != event) {
+      continue;
+    }
 
-        handler->handler(buf);
-        return;
+    if (buf->len < handler->min_len) {
+      BT_ERR("Too small (%u bytes) event 0x%02x", buf->len, event);
+      return;
     }
 
-    BT_WARN("Unhandled event 0x%02x len %u: %s", event,
-            buf->len, bt_hex(buf->data, buf->len));
+    handler->handler(buf);
+    return;
+  }
+
+  BT_WARN("Unhandled event 0x%02x len %u: %s", event, buf->len, bt_hex(buf->data, buf->len));
 }
 
-static inline bool is_wl_empty(void)
-{
+static inline bool is_wl_empty(void) {
 #if defined(CONFIG_BT_WHITELIST)
-    return !bt_dev.le.wl_entries;
+  return !bt_dev.le.wl_entries;
 #else
-    return true;
+  return true;
 #endif /* defined(CONFIG_BT_WHITELIST) */
 }
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-static void report_completed_packet(struct net_buf *buf)
-{
-    struct bt_hci_cp_host_num_completed_packets *cp;
-    u16_t handle = acl(buf)->handle;
-    struct bt_hci_handle_count *hc;
-    struct bt_conn *conn;
+static void report_completed_packet(struct net_buf *buf) {
+  struct bt_hci_cp_host_num_completed_packets *cp;
+  u16_t                                        handle = acl(buf)->handle;
+  struct bt_hci_handle_count                  *hc;
+  struct bt_conn                              *conn;
 
-    net_buf_destroy(buf);
-
-    /* Do nothing if controller to host flow control is not supported */
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) {
-        return;
-    }
+  net_buf_destroy(buf);
 
-    conn = bt_conn_lookup_id(acl(buf)->id);
-    if (!conn) {
-        BT_WARN("Unable to look up conn with id 0x%02x", acl(buf)->id);
-        return;
-    }
+  /* Do nothing if controller to host flow control is not supported */
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) {
+    return;
+  }
 
-    if (conn->state != BT_CONN_CONNECTED &&
-        conn->state != BT_CONN_DISCONNECT) {
-        BT_WARN("Not reporting packet for non-connected conn");
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_id(acl(buf)->id);
+  if (!conn) {
+    BT_WARN("Unable to look up conn with id 0x%02x", acl(buf)->id);
+    return;
+  }
 
+  if (conn->state != BT_CONN_CONNECTED && conn->state != BT_CONN_DISCONNECT) {
+    BT_WARN("Not reporting packet for non-connected conn");
     bt_conn_unref(conn);
+    return;
+  }
 
-    BT_DBG("Reporting completed packet for handle %u", handle);
+  bt_conn_unref(conn);
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS,
-                            sizeof(*cp) + sizeof(*hc));
-    if (!buf) {
-        BT_ERR("Unable to allocate new HCI command");
-        return;
-    }
+  BT_DBG("Reporting completed packet for handle %u", handle);
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->num_handles = sys_cpu_to_le16(1);
+  buf = bt_hci_cmd_create(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, sizeof(*cp) + sizeof(*hc));
+  if (!buf) {
+    BT_ERR("Unable to allocate new HCI command");
+    return;
+  }
 
-    hc = net_buf_add(buf, sizeof(*hc));
-    hc->handle = sys_cpu_to_le16(handle);
-    hc->count = sys_cpu_to_le16(1);
+  cp              = net_buf_add(buf, sizeof(*cp));
+  cp->num_handles = sys_cpu_to_le16(1);
 
-    bt_hci_cmd_send(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, buf);
+  hc         = net_buf_add(buf, sizeof(*hc));
+  hc->handle = sys_cpu_to_le16(handle);
+  hc->count  = sys_cpu_to_le16(1);
+
+  bt_hci_cmd_send(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, buf);
 }
 
 #define ACL_IN_SIZE BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_RX_MTU)
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
-NET_BUF_POOL_DEFINE(acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE,
-                    sizeof(struct acl_data), report_completed_packet);
+NET_BUF_POOL_DEFINE(acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE, sizeof(struct acl_data), report_completed_packet);
 #else
 struct net_buf_pool acl_in_pool;
 #endif
 #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */
 
-struct net_buf *bt_hci_cmd_create(u16_t opcode, u8_t param_len)
-{
-    struct bt_hci_cmd_hdr *hdr;
-    struct net_buf *buf;
+struct net_buf *bt_hci_cmd_create(u16_t opcode, u8_t param_len) {
+  struct bt_hci_cmd_hdr *hdr;
+  struct net_buf        *buf;
 
-    BT_DBG("opcode 0x%04x param_len %u", opcode, param_len);
+  BT_DBG("opcode 0x%04x param_len %u", opcode, param_len);
 
-    buf = net_buf_alloc(&hci_cmd_pool, K_FOREVER);
-    __ASSERT_NO_MSG(buf);
+  buf = net_buf_alloc(&hci_cmd_pool, K_FOREVER);
+  __ASSERT_NO_MSG(buf);
 
-    BT_DBG("buf %p", buf);
+  BT_DBG("buf %p", buf);
 
-    net_buf_reserve(buf, BT_BUF_RESERVE);
+  net_buf_reserve(buf, BT_BUF_RESERVE);
 
-    bt_buf_set_type(buf, BT_BUF_CMD);
+  bt_buf_set_type(buf, BT_BUF_CMD);
 
-    cmd(buf)->opcode = opcode;
-    cmd(buf)->sync = NULL;
-    cmd(buf)->state = NULL;
+  cmd(buf)->opcode = opcode;
+  cmd(buf)->sync   = NULL;
+  cmd(buf)->state  = NULL;
 
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->opcode = sys_cpu_to_le16(opcode);
-    hdr->param_len = param_len;
+  hdr            = net_buf_add(buf, sizeof(*hdr));
+  hdr->opcode    = sys_cpu_to_le16(opcode);
+  hdr->param_len = param_len;
 
-    return buf;
+  return buf;
 }
 
-int bt_hci_cmd_send(u16_t opcode, struct net_buf *buf)
-{
+int bt_hci_cmd_send(u16_t opcode, struct net_buf *buf) {
+  if (!buf) {
+    buf = bt_hci_cmd_create(opcode, 0);
     if (!buf) {
-        buf = bt_hci_cmd_create(opcode, 0);
-        if (!buf) {
-            return -ENOBUFS;
-        }
+      return -ENOBUFS;
     }
+  }
 
-    BT_DBG("opcode 0x%04x len %u", opcode, buf->len);
-
-    /* Host Number of Completed Packets can ignore the ncmd value
-	 * and does not generate any cmd complete/status events.
-	 */
-    if (opcode == BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS) {
-        int err;
+  BT_DBG("opcode 0x%04x len %u", opcode, buf->len);
 
-        err = bt_send(buf);
-        if (err) {
-            BT_ERR("Unable to send to driver (err %d)", err);
-            net_buf_unref(buf);
-        }
+  /* Host Number of Completed Packets can ignore the ncmd value
+   * and does not generate any cmd complete/status events.
+   */
+  if (opcode == BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS) {
+    int err;
 
-        return err;
+    err = bt_send(buf);
+    if (err) {
+      BT_ERR("Unable to send to driver (err %d)", err);
+      net_buf_unref(buf);
     }
 
-    net_buf_put(&bt_dev.cmd_tx_queue, buf);
+    return err;
+  }
+
+  net_buf_put(&bt_dev.cmd_tx_queue, buf);
 #if defined(BFLB_BLE)
-    k_sem_give(&g_poll_sem);
+  k_sem_give(&g_poll_sem);
 #endif
-    return 0;
+  return 0;
+}
+
+#if (BFLB_BT_CO_THREAD)
+struct k_thread *bt_get_co_thread(void) { return &co_thread_data; }
+
+static void bt_hci_sync_check(struct net_buf *buf) {
+  static struct k_poll_event events[EV_COUNT] = {
+      [0]            = K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &g_work_queue_main.fifo, BT_EVENT_WORK_QUEUE),
+      [1]            = K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &bt_dev.cmd_tx_queue, BT_EVENT_CMD_TX),
+      [EV_COUNT - 1] = K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &recv_fifo, BT_EVENT_RX_QUEUE),
+  };
+
+  uint32_t time_start = k_uptime_get_32();
+  send_cmd(buf);
+
+  while (1) {
+    int  ev_count, err;
+    u8_t to_process = 0;
+
+    events[0].state            = K_POLL_STATE_NOT_READY;
+    events[1].state            = K_POLL_STATE_NOT_READY;
+    events[EV_COUNT - 1].state = K_POLL_STATE_NOT_READY;
+    ev_count                   = 2;
+
+    if (IS_ENABLED(CONFIG_BT_CONN)) {
+      ev_count += bt_conn_prepare_events(&events[2]);
+    }
+    err = k_poll(events, ev_count, EV_COUNT, K_NO_WAIT, &to_process);
+    BT_ASSERT(err == 0);
+    if (to_process)
+      process_events(events, ev_count, EV_COUNT);
+
+    if ((cmd(buf)->sync_state == BT_CMD_SYNC_TX_DONE) || (k_uptime_get_32() - time_start) >= HCI_CMD_TIMEOUT) {
+      break;
+    }
+  }
 }
+#endif
 
 #if defined(BFLB_HOST_ASSISTANT)
 extern void blhast_bt_reset(void);
-uint16_t hci_cmd_to_cnt = 0;
+uint16_t    hci_cmd_to_cnt = 0;
+#endif
+int bt_hci_cmd_send_sync(u16_t opcode, struct net_buf *buf, struct net_buf **rsp) {
+  struct k_sem sync_sem;
+  int          err;
+#if (BFLB_BT_CO_THREAD)
+  bool is_bt_co_thread = k_is_current_thread(&co_thread_data);
 #endif
-int bt_hci_cmd_send_sync(u16_t opcode, struct net_buf *buf,
-                         struct net_buf **rsp)
-{
-    struct k_sem sync_sem;
-    int err;
 
+  if (!buf) {
+    buf = bt_hci_cmd_create(opcode, 0);
     if (!buf) {
-        buf = bt_hci_cmd_create(opcode, 0);
-        if (!buf) {
-            return -ENOBUFS;
-        }
+      return -ENOBUFS;
     }
+  }
 
-    BT_DBG("buf %p opcode 0x%04x len %u", buf, opcode, buf->len);
+  BT_DBG("buf %p opcode 0x%04x len %u", buf, opcode, buf->len);
 
+#if (BFLB_BT_CO_THREAD)
+  if (is_bt_co_thread) {
+    cmd(buf)->sync_state = BT_CMD_SYNC_TX;
+    cmd(buf)->sync       = NULL;
+  } else {
     k_sem_init(&sync_sem, 0, 1);
-    cmd(buf)->sync = &sync_sem;
+    cmd(buf)->sync       = &sync_sem;
+    cmd(buf)->sync_state = BT_CMD_SYNC_NONE;
+  }
+#else
+  k_sem_init(&sync_sem, 0, 1);
+  cmd(buf)->sync = &sync_sem;
+#endif
 
 #if defined(BFLB_BLE)
-    /*Assign a initial value to status in order to check if hci cmd timeout*/
-    cmd(buf)->status = 0xff;
+  /*Assign a initial value to status in order to check if hci cmd timeout*/
+  cmd(buf)->status = 0xff;
 #endif
 
-    /* Make sure the buffer stays around until the command completes */
-    net_buf_ref(buf);
+  /* Make sure the buffer stays around until the command completes */
+  net_buf_ref(buf);
 
+#if (BFLB_BT_CO_THREAD)
+  if (is_bt_co_thread)
+    bt_hci_sync_check(buf);
+  else {
     net_buf_put(&bt_dev.cmd_tx_queue, buf);
 #if defined(BFLB_BLE)
     k_sem_give(&g_poll_sem);
@@ -433,2733 +500,2639 @@ int bt_hci_cmd_send_sync(u16_t opcode, struct net_buf *buf,
     k_sem_delete(&sync_sem);
 #endif
     __ASSERT(err == 0, "k_sem_take failed with err %d", err);
+  }
+#else
+  net_buf_put(&bt_dev.cmd_tx_queue, buf);
+#if defined(BFLB_BLE)
+  k_sem_give(&g_poll_sem);
+#endif
+  err = k_sem_take(&sync_sem, HCI_CMD_TIMEOUT);
+#ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS
+  k_sem_delete(&sync_sem);
+#endif
+  __ASSERT(err == 0, "k_sem_take failed with err %d", err);
+#endif // #if (BFLB_BT_CO_THREAD)
 
-    BT_DBG("opcode 0x%04x status 0x%02x", opcode, cmd(buf)->status);
+  BT_DBG("opcode 0x%04x status 0x%02x", opcode, cmd(buf)->status);
 
-    if (cmd(buf)->status) {
-        switch (cmd(buf)->status) {
-            case BT_HCI_ERR_CONN_LIMIT_EXCEEDED:
-                err = -ECONNREFUSED;
-                break;
+  if (cmd(buf)->status) {
+    switch (cmd(buf)->status) {
+    case BT_HCI_ERR_CONN_LIMIT_EXCEEDED:
+      err = -ECONNREFUSED;
+      break;
 #if defined(BFLB_BLE)
-            case 0xff:
-                err = -ETIME;
-                BT_ERR("k_sem_take timeout with opcode 0x%04x", opcode);
+    case 0xff:
+      err = -ETIME;
+      BT_ERR("k_sem_take timeout with opcode 0x%04x", opcode);
 #if (defined(BL602) || defined(BL702)) && defined(BFLB_HOST_ASSISTANT)
-                BT_ERR("Restart and restore bt");
-                hci_cmd_to_cnt++;
-                if (cmd(buf)->state) {
-                    struct cmd_state_set *update = cmd(buf)->state;
-                    atomic_set_bit_to(update->target, update->bit, update->val);
-                }
-                blhast_bt_reset();
+      BT_ERR("Restart and restore bt");
+      hci_cmd_to_cnt++;
+      if (cmd(buf)->state) {
+        struct cmd_state_set *update = cmd(buf)->state;
+        atomic_set_bit_to(update->target, update->bit, update->val);
+      }
+      blhast_bt_reset();
 #else
-                BT_ASSERT(err == 0);
+      BT_ASSERT(err == 0);
 #endif
-                break;
+      break;
 #endif
-            default:
-                err = -EIO;
-                break;
-        }
+    default:
+      err = -EIO;
+      break;
+    }
 
-        net_buf_unref(buf);
+    net_buf_unref(buf);
+  } else {
+    err = 0;
+    if (rsp) {
+      *rsp = buf;
     } else {
-        err = 0;
-        if (rsp) {
-            *rsp = buf;
-        } else {
-            net_buf_unref(buf);
-        }
+      net_buf_unref(buf);
     }
+  }
 
-    return err;
+  return err;
 }
 
 #if defined(CONFIG_BT_OBSERVER) || defined(CONFIG_BT_CONN)
-const bt_addr_le_t *bt_lookup_id_addr(u8_t id, const bt_addr_le_t *addr)
-{
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        struct bt_keys *keys;
-
-        keys = bt_keys_find_irk(id, addr);
-        if (keys) {
-            BT_DBG("Identity %s matched RPA %s",
-                   bt_addr_le_str(&keys->addr),
-                   bt_addr_le_str(addr));
-            return &keys->addr;
-        }
+const bt_addr_le_t *bt_lookup_id_addr(u8_t id, const bt_addr_le_t *addr) {
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    struct bt_keys *keys;
+
+    keys = bt_keys_find_irk(id, addr);
+    if (keys) {
+      BT_DBG("Identity %s matched RPA %s", bt_addr_le_str(&keys->addr), bt_addr_le_str(addr));
+      return &keys->addr;
     }
+  }
 
-    return addr;
+  return addr;
 }
 #endif /* CONFIG_BT_OBSERVER || CONFIG_BT_CONN */
 
-static int set_advertise_enable(bool enable)
-{
-    struct net_buf *buf;
-    struct cmd_state_set state;
-    int err;
+static int set_advertise_enable(bool enable) {
+  struct net_buf      *buf;
+  struct cmd_state_set state;
+  int                  err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_ENABLE, 1);
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_ENABLE, 1);
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    if (enable) {
-        net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE);
-    } else {
-        net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE);
-    }
+  if (enable) {
+    net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE);
+  } else {
+    net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE);
+  }
 
-    cmd_state_set_init(&state, bt_dev.flags, BT_DEV_ADVERTISING, enable);
-    cmd(buf)->state = &state;
+  cmd_state_set_init(&state, bt_dev.flags, BT_DEV_ADVERTISING, enable);
+  cmd(buf)->state = &state;
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-static int set_random_address(const bt_addr_t *addr)
-{
-    struct net_buf *buf;
-    int err;
+static int set_random_address(const bt_addr_t *addr) {
+  struct net_buf *buf;
+  int             err;
 
 #if defined(CONFIG_BT_STACK_PTS)
-    BT_PTS("set random address %s", bt_addr_str(addr));
+  BT_PTS("set random address %s", bt_addr_str(addr));
 #else
-    BT_DBG("%s", bt_addr_str(addr));
+  BT_DBG("%s", bt_addr_str(addr));
 #endif
 
-    /* Do nothing if we already have the right address */
-    if (!bt_addr_cmp(addr, &bt_dev.random_addr.a)) {
-        return 0;
-    }
+  /* Do nothing if we already have the right address */
+  if (!bt_addr_cmp(addr, &bt_dev.random_addr.a)) {
+    return 0;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, sizeof(*addr));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, sizeof(*addr));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_mem(buf, addr, sizeof(*addr));
+  net_buf_add_mem(buf, addr, sizeof(*addr));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    bt_addr_copy(&bt_dev.random_addr.a, addr);
-    bt_dev.random_addr.type = BT_ADDR_LE_RANDOM;
+  bt_addr_copy(&bt_dev.random_addr.a, addr);
+  bt_dev.random_addr.type = BT_ADDR_LE_RANDOM;
 
-    return 0;
+  return 0;
 }
 
-int bt_addr_from_str(const char *str, bt_addr_t *addr)
-{
-    int i, j;
-    u8_t tmp;
-
-    if (strlen(str) != 17U) {
-        return -EINVAL;
-    }
+int bt_addr_from_str(const char *str, bt_addr_t *addr) {
+  int  i, j;
+  u8_t tmp;
 
-    for (i = 5, j = 1; *str != '\0'; str++, j++) {
-        if (!(j % 3) && (*str != ':')) {
-            return -EINVAL;
-        } else if (*str == ':') {
-            i--;
-            continue;
-        }
+  if (strlen(str) != 17U) {
+    return -EINVAL;
+  }
 
-        addr->val[i] = addr->val[i] << 4;
+  for (i = 5, j = 1; *str != '\0'; str++, j++) {
+    if (!(j % 3) && (*str != ':')) {
+      return -EINVAL;
+    } else if (*str == ':') {
+      i--;
+      continue;
+    }
 
-        if (char2hex(*str, &tmp) < 0) {
-            return -EINVAL;
-        }
+    addr->val[i] = addr->val[i] << 4;
 
-        addr->val[i] |= tmp;
+    if (char2hex(*str, &tmp) < 0) {
+      return -EINVAL;
     }
 
-    return 0;
+    addr->val[i] |= tmp;
+  }
+
+  return 0;
 }
 
-int bt_addr_le_from_str(const char *str, const char *type, bt_addr_le_t *addr)
-{
-    int err;
+int bt_addr_le_from_str(const char *str, const char *type, bt_addr_le_t *addr) {
+  int err;
 
-    err = bt_addr_from_str(str, &addr->a);
-    if (err < 0) {
-        return err;
-    }
+  err = bt_addr_from_str(str, &addr->a);
+  if (err < 0) {
+    return err;
+  }
 
-    if (!strcmp(type, "public") || !strcmp(type, "(public)")) {
-        addr->type = BT_ADDR_LE_PUBLIC;
-    } else if (!strcmp(type, "random") || !strcmp(type, "(random)")) {
-        addr->type = BT_ADDR_LE_RANDOM;
-    } else if (!strcmp(type, "public-id") || !strcmp(type, "(public-id)")) {
-        addr->type = BT_ADDR_LE_PUBLIC_ID;
-    } else if (!strcmp(type, "random-id") || !strcmp(type, "(random-id)")) {
-        addr->type = BT_ADDR_LE_RANDOM_ID;
-    } else {
-        return -EINVAL;
-    }
+  if (!strcmp(type, "public") || !strcmp(type, "(public)")) {
+    addr->type = BT_ADDR_LE_PUBLIC;
+  } else if (!strcmp(type, "random") || !strcmp(type, "(random)")) {
+    addr->type = BT_ADDR_LE_RANDOM;
+  } else if (!strcmp(type, "public-id") || !strcmp(type, "(public-id)")) {
+    addr->type = BT_ADDR_LE_PUBLIC_ID;
+  } else if (!strcmp(type, "random-id") || !strcmp(type, "(random-id)")) {
+    addr->type = BT_ADDR_LE_RANDOM_ID;
+  } else {
+    return -EINVAL;
+  }
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_PRIVACY)
 /* this function sets new RPA only if current one is no longer valid */
-static int le_set_private_addr(u8_t id)
-{
-    bt_addr_t rpa;
-    int err;
+static int le_set_private_addr(u8_t id) {
+  bt_addr_t rpa;
+  int       err;
 
-    /* check if RPA is valid */
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_RPA_VALID)) {
-        return 0;
-    }
+  /* check if RPA is valid */
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_RPA_VALID)) {
+    return 0;
+  }
 
-    err = bt_rpa_create(bt_dev.irk[id], &rpa);
+  err = bt_rpa_create(bt_dev.irk[id], &rpa);
+  if (!err) {
+    err = set_random_address(&rpa);
     if (!err) {
-        err = set_random_address(&rpa);
-        if (!err) {
-            atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID);
-        }
+      atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID);
     }
+  }
 
-    /* restart timer even if failed to set new RPA */
-    k_delayed_work_submit(&bt_dev.rpa_update, RPA_TIMEOUT);
+  /* restart timer even if failed to set new RPA */
+  k_delayed_work_submit(&bt_dev.rpa_update, RPA_TIMEOUT);
 
-    return err;
+  return err;
 }
 
-static void rpa_timeout(struct k_work *work)
-{
-    int err_adv = 0, err_scan = 0;
+static void rpa_timeout(struct k_work *work) {
+  int err_adv = 0, err_scan = 0;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    /* Invalidate RPA */
-    atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  /* Invalidate RPA */
+  atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
 
-    /*
-	 * we need to update rpa only if advertising is ongoing, with
-	 * BT_DEV_KEEP_ADVERTISING flag is handled in disconnected event
-	 */
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        /* make sure new address is used */
-        set_advertise_enable(false);
-        err_adv = le_set_private_addr(bt_dev.adv_id);
-        set_advertise_enable(true);
-    }
+  /*
+   * we need to update rpa only if advertising is ongoing, with
+   * BT_DEV_KEEP_ADVERTISING flag is handled in disconnected event
+   */
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    /* make sure new address is used */
+    set_advertise_enable(false);
+    err_adv = le_set_private_addr(bt_dev.adv_id);
+    set_advertise_enable(true);
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) {
-        /* TODO do we need to toggle scan? */
-        err_scan = le_set_private_addr(BT_ID_DEFAULT);
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) {
+    /* TODO do we need to toggle scan? */
+    err_scan = le_set_private_addr(BT_ID_DEFAULT);
+  }
 
-    /* If both advertising and scanning is active, le_set_private_addr
-	 * will fail. In this case, set back RPA_VALID so that if either of
-	 * advertising or scanning was restarted by application then
-	 * le_set_private_addr in the public API call path will not retry
-	 * set_random_address. This is needed so as to be able to stop and
-	 * restart either of the role by the application after rpa_timeout.
-	 */
-    if (err_adv || err_scan) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID);
-    }
+  /* If both advertising and scanning is active, le_set_private_addr
+   * will fail. In this case, set back RPA_VALID so that if either of
+   * advertising or scanning was restarted by application then
+   * le_set_private_addr in the public API call path will not retry
+   * set_random_address. This is needed so as to be able to stop and
+   * restart either of the role by the application after rpa_timeout.
+   */
+  if (err_adv || err_scan) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  }
 }
 
 #if defined(CONFIG_BT_STACK_PTS) || defined(CONFIG_AUTO_PTS)
-static int le_set_non_resolv_private_addr(u8_t id)
-{
-    bt_addr_t nrpa;
-    int err;
+static int le_set_non_resolv_private_addr(u8_t id) {
+  bt_addr_t nrpa;
+  int       err;
 
-    err = bt_rand(nrpa.val, sizeof(nrpa.val));
-    if (err) {
-        return err;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SETTED_NON_RESOLV_ADDR)) {
+    return 0;
+  }
 
-    nrpa.val[5] &= 0x3f;
-    atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
-    return set_random_address(&nrpa);
+  err = bt_rand(nrpa.val, sizeof(nrpa.val));
+  if (err) {
+    return err;
+  }
+
+  nrpa.val[5] &= 0x3f;
+  atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  return set_random_address(&nrpa);
 }
 
+int le_set_non_resolv_private_addr_ext(u8_t id, bt_addr_t *addr) {
+  bt_addr_t *nrpa = addr;
+  int        err;
+
+  err = bt_rand(nrpa->val, sizeof(nrpa->val));
+  if (err) {
+    return err;
+  }
+
+  nrpa->val[5] &= 0x3f;
+  atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  return set_random_address(nrpa);
+}
 #endif
 
 #else
-static int le_set_private_addr(u8_t id)
-{
-    bt_addr_t nrpa;
-    int err;
+static int le_set_private_addr(u8_t id) {
+  bt_addr_t nrpa;
+  int       err;
 
-    err = bt_rand(nrpa.val, sizeof(nrpa.val));
-    if (err) {
-        return err;
-    }
+  err = bt_rand(nrpa.val, sizeof(nrpa.val));
+  if (err) {
+    return err;
+  }
 
-    nrpa.val[5] &= 0x3f;
+  nrpa.val[5] &= 0x3f;
 
-    return set_random_address(&nrpa);
+  return set_random_address(&nrpa);
 }
 #endif
 
 #if defined(CONFIG_BT_OBSERVER)
-static int set_le_scan_enable(u8_t enable)
-{
-    struct bt_hci_cp_le_set_scan_enable *cp;
-    struct net_buf *buf;
-    struct cmd_state_set state;
-    int err;
+static int set_le_scan_enable(u8_t enable) {
+  struct bt_hci_cp_le_set_scan_enable *cp;
+  struct net_buf                      *buf;
+  struct cmd_state_set                 state;
+  int                                  err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_ENABLE, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_ENABLE, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    if (enable == BT_HCI_LE_SCAN_ENABLE) {
-        cp->filter_dup = atomic_test_bit(bt_dev.flags,
-                                         BT_DEV_SCAN_FILTER_DUP);
-    } else {
-        cp->filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE;
-    }
+  if (enable == BT_HCI_LE_SCAN_ENABLE) {
+    cp->filter_dup = atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP);
+  } else {
+    cp->filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE;
+  }
 
-    cp->enable = enable;
+  cp->enable = enable;
 
-    cmd_state_set_init(&state, bt_dev.flags, BT_DEV_SCANNING,
-                       enable == BT_HCI_LE_SCAN_ENABLE);
-    cmd(buf)->state = &state;
+  cmd_state_set_init(&state, bt_dev.flags, BT_DEV_SCANNING, enable == BT_HCI_LE_SCAN_ENABLE);
+  cmd(buf)->state = &state;
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_ENABLE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_ENABLE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_OBSERVER */
 
 #if defined(CONFIG_BT_CONN)
-static void hci_acl(struct net_buf *buf)
-{
-    struct bt_hci_acl_hdr *hdr;
-    u16_t handle, len;
-    struct bt_conn *conn;
-    u8_t flags;
+static void hci_acl(struct net_buf *buf) {
+  struct bt_hci_acl_hdr *hdr;
+  u16_t                  handle, len;
+  struct bt_conn        *conn;
+  u8_t                   flags;
 
-    BT_DBG("buf %p", buf);
+  BT_DBG("buf %p", buf);
 
-    BT_ASSERT(buf->len >= sizeof(*hdr));
+  BT_ASSERT(buf->len >= sizeof(*hdr));
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    len = sys_le16_to_cpu(hdr->len);
-    handle = sys_le16_to_cpu(hdr->handle);
-    flags = bt_acl_flags(handle);
+  hdr    = net_buf_pull_mem(buf, sizeof(*hdr));
+  len    = sys_le16_to_cpu(hdr->len);
+  handle = sys_le16_to_cpu(hdr->handle);
+  flags  = bt_acl_flags(handle);
 
-    acl(buf)->handle = bt_acl_handle(handle);
-    acl(buf)->id = BT_CONN_ID_INVALID;
+  acl(buf)->handle = bt_acl_handle(handle);
+  acl(buf)->id     = BT_CONN_ID_INVALID;
 
-    BT_DBG("handle %u len %u flags %u", acl(buf)->handle, len, flags);
+  BT_DBG("handle %u len %u flags %u", acl(buf)->handle, len, flags);
 
-    if (buf->len != len) {
-        BT_ERR("ACL data length mismatch (%u != %u)", buf->len, len);
-        net_buf_unref(buf);
-        return;
-    }
+  if (buf->len != len) {
+    BT_ERR("ACL data length mismatch (%u != %u)", buf->len, len);
+    net_buf_unref(buf);
+    return;
+  }
 
-    conn = bt_conn_lookup_handle(acl(buf)->handle);
-    if (!conn) {
-        BT_ERR("Unable to find conn for handle %u", acl(buf)->handle);
-        net_buf_unref(buf);
-        return;
-    }
+  conn = bt_conn_lookup_handle(acl(buf)->handle);
+  if (!conn) {
+    BT_ERR("Unable to find conn for handle %u", acl(buf)->handle);
+    net_buf_unref(buf);
+    return;
+  }
 
-    acl(buf)->id = bt_conn_index(conn);
+  acl(buf)->id = bt_conn_index(conn);
 
-    bt_conn_recv(conn, buf, flags);
-    bt_conn_unref(conn);
+  bt_conn_recv(conn, buf, flags);
+  bt_conn_unref(conn);
 }
 
-static void hci_data_buf_overflow(struct net_buf *buf)
-{
-    struct bt_hci_evt_data_buf_overflow *evt = (void *)buf->data;
+static void hci_data_buf_overflow(struct net_buf *buf) {
+  struct bt_hci_evt_data_buf_overflow *evt = (void *)buf->data;
 
-    BT_WARN("Data buffer overflow (link type 0x%02x)", evt->link_type);
-    // avoid compiler warning if BT_WARN is empty
-    (void)evt;
+  BT_WARN("Data buffer overflow (link type 0x%02x)", evt->link_type);
+  // avoid compiler warning if BT_WARN is empty
+  (void)evt;
 }
 
-static void hci_num_completed_packets(struct net_buf *buf)
-{
-    struct bt_hci_evt_num_completed_packets *evt = (void *)buf->data;
-    int i;
+static void hci_num_completed_packets(struct net_buf *buf) {
+  struct bt_hci_evt_num_completed_packets *evt = (void *)buf->data;
+  int                                      i;
 
-    BT_DBG("num_handles %u", evt->num_handles);
+  BT_DBG("num_handles %u", evt->num_handles);
 
-    for (i = 0; i < evt->num_handles; i++) {
-        u16_t handle, count;
-        struct bt_conn *conn;
-        unsigned int key;
+  for (i = 0; i < evt->num_handles; i++) {
+    u16_t           handle, count;
+    struct bt_conn *conn;
+    unsigned int    key;
 
-        handle = sys_le16_to_cpu(evt->h[i].handle);
-        count = sys_le16_to_cpu(evt->h[i].count);
+    handle = sys_le16_to_cpu(evt->h[i].handle);
+    count  = sys_le16_to_cpu(evt->h[i].count);
 
-        BT_DBG("handle %u count %u", handle, count);
+    BT_DBG("handle %u count %u", handle, count);
 
-        key = irq_lock();
+    key = irq_lock();
 
-        conn = bt_conn_lookup_handle(handle);
-        if (!conn) {
-            irq_unlock(key);
-            BT_ERR("No connection for handle %u", handle);
-            continue;
-        }
+    conn = bt_conn_lookup_handle(handle);
+    if (!conn) {
+      irq_unlock(key);
+      BT_ERR("No connection for handle %u", handle);
+      continue;
+    }
 
-        irq_unlock(key);
+    irq_unlock(key);
 
-        while (count--) {
-            struct bt_conn_tx *tx;
-            sys_snode_t *node;
+    while (count--) {
+      struct bt_conn_tx *tx;
+      sys_snode_t       *node;
 
-            key = irq_lock();
+      key = irq_lock();
 
-            if (conn->pending_no_cb) {
-                conn->pending_no_cb--;
-                irq_unlock(key);
-                k_sem_give(bt_conn_get_pkts(conn));
-                continue;
-            }
+      if (conn->pending_no_cb) {
+        conn->pending_no_cb--;
+        irq_unlock(key);
+        k_sem_give(bt_conn_get_pkts(conn));
+        continue;
+      }
 
-            node = sys_slist_get(&conn->tx_pending);
-            irq_unlock(key);
+      node = sys_slist_get(&conn->tx_pending);
+      irq_unlock(key);
 
-            if (!node) {
-                BT_ERR("packets count mismatch");
-                break;
-            }
+      if (!node) {
+        BT_ERR("packets count mismatch");
+        break;
+      }
 
-            tx = CONTAINER_OF(node, struct bt_conn_tx, node);
+      tx = CONTAINER_OF(node, struct bt_conn_tx, node);
 
-            key = irq_lock();
-            conn->pending_no_cb = tx->pending_no_cb;
-            tx->pending_no_cb = 0U;
-            sys_slist_append(&conn->tx_complete, &tx->node);
-            irq_unlock(key);
+      key                 = irq_lock();
+      conn->pending_no_cb = tx->pending_no_cb;
+      tx->pending_no_cb   = 0U;
+      sys_slist_append(&conn->tx_complete, &tx->node);
+      irq_unlock(key);
 
-            k_work_submit(&conn->tx_complete_work);
-            k_sem_give(bt_conn_get_pkts(conn));
+      k_work_submit(&conn->tx_complete_work);
+      k_sem_give(bt_conn_get_pkts(conn));
 #if defined(BFLB_BLE)
-            k_sem_give(&g_poll_sem);
+      k_sem_give(&g_poll_sem);
 #endif
-        }
-
-        bt_conn_unref(conn);
     }
+
+    bt_conn_unref(conn);
+  }
 }
 
 #if defined(CONFIG_BT_CENTRAL)
 #if defined(CONFIG_BT_WHITELIST)
-int bt_le_auto_conn(const struct bt_le_conn_param *conn_param)
-{
-    struct net_buf *buf;
-    struct cmd_state_set state;
-    struct bt_hci_cp_le_create_conn *cp;
-    u8_t own_addr_type;
-    int err;
+int bt_le_auto_conn(const struct bt_le_conn_param *conn_param) {
+  struct net_buf                  *buf;
+  struct cmd_state_set             state;
+  struct bt_hci_cp_le_create_conn *cp;
+  u8_t                             own_addr_type;
+  int                              err;
+
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
+    err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+    if (err) {
+      return err;
+    }
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
-        err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+#if defined(CONFIG_BT_STACK_PTS)
+  if (conn_param->own_address_type != BT_ADDR_LE_PUBLIC) {
+#endif
+
+    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+      err = le_set_private_addr(BT_ID_DEFAULT);
+      if (err) {
+        return err;
+      }
+      if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+        own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+      } else {
+        own_addr_type = BT_ADDR_LE_RANDOM;
+      }
+    } else {
+      const bt_addr_le_t *addr = &bt_dev.id_addr[BT_ID_DEFAULT];
+
+      /* If Static Random address is used as Identity address we
+       * need to restore it before creating connection. Otherwise
+       * NRPA used for active scan could be used for connection.
+       */
+      if (addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&addr->a);
         if (err) {
-            return err;
+          return err;
         }
-    }
+      }
 
-#if defined(CONFIG_BT_STACK_PTS)
-    if (conn_param->own_address_type != BT_ADDR_LE_PUBLIC) {
-#endif
-
-        if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-            err = le_set_private_addr(BT_ID_DEFAULT);
-            if (err) {
-                return err;
-            }
-            if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-                own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-            } else {
-                own_addr_type = BT_ADDR_LE_RANDOM;
-            }
-        } else {
-            const bt_addr_le_t *addr = &bt_dev.id_addr[BT_ID_DEFAULT];
-
-            /* If Static Random address is used as Identity address we
-			 * need to restore it before creating connection. Otherwise
-			 * NRPA used for active scan could be used for connection.
-			 */
-            if (addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&addr->a);
-                if (err) {
-                    return err;
-                }
-            }
-
-            own_addr_type = addr->type;
-        }
+      own_addr_type = addr->type;
+    }
 
 #if defined(CONFIG_BT_STACK_PTS)
-    } else {
-        own_addr_type = conn_param->own_address_type;
-    }
+  } else {
+    own_addr_type = conn_param->own_address_type;
+  }
 #endif
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    (void)memset(cp, 0, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
+  (void)memset(cp, 0, sizeof(*cp));
 
-    cp->filter_policy = BT_HCI_LE_CREATE_CONN_FP_WHITELIST;
-    cp->own_addr_type = own_addr_type;
+  cp->filter_policy = BT_HCI_LE_CREATE_CONN_FP_WHITELIST;
+  cp->own_addr_type = own_addr_type;
 
-    /* User Initiated procedure use fast scan parameters. */
-    cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
-    cp->scan_window = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW);
+  /* User Initiated procedure use fast scan parameters. */
+  cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
+  cp->scan_window   = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW);
 
-    cp->conn_interval_min = sys_cpu_to_le16(conn_param->interval_min);
-    cp->conn_interval_max = sys_cpu_to_le16(conn_param->interval_max);
-    cp->conn_latency = sys_cpu_to_le16(conn_param->latency);
-    cp->supervision_timeout = sys_cpu_to_le16(conn_param->timeout);
+  cp->conn_interval_min   = sys_cpu_to_le16(conn_param->interval_min);
+  cp->conn_interval_max   = sys_cpu_to_le16(conn_param->interval_max);
+  cp->conn_latency        = sys_cpu_to_le16(conn_param->latency);
+  cp->supervision_timeout = sys_cpu_to_le16(conn_param->timeout);
 
-    cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, true);
-    cmd(buf)->state = &state;
+  cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, true);
+  cmd(buf)->state = &state;
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL);
 }
 
-int bt_le_auto_conn_cancel(void)
-{
-    struct net_buf *buf;
-    struct cmd_state_set state;
+int bt_le_auto_conn_cancel(void) {
+  struct net_buf      *buf;
+  struct cmd_state_set state;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN_CANCEL, 0);
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN_CANCEL, 0);
 
-    cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, false);
-    cmd(buf)->state = &state;
+  cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, false);
+  cmd(buf)->state = &state;
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, buf, NULL);
 }
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-static int hci_le_create_conn(const struct bt_conn *conn)
-{
-    struct net_buf *buf;
-    struct bt_hci_cp_le_create_conn *cp;
-    u8_t own_addr_type;
-    const bt_addr_le_t *peer_addr;
-    int err;
+static int hci_le_create_conn(const struct bt_conn *conn) {
+  struct net_buf                  *buf;
+  struct bt_hci_cp_le_create_conn *cp;
+  u8_t                             own_addr_type;
+  const bt_addr_le_t              *peer_addr;
+  int                              err;
 
 #if defined(CONFIG_BT_STACK_PTS)
-    if (conn->le.own_adder_type == BT_ADDR_LE_PUBLIC || conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) {
-        own_addr_type = conn->le.own_adder_type;
-        goto start_connect;
-    }
+  if (conn->le.own_adder_type == BT_ADDR_LE_PUBLIC || conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) {
+    own_addr_type = conn->le.own_adder_type;
+    goto start_connect;
+  }
 
 #endif
 
-    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        err = le_set_private_addr(conn->id);
-        if (err) {
-            return err;
-        }
+  if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    err = le_set_private_addr(conn->id);
+    if (err) {
+      return err;
+    }
 #if defined(BFLB_BLE)
-        /*Use random type at the first time*/
-        own_addr_type = BT_ADDR_LE_RANDOM;
+    /*Use random type at the first time*/
+    own_addr_type = BT_ADDR_LE_RANDOM;
 #if defined(CONFIG_BT_STACK_PTS)
-        if (conn->le.own_adder_type == BT_ADDR_LE_RANDOM_ID) {
-            own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-        }
+    if (conn->le.own_adder_type == BT_ADDR_LE_RANDOM_ID) {
+      own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+    }
 #endif
 #else
-        if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-            own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-        } else {
-            own_addr_type = BT_ADDR_LE_RANDOM;
-        }
-#endif
+    if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
     } else {
-        /* If Static Random address is used as Identity address we
-		 * need to restore it before creating connection. Otherwise
-		 * NRPA used for active scan could be used for connection.
-		 */
-        const bt_addr_le_t *own_addr = &bt_dev.id_addr[conn->id];
-
-        if (own_addr->type == BT_ADDR_LE_RANDOM) {
-            err = set_random_address(&own_addr->a);
-            if (err) {
-                return err;
-            }
-        }
+      own_addr_type = BT_ADDR_LE_RANDOM;
+    }
+#endif
+  } else {
+    /* If Static Random address is used as Identity address we
+     * need to restore it before creating connection. Otherwise
+     * NRPA used for active scan could be used for connection.
+     */
+    const bt_addr_le_t *own_addr = &bt_dev.id_addr[conn->id];
 
-        own_addr_type = own_addr->type;
+    if (own_addr->type == BT_ADDR_LE_RANDOM) {
+      err = set_random_address(&own_addr->a);
+      if (err) {
+        return err;
+      }
     }
 
+    own_addr_type = own_addr->type;
+  }
+
 #if defined(CONFIG_BT_STACK_PTS)
 start_connect:
 #endif
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    (void)memset(cp, 0, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
+  (void)memset(cp, 0, sizeof(*cp));
 
-    /* Interval == window for continuous scanning */
-    cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
-    cp->scan_window = cp->scan_interval;
+  /* Interval == window for continuous scanning */
+  cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
+  cp->scan_window   = cp->scan_interval;
 
-    peer_addr = &conn->le.dst;
+  peer_addr = &conn->le.dst;
 
 #if defined(CONFIG_BT_SMP)
-    if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) {
-        /* Host resolving is used, use the RPA directly. */
-        peer_addr = &conn->le.resp_addr;
-    }
+  if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) {
+    /* Host resolving is used, use the RPA directly. */
+    peer_addr = &conn->le.resp_addr;
+  }
 #endif
 
-    bt_addr_le_copy(&cp->peer_addr, peer_addr);
-    cp->own_addr_type = own_addr_type;
-    cp->conn_interval_min = sys_cpu_to_le16(conn->le.interval_min);
-    cp->conn_interval_max = sys_cpu_to_le16(conn->le.interval_max);
-    cp->conn_latency = sys_cpu_to_le16(conn->le.latency);
-    cp->supervision_timeout = sys_cpu_to_le16(conn->le.timeout);
+  bt_addr_le_copy(&cp->peer_addr, peer_addr);
+  cp->own_addr_type       = own_addr_type;
+  cp->conn_interval_min   = sys_cpu_to_le16(conn->le.interval_min);
+  cp->conn_interval_max   = sys_cpu_to_le16(conn->le.interval_max);
+  cp->conn_latency        = sys_cpu_to_le16(conn->le.latency);
+  cp->supervision_timeout = sys_cpu_to_le16(conn->le.timeout);
 
 #if defined(CONFIG_BT_STACK_PTS)
-    if (event_flag == dir_connect_req) {
-        bt_addr_le_copy(&cp->peer_addr, &pts_addr);
+  if (event_flag == dir_connect_req) {
+    bt_addr_le_copy(&cp->peer_addr, &pts_addr);
 
-        cp->filter_policy = 0;
-        cp->own_addr_type = BT_ADDR_LE_PUBLIC;
+    cp->filter_policy = 0;
+    cp->own_addr_type = BT_ADDR_LE_PUBLIC;
 
-        /* User Initiated procedure use fast scan parameters. */
-        cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
-        cp->scan_window = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW);
-    }
+    /* User Initiated procedure use fast scan parameters. */
+    cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL);
+    cp->scan_window   = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW);
+  }
 #endif
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL);
 }
 #endif /* CONFIG_BT_CENTRAL */
 
-static void hci_disconn_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_disconn_complete *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
+static void hci_disconn_complete(struct net_buf *buf) {
+  struct bt_hci_evt_disconn_complete *evt    = (void *)buf->data;
+  u16_t                               handle = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                     *conn;
 
-    BT_DBG("status 0x%02x handle %u reason 0x%02x", evt->status, handle,
-           evt->reason);
+  BT_DBG("status 0x%02x handle %u reason 0x%02x", evt->status, handle, evt->reason);
 
-    if (evt->status) {
-        return;
-    }
+  if (evt->status) {
+    return;
+  }
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to look up conn with handle %u", handle);
-        goto advertise;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to look up conn with handle %u", handle);
+    goto advertise;
+  }
 
-    conn->err = evt->reason;
+  conn->err = evt->reason;
 
-    /* Check stacks usage */
+  /* Check stacks usage */
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
-    STACK_ANALYZE("rx stack", rx_thread_stack);
+  STACK_ANALYZE("rx stack", rx_thread_stack);
 #endif
 #if !defined(BFLB_BLE)
-    STACK_ANALYZE("tx stack", tx_thread_stack);
+  STACK_ANALYZE("tx stack", tx_thread_stack);
 #endif
 
-    bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-    conn->handle = 0U;
+  bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+  conn->handle = 0U;
 
-    if (conn->type != BT_CONN_TYPE_LE) {
+  if (conn->type != BT_CONN_TYPE_LE) {
 #if defined(CONFIG_BT_BREDR)
-        if (conn->type == BT_CONN_TYPE_SCO) {
-            bt_sco_cleanup(conn);
-            return;
-        }
-        /*
-		 * If only for one connection session bond was set, clear keys
-		 * database row for this connection.
-		 */
-        if (conn->type == BT_CONN_TYPE_BR &&
-            atomic_test_and_clear_bit(conn->flags, BT_CONN_BR_NOBOND)) {
-            bt_keys_link_key_clear(conn->br.link_key);
-        }
-#endif
-        bt_conn_unref(conn);
-        return;
+    if (conn->type == BT_CONN_TYPE_SCO) {
+      bt_sco_cleanup(conn);
+      return;
+    }
+    /*
+     * If only for one connection session bond was set, clear keys
+     * database row for this connection.
+     */
+    if (conn->type == BT_CONN_TYPE_BR && atomic_test_and_clear_bit(conn->flags, BT_CONN_BR_NOBOND)) {
+      bt_keys_link_key_clear(conn->br.link_key);
     }
+#endif
+    bt_conn_unref(conn);
+#if defined(CONFIG_BT_BREDR)
+    notify_disconnected(conn);
+#endif
+    return;
+  }
 
 #if defined(CONFIG_BT_CENTRAL) && !defined(CONFIG_BT_WHITELIST)
-    if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
-        bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
-        bt_le_scan_update(false);
-    }
+  if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
+    bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
+    bt_le_scan_update(false);
+  }
 #endif /* defined(CONFIG_BT_CENTRAL) && !defined(CONFIG_BT_WHITELIST) */
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 
 #if defined(BFLB_BLE_PATCH_CLEAN_UP_CONNECT_REF)
-    atomic_clear(&conn->ref);
+  atomic_clear(&conn->ref);
 #endif
 
 #if defined(BFLB_RELEASE_CMD_SEM_IF_CONN_DISC)
-    hci_release_conn_related_cmd();
+  hci_release_conn_related_cmd();
+#endif
+
+#if defined(BFLB_BLE)
+  notify_disconnected(conn);
 #endif
 
 #if defined(CONFIG_BLE_RECONNECT_TEST)
-    if (conn->role == BT_CONN_ROLE_MASTER) {
-        struct bt_le_conn_param param = {
-            .interval_min = BT_GAP_INIT_CONN_INT_MIN,
-            .interval_max = BT_GAP_INIT_CONN_INT_MAX,
-            .latency = 0,
-            .timeout = 400,
-        };
-
-        if (bt_conn_create_le(&conn->le.dst, ¶m)) {
-            printf("Reconnecting. \n");
-        } else {
-            printf("Reconnect fail. \n");
-        }
+  if (conn->role == BT_CONN_ROLE_MASTER) {
+    struct bt_le_conn_param param = {
+        .interval_min = BT_GAP_INIT_CONN_INT_MIN,
+        .interval_max = BT_GAP_INIT_CONN_INT_MAX,
+        .latency      = 0,
+        .timeout      = 400,
+    };
+
+    if (bt_conn_create_le(&conn->le.dst, ¶m)) {
+      BT_DBG("Reconnecting. \n");
+    } else {
+      BT_DBG("Reconnect fail. \n");
     }
+  }
 #endif
 
 advertise:
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) &&
-        !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-            le_set_private_addr(bt_dev.adv_id);
-        }
-
-        set_advertise_enable(true);
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) && !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+      le_set_private_addr(bt_dev.adv_id);
     }
+
+    set_advertise_enable(true);
+  }
 }
 
-static int hci_le_read_remote_features(struct bt_conn *conn)
-{
-    struct bt_hci_cp_le_read_remote_features *cp;
-    struct net_buf *buf;
+static int hci_le_read_remote_features(struct bt_conn *conn) {
+  struct bt_hci_cp_le_read_remote_features *cp;
+  struct net_buf                           *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_REMOTE_FEATURES,
-                            sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_REMOTE_FEATURES, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
-    bt_hci_cmd_send(BT_HCI_OP_LE_READ_REMOTE_FEATURES, buf);
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(conn->handle);
+  bt_hci_cmd_send(BT_HCI_OP_LE_READ_REMOTE_FEATURES, buf);
 
-    return 0;
+  return 0;
 }
 
 /* LE Data Length Change Event is optional so this function just ignore
  * error and stack will continue to use default values.
  */
-static void hci_le_set_data_len(struct bt_conn *conn)
-{
-    struct bt_hci_rp_le_read_max_data_len *rp;
-    struct bt_hci_cp_le_set_data_len *cp;
-    struct net_buf *buf, *rsp;
-    u16_t tx_octets, tx_time;
-    int err;
-
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, &rsp);
-    if (err) {
-        BT_ERR("Failed to read DLE max data len");
-        return;
-    }
+static void hci_le_set_data_len(struct bt_conn *conn) {
+  struct bt_hci_rp_le_read_max_data_len *rp;
+  struct bt_hci_cp_le_set_data_len      *cp;
+  struct net_buf                        *buf, *rsp;
+  u16_t                                  tx_octets, tx_time;
+  int                                    err;
+
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, &rsp);
+  if (err) {
+    BT_ERR("Failed to read DLE max data len");
+    return;
+  }
 
-    rp = (void *)rsp->data;
-    tx_octets = sys_le16_to_cpu(rp->max_tx_octets);
-    tx_time = sys_le16_to_cpu(rp->max_tx_time);
-    net_buf_unref(rsp);
+  rp        = (void *)rsp->data;
+  tx_octets = sys_le16_to_cpu(rp->max_tx_octets);
+  tx_time   = sys_le16_to_cpu(rp->max_tx_time);
+  net_buf_unref(rsp);
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Failed to create LE Set Data Length Command");
-        return;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Failed to create LE Set Data Length Command");
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
-    cp->tx_octets = sys_cpu_to_le16(tx_octets);
-    cp->tx_time = sys_cpu_to_le16(tx_time);
-    err = bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf);
-    if (err) {
-        BT_ERR("Failed to send LE Set Data Length Command");
-    }
+  cp            = net_buf_add(buf, sizeof(*cp));
+  cp->handle    = sys_cpu_to_le16(conn->handle);
+  cp->tx_octets = sys_cpu_to_le16(tx_octets);
+  cp->tx_time   = sys_cpu_to_le16(tx_time);
+  err           = bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf);
+  if (err) {
+    BT_ERR("Failed to send LE Set Data Length Command");
+  }
 }
 
-int bt_le_set_data_len(struct bt_conn *conn, u16_t tx_octets, u16_t tx_time)
-{
-    struct bt_hci_cp_le_set_data_len *cp;
-    struct net_buf *buf;
+int bt_le_set_data_len(struct bt_conn *conn, u16_t tx_octets, u16_t tx_time) {
+  struct bt_hci_cp_le_set_data_len *cp;
+  struct net_buf                   *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp));
-    if (!buf) {
-        BT_ERR("bt_le_set_data_len, Failed to create LE Set Data Length Command");
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("bt_le_set_data_len, Failed to create LE Set Data Length Command");
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
-    cp->tx_octets = sys_cpu_to_le16(tx_octets);
-    cp->tx_time = sys_cpu_to_le16(tx_time);
+  cp            = net_buf_add(buf, sizeof(*cp));
+  cp->handle    = sys_cpu_to_le16(conn->handle);
+  cp->tx_octets = sys_cpu_to_le16(tx_octets);
+  cp->tx_time   = sys_cpu_to_le16(tx_time);
 
-    return bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf);
+  return bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf);
 }
 
-int hci_le_set_phy(struct bt_conn *conn)
-{
-    struct bt_hci_cp_le_set_phy *cp;
-    struct net_buf *buf;
+int hci_le_set_phy(struct bt_conn *conn, uint8_t all_phys, uint8_t pref_tx_phy, uint8_t pref_rx_phy, uint8_t phy_opts) {
+  struct bt_hci_cp_le_set_phy *cp;
+  struct net_buf              *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PHY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PHY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
-    cp->all_phys = 0U;
-    cp->tx_phys = BT_HCI_LE_PHY_PREFER_2M;
-    cp->rx_phys = BT_HCI_LE_PHY_PREFER_2M;
-    cp->phy_opts = BT_HCI_LE_PHY_CODED_ANY;
-    bt_hci_cmd_send(BT_HCI_OP_LE_SET_PHY, buf);
+  cp           = net_buf_add(buf, sizeof(*cp));
+  cp->handle   = sys_cpu_to_le16(conn->handle);
+  cp->all_phys = all_phys;
+  cp->tx_phys  = pref_tx_phy;
+  cp->rx_phys  = pref_rx_phy;
+  cp->phy_opts = phy_opts;
 
-    return 0;
+  return bt_hci_cmd_send(BT_HCI_OP_LE_SET_PHY, buf);
 }
 
-int hci_le_set_default_phy(struct bt_conn *conn, u8_t default_phy)
-{
-    struct bt_hci_cp_le_set_default_phy *cp;
-    struct net_buf *buf;
+int hci_le_set_default_phy(u8_t default_phy) {
+  struct bt_hci_cp_le_set_default_phy *cp;
+  struct net_buf                      *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DEFAULT_PHY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DEFAULT_PHY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->all_phys = 0U;
-    cp->tx_phys = default_phy;
-    cp->rx_phys = default_phy;
-    bt_hci_cmd_send(BT_HCI_OP_LE_SET_DEFAULT_PHY, buf);
+  cp           = net_buf_add(buf, sizeof(*cp));
+  cp->all_phys = 0U;
+  cp->tx_phys  = default_phy;
+  cp->rx_phys  = default_phy;
+  bt_hci_cmd_send(BT_HCI_OP_LE_SET_DEFAULT_PHY, buf);
 
-    return 0;
+  return 0;
 }
 
-static void slave_update_conn_param(struct bt_conn *conn)
-{
-    if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
-        return;
-    }
+static void slave_update_conn_param(struct bt_conn *conn) {
+  if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
+    return;
+  }
 
-    /* don't start timer again on PHY update etc */
-    if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) {
-        return;
-    }
+  /* don't start timer again on PHY update etc */
+  if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) {
+    return;
+  }
 
-    /*
-	 * Core 4.2 Vol 3, Part C, 9.3.12.2
-	 * The Peripheral device should not perform a Connection Parameter
-	 * Update procedure within 5 s after establishing a connection.
-	 */
-    k_delayed_work_submit(&conn->update_work, CONN_UPDATE_TIMEOUT);
+  /*
+   * Core 4.2 Vol 3, Part C, 9.3.12.2
+   * The Peripheral device should not perform a Connection Parameter
+   * Update procedure within 5 s after establishing a connection.
+   */
+  k_delayed_work_submit(&conn->update_work, CONN_UPDATE_TIMEOUT);
 }
 
 #if defined(CONFIG_BT_SMP)
-static void update_pending_id(struct bt_keys *keys, void *data)
-{
-    if (keys->flags & BT_KEYS_ID_PENDING_ADD) {
-        keys->flags &= ~BT_KEYS_ID_PENDING_ADD;
-        bt_id_add(keys);
-        return;
-    }
+static void update_pending_id(struct bt_keys *keys, void *data) {
+  if (keys->flags & BT_KEYS_ID_PENDING_ADD) {
+    keys->flags &= ~BT_KEYS_ID_PENDING_ADD;
+    bt_id_add(keys);
+    return;
+  }
 
-    if (keys->flags & BT_KEYS_ID_PENDING_DEL) {
-        keys->flags &= ~BT_KEYS_ID_PENDING_DEL;
-        bt_id_del(keys);
-        return;
-    }
+  if (keys->flags & BT_KEYS_ID_PENDING_DEL) {
+    keys->flags &= ~BT_KEYS_ID_PENDING_DEL;
+    bt_id_del(keys);
+    return;
+  }
 }
 #endif
 
-static struct bt_conn *find_pending_connect(bt_addr_le_t *peer_addr)
-{
-    struct bt_conn *conn;
+static struct bt_conn *find_pending_connect(bt_addr_le_t *peer_addr) {
+  struct bt_conn *conn;
 
-    /*
-	 * Make lookup to check if there's a connection object in
-	 * CONNECT or DIR_ADV state associated with passed peer LE address.
-	 */
-    conn = bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT);
-    if (conn) {
-        return conn;
-    }
+  /*
+   * Make lookup to check if there's a connection object in
+   * CONNECT or DIR_ADV state associated with passed peer LE address.
+   */
+  conn = bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT);
+  if (conn) {
+    return conn;
+  }
 
-    return bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT_DIR_ADV);
+  return bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT_DIR_ADV);
 }
 
-static void enh_conn_complete(struct bt_hci_evt_le_enh_conn_complete *evt)
-{
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    bt_addr_le_t peer_addr, id_addr;
-    struct bt_conn *conn;
-    int err;
+static void enh_conn_complete(struct bt_hci_evt_le_enh_conn_complete *evt) {
+  u16_t           handle = sys_le16_to_cpu(evt->handle);
+  bt_addr_le_t    peer_addr, id_addr;
+  struct bt_conn *conn;
+  int             err;
 
-    BT_DBG("status 0x%02x handle %u role %u %s", evt->status, handle,
-           evt->role, bt_addr_le_str(&evt->peer_addr));
+  BT_DBG("status 0x%02x handle %u role %u %s", evt->status, handle, evt->role, bt_addr_le_str(&evt->peer_addr));
 
 #if defined(CONFIG_BT_SMP)
-    if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ID_PENDING)) {
-        bt_keys_foreach(BT_KEYS_IRK, update_pending_id, NULL);
-    }
-#endif
-
-    if (evt->status) {
-        /*
-		 * If there was an error we are only interested in pending
-		 * connection. There is no need to check ID address as
-		 * only one connection can be in that state.
-		 *
-		 * Depending on error code address might not be valid anyway.
-		 */
-        conn = find_pending_connect(NULL);
-        if (!conn) {
-            return;
-        }
+  if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ID_PENDING)) {
+    bt_keys_foreach(BT_KEYS_IRK, update_pending_id, NULL);
+  }
+#endif
+
+  if (evt->status) {
+    /*
+     * If there was an error we are only interested in pending
+     * connection. There is no need to check ID address as
+     * only one connection can be in that state.
+     *
+     * Depending on error code address might not be valid anyway.
+     */
+    conn = find_pending_connect(NULL);
+    if (!conn) {
+      return;
+    }
 
-        conn->err = evt->status;
+    conn->err = evt->status;
 
-        if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
-            /*
-			 * Handle advertising timeout after high duty directed
-			 * advertising.
-			 */
-            if (conn->err == BT_HCI_ERR_ADV_TIMEOUT) {
-                atomic_clear_bit(bt_dev.flags,
-                                 BT_DEV_ADVERTISING);
-                bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+    if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) {
+      /*
+       * Handle advertising timeout after high duty directed
+       * advertising.
+       */
+      if (conn->err == BT_HCI_ERR_ADV_TIMEOUT) {
+        atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING);
+        bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
 
-                goto done;
-            }
-        }
+        goto done;
+      }
+    }
 
-        if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-            /*
-			 * Handle cancellation of outgoing connection attempt.
-			 */
-            if (conn->err == BT_HCI_ERR_UNKNOWN_CONN_ID) {
-                /* We notify before checking autoconnect flag
-				 * as application may choose to change it from
-				 * callback.
-				 */
-                bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+      /*
+       * Handle cancellation of outgoing connection attempt.
+       */
+      if (conn->err == BT_HCI_ERR_UNKNOWN_CONN_ID) {
+        /* We notify before checking autoconnect flag
+         * as application may choose to change it from
+         * callback.
+         */
+        bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
 
 #if !defined(CONFIG_BT_WHITELIST)
-                /* Check if device is marked for autoconnect. */
-                if (atomic_test_bit(conn->flags,
-                                    BT_CONN_AUTO_CONNECT)) {
-                    bt_conn_set_state(conn,
-                                      BT_CONN_CONNECT_SCAN);
-                }
-#endif /* !defined(CONFIG_BT_WHITELIST) */
-                goto done;
-            }
+        /* Check if device is marked for autoconnect. */
+        if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
+          bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
         }
+#endif /* !defined(CONFIG_BT_WHITELIST) */
+        goto done;
+      }
+    }
 
-        BT_WARN("Unexpected status 0x%02x", evt->status);
-
-        bt_conn_unref(conn);
+    BT_WARN("Unexpected status 0x%02x", evt->status);
 
-        return;
-    }
+    bt_conn_unref(conn);
 
-    bt_addr_le_copy(&id_addr, &evt->peer_addr);
+    return;
+  }
 
-    /* Translate "enhanced" identity address type to normal one */
-    if (id_addr.type == BT_ADDR_LE_PUBLIC_ID ||
-        id_addr.type == BT_ADDR_LE_RANDOM_ID) {
-        id_addr.type -= BT_ADDR_LE_PUBLIC_ID;
-        bt_addr_copy(&peer_addr.a, &evt->peer_rpa);
-        peer_addr.type = BT_ADDR_LE_RANDOM;
-    } else {
-        bt_addr_le_copy(&peer_addr, &evt->peer_addr);
-    }
+  bt_addr_le_copy(&id_addr, &evt->peer_addr);
 
-    conn = find_pending_connect(&id_addr);
+  /* Translate "enhanced" identity address type to normal one */
+  if (id_addr.type == BT_ADDR_LE_PUBLIC_ID || id_addr.type == BT_ADDR_LE_RANDOM_ID) {
+    id_addr.type -= BT_ADDR_LE_PUBLIC_ID;
+    bt_addr_copy(&peer_addr.a, &evt->peer_rpa);
+    peer_addr.type = BT_ADDR_LE_RANDOM;
+  } else {
+    bt_addr_le_copy(&peer_addr, &evt->peer_addr);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
-        evt->role == BT_HCI_ROLE_SLAVE) {
-        /*
-		 * clear advertising even if we are not able to add connection
-		 * object to keep host in sync with controller state
-		 */
-        atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING);
+  conn = find_pending_connect(&id_addr);
 
-        /* for slave we may need to add new connection */
-        if (!conn) {
-            conn = bt_conn_add_le(bt_dev.adv_id, &id_addr);
-        }
-    }
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && evt->role == BT_HCI_ROLE_SLAVE) {
+    /*
+     * clear advertising even if we are not able to add connection
+     * object to keep host in sync with controller state
+     */
+    atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING);
 
-    if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-        IS_ENABLED(CONFIG_BT_WHITELIST) &&
-        evt->role == BT_HCI_ROLE_MASTER) {
-        /* for whitelist initiator me may need to add new connection. */
-        if (!conn) {
-            conn = bt_conn_add_le(BT_ID_DEFAULT, &id_addr);
-        }
+    /* for slave we may need to add new connection */
+    if (!conn) {
+      conn = bt_conn_add_le(bt_dev.adv_id, &id_addr);
     }
+  }
 
+  if (IS_ENABLED(CONFIG_BT_CENTRAL) && IS_ENABLED(CONFIG_BT_WHITELIST) && evt->role == BT_HCI_ROLE_MASTER) {
+    /* for whitelist initiator me may need to add new connection. */
     if (!conn) {
-        BT_ERR("Unable to add new conn for handle %u", handle);
-        return;
+      conn = bt_conn_add_le(BT_ID_DEFAULT, &id_addr);
     }
+  }
 
-    conn->handle = handle;
-    bt_addr_le_copy(&conn->le.dst, &id_addr);
-    conn->le.interval = sys_le16_to_cpu(evt->interval);
-    conn->le.latency = sys_le16_to_cpu(evt->latency);
-    conn->le.timeout = sys_le16_to_cpu(evt->supv_timeout);
-    conn->role = evt->role;
-    conn->err = 0U;
+  if (!conn) {
+    BT_ERR("Unable to add new conn for handle %u", handle);
+    return;
+  }
+
+  conn->handle = handle;
+  bt_addr_le_copy(&conn->le.dst, &id_addr);
+  conn->le.interval = sys_le16_to_cpu(evt->interval);
+  conn->le.latency  = sys_le16_to_cpu(evt->latency);
+  conn->le.timeout  = sys_le16_to_cpu(evt->supv_timeout);
+  conn->role        = evt->role;
+  conn->err         = 0U;
+
+  /*
+   * Use connection address (instead of identity address) as initiator
+   * or responder address. Only slave needs to be updated. For master all
+   * was set during outgoing connection creation.
+   */
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn->role == BT_HCI_ROLE_SLAVE) {
+    bt_addr_le_copy(&conn->le.init_addr, &peer_addr);
 
-    /*
-	 * Use connection address (instead of identity address) as initiator
-	 * or responder address. Only slave needs to be updated. For master all
-	 * was set during outgoing connection creation.
-	 */
-    if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
-        conn->role == BT_HCI_ROLE_SLAVE) {
-        bt_addr_le_copy(&conn->le.init_addr, &peer_addr);
-
-        if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
 #if defined(BFLB_BLE_PATCH_DHKEY_CHECK_FAILED)
-            if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t)))
-                bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa);
-            else
-                bt_addr_copy(&conn->le.resp_addr.a, &bt_dev.random_addr.a);
+      if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t)))
+        bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa);
+      else
+        bt_addr_copy(&conn->le.resp_addr.a, &bt_dev.random_addr.a);
 #else
-            bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa);
+      bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa);
 #endif
-            conn->le.resp_addr.type = BT_ADDR_LE_RANDOM;
-        } else {
-            bt_addr_le_copy(&conn->le.resp_addr,
-                            &bt_dev.id_addr[conn->id]);
-        }
+      conn->le.resp_addr.type = BT_ADDR_LE_RANDOM;
+    } else {
+      bt_addr_le_copy(&conn->le.resp_addr, &bt_dev.id_addr[conn->id]);
+    }
 
 #if defined(CONFIG_BT_STACK_PTS)
-        if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ADV_ADDRESS_IS_PUBLIC)) {
-            bt_addr_le_copy(&conn->le.resp_addr, &bt_dev.id_addr[conn->id]);
-        }
+    if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ADV_ADDRESS_IS_PUBLIC)) {
+      bt_addr_le_copy(&conn->le.resp_addr, &bt_dev.id_addr[conn->id]);
+    }
 #endif
 
-        /* if the controller supports, lets advertise for another
-		 * slave connection.
-		 * check for connectable advertising state is sufficient as
-		 * this is how this le connection complete for slave occurred.
-		 */
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) &&
-            BT_LE_STATES_SLAVE_CONN_ADV(bt_dev.le.states)) {
-            if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-                le_set_private_addr(bt_dev.adv_id);
-            }
+    /* if the controller supports, lets advertise for another
+     * slave connection.
+     * check for connectable advertising state is sufficient as
+     * this is how this le connection complete for slave occurred.
+     */
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) && BT_LE_STATES_SLAVE_CONN_ADV(bt_dev.le.states)) {
+      if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+        le_set_private_addr(bt_dev.adv_id);
+      }
 
-            set_advertise_enable(true);
-        }
+      set_advertise_enable(true);
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
-        conn->role == BT_HCI_ROLE_MASTER) {
-        if (IS_ENABLED(CONFIG_BT_WHITELIST) &&
-            atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
-            conn->id = BT_ID_DEFAULT;
-            atomic_clear_bit(bt_dev.flags, BT_DEV_AUTO_CONN);
-        }
+  if (IS_ENABLED(CONFIG_BT_CENTRAL) && conn->role == BT_HCI_ROLE_MASTER) {
+    if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
+      conn->id = BT_ID_DEFAULT;
+      atomic_clear_bit(bt_dev.flags, BT_DEV_AUTO_CONN);
+    }
 
-        bt_addr_le_copy(&conn->le.resp_addr, &peer_addr);
+    bt_addr_le_copy(&conn->le.resp_addr, &peer_addr);
 
-        if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
 #if defined(BFLB_BLE_PATCH_DHKEY_CHECK_FAILED)
-            if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t)))
-                bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa);
-            else
-                bt_addr_copy(&conn->le.init_addr.a, &bt_dev.random_addr.a);
+      if (memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t)))
+        bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa);
+      else
+        bt_addr_copy(&conn->le.init_addr.a, &bt_dev.random_addr.a);
 #else
-            bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa);
+      bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa);
 #endif
-            conn->le.init_addr.type = BT_ADDR_LE_RANDOM;
-        } else {
-            bt_addr_le_copy(&conn->le.init_addr,
-                            &bt_dev.id_addr[conn->id]);
-        }
+      conn->le.init_addr.type = BT_ADDR_LE_RANDOM;
+    } else {
+      bt_addr_le_copy(&conn->le.init_addr, &bt_dev.id_addr[conn->id]);
+    }
 
 #if defined(CONFIG_BT_STACK_PTS)
-        if (conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) {
-            bt_addr_le_copy(&conn->le.init_addr, &bt_dev.id_addr[conn->id]);
-        }
-#endif
+    if (conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) {
+      bt_addr_le_copy(&conn->le.init_addr, &bt_dev.id_addr[conn->id]);
     }
+#endif
+  }
 
-    bt_conn_set_state(conn, BT_CONN_CONNECTED);
+  bt_conn_set_state(conn, BT_CONN_CONNECTED);
 
-    /*
-	 * it is possible that connection was disconnected directly from
-	 * connected callback so we must check state before doing connection
-	 * parameters update
-	 */
-    if (conn->state != BT_CONN_CONNECTED) {
-        goto done;
-    }
+  /*
+   * it is possible that connection was disconnected directly from
+   * connected callback so we must check state before doing connection
+   * parameters update
+   */
+  if (conn->state != BT_CONN_CONNECTED) {
+    goto done;
+  }
 
-    if ((evt->role == BT_HCI_ROLE_MASTER) ||
-        BT_FEAT_LE_SLAVE_FEATURE_XCHG(bt_dev.le.features)) {
-        err = hci_le_read_remote_features(conn);
-        if (!err) {
-            goto done;
-        }
+  if ((evt->role == BT_HCI_ROLE_MASTER) || BT_FEAT_LE_SLAVE_FEATURE_XCHG(bt_dev.le.features)) {
+    err = hci_le_read_remote_features(conn);
+    if (!err) {
+      goto done;
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) &&
-        BT_FEAT_LE_PHY_2M(bt_dev.le.features)) {
-        err = hci_le_set_phy(conn);
-        if (!err) {
-            atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE);
-            goto done;
-        }
+  if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && BT_FEAT_LE_PHY_2M(bt_dev.le.features)) {
+    err = hci_le_set_phy(conn, 0U, BT_HCI_LE_PHY_PREFER_2M, BT_HCI_LE_PHY_PREFER_2M, BT_HCI_LE_PHY_CODED_ANY);
+    if (!err) {
+      atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE);
+      goto done;
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) &&
-        BT_FEAT_LE_DLE(bt_dev.le.features)) {
-        hci_le_set_data_len(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features)) {
+    hci_le_set_data_len(conn);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
-        conn->role == BT_CONN_ROLE_SLAVE) {
-        slave_update_conn_param(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn->role == BT_CONN_ROLE_SLAVE) {
+    slave_update_conn_param(conn);
+  }
 
 done:
-    bt_conn_unref(conn);
-    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-        bt_le_scan_update(false);
-    }
+  bt_conn_unref(conn);
+  if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+    bt_le_scan_update(false);
+  }
 }
 
-static void le_enh_conn_complete(struct net_buf *buf)
-{
-    enh_conn_complete((void *)buf->data);
-}
+static void le_enh_conn_complete(struct net_buf *buf) { enh_conn_complete((void *)buf->data); }
 
-static void le_legacy_conn_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_conn_complete *evt = (void *)buf->data;
-    struct bt_hci_evt_le_enh_conn_complete enh;
-    const bt_addr_le_t *id_addr;
+static void le_legacy_conn_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_conn_complete    *evt = (void *)buf->data;
+  struct bt_hci_evt_le_enh_conn_complete enh;
+  const bt_addr_le_t                    *id_addr;
 
-    BT_DBG("status 0x%02x role %u %s", evt->status, evt->role,
-           bt_addr_le_str(&evt->peer_addr));
+  BT_DBG("status 0x%02x role %u %s", evt->status, evt->role, bt_addr_le_str(&evt->peer_addr));
 
-    enh.status = evt->status;
-    enh.handle = evt->handle;
-    enh.role = evt->role;
-    enh.interval = evt->interval;
-    enh.latency = evt->latency;
-    enh.supv_timeout = evt->supv_timeout;
-    enh.clock_accuracy = evt->clock_accuracy;
+  enh.status         = evt->status;
+  enh.handle         = evt->handle;
+  enh.role           = evt->role;
+  enh.interval       = evt->interval;
+  enh.latency        = evt->latency;
+  enh.supv_timeout   = evt->supv_timeout;
+  enh.clock_accuracy = evt->clock_accuracy;
 
-    bt_addr_le_copy(&enh.peer_addr, &evt->peer_addr);
+  bt_addr_le_copy(&enh.peer_addr, &evt->peer_addr);
 
-    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        bt_addr_copy(&enh.local_rpa, &bt_dev.random_addr.a);
-    } else {
-        bt_addr_copy(&enh.local_rpa, BT_ADDR_ANY);
-    }
+  if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    bt_addr_copy(&enh.local_rpa, &bt_dev.random_addr.a);
+  } else {
+    bt_addr_copy(&enh.local_rpa, BT_ADDR_ANY);
+  }
 
-    if (evt->role == BT_HCI_ROLE_SLAVE) {
-        id_addr = bt_lookup_id_addr(bt_dev.adv_id, &enh.peer_addr);
-    } else {
-        id_addr = bt_lookup_id_addr(BT_ID_DEFAULT, &enh.peer_addr);
-    }
+  if (evt->role == BT_HCI_ROLE_SLAVE) {
+    id_addr = bt_lookup_id_addr(bt_dev.adv_id, &enh.peer_addr);
+  } else {
+    id_addr = bt_lookup_id_addr(BT_ID_DEFAULT, &enh.peer_addr);
+  }
 
-    if (id_addr != &enh.peer_addr) {
-        bt_addr_copy(&enh.peer_rpa, &enh.peer_addr.a);
-        bt_addr_le_copy(&enh.peer_addr, id_addr);
-        enh.peer_addr.type += BT_ADDR_LE_PUBLIC_ID;
-    } else {
-        bt_addr_copy(&enh.peer_rpa, BT_ADDR_ANY);
-    }
+  if (id_addr != &enh.peer_addr) {
+    bt_addr_copy(&enh.peer_rpa, &enh.peer_addr.a);
+    bt_addr_le_copy(&enh.peer_addr, id_addr);
+    enh.peer_addr.type += BT_ADDR_LE_PUBLIC_ID;
+  } else {
+    bt_addr_copy(&enh.peer_rpa, BT_ADDR_ANY);
+  }
 
-    enh_conn_complete(&enh);
+  enh_conn_complete(&enh);
 }
 
-static void le_remote_feat_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_remote_feat_complete *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
+static void le_remote_feat_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_remote_feat_complete *evt    = (void *)buf->data;
+  u16_t                                      handle = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                            *conn;
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    return;
+  }
 
-    if (!evt->status) {
-        memcpy(conn->le.features, evt->features,
-               sizeof(conn->le.features));
-    }
+  if (!evt->status) {
+    memcpy(conn->le.features, evt->features, sizeof(conn->le.features));
+  }
 
-    if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) &&
-        BT_FEAT_LE_PHY_2M(bt_dev.le.features) &&
-        BT_FEAT_LE_PHY_2M(conn->le.features)) {
-        int err;
+  if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && BT_FEAT_LE_PHY_2M(bt_dev.le.features) && BT_FEAT_LE_PHY_2M(conn->le.features)) {
+    int err;
 
-        err = hci_le_set_phy(conn);
-        if (!err) {
-            atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE);
-            goto done;
-        }
+    err = hci_le_set_phy(conn, 0U, BT_HCI_LE_PHY_PREFER_2M, BT_HCI_LE_PHY_PREFER_2M, BT_HCI_LE_PHY_CODED_ANY);
+    if (!err) {
+      atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE);
+      goto done;
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) &&
-        BT_FEAT_LE_DLE(bt_dev.le.features) &&
-        BT_FEAT_LE_DLE(conn->le.features)) {
-        hci_le_set_data_len(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features) && BT_FEAT_LE_DLE(conn->le.features)) {
+    hci_le_set_data_len(conn);
+  }
 
 #if !defined(CONFIG_BT_STACK_PTS)
-    if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
-        conn->role == BT_CONN_ROLE_SLAVE) {
-        slave_update_conn_param(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn->role == BT_CONN_ROLE_SLAVE) {
+    slave_update_conn_param(conn);
+  }
 #endif
 done:
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
 #if defined(CONFIG_BT_DATA_LEN_UPDATE)
-static void le_data_len_change(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_data_len_change *evt = (void *)buf->data;
-    u16_t max_tx_octets = sys_le16_to_cpu(evt->max_tx_octets);
-    u16_t max_rx_octets = sys_le16_to_cpu(evt->max_rx_octets);
-    u16_t max_tx_time = sys_le16_to_cpu(evt->max_tx_time);
-    u16_t max_rx_time = sys_le16_to_cpu(evt->max_rx_time);
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
-
-    UNUSED(max_tx_octets);
-    UNUSED(max_rx_octets);
-    UNUSED(max_tx_time);
-    UNUSED(max_rx_time);
-
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        return;
-    }
+static void le_data_len_change(struct net_buf *buf) {
+  struct bt_hci_evt_le_data_len_change *evt           = (void *)buf->data;
+  u16_t                                 max_tx_octets = sys_le16_to_cpu(evt->max_tx_octets);
+  u16_t                                 max_rx_octets = sys_le16_to_cpu(evt->max_rx_octets);
+  u16_t                                 max_tx_time   = sys_le16_to_cpu(evt->max_tx_time);
+  u16_t                                 max_rx_time   = sys_le16_to_cpu(evt->max_rx_time);
+  u16_t                                 handle        = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                       *conn;
+
+  UNUSED(max_tx_octets);
+  UNUSED(max_rx_octets);
+  UNUSED(max_tx_time);
+  UNUSED(max_rx_time);
+
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    return;
+  }
 
-    BT_DBG("max. tx: %u (%uus), max. rx: %u (%uus)", max_tx_octets,
-           max_tx_time, max_rx_octets, max_rx_time);
+  BT_DBG("max. tx: %u (%uus), max. rx: %u (%uus)", max_tx_octets, max_tx_time, max_rx_octets, max_rx_time);
 
-    /* TODO use those */
+  /* TODO use those */
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 #endif /* CONFIG_BT_DATA_LEN_UPDATE */
 
 #if defined(CONFIG_BT_PHY_UPDATE)
-static void le_phy_update_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_phy_update_complete *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
+static void le_phy_update_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_phy_update_complete *evt    = (void *)buf->data;
+  u16_t                                     handle = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                           *conn;
+
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    return;
+  }
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        return;
-    }
+  BT_DBG("PHY updated: status: 0x%02x, tx: %u, rx: %u", evt->status, evt->tx_phy, evt->rx_phy);
 
-    BT_DBG("PHY updated: status: 0x%02x, tx: %u, rx: %u",
-           evt->status, evt->tx_phy, evt->rx_phy);
+  notify_le_phy_updated(conn, evt->tx_phy, evt->rx_phy);
 
-    if (!IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) ||
-        !atomic_test_and_clear_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE)) {
-        goto done;
-    }
+  if (!IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) || !atomic_test_and_clear_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE)) {
+    goto done;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) &&
-        BT_FEAT_LE_DLE(bt_dev.le.features) &&
-        BT_FEAT_LE_DLE(conn->le.features)) {
-        hci_le_set_data_len(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features) && BT_FEAT_LE_DLE(conn->le.features)) {
+    hci_le_set_data_len(conn);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_PERIPHERAL) &&
-        conn->role == BT_CONN_ROLE_SLAVE) {
-        slave_update_conn_param(conn);
-    }
+  if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && conn->role == BT_CONN_ROLE_SLAVE) {
+    slave_update_conn_param(conn);
+  }
 
 done:
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 #endif /* CONFIG_BT_PHY_UPDATE */
 
-bool bt_le_conn_params_valid(const struct bt_le_conn_param *param)
-{
-    /* All limits according to BT Core spec 5.0 [Vol 2, Part E, 7.8.12] */
+bool bt_le_conn_params_valid(const struct bt_le_conn_param *param) {
+  /* All limits according to BT Core spec 5.0 [Vol 2, Part E, 7.8.12] */
 
-    if (param->interval_min > param->interval_max ||
-        param->interval_min < 6 || param->interval_max > 3200) {
-        return false;
-    }
+  if (param->interval_min > param->interval_max || param->interval_min < 6 || param->interval_max > 3200) {
+    return false;
+  }
 
-    if (param->latency > 499) {
-        return false;
-    }
+  if (param->latency > 499) {
+    return false;
+  }
 
-    if (param->timeout < 10 || param->timeout > 3200 ||
-        ((param->timeout * 4U) <=
-         ((1 + param->latency) * param->interval_max))) {
-        return false;
-    }
+  if (param->timeout < 10 || param->timeout > 3200 || ((param->timeout * 4U) <= ((1 + param->latency) * param->interval_max))) {
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
-static void le_conn_param_neg_reply(u16_t handle, u8_t reason)
-{
-    struct bt_hci_cp_le_conn_param_req_neg_reply *cp;
-    struct net_buf *buf;
+static void le_conn_param_neg_reply(u16_t handle, u8_t reason) {
+  struct bt_hci_cp_le_conn_param_req_neg_reply *cp;
+  struct net_buf                               *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY,
-                            sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Unable to allocate buffer");
-        return;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Unable to allocate buffer");
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(handle);
-    cp->reason = sys_cpu_to_le16(reason);
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(handle);
+  cp->reason = sys_cpu_to_le16(reason);
 
-    bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, buf);
+  bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, buf);
 }
 
-static int le_conn_param_req_reply(u16_t handle,
-                                   const struct bt_le_conn_param *param)
-{
-    struct bt_hci_cp_le_conn_param_req_reply *cp;
-    struct net_buf *buf;
+static int le_conn_param_req_reply(u16_t handle, const struct bt_le_conn_param *param) {
+  struct bt_hci_cp_le_conn_param_req_reply *cp;
+  struct net_buf                           *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    (void)memset(cp, 0, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
+  (void)memset(cp, 0, sizeof(*cp));
 
-    cp->handle = sys_cpu_to_le16(handle);
-    cp->interval_min = sys_cpu_to_le16(param->interval_min);
-    cp->interval_max = sys_cpu_to_le16(param->interval_max);
-    cp->latency = sys_cpu_to_le16(param->latency);
-    cp->timeout = sys_cpu_to_le16(param->timeout);
+  cp->handle       = sys_cpu_to_le16(handle);
+  cp->interval_min = sys_cpu_to_le16(param->interval_min);
+  cp->interval_max = sys_cpu_to_le16(param->interval_max);
+  cp->latency      = sys_cpu_to_le16(param->latency);
+  cp->timeout      = sys_cpu_to_le16(param->timeout);
 
-    return bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, buf);
+  return bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, buf);
 }
 
-static void le_conn_param_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_conn_param_req *evt = (void *)buf->data;
-    struct bt_le_conn_param param;
-    struct bt_conn *conn;
-    u16_t handle;
+static void le_conn_param_req(struct net_buf *buf) {
+  struct bt_hci_evt_le_conn_param_req *evt = (void *)buf->data;
+  struct bt_le_conn_param              param;
+  struct bt_conn                      *conn;
+  u16_t                                handle;
 
-    handle = sys_le16_to_cpu(evt->handle);
-    param.interval_min = sys_le16_to_cpu(evt->interval_min);
-    param.interval_max = sys_le16_to_cpu(evt->interval_max);
-    param.latency = sys_le16_to_cpu(evt->latency);
-    param.timeout = sys_le16_to_cpu(evt->timeout);
+  handle             = sys_le16_to_cpu(evt->handle);
+  param.interval_min = sys_le16_to_cpu(evt->interval_min);
+  param.interval_max = sys_le16_to_cpu(evt->interval_max);
+  param.latency      = sys_le16_to_cpu(evt->latency);
+  param.timeout      = sys_le16_to_cpu(evt->timeout);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        le_conn_param_neg_reply(handle, BT_HCI_ERR_UNKNOWN_CONN_ID);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    le_conn_param_neg_reply(handle, BT_HCI_ERR_UNKNOWN_CONN_ID);
+    return;
+  }
 
-    if (!le_param_req(conn, ¶m)) {
-        le_conn_param_neg_reply(handle, BT_HCI_ERR_INVALID_LL_PARAM);
-    } else {
-        le_conn_param_req_reply(handle, ¶m);
-    }
+  if (!le_param_req(conn, ¶m)) {
+    le_conn_param_neg_reply(handle, BT_HCI_ERR_INVALID_LL_PARAM);
+  } else {
+    le_conn_param_req_reply(handle, ¶m);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void le_conn_update_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_conn_update_complete *evt = (void *)buf->data;
-    struct bt_conn *conn;
-    u16_t handle;
+static void le_conn_update_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_conn_update_complete *evt = (void *)buf->data;
+  struct bt_conn                            *conn;
+  u16_t                                      handle;
 
-    handle = sys_le16_to_cpu(evt->handle);
+  handle = sys_le16_to_cpu(evt->handle);
 
-    BT_DBG("status 0x%02x, handle %u", evt->status, handle);
+  BT_DBG("status 0x%02x, handle %u", evt->status, handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    return;
+  }
 
-    if (!evt->status) {
-        conn->le.interval = sys_le16_to_cpu(evt->interval);
-        conn->le.latency = sys_le16_to_cpu(evt->latency);
-        conn->le.timeout = sys_le16_to_cpu(evt->supv_timeout);
-        notify_le_param_updated(conn);
-    } else if (evt->status == BT_HCI_ERR_UNSUPP_REMOTE_FEATURE &&
-               conn->role == BT_HCI_ROLE_SLAVE &&
-               !atomic_test_and_set_bit(conn->flags,
-                                        BT_CONN_SLAVE_PARAM_L2CAP)) {
-        /* CPR not supported, let's try L2CAP CPUP instead */
-        struct bt_le_conn_param param;
+  if (!evt->status) {
+    conn->le.interval = sys_le16_to_cpu(evt->interval);
+    conn->le.latency  = sys_le16_to_cpu(evt->latency);
+    conn->le.timeout  = sys_le16_to_cpu(evt->supv_timeout);
+    notify_le_param_updated(conn);
+  } else if (evt->status == BT_HCI_ERR_UNSUPP_REMOTE_FEATURE && conn->role == BT_HCI_ROLE_SLAVE && !atomic_test_and_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) {
+    /* CPR not supported, let's try L2CAP CPUP instead */
+    struct bt_le_conn_param param;
 
-        param.interval_min = conn->le.interval_min;
-        param.interval_max = conn->le.interval_max;
-        param.latency = conn->le.pending_latency;
-        param.timeout = conn->le.pending_timeout;
+    param.interval_min = conn->le.interval_min;
+    param.interval_max = conn->le.interval_max;
+    param.latency      = conn->le.pending_latency;
+    param.timeout      = conn->le.pending_timeout;
 
-        bt_l2cap_update_conn_param(conn, ¶m);
-    }
+    bt_l2cap_update_conn_param(conn, ¶m);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
 #if defined(CONFIG_BT_CENTRAL)
-static void check_pending_conn(const bt_addr_le_t *id_addr,
-                               const bt_addr_le_t *addr, u8_t evtype)
-{
-    struct bt_conn *conn;
+static void check_pending_conn(const bt_addr_le_t *id_addr, const bt_addr_le_t *addr, u8_t evtype) {
+  struct bt_conn *conn;
 
-    /* No connections are allowed during explicit scanning */
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return;
-    }
+  /* No connections are allowed during explicit scanning */
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return;
+  }
 
-    /* Return if event is not connectable */
-    if (evtype != BT_LE_ADV_IND && evtype != BT_LE_ADV_DIRECT_IND) {
-        return;
-    }
+  /* Return if event is not connectable */
+  if (evtype != BT_LE_ADV_IND && evtype != BT_LE_ADV_DIRECT_IND) {
+    return;
+  }
 
-    conn = bt_conn_lookup_state_le(id_addr, BT_CONN_CONNECT_SCAN);
-    if (!conn) {
-        return;
-    }
+  conn = bt_conn_lookup_state_le(id_addr, BT_CONN_CONNECT_SCAN);
+  if (!conn) {
+    return;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) &&
-        set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE)) {
-        goto failed;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE)) {
+    goto failed;
+  }
 
-    bt_addr_le_copy(&conn->le.resp_addr, addr);
-    if (hci_le_create_conn(conn)) {
-        goto failed;
-    }
+  bt_addr_le_copy(&conn->le.resp_addr, addr);
+  if (hci_le_create_conn(conn)) {
+    goto failed;
+  }
 
-    bt_conn_set_state(conn, BT_CONN_CONNECT);
-    bt_conn_unref(conn);
-    return;
+  bt_conn_set_state(conn, BT_CONN_CONNECT);
+  bt_conn_unref(conn);
+  return;
 
 failed:
-    conn->err = BT_HCI_ERR_UNSPECIFIED;
-    bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-    bt_conn_unref(conn);
-    bt_le_scan_update(false);
+  conn->err = BT_HCI_ERR_UNSPECIFIED;
+  bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+  bt_conn_unref(conn);
+  bt_le_scan_update(false);
 }
 #endif /* CONFIG_BT_CENTRAL */
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-static int set_flow_control(void)
-{
-    struct bt_hci_cp_host_buffer_size *hbs;
-    struct net_buf *buf;
-    int err;
-
-    /* Check if host flow control is actually supported */
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) {
-        BT_WARN("Controller to host flow control not supported");
-        return 0;
-    }
+static int set_flow_control(void) {
+  struct bt_hci_cp_host_buffer_size *hbs;
+  struct net_buf                    *buf;
+  int                                err;
+
+  /* Check if host flow control is actually supported */
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) {
+    BT_WARN("Controller to host flow control not supported");
+    return 0;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_HOST_BUFFER_SIZE,
-                            sizeof(*hbs));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_HOST_BUFFER_SIZE, sizeof(*hbs));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    hbs = net_buf_add(buf, sizeof(*hbs));
-    (void)memset(hbs, 0, sizeof(*hbs));
-    hbs->acl_mtu = sys_cpu_to_le16(CONFIG_BT_L2CAP_RX_MTU +
-                                   sizeof(struct bt_l2cap_hdr));
-    hbs->acl_pkts = sys_cpu_to_le16(CONFIG_BT_ACL_RX_COUNT);
+  hbs = net_buf_add(buf, sizeof(*hbs));
+  (void)memset(hbs, 0, sizeof(*hbs));
+  hbs->acl_mtu  = sys_cpu_to_le16(CONFIG_BT_L2CAP_RX_MTU + sizeof(struct bt_l2cap_hdr));
+  hbs->acl_pkts = sys_cpu_to_le16(CONFIG_BT_ACL_RX_COUNT);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_HOST_BUFFER_SIZE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_HOST_BUFFER_SIZE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, 1);
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, 1);
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_u8(buf, BT_HCI_CTL_TO_HOST_FLOW_ENABLE);
-    return bt_hci_cmd_send_sync(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, buf, NULL);
+  net_buf_add_u8(buf, BT_HCI_CTL_TO_HOST_FLOW_ENABLE);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, buf, NULL);
 }
 #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */
 
-static int bt_clear_all_pairings(u8_t id)
-{
-    bt_conn_disconnect_all(id);
+static int bt_clear_all_pairings(u8_t id) {
+  bt_conn_disconnect_all(id);
 
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        bt_keys_clear_all(id);
-    }
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    bt_keys_clear_all(id);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR)) {
-        bt_keys_link_key_clear_addr(NULL);
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR)) {
+    bt_keys_link_key_clear_addr(NULL);
+  }
 
-    return 0;
+  return 0;
 }
 
-int bt_unpair(u8_t id, const bt_addr_le_t *addr)
-{
-    struct bt_keys *keys = NULL;
-    struct bt_conn *conn;
+int bt_unpair(u8_t id, const bt_addr_le_t *addr) {
+  struct bt_keys *keys = NULL;
+  struct bt_conn *conn;
 
-    if (id >= CONFIG_BT_ID_MAX) {
-        return -EINVAL;
-    }
+  if (id >= CONFIG_BT_ID_MAX) {
+    return -EINVAL;
+  }
 
-    if (!addr || !bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
-        return bt_clear_all_pairings(id);
+  if (!addr || !bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
+    return bt_clear_all_pairings(id);
+  }
+
+  conn = bt_conn_lookup_addr_le(id, addr);
+  if (conn) {
+    /* Clear the conn->le.keys pointer since we'll invalidate it,
+     * and don't want any subsequent code (like disconnected
+     * callbacks) accessing it.
+     */
+    if (conn->type == BT_CONN_TYPE_LE) {
+      keys          = conn->le.keys;
+      conn->le.keys = NULL;
     }
 
-    conn = bt_conn_lookup_addr_le(id, addr);
-    if (conn) {
-        /* Clear the conn->le.keys pointer since we'll invalidate it,
-		 * and don't want any subsequent code (like disconnected
-		 * callbacks) accessing it.
-		 */
-        if (conn->type == BT_CONN_TYPE_LE) {
-            keys = conn->le.keys;
-            conn->le.keys = NULL;
-        }
+    bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
+    bt_conn_unref(conn);
+  }
 
-        bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
-        bt_conn_unref(conn);
+  if (IS_ENABLED(CONFIG_BT_BREDR)) {
+    /* LE Public may indicate BR/EDR as well */
+    if (addr->type == BT_ADDR_LE_PUBLIC) {
+      bt_keys_link_key_clear_addr(&addr->a);
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR)) {
-        /* LE Public may indicate BR/EDR as well */
-        if (addr->type == BT_ADDR_LE_PUBLIC) {
-            bt_keys_link_key_clear_addr(&addr->a);
-        }
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    if (!keys) {
+      keys = bt_keys_find_addr(id, addr);
     }
 
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        if (!keys) {
-            keys = bt_keys_find_addr(id, addr);
-        }
-
-        if (keys) {
-            bt_keys_clear(keys);
-        }
+    if (keys) {
+      bt_keys_clear(keys);
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        bt_gatt_clear(id, addr);
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    bt_gatt_clear(id, addr);
+  }
 
-    return 0;
+  return 0;
 }
 
 #endif /* CONFIG_BT_CONN */
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-static enum bt_security_err security_err_get(u8_t hci_err)
-{
-    switch (hci_err) {
-        case BT_HCI_ERR_SUCCESS:
-            return BT_SECURITY_ERR_SUCCESS;
-        case BT_HCI_ERR_AUTH_FAIL:
-            return BT_SECURITY_ERR_AUTH_FAIL;
-        case BT_HCI_ERR_PIN_OR_KEY_MISSING:
-            return BT_SECURITY_ERR_PIN_OR_KEY_MISSING;
-        case BT_HCI_ERR_PAIRING_NOT_SUPPORTED:
-            return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED;
-        case BT_HCI_ERR_PAIRING_NOT_ALLOWED:
-            return BT_SECURITY_ERR_PAIR_NOT_ALLOWED;
-        case BT_HCI_ERR_INVALID_PARAM:
-            return BT_SECURITY_ERR_INVALID_PARAM;
-        default:
-            return BT_SECURITY_ERR_UNSPECIFIED;
-    }
-}
-
-static void reset_pairing(struct bt_conn *conn)
-{
+static enum bt_security_err security_err_get(u8_t hci_err) {
+  switch (hci_err) {
+  case BT_HCI_ERR_SUCCESS:
+    return BT_SECURITY_ERR_SUCCESS;
+  case BT_HCI_ERR_AUTH_FAIL:
+    return BT_SECURITY_ERR_AUTH_FAIL;
+  case BT_HCI_ERR_PIN_OR_KEY_MISSING:
+    return BT_SECURITY_ERR_PIN_OR_KEY_MISSING;
+  case BT_HCI_ERR_PAIRING_NOT_SUPPORTED:
+    return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED;
+  case BT_HCI_ERR_PAIRING_NOT_ALLOWED:
+    return BT_SECURITY_ERR_PAIR_NOT_ALLOWED;
+  case BT_HCI_ERR_INVALID_PARAM:
+    return BT_SECURITY_ERR_INVALID_PARAM;
+  default:
+    return BT_SECURITY_ERR_UNSPECIFIED;
+  }
+}
+
+static void reset_pairing(struct bt_conn *conn) {
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING);
-        atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR);
-        atomic_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE);
-    }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING);
+    atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR);
+    atomic_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE);
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    /* Reset required security level to current operational */
-    conn->required_sec_level = conn->sec_level;
+  /* Reset required security level to current operational */
+  conn->required_sec_level = conn->sec_level;
 }
 #endif /* defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) */
 
 #if defined(CONFIG_BT_BREDR)
-static int reject_conn(const bt_addr_t *bdaddr, u8_t reason)
-{
-    struct bt_hci_cp_reject_conn_req *cp;
-    struct net_buf *buf;
-    int err;
-
-    buf = bt_hci_cmd_create(BT_HCI_OP_REJECT_CONN_REQ, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
-
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    cp->reason = reason;
-
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_REJECT_CONN_REQ, buf, NULL);
-    if (err) {
-        return err;
-    }
-
-    return 0;
-}
-
-static int accept_sco_conn(const bt_addr_t *bdaddr, struct bt_conn *sco_conn)
-{
-    struct bt_hci_cp_accept_sync_conn_req *cp;
-    struct net_buf *buf;
-    int err;
-
-    buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
-
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    cp->pkt_type = sco_conn->sco.pkt_type;
-
-    cp->tx_bandwidth = 0x00001f40;
-    cp->rx_bandwidth = 0x00001f40;
-    if (!hfp_codec_msbc) {
-        cp->max_latency = 0x0007;
-        cp->retrans_effort = 0x01;
-        cp->content_format = BT_VOICE_CVSD_16BIT;
-        BT_DBG("eSCO air coding CVSD!");
-    } else {
-        cp->max_latency = 0x000d;
-        cp->retrans_effort = 0x02;
-        cp->content_format = BT_VOICE_MSBC_16BIT;
-        BT_DBG("eSCO air coding mSBC!");
-    }
-
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, buf, NULL);
-    if (err) {
-        return err;
-    }
+static int reject_conn(const bt_addr_t *bdaddr, u8_t reason) {
+  struct bt_hci_cp_reject_conn_req *cp;
+  struct net_buf                   *buf;
+  int                               err;
+
+  buf = bt_hci_cmd_create(BT_HCI_OP_REJECT_CONN_REQ, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
+
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  cp->reason = reason;
+
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_REJECT_CONN_REQ, buf, NULL);
+  if (err) {
+    return err;
+  }
+
+  return 0;
+}
+
+static int accept_sco_conn(const bt_addr_t *bdaddr, struct bt_conn *sco_conn) {
+  struct bt_hci_cp_accept_sync_conn_req *cp;
+  struct net_buf                        *buf;
+  int                                    err;
+
+  buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
+
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  cp->pkt_type = sco_conn->sco.pkt_type;
+
+  cp->tx_bandwidth   = 0x00001f40;
+  cp->rx_bandwidth   = 0x00001f40;
+  cp->max_latency    = 0x0007;
+  cp->retrans_effort = 0x01;
+  cp->content_format = BT_VOICE_CVSD_16BIT;
+#if defined CONFIG_BT_HFP
+  if (!hfp_codec_msbc) {
+    cp->max_latency    = 0x000d;
+    cp->retrans_effort = 0x02;
+    cp->content_format = BT_VOICE_MSBC_16BIT;
+    BT_DBG("eSCO air coding mSBC!");
+  }
+#endif
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-static int accept_conn(const bt_addr_t *bdaddr)
-{
-    struct bt_hci_cp_accept_conn_req *cp;
-    struct net_buf *buf;
-    int err;
+static int accept_conn(const bt_addr_t *bdaddr) {
+  struct bt_hci_cp_accept_conn_req *cp;
+  struct net_buf                   *buf;
+  int                               err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_CONN_REQ, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_CONN_REQ, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    cp->role = BT_HCI_ROLE_SLAVE;
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  cp->role = BT_HCI_ROLE_SLAVE;
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_CONN_REQ, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_CONN_REQ, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-static void bt_esco_conn_req(struct bt_hci_evt_conn_request *evt)
-{
-    struct bt_conn *sco_conn;
+static void bt_esco_conn_req(struct bt_hci_evt_conn_request *evt) {
+  struct bt_conn *sco_conn;
 
-    sco_conn = bt_conn_add_sco(&evt->bdaddr, evt->link_type);
-    if (!sco_conn) {
-        reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES);
-        return;
-    }
+  sco_conn = bt_conn_add_sco(&evt->bdaddr, evt->link_type);
+  if (!sco_conn) {
+    reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES);
+    return;
+  }
 
-    if (accept_sco_conn(&evt->bdaddr, sco_conn)) {
-        BT_ERR("Error accepting connection from %s",
-               bt_addr_str(&evt->bdaddr));
-        reject_conn(&evt->bdaddr, BT_HCI_ERR_UNSPECIFIED);
-        bt_sco_cleanup(sco_conn);
-        return;
-    }
+  if (accept_sco_conn(&evt->bdaddr, sco_conn)) {
+    BT_ERR("Error accepting connection from %s", bt_addr_str(&evt->bdaddr));
+    reject_conn(&evt->bdaddr, BT_HCI_ERR_UNSPECIFIED);
+    bt_sco_cleanup(sco_conn);
+    return;
+  }
 
-    sco_conn->role = BT_HCI_ROLE_SLAVE;
-    bt_conn_set_state(sco_conn, BT_CONN_CONNECT);
-    bt_conn_unref(sco_conn);
+  sco_conn->role = BT_HCI_ROLE_SLAVE;
+  bt_conn_set_state(sco_conn, BT_CONN_CONNECT);
+  bt_conn_unref(sco_conn);
 }
 
-static void conn_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_conn_request *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void conn_req(struct net_buf *buf) {
+  struct bt_hci_evt_conn_request *evt = (void *)buf->data;
+  struct bt_conn                 *conn;
 
-    BT_DBG("conn req from %s, type 0x%02x", bt_addr_str(&evt->bdaddr),
-           evt->link_type);
+  BT_DBG("conn req from %s, type 0x%02x", bt_addr_str(&evt->bdaddr), evt->link_type);
 
-    if (evt->link_type != BT_HCI_ACL) {
-        bt_esco_conn_req(evt);
-        return;
-    }
+  if (evt->link_type != BT_HCI_ACL) {
+    bt_esco_conn_req(evt);
+    return;
+  }
 
-    conn = bt_conn_add_br(&evt->bdaddr);
-    if (!conn) {
-        reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES);
-        return;
-    }
+  conn = bt_conn_add_br(&evt->bdaddr);
+  if (!conn) {
+    reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES);
+    return;
+  }
 
-    accept_conn(&evt->bdaddr);
-    conn->role = BT_HCI_ROLE_SLAVE;
-    bt_conn_set_state(conn, BT_CONN_CONNECT);
-    bt_conn_unref(conn);
+  accept_conn(&evt->bdaddr);
+  conn->role = BT_HCI_ROLE_SLAVE;
+  bt_conn_set_state(conn, BT_CONN_CONNECT);
+  bt_conn_unref(conn);
 }
 
-static bool br_sufficient_key_size(struct bt_conn *conn)
-{
-    struct bt_hci_cp_read_encryption_key_size *cp;
-    struct bt_hci_rp_read_encryption_key_size *rp;
-    struct net_buf *buf, *rsp;
-    u8_t key_size;
-    int err;
-
-    buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
-                            sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Failed to allocate command buffer");
-        return false;
-    }
+static bool br_sufficient_key_size(struct bt_conn *conn) {
+  struct bt_hci_cp_read_encryption_key_size *cp;
+  struct bt_hci_rp_read_encryption_key_size *rp;
+  struct net_buf                            *buf, *rsp;
+  u8_t                                       key_size;
+  int                                        err;
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(conn->handle);
+  buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Failed to allocate command buffer");
+    return false;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
-                               buf, &rsp);
-    if (err) {
-        BT_ERR("Failed to read encryption key size (err %d)", err);
-        return false;
-    }
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(conn->handle);
 
-    if (rsp->len < sizeof(*rp)) {
-        BT_ERR("Too small command complete for encryption key size");
-        net_buf_unref(rsp);
-        return false;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, buf, &rsp);
+  if (err) {
+    BT_ERR("Failed to read encryption key size (err %d)", err);
+    return false;
+  }
 
-    rp = (void *)rsp->data;
-    key_size = rp->key_size;
+  if (rsp->len < sizeof(*rp)) {
+    BT_ERR("Too small command complete for encryption key size");
     net_buf_unref(rsp);
+    return false;
+  }
 
-    BT_DBG("Encryption key size is %u", key_size);
+  rp       = (void *)rsp->data;
+  key_size = rp->key_size;
+  net_buf_unref(rsp);
 
-    if (conn->sec_level == BT_SECURITY_L4) {
-        return key_size == BT_HCI_ENCRYPTION_KEY_SIZE_MAX;
-    }
+  BT_DBG("Encryption key size is %u", key_size);
 
-    return key_size >= BT_HCI_ENCRYPTION_KEY_SIZE_MIN;
-}
+  if (conn->sec_level == BT_SECURITY_L4) {
+    return key_size == BT_HCI_ENCRYPTION_KEY_SIZE_MAX;
+  }
 
-static bool update_sec_level_br(struct bt_conn *conn)
-{
-    if (!conn->encrypt) {
-        conn->sec_level = BT_SECURITY_L1;
-        return true;
-    }
+  return key_size >= BT_HCI_ENCRYPTION_KEY_SIZE_MIN;
+}
 
-    if (conn->br.link_key) {
-        if (conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) {
-            if (conn->encrypt == 0x02) {
-                conn->sec_level = BT_SECURITY_L4;
-            } else {
-                conn->sec_level = BT_SECURITY_L3;
-            }
-        } else {
-            conn->sec_level = BT_SECURITY_L2;
-        }
+static bool update_sec_level_br(struct bt_conn *conn) {
+  if (!conn->encrypt) {
+    conn->sec_level = BT_SECURITY_L1;
+    return true;
+  }
+
+  if (conn->br.link_key) {
+    if (conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) {
+      if (conn->encrypt == 0x02) {
+        conn->sec_level = BT_SECURITY_L4;
+      } else {
+        conn->sec_level = BT_SECURITY_L3;
+      }
     } else {
-        BT_WARN("No BR/EDR link key found");
-        conn->sec_level = BT_SECURITY_L2;
+      conn->sec_level = BT_SECURITY_L2;
     }
+  } else {
+    BT_WARN("No BR/EDR link key found");
+    conn->sec_level = BT_SECURITY_L2;
+  }
 
-    if (!br_sufficient_key_size(conn)) {
-        BT_ERR("Encryption key size is not sufficient");
-        bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
-        return false;
-    }
+  if (!br_sufficient_key_size(conn)) {
+    BT_ERR("Encryption key size is not sufficient");
+    bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
+    return false;
+  }
 
-    if (conn->required_sec_level > conn->sec_level) {
-        BT_ERR("Failed to set required security level");
-        bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
-        return false;
-    }
+  if (conn->required_sec_level > conn->sec_level) {
+    BT_ERR("Failed to set required security level");
+    bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
-static void synchronous_conn_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_sync_conn_complete *evt = (void *)buf->data;
-    struct bt_conn *sco_conn;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
+static void synchronous_conn_complete(struct net_buf *buf) {
+  struct bt_hci_evt_sync_conn_complete *evt = (void *)buf->data;
+  struct bt_conn                       *sco_conn;
+  u16_t                                 handle = sys_le16_to_cpu(evt->handle);
 
-    BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle,
-           evt->link_type);
+  BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle, evt->link_type);
 
-    sco_conn = bt_conn_lookup_addr_sco(&evt->bdaddr);
-    if (!sco_conn) {
-        BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
-
-    if (evt->status) {
-        sco_conn->err = evt->status;
-        bt_conn_set_state(sco_conn, BT_CONN_DISCONNECTED);
-        bt_conn_unref(sco_conn);
-        return;
-    }
+  sco_conn = bt_conn_lookup_addr_sco(&evt->bdaddr);
+  if (!sco_conn) {
+    BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    sco_conn->handle = handle;
-    bt_conn_set_state(sco_conn, BT_CONN_CONNECTED);
+  if (evt->status) {
+    sco_conn->err = evt->status;
+    bt_conn_set_state(sco_conn, BT_CONN_DISCONNECTED);
     bt_conn_unref(sco_conn);
-}
+    return;
+  }
 
-static void conn_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_conn_complete *evt = (void *)buf->data;
-    struct bt_conn *conn;
-    struct bt_hci_cp_read_remote_features *cp;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
+  sco_conn->handle = handle;
+  bt_conn_set_state(sco_conn, BT_CONN_CONNECTED);
+  bt_conn_unref(sco_conn);
+}
 
-    BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle,
-           evt->link_type);
+static void conn_complete(struct net_buf *buf) {
+  struct bt_hci_evt_conn_complete       *evt = (void *)buf->data;
+  struct bt_conn                        *conn;
+  struct bt_hci_cp_read_remote_features *cp;
+  u16_t                                  handle = sys_le16_to_cpu(evt->handle);
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle, evt->link_type);
 
-    if (evt->status) {
-        conn->err = evt->status;
-        bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    conn->handle = handle;
-    conn->err = 0U;
-    conn->encrypt = evt->encr_enabled;
+  if (evt->status) {
+    conn->err = evt->status;
+    bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
+    bt_conn_unref(conn);
+    return;
+  }
 
-    if (!update_sec_level_br(conn)) {
-        bt_conn_unref(conn);
-        return;
-    }
+  conn->handle  = handle;
+  conn->err     = 0U;
+  conn->encrypt = evt->encr_enabled;
 
-    bt_conn_set_state(conn, BT_CONN_CONNECTED);
+  if (!update_sec_level_br(conn)) {
     bt_conn_unref(conn);
+    return;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_FEATURES, sizeof(*cp));
-    if (!buf) {
-        return;
-    }
+  bt_conn_set_state(conn, BT_CONN_CONNECTED);
+  bt_conn_unref(conn);
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = evt->handle;
+  buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_FEATURES, sizeof(*cp));
+  if (!buf) {
+    return;
+  }
 
-    bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_FEATURES, buf, NULL);
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = evt->handle;
+
+  bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_FEATURES, buf, NULL);
 }
 
-static void pin_code_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_pin_code_req *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void pin_code_req(struct net_buf *buf) {
+  struct bt_hci_evt_pin_code_req *evt = (void *)buf->data;
+  struct bt_conn                 *conn;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_pin_code_req(conn);
-    bt_conn_unref(conn);
+  bt_conn_pin_code_req(conn);
+  bt_conn_unref(conn);
 }
 
-static void link_key_notify(struct net_buf *buf)
-{
-    struct bt_hci_evt_link_key_notify *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void link_key_notify(struct net_buf *buf) {
+  struct bt_hci_evt_link_key_notify *evt = (void *)buf->data;
+  struct bt_conn                    *conn;
 
-    printf("bredr link key: ");
-    for (int i = 0; i < 16; i++) {
-        printf("0x%02x ", evt->link_key[i]);
-    }
-    printf("\n");
+  printf("bredr link key: ");
+  for (int i = 0; i < 16; i++) {
+    printf("0x%02x ", evt->link_key[i]);
+  }
+  printf("\n");
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
-
-    BT_DBG("%s, link type 0x%02x", bt_addr_str(&evt->bdaddr), evt->key_type);
-
-    if (!conn->br.link_key) {
-        conn->br.link_key = bt_keys_get_link_key(&evt->bdaddr);
-    }
-    if (!conn->br.link_key) {
-        BT_ERR("Can't update keys for %s", bt_addr_str(&evt->bdaddr));
-        bt_conn_unref(conn);
-        return;
-    }
-
-    /* clear any old Link Key flags */
-    conn->br.link_key->flags = 0U;
-
-    switch (evt->key_type) {
-        case BT_LK_COMBINATION:
-            /*
-		 * Setting Combination Link Key as AUTHENTICATED means it was
-		 * successfully generated by 16 digits wide PIN code.
-		 */
-            if (atomic_test_and_clear_bit(conn->flags,
-                                          BT_CONN_BR_LEGACY_SECURE)) {
-                conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
-            }
-            memcpy(conn->br.link_key->val, evt->link_key, 16);
-            break;
-        case BT_LK_AUTH_COMBINATION_P192:
-            conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
-            /* fall through */
-            __attribute__((fallthrough));
-        case BT_LK_UNAUTH_COMBINATION_P192:
-            /* Mark no-bond so that link-key is removed on disconnection */
-            if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) {
-                atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND);
-            }
-
-            memcpy(conn->br.link_key->val, evt->link_key, 16);
-            break;
-        case BT_LK_AUTH_COMBINATION_P256:
-            conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
-            /* fall through */
-            __attribute__((fallthrough));
-        case BT_LK_UNAUTH_COMBINATION_P256:
-            conn->br.link_key->flags |= BT_LINK_KEY_SC;
-
-            /* Mark no-bond so that link-key is removed on disconnection */
-            if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) {
-                atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND);
-            }
-
-            memcpy(conn->br.link_key->val, evt->link_key, 16);
-            break;
-        default:
-            BT_WARN("Unsupported Link Key type %u", evt->key_type);
-            (void)memset(conn->br.link_key->val, 0,
-                         sizeof(conn->br.link_key->val));
-            break;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_unref(conn);
-}
+  BT_DBG("%s, link type 0x%02x", bt_addr_str(&evt->bdaddr), evt->key_type);
 
-static void link_key_neg_reply(const bt_addr_t *bdaddr)
-{
-    struct bt_hci_cp_link_key_neg_reply *cp;
-    struct net_buf *buf;
+  if (!conn->br.link_key) {
+    conn->br.link_key = bt_keys_get_link_key(&evt->bdaddr);
+  }
+  if (!conn->br.link_key) {
+    BT_ERR("Can't update keys for %s", bt_addr_str(&evt->bdaddr));
+    bt_conn_unref(conn);
+    return;
+  }
 
-    BT_DBG("");
+  /* clear any old Link Key flags */
+  conn->br.link_key->flags = 0U;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_NEG_REPLY, sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Out of command buffers");
-        return;
-    }
+  switch (evt->key_type) {
+  case BT_LK_COMBINATION:
+    /*
+     * Setting Combination Link Key as AUTHENTICATED means it was
+     * successfully generated by 16 digits wide PIN code.
+     */
+    if (atomic_test_and_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE)) {
+      conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
+    }
+    memcpy(conn->br.link_key->val, evt->link_key, 16);
+    break;
+  case BT_LK_AUTH_COMBINATION_P192:
+    conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
+    /* fall through */
+    __attribute__((fallthrough));
+  case BT_LK_UNAUTH_COMBINATION_P192:
+    /* Mark no-bond so that link-key is removed on disconnection */
+    if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) {
+      atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND);
+    }
+
+    memcpy(conn->br.link_key->val, evt->link_key, 16);
+    break;
+  case BT_LK_AUTH_COMBINATION_P256:
+    conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED;
+    /* fall through */
+    __attribute__((fallthrough));
+  case BT_LK_UNAUTH_COMBINATION_P256:
+    conn->br.link_key->flags |= BT_LINK_KEY_SC;
+
+    /* Mark no-bond so that link-key is removed on disconnection */
+    if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) {
+      atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND);
+    }
+
+    memcpy(conn->br.link_key->val, evt->link_key, 16);
+    break;
+  default:
+    BT_WARN("Unsupported Link Key type %u", evt->key_type);
+    (void)memset(conn->br.link_key->val, 0, sizeof(conn->br.link_key->val));
+    break;
+  }
+
+  bt_conn_unref(conn);
+}
+
+static void link_key_neg_reply(const bt_addr_t *bdaddr) {
+  struct bt_hci_cp_link_key_neg_reply *cp;
+  struct net_buf                      *buf;
+
+  BT_DBG("");
+
+  buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Out of command buffers");
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_NEG_REPLY, buf, NULL);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_NEG_REPLY, buf, NULL);
 }
 
-static void link_key_reply(const bt_addr_t *bdaddr, const u8_t *lk)
-{
-    struct bt_hci_cp_link_key_reply *cp;
-    struct net_buf *buf;
+static void link_key_reply(const bt_addr_t *bdaddr, const u8_t *lk) {
+  struct bt_hci_cp_link_key_reply *cp;
+  struct net_buf                  *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_REPLY, sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Out of command buffers");
-        return;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_REPLY, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Out of command buffers");
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    memcpy(cp->link_key, lk, 16);
-    bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_REPLY, buf, NULL);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  memcpy(cp->link_key, lk, 16);
+  bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_REPLY, buf, NULL);
 }
 
-static void link_key_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_link_key_req *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void link_key_req(struct net_buf *buf) {
+  struct bt_hci_evt_link_key_req *evt = (void *)buf->data;
+  struct bt_conn                 *conn;
 
-    BT_DBG("%s", bt_addr_str(&evt->bdaddr));
+  BT_DBG("%s", bt_addr_str(&evt->bdaddr));
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        link_key_neg_reply(&evt->bdaddr);
-        return;
-    }
-
-    if (!conn->br.link_key) {
-        conn->br.link_key = bt_keys_find_link_key(&evt->bdaddr);
-    }
-
-    if (!conn->br.link_key) {
-        link_key_neg_reply(&evt->bdaddr);
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    link_key_neg_reply(&evt->bdaddr);
+    return;
+  }
 
-    /*
-	 * Enforce regenerate by controller stronger link key since found one
-	 * in database not covers requested security level.
-	 */
-    if (!(conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) &&
-        conn->required_sec_level > BT_SECURITY_L2) {
-        link_key_neg_reply(&evt->bdaddr);
-        bt_conn_unref(conn);
-        return;
-    }
+  if (!conn->br.link_key) {
+    conn->br.link_key = bt_keys_find_link_key(&evt->bdaddr);
+  }
 
-    link_key_reply(&evt->bdaddr, conn->br.link_key->val);
+  if (!conn->br.link_key) {
+    link_key_neg_reply(&evt->bdaddr);
     bt_conn_unref(conn);
+    return;
+  }
+
+  /*
+   * Enforce regenerate by controller stronger link key since found one
+   * in database not covers requested security level.
+   */
+  if (!(conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) && conn->required_sec_level > BT_SECURITY_L2) {
+    link_key_neg_reply(&evt->bdaddr);
+    bt_conn_unref(conn);
+    return;
+  }
+
+  link_key_reply(&evt->bdaddr, conn->br.link_key->val);
+  bt_conn_unref(conn);
 }
 
-static void io_capa_neg_reply(const bt_addr_t *bdaddr, const u8_t reason)
-{
-    struct bt_hci_cp_io_capability_neg_reply *cp;
-    struct net_buf *resp_buf;
+static void io_capa_neg_reply(const bt_addr_t *bdaddr, const u8_t reason) {
+  struct bt_hci_cp_io_capability_neg_reply *cp;
+  struct net_buf                           *resp_buf;
 
-    resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY,
-                                 sizeof(*cp));
-    if (!resp_buf) {
-        BT_ERR("Out of command buffers");
-        return;
-    }
+  resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, sizeof(*cp));
+  if (!resp_buf) {
+    BT_ERR("Out of command buffers");
+    return;
+  }
 
-    cp = net_buf_add(resp_buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, bdaddr);
-    cp->reason = reason;
-    bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, resp_buf, NULL);
+  cp = net_buf_add(resp_buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, bdaddr);
+  cp->reason = reason;
+  bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, resp_buf, NULL);
 }
 
-static void io_capa_resp(struct net_buf *buf)
-{
-    struct bt_hci_evt_io_capa_resp *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void io_capa_resp(struct net_buf *buf) {
+  struct bt_hci_evt_io_capa_resp *evt = (void *)buf->data;
+  struct bt_conn                 *conn;
 
-    BT_DBG("remote %s, IOcapa 0x%02x, auth 0x%02x",
-           bt_addr_str(&evt->bdaddr), evt->capability, evt->authentication);
+  BT_DBG("remote %s, IOcapa 0x%02x, auth 0x%02x", bt_addr_str(&evt->bdaddr), evt->capability, evt->authentication);
 
-    if (evt->authentication > BT_HCI_GENERAL_BONDING_MITM) {
-        BT_ERR("Invalid remote authentication requirements");
-        io_capa_neg_reply(&evt->bdaddr,
-                          BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL);
-        return;
-    }
+  if (evt->authentication > BT_HCI_GENERAL_BONDING_MITM) {
+    BT_ERR("Invalid remote authentication requirements");
+    io_capa_neg_reply(&evt->bdaddr, BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL);
+    return;
+  }
 
-    if (evt->capability > BT_IO_NO_INPUT_OUTPUT) {
-        BT_ERR("Invalid remote io capability requirements");
-        io_capa_neg_reply(&evt->bdaddr,
-                          BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL);
-        return;
-    }
+  if (evt->capability > BT_IO_NO_INPUT_OUTPUT) {
+    BT_ERR("Invalid remote io capability requirements");
+    io_capa_neg_reply(&evt->bdaddr, BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL);
+    return;
+  }
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    conn->br.remote_io_capa = evt->capability;
-    conn->br.remote_auth = evt->authentication;
-    atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING);
-    bt_conn_unref(conn);
+  conn->br.remote_io_capa = evt->capability;
+  conn->br.remote_auth    = evt->authentication;
+  atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING);
+  bt_conn_unref(conn);
 }
 
-static void io_capa_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_io_capa_req *evt = (void *)buf->data;
-    struct net_buf *resp_buf;
-    struct bt_conn *conn;
-    struct bt_hci_cp_io_capability_reply *cp;
-    u8_t auth;
-
-    BT_DBG("");
+static void io_capa_req(struct net_buf *buf) {
+  struct bt_hci_evt_io_capa_req        *evt = (void *)buf->data;
+  struct net_buf                       *resp_buf;
+  struct bt_conn                       *conn;
+  struct bt_hci_cp_io_capability_reply *cp;
+  u8_t                                  auth;
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  BT_DBG("");
 
-    resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_REPLY,
-                                 sizeof(*cp));
-    if (!resp_buf) {
-        BT_ERR("Out of command buffers");
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    /*
-	 * Set authentication requirements when acting as pairing initiator to
-	 * 'dedicated bond' with MITM protection set if local IO capa
-	 * potentially allows it, and for acceptor, based on local IO capa and
-	 * remote's authentication set.
-	 */
-    if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR)) {
-        if (bt_conn_get_io_capa() != BT_IO_NO_INPUT_OUTPUT) {
-            auth = BT_HCI_DEDICATED_BONDING_MITM;
-        } else {
-            auth = BT_HCI_DEDICATED_BONDING;
-        }
+  resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_REPLY, sizeof(*cp));
+  if (!resp_buf) {
+    BT_ERR("Out of command buffers");
+    bt_conn_unref(conn);
+    return;
+  }
+
+  /*
+   * Set authentication requirements when acting as pairing initiator to
+   * 'dedicated bond' with MITM protection set if local IO capa
+   * potentially allows it, and for acceptor, based on local IO capa and
+   * remote's authentication set.
+   */
+  if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR)) {
+    if (bt_conn_get_io_capa() != BT_IO_NO_INPUT_OUTPUT) {
+      auth = BT_HCI_DEDICATED_BONDING_MITM;
     } else {
-        auth = bt_conn_ssp_get_auth(conn);
+      auth = BT_HCI_DEDICATED_BONDING;
     }
+  } else {
+    auth = bt_conn_ssp_get_auth(conn);
+  }
 
-    cp = net_buf_add(resp_buf, sizeof(*cp));
-    bt_addr_copy(&cp->bdaddr, &evt->bdaddr);
-    cp->capability = bt_conn_get_io_capa();
-    cp->authentication = auth;
-    cp->oob_data = 0U;
-    bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_REPLY, resp_buf, NULL);
-    bt_conn_unref(conn);
+  cp = net_buf_add(resp_buf, sizeof(*cp));
+  bt_addr_copy(&cp->bdaddr, &evt->bdaddr);
+  cp->capability     = bt_conn_get_io_capa();
+  cp->authentication = auth;
+  cp->oob_data       = 0U;
+  bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_REPLY, resp_buf, NULL);
+  bt_conn_unref(conn);
 }
 
-static void ssp_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_ssp_complete *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void ssp_complete(struct net_buf *buf) {
+  struct bt_hci_evt_ssp_complete *evt = (void *)buf->data;
+  struct bt_conn                 *conn;
 
-    BT_DBG("status 0x%02x", evt->status);
+  BT_DBG("status 0x%02x", evt->status);
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_ssp_auth_complete(conn, security_err_get(evt->status));
-    if (evt->status) {
-        bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
-    }
+  bt_conn_ssp_auth_complete(conn, security_err_get(evt->status));
+  if (evt->status) {
+    bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void user_confirm_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_user_confirm_req *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void user_confirm_req(struct net_buf *buf) {
+  struct bt_hci_evt_user_confirm_req *evt = (void *)buf->data;
+  struct bt_conn                     *conn;
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey));
-    bt_conn_unref(conn);
+  bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey));
+  bt_conn_unref(conn);
 }
 
-static void user_passkey_notify(struct net_buf *buf)
-{
-    struct bt_hci_evt_user_passkey_notify *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void user_passkey_notify(struct net_buf *buf) {
+  struct bt_hci_evt_user_passkey_notify *evt = (void *)buf->data;
+  struct bt_conn                        *conn;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey));
-    bt_conn_unref(conn);
+  bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey));
+  bt_conn_unref(conn);
 }
 
-static void user_passkey_req(struct net_buf *buf)
-{
-    struct bt_hci_evt_user_passkey_req *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void user_passkey_req(struct net_buf *buf) {
+  struct bt_hci_evt_user_passkey_req *evt = (void *)buf->data;
+  struct bt_conn                     *conn;
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    bt_conn_ssp_auth(conn, 0);
-    bt_conn_unref(conn);
+  bt_conn_ssp_auth(conn, 0);
+  bt_conn_unref(conn);
 }
 
 struct discovery_priv {
-    u16_t clock_offset;
-    u8_t pscan_rep_mode;
-    u8_t resolving;
+  u16_t clock_offset;
+  u8_t  pscan_rep_mode;
+  u8_t  resolving;
 } __packed;
 
-static int request_name(const bt_addr_t *addr, u8_t pscan, u16_t offset)
-{
-    struct bt_hci_cp_remote_name_request *cp;
-    struct net_buf *buf;
+static int request_name(const bt_addr_t *addr, u8_t pscan, u16_t offset) {
+  struct bt_hci_cp_remote_name_request *cp;
+  struct net_buf                       *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_REQUEST, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_REQUEST, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    bt_addr_copy(&cp->bdaddr, addr);
-    cp->pscan_rep_mode = pscan;
-    cp->reserved = 0x00; /* reserver, should be set to 0x00 */
-    cp->clock_offset = offset;
+  bt_addr_copy(&cp->bdaddr, addr);
+  cp->pscan_rep_mode = pscan;
+  cp->reserved       = 0x00; /* reserver, should be set to 0x00 */
+  cp->clock_offset   = offset;
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_REQUEST, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_REQUEST, buf, NULL);
 }
 
-#define EIR_SHORT_NAME    0x08
-#define EIR_COMPLETE_NAME 0x09
+bredr_name_callback name_callback = NULL;
+int                 remote_name_req(const bt_addr_t *addr, bredr_name_callback cb) {
+  u8_t  pscan        = 0x01;
+  u16_t clock_offset = 0x00;
 
-static bool eir_has_name(const u8_t *eir)
-{
-    int len = 240;
+  name_callback = cb;
 
-    while (len) {
-        if (len < 2) {
-            break;
-        };
+  return request_name(addr, pscan, clock_offset);
+}
 
-        /* Look for early termination */
-        if (!eir[0]) {
-            break;
-        }
+void remote_name_complete(u8_t *name) {
+  if (name_callback) {
+    name_callback((const char *)name);
+  }
+}
 
-        /* Check if field length is correct */
-        if (eir[0] > len - 1) {
-            break;
-        }
+#define EIR_SHORT_NAME    0x08
+#define EIR_COMPLETE_NAME 0x09
 
-        switch (eir[1]) {
-            case EIR_SHORT_NAME:
-            case EIR_COMPLETE_NAME:
-                if (eir[0] > 1) {
-                    return true;
-                }
-                break;
-            default:
-                break;
-        }
+static bool eir_has_name(const u8_t *eir) {
+  int len = 240;
+
+  while (len) {
+    if (len < 2) {
+      break;
+    };
 
-        /* Parse next AD Structure */
-        len -= eir[0] + 1;
-        eir += eir[0] + 1;
+    /* Look for early termination */
+    if (!eir[0]) {
+      break;
     }
 
-    return false;
-}
+    /* Check if field length is correct */
+    if (eir[0] > len - 1) {
+      break;
+    }
 
-static void report_discovery_results(void)
-{
-    bool resolving_names = false;
-    int i;
+    switch (eir[1]) {
+    case EIR_SHORT_NAME:
+    case EIR_COMPLETE_NAME:
+      if (eir[0] > 1) {
+        return true;
+      }
+      break;
+    default:
+      break;
+    }
 
-    for (i = 0; i < discovery_results_count; i++) {
-        struct discovery_priv *priv;
+    /* Parse next AD Structure */
+    len -= eir[0] + 1;
+    eir += eir[0] + 1;
+  }
 
-        priv = (struct discovery_priv *)&discovery_results[i]._priv;
+  return false;
+}
 
-        if (eir_has_name(discovery_results[i].eir)) {
-            continue;
-        }
+static void report_discovery_results(void) {
+  bool resolving_names = false;
+  int  i;
 
-        if (request_name(&discovery_results[i].addr,
-                         priv->pscan_rep_mode, priv->clock_offset)) {
-            continue;
-        }
+  for (i = 0; i < discovery_results_count; i++) {
+    struct discovery_priv *priv;
+
+    priv = (struct discovery_priv *)&discovery_results[i]._priv;
 
-        priv->resolving = 1U;
-        resolving_names = true;
+    if (eir_has_name(discovery_results[i].eir)) {
+      continue;
     }
 
-    if (resolving_names) {
-        return;
+    if (request_name(&discovery_results[i].addr, priv->pscan_rep_mode, priv->clock_offset)) {
+      continue;
     }
 
-    atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
+    priv->resolving = 1U;
+    resolving_names = true;
+  }
 
-    discovery_cb(discovery_results, discovery_results_count);
+  if (resolving_names) {
+    return;
+  }
+
+  atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
 
-    discovery_cb = NULL;
-    discovery_results = NULL;
-    discovery_results_size = 0;
-    discovery_results_count = 0;
+  discovery_cb(discovery_results, discovery_results_count);
+
+  discovery_cb            = NULL;
+  discovery_results       = NULL;
+  discovery_results_size  = 0;
+  discovery_results_count = 0;
 }
 
-static void inquiry_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_inquiry_complete *evt = (void *)buf->data;
+static void inquiry_complete(struct net_buf *buf) {
+  struct bt_hci_evt_inquiry_complete *evt = (void *)buf->data;
 
-    if (evt->status) {
-        BT_ERR("Failed to complete inquiry");
-    }
+  if (evt->status) {
+    BT_ERR("Failed to complete inquiry");
+  }
 
-    report_discovery_results();
+  report_discovery_results();
 }
 
-static struct bt_br_discovery_result *get_result_slot(const bt_addr_t *addr,
-                                                      s8_t rssi)
-{
-    struct bt_br_discovery_result *result = NULL;
-    size_t i;
+static struct bt_br_discovery_result *get_result_slot(const bt_addr_t *addr, s8_t rssi) {
+  struct bt_br_discovery_result *result = NULL;
+  size_t                         i;
 
-    /* check if already present in results */
-    for (i = 0; i < discovery_results_count; i++) {
-        if (!bt_addr_cmp(addr, &discovery_results[i].addr)) {
-            return &discovery_results[i];
-        }
+  /* check if already present in results */
+  for (i = 0; i < discovery_results_count; i++) {
+    if (!bt_addr_cmp(addr, &discovery_results[i].addr)) {
+      return &discovery_results[i];
     }
+  }
 
-    /* Pick a new slot (if available) */
-    if (discovery_results_count < discovery_results_size) {
-        bt_addr_copy(&discovery_results[discovery_results_count].addr,
-                     addr);
-        return &discovery_results[discovery_results_count++];
-    }
+  /* Pick a new slot (if available) */
+  if (discovery_results_count < discovery_results_size) {
+    bt_addr_copy(&discovery_results[discovery_results_count].addr, addr);
+    return &discovery_results[discovery_results_count++];
+  }
 
-    /* ignore if invalid RSSI */
-    if (rssi == 0xff) {
-        return NULL;
-    }
+  /* ignore if invalid RSSI */
+  if (rssi == 0xff) {
+    return NULL;
+  }
 
-    /*
-	 * Pick slot with smallest RSSI that is smaller then passed RSSI
-	 * TODO handle TX if present
-	 */
-    for (i = 0; i < discovery_results_size; i++) {
-        if (discovery_results[i].rssi > rssi) {
-            continue;
-        }
+  /*
+   * Pick slot with smallest RSSI that is smaller then passed RSSI
+   * TODO handle TX if present
+   */
+  for (i = 0; i < discovery_results_size; i++) {
+    if (discovery_results[i].rssi > rssi) {
+      continue;
+    }
 
-        if (!result || result->rssi > discovery_results[i].rssi) {
-            result = &discovery_results[i];
-        }
+    if (!result || result->rssi > discovery_results[i].rssi) {
+      result = &discovery_results[i];
     }
+  }
 
-    if (result) {
-        BT_DBG("Reusing slot (old %s rssi %d dBm)",
-               bt_addr_str(&result->addr), result->rssi);
+  if (result) {
+    BT_DBG("Reusing slot (old %s rssi %d dBm)", bt_addr_str(&result->addr), result->rssi);
 
-        bt_addr_copy(&result->addr, addr);
-    }
+    bt_addr_copy(&result->addr, addr);
+  }
 
-    return result;
+  return result;
 }
 
-static void inquiry_result_with_rssi(struct net_buf *buf)
-{
-    u8_t num_reports = net_buf_pull_u8(buf);
+static void inquiry_result_with_rssi(struct net_buf *buf) {
+  u8_t num_reports = net_buf_pull_u8(buf);
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
-        return;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
+    return;
+  }
 
-    BT_DBG("number of results: %u", num_reports);
+  BT_DBG("number of results: %u", num_reports);
 
-    while (num_reports--) {
-        struct bt_hci_evt_inquiry_result_with_rssi *evt;
-        struct bt_br_discovery_result *result;
-        struct discovery_priv *priv;
+  while (num_reports--) {
+    struct bt_hci_evt_inquiry_result_with_rssi *evt;
+    struct bt_br_discovery_result              *result;
+    struct discovery_priv                      *priv;
 
-        if (buf->len < sizeof(*evt)) {
-            BT_ERR("Unexpected end to buffer");
-            return;
-        }
+    if (buf->len < sizeof(*evt)) {
+      BT_ERR("Unexpected end to buffer");
+      return;
+    }
 
-        evt = net_buf_pull_mem(buf, sizeof(*evt));
-        BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi);
+    evt = net_buf_pull_mem(buf, sizeof(*evt));
+    BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi);
 
-        result = get_result_slot(&evt->addr, evt->rssi);
-        if (!result) {
-            return;
-        }
+    result = get_result_slot(&evt->addr, evt->rssi);
+    if (!result) {
+      return;
+    }
 
-        priv = (struct discovery_priv *)&result->_priv;
-        priv->pscan_rep_mode = evt->pscan_rep_mode;
-        priv->clock_offset = evt->clock_offset;
+    priv                 = (struct discovery_priv *)&result->_priv;
+    priv->pscan_rep_mode = evt->pscan_rep_mode;
+    priv->clock_offset   = evt->clock_offset;
 
-        memcpy(result->cod, evt->cod, 3);
-        result->rssi = evt->rssi;
+    memcpy(result->cod, evt->cod, 3);
+    result->rssi = evt->rssi;
 
-        /* we could reuse slot so make sure EIR is cleared */
-        (void)memset(result->eir, 0, sizeof(result->eir));
-    }
+    /* we could reuse slot so make sure EIR is cleared */
+    (void)memset(result->eir, 0, sizeof(result->eir));
+  }
 }
 
-static void extended_inquiry_result(struct net_buf *buf)
-{
-    struct bt_hci_evt_extended_inquiry_result *evt = (void *)buf->data;
-    struct bt_br_discovery_result *result;
-    struct discovery_priv *priv;
+static void extended_inquiry_result(struct net_buf *buf) {
+  struct bt_hci_evt_extended_inquiry_result *evt = (void *)buf->data;
+  struct bt_br_discovery_result             *result;
+  struct discovery_priv                     *priv;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
-        return;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
+    return;
+  }
 
-    BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi);
+  BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi);
 
-    result = get_result_slot(&evt->addr, evt->rssi);
-    if (!result) {
-        return;
-    }
+  result = get_result_slot(&evt->addr, evt->rssi);
+  if (!result) {
+    return;
+  }
 
-    priv = (struct discovery_priv *)&result->_priv;
-    priv->pscan_rep_mode = evt->pscan_rep_mode;
-    priv->clock_offset = evt->clock_offset;
+  priv                 = (struct discovery_priv *)&result->_priv;
+  priv->pscan_rep_mode = evt->pscan_rep_mode;
+  priv->clock_offset   = evt->clock_offset;
 
-    result->rssi = evt->rssi;
-    memcpy(result->cod, evt->cod, 3);
-    memcpy(result->eir, evt->eir, sizeof(result->eir));
+  result->rssi = evt->rssi;
+  memcpy(result->cod, evt->cod, 3);
+  memcpy(result->eir, evt->eir, sizeof(result->eir));
 }
 
-static void remote_name_request_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_remote_name_req_complete *evt = (void *)buf->data;
-    struct bt_br_discovery_result *result;
-    struct discovery_priv *priv;
-    int eir_len = 240;
-    u8_t *eir;
-    int i;
+static void remote_name_request_complete(struct net_buf *buf) {
+  struct bt_hci_evt_remote_name_req_complete *evt = (void *)buf->data;
+  struct bt_br_discovery_result              *result;
+  struct discovery_priv                      *priv;
+  int                                         eir_len = 240;
+  u8_t                                       *eir;
+  int                                         i;
+  BT_DBG("remote name:%s", evt->name);
 
-    result = get_result_slot(&evt->bdaddr, 0xff);
-    if (!result) {
-        return;
-    }
+  if (evt->name) {
+    remote_name_complete(evt->name);
+  }
 
-    priv = (struct discovery_priv *)&result->_priv;
-    priv->resolving = 0U;
+  result = get_result_slot(&evt->bdaddr, 0xff);
+  if (!result) {
+    return;
+  }
 
-    if (evt->status) {
-        goto check_names;
-    }
+  priv            = (struct discovery_priv *)&result->_priv;
+  priv->resolving = 0U;
 
-    eir = result->eir;
+  if (evt->status) {
+    goto check_names;
+  }
 
-    while (eir_len) {
-        if (eir_len < 2) {
-            break;
-        };
+  eir = result->eir;
 
-        /* Look for early termination */
-        if (!eir[0]) {
-            size_t name_len;
+  while (eir_len) {
+    if (eir_len < 2) {
+      break;
+    };
 
-            eir_len -= 2;
+    /* Look for early termination */
+    if (!eir[0]) {
+      size_t name_len;
 
-            /* name is null terminated */
-            name_len = strlen((const char *)evt->name);
+      eir_len -= 2;
 
-            if (name_len > eir_len) {
-                eir[0] = eir_len + 1;
-                eir[1] = EIR_SHORT_NAME;
-            } else {
-                eir[0] = name_len + 1;
-                eir[1] = EIR_SHORT_NAME;
-            }
+      /* name is null terminated */
+      name_len = strlen((const char *)evt->name);
 
-            memcpy(&eir[2], evt->name, eir[0] - 1);
+      if (name_len > eir_len) {
+        eir[0] = eir_len + 1;
+        eir[1] = EIR_SHORT_NAME;
+      } else {
+        eir[0] = name_len + 1;
+        eir[1] = EIR_SHORT_NAME;
+      }
 
-            break;
-        }
+      memcpy(&eir[2], evt->name, eir[0] - 1);
 
-        /* Check if field length is correct */
-        if (eir[0] > eir_len - 1) {
-            break;
-        }
+      break;
+    }
 
-        /* next EIR Structure */
-        eir_len -= eir[0] + 1;
-        eir += eir[0] + 1;
+    /* Check if field length is correct */
+    if (eir[0] > eir_len - 1) {
+      break;
     }
 
+    /* next EIR Structure */
+    eir_len -= eir[0] + 1;
+    eir += eir[0] + 1;
+  }
+
 check_names:
-    /* if still waiting for names */
-    for (i = 0; i < discovery_results_count; i++) {
-        struct discovery_priv *priv;
+  /* if still waiting for names */
+  for (i = 0; i < discovery_results_count; i++) {
+    struct discovery_priv *priv;
 
-        priv = (struct discovery_priv *)&discovery_results[i]._priv;
+    priv = (struct discovery_priv *)&discovery_results[i]._priv;
 
-        if (priv->resolving) {
-            return;
-        }
+    if (priv->resolving) {
+      return;
     }
+  }
 
-    /* all names resolved, report discovery results */
-    atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
+  /* all names resolved, report discovery results */
+  atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
 
-    discovery_cb(discovery_results, discovery_results_count);
+  discovery_cb(discovery_results, discovery_results_count);
 
-    discovery_cb = NULL;
-    discovery_results = NULL;
-    discovery_results_size = 0;
-    discovery_results_count = 0;
+  discovery_cb            = NULL;
+  discovery_results       = NULL;
+  discovery_results_size  = 0;
+  discovery_results_count = 0;
 }
 
-static void link_encr(const u16_t handle)
-{
-    struct bt_hci_cp_set_conn_encrypt *encr;
-    struct net_buf *buf;
+static void link_encr(const u16_t handle) {
+  struct bt_hci_cp_set_conn_encrypt *encr;
+  struct net_buf                    *buf;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_SET_CONN_ENCRYPT, sizeof(*encr));
-    if (!buf) {
-        BT_ERR("Out of command buffers");
-        return;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_SET_CONN_ENCRYPT, sizeof(*encr));
+  if (!buf) {
+    BT_ERR("Out of command buffers");
+    return;
+  }
 
-    encr = net_buf_add(buf, sizeof(*encr));
-    encr->handle = sys_cpu_to_le16(handle);
-    encr->encrypt = 0x01;
+  encr          = net_buf_add(buf, sizeof(*encr));
+  encr->handle  = sys_cpu_to_le16(handle);
+  encr->encrypt = 0x01;
 
-    bt_hci_cmd_send_sync(BT_HCI_OP_SET_CONN_ENCRYPT, buf, NULL);
+  bt_hci_cmd_send_sync(BT_HCI_OP_SET_CONN_ENCRYPT, buf, NULL);
 }
 
-static void auth_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_auth_complete *evt = (void *)buf->data;
-    struct bt_conn *conn;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
+static void auth_complete(struct net_buf *buf) {
+  struct bt_hci_evt_auth_complete *evt = (void *)buf->data;
+  struct bt_conn                  *conn;
+  u16_t                            handle = sys_le16_to_cpu(evt->handle);
 
-    BT_DBG("status 0x%02x, handle %u", evt->status, handle);
+  BT_DBG("status 0x%02x, handle %u", evt->status, handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Can't find conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Can't find conn for handle %u", handle);
+    return;
+  }
 
-    if (evt->status) {
-        if (conn->state == BT_CONN_CONNECTED) {
-            /*
-			 * Inform layers above HCI about non-zero authentication
-			 * status to make them able cleanup pending jobs.
-			 */
-            bt_l2cap_encrypt_change(conn, evt->status);
-        }
-        reset_pairing(conn);
-    } else {
-        link_encr(handle);
+  if (evt->status) {
+    if (conn->state == BT_CONN_CONNECTED) {
+      /*
+       * Inform layers above HCI about non-zero authentication
+       * status to make them able cleanup pending jobs.
+       */
+      bt_l2cap_encrypt_change(conn, evt->status);
     }
+    reset_pairing(conn);
+  } else {
+    link_encr(handle);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void read_remote_features_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_remote_features *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_hci_cp_read_remote_ext_features *cp;
-    struct bt_conn *conn;
+static void read_remote_features_complete(struct net_buf *buf) {
+  struct bt_hci_evt_remote_features         *evt    = (void *)buf->data;
+  u16_t                                      handle = sys_le16_to_cpu(evt->handle);
+  struct bt_hci_cp_read_remote_ext_features *cp;
+  struct bt_conn                            *conn;
 
-    BT_DBG("status 0x%02x handle %u", evt->status, handle);
+  BT_DBG("status 0x%02x handle %u", evt->status, handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Can't find conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Can't find conn for handle %u", handle);
+    return;
+  }
 
-    if (evt->status) {
-        goto done;
-    }
+  if (evt->status) {
+    goto done;
+  }
 
-    memcpy(conn->br.features[0], evt->features, sizeof(evt->features));
+  memcpy(conn->br.features[0], evt->features, sizeof(evt->features));
 
-    if (!BT_FEAT_EXT_FEATURES(conn->br.features)) {
-        goto done;
-    }
+  if (!BT_FEAT_EXT_FEATURES(conn->br.features)) {
+    goto done;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_EXT_FEATURES,
-                            sizeof(*cp));
-    if (!buf) {
-        goto done;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, sizeof(*cp));
+  if (!buf) {
+    goto done;
+  }
 
-    /* Read remote host features (page 1) */
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = evt->handle;
-    cp->page = 0x01;
+  /* Read remote host features (page 1) */
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = evt->handle;
+  cp->page   = 0x01;
 
-    bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, buf, NULL);
+  bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, buf, NULL);
 
 done:
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void read_remote_ext_features_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_remote_ext_features *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
+static void read_remote_ext_features_complete(struct net_buf *buf) {
+  struct bt_hci_evt_remote_ext_features *evt    = (void *)buf->data;
+  u16_t                                  handle = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                        *conn;
 
-    BT_DBG("status 0x%02x handle %u", evt->status, handle);
+  BT_DBG("status 0x%02x handle %u", evt->status, handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Can't find conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Can't find conn for handle %u", handle);
+    return;
+  }
 
-    if (!evt->status && evt->page == 0x01) {
-        memcpy(conn->br.features[1], evt->features,
-               sizeof(conn->br.features[1]));
-    }
+  if (!evt->status && evt->page == 0x01) {
+    memcpy(conn->br.features[1], evt->features, sizeof(conn->br.features[1]));
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void role_change(struct net_buf *buf)
-{
-    struct bt_hci_evt_role_change *evt = (void *)buf->data;
-    struct bt_conn *conn;
+static void role_change(struct net_buf *buf) {
+  struct bt_hci_evt_role_change *evt = (void *)buf->data;
+  struct bt_conn                *conn;
 
-    BT_DBG("status 0x%02x role %u addr %s", evt->status, evt->role,
-           bt_addr_str(&evt->bdaddr));
+  BT_DBG("status 0x%02x role %u addr %s", evt->status, evt->role, bt_addr_str(&evt->bdaddr));
 
-    if (evt->status) {
-        return;
-    }
+  if (evt->status) {
+    return;
+  }
 
-    conn = bt_conn_lookup_addr_br(&evt->bdaddr);
-    if (!conn) {
-        BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
-        return;
-    }
+  conn = bt_conn_lookup_addr_br(&evt->bdaddr);
+  if (!conn) {
+    BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr));
+    return;
+  }
 
-    if (evt->role) {
-        conn->role = BT_CONN_ROLE_SLAVE;
-    } else {
-        conn->role = BT_CONN_ROLE_MASTER;
-    }
+  if (evt->role) {
+    conn->role = BT_CONN_ROLE_SLAVE;
+  } else {
+    conn->role = BT_CONN_ROLE_MASTER;
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 #endif /* CONFIG_BT_BREDR */
 
 #if defined(CONFIG_BT_SMP)
-static int le_set_privacy_mode(const bt_addr_le_t *addr, u8_t mode)
-{
-    struct bt_hci_cp_le_set_privacy_mode cp;
-    struct net_buf *buf;
-    int err;
-
-    /* Check if set privacy mode command is supported */
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 39, 2)) {
-        BT_WARN("Set privacy mode command is not supported");
-        return 0;
-    }
+static int le_set_privacy_mode(const bt_addr_le_t *addr, u8_t mode) {
+  struct bt_hci_cp_le_set_privacy_mode cp;
+  struct net_buf                      *buf;
+  int                                  err;
+
+  /* Check if set privacy mode command is supported */
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 39, 2)) {
+    BT_WARN("Set privacy mode command is not supported");
+    return 0;
+  }
 
-    BT_DBG("addr %s mode 0x%02x", bt_addr_le_str(addr), mode);
+  BT_DBG("addr %s mode 0x%02x", bt_addr_le_str(addr), mode);
 
-    bt_addr_le_copy(&cp.id_addr, addr);
-    cp.mode = mode;
+  bt_addr_le_copy(&cp.id_addr, addr);
+  cp.mode = mode;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PRIVACY_MODE, sizeof(cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PRIVACY_MODE, sizeof(cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_mem(buf, &cp, sizeof(cp));
+  net_buf_add_mem(buf, &cp, sizeof(cp));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PRIVACY_MODE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PRIVACY_MODE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 #if defined(CONFIG_BT_STACK_PTS)
 int addr_res_enable(u8_t enable)
@@ -3167,19 +3140,18 @@ int addr_res_enable(u8_t enable)
 static int addr_res_enable(u8_t enable)
 #endif
 {
-    struct net_buf *buf;
+  struct net_buf *buf;
 
-    BT_DBG("%s", enable ? "enabled" : "disabled");
+  BT_DBG("%s", enable ? "enabled" : "disabled");
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, 1);
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, 1);
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_u8(buf, enable);
+  net_buf_add_u8(buf, enable);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE,
-                                buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, buf, NULL);
 }
 
 #if defined(CONFIG_BT_STACK_PTS)
@@ -3188,1896 +3160,1861 @@ int hci_id_add(const bt_addr_le_t *addr, u8_t val[16])
 static int hci_id_add(const bt_addr_le_t *addr, u8_t val[16])
 #endif
 {
-    struct bt_hci_cp_le_add_dev_to_rl *cp;
-    struct net_buf *buf;
+  struct bt_hci_cp_le_add_dev_to_rl *cp;
+  struct net_buf                    *buf;
 
-    BT_DBG("addr %s", bt_addr_le_str(addr));
+  BT_DBG("addr %s", bt_addr_le_str(addr));
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_RL, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_RL, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_le_copy(&cp->peer_id_addr, addr);
-    memcpy(cp->peer_irk, val, 16);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_le_copy(&cp->peer_id_addr, addr);
+  memcpy(cp->peer_irk, val, 16);
 
 #if defined(CONFIG_BT_PRIVACY)
-    memcpy(cp->local_irk, bt_dev.irk, 16);
+  memcpy(cp->local_irk, bt_dev.irk, 16);
 #else
-    (void)memset(cp->local_irk, 0, 16);
+  (void)memset(cp->local_irk, 0, 16);
 #endif
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_RL, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_RL, buf, NULL);
 }
 
-void bt_id_add(struct bt_keys *keys)
-{
-    bool adv_enabled;
+void bt_id_add(struct bt_keys *keys) {
+  bool adv_enabled;
 #if defined(CONFIG_BT_OBSERVER)
-    bool scan_enabled;
+  bool scan_enabled;
 #endif /* CONFIG_BT_OBSERVER */
-    struct bt_conn *conn;
-    int err;
+  struct bt_conn *conn;
+  int             err;
 
-    BT_DBG("addr %s", bt_addr_le_str(&keys->addr));
+  BT_DBG("addr %s", bt_addr_le_str(&keys->addr));
 
-    /* Nothing to be done if host-side resolving is used */
-    if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) {
-        bt_dev.le.rl_entries++;
-        return;
-    }
+  /* Nothing to be done if host-side resolving is used */
+  if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) {
+    bt_dev.le.rl_entries++;
+    return;
+  }
 
-    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
-    if (conn) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING);
-        keys->flags |= BT_KEYS_ID_PENDING_ADD;
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
+  if (conn) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING);
+    keys->flags |= BT_KEYS_ID_PENDING_ADD;
+    bt_conn_unref(conn);
+    return;
+  }
 
-    adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING);
-    if (adv_enabled) {
-        set_advertise_enable(false);
-    }
+  adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING);
+  if (adv_enabled) {
+    set_advertise_enable(false);
+  }
 
 #if defined(CONFIG_BT_OBSERVER)
-    scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
-    if (scan_enabled) {
-        set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-    }
+  scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
+  if (scan_enabled) {
+    set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+  }
 #endif /* CONFIG_BT_OBSERVER */
 
-    /* If there are any existing entries address resolution will be on */
-    if (bt_dev.le.rl_entries) {
-        err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
-        if (err) {
-            BT_WARN("Failed to disable address resolution");
-            goto done;
-        }
+  /* If there are any existing entries address resolution will be on */
+  if (bt_dev.le.rl_entries) {
+    err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
+    if (err) {
+      BT_WARN("Failed to disable address resolution");
+      goto done;
     }
+  }
 
-    if (bt_dev.le.rl_entries == bt_dev.le.rl_size) {
-        BT_WARN("Resolving list size exceeded. Switching to host.");
-
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_RL, NULL, NULL);
-        if (err) {
-            BT_ERR("Failed to clear resolution list");
-            goto done;
-        }
-
-        bt_dev.le.rl_entries++;
-
-        goto done;
-    }
+  if (bt_dev.le.rl_entries == bt_dev.le.rl_size) {
+    BT_WARN("Resolving list size exceeded. Switching to host.");
 
-    err = hci_id_add(&keys->addr, keys->irk.val);
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_RL, NULL, NULL);
     if (err) {
-        BT_ERR("Failed to add IRK to controller");
-        goto done;
+      BT_ERR("Failed to clear resolution list");
+      goto done;
     }
 
     bt_dev.le.rl_entries++;
 
-    /*
-	 * According to Core Spec. 5.0 Vol 1, Part A 5.4.5 Privacy Feature
-	 *
-	 * By default, network privacy mode is used when private addresses are
-	 * resolved and generated by the Controller, so advertising packets from
-	 * peer devices that contain private addresses will only be accepted.
-	 * By changing to the device privacy mode device is only concerned about
-	 * its privacy and will accept advertising packets from peer devices
-	 * that contain their identity address as well as ones that contain
-	 * a private address, even if the peer device has distributed its IRK in
-	 * the past.
-	 */
-    err = le_set_privacy_mode(&keys->addr, BT_HCI_LE_PRIVACY_MODE_DEVICE);
-    if (err) {
-        BT_ERR("Failed to set privacy mode");
-        goto done;
-    }
+    goto done;
+  }
+
+  err = hci_id_add(&keys->addr, keys->irk.val);
+  if (err) {
+    BT_ERR("Failed to add IRK to controller");
+    goto done;
+  }
+
+  bt_dev.le.rl_entries++;
+
+  /*
+   * According to Core Spec. 5.0 Vol 1, Part A 5.4.5 Privacy Feature
+   *
+   * By default, network privacy mode is used when private addresses are
+   * resolved and generated by the Controller, so advertising packets from
+   * peer devices that contain private addresses will only be accepted.
+   * By changing to the device privacy mode device is only concerned about
+   * its privacy and will accept advertising packets from peer devices
+   * that contain their identity address as well as ones that contain
+   * a private address, even if the peer device has distributed its IRK in
+   * the past.
+   */
+  err = le_set_privacy_mode(&keys->addr, BT_HCI_LE_PRIVACY_MODE_DEVICE);
+  if (err) {
+    BT_ERR("Failed to set privacy mode");
+    goto done;
+  }
 
 done:
-    addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
+  addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
 
 #if defined(CONFIG_BT_OBSERVER)
-    if (scan_enabled) {
-        set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
-    }
+  if (scan_enabled) {
+    set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
+  }
 #endif /* CONFIG_BT_OBSERVER */
 
-    if (adv_enabled) {
-        set_advertise_enable(true);
-    }
+  if (adv_enabled) {
+    set_advertise_enable(true);
+  }
 }
 
-static void keys_add_id(struct bt_keys *keys, void *data)
-{
-    hci_id_add(&keys->addr, keys->irk.val);
-}
+static void keys_add_id(struct bt_keys *keys, void *data) { hci_id_add(&keys->addr, keys->irk.val); }
 
-void bt_id_del(struct bt_keys *keys)
-{
-    struct bt_hci_cp_le_rem_dev_from_rl *cp;
-    bool adv_enabled;
+void bt_id_del(struct bt_keys *keys) {
+  struct bt_hci_cp_le_rem_dev_from_rl *cp;
+  bool                                 adv_enabled;
 #if defined(CONFIG_BT_OBSERVER)
-    bool scan_enabled;
+  bool scan_enabled;
 #endif /* CONFIG_BT_OBSERVER */
-    struct bt_conn *conn;
-    struct net_buf *buf;
-    int err;
+  struct bt_conn *conn;
+  struct net_buf *buf;
+  int             err;
 
-    BT_DBG("addr %s", bt_addr_le_str(&keys->addr));
+  BT_DBG("addr %s", bt_addr_le_str(&keys->addr));
 
-    if (!bt_dev.le.rl_size ||
-        bt_dev.le.rl_entries > bt_dev.le.rl_size + 1) {
-        bt_dev.le.rl_entries--;
-        return;
-    }
+  if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size + 1) {
+    bt_dev.le.rl_entries--;
+    return;
+  }
 
-    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
-    if (conn) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING);
-        keys->flags |= BT_KEYS_ID_PENDING_DEL;
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
+  if (conn) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING);
+    keys->flags |= BT_KEYS_ID_PENDING_DEL;
+    bt_conn_unref(conn);
+    return;
+  }
 
-    adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING);
-    if (adv_enabled) {
-        set_advertise_enable(false);
-    }
+  adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING);
+  if (adv_enabled) {
+    set_advertise_enable(false);
+  }
 
 #if defined(CONFIG_BT_OBSERVER)
-    scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
-    if (scan_enabled) {
-        set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-    }
+  scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
+  if (scan_enabled) {
+    set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+  }
 #endif /* CONFIG_BT_OBSERVER */
 
-    err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
-    if (err) {
-        BT_ERR("Disabling address resolution failed (err %d)", err);
-        goto done;
-    }
+  err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
+  if (err) {
+    BT_ERR("Disabling address resolution failed (err %d)", err);
+    goto done;
+  }
 
-    /* We checked size + 1 earlier, so here we know we can fit again */
-    if (bt_dev.le.rl_entries > bt_dev.le.rl_size) {
-        bt_dev.le.rl_entries--;
-        keys->keys &= ~BT_KEYS_IRK;
-        bt_keys_foreach(BT_KEYS_IRK, keys_add_id, NULL);
-        goto done;
-    }
+  /* We checked size + 1 earlier, so here we know we can fit again */
+  if (bt_dev.le.rl_entries > bt_dev.le.rl_size) {
+    bt_dev.le.rl_entries--;
+    keys->keys &= ~BT_KEYS_IRK;
+    bt_keys_foreach(BT_KEYS_IRK, keys_add_id, NULL);
+    goto done;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_RL, sizeof(*cp));
-    if (!buf) {
-        goto done;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_RL, sizeof(*cp));
+  if (!buf) {
+    goto done;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_le_copy(&cp->peer_id_addr, &keys->addr);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_le_copy(&cp->peer_id_addr, &keys->addr);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_RL, buf, NULL);
-    if (err) {
-        BT_ERR("Failed to remove IRK from controller");
-        goto done;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_RL, buf, NULL);
+  if (err) {
+    BT_ERR("Failed to remove IRK from controller");
+    goto done;
+  }
 
-    bt_dev.le.rl_entries--;
+  bt_dev.le.rl_entries--;
 
 done:
-    /* Only re-enable if there are entries to do resolving with */
-    if (bt_dev.le.rl_entries) {
-        addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
-    }
+  /* Only re-enable if there are entries to do resolving with */
+  if (bt_dev.le.rl_entries) {
+    addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
+  }
 
 #if defined(CONFIG_BT_OBSERVER)
-    if (scan_enabled) {
-        set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
-    }
+  if (scan_enabled) {
+    set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
+  }
 #endif /* CONFIG_BT_OBSERVER */
 
-    if (adv_enabled) {
-        set_advertise_enable(true);
-    }
+  if (adv_enabled) {
+    set_advertise_enable(true);
+  }
 }
 
-static void update_sec_level(struct bt_conn *conn)
-{
-    if (!conn->encrypt) {
-        conn->sec_level = BT_SECURITY_L1;
-        return;
-    }
+static void update_sec_level(struct bt_conn *conn) {
+  if (!conn->encrypt) {
+    conn->sec_level = BT_SECURITY_L1;
+    return;
+  }
 
-    if (conn->le.keys && (conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) {
-        if (conn->le.keys->flags & BT_KEYS_SC &&
-            conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE) {
-            conn->sec_level = BT_SECURITY_L4;
-        } else {
-            conn->sec_level = BT_SECURITY_L3;
-        }
+  if (conn->le.keys && (conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) {
+    if (conn->le.keys->flags & BT_KEYS_SC && conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE) {
+      conn->sec_level = BT_SECURITY_L4;
     } else {
-        conn->sec_level = BT_SECURITY_L2;
+      conn->sec_level = BT_SECURITY_L3;
     }
+  } else {
+    conn->sec_level = BT_SECURITY_L2;
+  }
 
-    if (conn->required_sec_level > conn->sec_level) {
-        BT_ERR("Failed to set required security level");
-        bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
-    }
+  if (conn->required_sec_level > conn->sec_level) {
+    BT_ERR("Failed to set required security level");
+    bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL);
+  }
 }
 #endif /* CONFIG_BT_SMP */
 
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-static void hci_encrypt_change(struct net_buf *buf)
-{
-    struct bt_hci_evt_encrypt_change *evt = (void *)buf->data;
-    u16_t handle = sys_le16_to_cpu(evt->handle);
-    struct bt_conn *conn;
+static void hci_encrypt_change(struct net_buf *buf) {
+  struct bt_hci_evt_encrypt_change *evt    = (void *)buf->data;
+  u16_t                             handle = sys_le16_to_cpu(evt->handle);
+  struct bt_conn                   *conn;
 
-    BT_DBG("status 0x%02x handle %u encrypt 0x%02x", evt->status, handle,
-           evt->encrypt);
+  BT_DBG("status 0x%02x handle %u encrypt 0x%02x", evt->status, handle, evt->encrypt);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to look up conn with handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to look up conn with handle %u", handle);
+    return;
+  }
 
-    if (evt->status) {
-        reset_pairing(conn);
-        bt_l2cap_encrypt_change(conn, evt->status);
-        bt_conn_security_changed(conn, security_err_get(evt->status));
-        bt_conn_unref(conn);
-        return;
-    }
+  if (evt->status) {
+    reset_pairing(conn);
+    bt_l2cap_encrypt_change(conn, evt->status);
+    bt_conn_security_changed(conn, security_err_get(evt->status));
+    bt_conn_unref(conn);
+    return;
+  }
 
-    conn->encrypt = evt->encrypt;
+  conn->encrypt = evt->encrypt;
 
 #if defined(CONFIG_BT_SMP)
-    if (conn->type == BT_CONN_TYPE_LE) {
-        /*
-		 * we update keys properties only on successful encryption to
-		 * avoid losing valid keys if encryption was not successful.
-		 *
-		 * Update keys with last pairing info for proper sec level
-		 * update. This is done only for LE transport, for BR/EDR keys
-		 * are updated on HCI 'Link Key Notification Event'
-		 */
-        if (conn->encrypt) {
-            bt_smp_update_keys(conn);
-        }
-        update_sec_level(conn);
+  if (conn->type == BT_CONN_TYPE_LE) {
+    /*
+     * we update keys properties only on successful encryption to
+     * avoid losing valid keys if encryption was not successful.
+     *
+     * Update keys with last pairing info for proper sec level
+     * update. This is done only for LE transport, for BR/EDR keys
+     * are updated on HCI 'Link Key Notification Event'
+     */
+    if (conn->encrypt) {
+      bt_smp_update_keys(conn);
     }
+    update_sec_level(conn);
+  }
 #endif /* CONFIG_BT_SMP */
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        if (!update_sec_level_br(conn)) {
-            bt_conn_unref(conn);
-            return;
-        }
-
-        if (IS_ENABLED(CONFIG_BT_SMP)) {
-            /*
-			 * Start SMP over BR/EDR if we are pairing and are
-			 * master on the link
-			 */
-            if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING) &&
-                conn->role == BT_CONN_ROLE_MASTER) {
-                bt_smp_br_send_pairing_req(conn);
-            }
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    if (!update_sec_level_br(conn)) {
+      bt_conn_unref(conn);
+      return;
     }
+
+    if (IS_ENABLED(CONFIG_BT_SMP)) {
+      /*
+       * Start SMP over BR/EDR if we are pairing and are
+       * master on the link
+       */
+      if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING) && conn->role == BT_CONN_ROLE_MASTER) {
+        bt_smp_br_send_pairing_req(conn);
+      }
+    }
+  }
 #endif /* CONFIG_BT_BREDR */
-    reset_pairing(conn);
+  reset_pairing(conn);
 
-    bt_l2cap_encrypt_change(conn, evt->status);
-    bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS);
+  bt_l2cap_encrypt_change(conn, evt->status);
+  bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS);
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 
-static void hci_encrypt_key_refresh_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_encrypt_key_refresh_complete *evt = (void *)buf->data;
-    struct bt_conn *conn;
-    u16_t handle;
+static void hci_encrypt_key_refresh_complete(struct net_buf *buf) {
+  struct bt_hci_evt_encrypt_key_refresh_complete *evt = (void *)buf->data;
+  struct bt_conn                                 *conn;
+  u16_t                                           handle;
 
-    handle = sys_le16_to_cpu(evt->handle);
+  handle = sys_le16_to_cpu(evt->handle);
 
-    BT_DBG("status 0x%02x handle %u", evt->status, handle);
-
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to look up conn with handle %u", handle);
-        return;
-    }
+  BT_DBG("status 0x%02x handle %u", evt->status, handle);
 
-    if (evt->status) {
-        reset_pairing(conn);
-        bt_l2cap_encrypt_change(conn, evt->status);
-        bt_conn_security_changed(conn, security_err_get(evt->status));
-        bt_conn_unref(conn);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to look up conn with handle %u", handle);
+    return;
+  }
 
-    /*
-	 * Update keys with last pairing info for proper sec level update.
-	 * This is done only for LE transport. For BR/EDR transport keys are
-	 * updated on HCI 'Link Key Notification Event', therefore update here
-	 * only security level based on available keys and encryption state.
-	 */
+  if (evt->status) {
+    reset_pairing(conn);
+    bt_l2cap_encrypt_change(conn, evt->status);
+    bt_conn_security_changed(conn, security_err_get(evt->status));
+    bt_conn_unref(conn);
+    return;
+  }
+
+  /*
+   * Update keys with last pairing info for proper sec level update.
+   * This is done only for LE transport. For BR/EDR transport keys are
+   * updated on HCI 'Link Key Notification Event', therefore update here
+   * only security level based on available keys and encryption state.
+   */
 #if defined(CONFIG_BT_SMP)
-    if (conn->type == BT_CONN_TYPE_LE) {
-        bt_smp_update_keys(conn);
-        update_sec_level(conn);
-    }
+  if (conn->type == BT_CONN_TYPE_LE) {
+    bt_smp_update_keys(conn);
+    update_sec_level(conn);
+  }
 #endif /* CONFIG_BT_SMP */
 #if defined(CONFIG_BT_BREDR)
-    if (conn->type == BT_CONN_TYPE_BR) {
-        if (!update_sec_level_br(conn)) {
-            bt_conn_unref(conn);
-            return;
-        }
+  if (conn->type == BT_CONN_TYPE_BR) {
+    if (!update_sec_level_br(conn)) {
+      bt_conn_unref(conn);
+      return;
     }
+  }
 #endif /* CONFIG_BT_BREDR */
 
-    reset_pairing(conn);
-    bt_l2cap_encrypt_change(conn, evt->status);
-    bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS);
-    bt_conn_unref(conn);
+  reset_pairing(conn);
+  bt_l2cap_encrypt_change(conn, evt->status);
+  bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS);
+  bt_conn_unref(conn);
 }
 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
 
 #if defined(CONFIG_BT_SMP)
-static void le_ltk_neg_reply(u16_t handle)
-{
-    struct bt_hci_cp_le_ltk_req_neg_reply *cp;
-    struct net_buf *buf;
+static void le_ltk_neg_reply(u16_t handle) {
+  struct bt_hci_cp_le_ltk_req_neg_reply *cp;
+  struct net_buf                        *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Out of command buffers");
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Out of command buffers");
 
-        return;
-    }
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(handle);
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(handle);
 
-    bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, buf);
+  bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, buf);
 }
 
-static void le_ltk_reply(u16_t handle, u8_t *ltk)
-{
-    struct bt_hci_cp_le_ltk_req_reply *cp;
-    struct net_buf *buf;
+static void le_ltk_reply(u16_t handle, u8_t *ltk) {
+  struct bt_hci_cp_le_ltk_req_reply *cp;
+  struct net_buf                    *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_REPLY,
-                            sizeof(*cp));
-    if (!buf) {
-        BT_ERR("Out of command buffers");
-        return;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_REPLY, sizeof(*cp));
+  if (!buf) {
+    BT_ERR("Out of command buffers");
+    return;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    cp->handle = sys_cpu_to_le16(handle);
-    memcpy(cp->ltk, ltk, sizeof(cp->ltk));
+  cp         = net_buf_add(buf, sizeof(*cp));
+  cp->handle = sys_cpu_to_le16(handle);
+  memcpy(cp->ltk, ltk, sizeof(cp->ltk));
 
-    bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_REPLY, buf);
+  bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_REPLY, buf);
 }
 
-static void le_ltk_request(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_ltk_request *evt = (void *)buf->data;
-    struct bt_conn *conn;
-    u16_t handle;
-    u8_t ltk[16];
+static void le_ltk_request(struct net_buf *buf) {
+  struct bt_hci_evt_le_ltk_request *evt = (void *)buf->data;
+  struct bt_conn                   *conn;
+  u16_t                             handle;
+  u8_t                              ltk[16];
 
-    handle = sys_le16_to_cpu(evt->handle);
+  handle = sys_le16_to_cpu(evt->handle);
 
-    BT_DBG("handle %u", handle);
+  BT_DBG("handle %u", handle);
 
-    conn = bt_conn_lookup_handle(handle);
-    if (!conn) {
-        BT_ERR("Unable to lookup conn for handle %u", handle);
-        return;
-    }
+  conn = bt_conn_lookup_handle(handle);
+  if (!conn) {
+    BT_ERR("Unable to lookup conn for handle %u", handle);
+    return;
+  }
 
-    if (bt_smp_request_ltk(conn, evt->rand, evt->ediv, ltk)) {
-        le_ltk_reply(handle, ltk);
-    } else {
-        le_ltk_neg_reply(handle);
-    }
+  if (bt_smp_request_ltk(conn, evt->rand, evt->ediv, ltk)) {
+    le_ltk_reply(handle, ltk);
+  } else {
+    le_ltk_neg_reply(handle);
+  }
 
-    bt_conn_unref(conn);
+  bt_conn_unref(conn);
 }
 #endif /* CONFIG_BT_SMP */
 
 #if defined(CONFIG_BT_ECC)
-static void le_pkey_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_p256_public_key_complete *evt = (void *)buf->data;
-    struct bt_pub_key_cb *cb;
+static void le_pkey_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_p256_public_key_complete *evt = (void *)buf->data;
+  struct bt_pub_key_cb                          *cb;
 
-    BT_DBG("status: 0x%02x", evt->status);
+  BT_DBG("status: 0x%02x", evt->status);
 
-    atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY);
+  atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY);
 
-    if (!evt->status) {
-        memcpy(pub_key, evt->key, 64);
-        atomic_set_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY);
-    }
+  if (!evt->status) {
+    memcpy(pub_key, evt->key, 64);
+    atomic_set_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY);
+  }
 
-    for (cb = pub_key_cb; cb; cb = cb->_next) {
-        cb->func(evt->status ? NULL : pub_key);
-    }
+  for (cb = pub_key_cb; cb; cb = cb->_next) {
+    cb->func(evt->status ? NULL : pub_key);
+  }
 
-    pub_key_cb = NULL;
+  pub_key_cb = NULL;
 }
 
-static void le_dhkey_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_generate_dhkey_complete *evt = (void *)buf->data;
+static void le_dhkey_complete(struct net_buf *buf) {
+  struct bt_hci_evt_le_generate_dhkey_complete *evt = (void *)buf->data;
 
-    BT_DBG("status: 0x%02x", evt->status);
+  BT_DBG("status: 0x%02x", evt->status);
 
-    if (dh_key_cb) {
-        dh_key_cb(evt->status ? NULL : evt->dhkey);
-        dh_key_cb = NULL;
-    }
+  if (dh_key_cb) {
+    dh_key_cb(evt->status ? NULL : evt->dhkey);
+    dh_key_cb = NULL;
+  }
 }
 #endif /* CONFIG_BT_ECC */
 
-static void hci_reset_complete(struct net_buf *buf)
-{
-    u8_t status = buf->data[0];
-    atomic_t flags;
+static void hci_reset_complete(struct net_buf *buf) {
+  u8_t     status = buf->data[0];
+  atomic_t flags;
 
-    BT_DBG("status 0x%02x", status);
+  BT_DBG("status 0x%02x", status);
 
-    if (status) {
-        return;
-    }
+  if (status) {
+    return;
+  }
 
-    scan_dev_found_cb = NULL;
+  scan_dev_found_cb = NULL;
 #if defined(CONFIG_BT_BREDR)
-    discovery_cb = NULL;
-    discovery_results = NULL;
-    discovery_results_size = 0;
-    discovery_results_count = 0;
+  discovery_cb            = NULL;
+  discovery_results       = NULL;
+  discovery_results_size  = 0;
+  discovery_results_count = 0;
 #endif /* CONFIG_BT_BREDR */
 
-    flags = (atomic_get(bt_dev.flags) & BT_DEV_PERSISTENT_FLAGS);
-    atomic_set(bt_dev.flags, flags);
+  flags = (atomic_get(bt_dev.flags) & BT_DEV_PERSISTENT_FLAGS);
+  atomic_set(bt_dev.flags, flags);
 }
 
-static void hci_cmd_done(u16_t opcode, u8_t status, struct net_buf *buf)
-{
-    BT_DBG("opcode 0x%04x status 0x%02x buf %p", opcode, status, buf);
-
-    if (net_buf_pool_get(buf->pool_id) != &hci_cmd_pool) {
-        BT_WARN("opcode 0x%04x pool id %u pool %p != &hci_cmd_pool %p",
-                opcode, buf->pool_id, net_buf_pool_get(buf->pool_id),
-                &hci_cmd_pool);
-        return;
-    }
-
-    if (cmd(buf)->opcode != opcode) {
-        BT_WARN("OpCode 0x%04x completed instead of expected 0x%04x",
-                opcode, cmd(buf)->opcode);
-    }
-
-    if (cmd(buf)->state && !status) {
-        struct cmd_state_set *update = cmd(buf)->state;
-
-        atomic_set_bit_to(update->target, update->bit, update->val);
-    }
+static void hci_cmd_done(u16_t opcode, u8_t status, struct net_buf *buf) {
+  BT_DBG("opcode 0x%04x status 0x%02x buf %p", opcode, status, buf);
 
-    /* If the command was synchronous wake up bt_hci_cmd_send_sync() */
-    if (cmd(buf)->sync) {
-        cmd(buf)->status = status;
-        k_sem_give(cmd(buf)->sync);
-    }
+  if (net_buf_pool_get(buf->pool_id) != &hci_cmd_pool) {
+    BT_WARN("opcode 0x%04x pool id %u pool %p != &hci_cmd_pool %p", opcode, buf->pool_id, net_buf_pool_get(buf->pool_id), &hci_cmd_pool);
+    return;
+  }
+
+  if (cmd(buf)->opcode != opcode) {
+    BT_WARN("OpCode 0x%04x completed instead of expected 0x%04x", opcode, cmd(buf)->opcode);
+  }
+
+  if (cmd(buf)->state && !status) {
+    struct cmd_state_set *update = cmd(buf)->state;
+
+    atomic_set_bit_to(update->target, update->bit, update->val);
+  }
+
+#if (BFLB_BT_CO_THREAD)
+  /* If the command was synchronous wake up bt_hci_cmd_send_sync() */
+  if (cmd(buf)->sync || cmd(buf)->sync_state) {
+    cmd(buf)->status = status;
+    if (cmd(buf)->sync_state)
+      cmd(buf)->sync_state = BT_CMD_SYNC_TX_DONE;
+    else
+      k_sem_give(cmd(buf)->sync);
+  }
+#else
+  if (cmd(buf)->sync) {
+    cmd(buf)->status = status;
+    k_sem_give(cmd(buf)->sync);
+  }
+#endif // BFLB_BT_CO_THREAD
 }
 
-static void hci_cmd_complete(struct net_buf *buf)
-{
-    struct bt_hci_evt_cmd_complete *evt;
-    u8_t status, ncmd;
-    u16_t opcode;
+static void hci_cmd_complete(struct net_buf *buf) {
+  struct bt_hci_evt_cmd_complete *evt;
+  u8_t                            status, ncmd;
+  u16_t                           opcode;
 
-    evt = net_buf_pull_mem(buf, sizeof(*evt));
-    ncmd = evt->ncmd;
-    opcode = sys_le16_to_cpu(evt->opcode);
+  evt    = net_buf_pull_mem(buf, sizeof(*evt));
+  ncmd   = evt->ncmd;
+  opcode = sys_le16_to_cpu(evt->opcode);
 
-    BT_DBG("opcode 0x%04x", opcode);
+  BT_DBG("opcode 0x%04x", opcode);
 
-    /* All command return parameters have a 1-byte status in the
-	 * beginning, so we can safely make this generalization.
-	 */
-    status = buf->data[0];
+  /* All command return parameters have a 1-byte status in the
+   * beginning, so we can safely make this generalization.
+   */
+  status = buf->data[0];
 
-    hci_cmd_done(opcode, status, buf);
+  hci_cmd_done(opcode, status, buf);
 
-    /* Allow next command to be sent */
-    if (ncmd) {
-        k_sem_give(&bt_dev.ncmd_sem);
-    }
+  /* Allow next command to be sent */
+  if (ncmd) {
+    k_sem_give(&bt_dev.ncmd_sem);
+  }
 }
 
-static void hci_cmd_status(struct net_buf *buf)
-{
-    struct bt_hci_evt_cmd_status *evt;
-    u16_t opcode;
-    u8_t ncmd;
+static void hci_cmd_status(struct net_buf *buf) {
+  struct bt_hci_evt_cmd_status *evt;
+  u16_t                         opcode;
+  u8_t                          ncmd;
 
-    evt = net_buf_pull_mem(buf, sizeof(*evt));
-    opcode = sys_le16_to_cpu(evt->opcode);
-    ncmd = evt->ncmd;
+  evt    = net_buf_pull_mem(buf, sizeof(*evt));
+  opcode = sys_le16_to_cpu(evt->opcode);
+  ncmd   = evt->ncmd;
 
-    BT_DBG("opcode 0x%04x", opcode);
+  BT_DBG("opcode 0x%04x", opcode);
 
-    hci_cmd_done(opcode, evt->status, buf);
+  hci_cmd_done(opcode, evt->status, buf);
 
-    /* Allow next command to be sent */
-    if (ncmd) {
-        k_sem_give(&bt_dev.ncmd_sem);
-    }
+  /* Allow next command to be sent */
+  if (ncmd) {
+    k_sem_give(&bt_dev.ncmd_sem);
+  }
 }
 
 #if defined(CONFIG_BT_OBSERVER)
-static int start_le_scan(u8_t scan_type, u16_t interval, u16_t window)
-{
-    struct bt_hci_cp_le_set_scan_param set_param;
-    struct net_buf *buf;
-    int err;
-
-    (void)memset(&set_param, 0, sizeof(set_param));
+static int start_le_scan(u8_t scan_type, u16_t interval, u16_t window) {
+  struct bt_hci_cp_le_set_scan_param set_param;
+  struct net_buf                    *buf;
+  int                                err;
 
-    set_param.scan_type = scan_type;
+  (void)memset(&set_param, 0, sizeof(set_param));
 
-    /* for the rest parameters apply default values according to
-	 *  spec 4.2, vol2, part E, 7.8.10
-	 */
-    set_param.interval = sys_cpu_to_le16(interval);
-    set_param.window = sys_cpu_to_le16(window);
+  set_param.scan_type = scan_type;
 
-    if (IS_ENABLED(CONFIG_BT_WHITELIST) &&
-        atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_WL)) {
-        set_param.filter_policy = BT_HCI_LE_SCAN_FP_USE_WHITELIST;
-    } else {
-        set_param.filter_policy = BT_HCI_LE_SCAN_FP_NO_WHITELIST;
-    }
+  /* for the rest parameters apply default values according to
+   *  spec 4.2, vol2, part E, 7.8.10
+   */
+  set_param.interval = sys_cpu_to_le16(interval);
+  set_param.window   = sys_cpu_to_le16(window);
 
-    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        err = le_set_private_addr(BT_ID_DEFAULT);
-        if (err) {
-            return err;
-        }
+  if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_WL)) {
+    set_param.filter_policy = BT_HCI_LE_SCAN_FP_USE_WHITELIST;
+  } else {
+    set_param.filter_policy = BT_HCI_LE_SCAN_FP_NO_WHITELIST;
+  }
 
-        if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-            set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-        } else {
-            set_param.addr_type = BT_ADDR_LE_RANDOM;
-        }
-    } else {
-        set_param.addr_type = bt_dev.id_addr[0].type;
-
-        /* Use NRPA unless identity has been explicitly requested
-		 * (through Kconfig), or if there is no advertising ongoing.
-		 */
-        if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) &&
-            scan_type == BT_HCI_LE_SCAN_ACTIVE &&
-            !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-            err = le_set_private_addr(BT_ID_DEFAULT);
-            if (err) {
-                return err;
-            }
-
-            set_param.addr_type = BT_ADDR_LE_RANDOM;
-        } else if (set_param.addr_type == BT_ADDR_LE_RANDOM) {
-            err = set_random_address(&bt_dev.id_addr[0].a);
-            if (err) {
-                return err;
-            }
-        }
+  if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    err = le_set_private_addr(BT_ID_DEFAULT);
+    if (err) {
+      return err;
     }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
+    if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+    } else {
+      set_param.addr_type = BT_ADDR_LE_RANDOM;
     }
+  } else {
+    set_param.addr_type = bt_dev.id_addr[0].type;
 
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
-
-    bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_PARAM, buf, NULL);
+    /* Use NRPA unless identity has been explicitly requested
+     * (through Kconfig), or if there is no advertising ongoing.
+     */
+    if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && scan_type == BT_HCI_LE_SCAN_ACTIVE && !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+      err = le_set_private_addr(BT_ID_DEFAULT);
+      if (err) {
+        return err;
+      }
 
-    err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
-    if (err) {
+      set_param.addr_type = BT_ADDR_LE_RANDOM;
+    } else if (set_param.addr_type == BT_ADDR_LE_RANDOM) {
+      err = set_random_address(&bt_dev.id_addr[0].a);
+      if (err) {
         return err;
+      }
     }
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN,
-                      scan_type == BT_HCI_LE_SCAN_ACTIVE);
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    return 0;
-}
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-#if defined(CONFIG_BT_STACK_PTS)
-static int start_le_scan_with_isrpa(u8_t scan_type, u16_t interval, u16_t window, u8_t addre_type)
-{
-    struct bt_hci_cp_le_set_scan_param set_param;
-    struct net_buf *buf;
-    int err = 0;
+  bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_PARAM, buf, NULL);
 
-    memset(&set_param, 0, sizeof(set_param));
+  err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
+  if (err) {
+    return err;
+  }
 
-    set_param.scan_type = scan_type;
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN, scan_type == BT_HCI_LE_SCAN_ACTIVE);
 
-    /* for the rest parameters apply default values according to
-     *  spec 4.2, vol2, part E, 7.8.10
-     */
-    set_param.interval = sys_cpu_to_le16(interval);
-    set_param.window = sys_cpu_to_le16(window);
-    set_param.filter_policy = 0x00;
+  return 0;
+}
 
-    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        if (addre_type == 1)
-            err = le_set_private_addr(BT_ID_DEFAULT);
-        else if (addre_type == 0)
-            err = le_set_non_resolv_private_addr(BT_ID_DEFAULT);
-        if (err) {
-            return err;
-        }
+#if defined(CONFIG_BT_STACK_PTS)
+static int start_le_scan_with_isrpa(u8_t scan_type, u16_t interval, u16_t window, u8_t addre_type) {
+  struct bt_hci_cp_le_set_scan_param set_param;
+  struct net_buf                    *buf;
+  int                                err = 0;
+
+  memset(&set_param, 0, sizeof(set_param));
+
+  set_param.scan_type = scan_type;
+
+  /* for the rest parameters apply default values according to
+   *  spec 4.2, vol2, part E, 7.8.10
+   */
+  set_param.interval      = sys_cpu_to_le16(interval);
+  set_param.window        = sys_cpu_to_le16(window);
+  set_param.filter_policy = 0x00;
+
+  if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    if (addre_type == 1)
+      err = le_set_private_addr(BT_ID_DEFAULT);
+    else if (addre_type == 0)
+      err = le_set_non_resolv_private_addr(BT_ID_DEFAULT);
+    if (err) {
+      return err;
+    }
 
-        if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-            if (addre_type == 2)
-                set_param.addr_type = BT_ADDR_LE_PUBLIC;
-            if (addre_type == 1)
-                set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-            else if (addre_type == 0)
-                set_param.addr_type = BT_ADDR_LE_RANDOM;
-        } else {
-            set_param.addr_type = BT_ADDR_LE_RANDOM;
-        }
+    if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      if (addre_type == 2)
+        set_param.addr_type = BT_ADDR_LE_PUBLIC;
+      if (addre_type == 1)
+        set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+      else if (addre_type == 0)
+        set_param.addr_type = BT_ADDR_LE_RANDOM;
     } else {
-        set_param.addr_type = bt_dev.id_addr[0].type;
-
-        /* Use NRPA unless identity has been explicitly requested
-         * (through Kconfig), or if there is no advertising ongoing.
-         */
-        if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) &&
-            scan_type == BT_HCI_LE_SCAN_ACTIVE &&
-            !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-            err = le_set_private_addr(BT_ID_DEFAULT);
-            if (err) {
-                return err;
-            }
-
-            set_param.addr_type = BT_ADDR_LE_RANDOM;
-        }
+      set_param.addr_type = BT_ADDR_LE_RANDOM;
     }
+  } else {
+    set_param.addr_type = bt_dev.id_addr[0].type;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
+    /* Use NRPA unless identity has been explicitly requested
+     * (through Kconfig), or if there is no advertising ongoing.
+     */
+    if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && scan_type == BT_HCI_LE_SCAN_ACTIVE && !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+      err = le_set_private_addr(BT_ID_DEFAULT);
+      if (err) {
+        return err;
+      }
+
+      set_param.addr_type = BT_ADDR_LE_RANDOM;
     }
+  }
 
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_PARAM, buf, NULL);
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-    err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
-    if (err) {
-        return err;
-    }
+  bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_PARAM, buf, NULL);
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN,
-                      scan_type == BT_HCI_LE_SCAN_ACTIVE);
+  err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN, scan_type == BT_HCI_LE_SCAN_ACTIVE);
+
+  return 0;
 }
 
 #endif
 
-int bt_le_scan_update(bool fast_scan)
-{
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return 0;
-    }
+int bt_le_scan_update(bool fast_scan) {
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return 0;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
-        int err;
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
+    int err;
 
-        err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-        if (err) {
-            return err;
-        }
+    err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+    if (err) {
+      return err;
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-        u16_t interval, window;
-        struct bt_conn *conn;
-
-        /* don't restart scan if we have pending connection */
-        conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
-        if (conn) {
-            bt_conn_unref(conn);
-            return 0;
-        }
+  if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+    u16_t           interval, window;
+    struct bt_conn *conn;
 
-        conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN);
-        if (!conn) {
-            return 0;
-        }
+    /* don't restart scan if we have pending connection */
+    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT);
+    if (conn) {
+      bt_conn_unref(conn);
+      return 0;
+    }
 
-        //atomic_set_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP);
-        atomic_clear_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP);
+    conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN);
+    if (!conn) {
+      return 0;
+    }
 
-        bt_conn_unref(conn);
+    // atomic_set_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP);
+    atomic_clear_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP);
 
-        if (fast_scan) {
-            interval = BT_GAP_SCAN_FAST_INTERVAL;
-            window = BT_GAP_SCAN_FAST_WINDOW;
-        } else {
-            interval = CONFIG_BT_BACKGROUND_SCAN_INTERVAL;
-            window = CONFIG_BT_BACKGROUND_SCAN_WINDOW;
-        }
+    bt_conn_unref(conn);
 
-        return start_le_scan(BT_HCI_LE_SCAN_PASSIVE, interval, window);
+    if (fast_scan) {
+      interval = BT_GAP_SCAN_FAST_INTERVAL;
+      window   = BT_GAP_SCAN_FAST_WINDOW;
+    } else {
+      interval = CONFIG_BT_BACKGROUND_SCAN_INTERVAL;
+      window   = CONFIG_BT_BACKGROUND_SCAN_WINDOW;
     }
 
-    return 0;
+    return start_le_scan(BT_HCI_LE_SCAN_PASSIVE, interval, window);
+  }
+
+  return 0;
 }
 
-void bt_data_parse(struct net_buf_simple *ad,
-                   bool (*func)(struct bt_data *data, void *user_data),
-                   void *user_data)
-{
-    while (ad->len > 1) {
-        struct bt_data data;
-        u8_t len;
-
-        len = net_buf_simple_pull_u8(ad);
-        if (len == 0U) {
-            /* Early termination */
-            return;
-        }
+void bt_data_parse(struct net_buf_simple *ad, bool (*func)(struct bt_data *data, void *user_data), void *user_data) {
+  while (ad->len > 1) {
+    struct bt_data data;
+    u8_t           len;
 
-        if (len > ad->len) {
-            BT_WARN("Malformed data");
-            return;
-        }
+    len = net_buf_simple_pull_u8(ad);
+    if (len == 0U) {
+      /* Early termination */
+      return;
+    }
 
-        data.type = net_buf_simple_pull_u8(ad);
-        data.data_len = len - 1;
-        data.data = ad->data;
+    if (len > ad->len) {
+      BT_WARN("Malformed data");
+      return;
+    }
 
-        if (!func(&data, user_data)) {
-            return;
-        }
+    data.type     = net_buf_simple_pull_u8(ad);
+    data.data_len = len - 1;
+    data.data     = ad->data;
 
-        net_buf_simple_pull(ad, len - 1);
+    if (!func(&data, user_data)) {
+      return;
     }
+
+    net_buf_simple_pull(ad, len - 1);
+  }
 }
 
-static void le_adv_report(struct net_buf *buf)
-{
-    u8_t num_reports = net_buf_pull_u8(buf);
-    struct bt_hci_evt_le_advertising_info *info;
+static void le_adv_report(struct net_buf *buf) {
+  u8_t                                   num_reports = net_buf_pull_u8(buf);
+  struct bt_hci_evt_le_advertising_info *info;
 
-    BT_DBG("Adv number of reports %u", num_reports);
+  BT_DBG("Adv number of reports %u", num_reports);
 
-    while (num_reports--) {
-        bt_addr_le_t id_addr;
-        s8_t rssi;
+  while (num_reports--) {
+    bt_addr_le_t id_addr;
+    s8_t         rssi;
 
-        if (buf->len < sizeof(*info)) {
-            BT_ERR("Unexpected end of buffer");
-            break;
-        }
+    if (buf->len < sizeof(*info)) {
+      BT_ERR("Unexpected end of buffer");
+      break;
+    }
 
-        info = net_buf_pull_mem(buf, sizeof(*info));
-        rssi = info->data[info->length];
-
-        BT_DBG("%s event %u, len %u, rssi %d dBm",
-               bt_addr_le_str(&info->addr),
-               info->evt_type, info->length, rssi);
-
-        if (info->addr.type == BT_ADDR_LE_PUBLIC_ID ||
-            info->addr.type == BT_ADDR_LE_RANDOM_ID) {
-            bt_addr_le_copy(&id_addr, &info->addr);
-            id_addr.type -= BT_ADDR_LE_PUBLIC_ID;
-        } else {
-            bt_addr_le_copy(&id_addr,
-                            bt_lookup_id_addr(bt_dev.adv_id,
-                                              &info->addr));
-        }
+    info = net_buf_pull_mem(buf, sizeof(*info));
+    rssi = info->data[info->length];
 
-        if (scan_dev_found_cb) {
-            struct net_buf_simple_state state;
+    BT_DBG("%s event %u, len %u, rssi %d dBm", bt_addr_le_str(&info->addr), info->evt_type, info->length, rssi);
 
-            net_buf_simple_save(&buf->b, &state);
+    if (info->addr.type == BT_ADDR_LE_PUBLIC_ID || info->addr.type == BT_ADDR_LE_RANDOM_ID) {
+      bt_addr_le_copy(&id_addr, &info->addr);
+      id_addr.type -= BT_ADDR_LE_PUBLIC_ID;
+    } else {
+      bt_addr_le_copy(&id_addr, bt_lookup_id_addr(bt_dev.adv_id, &info->addr));
+    }
 
-            buf->len = info->length;
-            scan_dev_found_cb(&id_addr, rssi, info->evt_type,
-                              &buf->b);
+    if (scan_dev_found_cb) {
+      struct net_buf_simple_state state;
 
-            net_buf_simple_restore(&buf->b, &state);
-        }
+      net_buf_simple_save(&buf->b, &state);
+
+      buf->len = info->length;
+      scan_dev_found_cb(&id_addr, rssi, info->evt_type, &buf->b);
+
+      net_buf_simple_restore(&buf->b, &state);
+    }
 
 #if defined(CONFIG_BT_CENTRAL)
-        check_pending_conn(&id_addr, &info->addr, info->evt_type);
+    check_pending_conn(&id_addr, &info->addr, info->evt_type);
 #endif /* CONFIG_BT_CENTRAL */
 
-        net_buf_pull(buf, info->length + sizeof(rssi));
-    }
+    net_buf_pull(buf, info->length + sizeof(rssi));
+  }
 }
 #endif /* CONFIG_BT_OBSERVER */
 
-int bt_hci_get_conn_handle(const struct bt_conn *conn, u16_t *conn_handle)
-{
-    if (conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+int bt_hci_get_conn_handle(const struct bt_conn *conn, u16_t *conn_handle) {
+  if (conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    *conn_handle = conn->handle;
-    return 0;
+  *conn_handle = conn->handle;
+  return 0;
 }
 
 #if defined(CONFIG_BT_HCI_VS_EVT_USER)
-int bt_hci_register_vnd_evt_cb(bt_hci_vnd_evt_cb_t cb)
-{
-    hci_vnd_evt_cb = cb;
-    return 0;
+int bt_hci_register_vnd_evt_cb(bt_hci_vnd_evt_cb_t cb) {
+  hci_vnd_evt_cb = cb;
+  return 0;
 }
 #endif /* CONFIG_BT_HCI_VS_EVT_USER */
 
-static void hci_vendor_event(struct net_buf *buf)
-{
-    bool handled = false;
+static void hci_vendor_event(struct net_buf *buf) {
+  bool handled = false;
 
 #if defined(CONFIG_BT_HCI_VS_EVT_USER)
-    if (hci_vnd_evt_cb) {
-        struct net_buf_simple_state state;
+  if (hci_vnd_evt_cb) {
+    struct net_buf_simple_state state;
 
-        net_buf_simple_save(&buf->b, &state);
+    net_buf_simple_save(&buf->b, &state);
 
-        handled = (hci_vnd_evt_cb)(&buf->b);
+    handled = (hci_vnd_evt_cb)(&buf->b);
 
-        net_buf_simple_restore(&buf->b, &state);
-    }
+    net_buf_simple_restore(&buf->b, &state);
+  }
 #endif /* CONFIG_BT_HCI_VS_EVT_USER */
 
-    if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT) && !handled) {
-        /* do nothing at present time */
-        BT_WARN("Unhandled vendor-specific event: %s",
-                bt_hex(buf->data, buf->len));
-    }
+  if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT) && !handled) {
+    /* do nothing at present time */
+    BT_WARN("Unhandled vendor-specific event: %s", bt_hex(buf->data, buf->len));
+  }
 }
 
 static const struct event_handler meta_events[] = {
 #if defined(CONFIG_BT_OBSERVER)
-    EVENT_HANDLER(BT_HCI_EVT_LE_ADVERTISING_REPORT, le_adv_report,
-                  sizeof(struct bt_hci_evt_le_advertising_report)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_ADVERTISING_REPORT, le_adv_report, sizeof(struct bt_hci_evt_le_advertising_report)),
 #endif /* CONFIG_BT_OBSERVER */
 #if defined(CONFIG_BT_CONN)
-    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_COMPLETE, le_legacy_conn_complete,
-                  sizeof(struct bt_hci_evt_le_conn_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_LE_ENH_CONN_COMPLETE, le_enh_conn_complete,
-                  sizeof(struct bt_hci_evt_le_enh_conn_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE,
-                  le_conn_update_complete,
-                  sizeof(struct bt_hci_evt_le_conn_update_complete)),
-    EVENT_HANDLER(BT_HCI_EV_LE_REMOTE_FEAT_COMPLETE,
-                  le_remote_feat_complete,
-                  sizeof(struct bt_hci_evt_le_remote_feat_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_PARAM_REQ, le_conn_param_req,
-                  sizeof(struct bt_hci_evt_le_conn_param_req)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_COMPLETE, le_legacy_conn_complete, sizeof(struct bt_hci_evt_le_conn_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_ENH_CONN_COMPLETE, le_enh_conn_complete, sizeof(struct bt_hci_evt_le_enh_conn_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE, le_conn_update_complete, sizeof(struct bt_hci_evt_le_conn_update_complete)),
+    EVENT_HANDLER(BT_HCI_EV_LE_REMOTE_FEAT_COMPLETE, le_remote_feat_complete, sizeof(struct bt_hci_evt_le_remote_feat_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_CONN_PARAM_REQ, le_conn_param_req, sizeof(struct bt_hci_evt_le_conn_param_req)),
 #if defined(CONFIG_BT_DATA_LEN_UPDATE)
-    EVENT_HANDLER(BT_HCI_EVT_LE_DATA_LEN_CHANGE, le_data_len_change,
-                  sizeof(struct bt_hci_evt_le_data_len_change)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_DATA_LEN_CHANGE, le_data_len_change, sizeof(struct bt_hci_evt_le_data_len_change)),
 #endif /* CONFIG_BT_DATA_LEN_UPDATE */
 #if defined(CONFIG_BT_PHY_UPDATE)
-    EVENT_HANDLER(BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE,
-                  le_phy_update_complete,
-                  sizeof(struct bt_hci_evt_le_phy_update_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE, le_phy_update_complete, sizeof(struct bt_hci_evt_le_phy_update_complete)),
 #endif /* CONFIG_BT_PHY_UPDATE */
 #endif /* CONFIG_BT_CONN */
 #if defined(CONFIG_BT_SMP)
-    EVENT_HANDLER(BT_HCI_EVT_LE_LTK_REQUEST, le_ltk_request,
-                  sizeof(struct bt_hci_evt_le_ltk_request)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_LTK_REQUEST, le_ltk_request, sizeof(struct bt_hci_evt_le_ltk_request)),
 #endif /* CONFIG_BT_SMP */
 #if defined(CONFIG_BT_ECC)
-    EVENT_HANDLER(BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE, le_pkey_complete,
-                  sizeof(struct bt_hci_evt_le_p256_public_key_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE, le_dhkey_complete,
-                  sizeof(struct bt_hci_evt_le_generate_dhkey_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE, le_pkey_complete, sizeof(struct bt_hci_evt_le_p256_public_key_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE, le_dhkey_complete, sizeof(struct bt_hci_evt_le_generate_dhkey_complete)),
 #endif /* CONFIG_BT_SMP */
 };
 
-static void hci_le_meta_event(struct net_buf *buf)
-{
-    struct bt_hci_evt_le_meta_event *evt;
+static void hci_le_meta_event(struct net_buf *buf) {
+  struct bt_hci_evt_le_meta_event *evt;
 
-    evt = net_buf_pull_mem(buf, sizeof(*evt));
+  evt = net_buf_pull_mem(buf, sizeof(*evt));
 
-    BT_DBG("subevent 0x%02x", evt->subevent);
+  BT_DBG("subevent 0x%02x", evt->subevent);
 
-    handle_event(evt->subevent, buf, meta_events, ARRAY_SIZE(meta_events));
+  handle_event(evt->subevent, buf, meta_events, ARRAY_SIZE(meta_events));
 }
 
 static const struct event_handler normal_events[] = {
-    EVENT_HANDLER(BT_HCI_EVT_VENDOR, hci_vendor_event,
-                  sizeof(struct bt_hci_evt_vs)),
-    EVENT_HANDLER(BT_HCI_EVT_LE_META_EVENT, hci_le_meta_event,
-                  sizeof(struct bt_hci_evt_le_meta_event)),
+    EVENT_HANDLER(BT_HCI_EVT_VENDOR, hci_vendor_event, sizeof(struct bt_hci_evt_vs)),
+    EVENT_HANDLER(BT_HCI_EVT_LE_META_EVENT, hci_le_meta_event, sizeof(struct bt_hci_evt_le_meta_event)),
 #if defined(CONFIG_BT_BREDR)
-    EVENT_HANDLER(BT_HCI_EVT_CONN_REQUEST, conn_req,
-                  sizeof(struct bt_hci_evt_conn_request)),
-    EVENT_HANDLER(BT_HCI_EVT_CONN_COMPLETE, conn_complete,
-                  sizeof(struct bt_hci_evt_conn_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_PIN_CODE_REQ, pin_code_req,
-                  sizeof(struct bt_hci_evt_pin_code_req)),
-    EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_NOTIFY, link_key_notify,
-                  sizeof(struct bt_hci_evt_link_key_notify)),
-    EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_REQ, link_key_req,
-                  sizeof(struct bt_hci_evt_link_key_req)),
-    EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_RESP, io_capa_resp,
-                  sizeof(struct bt_hci_evt_io_capa_resp)),
-    EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_REQ, io_capa_req,
-                  sizeof(struct bt_hci_evt_io_capa_req)),
-    EVENT_HANDLER(BT_HCI_EVT_SSP_COMPLETE, ssp_complete,
-                  sizeof(struct bt_hci_evt_ssp_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_USER_CONFIRM_REQ, user_confirm_req,
-                  sizeof(struct bt_hci_evt_user_confirm_req)),
-    EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_NOTIFY, user_passkey_notify,
-                  sizeof(struct bt_hci_evt_user_passkey_notify)),
-    EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_REQ, user_passkey_req,
-                  sizeof(struct bt_hci_evt_user_passkey_req)),
-    EVENT_HANDLER(BT_HCI_EVT_INQUIRY_COMPLETE, inquiry_complete,
-                  sizeof(struct bt_hci_evt_inquiry_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI,
-                  inquiry_result_with_rssi,
-                  sizeof(struct bt_hci_evt_inquiry_result_with_rssi)),
-    EVENT_HANDLER(BT_HCI_EVT_EXTENDED_INQUIRY_RESULT,
-                  extended_inquiry_result,
-                  sizeof(struct bt_hci_evt_extended_inquiry_result)),
-    EVENT_HANDLER(BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE,
-                  remote_name_request_complete,
-                  sizeof(struct bt_hci_evt_remote_name_req_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_AUTH_COMPLETE, auth_complete,
-                  sizeof(struct bt_hci_evt_auth_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_REMOTE_FEATURES,
-                  read_remote_features_complete,
-                  sizeof(struct bt_hci_evt_remote_features)),
-    EVENT_HANDLER(BT_HCI_EVT_REMOTE_EXT_FEATURES,
-                  read_remote_ext_features_complete,
-                  sizeof(struct bt_hci_evt_remote_ext_features)),
-    EVENT_HANDLER(BT_HCI_EVT_ROLE_CHANGE, role_change,
-                  sizeof(struct bt_hci_evt_role_change)),
-    EVENT_HANDLER(BT_HCI_EVT_SYNC_CONN_COMPLETE, synchronous_conn_complete,
-                  sizeof(struct bt_hci_evt_sync_conn_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_CONN_REQUEST, conn_req, sizeof(struct bt_hci_evt_conn_request)),
+    EVENT_HANDLER(BT_HCI_EVT_CONN_COMPLETE, conn_complete, sizeof(struct bt_hci_evt_conn_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_PIN_CODE_REQ, pin_code_req, sizeof(struct bt_hci_evt_pin_code_req)),
+    EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_NOTIFY, link_key_notify, sizeof(struct bt_hci_evt_link_key_notify)),
+    EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_REQ, link_key_req, sizeof(struct bt_hci_evt_link_key_req)),
+    EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_RESP, io_capa_resp, sizeof(struct bt_hci_evt_io_capa_resp)),
+    EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_REQ, io_capa_req, sizeof(struct bt_hci_evt_io_capa_req)),
+    EVENT_HANDLER(BT_HCI_EVT_SSP_COMPLETE, ssp_complete, sizeof(struct bt_hci_evt_ssp_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_USER_CONFIRM_REQ, user_confirm_req, sizeof(struct bt_hci_evt_user_confirm_req)),
+    EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_NOTIFY, user_passkey_notify, sizeof(struct bt_hci_evt_user_passkey_notify)),
+    EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_REQ, user_passkey_req, sizeof(struct bt_hci_evt_user_passkey_req)),
+    EVENT_HANDLER(BT_HCI_EVT_INQUIRY_COMPLETE, inquiry_complete, sizeof(struct bt_hci_evt_inquiry_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI, inquiry_result_with_rssi, sizeof(struct bt_hci_evt_inquiry_result_with_rssi)),
+    EVENT_HANDLER(BT_HCI_EVT_EXTENDED_INQUIRY_RESULT, extended_inquiry_result, sizeof(struct bt_hci_evt_extended_inquiry_result)),
+    EVENT_HANDLER(BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE, remote_name_request_complete, sizeof(struct bt_hci_evt_remote_name_req_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_AUTH_COMPLETE, auth_complete, sizeof(struct bt_hci_evt_auth_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_REMOTE_FEATURES, read_remote_features_complete, sizeof(struct bt_hci_evt_remote_features)),
+    EVENT_HANDLER(BT_HCI_EVT_REMOTE_EXT_FEATURES, read_remote_ext_features_complete, sizeof(struct bt_hci_evt_remote_ext_features)),
+    EVENT_HANDLER(BT_HCI_EVT_ROLE_CHANGE, role_change, sizeof(struct bt_hci_evt_role_change)),
+    EVENT_HANDLER(BT_HCI_EVT_SYNC_CONN_COMPLETE, synchronous_conn_complete, sizeof(struct bt_hci_evt_sync_conn_complete)),
 #endif /* CONFIG_BT_BREDR */
 #if defined(CONFIG_BT_CONN)
-    EVENT_HANDLER(BT_HCI_EVT_DISCONN_COMPLETE, hci_disconn_complete,
-                  sizeof(struct bt_hci_evt_disconn_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_DISCONN_COMPLETE, hci_disconn_complete, sizeof(struct bt_hci_evt_disconn_complete)),
 #endif /* CONFIG_BT_CONN */
 #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
-    EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_CHANGE, hci_encrypt_change,
-                  sizeof(struct bt_hci_evt_encrypt_change)),
-    EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE,
-                  hci_encrypt_key_refresh_complete,
-                  sizeof(struct bt_hci_evt_encrypt_key_refresh_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_CHANGE, hci_encrypt_change, sizeof(struct bt_hci_evt_encrypt_change)),
+    EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE, hci_encrypt_key_refresh_complete, sizeof(struct bt_hci_evt_encrypt_key_refresh_complete)),
 #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */
 };
 
-static void hci_event(struct net_buf *buf)
-{
-    struct bt_hci_evt_hdr *hdr;
+static void hci_event(struct net_buf *buf) {
+  struct bt_hci_evt_hdr *hdr;
 
-    BT_ASSERT(buf->len >= sizeof(*hdr));
+  BT_ASSERT(buf->len >= sizeof(*hdr));
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    BT_DBG("event 0x%02x", hdr->evt);
-    BT_ASSERT(!bt_hci_evt_is_prio(hdr->evt));
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  BT_DBG("event 0x%02x", hdr->evt);
+  BT_ASSERT(!bt_hci_evt_is_prio(hdr->evt));
 
-    handle_event(hdr->evt, buf, normal_events, ARRAY_SIZE(normal_events));
+  handle_event(hdr->evt, buf, normal_events, ARRAY_SIZE(normal_events));
 
-    net_buf_unref(buf);
+  net_buf_unref(buf);
 }
 
+#if (BFLB_BT_CO_THREAD)
+static void send_cmd(struct net_buf *tx_buf)
+#else
 static void send_cmd(void)
+#endif
 {
-    struct net_buf *buf;
-    int err;
+  struct net_buf *buf;
+  int             err;
 
-    /* Get next command */
-    BT_DBG("calling net_buf_get");
+#if (BFLB_BT_CO_THREAD)
+  if (tx_buf) {
+    buf = tx_buf;
+  } else {
     buf = net_buf_get(&bt_dev.cmd_tx_queue, K_NO_WAIT);
-    BT_ASSERT(buf);
+  }
+#else
+  /* Get next command */
+  BT_DBG("calling net_buf_get");
+  buf = net_buf_get(&bt_dev.cmd_tx_queue, K_NO_WAIT);
+#endif
+  BT_ASSERT(buf);
 
-    /* Wait until ncmd > 0 */
-    BT_DBG("calling sem_take_wait");
-    k_sem_take(&bt_dev.ncmd_sem, K_FOREVER);
+  /* Wait until ncmd > 0 */
+  BT_DBG("calling sem_take_wait");
+  k_sem_take(&bt_dev.ncmd_sem, K_FOREVER);
 
-    /* Clear out any existing sent command */
-    if (bt_dev.sent_cmd) {
-        BT_ERR("Uncleared pending sent_cmd");
-        net_buf_unref(bt_dev.sent_cmd);
-        bt_dev.sent_cmd = NULL;
-    }
+  /* Clear out any existing sent command */
+  if (bt_dev.sent_cmd) {
+    BT_ERR("Uncleared pending sent_cmd");
+    net_buf_unref(bt_dev.sent_cmd);
+    bt_dev.sent_cmd = NULL;
+  }
 
-    bt_dev.sent_cmd = net_buf_ref(buf);
+  bt_dev.sent_cmd = net_buf_ref(buf);
 
-    BT_DBG("Sending command 0x%04x (buf %p) to driver",
-           cmd(buf)->opcode, buf);
+  BT_DBG("Sending command 0x%04x (buf %p) to driver", cmd(buf)->opcode, buf);
 
-    err = bt_send(buf);
-    if (err) {
-        BT_ERR("Unable to send to driver (err %d)", err);
-        k_sem_give(&bt_dev.ncmd_sem);
-        hci_cmd_done(cmd(buf)->opcode, BT_HCI_ERR_UNSPECIFIED, buf);
-        net_buf_unref(bt_dev.sent_cmd);
-        bt_dev.sent_cmd = NULL;
-        net_buf_unref(buf);
-    }
+  err = bt_send(buf);
+  if (err) {
+    BT_ERR("Unable to send to driver (err %d)", err);
+    k_sem_give(&bt_dev.ncmd_sem);
+    hci_cmd_done(cmd(buf)->opcode, BT_HCI_ERR_UNSPECIFIED, buf);
+    net_buf_unref(bt_dev.sent_cmd);
+    bt_dev.sent_cmd = NULL;
+    net_buf_unref(buf);
+  }
+}
+
+#if (BFLB_BT_CO_THREAD)
+static void handle_rx_queue(void) {
+  struct net_buf *buf = NULL;
+  buf                 = net_buf_get(&recv_fifo, K_NO_WAIT);
+  if (buf) {
+    BT_DBG("Calling bt_recv(%p)", buf);
+    bt_recv(buf);
+  }
 }
+#endif
+
+#if (BFLB_BT_CO_THREAD)
+static void process_events(struct k_poll_event *ev, int count, int total_evt_array_cnt)
+#else
+static void process_events(struct k_poll_event *ev, int count)
+#endif
+{
+  BT_DBG("count %d", count);
+#if (BFLB_BT_CO_THREAD)
+  for (int ii = 0; ii < total_evt_array_cnt; ev++, ii++) {
+    if (ii >= count && ii != total_evt_array_cnt - 1)
+      continue;
+#else
+  for (; count; ev++, count--) {
+#endif
+    BT_DBG("ev->state %u", ev->state);
+    switch (ev->state) {
+    case K_POLL_STATE_SIGNALED:
+      break;
+    case K_POLL_STATE_FIFO_DATA_AVAILABLE:
+      if (ev->tag == BT_EVENT_CMD_TX) {
+#if (BFLB_BT_CO_THREAD)
+        send_cmd(NULL);
+#else
+        send_cmd();
+#endif
+      }
+#if (BFLB_BT_CO_THREAD)
+      else if (ev->tag == BT_EVENT_RX_QUEUE) {
+        handle_rx_queue();
+      } else if (ev->tag == BT_EVENT_WORK_QUEUE) {
+        extern void handle_work_queue(void);
+        handle_work_queue();
+      }
+#endif
+      else if (IS_ENABLED(CONFIG_BT_CONN)) {
+        struct bt_conn *conn;
 
-static void process_events(struct k_poll_event *ev, int count)
-{
-    BT_DBG("count %d", count);
-
-    for (; count; ev++, count--) {
-        BT_DBG("ev->state %u", ev->state);
-
-        switch (ev->state) {
-            case K_POLL_STATE_SIGNALED:
-                break;
-            case K_POLL_STATE_FIFO_DATA_AVAILABLE:
-                if (ev->tag == BT_EVENT_CMD_TX) {
-                    send_cmd();
-                } else if (IS_ENABLED(CONFIG_BT_CONN)) {
-                    struct bt_conn *conn;
-
-                    if (ev->tag == BT_EVENT_CONN_TX_QUEUE) {
-                        conn = CONTAINER_OF(ev->fifo,
-                                            struct bt_conn,
-                                            tx_queue);
-                        bt_conn_process_tx(conn);
-                    }
-                }
-                break;
-            case K_POLL_STATE_NOT_READY:
-                break;
-            default:
-                BT_WARN("Unexpected k_poll event state %u", ev->state);
-                break;
+        if (ev->tag == BT_EVENT_CONN_TX_QUEUE) {
+          conn = CONTAINER_OF(ev->fifo, struct bt_conn, tx_queue);
+#if (BFLB_BT_CO_THREAD)
+          bt_conn_process_tx(conn, NULL);
+#else
+          bt_conn_process_tx(conn);
+#endif
         }
+      }
+      break;
+    case K_POLL_STATE_NOT_READY:
+      break;
+    default:
+      BT_WARN("Unexpected k_poll event state %u", ev->state);
+      break;
     }
+  }
 }
 
-#if defined(CONFIG_BT_CONN)
-/* command FIFO + conn_change signal + MAX_CONN */
-#define EV_COUNT (2 + CONFIG_BT_MAX_CONN)
-#else
-/* command FIFO */
-#define EV_COUNT 1
-#endif
+#if (BFLB_BT_CO_THREAD)
+static void bt_co_thread(void *p1, void *p2, void *p3) {
+  static struct k_poll_event events[EV_COUNT] = {
 
-#if defined(BFLB_BLE)
-#if (BFLB_BLE_CO_THREAD)
-void co_tx_thread()
-{
-    static struct k_poll_event events[EV_COUNT] = {
-        K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE,
-                                        K_POLL_MODE_NOTIFY_ONLY,
-                                        &bt_dev.cmd_tx_queue,
-                                        BT_EVENT_CMD_TX),
-    };
+      [0]            = K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &g_work_queue_main.fifo, BT_EVENT_WORK_QUEUE),
+      [1]            = K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &bt_dev.cmd_tx_queue, BT_EVENT_CMD_TX),
+      [EV_COUNT - 1] = K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &recv_fifo, BT_EVENT_RX_QUEUE),
+  };
 
-    if (k_sem_count_get(&g_poll_sem) > 0) {
-        int ev_count, err;
-        events[0].state = K_POLL_STATE_NOT_READY;
-        ev_count = 1;
+  BT_DBG("Started");
 
-        if (IS_ENABLED(CONFIG_BT_CONN)) {
-            ev_count += bt_conn_prepare_events(&events[1]);
-        }
+  while (1) {
+    int ev_count, err;
+
+    events[0].state            = K_POLL_STATE_NOT_READY;
+    events[1].state            = K_POLL_STATE_NOT_READY;
+    events[EV_COUNT - 1].state = K_POLL_STATE_NOT_READY;
+    ev_count                   = 2;
 
-        err = k_poll(events, ev_count, K_NO_WAIT);
-        process_events(events, ev_count);
+    if (IS_ENABLED(CONFIG_BT_CONN)) {
+      ev_count += bt_conn_prepare_events(&events[2]);
     }
+
+    BT_DBG("Calling k_poll with %d events", ev_count);
+
+    err = k_poll(events, ev_count, EV_COUNT, K_FOREVER, NULL);
+
+    BT_ASSERT(err == 0);
+
+    process_events(events, ev_count, EV_COUNT);
+
+    /* Make sure we don't hog the CPU if there's all the time
+     * some ready events.
+     */
+    k_yield();
+  }
 }
-#endif
+#else
 
+#if defined(BFLB_BLE)
 static void hci_tx_thread(void *p1)
 #else
 static void hci_tx_thread(void *p1, void *p2, void *p3)
 #endif
 {
-    static struct k_poll_event events[EV_COUNT] = {
-        K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE,
-                                        K_POLL_MODE_NOTIFY_ONLY,
-                                        &bt_dev.cmd_tx_queue,
-                                        BT_EVENT_CMD_TX),
-    };
+  static struct k_poll_event events[EV_COUNT] = {
+      K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &bt_dev.cmd_tx_queue, BT_EVENT_CMD_TX),
+  };
 
-    BT_DBG("Started");
+  BT_DBG("Started");
 
-    while (1) {
-        int ev_count, err;
+  while (1) {
+    int ev_count, err;
 
-        events[0].state = K_POLL_STATE_NOT_READY;
-        ev_count = 1;
+    events[0].state = K_POLL_STATE_NOT_READY;
+    ev_count        = 1;
 
-        if (IS_ENABLED(CONFIG_BT_CONN)) {
-            ev_count += bt_conn_prepare_events(&events[1]);
-        }
+    if (IS_ENABLED(CONFIG_BT_CONN)) {
+      ev_count += bt_conn_prepare_events(&events[1]);
+    }
 
-        BT_DBG("Calling k_poll with %d events", ev_count);
+    BT_DBG("Calling k_poll with %d events", ev_count);
 
-        err = k_poll(events, ev_count, K_FOREVER);
-        BT_ASSERT(err == 0);
+    err = k_poll(events, ev_count, K_FOREVER);
+    BT_ASSERT(err == 0);
 
-        process_events(events, ev_count);
+    process_events(events, ev_count);
 
-        /* Make sure we don't hog the CPU if there's all the time
-		 * some ready events.
-		 */
-        k_yield();
-    }
+    /* Make sure we don't hog the CPU if there's all the time
+     * some ready events.
+     */
+    k_yield();
+  }
 }
+#endif // BFLB_BT_CO_THREAD
 
-static void read_local_ver_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_local_version_info *rp = (void *)buf->data;
+static void read_local_ver_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_local_version_info *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    bt_dev.hci_version = rp->hci_version;
-    bt_dev.hci_revision = sys_le16_to_cpu(rp->hci_revision);
-    bt_dev.lmp_version = rp->lmp_version;
-    bt_dev.lmp_subversion = sys_le16_to_cpu(rp->lmp_subversion);
-    bt_dev.manufacturer = sys_le16_to_cpu(rp->manufacturer);
+  bt_dev.hci_version    = rp->hci_version;
+  bt_dev.hci_revision   = sys_le16_to_cpu(rp->hci_revision);
+  bt_dev.lmp_version    = rp->lmp_version;
+  bt_dev.lmp_subversion = sys_le16_to_cpu(rp->lmp_subversion);
+  bt_dev.manufacturer   = sys_le16_to_cpu(rp->manufacturer);
 }
 
-static void read_bdaddr_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_bd_addr *rp = (void *)buf->data;
+static void read_bdaddr_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_bd_addr *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    if (!bt_addr_cmp(&rp->bdaddr, BT_ADDR_ANY) ||
-        !bt_addr_cmp(&rp->bdaddr, BT_ADDR_NONE)) {
-        BT_DBG("Controller has no public address");
-        return;
-    }
+  if (!bt_addr_cmp(&rp->bdaddr, BT_ADDR_ANY) || !bt_addr_cmp(&rp->bdaddr, BT_ADDR_NONE)) {
+    BT_DBG("Controller has no public address");
+    return;
+  }
 
-    bt_addr_copy(&bt_dev.id_addr[0].a, &rp->bdaddr);
-    bt_dev.id_addr[0].type = BT_ADDR_LE_PUBLIC;
-    bt_dev.id_count = 1U;
+  bt_addr_copy(&bt_dev.id_addr[0].a, &rp->bdaddr);
+  bt_dev.id_addr[0].type = BT_ADDR_LE_PUBLIC;
+  bt_dev.id_count        = 1U;
 }
 
-static void read_le_features_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_le_read_local_features *rp = (void *)buf->data;
+static void read_le_features_complete(struct net_buf *buf) {
+  struct bt_hci_rp_le_read_local_features *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    memcpy(bt_dev.le.features, rp->features, sizeof(bt_dev.le.features));
+  memcpy(bt_dev.le.features, rp->features, sizeof(bt_dev.le.features));
 }
 
 #if defined(CONFIG_BT_BREDR)
-static void read_buffer_size_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data;
-    u16_t pkts;
+static void read_buffer_size_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data;
+  u16_t                              pkts;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    bt_dev.br.mtu = sys_le16_to_cpu(rp->acl_max_len);
-    pkts = sys_le16_to_cpu(rp->acl_max_num);
+  bt_dev.br.mtu = sys_le16_to_cpu(rp->acl_max_len);
+  pkts          = sys_le16_to_cpu(rp->acl_max_num);
 
-    BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.br.mtu);
+  BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.br.mtu);
 
-    k_sem_init(&bt_dev.br.pkts, pkts, pkts);
+  k_sem_init(&bt_dev.br.pkts, pkts, pkts);
 }
 #elif defined(CONFIG_BT_CONN)
-static void read_buffer_size_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data;
-    u16_t pkts;
+static void read_buffer_size_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data;
+  u16_t                              pkts;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    /* If LE-side has buffers we can ignore the BR/EDR values */
-    if (bt_dev.le.mtu) {
-        return;
-    }
+  /* If LE-side has buffers we can ignore the BR/EDR values */
+  if (bt_dev.le.mtu) {
+    return;
+  }
 
-    bt_dev.le.mtu = sys_le16_to_cpu(rp->acl_max_len);
-    pkts = sys_le16_to_cpu(rp->acl_max_num);
+  bt_dev.le.mtu = sys_le16_to_cpu(rp->acl_max_len);
+  pkts          = sys_le16_to_cpu(rp->acl_max_num);
 
-    BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.le.mtu);
+  BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.le.mtu);
 
-    k_sem_init(&bt_dev.le.pkts, pkts, pkts);
+  k_sem_init(&bt_dev.le.pkts, pkts, pkts);
 }
 #endif
 
 #if defined(CONFIG_BT_CONN)
-static void le_read_buffer_size_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_le_read_buffer_size *rp = (void *)buf->data;
+static void le_read_buffer_size_complete(struct net_buf *buf) {
+  struct bt_hci_rp_le_read_buffer_size *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    bt_dev.le.mtu = sys_le16_to_cpu(rp->le_max_len);
-    if (!bt_dev.le.mtu) {
-        return;
-    }
+  bt_dev.le.mtu = sys_le16_to_cpu(rp->le_max_len);
+  if (!bt_dev.le.mtu) {
+    return;
+  }
 
-    BT_DBG("ACL LE buffers: pkts %u mtu %u", rp->le_max_num, bt_dev.le.mtu);
+  BT_DBG("ACL LE buffers: pkts %u mtu %u", rp->le_max_num, bt_dev.le.mtu);
 
-    k_sem_init(&bt_dev.le.pkts, rp->le_max_num, rp->le_max_num);
+  k_sem_init(&bt_dev.le.pkts, rp->le_max_num, rp->le_max_num);
 }
 #endif
 
-static void read_supported_commands_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_supported_commands *rp = (void *)buf->data;
+static void read_supported_commands_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_supported_commands *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    memcpy(bt_dev.supported_commands, rp->commands,
-           sizeof(bt_dev.supported_commands));
+  memcpy(bt_dev.supported_commands, rp->commands, sizeof(bt_dev.supported_commands));
 
-    /*
-	 * Report "LE Read Local P-256 Public Key" and "LE Generate DH Key" as
-	 * supported if TinyCrypt ECC is used for emulation.
-	 */
-    if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
-        bt_dev.supported_commands[34] |= 0x02;
-        bt_dev.supported_commands[34] |= 0x04;
-    }
+  /*
+   * Report "LE Read Local P-256 Public Key" and "LE Generate DH Key" as
+   * supported if TinyCrypt ECC is used for emulation.
+   */
+  if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
+    bt_dev.supported_commands[34] |= 0x02;
+    bt_dev.supported_commands[34] |= 0x04;
+  }
 }
 
-static void read_local_features_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_read_local_features *rp = (void *)buf->data;
+static void read_local_features_complete(struct net_buf *buf) {
+  struct bt_hci_rp_read_local_features *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    memcpy(bt_dev.features[0], rp->features, sizeof(bt_dev.features[0]));
+  memcpy(bt_dev.features[0], rp->features, sizeof(bt_dev.features[0]));
 }
 
-static void le_read_supp_states_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_le_read_supp_states *rp = (void *)buf->data;
+static void le_read_supp_states_complete(struct net_buf *buf) {
+  struct bt_hci_rp_le_read_supp_states *rp = (void *)buf->data;
 
-    BT_DBG("status 0x%02x", rp->status);
+  BT_DBG("status 0x%02x", rp->status);
 
-    bt_dev.le.states = sys_get_le64(rp->le_states);
+  bt_dev.le.states = sys_get_le64(rp->le_states);
 }
 
 #if defined(CONFIG_BT_SMP)
-static void le_read_resolving_list_size_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_le_read_rl_size *rp = (void *)buf->data;
+static void le_read_resolving_list_size_complete(struct net_buf *buf) {
+  struct bt_hci_rp_le_read_rl_size *rp = (void *)buf->data;
 
-    BT_DBG("Resolving List size %u", rp->rl_size);
+  BT_DBG("Resolving List size %u", rp->rl_size);
 
-    bt_dev.le.rl_size = rp->rl_size;
+  bt_dev.le.rl_size = rp->rl_size;
 }
 #endif /* defined(CONFIG_BT_SMP) */
 
 #if defined(CONFIG_BT_WHITELIST)
-static void le_read_wl_size_complete(struct net_buf *buf)
-{
-    struct bt_hci_rp_le_read_wl_size *rp =
-        (struct bt_hci_rp_le_read_wl_size *)buf->data;
+static void le_read_wl_size_complete(struct net_buf *buf) {
+  struct bt_hci_rp_le_read_wl_size *rp = (struct bt_hci_rp_le_read_wl_size *)buf->data;
 
-    BT_DBG("Whitelist size %u", rp->wl_size);
+  BT_DBG("Whitelist size %u", rp->wl_size);
 
-    bt_dev.le.wl_size = rp->wl_size;
+  bt_dev.le.wl_size = rp->wl_size;
 }
 #endif
 
-static int common_init(void)
-{
-    struct net_buf *rsp;
-    int err;
-
-    if (!(bt_dev.drv->quirks & BT_QUIRK_NO_RESET)) {
-        /* Send HCI_RESET */
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_RESET, NULL, &rsp);
-        if (err) {
-            return err;
-        }
-        hci_reset_complete(rsp);
-        net_buf_unref(rsp);
-    }
+static int common_init(void) {
+  struct net_buf *rsp;
+  int             err;
 
-    /* Read Local Supported Features */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_FEATURES, NULL, &rsp);
+  if (!(bt_dev.drv->quirks & BT_QUIRK_NO_RESET)) {
+    /* Send HCI_RESET */
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_RESET, NULL, &rsp);
     if (err) {
-        return err;
+      return err;
     }
-    read_local_features_complete(rsp);
+    hci_reset_complete(rsp);
     net_buf_unref(rsp);
+  }
 
-    /* Read Local Version Information */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_VERSION_INFO, NULL,
-                               &rsp);
-    if (err) {
-        return err;
-    }
-    read_local_ver_complete(rsp);
-    net_buf_unref(rsp);
+  /* Read Local Supported Features */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_FEATURES, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+  read_local_features_complete(rsp);
+  net_buf_unref(rsp);
 
-    /* Read Bluetooth Address */
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR)) {
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BD_ADDR, NULL, &rsp);
-        if (err) {
-            return err;
-        }
-        read_bdaddr_complete(rsp);
-        net_buf_unref(rsp);
-    }
+  /* Read Local Version Information */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_VERSION_INFO, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+  read_local_ver_complete(rsp);
+  net_buf_unref(rsp);
 
-    /* Read Local Supported Commands */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_SUPPORTED_COMMANDS, NULL,
-                               &rsp);
+  /* Read Bluetooth Address */
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR)) {
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BD_ADDR, NULL, &rsp);
     if (err) {
-        return err;
+      return err;
     }
-    read_supported_commands_complete(rsp);
+    read_bdaddr_complete(rsp);
     net_buf_unref(rsp);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_HOST_CRYPTO)) {
-        /* Initialize the PRNG so that it is safe to use it later
-		 * on in the initialization process.
-		 */
-        err = prng_init();
-        if (err) {
-            return err;
-        }
-    }
+  /* Read Local Supported Commands */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_SUPPORTED_COMMANDS, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+  read_supported_commands_complete(rsp);
+  net_buf_unref(rsp);
 
-#if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    err = set_flow_control();
+  if (IS_ENABLED(CONFIG_BT_HOST_CRYPTO)) {
+    /* Initialize the PRNG so that it is safe to use it later
+     * on in the initialization process.
+     */
+    err = prng_init();
     if (err) {
-        return err;
+      return err;
     }
+  }
+
+#if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
+  err = set_flow_control();
+  if (err) {
+    return err;
+  }
 #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */
 
-    return 0;
+  return 0;
 }
 
-static int le_set_event_mask(void)
-{
-    struct bt_hci_cp_le_set_event_mask *cp_mask;
-    struct net_buf *buf;
-    u64_t mask = 0U;
-
-    /* Set LE event mask */
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EVENT_MASK, sizeof(*cp_mask));
-    if (!buf) {
-        return -ENOBUFS;
-    }
-
-    cp_mask = net_buf_add(buf, sizeof(*cp_mask));
+static int le_set_event_mask(void) {
+  struct bt_hci_cp_le_set_event_mask *cp_mask;
+  struct net_buf                     *buf;
+  u64_t                               mask = 0U;
 
-    mask |= BT_EVT_MASK_LE_ADVERTISING_REPORT;
+  /* Set LE event mask */
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EVENT_MASK, sizeof(*cp_mask));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CONN)) {
-        if (IS_ENABLED(CONFIG_BT_SMP) &&
-            BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-            mask |= BT_EVT_MASK_LE_ENH_CONN_COMPLETE;
-        } else {
-            mask |= BT_EVT_MASK_LE_CONN_COMPLETE;
-        }
+  cp_mask = net_buf_add(buf, sizeof(*cp_mask));
 
-        mask |= BT_EVT_MASK_LE_CONN_UPDATE_COMPLETE;
-        mask |= BT_EVT_MASK_LE_REMOTE_FEAT_COMPLETE;
+  mask |= BT_EVT_MASK_LE_ADVERTISING_REPORT;
 
-        if (BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features)) {
-            mask |= BT_EVT_MASK_LE_CONN_PARAM_REQ;
-        }
+  if (IS_ENABLED(CONFIG_BT_CONN)) {
+    if (IS_ENABLED(CONFIG_BT_SMP) && BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      mask |= BT_EVT_MASK_LE_ENH_CONN_COMPLETE;
+    } else {
+      mask |= BT_EVT_MASK_LE_CONN_COMPLETE;
+    }
 
-        if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) &&
-            BT_FEAT_LE_DLE(bt_dev.le.features)) {
-            mask |= BT_EVT_MASK_LE_DATA_LEN_CHANGE;
-        }
+    mask |= BT_EVT_MASK_LE_CONN_UPDATE_COMPLETE;
+    mask |= BT_EVT_MASK_LE_REMOTE_FEAT_COMPLETE;
 
-        if (IS_ENABLED(CONFIG_BT_PHY_UPDATE) &&
-            (BT_FEAT_LE_PHY_2M(bt_dev.le.features) ||
-             BT_FEAT_LE_PHY_CODED(bt_dev.le.features))) {
-            mask |= BT_EVT_MASK_LE_PHY_UPDATE_COMPLETE;
-        }
+    if (BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features)) {
+      mask |= BT_EVT_MASK_LE_CONN_PARAM_REQ;
     }
 
-    if (IS_ENABLED(CONFIG_BT_SMP) &&
-        BT_FEAT_LE_ENCR(bt_dev.le.features)) {
-        mask |= BT_EVT_MASK_LE_LTK_REQUEST;
+    if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features)) {
+      mask |= BT_EVT_MASK_LE_DATA_LEN_CHANGE;
     }
 
-    /*
-	 * If "LE Read Local P-256 Public Key" and "LE Generate DH Key" are
-	 * supported we need to enable events generated by those commands.
-	 */
-    if (IS_ENABLED(CONFIG_BT_ECC) &&
-        (BT_CMD_TEST(bt_dev.supported_commands, 34, 1)) &&
-        (BT_CMD_TEST(bt_dev.supported_commands, 34, 2))) {
-        mask |= BT_EVT_MASK_LE_P256_PUBLIC_KEY_COMPLETE;
-        mask |= BT_EVT_MASK_LE_GENERATE_DHKEY_COMPLETE;
+    if (IS_ENABLED(CONFIG_BT_PHY_UPDATE) && (BT_FEAT_LE_PHY_2M(bt_dev.le.features) || BT_FEAT_LE_PHY_CODED(bt_dev.le.features))) {
+      mask |= BT_EVT_MASK_LE_PHY_UPDATE_COMPLETE;
     }
+  }
+
+  if (IS_ENABLED(CONFIG_BT_SMP) && BT_FEAT_LE_ENCR(bt_dev.le.features)) {
+    mask |= BT_EVT_MASK_LE_LTK_REQUEST;
+  }
+
+  /*
+   * If "LE Read Local P-256 Public Key" and "LE Generate DH Key" are
+   * supported we need to enable events generated by those commands.
+   */
+  if (IS_ENABLED(CONFIG_BT_ECC) && (BT_CMD_TEST(bt_dev.supported_commands, 34, 1)) && (BT_CMD_TEST(bt_dev.supported_commands, 34, 2))) {
+    mask |= BT_EVT_MASK_LE_P256_PUBLIC_KEY_COMPLETE;
+    mask |= BT_EVT_MASK_LE_GENERATE_DHKEY_COMPLETE;
+  }
 
-    sys_put_le64(mask, cp_mask->events);
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EVENT_MASK, buf, NULL);
+  sys_put_le64(mask, cp_mask->events);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EVENT_MASK, buf, NULL);
 }
 
-static int le_init(void)
-{
-    struct bt_hci_cp_write_le_host_supp *cp_le;
-    struct net_buf *buf, *rsp;
-    int err;
+static int le_init(void) {
+  struct bt_hci_cp_write_le_host_supp *cp_le;
+  struct net_buf                      *buf, *rsp;
+  int                                  err;
 
-    /* For now we only support LE capable controllers */
-    if (!BT_FEAT_LE(bt_dev.features)) {
-        BT_ERR("Non-LE capable controller detected!");
-        return -ENODEV;
-    }
+  /* For now we only support LE capable controllers */
+  if (!BT_FEAT_LE(bt_dev.features)) {
+    BT_ERR("Non-LE capable controller detected!");
+    return -ENODEV;
+  }
 
-    /* Read Low Energy Supported Features */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_LOCAL_FEATURES, NULL,
-                               &rsp);
-    if (err) {
-        return err;
-    }
-    read_le_features_complete(rsp);
-    net_buf_unref(rsp);
+  /* Read Low Energy Supported Features */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_LOCAL_FEATURES, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+  read_le_features_complete(rsp);
+  net_buf_unref(rsp);
 
 #if defined(CONFIG_BT_CONN)
-    /* Read LE Buffer Size */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_BUFFER_SIZE,
-                               NULL, &rsp);
-    if (err) {
-        return err;
-    }
-    le_read_buffer_size_complete(rsp);
-    net_buf_unref(rsp);
+  /* Read LE Buffer Size */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_BUFFER_SIZE, NULL, &rsp);
+  if (err) {
+    return err;
+  }
+  le_read_buffer_size_complete(rsp);
+  net_buf_unref(rsp);
 #endif
 
-    if (BT_FEAT_BREDR(bt_dev.features)) {
-        buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP,
-                                sizeof(*cp_le));
-        if (!buf) {
-            return -ENOBUFS;
-        }
+  if (BT_FEAT_BREDR(bt_dev.features)) {
+    buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, sizeof(*cp_le));
+    if (!buf) {
+      return -ENOBUFS;
+    }
 
-        cp_le = net_buf_add(buf, sizeof(*cp_le));
+    cp_le = net_buf_add(buf, sizeof(*cp_le));
 
-        /* Explicitly enable LE for dual-mode controllers */
-        cp_le->le = 0x01;
-        cp_le->simul = 0x00;
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, buf,
-                                   NULL);
-        if (err) {
-            return err;
-        }
+    /* Explicitly enable LE for dual-mode controllers */
+    cp_le->le    = 0x01;
+    cp_le->simul = 0x00;
+    err          = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, buf, NULL);
+    if (err) {
+      return err;
     }
+  }
 
-    /* Read LE Supported States */
-    if (BT_CMD_LE_STATES(bt_dev.supported_commands)) {
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_SUPP_STATES, NULL,
-                                   &rsp);
-        if (err) {
-            return err;
-        }
-        le_read_supp_states_complete(rsp);
-        net_buf_unref(rsp);
+  /* Read LE Supported States */
+  if (BT_CMD_LE_STATES(bt_dev.supported_commands)) {
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_SUPP_STATES, NULL, &rsp);
+    if (err) {
+      return err;
     }
+    le_read_supp_states_complete(rsp);
+    net_buf_unref(rsp);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CONN) &&
-        IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) &&
-        BT_FEAT_LE_DLE(bt_dev.le.features)) {
-        struct bt_hci_cp_le_write_default_data_len *cp;
-        struct bt_hci_rp_le_read_max_data_len *rp;
-        u16_t tx_octets, tx_time;
+  if (IS_ENABLED(CONFIG_BT_CONN) && IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && BT_FEAT_LE_DLE(bt_dev.le.features)) {
+    struct bt_hci_cp_le_write_default_data_len *cp;
+    struct bt_hci_rp_le_read_max_data_len      *rp;
+    u16_t                                       tx_octets, tx_time;
 
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL,
-                                   &rsp);
-        if (err) {
-            return err;
-        }
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, &rsp);
+    if (err) {
+      return err;
+    }
 
-        rp = (void *)rsp->data;
-        tx_octets = sys_le16_to_cpu(rp->max_tx_octets);
-        tx_time = sys_le16_to_cpu(rp->max_tx_time);
-        net_buf_unref(rsp);
+    rp        = (void *)rsp->data;
+    tx_octets = sys_le16_to_cpu(rp->max_tx_octets);
+    tx_time   = sys_le16_to_cpu(rp->max_tx_time);
+    net_buf_unref(rsp);
 
-        buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN,
-                                sizeof(*cp));
-        if (!buf) {
-            return -ENOBUFS;
-        }
+    buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, sizeof(*cp));
+    if (!buf) {
+      return -ENOBUFS;
+    }
 
-        cp = net_buf_add(buf, sizeof(*cp));
-        cp->max_tx_octets = sys_cpu_to_le16(tx_octets);
-        cp->max_tx_time = sys_cpu_to_le16(tx_time);
+    cp                = net_buf_add(buf, sizeof(*cp));
+    cp->max_tx_octets = sys_cpu_to_le16(tx_octets);
+    cp->max_tx_time   = sys_cpu_to_le16(tx_time);
 
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN,
-                                   buf, NULL);
-        if (err) {
-            return err;
-        }
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, buf, NULL);
+    if (err) {
+      return err;
     }
+  }
 
 #if defined(CONFIG_BT_SMP)
-    if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+  if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
 #if defined(CONFIG_BT_PRIVACY)
-        struct bt_hci_cp_le_set_rpa_timeout *cp;
+    struct bt_hci_cp_le_set_rpa_timeout *cp;
 
-        buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RPA_TIMEOUT,
-                                sizeof(*cp));
-        if (!buf) {
-            return -ENOBUFS;
-        }
+    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RPA_TIMEOUT, sizeof(*cp));
+    if (!buf) {
+      return -ENOBUFS;
+    }
 
-        cp = net_buf_add(buf, sizeof(*cp));
-        cp->rpa_timeout = sys_cpu_to_le16(CONFIG_BT_RPA_TIMEOUT);
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RPA_TIMEOUT, buf,
-                                   NULL);
-        if (err) {
-            return err;
-        }
+    cp              = net_buf_add(buf, sizeof(*cp));
+    cp->rpa_timeout = sys_cpu_to_le16(CONFIG_BT_RPA_TIMEOUT);
+    err             = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RPA_TIMEOUT, buf, NULL);
+    if (err) {
+      return err;
+    }
 #endif /* defined(CONFIG_BT_PRIVACY) */
 
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_RL_SIZE, NULL,
-                                   &rsp);
-        if (err) {
-            return err;
-        }
-        le_read_resolving_list_size_complete(rsp);
-        net_buf_unref(rsp);
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_RL_SIZE, NULL, &rsp);
+    if (err) {
+      return err;
     }
+    le_read_resolving_list_size_complete(rsp);
+    net_buf_unref(rsp);
+  }
 #endif
 
 #if defined(CONFIG_BT_WHITELIST)
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_WL_SIZE, NULL,
-                               &rsp);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_WL_SIZE, NULL, &rsp);
+  if (err) {
+    return err;
+  }
 
-    le_read_wl_size_complete(rsp);
-    net_buf_unref(rsp);
+  le_read_wl_size_complete(rsp);
+  net_buf_unref(rsp);
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-    return le_set_event_mask();
+  return le_set_event_mask();
 }
 
 #if defined(CONFIG_BT_BREDR)
-static int read_ext_features(void)
-{
-    int i;
-
-    /* Read Local Supported Extended Features */
-    for (i = 1; i < LMP_FEAT_PAGES_COUNT; i++) {
-        struct bt_hci_cp_read_local_ext_features *cp;
-        struct bt_hci_rp_read_local_ext_features *rp;
-        struct net_buf *buf, *rsp;
-        int err;
-
-        buf = bt_hci_cmd_create(BT_HCI_OP_READ_LOCAL_EXT_FEATURES,
-                                sizeof(*cp));
-        if (!buf) {
-            return -ENOBUFS;
-        }
+static int read_ext_features(void) {
+  int i;
 
-        cp = net_buf_add(buf, sizeof(*cp));
-        cp->page = i;
+  /* Read Local Supported Extended Features */
+  for (i = 1; i < LMP_FEAT_PAGES_COUNT; i++) {
+    struct bt_hci_cp_read_local_ext_features *cp;
+    struct bt_hci_rp_read_local_ext_features *rp;
+    struct net_buf                           *buf, *rsp;
+    int                                       err;
 
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_EXT_FEATURES,
-                                   buf, &rsp);
-        if (err) {
-            return err;
-        }
+    buf = bt_hci_cmd_create(BT_HCI_OP_READ_LOCAL_EXT_FEATURES, sizeof(*cp));
+    if (!buf) {
+      return -ENOBUFS;
+    }
+
+    cp       = net_buf_add(buf, sizeof(*cp));
+    cp->page = i;
 
-        rp = (void *)rsp->data;
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_EXT_FEATURES, buf, &rsp);
+    if (err) {
+      return err;
+    }
 
-        memcpy(&bt_dev.features[i], rp->ext_features,
-               sizeof(bt_dev.features[i]));
+    rp = (void *)rsp->data;
 
-        if (rp->max_page <= i) {
-            net_buf_unref(rsp);
-            break;
-        }
+    memcpy(&bt_dev.features[i], rp->ext_features, sizeof(bt_dev.features[i]));
 
-        net_buf_unref(rsp);
+    if (rp->max_page <= i) {
+      net_buf_unref(rsp);
+      break;
     }
 
-    return 0;
+    net_buf_unref(rsp);
+  }
+
+  return 0;
 }
 
-void device_supported_pkt_type(void)
-{
-    /* Device supported features and sco packet types */
-    if (BT_FEAT_HV2_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV2);
-    }
+void device_supported_pkt_type(void) {
+  /* Device supported features and sco packet types */
+  if (BT_FEAT_HV2_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV2);
+  }
 
-    if (BT_FEAT_HV3_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV3);
-    }
+  if (BT_FEAT_HV3_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV3);
+  }
 
-    if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV3);
-    }
+  if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV3);
+  }
 
-    if (BT_FEAT_EV4_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV4);
-    }
+  if (BT_FEAT_EV4_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV4);
+  }
 
-    if (BT_FEAT_EV5_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV5);
-    }
+  if (BT_FEAT_EV5_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV5);
+  }
 
-    if (BT_FEAT_2EV3_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV3);
-    }
+  if (BT_FEAT_2EV3_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV3);
+  }
 
-    if (BT_FEAT_3EV3_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_3EV3);
-    }
+  if (BT_FEAT_3EV3_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_3EV3);
+  }
 
-    if (BT_FEAT_3SLOT_PKT(bt_dev.features)) {
-        bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV5 |
-                                    HCI_PKT_TYPE_ESCO_3EV5);
-    }
+  if (BT_FEAT_3SLOT_PKT(bt_dev.features)) {
+    bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV5 | HCI_PKT_TYPE_ESCO_3EV5);
+  }
 }
 
-static int br_init(void)
-{
-    struct net_buf *buf;
-    struct bt_hci_cp_write_ssp_mode *ssp_cp;
-    struct bt_hci_cp_write_inquiry_mode *inq_cp;
-    struct bt_hci_write_local_name *name_cp;
-    int err;
-
-    /* Read extended local features */
-    if (BT_FEAT_EXT_FEATURES(bt_dev.features)) {
-        err = read_ext_features();
-        if (err) {
-            return err;
-        }
-    }
-
-    /* Add local supported packet types to bt_dev */
-    device_supported_pkt_type();
+static int br_init(void) {
+  struct net_buf                               *buf;
+  struct bt_hci_cp_write_ssp_mode              *ssp_cp;
+  struct bt_hci_cp_write_class_of_device       *cod_cp;
+  struct bt_hci_cp_write_inquiry_scan_activity *inq_scan_act_cp;
+  struct bt_hci_cp_write_inquiry_scan_type     *inq_scan_cp;
+  struct bt_hci_cp_write_page_scan_type        *page_scan_cp;
+  struct bt_hci_cp_write_inquiry_mode          *inq_cp;
+  struct bt_hci_write_local_name               *name_cp;
+  int                                           err;
 
-    /* Get BR/EDR buffer size */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &buf);
+  /* Read extended local features */
+  if (BT_FEAT_EXT_FEATURES(bt_dev.features)) {
+    err = read_ext_features();
     if (err) {
-        return err;
+      return err;
     }
+  }
 
-    read_buffer_size_complete(buf);
-    net_buf_unref(buf);
+  /* Add local supported packet types to bt_dev */
+  device_supported_pkt_type();
 
-    /* Set SSP mode */
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SSP_MODE, sizeof(*ssp_cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  /* Get BR/EDR buffer size */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &buf);
+  if (err) {
+    return err;
+  }
 
-    ssp_cp = net_buf_add(buf, sizeof(*ssp_cp));
-    ssp_cp->mode = 0x01;
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SSP_MODE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  read_buffer_size_complete(buf);
+  net_buf_unref(buf);
 
-    /* Enable Inquiry results with RSSI or extended Inquiry */
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_INQUIRY_MODE, sizeof(*inq_cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  /* Set SSP mode */
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SSP_MODE, sizeof(*ssp_cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    inq_cp = net_buf_add(buf, sizeof(*inq_cp));
-    inq_cp->mode = 0x02;
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_INQUIRY_MODE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  ssp_cp       = net_buf_add(buf, sizeof(*ssp_cp));
+  ssp_cp->mode = 0x01;
+  err          = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SSP_MODE, buf, NULL);
+  if (err) {
+    return err;
+  }
+
+  /* Write Class of Device */
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_CLASS_OF_DEVICE, sizeof(*cod_cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
+
+  cod_cp     = net_buf_add(buf, sizeof(*cod_cp));
+  u8_t cd[3] = {0x14, 0x04, 0x24};
+  memcpy(cod_cp->cod, cd, 3);
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_CLASS_OF_DEVICE, buf, NULL);
+  if (err) {
+    return err;
+  }
+
+  /* Write Inquiry Scan Activity */
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_INQUIRY_SCAN_ACTIVITY, sizeof(*inq_scan_act_cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
+
+  inq_scan_act_cp           = net_buf_add(buf, sizeof(*inq_scan_act_cp));
+  inq_scan_act_cp->interval = 0x0400;
+  inq_scan_act_cp->window   = 0x0012;
+  err                       = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_INQUIRY_SCAN_ACTIVITY, buf, NULL);
+  if (err) {
+    return err;
+  }
+
+  /* Write Inquiry Scan type with Interlaced */
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_INQUIRY_SCAN_TYPE, sizeof(*inq_scan_cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
+
+  inq_scan_cp       = net_buf_add(buf, sizeof(*inq_scan_cp));
+  inq_scan_cp->type = 0x01;
+  err               = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_INQUIRY_SCAN_TYPE, buf, NULL);
+  if (err) {
+    return err;
+  }
+
+  /* Write Page Scan type with Interlaced */
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_PAGE_SCAN_TYPE, sizeof(*page_scan_cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
+
+  page_scan_cp       = net_buf_add(buf, sizeof(*page_scan_cp));
+  page_scan_cp->type = 0x01;
+  err                = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_PAGE_SCAN_TYPE, buf, NULL);
+  if (err) {
+    return err;
+  }
+
+  /* Enable Inquiry results with RSSI or extended Inquiry */
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_INQUIRY_MODE, sizeof(*inq_cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
+
+  inq_cp       = net_buf_add(buf, sizeof(*inq_cp));
+  inq_cp->mode = 0x02;
+  err          = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_INQUIRY_MODE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    /* Set local name */
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_LOCAL_NAME, sizeof(*name_cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  /* Set local name */
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_LOCAL_NAME, sizeof(*name_cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    name_cp = net_buf_add(buf, sizeof(*name_cp));
-    strncpy((char *)name_cp->local_name, CONFIG_BT_DEVICE_NAME,
-            sizeof(name_cp->local_name));
+  name_cp = net_buf_add(buf, sizeof(*name_cp));
+  strncpy((char *)name_cp->local_name, CONFIG_BT_DEVICE_NAME, sizeof(name_cp->local_name));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_LOCAL_NAME, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_LOCAL_NAME, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    /* Set page timeout*/
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_PAGE_TIMEOUT, sizeof(u16_t));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  /* Set page timeout*/
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_PAGE_TIMEOUT, sizeof(u16_t));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_le16(buf, CONFIG_BT_PAGE_TIMEOUT);
+  net_buf_add_le16(buf, CONFIG_BT_PAGE_TIMEOUT);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_PAGE_TIMEOUT, buf, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_PAGE_TIMEOUT, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    /* Enable BR/EDR SC if supported */
-    if (BT_FEAT_SC(bt_dev.features)) {
-        struct bt_hci_cp_write_sc_host_supp *sc_cp;
+  /* Enable BR/EDR SC if supported */
+  if (BT_FEAT_SC(bt_dev.features)) {
+    struct bt_hci_cp_write_sc_host_supp *sc_cp;
 
-        buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SC_HOST_SUPP,
-                                sizeof(*sc_cp));
-        if (!buf) {
-            return -ENOBUFS;
-        }
+    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SC_HOST_SUPP, sizeof(*sc_cp));
+    if (!buf) {
+      return -ENOBUFS;
+    }
 
-        sc_cp = net_buf_add(buf, sizeof(*sc_cp));
-        sc_cp->sc_support = 0x01;
+    sc_cp             = net_buf_add(buf, sizeof(*sc_cp));
+    sc_cp->sc_support = 0x01;
 
-        err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SC_HOST_SUPP, buf,
-                                   NULL);
-        if (err) {
-            return err;
-        }
+    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SC_HOST_SUPP, buf, NULL);
+    if (err) {
+      return err;
     }
+  }
 
-    return 0;
+  return 0;
 }
 #else
-static int br_init(void)
-{
+static int br_init(void) {
 #if defined(CONFIG_BT_CONN)
-    struct net_buf *rsp;
-    int err;
+  struct net_buf *rsp;
+  int             err;
 
-    if (bt_dev.le.mtu) {
-        return 0;
-    }
+  if (bt_dev.le.mtu) {
+    return 0;
+  }
 
-    /* Use BR/EDR buffer size if LE reports zero buffers */
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &rsp);
-    if (err) {
-        return err;
-    }
+  /* Use BR/EDR buffer size if LE reports zero buffers */
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &rsp);
+  if (err) {
+    return err;
+  }
 
-    read_buffer_size_complete(rsp);
-    net_buf_unref(rsp);
+  read_buffer_size_complete(rsp);
+  net_buf_unref(rsp);
 #endif /* CONFIG_BT_CONN */
 
-    return 0;
+  return 0;
 }
 #endif
 
-static int set_event_mask(void)
-{
-    struct bt_hci_cp_set_event_mask *ev;
-    struct net_buf *buf;
-    u64_t mask = 0U;
-
-    buf = bt_hci_cmd_create(BT_HCI_OP_SET_EVENT_MASK, sizeof(*ev));
-    if (!buf) {
-        return -ENOBUFS;
-    }
-
-    ev = net_buf_add(buf, sizeof(*ev));
-
-    if (IS_ENABLED(CONFIG_BT_BREDR)) {
-        /* Since we require LE support, we can count on a
-		 * Bluetooth 4.0 feature set
-		 */
-        mask |= BT_EVT_MASK_INQUIRY_COMPLETE;
-        mask |= BT_EVT_MASK_CONN_COMPLETE;
-        mask |= BT_EVT_MASK_CONN_REQUEST;
-        mask |= BT_EVT_MASK_AUTH_COMPLETE;
-        mask |= BT_EVT_MASK_REMOTE_NAME_REQ_COMPLETE;
-        mask |= BT_EVT_MASK_REMOTE_FEATURES;
-        mask |= BT_EVT_MASK_ROLE_CHANGE;
-        mask |= BT_EVT_MASK_PIN_CODE_REQ;
-        mask |= BT_EVT_MASK_LINK_KEY_REQ;
-        mask |= BT_EVT_MASK_LINK_KEY_NOTIFY;
-        mask |= BT_EVT_MASK_INQUIRY_RESULT_WITH_RSSI;
-        mask |= BT_EVT_MASK_REMOTE_EXT_FEATURES;
-        mask |= BT_EVT_MASK_SYNC_CONN_COMPLETE;
-        mask |= BT_EVT_MASK_EXTENDED_INQUIRY_RESULT;
-        mask |= BT_EVT_MASK_IO_CAPA_REQ;
-        mask |= BT_EVT_MASK_IO_CAPA_RESP;
-        mask |= BT_EVT_MASK_USER_CONFIRM_REQ;
-        mask |= BT_EVT_MASK_USER_PASSKEY_REQ;
-        mask |= BT_EVT_MASK_SSP_COMPLETE;
-        mask |= BT_EVT_MASK_USER_PASSKEY_NOTIFY;
-    }
-
-    mask |= BT_EVT_MASK_HARDWARE_ERROR;
-    mask |= BT_EVT_MASK_DATA_BUFFER_OVERFLOW;
-    mask |= BT_EVT_MASK_LE_META_EVENT;
-
-    if (IS_ENABLED(CONFIG_BT_CONN)) {
-        mask |= BT_EVT_MASK_DISCONN_COMPLETE;
-        mask |= BT_EVT_MASK_REMOTE_VERSION_INFO;
-    }
-
-    if (IS_ENABLED(CONFIG_BT_SMP) &&
-        BT_FEAT_LE_ENCR(bt_dev.le.features)) {
-        mask |= BT_EVT_MASK_ENCRYPT_CHANGE;
-        mask |= BT_EVT_MASK_ENCRYPT_KEY_REFRESH_COMPLETE;
-    }
-
-    sys_put_le64(mask, ev->events);
-    return bt_hci_cmd_send_sync(BT_HCI_OP_SET_EVENT_MASK, buf, NULL);
-}
-
-static inline int create_random_addr(bt_addr_le_t *addr)
-{
-    addr->type = BT_ADDR_LE_RANDOM;
-
-    return bt_rand(addr->a.val, 6);
-}
+static int set_event_mask(void) {
+  struct bt_hci_cp_set_event_mask *ev;
+  struct net_buf                  *buf;
+  u64_t                            mask = 0U;
 
-int bt_addr_le_create_nrpa(bt_addr_le_t *addr)
-{
-    int err;
+  buf = bt_hci_cmd_create(BT_HCI_OP_SET_EVENT_MASK, sizeof(*ev));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    err = create_random_addr(addr);
-    if (err) {
-        return err;
-    }
+  ev = net_buf_add(buf, sizeof(*ev));
 
-    BT_ADDR_SET_NRPA(&addr->a);
+  if (IS_ENABLED(CONFIG_BT_BREDR)) {
+    /* Since we require LE support, we can count on a
+     * Bluetooth 4.0 feature set
+     */
+    mask |= BT_EVT_MASK_INQUIRY_COMPLETE;
+    mask |= BT_EVT_MASK_CONN_COMPLETE;
+    mask |= BT_EVT_MASK_CONN_REQUEST;
+    mask |= BT_EVT_MASK_AUTH_COMPLETE;
+    mask |= BT_EVT_MASK_REMOTE_NAME_REQ_COMPLETE;
+    mask |= BT_EVT_MASK_REMOTE_FEATURES;
+    mask |= BT_EVT_MASK_ROLE_CHANGE;
+    mask |= BT_EVT_MASK_PIN_CODE_REQ;
+    mask |= BT_EVT_MASK_LINK_KEY_REQ;
+    mask |= BT_EVT_MASK_LINK_KEY_NOTIFY;
+    mask |= BT_EVT_MASK_INQUIRY_RESULT_WITH_RSSI;
+    mask |= BT_EVT_MASK_REMOTE_EXT_FEATURES;
+    mask |= BT_EVT_MASK_SYNC_CONN_COMPLETE;
+    mask |= BT_EVT_MASK_EXTENDED_INQUIRY_RESULT;
+    mask |= BT_EVT_MASK_IO_CAPA_REQ;
+    mask |= BT_EVT_MASK_IO_CAPA_RESP;
+    mask |= BT_EVT_MASK_USER_CONFIRM_REQ;
+    mask |= BT_EVT_MASK_USER_PASSKEY_REQ;
+    mask |= BT_EVT_MASK_SSP_COMPLETE;
+    mask |= BT_EVT_MASK_USER_PASSKEY_NOTIFY;
+  }
+
+  mask |= BT_EVT_MASK_HARDWARE_ERROR;
+  mask |= BT_EVT_MASK_DATA_BUFFER_OVERFLOW;
+  mask |= BT_EVT_MASK_LE_META_EVENT;
+
+  if (IS_ENABLED(CONFIG_BT_CONN)) {
+    mask |= BT_EVT_MASK_DISCONN_COMPLETE;
+    mask |= BT_EVT_MASK_REMOTE_VERSION_INFO;
+  }
+
+  if (IS_ENABLED(CONFIG_BT_SMP) && BT_FEAT_LE_ENCR(bt_dev.le.features)) {
+    mask |= BT_EVT_MASK_ENCRYPT_CHANGE;
+    mask |= BT_EVT_MASK_ENCRYPT_KEY_REFRESH_COMPLETE;
+  }
+
+  sys_put_le64(mask, ev->events);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_SET_EVENT_MASK, buf, NULL);
+}
+
+static inline int create_random_addr(bt_addr_le_t *addr) {
+  addr->type = BT_ADDR_LE_RANDOM;
+
+  return bt_rand(addr->a.val, 6);
+}
+
+int bt_addr_le_create_nrpa(bt_addr_le_t *addr) {
+  int err;
+
+  err = create_random_addr(addr);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  BT_ADDR_SET_NRPA(&addr->a);
+
+  return 0;
 }
 
-int bt_addr_le_create_static(bt_addr_le_t *addr)
-{
-    int err;
+int bt_addr_le_create_static(bt_addr_le_t *addr) {
+  int err;
 
-    err = create_random_addr(addr);
-    if (err) {
-        return err;
-    }
+  err = create_random_addr(addr);
+  if (err) {
+    return err;
+  }
 
-    BT_ADDR_SET_STATIC(&addr->a);
+  BT_ADDR_SET_STATIC(&addr->a);
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_DEBUG)
@@ -5097,8 +5034,7 @@ static const char *ver_str(u8_t ver)
 }
 #endif
 
-static void bt_dev_show_info(void)
-{
+static void bt_dev_show_info(void) {
 #if 0
 	int i;
 
@@ -5119,600 +5055,565 @@ static void bt_dev_show_info(void)
 #endif
 }
 #else
-static inline void bt_dev_show_info(void)
-{
-}
+static inline void bt_dev_show_info(void) {}
 #endif /* CONFIG_BT_DEBUG */
 
 #if defined(CONFIG_BT_HCI_VS_EXT)
 #if defined(CONFIG_BT_DEBUG)
-static const char *vs_hw_platform(u16_t platform)
-{
-    static const char *const plat_str[] = {
-        "reserved", "Intel Corporation", "Nordic Semiconductor",
-        "NXP Semiconductors"
-    };
+static const char *vs_hw_platform(u16_t platform) {
+  static const char *const plat_str[] = {"reserved", "Intel Corporation", "Nordic Semiconductor", "NXP Semiconductors"};
 
-    if (platform < ARRAY_SIZE(plat_str)) {
-        return plat_str[platform];
-    }
+  if (platform < ARRAY_SIZE(plat_str)) {
+    return plat_str[platform];
+  }
 
-    return "unknown";
+  return "unknown";
 }
 
-static const char *vs_hw_variant(u16_t platform, u16_t variant)
-{
-    static const char *const nordic_str[] = {
-        "reserved", "nRF51x", "nRF52x", "nRF53x"
-    };
+static const char *vs_hw_variant(u16_t platform, u16_t variant) {
+  static const char *const nordic_str[] = {"reserved", "nRF51x", "nRF52x", "nRF53x"};
 
-    if (platform != BT_HCI_VS_HW_PLAT_NORDIC) {
-        return "unknown";
-    }
+  if (platform != BT_HCI_VS_HW_PLAT_NORDIC) {
+    return "unknown";
+  }
 
-    if (variant < ARRAY_SIZE(nordic_str)) {
-        return nordic_str[variant];
-    }
+  if (variant < ARRAY_SIZE(nordic_str)) {
+    return nordic_str[variant];
+  }
 
-    return "unknown";
+  return "unknown";
 }
 
-static const char *vs_fw_variant(u8_t variant)
-{
-    static const char *const var_str[] = {
-        "Standard Bluetooth controller",
-        "Vendor specific controller",
-        "Firmware loader",
-        "Rescue image",
-    };
+static const char *vs_fw_variant(u8_t variant) {
+  static const char *const var_str[] = {
+      "Standard Bluetooth controller",
+      "Vendor specific controller",
+      "Firmware loader",
+      "Rescue image",
+  };
 
-    if (variant < ARRAY_SIZE(var_str)) {
-        return var_str[variant];
-    }
+  if (variant < ARRAY_SIZE(var_str)) {
+    return var_str[variant];
+  }
 
-    return "unknown";
+  return "unknown";
 }
 #endif /* CONFIG_BT_DEBUG */
 
-static void hci_vs_init(void)
-{
-    union {
-        struct bt_hci_rp_vs_read_version_info *info;
-        struct bt_hci_rp_vs_read_supported_commands *cmds;
-        struct bt_hci_rp_vs_read_supported_features *feat;
-    } rp;
-    struct net_buf *rsp;
-    int err;
-
-    /* If heuristics is enabled, try to guess HCI VS support by looking
-	 * at the HCI version and identity address. We haven't tried to set
-	 * a static random address yet at this point, so the identity will
-	 * either be zeroes or a valid public address.
-	 */
-    if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) &&
-        (bt_dev.hci_version < BT_HCI_VERSION_5_0 ||
-         (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR) &&
-          bt_addr_le_cmp(&bt_dev.id_addr[0], BT_ADDR_LE_ANY)))) {
-        BT_WARN("Controller doesn't seem to support Zephyr vendor HCI");
-        return;
-    }
+static void hci_vs_init(void) {
+  union {
+    struct bt_hci_rp_vs_read_version_info       *info;
+    struct bt_hci_rp_vs_read_supported_commands *cmds;
+    struct bt_hci_rp_vs_read_supported_features *feat;
+  } rp;
+  struct net_buf *rsp;
+  int             err;
+
+  /* If heuristics is enabled, try to guess HCI VS support by looking
+   * at the HCI version and identity address. We haven't tried to set
+   * a static random address yet at this point, so the identity will
+   * either be zeroes or a valid public address.
+   */
+  if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) &&
+      (bt_dev.hci_version < BT_HCI_VERSION_5_0 || (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR) && bt_addr_le_cmp(&bt_dev.id_addr[0], BT_ADDR_LE_ANY)))) {
+    BT_WARN("Controller doesn't seem to support Zephyr vendor HCI");
+    return;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_VERSION_INFO, NULL, &rsp);
-    if (err) {
-        BT_WARN("Vendor HCI extensions not available");
-        return;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_VERSION_INFO, NULL, &rsp);
+  if (err) {
+    BT_WARN("Vendor HCI extensions not available");
+    return;
+  }
 
 #if defined(CONFIG_BT_DEBUG)
-    rp.info = (void *)rsp->data;
-    BT_INFO("HW Platform: %s (0x%04x)",
-            vs_hw_platform(sys_le16_to_cpu(rp.info->hw_platform)),
-            sys_le16_to_cpu(rp.info->hw_platform));
-    BT_INFO("HW Variant: %s (0x%04x)",
-            vs_hw_variant(sys_le16_to_cpu(rp.info->hw_platform),
-                          sys_le16_to_cpu(rp.info->hw_variant)),
-            sys_le16_to_cpu(rp.info->hw_variant));
-    BT_INFO("Firmware: %s (0x%02x) Version %u.%u Build %u",
-            vs_fw_variant(rp.info->fw_variant), rp.info->fw_variant,
-            rp.info->fw_version, sys_le16_to_cpu(rp.info->fw_revision),
-            sys_le32_to_cpu(rp.info->fw_build));
+  rp.info = (void *)rsp->data;
+  BT_INFO("HW Platform: %s (0x%04x)", vs_hw_platform(sys_le16_to_cpu(rp.info->hw_platform)), sys_le16_to_cpu(rp.info->hw_platform));
+  BT_INFO("HW Variant: %s (0x%04x)", vs_hw_variant(sys_le16_to_cpu(rp.info->hw_platform), sys_le16_to_cpu(rp.info->hw_variant)), sys_le16_to_cpu(rp.info->hw_variant));
+  BT_INFO("Firmware: %s (0x%02x) Version %u.%u Build %u", vs_fw_variant(rp.info->fw_variant), rp.info->fw_variant, rp.info->fw_version, sys_le16_to_cpu(rp.info->fw_revision),
+          sys_le32_to_cpu(rp.info->fw_build));
 #endif /* CONFIG_BT_DEBUG */
 
-    net_buf_unref(rsp);
+  net_buf_unref(rsp);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS,
-                               NULL, &rsp);
-    if (err) {
-        BT_WARN("Failed to read supported vendor features");
-        return;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS, NULL, &rsp);
+  if (err) {
+    BT_WARN("Failed to read supported vendor features");
+    return;
+  }
 
-    rp.cmds = (void *)rsp->data;
-    memcpy(bt_dev.vs_commands, rp.cmds->commands, BT_DEV_VS_CMDS_MAX);
-    net_buf_unref(rsp);
+  rp.cmds = (void *)rsp->data;
+  memcpy(bt_dev.vs_commands, rp.cmds->commands, BT_DEV_VS_CMDS_MAX);
+  net_buf_unref(rsp);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_FEATURES,
-                               NULL, &rsp);
-    if (err) {
-        BT_WARN("Failed to read supported vendor commands");
-        return;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_FEATURES, NULL, &rsp);
+  if (err) {
+    BT_WARN("Failed to read supported vendor commands");
+    return;
+  }
 
-    rp.feat = (void *)rsp->data;
-    memcpy(bt_dev.vs_features, rp.feat->features, BT_DEV_VS_FEAT_MAX);
-    net_buf_unref(rsp);
+  rp.feat = (void *)rsp->data;
+  memcpy(bt_dev.vs_features, rp.feat->features, BT_DEV_VS_FEAT_MAX);
+  net_buf_unref(rsp);
 }
 #endif /* CONFIG_BT_HCI_VS_EXT */
 
-static int host_hci_init(void)
-{
-    int err;
-
-    err = common_init();
-    if (err) {
-        return err;
-    }
+static int host_hci_init(void) {
+  int err;
 
-    err = le_init();
-    if (err) {
-        return err;
-    }
+  err = common_init();
+  if (err) {
+    return err;
+  }
 
-    if (BT_FEAT_BREDR(bt_dev.features)) {
-        err = br_init();
-        if (err) {
-            return err;
-        }
-    } else if (IS_ENABLED(CONFIG_BT_BREDR)) {
-        BT_ERR("Non-BR/EDR controller detected");
-        return -EIO;
-    }
+  err = le_init();
+  if (err) {
+    return err;
+  }
 
-    err = set_event_mask();
+  if (BT_FEAT_BREDR(bt_dev.features)) {
+    err = br_init();
     if (err) {
-        return err;
+      return err;
     }
+  } else if (IS_ENABLED(CONFIG_BT_BREDR)) {
+    BT_ERR("Non-BR/EDR controller detected");
+    return -EIO;
+  }
+
+  err = set_event_mask();
+  if (err) {
+    return err;
+  }
 
 #if defined(CONFIG_BT_HCI_VS_EXT)
-    hci_vs_init();
+  hci_vs_init();
 #endif
 
-    if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) {
-        BT_DBG("No public address. Trying to set static random.");
-        err = bt_setup_id_addr();
-        if (err) {
-            BT_ERR("Unable to set identity address");
-            return err;
-        }
+  if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) {
+    BT_DBG("No public address. Trying to set static random.");
+    err = bt_setup_id_addr();
+    if (err) {
+      BT_ERR("Unable to set identity address");
+      return err;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
-int bt_send(struct net_buf *buf)
-{
-    BT_DBG("buf %p len %u type %u", buf, buf->len, bt_buf_get_type(buf));
+int bt_send(struct net_buf *buf) {
+  BT_DBG("buf %p len %u type %u", buf, buf->len, bt_buf_get_type(buf));
 
-    bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
+  bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
 
-    if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
-        return bt_hci_ecc_send(buf);
-    }
+  if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
+    return bt_hci_ecc_send(buf);
+  }
 
-    return bt_dev.drv->send(buf);
+  return bt_dev.drv->send(buf);
 }
 
-int bt_recv(struct net_buf *buf)
-{
-    bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
+int bt_recv(struct net_buf *buf) {
+  bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
 
-    BT_DBG("buf %p len %u", buf, buf->len);
+  BT_DBG("buf %p len %u", buf, buf->len);
 
-    switch (bt_buf_get_type(buf)) {
+  switch (bt_buf_get_type(buf)) {
 #if defined(CONFIG_BT_CONN)
-        case BT_BUF_ACL_IN:
+  case BT_BUF_ACL_IN:
 #if defined(CONFIG_BT_RECV_IS_RX_THREAD)
-            hci_acl(buf);
+    hci_acl(buf);
 #else
-            net_buf_put(&bt_dev.rx_queue, buf);
+    net_buf_put(&bt_dev.rx_queue, buf);
 #endif
-            return 0;
+    return 0;
 #endif /* BT_CONN */
-        case BT_BUF_EVT:
+  case BT_BUF_EVT:
 #if defined(CONFIG_BT_RECV_IS_RX_THREAD)
-            hci_event(buf);
+    hci_event(buf);
 #else
-            net_buf_put(&bt_dev.rx_queue, buf);
+    net_buf_put(&bt_dev.rx_queue, buf);
 #endif
-            return 0;
-        default:
-            BT_ERR("Invalid buf type %u", bt_buf_get_type(buf));
-            net_buf_unref(buf);
-            return -EINVAL;
-    }
+    return 0;
+  default:
+    BT_ERR("Invalid buf type %u", bt_buf_get_type(buf));
+    net_buf_unref(buf);
+    return -EINVAL;
+  }
 }
 
 static const struct event_handler prio_events[] = {
-    EVENT_HANDLER(BT_HCI_EVT_CMD_COMPLETE, hci_cmd_complete,
-                  sizeof(struct bt_hci_evt_cmd_complete)),
-    EVENT_HANDLER(BT_HCI_EVT_CMD_STATUS, hci_cmd_status,
-                  sizeof(struct bt_hci_evt_cmd_status)),
+    EVENT_HANDLER(BT_HCI_EVT_CMD_COMPLETE, hci_cmd_complete, sizeof(struct bt_hci_evt_cmd_complete)),
+    EVENT_HANDLER(BT_HCI_EVT_CMD_STATUS, hci_cmd_status, sizeof(struct bt_hci_evt_cmd_status)),
 #if defined(CONFIG_BT_CONN)
-    EVENT_HANDLER(BT_HCI_EVT_DATA_BUF_OVERFLOW,
-                  hci_data_buf_overflow,
-                  sizeof(struct bt_hci_evt_data_buf_overflow)),
-    EVENT_HANDLER(BT_HCI_EVT_NUM_COMPLETED_PACKETS,
-                  hci_num_completed_packets,
-                  sizeof(struct bt_hci_evt_num_completed_packets)),
+    EVENT_HANDLER(BT_HCI_EVT_DATA_BUF_OVERFLOW, hci_data_buf_overflow, sizeof(struct bt_hci_evt_data_buf_overflow)),
+    EVENT_HANDLER(BT_HCI_EVT_NUM_COMPLETED_PACKETS, hci_num_completed_packets, sizeof(struct bt_hci_evt_num_completed_packets)),
 #endif /* CONFIG_BT_CONN */
 };
 
-int bt_recv_prio(struct net_buf *buf)
-{
-    struct bt_hci_evt_hdr *hdr;
+int bt_recv_prio(struct net_buf *buf) {
+  struct bt_hci_evt_hdr *hdr;
 
-    bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
+  bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len);
 
-    BT_ASSERT(bt_buf_get_type(buf) == BT_BUF_EVT);
-    BT_ASSERT(buf->len >= sizeof(*hdr));
+  BT_ASSERT(bt_buf_get_type(buf) == BT_BUF_EVT);
+  BT_ASSERT(buf->len >= sizeof(*hdr));
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    BT_ASSERT(bt_hci_evt_is_prio(hdr->evt));
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  BT_ASSERT(bt_hci_evt_is_prio(hdr->evt));
 
-    handle_event(hdr->evt, buf, prio_events, ARRAY_SIZE(prio_events));
+  handle_event(hdr->evt, buf, prio_events, ARRAY_SIZE(prio_events));
 
-    net_buf_unref(buf);
+  net_buf_unref(buf);
 
-    return 0;
+  return 0;
 }
 
-int bt_hci_driver_register(const struct bt_hci_driver *drv)
-{
-    if (bt_dev.drv) {
-        return -EALREADY;
-    }
+int bt_hci_driver_register(const struct bt_hci_driver *drv) {
+  if (bt_dev.drv) {
+    return -EALREADY;
+  }
 
-    if (!drv->open || !drv->send) {
-        return -EINVAL;
-    }
+  if (!drv->open || !drv->send) {
+    return -EINVAL;
+  }
 
-    bt_dev.drv = drv;
+  bt_dev.drv = drv;
 
-    BT_DBG("Registered %s", drv->name ? drv->name : "");
+  BT_DBG("Registered %s", drv->name ? drv->name : "");
 
-    bt_monitor_new_index(BT_MONITOR_TYPE_PRIMARY, drv->bus,
-                         BT_ADDR_ANY, drv->name ? drv->name : "bt0");
+  bt_monitor_new_index(BT_MONITOR_TYPE_PRIMARY, drv->bus, BT_ADDR_ANY, drv->name ? drv->name : "bt0");
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_PRIVACY)
-static int irk_init(void)
-{
+static int irk_init(void) {
 #if (BFLB_FIXED_IRK)
-    //use fixed irk
-    memset(&bt_dev.irk[0], 0x11, 16);
-    return 0;
+  // use fixed irk
+  memset(&bt_dev.irk[0], 0x11, 16);
+  return 0;
 #endif
 #if defined(BFLB_BLE_PATCH_SETTINGS_LOAD)
-    u8_t empty_irk[16];
-    int err;
-    /*local irk has been loaded from flash in bt_enable, check if irk is null*/
-    memset(empty_irk, 0, 16);
-    if (memcmp(bt_dev.irk[0], empty_irk, 16) != 0)
-        return 0;
+  u8_t empty_irk[16];
+  int  err;
+  /*local irk has been loaded from flash in bt_enable, check if irk is null*/
+  memset(empty_irk, 0, 16);
+  if (memcmp(bt_dev.irk[0], empty_irk, 16) != 0)
+    return 0;
 
-    err = bt_rand(&bt_dev.irk[0], 16);
+  err = bt_rand(&bt_dev.irk[0], 16);
 
-    return err;
+  return err;
 #else
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        BT_DBG("Expecting settings to handle local IRK");
-    } else {
-        int err;
-
-        err = bt_rand(&bt_dev.irk[0], 16);
-        if (err) {
-            return err;
-        }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    BT_DBG("Expecting settings to handle local IRK");
+  } else {
+    int err;
 
-        BT_WARN("Using temporary IRK");
+    err = bt_rand(&bt_dev.irk[0], 16);
+    if (err) {
+      return err;
     }
 
-    return 0;
+    BT_WARN("Using temporary IRK");
+  }
+
+  return 0;
 #endif
 }
 #endif /* CONFIG_BT_PRIVACY */
-void bt_finalize_init(void)
-{
-    atomic_set_bit(bt_dev.flags, BT_DEV_READY);
+void bt_finalize_init(void) {
+  atomic_set_bit(bt_dev.flags, BT_DEV_READY);
 
-    if (IS_ENABLED(CONFIG_BT_OBSERVER)) {
-        bt_le_scan_update(false);
-    }
+  if (IS_ENABLED(CONFIG_BT_OBSERVER)) {
+    bt_le_scan_update(false);
+  }
 
-    bt_dev_show_info();
+  bt_dev_show_info();
 }
 
 #if defined(BFLB_HOST_ASSISTANT)
 extern void blhast_init(struct blhast_cb *cb);
 #endif
-static int bt_init(void)
-{
-    int err;
+static int bt_init(void) {
+  int err;
 #if defined(CONFIG_BT_STACK_PTS)
-    u8_t dbg_irk[16];
+  u8_t dbg_irk[16];
 #endif
 /*Make sure that freertos is running when set info into flash, because Semaphore is used in ef_set_env*/
 #if defined(BFLB_BLE_PATCH_SETTINGS_LOAD)
-    char empty_name[CONFIG_BT_DEVICE_NAME_MAX];
-    memset(empty_name, 0, CONFIG_BT_DEVICE_NAME_MAX);
+  char empty_name[CONFIG_BT_DEVICE_NAME_MAX];
+  memset(empty_name, 0, CONFIG_BT_DEVICE_NAME_MAX);
 
-    if (!memcmp(bt_dev.name, empty_name, CONFIG_BT_DEVICE_NAME_MAX))
-        bt_set_name(CONFIG_BT_DEVICE_NAME);
+  if (!memcmp(bt_dev.name, empty_name, CONFIG_BT_DEVICE_NAME_MAX))
+    bt_set_name(CONFIG_BT_DEVICE_NAME);
 #endif
 
 #if defined(BFLB_BLE)
-    err = bl_onchiphci_interface_init();
-    if (err) {
-        return err;
-    }
+  err = bl_onchiphci_interface_init();
+  if (err) {
+    return err;
+  }
 #if defined(BFLB_HOST_ASSISTANT)
-    blhast_init(host_assist_cb);
+  blhast_init(host_assist_cb);
 #endif
 #endif
 
-    err = host_hci_init();
+  err = host_hci_init();
+  if (err) {
+    return err;
+  }
+  if (IS_ENABLED(CONFIG_BT_CONN)) {
+    err = bt_conn_init();
     if (err) {
-        return err;
-    }
-    if (IS_ENABLED(CONFIG_BT_CONN)) {
-        err = bt_conn_init();
-        if (err) {
-            return err;
-        }
+      return err;
     }
+  }
 
 #if defined(CONFIG_BT_PRIVACY)
-    err = irk_init();
-    if (err) {
-        return err;
-    }
+  err = irk_init();
+  if (err) {
+    return err;
+  }
 #if defined(CONFIG_BT_STACK_PTS)
-    reverse_bytearray(bt_dev.irk[0], dbg_irk, sizeof(dbg_irk));
-    BT_PTS("Local IRK %s public identity bdaddr %s",
-           bt_hex(dbg_irk, 16), bt_addr_str(&(bt_dev.id_addr[0].a)));
+  reverse_bytearray(bt_dev.irk[0], dbg_irk, sizeof(dbg_irk));
+  BT_PTS("Local IRK %s public identity bdaddr %s", bt_hex(dbg_irk, 16), bt_addr_str(&(bt_dev.id_addr[0].a)));
 #endif
 
-    k_delayed_work_init(&bt_dev.rpa_update, rpa_timeout);
+  k_delayed_work_init(&bt_dev.rpa_update, rpa_timeout);
 #endif
 
 #if defined(CONFIG_BT_SMP)
 #if defined(BFLB_BLE_PATCH_SETTINGS_LOAD)
 #if defined(CFG_SLEEP)
-    if (HBN_Get_Status_Flag() == 0)
+  if (HBN_Get_Status_Flag() == 0)
 #endif
-    {
-        if (!bt_keys_load())
-            keys_commit();
-    }
+  {
+    if (!bt_keys_load())
+      keys_commit();
+  }
 #endif
-#endif //CONFIG_BT_SMP
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        if (!bt_dev.id_count) {
-            BT_INFO("No ID address. App must call settings_load()");
-            return 0;
-        }
-
-        atomic_set_bit(bt_dev.flags, BT_DEV_PRESET_ID);
+#endif // CONFIG_BT_SMP
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    if (!bt_dev.id_count) {
+      BT_INFO("No ID address. App must call settings_load()");
+      return 0;
     }
 
-    bt_finalize_init();
-    return 0;
+    atomic_set_bit(bt_dev.flags, BT_DEV_PRESET_ID);
+  }
+
+  bt_finalize_init();
+  return 0;
 }
 
-static void init_work(struct k_work *work)
-{
-    int err;
+static void init_work(struct k_work *work) {
+  int err;
 
-    err = bt_init();
-    if (ready_cb) {
-        ready_cb(err);
-    }
+  err = bt_init();
+  if (ready_cb) {
+    ready_cb(err);
+  }
 }
 
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
-static void hci_rx_thread(void)
-{
-    struct net_buf *buf;
+static void hci_rx_thread(void) {
+  struct net_buf *buf;
 
-    BT_DBG("started");
+  BT_DBG("started");
 
-    while (1) {
-        BT_DBG("calling fifo_get_wait");
-        buf = net_buf_get(&bt_dev.rx_queue, K_FOREVER);
+  while (1) {
+    BT_DBG("calling fifo_get_wait");
+    buf = net_buf_get(&bt_dev.rx_queue, K_FOREVER);
 
-        BT_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf),
-               buf->len);
+    BT_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf), buf->len);
 
-        switch (bt_buf_get_type(buf)) {
+    switch (bt_buf_get_type(buf)) {
 #if defined(CONFIG_BT_CONN)
-            case BT_BUF_ACL_IN:
-                hci_acl(buf);
-                break;
+    case BT_BUF_ACL_IN:
+      hci_acl(buf);
+      break;
 #endif /* CONFIG_BT_CONN */
-            case BT_BUF_EVT:
-                hci_event(buf);
-                break;
-            default:
-                BT_ERR("Unknown buf type %u", bt_buf_get_type(buf));
-                net_buf_unref(buf);
-                break;
-        }
-
-        /* Make sure we don't hog the CPU if the rx_queue never
-		 * gets empty.
-		 */
-        k_yield();
+    case BT_BUF_EVT:
+      hci_event(buf);
+      break;
+    default:
+      BT_ERR("Unknown buf type %u", bt_buf_get_type(buf));
+      net_buf_unref(buf);
+      break;
     }
+
+    /* Make sure we don't hog the CPU if the rx_queue never
+     * gets empty.
+     */
+    k_yield();
+  }
 }
 #endif /* !CONFIG_BT_RECV_IS_RX_THREAD */
 
-int bt_enable(bt_ready_cb_t cb)
-{
-    int err;
+int bt_enable(bt_ready_cb_t cb) {
+  int err;
 
-    if (!bt_dev.drv) {
-        BT_ERR("No HCI driver registered");
-        return -ENODEV;
-    }
+  if (!bt_dev.drv) {
+    BT_ERR("No HCI driver registered");
+    return -ENODEV;
+  }
 
-    if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_ENABLE)) {
-        return -EALREADY;
-    }
+  if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_ENABLE)) {
+    return -EALREADY;
+  }
 
 #if defined(BFLB_BLE)
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_init(&hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, CMD_BUF_SIZE, NULL);
-    net_buf_init(&hci_rx_pool, CONFIG_BT_RX_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
+#if (BFLB_STATIC_ALLOC_MEM)
+  net_buf_init(HCI_CMD, &hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, CMD_BUF_SIZE, NULL);
+  net_buf_init(HCI_RX, &hci_rx_pool, CONFIG_BT_RX_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
+#else
+  net_buf_init(&hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, CMD_BUF_SIZE, NULL);
+  net_buf_init(&hci_rx_pool, CONFIG_BT_RX_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
+#endif
 #if defined(CONFIG_BT_CONN)
-    net_buf_init(&num_complete_pool, 1, BT_BUF_RX_SIZE, NULL);
+#if (BFLB_STATIC_ALLOC_MEM)
+  net_buf_init(NUM_COMPLETE, &num_complete_pool, 1, BT_BUF_RX_SIZE, NULL);
+#else
+  net_buf_init(&num_complete_pool, 1, BT_BUF_RX_SIZE, NULL);
+#endif
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    net_buf_init(&acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE, report_completed_packet);
-#endif //CONFIG_BT_HCI_ACL_FLOW_CONTROL
-#endif //CONFIG_BT_CONN
+#if (BFLB_STATIC_ALLOC_MEM)
+  net_buf_init(ACL_IN, &acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE, report_completed_packet);
+#else
+  net_buf_init(&acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE, report_completed_packet);
+#endif
+#endif // CONFIG_BT_HCI_ACL_FLOW_CONTROL
+#endif // CONFIG_BT_CONN
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
-    net_buf_init(&discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
+#if (BFLB_STATIC_ALLOC_MEM)
+  net_buf_init(DISCARDABLE, &discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
+#else
+  net_buf_init(&discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT, BT_BUF_RX_SIZE, NULL);
+#endif
 #endif
 #endif
 
-    k_work_init(&bt_dev.init, init_work);
-    k_work_q_start();
+  k_work_init(&bt_dev.init, init_work);
+#if (BFLB_BT_CO_THREAD)
+  k_fifo_init(&g_work_queue_main.fifo, 20);
+#else
+  k_work_q_start();
+#endif
 #if !defined(CONFIG_BT_WAIT_NOP)
-    k_sem_init(&bt_dev.ncmd_sem, 1, 1);
+  k_sem_init(&bt_dev.ncmd_sem, 1, 1);
 #else
-    k_sem_init(&bt_dev.ncmd_sem, 0, 1);
+  k_sem_init(&bt_dev.ncmd_sem, 0, 1);
 #endif
-    k_fifo_init(&bt_dev.cmd_tx_queue, 20);
+  k_fifo_init(&bt_dev.cmd_tx_queue, 20);
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
-    k_fifo_init(&bt_dev.rx_queue, 20);
+  k_fifo_init(&bt_dev.rx_queue, 20);
 #endif
 
-    k_sem_init(&g_poll_sem, 0, 1);
+  k_sem_init(&g_poll_sem, 0, 1);
+#if (BFLB_BT_CO_THREAD)
+  // need to initialize recv_fifo before create bt_co_thread
+  k_fifo_init(&recv_fifo, 20);
+#endif
 #endif
 
 #if defined(BFLB_BLE_PATCH_SETTINGS_LOAD)
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
 #if defined(CFG_SLEEP)
-/* When using eflash_loader upprade firmware and softreset, 
-         * HBN_Get_Status_Flag() is 0x594c440b. so comment this line. */
-//if( HBN_Get_Status_Flag() == 0)
+/* When using eflash_loader upprade firmware and softreset,
+ * HBN_Get_Status_Flag() is 0x594c440b. so comment this line. */
+// if( HBN_Get_Status_Flag() == 0)
 #endif
-        bt_local_info_load();
-    }
+    bt_local_info_load();
+  }
 #else
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        err = bt_settings_init();
-        if (err) {
-            return err;
-        }
-    } else {
-        bt_set_name(CONFIG_BT_DEVICE_NAME);
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    err = bt_settings_init();
+    if (err) {
+      return err;
     }
+  } else {
+    bt_set_name(CONFIG_BT_DEVICE_NAME);
+  }
 #endif
 
-    ready_cb = cb;
+  ready_cb = cb;
 
-    /* TX thread */
+  /* TX thread */
 #if defined(BFLB_BLE)
-#if (!BFLB_BLE_CO_THREAD)
-    k_thread_create(&tx_thread_data, "hci_tx_thread",
-                    CONFIG_BT_HCI_TX_STACK_SIZE,
-                    hci_tx_thread,
-                    CONFIG_BT_HCI_TX_PRIO);
+#if (BFLB_BT_CO_THREAD)
+  k_thread_create(&co_thread_data, "bt_co_thread", CONFIG_BT_CO_STACK_SIZE, bt_co_thread, CONFIG_BT_CO_TASK_PRIO);
+#else
+  k_thread_create(&tx_thread_data, "hci_tx_thread", CONFIG_BT_HCI_TX_STACK_SIZE, hci_tx_thread, CONFIG_BT_HCI_TX_PRIO);
 #endif
 #else
-    k_thread_create(&tx_thread_data, tx_thread_stack,
-                    K_THREAD_STACK_SIZEOF(tx_thread_stack),
-                    hci_tx_thread, NULL, NULL, NULL,
-                    K_PRIO_COOP(CONFIG_BT_HCI_TX_PRIO),
-                    0, K_NO_WAIT);
-    k_thread_name_set(&tx_thread_data, "BT TX");
+  k_thread_create(&tx_thread_data, tx_thread_stack, K_THREAD_STACK_SIZEOF(tx_thread_stack), hci_tx_thread, NULL, NULL, NULL, K_PRIO_COOP(CONFIG_BT_HCI_TX_PRIO), 0, K_NO_WAIT);
+  k_thread_name_set(&tx_thread_data, "BT TX");
 #endif
 
 #if !defined(CONFIG_BT_RECV_IS_RX_THREAD)
-    /* RX thread */
+  /* RX thread */
 #if defined(BFLB_BLE)
-    k_thread_create(&rx_thread_data, "hci_rx_thread",
-                    CONFIG_BT_HCI_RX_STACK_SIZE /*K_THREAD_STACK_SIZEOF(rx_thread_stack)*/,
-                    (k_thread_entry_t)hci_rx_thread,
-                    CONFIG_BT_RX_PRIO);
+  k_thread_create(&rx_thread_data, "hci_rx_thread", CONFIG_BT_HCI_RX_STACK_SIZE /*K_THREAD_STACK_SIZEOF(rx_thread_stack)*/, (k_thread_entry_t)hci_rx_thread, CONFIG_BT_RX_PRIO);
 #else
-    k_thread_create(&rx_thread_data, rx_thread_stack,
-                    K_THREAD_STACK_SIZEOF(rx_thread_stack),
-                    (k_thread_entry_t)hci_rx_thread, NULL, NULL, NULL,
-                    K_PRIO_COOP(CONFIG_BT_RX_PRIO),
-                    0, K_NO_WAIT);
-    k_thread_name_set(&rx_thread_data, "BT RX");
-#endif //BFLB_BLE
+  k_thread_create(&rx_thread_data, rx_thread_stack, K_THREAD_STACK_SIZEOF(rx_thread_stack), (k_thread_entry_t)hci_rx_thread, NULL, NULL, NULL, K_PRIO_COOP(CONFIG_BT_RX_PRIO), 0, K_NO_WAIT);
+  k_thread_name_set(&rx_thread_data, "BT RX");
+#endif // BFLB_BLE
 #endif
 
-    if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
-        bt_hci_ecc_init();
-    }
+  if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) {
+    bt_hci_ecc_init();
+  }
 
-    err = bt_dev.drv->open();
-    if (err) {
-        BT_ERR("HCI driver open failed (%d)", err);
-        return err;
-    }
+  err = bt_dev.drv->open();
+  if (err) {
+    BT_ERR("HCI driver open failed (%d)", err);
+    return err;
+  }
 
 #if !defined(BFLB_BLE)
-    if (!cb) {
-        return bt_init();
-    }
+  if (!cb) {
+    return bt_init();
+  }
 #endif
 
 #if defined(CONFIG_BLE_MULTI_ADV)
-    bt_le_multi_adv_thread_init();
+  bt_le_multi_adv_thread_init();
 #endif
 
-    k_work_submit(&bt_dev.init);
-    return 0;
+  k_work_submit(&bt_dev.init);
+  return 0;
 }
 
 struct bt_ad {
-    const struct bt_data *data;
-    size_t len;
+  const struct bt_data *data;
+  size_t                len;
 };
 
 #if defined(BFLB_BLE)
-bool le_check_valid_scan(void)
-{
-    return atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
-}
+bool le_check_valid_scan(void) { return atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); }
 #endif
 
 #if defined(BFLB_DISABLE_BT)
 extern struct k_thread recv_thread_data;
 extern struct k_thread work_q_thread;
-extern struct k_fifo recv_fifo;
-extern struct k_fifo free_tx;
-extern struct k_work_q g_work_queue_main;
+extern struct k_fifo   free_tx;
 #if defined(CONFIG_BT_SMP)
 extern struct k_sem sc_local_pkey_ready;
 #endif
 
-void bt_delete_queue(struct k_fifo *queue_to_del)
-{
-    struct net_buf *buf = NULL;
+void bt_delete_queue(struct k_fifo *queue_to_del) {
+  struct net_buf *buf = NULL;
+  buf                 = net_buf_get(queue_to_del, K_NO_WAIT);
+  while (buf) {
+    net_buf_unref(buf);
     buf = net_buf_get(queue_to_del, K_NO_WAIT);
-    while (buf) {
-        net_buf_unref(buf);
-        buf = net_buf_get(queue_to_del, K_NO_WAIT);
-    }
+  }
 
-    k_queue_free(&(queue_to_del->_queue));
+  k_queue_free(&(queue_to_del->_queue));
 }
 
 #if defined(BFLB_DYNAMIC_ALLOC_MEM) && (CONFIG_BT_CONN)
@@ -5721,2042 +5622,1903 @@ extern struct net_buf_pool prep_pool;
 #if defined(CONFIG_BT_BREDR)
 extern struct net_buf_pool br_sig_pool;
 extern struct net_buf_pool sdp_pool;
+#if defined CONFIG_BT_HFP
 extern struct net_buf_pool hf_pool;
 extern struct net_buf_pool dummy_pool;
 #endif
 #endif
+#endif
 
-int bt_disable_action(void)
-{
+int bt_disable_action(void) {
 #if defined(CONFIG_BT_PRIVACY)
-    k_delayed_work_del_timer(&bt_dev.rpa_update);
+  k_delayed_work_del_timer(&bt_dev.rpa_update);
 #endif
-
-    bt_gatt_deinit();
-
-    //delete task
-    k_thread_delete(&tx_thread_data);
-    k_thread_delete(&recv_thread_data);
-    k_thread_delete(&work_q_thread);
-
-    //delete queue, not delete hci_cmd_pool.free/hci_rx_pool.free/acl_tx_pool.free which store released buffers.
-    bt_delete_queue(&recv_fifo);
-    bt_delete_queue(&g_work_queue_main.fifo);
-    bt_delete_queue(&bt_dev.cmd_tx_queue);
-
-    k_queue_free((struct k_queue *)&free_tx);
-
-    //delete sem
-    k_sem_delete(&bt_dev.ncmd_sem);
-    k_sem_delete(&g_poll_sem);
+#if defined(CONFIG_BT_CONN)
+  bt_gatt_deinit();
+#endif
+  // delete queue, not delete hci_cmd_pool.free/hci_rx_pool.free/acl_tx_pool.free which store released buffers.
+  bt_delete_queue(&recv_fifo);
+  bt_delete_queue(&g_work_queue_main.fifo);
+  bt_delete_queue(&bt_dev.cmd_tx_queue);
+#if defined(CONFIG_BT_CONN)
+  k_queue_free((struct k_queue *)&free_tx);
+#endif
+  // delete sem
+  k_sem_delete(&bt_dev.ncmd_sem);
+  k_sem_delete(&g_poll_sem);
 #if defined(CONFIG_BT_SMP)
-    k_sem_delete(&sc_local_pkey_ready);
+  k_sem_delete(&sc_local_pkey_ready);
+#endif
+#if defined(CONFIG_BT_CONN)
+  k_sem_delete(&bt_dev.le.pkts);
 #endif
-    k_sem_delete(&bt_dev.le.pkts);
 
-    atomic_clear_bit(bt_dev.flags, BT_DEV_ENABLE);
+  atomic_clear_bit(bt_dev.flags, BT_DEV_ENABLE);
 
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_deinit(&hci_cmd_pool);
-    net_buf_deinit(&hci_rx_pool);
+  net_buf_deinit(&hci_cmd_pool);
+  net_buf_deinit(&hci_rx_pool);
 #if defined(CONFIG_BT_CONN)
-    net_buf_deinit(&acl_tx_pool);
-    net_buf_deinit(&num_complete_pool);
+  net_buf_deinit(&acl_tx_pool);
+  net_buf_deinit(&num_complete_pool);
 #if CONFIG_BT_ATT_PREPARE_COUNT > 0
-    net_buf_deinit(&prep_pool);
+  net_buf_deinit(&prep_pool);
 #endif
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    net_buf_deinit(&acl_in_pool);
+  net_buf_deinit(&acl_in_pool);
 #endif
 #if (CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0)
-    net_buf_deinit(&frag_pool);
+  net_buf_deinit(&frag_pool);
 #endif
 #if defined(CONFIG_BT_BREDR)
-    net_buf_deinit(&br_sig_pool);
-    net_buf_deinit(&sdp_pool);
-    net_buf_deinit(&hf_pool);
-    net_buf_deinit(&dummy_pool);
+  net_buf_deinit(&br_sig_pool);
+  net_buf_deinit(&sdp_pool);
+#if defined CONFIG_BT_HFP
+  net_buf_deinit(&hf_pool);
+  net_buf_deinit(&dummy_pool);
+#endif
 #endif
-#endif //defined(CONFIG_BT_CONN)
+#endif // defined(CONFIG_BT_CONN)
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
-    net_buf_deinit(&discardable_pool);
+  net_buf_deinit(&discardable_pool);
 #endif
-#endif //defined(BFLB_DYNAMIC_ALLOC_MEM)
+#endif // defined(BFLB_DYNAMIC_ALLOC_MEM)
 
-    bl_onchiphci_interface_deinit();
+  bl_onchiphci_interface_deinit();
 
-    extern void ble_controller_deinit(void);
-    ble_controller_deinit();
+  // delete task
+  ble_controller_deinit();
+#if (BFLB_BT_CO_THREAD)
+  k_thread_delete(&co_thread_data);
+#else
+  k_thread_delete(&tx_thread_data);
+  k_thread_delete(&work_q_thread);
+  k_thread_delete(&recv_thread_data);
+#endif
 
-    return 0;
+  return 0;
 }
 
-int bt_disable(void)
-{
-    if (le_check_valid_conn() || atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN) || atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return -1;
-    } else
-        return bt_disable_action();
+int bt_disable(void) {
+  if (
+#if defined(CONFIG_BT_CONN)
+      le_check_valid_conn() ||
+#endif
+      atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN) || atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -1;
+  } else
+    return bt_disable_action();
 }
 #endif
 
-static int set_ad(u16_t hci_op, const struct bt_ad *ad, size_t ad_len)
-{
-    struct bt_hci_cp_le_set_adv_data *set_data;
-    struct net_buf *buf;
-    int c, i;
+static int set_ad(u16_t hci_op, const struct bt_ad *ad, size_t ad_len) {
+  struct bt_hci_cp_le_set_adv_data *set_data;
+  struct net_buf                   *buf;
+  int                               c, i;
 
-    buf = bt_hci_cmd_create(hci_op, sizeof(*set_data));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(hci_op, sizeof(*set_data));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    set_data = net_buf_add(buf, sizeof(*set_data));
+  set_data = net_buf_add(buf, sizeof(*set_data));
 
-    (void)memset(set_data, 0, sizeof(*set_data));
+  (void)memset(set_data, 0, sizeof(*set_data));
 
-    for (c = 0; c < ad_len; c++) {
-        const struct bt_data *data = ad[c].data;
+  for (c = 0; c < ad_len; c++) {
+    const struct bt_data *data = ad[c].data;
 
-        for (i = 0; i < ad[c].len; i++) {
-            int len = data[i].data_len;
-            u8_t type = data[i].type;
+    for (i = 0; i < ad[c].len; i++) {
+      int  len  = data[i].data_len;
+      u8_t type = data[i].type;
 
-            /* Check if ad fit in the remaining buffer */
-            if (set_data->len + len + 2 > 31) {
-                len = 31 - (set_data->len + 2);
-                if (type != BT_DATA_NAME_COMPLETE || !len) {
-                    net_buf_unref(buf);
-                    BT_ERR("Too big advertising data");
-                    return -EINVAL;
-                }
-                type = BT_DATA_NAME_SHORTENED;
-            }
+      /* Check if ad fit in the remaining buffer */
+      if (set_data->len + len + 2 > 31) {
+        len = 31 - (set_data->len + 2);
+        if (type != BT_DATA_NAME_COMPLETE || !len) {
+          net_buf_unref(buf);
+          BT_ERR("Too big advertising data");
+          return -EINVAL;
+        }
+        type = BT_DATA_NAME_SHORTENED;
+      }
 
-            set_data->data[set_data->len++] = len + 1;
-            set_data->data[set_data->len++] = type;
+      set_data->data[set_data->len++] = len + 1;
+      set_data->data[set_data->len++] = type;
 
-            memcpy(&set_data->data[set_data->len], data[i].data,
-                   len);
-            set_data->len += len;
-        }
+      memcpy(&set_data->data[set_data->len], data[i].data, len);
+      set_data->len += len;
     }
+  }
 
-    return bt_hci_cmd_send_sync(hci_op, buf, NULL);
+  return bt_hci_cmd_send_sync(hci_op, buf, NULL);
 }
 
-int bt_set_name(const char *name)
-{
+int bt_set_name(const char *name) {
 #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC)
-    size_t len = strlen(name);
+  size_t len = strlen(name);
 #if !defined(BFLB_BLE)
-    int err;
+  int err;
 #endif
-    if (len >= sizeof(bt_dev.name)) {
-        return -ENOMEM;
-    }
+  if (len >= sizeof(bt_dev.name)) {
+    return -ENOMEM;
+  }
 
-    if (!strcmp(bt_dev.name, name)) {
-        return 0;
-    }
+  if (!strcmp(bt_dev.name, name)) {
+    return 0;
+  }
 
-    strncpy(bt_dev.name, name, sizeof(bt_dev.name));
+  strncpy(bt_dev.name, name, sizeof(bt_dev.name));
 
-    /* Update advertising name if in use */
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME)) {
-        struct bt_data data[] = { BT_DATA(BT_DATA_NAME_COMPLETE, name,
-                                          strlen(name)) };
-        struct bt_ad sd = { data, ARRAY_SIZE(data) };
+  /* Update advertising name if in use */
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME)) {
+    struct bt_data data[] = {BT_DATA(BT_DATA_NAME_COMPLETE, name, strlen(name))};
+    struct bt_ad   sd     = {data, ARRAY_SIZE(data)};
 
-        set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, &sd, 1);
+    set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, &sd, 1);
 
-        /* Make sure the new name is set */
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-            set_advertise_enable(false);
-            set_advertise_enable(true);
-        }
+    /* Make sure the new name is set */
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+      set_advertise_enable(false);
+      set_advertise_enable(true);
     }
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
 #if defined(BFLB_BLE)
 #if defined(CFG_SLEEP)
-        if (HBN_Get_Status_Flag() == 0)
+    if (HBN_Get_Status_Flag() == 0)
 #endif
-            bt_settings_save_name();
+      bt_settings_save_name();
 #else
-        err = settings_save_one("bt/name", bt_dev.name, len);
-        if (err) {
-            BT_WARN("Unable to store name");
-        }
-#endif
+    err = settings_save_one("bt/name", bt_dev.name, len);
+    if (err) {
+      BT_WARN("Unable to store name");
     }
+#endif
+  }
 
-    return 0;
+  return 0;
 #else
-    return -ENOMEM;
+  return -ENOMEM;
 #endif
 }
 
-const char *bt_get_name(void)
-{
+const char *bt_get_name(void) {
 #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC)
-    return bt_dev.name;
+  return bt_dev.name;
 #else
-    return CONFIG_BT_DEVICE_NAME;
+  return CONFIG_BT_DEVICE_NAME;
 #endif
 }
 
-int bt_set_id_addr(const bt_addr_le_t *addr)
-{
-    bt_addr_le_t non_const_addr;
+int bt_set_id_addr(const bt_addr_le_t *addr) {
+  bt_addr_le_t non_const_addr;
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        BT_ERR("Setting identity not allowed after bt_enable()");
-        return -EBUSY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    BT_ERR("Setting identity not allowed after bt_enable()");
+    return -EBUSY;
+  }
 
-    bt_addr_le_copy(&non_const_addr, addr);
+  bt_addr_le_copy(&non_const_addr, addr);
 
-    return bt_id_create(&non_const_addr, NULL);
+  return bt_id_create(&non_const_addr, NULL);
 }
 
-void bt_id_get(bt_addr_le_t *addrs, size_t *count)
-{
-    size_t to_copy = MIN(*count, bt_dev.id_count);
+void bt_id_get(bt_addr_le_t *addrs, size_t *count) {
+  size_t to_copy = MIN(*count, bt_dev.id_count);
 
-    memcpy(addrs, bt_dev.id_addr, to_copy * sizeof(bt_addr_le_t));
-    *count = to_copy;
+  memcpy(addrs, bt_dev.id_addr, to_copy * sizeof(bt_addr_le_t));
+  *count = to_copy;
 }
 
-static int id_find(const bt_addr_le_t *addr)
-{
-    u8_t id;
+static int id_find(const bt_addr_le_t *addr) {
+  u8_t id;
 
-    for (id = 0U; id < bt_dev.id_count; id++) {
-        if (!bt_addr_le_cmp(addr, &bt_dev.id_addr[id])) {
-            return id;
-        }
+  for (id = 0U; id < bt_dev.id_count; id++) {
+    if (!bt_addr_le_cmp(addr, &bt_dev.id_addr[id])) {
+      return id;
     }
+  }
 
-    return -ENOENT;
+  return -ENOENT;
 }
 
-static void id_create(u8_t id, bt_addr_le_t *addr, u8_t *irk)
-{
-    if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
-        bt_addr_le_copy(&bt_dev.id_addr[id], addr);
-    } else {
-        bt_addr_le_t new_addr;
+static void id_create(u8_t id, bt_addr_le_t *addr, u8_t *irk) {
+  if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
+    bt_addr_le_copy(&bt_dev.id_addr[id], addr);
+  } else {
+    bt_addr_le_t new_addr;
 
-        do {
-            bt_addr_le_create_static(&new_addr);
-            /* Make sure we didn't generate a duplicate */
-        } while (id_find(&new_addr) >= 0);
+    do {
+      bt_addr_le_create_static(&new_addr);
+      /* Make sure we didn't generate a duplicate */
+    } while (id_find(&new_addr) >= 0);
 
-        bt_addr_le_copy(&bt_dev.id_addr[id], &new_addr);
+    bt_addr_le_copy(&bt_dev.id_addr[id], &new_addr);
 
-        if (addr) {
-            bt_addr_le_copy(addr, &bt_dev.id_addr[id]);
-        }
+    if (addr) {
+      bt_addr_le_copy(addr, &bt_dev.id_addr[id]);
     }
+  }
 
 #if defined(CONFIG_BT_PRIVACY)
-    {
-        u8_t zero_irk[16] = { 0 };
-
-        if (irk && memcmp(irk, zero_irk, 16)) {
-            memcpy(&bt_dev.irk[id], irk, 16);
-        } else {
-            bt_rand(&bt_dev.irk[id], 16);
-            if (irk) {
-                memcpy(irk, &bt_dev.irk[id], 16);
-            }
-        }
+  {
+    u8_t zero_irk[16] = {0};
+
+    if (irk && memcmp(irk, zero_irk, 16)) {
+      memcpy(&bt_dev.irk[id], irk, 16);
+    } else {
+      bt_rand(&bt_dev.irk[id], 16);
+      if (irk) {
+        memcpy(irk, &bt_dev.irk[id], 16);
+      }
     }
+  }
 #endif
-    /* Only store if stack was already initialized. Before initialization
-	 * we don't know the flash content, so it's potentially harmful to
-	 * try to write anything there.
-	 */
-    if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
-        atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        bt_settings_save_id();
-    }
+  /* Only store if stack was already initialized. Before initialization
+   * we don't know the flash content, so it's potentially harmful to
+   * try to write anything there.
+   */
+  if (IS_ENABLED(CONFIG_BT_SETTINGS) && atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    bt_settings_save_id();
+  }
 }
 
-int bt_id_create(bt_addr_le_t *addr, u8_t *irk)
-{
-    int new_id;
-
-    if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
-        if (addr->type != BT_ADDR_LE_RANDOM ||
-            !BT_ADDR_IS_STATIC(&addr->a)) {
-            BT_ERR("Only static random identity address supported");
-            return -EINVAL;
-        }
+int bt_id_create(bt_addr_le_t *addr, u8_t *irk) {
+  int new_id;
 
-        if (id_find(addr) >= 0) {
-            return -EALREADY;
-        }
+  if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
+    if (addr->type != BT_ADDR_LE_RANDOM || !BT_ADDR_IS_STATIC(&addr->a)) {
+      BT_ERR("Only static random identity address supported");
+      return -EINVAL;
     }
 
-    if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
-        return -EINVAL;
+    if (id_find(addr) >= 0) {
+      return -EALREADY;
     }
+  }
 
-    if (bt_dev.id_count == ARRAY_SIZE(bt_dev.id_addr)) {
-        return -ENOMEM;
-    }
+  if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
+    return -EINVAL;
+  }
 
-    new_id = bt_dev.id_count++;
-    if (new_id == BT_ID_DEFAULT &&
-        !atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR);
-    }
+  if (bt_dev.id_count == ARRAY_SIZE(bt_dev.id_addr)) {
+    return -ENOMEM;
+  }
 
-    id_create(new_id, addr, irk);
+  new_id = bt_dev.id_count++;
+  if (new_id == BT_ID_DEFAULT && !atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR);
+  }
 
-    return new_id;
-}
+  id_create(new_id, addr, irk);
 
-int bt_id_reset(u8_t id, bt_addr_le_t *addr, u8_t *irk)
-{
-    if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
-        if (addr->type != BT_ADDR_LE_RANDOM ||
-            !BT_ADDR_IS_STATIC(&addr->a)) {
-            BT_ERR("Only static random identity address supported");
-            return -EINVAL;
-        }
+  return new_id;
+}
 
-        if (id_find(addr) >= 0) {
-            return -EALREADY;
-        }
+int bt_id_reset(u8_t id, bt_addr_le_t *addr, u8_t *irk) {
+  if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) {
+    if (addr->type != BT_ADDR_LE_RANDOM || !BT_ADDR_IS_STATIC(&addr->a)) {
+      BT_ERR("Only static random identity address supported");
+      return -EINVAL;
     }
 
-    if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
-        return -EINVAL;
+    if (id_find(addr) >= 0) {
+      return -EALREADY;
     }
+  }
 
-    if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
-        return -EINVAL;
-    }
+  if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
+    return -EINVAL;
+  }
 
-    if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags,
-                                               BT_DEV_ADVERTISING)) {
-        return -EBUSY;
-    }
+  if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
+    return -EINVAL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CONN) &&
-        bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
-        int err;
+  if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EBUSY;
+  }
 
-        err = bt_unpair(id, NULL);
-        if (err) {
-            return err;
-        }
+  if (IS_ENABLED(CONFIG_BT_CONN) && bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
+    int err;
+
+    err = bt_unpair(id, NULL);
+    if (err) {
+      return err;
     }
+  }
 
-    id_create(id, addr, irk);
+  id_create(id, addr, irk);
 
-    return id;
+  return id;
 }
 
-int bt_id_delete(u8_t id)
-{
-    if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
-        return -EINVAL;
-    }
+int bt_id_delete(u8_t id) {
+  if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
+    return -EINVAL;
+  }
 
-    if (!bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
-        return -EALREADY;
-    }
+  if (!bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
+    return -EALREADY;
+  }
 
-    if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags,
-                                               BT_DEV_ADVERTISING)) {
-        return -EBUSY;
-    }
+  if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EBUSY;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_CONN)) {
-        int err;
+  if (IS_ENABLED(CONFIG_BT_CONN)) {
+    int err;
 
-        err = bt_unpair(id, NULL);
-        if (err) {
-            return err;
-        }
+    err = bt_unpair(id, NULL);
+    if (err) {
+      return err;
     }
+  }
 
 #if defined(CONFIG_BT_PRIVACY)
-    (void)memset(bt_dev.irk[id], 0, 16);
+  (void)memset(bt_dev.irk[id], 0, 16);
 #endif
-    bt_addr_le_copy(&bt_dev.id_addr[id], BT_ADDR_LE_ANY);
+  bt_addr_le_copy(&bt_dev.id_addr[id], BT_ADDR_LE_ANY);
 
-    if (id == bt_dev.id_count - 1) {
-        bt_dev.id_count--;
-    }
+  if (id == bt_dev.id_count - 1) {
+    bt_dev.id_count--;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
-        atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        bt_settings_save_id();
-    }
+  if (IS_ENABLED(CONFIG_BT_SETTINGS) && atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    bt_settings_save_id();
+  }
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_HCI_VS_EXT)
-static uint8_t bt_read_static_addr(bt_addr_le_t *addr)
-{
-    struct bt_hci_rp_vs_read_static_addrs *rp;
-    struct net_buf *rsp;
-    int err, i;
-    u8_t cnt;
-    if (!(bt_dev.vs_commands[1] & BIT(0))) {
-        BT_WARN("Read Static Addresses command not available");
-        return 0;
-    }
-
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_STATIC_ADDRS, NULL, &rsp);
-    if (err) {
-        BT_WARN("Failed to read static addresses");
-        return 0;
-    }
-    rp = (void *)rsp->data;
-    cnt = MIN(rp->num_addrs, CONFIG_BT_ID_MAX);
+static uint8_t bt_read_static_addr(bt_addr_le_t *addr) {
+  struct bt_hci_rp_vs_read_static_addrs *rp;
+  struct net_buf                        *rsp;
+  int                                    err, i;
+  u8_t                                   cnt;
+  if (!(bt_dev.vs_commands[1] & BIT(0))) {
+    BT_WARN("Read Static Addresses command not available");
+    return 0;
+  }
 
-    for (i = 0; i < cnt; i++) {
-        addr[i].type = BT_ADDR_LE_RANDOM;
-        bt_addr_copy(&addr[i].a, &rp->a[i].bdaddr);
-    }
-    net_buf_unref(rsp);
-    if (!cnt) {
-        BT_WARN("No static addresses stored in controller");
-    }
-    return cnt;
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_STATIC_ADDRS, NULL, &rsp);
+  if (err) {
+    BT_WARN("Failed to read static addresses");
+    return 0;
+  }
+  rp  = (void *)rsp->data;
+  cnt = MIN(rp->num_addrs, CONFIG_BT_ID_MAX);
+
+  for (i = 0; i < cnt; i++) {
+    addr[i].type = BT_ADDR_LE_RANDOM;
+    bt_addr_copy(&addr[i].a, &rp->a[i].bdaddr);
+  }
+  net_buf_unref(rsp);
+  if (!cnt) {
+    BT_WARN("No static addresses stored in controller");
+  }
+  return cnt;
 }
 #elif defined(CONFIG_BT_CTLR)
 uint8_t bt_read_static_addr(bt_addr_le_t *addr);
 #endif /* CONFIG_BT_HCI_VS_EXT */
 
-int bt_setup_id_addr(void)
-{
+int bt_setup_id_addr(void) {
 #if defined(CONFIG_BT_HCI_VS_EXT) || defined(CONFIG_BT_CTLR)
-    /* Only read the addresses if the user has not already configured one or
-	 * more identities (!bt_dev.id_count).
-	 */
-    if (!bt_dev.id_count) {
-        bt_addr_le_t addrs[CONFIG_BT_ID_MAX];
+  /* Only read the addresses if the user has not already configured one or
+   * more identities (!bt_dev.id_count).
+   */
+  if (!bt_dev.id_count) {
+    bt_addr_le_t addrs[CONFIG_BT_ID_MAX];
 
-        bt_dev.id_count = bt_read_static_addr(addrs);
-        if (bt_dev.id_count) {
-            int i;
+    bt_dev.id_count = bt_read_static_addr(addrs);
+    if (bt_dev.id_count) {
+      int i;
 
-            for (i = 0; i < bt_dev.id_count; i++) {
-                id_create(i, &addrs[i], NULL);
-            }
+      for (i = 0; i < bt_dev.id_count; i++) {
+        id_create(i, &addrs[i], NULL);
+      }
 
-            return set_random_address(&bt_dev.id_addr[0].a);
-        }
+      return set_random_address(&bt_dev.id_addr[0].a);
     }
+  }
 #endif
-    return bt_id_create(NULL, NULL);
+  return bt_id_create(NULL, NULL);
 }
 
-bool bt_addr_le_is_bonded(u8_t id, const bt_addr_le_t *addr)
-{
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        struct bt_keys *keys = bt_keys_find_addr(id, addr);
+bool bt_addr_le_is_bonded(u8_t id, const bt_addr_le_t *addr) {
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    struct bt_keys *keys = bt_keys_find_addr(id, addr);
 
-        /* if there are any keys stored then device is bonded */
-        return keys && keys->keys;
-    } else {
-        return false;
-    }
+    /* if there are any keys stored then device is bonded */
+    return keys && keys->keys;
+  } else {
+    return false;
+  }
 }
 
-static bool valid_adv_param(const struct bt_le_adv_param *param, bool dir_adv)
-{
-    if (param->id >= bt_dev.id_count ||
-        !bt_addr_le_cmp(&bt_dev.id_addr[param->id], BT_ADDR_LE_ANY)) {
-        return false;
-    }
+static bool valid_adv_param(const struct bt_le_adv_param *param, bool dir_adv) {
+  if (param->id >= bt_dev.id_count || !bt_addr_le_cmp(&bt_dev.id_addr[param->id], BT_ADDR_LE_ANY)) {
+    return false;
+  }
 
 #if !defined(BFLB_BLE)
-    if (!(param->options & BT_LE_ADV_OPT_CONNECTABLE)) {
-        /*
-		 * BT Core 4.2 [Vol 2, Part E, 7.8.5]
-		 * The Advertising_Interval_Min and Advertising_Interval_Max
-		 * shall not be set to less than 0x00A0 (100 ms) if the
-		 * Advertising_Type is set to ADV_SCAN_IND or ADV_NONCONN_IND.
-		 */
-        if (bt_dev.hci_version < BT_HCI_VERSION_5_0 &&
-            param->interval_min < 0x00a0) {
-            return false;
-        }
+  if (!(param->options & BT_LE_ADV_OPT_CONNECTABLE)) {
+    /*
+     * BT Core 4.2 [Vol 2, Part E, 7.8.5]
+     * The Advertising_Interval_Min and Advertising_Interval_Max
+     * shall not be set to less than 0x00A0 (100 ms) if the
+     * Advertising_Type is set to ADV_SCAN_IND or ADV_NONCONN_IND.
+     */
+    if (bt_dev.hci_version < BT_HCI_VERSION_5_0 && param->interval_min < 0x00a0) {
+      return false;
     }
+  }
 #endif
 
-    if (is_wl_empty() &&
-        ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) ||
-         (param->options & BT_LE_ADV_OPT_FILTER_CONN))) {
-        return false;
-    }
+  if (is_wl_empty() && ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) || (param->options & BT_LE_ADV_OPT_FILTER_CONN))) {
+    return false;
+  }
 
-    if ((param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) || !dir_adv) {
-        if (param->interval_min > param->interval_max ||
+  if ((param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) || !dir_adv) {
+    if (param->interval_min > param->interval_max ||
 #if !defined(BFLB_BLE)
-            param->interval_min < 0x0020 ||
+        param->interval_min < 0x0020 ||
 #endif
-            param->interval_max > 0x4000) {
-            return false;
-        }
+        param->interval_max > 0x4000) {
+      return false;
     }
+  }
 
-    return true;
+  return true;
 }
 
-static inline bool ad_has_name(const struct bt_data *ad, size_t ad_len)
-{
-    int i;
+static inline bool ad_has_name(const struct bt_data *ad, size_t ad_len) {
+  int i;
 
-    for (i = 0; i < ad_len; i++) {
-        if (ad[i].type == BT_DATA_NAME_COMPLETE ||
-            ad[i].type == BT_DATA_NAME_SHORTENED) {
-            return true;
-        }
+  for (i = 0; i < ad_len; i++) {
+    if (ad[i].type == BT_DATA_NAME_COMPLETE || ad[i].type == BT_DATA_NAME_SHORTENED) {
+      return true;
     }
+  }
 
-    return false;
+  return false;
 }
 
-static int le_adv_update(const struct bt_data *ad, size_t ad_len,
-                         const struct bt_data *sd, size_t sd_len,
-                         bool connectable, bool use_name)
-{
-    struct bt_ad d[2] = {};
-    struct bt_data data;
-    int err;
-
-    d[0].data = ad;
-    d[0].len = ad_len;
+static int le_adv_update(const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len, bool connectable, bool use_name) {
+  struct bt_ad   d[2] = {};
+  struct bt_data data;
+  int            err;
 
-    err = set_ad(BT_HCI_OP_LE_SET_ADV_DATA, d, 1);
-    if (err) {
-        return err;
-    }
-
-    d[0].data = sd;
-    d[0].len = sd_len;
+  d[0].data = ad;
+  d[0].len  = ad_len;
 
-    if (use_name) {
-        const char *name;
-
-        if (sd) {
-            /* Cannot use name if name is already set */
-            if (ad_has_name(sd, sd_len)) {
-                return -EINVAL;
-            }
-        }
+  err = set_ad(BT_HCI_OP_LE_SET_ADV_DATA, d, 1);
+  if (err) {
+    return err;
+  }
 
-        name = bt_get_name();
-        data = (struct bt_data)BT_DATA(
-            BT_DATA_NAME_COMPLETE,
-            name, strlen(name));
+  d[0].data = sd;
+  d[0].len  = sd_len;
 
-        d[1].data = &data;
-        d[1].len = 1;
-    }
+  if (use_name) {
+    const char *name;
 
-    /*
-	 * We need to set SCAN_RSP when enabling advertising type that
-	 * allows for Scan Requests.
-	 *
-	 * If any data was not provided but we enable connectable
-	 * undirected advertising sd needs to be cleared from values set
-	 * by previous calls.
-	 * Clearing sd is done by calling set_ad() with NULL data and
-	 * zero len.
-	 * So following condition check is unusual but correct.
-	 */
-    if (d[0].data || d[1].data || connectable) {
-        err = set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, d, 2);
-        if (err) {
-            return err;
-        }
+    if (sd) {
+      /* Cannot use name if name is already set */
+      if (ad_has_name(sd, sd_len)) {
+        return -EINVAL;
+      }
+    }
+
+    name = bt_get_name();
+    data = (struct bt_data)BT_DATA(BT_DATA_NAME_COMPLETE, name, strlen(name));
+
+    d[1].data = &data;
+    d[1].len  = 1;
+  }
+
+  /*
+   * We need to set SCAN_RSP when enabling advertising type that
+   * allows for Scan Requests.
+   *
+   * If any data was not provided but we enable connectable
+   * undirected advertising sd needs to be cleared from values set
+   * by previous calls.
+   * Clearing sd is done by calling set_ad() with NULL data and
+   * zero len.
+   * So following condition check is unusual but correct.
+   */
+  if (d[0].data || d[1].data || connectable) {
+    err = set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, d, 2);
+    if (err) {
+      return err;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
-int bt_le_adv_update_data(const struct bt_data *ad, size_t ad_len,
-                          const struct bt_data *sd, size_t sd_len)
-{
-    bool connectable, use_name;
+int bt_le_adv_update_data(const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len) {
+  bool connectable, use_name;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return -EAGAIN;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EAGAIN;
+  }
 
-    connectable = atomic_test_bit(bt_dev.flags,
-                                  BT_DEV_ADVERTISING_CONNECTABLE);
-    use_name = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME);
+  connectable = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE);
+  use_name    = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME);
 
-    return le_adv_update(ad, ad_len, sd, sd_len, connectable, use_name);
+  return le_adv_update(ad, ad_len, sd, sd_len, connectable, use_name);
 }
 
-int bt_le_adv_start_internal(const struct bt_le_adv_param *param,
-                             const struct bt_data *ad, size_t ad_len,
-                             const struct bt_data *sd, size_t sd_len,
-                             const bt_addr_le_t *peer)
-{
-    struct bt_hci_cp_le_set_adv_param set_param;
-    const bt_addr_le_t *id_addr;
-    struct net_buf *buf;
-    bool dir_adv = (peer != NULL);
-    int err = 0;
+int bt_le_adv_start_internal(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len, const bt_addr_le_t *peer) {
+  struct bt_hci_cp_le_set_adv_param set_param;
+  const bt_addr_le_t               *id_addr;
+  struct net_buf                   *buf;
+  bool                              dir_adv = (peer != NULL);
+  int                               err     = 0;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EAGAIN;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EAGAIN;
+  }
 
-    if (!valid_adv_param(param, dir_adv)) {
-        return -EINVAL;
-    }
+  if (!valid_adv_param(param, dir_adv)) {
+    return -EINVAL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return -EALREADY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EALREADY;
+  }
 
-    (void)memset(&set_param, 0, sizeof(set_param));
+  (void)memset(&set_param, 0, sizeof(set_param));
 
-    set_param.min_interval = sys_cpu_to_le16(param->interval_min);
-    set_param.max_interval = sys_cpu_to_le16(param->interval_max);
-    set_param.channel_map = adv_ch_map;
+  set_param.min_interval = sys_cpu_to_le16(param->interval_min);
+  set_param.max_interval = sys_cpu_to_le16(param->interval_max);
+  set_param.channel_map  = adv_ch_map;
 
-    if (bt_dev.adv_id != param->id) {
-        atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
-    }
+  if (bt_dev.adv_id != param->id) {
+    atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  }
 
 #if defined(CONFIG_BT_WHITELIST)
-    if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) &&
-        (param->options & BT_LE_ADV_OPT_FILTER_CONN)) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH;
-    } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ;
-    } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND;
-    } else {
+  if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) && (param->options & BT_LE_ADV_OPT_FILTER_CONN)) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH;
+  } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ;
+  } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND;
+  } else {
 #else
-    {
+  {
 #endif /* defined(CONFIG_BT_WHITELIST) */
-        set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST;
-    }
+    set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST;
+  }
 
-    /* Set which local identity address we're advertising with */
-    bt_dev.adv_id = param->id;
-    id_addr = &bt_dev.id_addr[param->id];
+  /* Set which local identity address we're advertising with */
+  bt_dev.adv_id = param->id;
+  id_addr       = &bt_dev.id_addr[param->id];
 
-    if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
-        if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
-            !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) {
-#if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_TYPE_RPA)
-                err = le_set_private_addr(param->id);
-            else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                err = le_set_non_resolv_private_addr(param->id);
+  if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY) && !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) {
+#if defined(CONFIG_BT_STACK_PTS) || defined(CONFIG_AUTO_PTS)
+      if (param->addr_type == BT_ADDR_LE_RANDOM_ID)
+        err = le_set_private_addr(param->id);
+      else if (param->addr_type == BT_ADDR_LE_RANDOM)
+        err = le_set_non_resolv_private_addr(param->id);
 #else
-            err = le_set_private_addr(param->id);
+      err = le_set_private_addr(param->id);
 #endif
-            if (err) {
-                return err;
-            }
+      if (err) {
+        return err;
+      }
 
-            if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-#if defined(CONFIG_BT_STACK_PTS)
-                if (param->addr_type == BT_ADDR_LE_PUBLIC)
-                    set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
-                if (param->addr_type == BT_ADDR_TYPE_RPA)
-                    set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-                else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                    set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+      if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+#if defined(CONFIG_BT_STACK_PTS) || defined(CONFIG_AUTO_PTS)
+        set_param.own_addr_type = param->addr_type;
 #else
-                set_param.own_addr_type =
-                    BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-#endif
-            } else {
-                set_param.own_addr_type = BT_ADDR_LE_RANDOM;
-            }
-        } else {
-            /*
-			 * If Static Random address is used as Identity
-			 * address we need to restore it before advertising
-			 * is enabled. Otherwise NRPA used for active scan
-			 * could be used for advertising.
-			 */
-            if (id_addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&id_addr->a);
-                if (err) {
-                    return err;
-                }
-            }
-
-            set_param.own_addr_type = id_addr->type;
+        set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+#endif
+      } else {
+        set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+      }
+    } else {
+      /*
+       * If Static Random address is used as Identity
+       * address we need to restore it before advertising
+       * is enabled. Otherwise NRPA used for active scan
+       * could be used for advertising.
+       */
+      if (id_addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&id_addr->a);
+        if (err) {
+          return err;
         }
+      }
 
-        if (dir_adv) {
-            if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) {
-                set_param.type = BT_LE_ADV_DIRECT_IND_LOW_DUTY;
-            } else {
-                set_param.type = BT_LE_ADV_DIRECT_IND;
-            }
-
-            bt_addr_le_copy(&set_param.direct_addr, peer);
-
-            if (IS_ENABLED(CONFIG_BT_SMP) &&
-                !IS_ENABLED(CONFIG_BT_PRIVACY) &&
-                BT_FEAT_LE_PRIVACY(bt_dev.le.features) &&
-                (param->options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) {
-                /* This will not use RPA for our own address
-				 * since we have set zeroed out the local IRK.
-				 */
-                set_param.own_addr_type |=
-                    BT_HCI_OWN_ADDR_RPA_MASK;
-            }
-        } else {
-            set_param.type = BT_LE_ADV_IND;
-        }
+      set_param.own_addr_type = id_addr->type;
+    }
+
+    if (dir_adv) {
+      if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) {
+        set_param.type = BT_LE_ADV_DIRECT_IND_LOW_DUTY;
+      } else {
+        set_param.type = BT_LE_ADV_DIRECT_IND;
+      }
+
+      bt_addr_le_copy(&set_param.direct_addr, peer);
+
+      if (IS_ENABLED(CONFIG_BT_SMP) && !IS_ENABLED(CONFIG_BT_PRIVACY) && BT_FEAT_LE_PRIVACY(bt_dev.le.features) && (param->options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) {
+        /* This will not use RPA for our own address
+         * since we have set zeroed out the local IRK.
+         */
+        set_param.own_addr_type |= BT_HCI_OWN_ADDR_RPA_MASK;
+      }
     } else {
-        if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) {
-            if (id_addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&id_addr->a);
-            }
+      set_param.type = BT_LE_ADV_IND;
+    }
+  } else {
+    if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) {
+      if (id_addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&id_addr->a);
+      }
 
-            set_param.own_addr_type = id_addr->type;
-        } else {
+      set_param.own_addr_type = id_addr->type;
+    } else {
 #if defined(BFLB_BLE) && !defined(CONFIG_BT_MESH)
-#if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_TYPE_RPA)
-                err = le_set_private_addr(param->id);
-            else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                err = le_set_non_resolv_private_addr(param->id);
+#if defined(CONFIG_BT_STACK_PTS) || defined(CONFIG_AUTO_PTS)
+      if (param->addr_type == BT_ADDR_LE_RANDOM_ID)
+        err = le_set_private_addr(param->id);
+      else if (param->addr_type == BT_ADDR_LE_RANDOM)
+        err = le_set_non_resolv_private_addr(param->id);
 #else
-//#if !defined(CONFIG_BT_ADV_WITH_PUBLIC_ADDR)
-//err = le_set_private_addr(param->id);
-//#endif
-#endif //CONFIG_BT_STACK_PTS
-#if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_LE_PUBLIC)
-                set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
-            else
+// #if !defined(CONFIG_BT_ADV_WITH_PUBLIC_ADDR)
+// err = le_set_private_addr(param->id);
+// #endif
+#endif // CONFIG_BT_STACK_PTS
+#if defined(CONFIG_BT_STACK_PTS) || defined(CONFIG_AUTO_PTS)
+      set_param.own_addr_type = param->addr_type;
+#else
+      // set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+      // #if defined(CONFIG_BT_ADV_WITH_PUBLIC_ADDR)
+      set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
+// #endif
 #endif
-                //set_param.own_addr_type = BT_ADDR_LE_RANDOM;
-                //#if defined(CONFIG_BT_ADV_WITH_PUBLIC_ADDR)
-                set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
-                //#endif
 #endif
-        }
+    }
 
-        if (err) {
-            return err;
-        }
+    if (err) {
+      return err;
+    }
 
-        if (sd) {
-            set_param.type = BT_LE_ADV_SCAN_IND;
-        } else {
-            set_param.type = BT_LE_ADV_NONCONN_IND;
-        }
+    if (sd) {
+      set_param.type = BT_LE_ADV_SCAN_IND;
+    } else {
+      set_param.type = BT_LE_ADV_NONCONN_IND;
     }
+  }
 
 #if defined(CONFIG_BT_STACK_PTS)
-    if (set_param.own_addr_type == BT_ADDR_LE_PUBLIC) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_ADV_ADDRESS_IS_PUBLIC);
-    }
+  if (set_param.own_addr_type == BT_ADDR_LE_PUBLIC) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_ADV_ADDRESS_IS_PUBLIC);
+  }
 #endif
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
-    }
-
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
-    if (err) {
-        return err;
-    }
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-    if (!dir_adv) {
-        err = le_adv_update(ad, ad_len, sd, sd_len,
-                            param->options & BT_LE_ADV_OPT_CONNECTABLE,
-                            param->options & BT_LE_ADV_OPT_USE_NAME);
-        if (err) {
-            return err;
-        }
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    err = set_advertise_enable(true);
+  if (!dir_adv) {
+    err = le_adv_update(ad, ad_len, sd, sd_len, param->options & BT_LE_ADV_OPT_CONNECTABLE, param->options & BT_LE_ADV_OPT_USE_NAME);
     if (err) {
-        return err;
+      return err;
     }
+  }
+
+  err = set_advertise_enable(true);
+  if (err) {
+    return err;
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING,
-                      !(param->options & BT_LE_ADV_OPT_ONE_TIME));
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING, !(param->options & BT_LE_ADV_OPT_ONE_TIME));
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME,
-                      param->options & BT_LE_ADV_OPT_USE_NAME);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME, param->options & BT_LE_ADV_OPT_USE_NAME);
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE,
-                      param->options & BT_LE_ADV_OPT_CONNECTABLE);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE, param->options & BT_LE_ADV_OPT_CONNECTABLE);
 
 #if defined(BFLB_HOST_ASSISTANT)
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_adv_cb)
-        host_assist_cb->le_adv_cb(param, ad, ad_len, sd, sd_len);
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_adv_cb)
+    host_assist_cb->le_adv_cb(param, ad, ad_len, sd, sd_len);
 #endif
 
-    return 0;
+  return 0;
 }
 #if defined(BFLB_BLE)
-int bt_le_read_rssi(u16_t handle, int8_t *rssi)
-{
-    struct bt_hci_cp_read_rssi *le_rssi;
-    struct bt_hci_rp_read_rssi *rsp_rssi;
-    struct net_buf *buf;
-    struct net_buf *rsp;
-    int ret;
+int bt_le_read_rssi(u16_t handle, int8_t *rssi) {
+  struct bt_hci_cp_read_rssi *le_rssi;
+  struct bt_hci_rp_read_rssi *rsp_rssi;
+  struct net_buf             *buf;
+  struct net_buf             *rsp;
+  int                         ret;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_READ_RSSI, sizeof(*le_rssi));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_READ_RSSI, sizeof(*le_rssi));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    le_rssi = net_buf_add(buf, sizeof(*le_rssi));
-    memset(le_rssi, 0, sizeof(*le_rssi));
+  le_rssi = net_buf_add(buf, sizeof(*le_rssi));
+  memset(le_rssi, 0, sizeof(*le_rssi));
 
-    le_rssi->handle = handle;
+  le_rssi->handle = handle;
 
-    ret = bt_hci_cmd_send_sync(BT_HCI_OP_READ_RSSI, buf, &rsp);
+  ret = bt_hci_cmd_send_sync(BT_HCI_OP_READ_RSSI, buf, &rsp);
 
-    if (ret) {
-        return ret;
-    }
+  if (ret) {
+    return ret;
+  }
 
-    rsp_rssi = (struct bt_hci_rp_read_rssi *)rsp->data;
-    *rssi = rsp_rssi->rssi;
+  rsp_rssi = (struct bt_hci_rp_read_rssi *)rsp->data;
+  *rssi    = rsp_rssi->rssi;
 
-    net_buf_unref(rsp);
+  net_buf_unref(rsp);
 
-    return ret;
+  return ret;
 }
 
-int set_adv_enable(bool enable)
-{
-    int err;
-    err = set_advertise_enable(enable);
-    if (err) {
-        return err;
-    }
+int set_adv_enable(bool enable) {
+  int err;
+  err = set_advertise_enable(enable);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int set_adv_param(const struct bt_le_adv_param *param)
-{
-    struct bt_hci_cp_le_set_adv_param set_param;
-    const bt_addr_le_t *id_addr;
-    struct net_buf *buf;
-    int err = 0;
+int set_adv_param(const struct bt_le_adv_param *param) {
+  struct bt_hci_cp_le_set_adv_param set_param;
+  const bt_addr_le_t               *id_addr;
+  struct net_buf                   *buf;
+  int                               err = 0;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EAGAIN;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EAGAIN;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return -EALREADY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EALREADY;
+  }
 
-    (void)memset(&set_param, 0, sizeof(set_param));
+  (void)memset(&set_param, 0, sizeof(set_param));
 
-    set_param.min_interval = sys_cpu_to_le16(param->interval_min);
-    set_param.max_interval = sys_cpu_to_le16(param->interval_max);
-    set_param.channel_map = 0x07;
+  set_param.min_interval = sys_cpu_to_le16(param->interval_min);
+  set_param.max_interval = sys_cpu_to_le16(param->interval_max);
+  set_param.channel_map  = 0x07;
 
-    if (bt_dev.adv_id != param->id) {
-        atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
-    }
+  if (bt_dev.adv_id != param->id) {
+    atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  }
 
 #if defined(CONFIG_BT_WHITELIST)
-    if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) &&
-        (param->options & BT_LE_ADV_OPT_FILTER_CONN)) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH;
-    } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ;
-    } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) {
-        set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND;
-    } else {
+  if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) && (param->options & BT_LE_ADV_OPT_FILTER_CONN)) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH;
+  } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ;
+  } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) {
+    set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND;
+  } else {
 #else
-    {
+  {
 #endif /* defined(CONFIG_BT_WHITELIST) */
-        set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST;
-    }
+    set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST;
+  }
 
-    /* Set which local identity address we're advertising with */
-    bt_dev.adv_id = param->id;
-    id_addr = &bt_dev.id_addr[param->id];
+  /* Set which local identity address we're advertising with */
+  bt_dev.adv_id = param->id;
+  id_addr       = &bt_dev.id_addr[param->id];
 
-    if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
-        if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
-            !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) {
+  if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY) && !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) {
 #if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_TYPE_RPA)
-                err = le_set_private_addr(param->id);
-            else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                err = le_set_non_resolv_private_addr(param->id);
+      if (param->addr_type == BT_ADDR_TYPE_RPA)
+        err = le_set_private_addr(param->id);
+      else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
+        err = le_set_non_resolv_private_addr(param->id);
 #else
-            err = le_set_private_addr(param->id);
+      err = le_set_private_addr(param->id);
 #endif
-            if (err) {
-                return err;
-            }
+      if (err) {
+        return err;
+      }
 
-            if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+      if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
 #if defined(CONFIG_BT_STACK_PTS)
-                if (param->addr_type == BT_ADDR_LE_PUBLIC)
-                    set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
-                if (param->addr_type == BT_ADDR_TYPE_RPA)
-                    set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-                else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                    set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+        if (param->addr_type == BT_ADDR_LE_PUBLIC)
+          set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
+        if (param->addr_type == BT_ADDR_TYPE_RPA)
+          set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+        else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
+          set_param.own_addr_type = BT_ADDR_LE_RANDOM;
 #else
-                set_param.own_addr_type =
-                    BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-#endif
-            } else {
-                set_param.own_addr_type = BT_ADDR_LE_RANDOM;
-            }
-        } else {
-            /*
-			 * If Static Random address is used as Identity
-			 * address we need to restore it before advertising
-			 * is enabled. Otherwise NRPA used for active scan
-			 * could be used for advertising.
-			 */
-            if (id_addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&id_addr->a);
-                if (err) {
-                    return err;
-                }
-            }
-
-            set_param.own_addr_type = id_addr->type;
+        set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+#endif
+      } else {
+        set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+      }
+    } else {
+      /*
+       * If Static Random address is used as Identity
+       * address we need to restore it before advertising
+       * is enabled. Otherwise NRPA used for active scan
+       * could be used for advertising.
+       */
+      if (id_addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&id_addr->a);
+        if (err) {
+          return err;
         }
+      }
+
+      set_param.own_addr_type = id_addr->type;
+    }
 
-        set_param.type = BT_LE_ADV_IND;
+    set_param.type = BT_LE_ADV_IND;
 
-    } else {
-        if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) {
-            if (id_addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&id_addr->a);
-            }
+  } else {
+    if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) {
+      if (id_addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&id_addr->a);
+      }
 
-            set_param.own_addr_type = id_addr->type;
-        } else {
+      set_param.own_addr_type = id_addr->type;
+    } else {
 #if defined(BFLB_BLE) && !defined(CONFIG_BT_MESH)
 #if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_TYPE_RPA)
-                err = le_set_private_addr(param->id);
-            else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
-                err = le_set_non_resolv_private_addr(param->id);
+      if (param->addr_type == BT_ADDR_TYPE_RPA)
+        err = le_set_private_addr(param->id);
+      else if (param->addr_type == BT_ADDR_TYPE_NON_RPA)
+        err = le_set_non_resolv_private_addr(param->id);
 #else
-            err = le_set_private_addr(param->id);
-#endif //CONFIG_BT_STACK_PTS
+      err = le_set_private_addr(param->id);
+#endif // CONFIG_BT_STACK_PTS
 #if defined(CONFIG_BT_STACK_PTS)
-            if (param->addr_type == BT_ADDR_LE_PUBLIC)
-                set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
-            else
+      if (param->addr_type == BT_ADDR_LE_PUBLIC)
+        set_param.own_addr_type = BT_ADDR_LE_PUBLIC;
+      else
 #endif
-                set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+        set_param.own_addr_type = BT_ADDR_LE_RANDOM;
 #endif
-        }
-
-        if (err) {
-            return err;
-        }
-
-        set_param.type = BT_LE_ADV_NONCONN_IND;
     }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
+    if (err) {
+      return err;
     }
 
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
+    set_param.type = BT_LE_ADV_NONCONN_IND;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
-    if (err) {
-        return err;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING,
-                      !(param->options & BT_LE_ADV_OPT_ONE_TIME));
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME,
-                      param->options & BT_LE_ADV_OPT_USE_NAME);
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE,
-                      param->options & BT_LE_ADV_OPT_CONNECTABLE);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING, !(param->options & BT_LE_ADV_OPT_ONE_TIME));
 
-    return 0;
-}
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME, param->options & BT_LE_ADV_OPT_USE_NAME);
 
-int set_ad_and_rsp_d(u16_t hci_op, u8_t *data, u32_t ad_len)
-{
-    struct net_buf *buf;
-    u32_t len;
-    u8_t size;
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE, param->options & BT_LE_ADV_OPT_CONNECTABLE);
 
-    if (BT_HCI_OP_LE_SET_ADV_DATA == hci_op) {
-        size = sizeof(struct bt_hci_cp_le_set_adv_data);
+  return 0;
+}
 
-    } else if (BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op) {
-        size = sizeof(struct bt_hci_cp_le_set_scan_rsp_data);
+int set_ad_and_rsp_d(u16_t hci_op, u8_t *data, u32_t ad_len) {
+  struct net_buf *buf;
+  u32_t           len;
+  u8_t            size;
 
-    } else
-        return -ENOTSUP;
+  if (BT_HCI_OP_LE_SET_ADV_DATA == hci_op) {
+    size = sizeof(struct bt_hci_cp_le_set_adv_data);
 
-    buf = bt_hci_cmd_create(hci_op, size);
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  } else if (BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op) {
+    size = sizeof(struct bt_hci_cp_le_set_scan_rsp_data);
 
-    if (BT_HCI_OP_LE_SET_ADV_DATA == hci_op) {
-        struct bt_hci_cp_le_set_adv_data *set_data = net_buf_add(buf, size);
-        memset(set_data, 0, size);
-        set_data->len = ad_len;
+  } else
+    return -ENOTSUP;
 
-        if (set_data->len > 30) {
-            len = 30 - (set_data->len);
-            if (!len) {
-                net_buf_unref(buf);
-                return -ENOBUFS;
-            }
-        }
+  buf = bt_hci_cmd_create(hci_op, size);
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-        memcpy(set_data->data, data, set_data->len);
+  if (BT_HCI_OP_LE_SET_ADV_DATA == hci_op) {
+    struct bt_hci_cp_le_set_adv_data *set_data = net_buf_add(buf, size);
+    memset(set_data, 0, size);
+    set_data->len = ad_len;
 
-    } else if (BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op) {
-        struct bt_hci_cp_le_set_scan_rsp_data *set_data = net_buf_add(buf, size);
-        memset(set_data, 0, size);
+    if (set_data->len > 30) {
+      len = 30 - (set_data->len);
+      if (!len) {
+        net_buf_unref(buf);
+        return -ENOBUFS;
+      }
+    }
 
-        set_data->len = ad_len;
+    memcpy(set_data->data, data, set_data->len);
 
-        if (set_data->len > 30) {
-            len = 30 - (set_data->len);
-            if (!len) {
-                net_buf_unref(buf);
-                return -ENOBUFS;
-            }
-        }
+  } else if (BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op) {
+    struct bt_hci_cp_le_set_scan_rsp_data *set_data = net_buf_add(buf, size);
+    memset(set_data, 0, size);
 
-        memcpy(set_data->data, data, set_data->len);
+    set_data->len = ad_len;
 
-    } else
+    if (set_data->len > 30) {
+      len = 30 - (set_data->len);
+      if (!len) {
+        net_buf_unref(buf);
         return -ENOBUFS;
+      }
+    }
+
+    memcpy(set_data->data, data, set_data->len);
+
+  } else
+    return -ENOBUFS;
 
-    return bt_hci_cmd_send_sync(hci_op, buf, NULL);
+  return bt_hci_cmd_send_sync(hci_op, buf, NULL);
 }
 
-int set_adv_channel_map(u8_t channel)
-{
-    int err = 0;
+int set_adv_channel_map(u8_t channel) {
+  int err = 0;
 
-    if (channel >= 1 && channel <= 7) {
-        adv_ch_map = channel;
-    } else {
-        err = -1;
-    }
+  if (channel >= 1 && channel <= 7) {
+    adv_ch_map = channel;
+  } else {
+    err = -1;
+  }
 
-    return err;
+  return err;
 }
 
-int bt_get_local_public_address(bt_addr_le_t *adv_addr)
-{
-    int err = 0;
+int bt_get_local_public_address(bt_addr_le_t *adv_addr) {
+  int err = 0;
 
-    bt_addr_le_copy(adv_addr, bt_dev.id_addr);
-    return err;
+  bt_addr_le_copy(adv_addr, bt_dev.id_addr);
+  return err;
 }
 
-int bt_get_local_ramdon_address(bt_addr_le_t *adv_addr)
-{
-    int err = 0;
+int bt_get_local_ramdon_address(bt_addr_le_t *adv_addr) {
+  int err = 0;
 
-    bt_addr_le_copy(adv_addr, &bt_dev.random_addr);
-    return err;
+  bt_addr_le_copy(adv_addr, &bt_dev.random_addr);
+  return err;
 }
 #endif
 
-int bt_le_adv_start(const struct bt_le_adv_param *param,
-                    const struct bt_data *ad, size_t ad_len,
-                    const struct bt_data *sd, size_t sd_len)
-{
-    if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) {
-        return -EINVAL;
-    }
+int bt_le_adv_start(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len) {
+  if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) {
+    return -EINVAL;
+  }
 
-    return bt_le_adv_start_internal(param, ad, ad_len, sd, sd_len, NULL);
+  return bt_le_adv_start_internal(param, ad, ad_len, sd, sd_len, NULL);
 }
 
-int bt_le_adv_stop(void)
-{
-    int err;
+int bt_le_adv_stop(void) {
+  int err;
 
-    /* Make sure advertising is not re-enabled later even if it's not
-	 * currently enabled (i.e. BT_DEV_ADVERTISING is not set).
-	 */
-    atomic_clear_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING);
+  /* Make sure advertising is not re-enabled later even if it's not
+   * currently enabled (i.e. BT_DEV_ADVERTISING is not set).
+   */
+  atomic_clear_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING);
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return 0;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return 0;
+  }
 
-    err = set_advertise_enable(false);
-    if (err) {
-        return err;
-    }
+  err = set_advertise_enable(false);
+  if (err) {
+    return err;
+  }
 
-    if (!IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        /* If active scan is ongoing set NRPA */
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) &&
-            atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) {
-            le_set_private_addr(bt_dev.adv_id);
-        }
+  if (!IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    /* If active scan is ongoing set NRPA */
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) {
+      le_set_private_addr(bt_dev.adv_id);
     }
+  }
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BLE_MULTI_ADV)
-static int set_ad_data(u16_t hci_op, const uint8_t *ad_data, int ad_len)
-{
-    struct bt_hci_cp_le_set_adv_data *set_data;
-    struct net_buf *buf;
+static int set_ad_data(u16_t hci_op, const uint8_t *ad_data, int ad_len) {
+  struct bt_hci_cp_le_set_adv_data *set_data;
+  struct net_buf                   *buf;
 
-    buf = bt_hci_cmd_create(hci_op, sizeof(*set_data));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(hci_op, sizeof(*set_data));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    if (ad_len > 31)
-        return -EINVAL;
+  if (ad_len > 31)
+    return -EINVAL;
 
-    set_data = net_buf_add(buf, sizeof(*set_data));
+  set_data = net_buf_add(buf, sizeof(*set_data));
 
-    memset(set_data, 0, sizeof(*set_data));
-    memcpy(set_data->data, ad_data, ad_len);
-    set_data->len = ad_len;
+  memset(set_data, 0, sizeof(*set_data));
+  memcpy(set_data->data, ad_data, ad_len);
+  set_data->len = ad_len;
 
-    return bt_hci_cmd_send_sync(hci_op, buf, NULL);
+  return bt_hci_cmd_send_sync(hci_op, buf, NULL);
 }
 
-int bt_le_adv_start_instant(const struct bt_le_adv_param *param,
-                            const uint8_t *ad_data, size_t ad_len,
-                            const uint8_t *sd_data, size_t sd_len)
-{
-    struct bt_hci_cp_le_set_adv_param set_param;
-    struct net_buf *buf;
-    const bt_addr_le_t *id_addr;
-    int err;
+int bt_le_adv_start_instant(const struct bt_le_adv_param *param, const uint8_t *ad_data, size_t ad_len, const uint8_t *sd_data, size_t sd_len) {
+  struct bt_hci_cp_le_set_adv_param set_param;
+  struct net_buf                   *buf;
+  const bt_addr_le_t               *id_addr;
+  int                               err;
 
-    bt_le_adv_stop();
+  bt_le_adv_stop();
 
-    if (!valid_adv_param(param, false)) {
-        return -EINVAL;
-    }
+  if (!valid_adv_param(param, false)) {
+    return -EINVAL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
-        return -EALREADY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
+    return -EALREADY;
+  }
 
-    err = set_ad_data(BT_HCI_OP_LE_SET_ADV_DATA, ad_data, ad_len);
+  err = set_ad_data(BT_HCI_OP_LE_SET_ADV_DATA, ad_data, ad_len);
+  if (err) {
+    return err;
+  }
+
+  /*
+   * We need to set SCAN_RSP when enabling advertising type that allows
+   * for Scan Requests.
+   *
+   * If sd was not provided but we enable connectable undirected
+   * advertising sd needs to be cleared from values set by previous calls.
+   * Clearing sd is done by calling set_ad() with NULL data and zero len.
+   * So following condition check is unusual but correct.
+   */
+  if (sd_len || (param->options & BT_LE_ADV_OPT_CONNECTABLE)) {
+    err = set_ad_data(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, sd_data, sd_len);
     if (err) {
-        return err;
+      return err;
     }
+  }
 
-    /*
-     * We need to set SCAN_RSP when enabling advertising type that allows
-     * for Scan Requests.
-     *
-     * If sd was not provided but we enable connectable undirected
-     * advertising sd needs to be cleared from values set by previous calls.
-     * Clearing sd is done by calling set_ad() with NULL data and zero len.
-     * So following condition check is unusual but correct.
-     */
-    if (sd_len || (param->options & BT_LE_ADV_OPT_CONNECTABLE)) {
-        err = set_ad_data(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, sd_data, sd_len);
-        if (err) {
-            return err;
-        }
-    }
+  memset(&set_param, 0, sizeof(set_param));
 
-    memset(&set_param, 0, sizeof(set_param));
-
-    set_param.min_interval = sys_cpu_to_le16(param->interval_min);
-    set_param.max_interval = sys_cpu_to_le16(param->interval_max);
-    set_param.channel_map = 0x07;
-
-    bt_dev.adv_id = param->id;
-    id_addr = &bt_dev.id_addr[param->id];
-
-    if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
-        if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-            err = le_set_private_addr(bt_dev.adv_id);
-            if (err) {
-                return err;
-            }
-
-            if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
-                set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
-            } else {
-                set_param.own_addr_type = BT_ADDR_LE_RANDOM;
-            }
-        } else {
-            /*
-             * If Static Random address is used as Identity
-             * address we need to restore it before advertising
-             * is enabled. Otherwise NRPA used for active scan
-             * could be used for advertising.
-             */
-            if (id_addr->type == BT_ADDR_LE_RANDOM) {
-                err = set_random_address(&id_addr->a);
-                if (err) {
-                    return err;
-                }
-            }
-            set_param.own_addr_type = id_addr->type;
-        }
+  set_param.min_interval = sys_cpu_to_le16(param->interval_min);
+  set_param.max_interval = sys_cpu_to_le16(param->interval_max);
+  set_param.channel_map  = 0x07;
+
+  bt_dev.adv_id = param->id;
+  id_addr       = &bt_dev.id_addr[param->id];
+
+  if (param->options & BT_LE_ADV_OPT_CONNECTABLE) {
+    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+      err = le_set_private_addr(bt_dev.adv_id);
+      if (err) {
+        return err;
+      }
 
-        set_param.type = BT_LE_ADV_IND;
+      if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
+        set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
+      } else {
+        set_param.own_addr_type = BT_ADDR_LE_RANDOM;
+      }
     } else {
-        if (sd_len) {
-            set_param.type = BT_LE_ADV_SCAN_IND;
-        } else {
-            set_param.type = BT_LE_ADV_NONCONN_IND;
+      /*
+       * If Static Random address is used as Identity
+       * address we need to restore it before advertising
+       * is enabled. Otherwise NRPA used for active scan
+       * could be used for advertising.
+       */
+      if (id_addr->type == BT_ADDR_LE_RANDOM) {
+        err = set_random_address(&id_addr->a);
+        if (err) {
+          return err;
         }
+      }
+      set_param.own_addr_type = id_addr->type;
     }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
+    set_param.type = BT_LE_ADV_IND;
+  } else {
+    if (sd_len) {
+      set_param.type = BT_LE_ADV_SCAN_IND;
+    } else {
+      set_param.type = BT_LE_ADV_NONCONN_IND;
     }
+  }
 
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
-    if (err) {
-        return err;
-    }
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-    err = set_advertise_enable(true);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    if (!(param->options & BT_LE_ADV_OPT_ONE_TIME)) {
-        atomic_set_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING);
-    }
+  err = set_advertise_enable(true);
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  if (!(param->options & BT_LE_ADV_OPT_ONE_TIME)) {
+    atomic_set_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING);
+  }
+
+  return 0;
 }
-#endif //CONFIG_BLE_MULTI_ADV
+#endif // CONFIG_BLE_MULTI_ADV
 
 #if defined(CONFIG_BT_OBSERVER)
-static bool valid_le_scan_param(const struct bt_le_scan_param *param)
-{
-    if (param->type != BT_HCI_LE_SCAN_PASSIVE &&
-        param->type != BT_HCI_LE_SCAN_ACTIVE) {
-        return false;
-    }
+static bool valid_le_scan_param(const struct bt_le_scan_param *param) {
+  if (param->type != BT_HCI_LE_SCAN_PASSIVE && param->type != BT_HCI_LE_SCAN_ACTIVE) {
+    return false;
+  }
 
-    if (param->filter_dup &
-        ~(BT_LE_SCAN_FILTER_DUPLICATE | BT_LE_SCAN_FILTER_WHITELIST)) {
-        return false;
-    }
+  if (param->filter_dup & ~(BT_LE_SCAN_FILTER_DUPLICATE | BT_LE_SCAN_FILTER_WHITELIST)) {
+    return false;
+  }
 
-    if (is_wl_empty() &&
-        param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST) {
-        return false;
-    }
+  if (is_wl_empty() && param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST) {
+    return false;
+  }
 
-    if (param->interval < 0x0004 || param->interval > 0x4000) {
-        return false;
-    }
+  if (param->interval < 0x0004 || param->interval > 0x4000) {
+    return false;
+  }
 
-    if (param->window < 0x0004 || param->window > 0x4000) {
-        return false;
-    }
+  if (param->window < 0x0004 || param->window > 0x4000) {
+    return false;
+  }
 
-    if (param->window > param->interval) {
-        return false;
-    }
+  if (param->window > param->interval) {
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
-#if defined(CONFIG_BT_STACK_PTS)
-int bt_le_pts_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb, u8_t addre_type)
-{
-    int err;
+#if defined(CONFIG_BT_STACK_PTS)
+int bt_le_pts_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb, u8_t addre_type) {
+  int err;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EAGAIN;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EAGAIN;
+  }
 
-    /* Check that the parameters have valid values */
-    if (!valid_le_scan_param(param)) {
-        return -EINVAL;
-    }
+  /* Check that the parameters have valid values */
+  if (!valid_le_scan_param(param)) {
+    return -EINVAL;
+  }
 
-    /* Return if active scan is already enabled */
-    if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return -EALREADY;
-    }
+  /* Return if active scan is already enabled */
+  if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return -EALREADY;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
-        err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-        if (err) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
-            return err;
-        }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
+    err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+    if (err) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
+      return err;
     }
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP,
-                      param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP, param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE);
 
 #if defined(CONFIG_BT_WHITELIST)
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL,
-                      param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL, param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST);
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-    err = start_le_scan_with_isrpa(param->type, param->interval, param->window, addre_type);
+  err = start_le_scan_with_isrpa(param->type, param->interval, param->window, addre_type);
 
-    if (err) {
-        atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
-        return err;
-    }
+  if (err) {
+    atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
+    return err;
+  }
 
-    scan_dev_found_cb = cb;
+  scan_dev_found_cb = cb;
 
-    return 0;
+  return 0;
 }
 #endif
 int bt_le_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb)
 
 {
-    int err;
+  int err;
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        return -EAGAIN;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    return -EAGAIN;
+  }
 
-    /* Check that the parameters have valid values */
-    if (!valid_le_scan_param(param)) {
-        return -EINVAL;
-    }
+  /* Check that the parameters have valid values */
+  if (!valid_le_scan_param(param)) {
+    return -EINVAL;
+  }
 
-    /* Return if active scan is already enabled */
-    if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return -EALREADY;
-    }
+  /* Return if active scan is already enabled */
+  if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return -EALREADY;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
-        err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
-        if (err) {
-            atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
-            return err;
-        }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
+    err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE);
+    if (err) {
+      atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
+      return err;
     }
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP,
-                      param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP, param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE);
 
 #if defined(CONFIG_BT_WHITELIST)
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL,
-                      param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST);
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL, param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST);
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-    err = start_le_scan(param->type, param->interval, param->window);
-    if (err) {
-        atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
-        return err;
-    }
+  err = start_le_scan(param->type, param->interval, param->window);
+  if (err) {
+    atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
+    return err;
+  }
 
-    scan_dev_found_cb = cb;
+  scan_dev_found_cb = cb;
 
 #if defined(BFLB_HOST_ASSISTANT)
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_scan_cb)
-        host_assist_cb->le_scan_cb(param, cb);
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_ASSIST_RUN) && host_assist_cb && host_assist_cb->le_scan_cb)
+    host_assist_cb->le_scan_cb(param, cb);
 #endif
 
-    return 0;
+  return 0;
 }
 
-int bt_le_scan_stop(void)
-{
-    /* Return if active scanning is already disabled */
-    if (!atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
-        return -EALREADY;
-    }
+int bt_le_scan_stop(void) {
+  /* Return if active scanning is already disabled */
+  if (!atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+    return -EALREADY;
+  }
 
-    scan_dev_found_cb = NULL;
+  scan_dev_found_cb = NULL;
 
-    return bt_le_scan_update(false);
+  return bt_le_scan_update(false);
 }
 #endif /* CONFIG_BT_OBSERVER */
 
 #if defined(CONFIG_BT_WHITELIST)
-int bt_le_whitelist_add(const bt_addr_le_t *addr)
-{
-    struct bt_hci_cp_le_add_dev_to_wl *cp;
-    struct net_buf *buf;
-    int err;
+int bt_le_whitelist_add(const bt_addr_le_t *addr) {
+  struct bt_hci_cp_le_add_dev_to_wl *cp;
+  struct net_buf                    *buf;
+  int                                err;
 
-    if (!(bt_dev.le.wl_entries < bt_dev.le.wl_size)) {
-        return -ENOMEM;
-    }
+  if (!(bt_dev.le.wl_entries < bt_dev.le.wl_size)) {
+    return -ENOMEM;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_WL, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_WL, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_le_copy(&cp->addr, addr);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_le_copy(&cp->addr, addr);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_WL, buf, NULL);
-    if (err) {
-        BT_ERR("Failed to add device to whitelist");
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_WL, buf, NULL);
+  if (err) {
+    BT_ERR("Failed to add device to whitelist");
 
-        return err;
-    }
+    return err;
+  }
 
-    bt_dev.le.wl_entries++;
+  bt_dev.le.wl_entries++;
 
-    return 0;
+  return 0;
 }
 
-int bt_le_whitelist_rem(const bt_addr_le_t *addr)
-{
-    struct bt_hci_cp_le_rem_dev_from_wl *cp;
-    struct net_buf *buf;
-    int err;
+int bt_le_whitelist_rem(const bt_addr_le_t *addr) {
+  struct bt_hci_cp_le_rem_dev_from_wl *cp;
+  struct net_buf                      *buf;
+  int                                  err;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_WL, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_WL, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    bt_addr_le_copy(&cp->addr, addr);
+  cp = net_buf_add(buf, sizeof(*cp));
+  bt_addr_le_copy(&cp->addr, addr);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_WL, buf, NULL);
-    if (err) {
-        BT_ERR("Failed to remove device from whitelist");
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_WL, buf, NULL);
+  if (err) {
+    BT_ERR("Failed to remove device from whitelist");
+    return err;
+  }
 
-    bt_dev.le.wl_entries--;
-    return 0;
+  bt_dev.le.wl_entries--;
+  return 0;
 }
 
-int bt_le_whitelist_clear(void)
-{
-    int err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_WL, NULL, NULL);
+int bt_le_whitelist_clear(void) {
+  int err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_WL, NULL, NULL);
 
-    if (err) {
-        BT_ERR("Failed to clear whitelist");
-        return err;
-    }
+  if (err) {
+    BT_ERR("Failed to clear whitelist");
+    return err;
+  }
 
-    bt_dev.le.wl_entries = 0;
-    return 0;
+  bt_dev.le.wl_entries = 0;
+  return 0;
 }
 #endif /* defined(CONFIG_BT_WHITELIST) */
 
-int bt_le_set_chan_map(u8_t chan_map[5])
-{
-    struct bt_hci_cp_le_set_host_chan_classif *cp;
-    struct net_buf *buf;
+int bt_le_set_chan_map(u8_t chan_map[5]) {
+  struct bt_hci_cp_le_set_host_chan_classif *cp;
+  struct net_buf                            *buf;
 
-    if (!IS_ENABLED(CONFIG_BT_CENTRAL)) {
-        return -ENOTSUP;
-    }
+  if (!IS_ENABLED(CONFIG_BT_CENTRAL)) {
+    return -ENOTSUP;
+  }
 
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 3)) {
-        BT_WARN("Set Host Channel Classification command is "
-                "not supported");
-        return -ENOTSUP;
-    }
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 3)) {
+    BT_WARN("Set Host Channel Classification command is "
+            "not supported");
+    return -ENOTSUP;
+  }
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF,
-                            sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    memcpy(&cp->ch_map[0], &chan_map[0], 4);
-    cp->ch_map[4] = chan_map[4] & BIT_MASK(5);
+  memcpy(&cp->ch_map[0], &chan_map[0], 4);
+  cp->ch_map[4] = chan_map[4] & BIT_MASK(5);
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF,
-                                buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, buf, NULL);
 }
 #if defined(CONFIG_SET_TX_PWR)
-int bt_set_tx_pwr(int8_t power)
-{
-    struct bt_hci_cp_vs_set_tx_pwr set_param;
-    struct net_buf *buf;
-    int err;
+int bt_set_tx_pwr(int8_t power) {
+  struct bt_hci_cp_vs_set_tx_pwr set_param;
+  struct net_buf                *buf;
+  int                            err;
 
-    if (power < 0 || power > 20)
-        return BT_HCI_ERR_INVALID_PARAM;
+  if (power < 0 || power > 20)
+    return BT_HCI_ERR_INVALID_PARAM;
 
-    memset(&set_param, 0, sizeof(set_param));
+  memset(&set_param, 0, sizeof(set_param));
 
-    set_param.power = power;
+  set_param.power = power;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_VS_SET_TX_PWR, sizeof(set_param));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_VS_SET_TX_PWR, sizeof(set_param));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_mem(buf, &set_param, sizeof(set_param));
+  net_buf_add_mem(buf, &set_param, sizeof(set_param));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_SET_TX_PWR, buf, NULL);
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_SET_TX_PWR, buf, NULL);
 
-    if (err) {
-        return err;
-    }
+  if (err) {
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 #endif
 
-int bt_buf_get_rx_avail_cnt(void)
-{
-    return (k_queue_get_cnt(&hci_rx_pool.free._queue) + hci_rx_pool.uninit_count);
-}
+int bt_buf_get_rx_avail_cnt(void) { return (k_queue_get_cnt(&hci_rx_pool.free._queue) + hci_rx_pool.uninit_count); }
 
-struct net_buf *bt_buf_get_rx(enum bt_buf_type type, s32_t timeout)
-{
-    struct net_buf *buf;
+struct net_buf *bt_buf_get_rx(enum bt_buf_type type, s32_t timeout) {
+  struct net_buf *buf;
 
-    __ASSERT(type == BT_BUF_EVT || type == BT_BUF_ACL_IN,
-             "Invalid buffer type requested");
+  __ASSERT(type == BT_BUF_EVT || type == BT_BUF_ACL_IN, "Invalid buffer type requested");
 
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-    if (type == BT_BUF_EVT) {
-        buf = net_buf_alloc(&hci_rx_pool, timeout);
-    } else {
-        buf = net_buf_alloc(&acl_in_pool, timeout);
-    }
-#else
+  if (type == BT_BUF_EVT) {
     buf = net_buf_alloc(&hci_rx_pool, timeout);
+  } else {
+    buf = net_buf_alloc(&acl_in_pool, timeout);
+  }
+#else
+  buf = net_buf_alloc(&hci_rx_pool, timeout);
 #endif
 
-    if (buf) {
-        net_buf_reserve(buf, BT_BUF_RESERVE);
-        bt_buf_set_type(buf, type);
-    }
+  if (buf) {
+    net_buf_reserve(buf, BT_BUF_RESERVE);
+    bt_buf_set_type(buf, type);
+  }
 
-    return buf;
+  return buf;
 }
 
-struct net_buf *bt_buf_get_cmd_complete(s32_t timeout)
-{
-    struct net_buf *buf;
-    unsigned int key;
+struct net_buf *bt_buf_get_cmd_complete(s32_t timeout) {
+  struct net_buf *buf;
+  unsigned int    key;
 
-    key = irq_lock();
-    buf = bt_dev.sent_cmd;
-    bt_dev.sent_cmd = NULL;
-    irq_unlock(key);
+  key             = irq_lock();
+  buf             = bt_dev.sent_cmd;
+  bt_dev.sent_cmd = NULL;
+  irq_unlock(key);
 
-    BT_DBG("sent_cmd %p", buf);
+  BT_DBG("sent_cmd %p", buf);
 
-    if (buf) {
-        bt_buf_set_type(buf, BT_BUF_EVT);
-        buf->len = 0U;
-        net_buf_reserve(buf, BT_BUF_RESERVE);
+  if (buf) {
+    bt_buf_set_type(buf, BT_BUF_EVT);
+    buf->len = 0U;
+    net_buf_reserve(buf, BT_BUF_RESERVE);
 
-        return buf;
-    }
+    return buf;
+  }
 
-    return bt_buf_get_rx(BT_BUF_EVT, timeout);
+  return bt_buf_get_rx(BT_BUF_EVT, timeout);
 }
 
-struct net_buf *bt_buf_get_evt(u8_t evt, bool discardable, s32_t timeout)
-{
-    switch (evt) {
+struct net_buf *bt_buf_get_evt(u8_t evt, bool discardable, s32_t timeout) {
+  switch (evt) {
 #if defined(CONFIG_BT_CONN)
-        case BT_HCI_EVT_NUM_COMPLETED_PACKETS: {
-            struct net_buf *buf;
+  case BT_HCI_EVT_NUM_COMPLETED_PACKETS: {
+    struct net_buf *buf;
 
-            buf = net_buf_alloc(&num_complete_pool, timeout);
-            if (buf) {
-                net_buf_reserve(buf, BT_BUF_RESERVE);
-                bt_buf_set_type(buf, BT_BUF_EVT);
-            }
+    buf = net_buf_alloc(&num_complete_pool, timeout);
+    if (buf) {
+      net_buf_reserve(buf, BT_BUF_RESERVE);
+      bt_buf_set_type(buf, BT_BUF_EVT);
+    }
 
-            return buf;
-        }
+    return buf;
+  }
 #endif /* CONFIG_BT_CONN */
-        case BT_HCI_EVT_CMD_COMPLETE:
-        case BT_HCI_EVT_CMD_STATUS:
-            return bt_buf_get_cmd_complete(timeout);
-        default:
+  case BT_HCI_EVT_CMD_COMPLETE:
+  case BT_HCI_EVT_CMD_STATUS:
+    return bt_buf_get_cmd_complete(timeout);
+  default:
 #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
-            if (discardable) {
-                struct net_buf *buf;
+    if (discardable) {
+      struct net_buf *buf;
 
-                buf = net_buf_alloc(&discardable_pool, timeout);
-                if (buf) {
-                    net_buf_reserve(buf, BT_BUF_RESERVE);
-                    bt_buf_set_type(buf, BT_BUF_EVT);
-                }
+      buf = net_buf_alloc(&discardable_pool, timeout);
+      if (buf) {
+        net_buf_reserve(buf, BT_BUF_RESERVE);
+        bt_buf_set_type(buf, BT_BUF_EVT);
+      }
 
-                return buf;
-            }
+      return buf;
+    }
 #endif /* CONFIG_BT_DISCARDABLE_BUF_COUNT */
 
-            return bt_buf_get_rx(BT_BUF_EVT, timeout);
-    }
+    return bt_buf_get_rx(BT_BUF_EVT, timeout);
+  }
 }
 
 #if defined(CONFIG_BT_BREDR)
-static int br_start_inquiry(const struct bt_br_discovery_param *param)
-{
-    const u8_t iac[3] = { 0x33, 0x8b, 0x9e };
-    struct bt_hci_op_inquiry *cp;
-    struct net_buf *buf;
+static int br_start_inquiry(const struct bt_br_discovery_param *param) {
+  const u8_t                iac[3] = {0x33, 0x8b, 0x9e};
+  struct bt_hci_op_inquiry *cp;
+  struct net_buf           *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_INQUIRY, sizeof(*cp));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_INQUIRY, sizeof(*cp));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
+  cp = net_buf_add(buf, sizeof(*cp));
 
-    cp->length = param->length;
-    cp->num_rsp = 0xff; /* we limit discovery only by time */
+  cp->length  = param->length;
+  cp->num_rsp = 0xff; /* we limit discovery only by time */
 
-    memcpy(cp->lap, iac, 3);
-    if (param->limited) {
-        cp->lap[0] = 0x00;
-    }
+  memcpy(cp->lap, iac, 3);
+  if (param->limited) {
+    cp->lap[0] = 0x00;
+  }
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY, buf, NULL);
 }
 
-static bool valid_br_discov_param(const struct bt_br_discovery_param *param,
-                                  size_t num_results)
-{
-    if (!num_results || num_results > 255) {
-        return false;
-    }
+static bool valid_br_discov_param(const struct bt_br_discovery_param *param, size_t num_results) {
+  if (!num_results || num_results > 255) {
+    return false;
+  }
 
-    if (!param->length || param->length > 0x30) {
-        return false;
-    }
+  if (!param->length || param->length > 0x30) {
+    return false;
+  }
 
-    return true;
+  return true;
 }
 
-int bt_br_discovery_start(const struct bt_br_discovery_param *param,
-                          struct bt_br_discovery_result *results, size_t cnt,
-                          bt_br_discovery_cb_t cb)
-{
-    int err;
+int bt_br_discovery_start(const struct bt_br_discovery_param *param, struct bt_br_discovery_result *results, size_t cnt, bt_br_discovery_cb_t cb) {
+  int err;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    if (!valid_br_discov_param(param, cnt)) {
-        return -EINVAL;
-    }
+  if (!valid_br_discov_param(param, cnt)) {
+    return -EINVAL;
+  }
 
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
-        return -EALREADY;
-    }
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
+    return -EALREADY;
+  }
 
-    err = br_start_inquiry(param);
-    if (err) {
-        return err;
-    }
+  err = br_start_inquiry(param);
+  if (err) {
+    return err;
+  }
 
-    atomic_set_bit(bt_dev.flags, BT_DEV_INQUIRY);
+  atomic_set_bit(bt_dev.flags, BT_DEV_INQUIRY);
 
-    (void)memset(results, 0, sizeof(*results) * cnt);
+  (void)memset(results, 0, sizeof(*results) * cnt);
 
-    discovery_cb = cb;
-    discovery_results = results;
-    discovery_results_size = cnt;
-    discovery_results_count = 0;
+  discovery_cb            = cb;
+  discovery_results       = results;
+  discovery_results_size  = cnt;
+  discovery_results_count = 0;
 
-    return 0;
+  return 0;
 }
 
-int bt_br_discovery_stop(void)
-{
-    int err;
-    int i;
+int bt_br_discovery_stop(void) {
+  int err;
+  int i;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
-        return -EALREADY;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) {
+    return -EALREADY;
+  }
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY_CANCEL, NULL, NULL);
-    if (err) {
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY_CANCEL, NULL, NULL);
+  if (err) {
+    return err;
+  }
 
-    for (i = 0; i < discovery_results_count; i++) {
-        struct discovery_priv *priv;
-        struct bt_hci_cp_remote_name_cancel *cp;
-        struct net_buf *buf;
+  for (i = 0; i < discovery_results_count; i++) {
+    struct discovery_priv               *priv;
+    struct bt_hci_cp_remote_name_cancel *cp;
+    struct net_buf                      *buf;
 
-        priv = (struct discovery_priv *)&discovery_results[i]._priv;
+    priv = (struct discovery_priv *)&discovery_results[i]._priv;
 
-        if (!priv->resolving) {
-            continue;
-        }
+    if (!priv->resolving) {
+      continue;
+    }
 
-        buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_CANCEL,
-                                sizeof(*cp));
-        if (!buf) {
-            continue;
-        }
+    buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_CANCEL, sizeof(*cp));
+    if (!buf) {
+      continue;
+    }
 
-        cp = net_buf_add(buf, sizeof(*cp));
-        bt_addr_copy(&cp->bdaddr, &discovery_results[i].addr);
+    cp = net_buf_add(buf, sizeof(*cp));
+    bt_addr_copy(&cp->bdaddr, &discovery_results[i].addr);
 
-        bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_CANCEL, buf, NULL);
-    }
+    bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_CANCEL, buf, NULL);
+  }
 
-    atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
+  atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY);
 
-    discovery_cb = NULL;
-    discovery_results = NULL;
-    discovery_results_size = 0;
-    discovery_results_count = 0;
+  discovery_cb            = NULL;
+  discovery_results       = NULL;
+  discovery_results_size  = 0;
+  discovery_results_count = 0;
 
-    return 0;
+  return 0;
 }
 
-static int write_scan_enable(u8_t scan)
-{
-    struct net_buf *buf;
-    int err;
+static int write_scan_enable(u8_t scan) {
+  struct net_buf *buf;
+  int             err;
 
-    BT_DBG("type %u", scan);
+  BT_DBG("type %u", scan);
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SCAN_ENABLE, 1);
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SCAN_ENABLE, 1);
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    net_buf_add_u8(buf, scan);
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SCAN_ENABLE, buf, NULL);
-    if (err) {
-        return err;
-    }
+  net_buf_add_u8(buf, scan);
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SCAN_ENABLE, buf, NULL);
+  if (err) {
+    return err;
+  }
 
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_ISCAN,
-                      (scan & BT_BREDR_SCAN_INQUIRY));
-    atomic_set_bit_to(bt_dev.flags, BT_DEV_PSCAN,
-                      (scan & BT_BREDR_SCAN_PAGE));
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_ISCAN, (scan & BT_BREDR_SCAN_INQUIRY));
+  atomic_set_bit_to(bt_dev.flags, BT_DEV_PSCAN, (scan & BT_BREDR_SCAN_PAGE));
 
-    return 0;
+  return 0;
 }
 
-int bt_br_set_connectable(bool enable)
-{
-    if (enable) {
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
-            return -EALREADY;
-        } else {
-            return write_scan_enable(BT_BREDR_SCAN_PAGE);
-        }
+int bt_br_set_connectable(bool enable) {
+  if (enable) {
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
+      return -EALREADY;
     } else {
-        if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
-            return -EALREADY;
-        } else {
-            return write_scan_enable(BT_BREDR_SCAN_DISABLED);
-        }
+      return write_scan_enable(BT_BREDR_SCAN_PAGE);
+    }
+  } else {
+    if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
+      return -EALREADY;
+    } else {
+      return write_scan_enable(BT_BREDR_SCAN_DISABLED);
     }
+  }
 }
 
-int bt_br_set_discoverable(bool enable)
-{
-    if (enable) {
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
-            return -EALREADY;
-        }
-
-        if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
-            return -EPERM;
-        }
+int bt_br_set_discoverable(bool enable) {
+  if (enable) {
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
+      return -EALREADY;
+    }
 
-        return write_scan_enable(BT_BREDR_SCAN_INQUIRY |
-                                 BT_BREDR_SCAN_PAGE);
-    } else {
-        if (!atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
-            return -EALREADY;
-        }
+    if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) {
+      return -EPERM;
+    }
 
-        return write_scan_enable(BT_BREDR_SCAN_PAGE);
+    return write_scan_enable(BT_BREDR_SCAN_INQUIRY | BT_BREDR_SCAN_PAGE);
+  } else {
+    if (!atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) {
+      return -EALREADY;
     }
+
+    return write_scan_enable(BT_BREDR_SCAN_PAGE);
+  }
 }
 
-int bt_br_write_eir(u8_t rec, u8_t *data)
-{
-    struct bt_hci_cp_write_ext_inquiry_resp *ext_ir;
-    struct net_buf *buf;
+int bt_br_write_eir(u8_t rec, u8_t *data) {
+  struct bt_hci_cp_write_ext_inquiry_resp *ext_ir;
+  struct net_buf                          *buf;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_EXT_INQUIRY_RESP, sizeof(*ext_ir));
-    if (!buf) {
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_EXT_INQUIRY_RESP, sizeof(*ext_ir));
+  if (!buf) {
+    return -ENOBUFS;
+  }
 
-    ext_ir = net_buf_add(buf, sizeof(*ext_ir));
-    memset(ext_ir, 0, sizeof(*ext_ir));
+  ext_ir = net_buf_add(buf, sizeof(*ext_ir));
+  memset(ext_ir, 0, sizeof(*ext_ir));
 
-    ext_ir->rec = rec;
-    memcpy(ext_ir->eir, data, strlen((char *)data));
+  ext_ir->rec = rec;
+  memcpy(ext_ir->eir, data, strlen((char *)data));
 
-    return bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_EXT_INQUIRY_RESP, buf, NULL);
+  return bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_EXT_INQUIRY_RESP, buf, NULL);
 }
 
 #endif /* CONFIG_BT_BREDR */
 
 #if defined(CONFIG_BT_ECC)
-int bt_pub_key_gen(struct bt_pub_key_cb *new_cb)
-{
-    int err;
-
-    /*
-	 * We check for both "LE Read Local P-256 Public Key" and
-	 * "LE Generate DH Key" support here since both commands are needed for
-	 * ECC support. If "LE Generate DH Key" is not supported then there
-	 * is no point in reading local public key.
-	 */
-    if (!BT_CMD_TEST(bt_dev.supported_commands, 34, 1) ||
-        !BT_CMD_TEST(bt_dev.supported_commands, 34, 2)) {
-        BT_WARN("ECC HCI commands not available");
-        return -ENOTSUP;
-    }
+int bt_pub_key_gen(struct bt_pub_key_cb *new_cb) {
+  int err;
+
+  /*
+   * We check for both "LE Read Local P-256 Public Key" and
+   * "LE Generate DH Key" support here since both commands are needed for
+   * ECC support. If "LE Generate DH Key" is not supported then there
+   * is no point in reading local public key.
+   */
+  if (!BT_CMD_TEST(bt_dev.supported_commands, 34, 1) || !BT_CMD_TEST(bt_dev.supported_commands, 34, 2)) {
+    BT_WARN("ECC HCI commands not available");
+    return -ENOTSUP;
+  }
 
 #if defined(BFLB_BLE_PATCH_AVOID_DUPLI_PUBKEY_CB)
-    struct bt_pub_key_cb *cb;
-    struct bt_pub_key_cb *valid_cb;
-    bool existed = false;
-
-    if (pub_key_cb) {
-        cb = pub_key_cb;
-        valid_cb = cb;
-        while (cb) {
-            if (new_cb->func == cb->func) {
-                existed = true;
-                break;
-            }
-
-            valid_cb = cb;
-            cb = cb->_next;
-        }
+  struct bt_pub_key_cb *cb;
+  struct bt_pub_key_cb *valid_cb;
+  bool                  existed = false;
 
-        if (!existed) {
-            valid_cb->_next = new_cb;
-        }
-    } else {
-        pub_key_cb = new_cb;
+  if (pub_key_cb) {
+    cb       = pub_key_cb;
+    valid_cb = cb;
+    while (cb) {
+      if (new_cb->func == cb->func) {
+        existed = true;
+        break;
+      }
+
+      valid_cb = cb;
+      cb       = cb->_next;
     }
-#else
-    new_cb->_next = pub_key_cb;
+
+    if (!existed) {
+      valid_cb->_next = new_cb;
+    }
+  } else {
     pub_key_cb = new_cb;
+  }
+#else
+  new_cb->_next = pub_key_cb;
+  pub_key_cb    = new_cb;
 #endif
 
-    if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) {
-        return 0;
-    }
+  if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) {
+    return 0;
+  }
 
-    atomic_clear_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY);
+  atomic_clear_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY);
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_P256_PUBLIC_KEY, NULL, NULL);
-    if (err) {
-        BT_ERR("Sending LE P256 Public Key command failed");
-        atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY);
-        pub_key_cb = NULL;
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_P256_PUBLIC_KEY, NULL, NULL);
+  if (err) {
+    BT_ERR("Sending LE P256 Public Key command failed");
+    atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY);
+    pub_key_cb = NULL;
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-const u8_t *bt_pub_key_get(void)
-{
-    if (atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) {
-        return pub_key;
-    }
+const u8_t *bt_pub_key_get(void) {
+  if (atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) {
+    return pub_key;
+  }
 
-    return NULL;
+  return NULL;
 }
 
-int bt_dh_key_gen(const u8_t remote_pk[64], bt_dh_key_cb_t cb)
-{
-    struct bt_hci_cp_le_generate_dhkey *cp;
-    struct net_buf *buf;
-    int err;
+int bt_dh_key_gen(const u8_t remote_pk[64], bt_dh_key_cb_t cb) {
+  struct bt_hci_cp_le_generate_dhkey *cp;
+  struct net_buf                     *buf;
+  int                                 err;
 
-    if (dh_key_cb || atomic_test_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) {
-        return -EBUSY;
-    }
+  if (dh_key_cb || atomic_test_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) {
+    return -EBUSY;
+  }
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) {
-        return -EADDRNOTAVAIL;
-    }
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) {
+    return -EADDRNOTAVAIL;
+  }
 
-    dh_key_cb = cb;
+  dh_key_cb = cb;
 
-    buf = bt_hci_cmd_create(BT_HCI_OP_LE_GENERATE_DHKEY, sizeof(*cp));
-    if (!buf) {
-        dh_key_cb = NULL;
-        return -ENOBUFS;
-    }
+  buf = bt_hci_cmd_create(BT_HCI_OP_LE_GENERATE_DHKEY, sizeof(*cp));
+  if (!buf) {
+    dh_key_cb = NULL;
+    return -ENOBUFS;
+  }
 
-    cp = net_buf_add(buf, sizeof(*cp));
-    memcpy(cp->key, remote_pk, sizeof(cp->key));
+  cp = net_buf_add(buf, sizeof(*cp));
+  memcpy(cp->key, remote_pk, sizeof(cp->key));
 
-    err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_GENERATE_DHKEY, buf, NULL);
-    if (err) {
-        dh_key_cb = NULL;
-        return err;
-    }
+  err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_GENERATE_DHKEY, buf, NULL);
+  if (err) {
+    dh_key_cb = NULL;
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_ECC */
 
 #if defined(CONFIG_BT_BREDR)
-int bt_br_oob_get_local(struct bt_br_oob *oob)
-{
-    bt_addr_copy(&oob->addr, &bt_dev.id_addr[0].a);
+int bt_br_oob_get_local(struct bt_br_oob *oob) {
+  bt_addr_copy(&oob->addr, &bt_dev.id_addr[0].a);
 
-    return 0;
+  return 0;
 }
 #endif /* CONFIG_BT_BREDR */
 
-int bt_le_oob_get_local(u8_t id, struct bt_le_oob *oob)
-{
-    int err;
-
-    if (id >= CONFIG_BT_ID_MAX) {
-        return -EINVAL;
-    }
+int bt_le_oob_get_local(u8_t id, struct bt_le_oob *oob) {
+  int err;
 
-    if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
-        /* Invalidate RPA so a new one is generated */
-        atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
+  if (id >= CONFIG_BT_ID_MAX) {
+    return -EINVAL;
+  }
 
-        err = le_set_private_addr(id);
-        if (err) {
-            return err;
-        }
+  if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
+    /* Invalidate RPA so a new one is generated */
+    atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
 
-        bt_addr_le_copy(&oob->addr, &bt_dev.random_addr);
-    } else {
-        bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[id]);
+    err = le_set_private_addr(id);
+    if (err) {
+      return err;
     }
 
-    if (IS_ENABLED(CONFIG_BT_SMP)) {
-        err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data);
-        if (err) {
-            return err;
-        }
+    bt_addr_le_copy(&oob->addr, &bt_dev.random_addr);
+  } else {
+    bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[id]);
+  }
+
+  if (IS_ENABLED(CONFIG_BT_SMP)) {
+    err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data);
+    if (err) {
+      return err;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_SMP)
-int bt_le_oob_set_sc_data(struct bt_conn *conn,
-                          const struct bt_le_oob_sc_data *oobd_local,
-                          const struct bt_le_oob_sc_data *oobd_remote)
-{
-    return bt_smp_le_oob_set_sc_data(conn, oobd_local, oobd_remote);
+int bt_le_oob_set_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data *oobd_local, const struct bt_le_oob_sc_data *oobd_remote) {
+  return bt_smp_le_oob_set_sc_data(conn, oobd_local, oobd_remote);
 }
 
-int bt_le_oob_get_sc_data(struct bt_conn *conn,
-                          const struct bt_le_oob_sc_data **oobd_local,
-                          const struct bt_le_oob_sc_data **oobd_remote)
-{
-    return bt_smp_le_oob_get_sc_data(conn, oobd_local, oobd_remote);
+int bt_le_oob_get_sc_data(struct bt_conn *conn, const struct bt_le_oob_sc_data **oobd_local, const struct bt_le_oob_sc_data **oobd_remote) {
+  return bt_smp_le_oob_get_sc_data(conn, oobd_local, oobd_remote);
 }
 #endif
 
 #if defined(BFLB_RELEASE_CMD_SEM_IF_CONN_DISC)
-void hci_release_conn_related_cmd(void)
-{
-    u16_t opcode;
-
-    (void)opcode;
-
-    if (bt_dev.sent_cmd) {
-        opcode = cmd(bt_dev.sent_cmd)->opcode;
-        switch (opcode) {
-            case BT_HCI_OP_LE_SET_DATA_LEN:
-            case BT_HCI_OP_LE_READ_REMOTE_FEATURES:
-            case BT_HCI_OP_LE_SET_DEFAULT_PHY:
-            case BT_HCI_OP_LE_SET_PHY:
-            case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY:
-            case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY:
-            case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY:
-            case BT_HCI_OP_LE_LTK_REQ_REPLY: {
-                k_sem_give(&bt_dev.ncmd_sem);
-                hci_cmd_done(opcode, BT_HCI_ERR_UNSPECIFIED, bt_dev.sent_cmd);
-                net_buf_unref(bt_dev.sent_cmd);
-                bt_dev.sent_cmd = NULL;
-            } break;
-            default:
-                break;
-        }
-    }
+void hci_release_conn_related_cmd(void) {
+  u16_t opcode;
+
+  (void)opcode;
+
+  if (bt_dev.sent_cmd) {
+    opcode = cmd(bt_dev.sent_cmd)->opcode;
+    switch (opcode) {
+    case BT_HCI_OP_LE_SET_DATA_LEN:
+    case BT_HCI_OP_LE_READ_REMOTE_FEATURES:
+    case BT_HCI_OP_LE_SET_DEFAULT_PHY:
+    case BT_HCI_OP_LE_SET_PHY:
+    case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY:
+    case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY:
+    case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY:
+    case BT_HCI_OP_LE_LTK_REQ_REPLY: {
+      k_sem_give(&bt_dev.ncmd_sem);
+      hci_cmd_done(opcode, BT_HCI_ERR_UNSPECIFIED, bt_dev.sent_cmd);
+      net_buf_unref(bt_dev.sent_cmd);
+      bt_dev.sent_cmd = NULL;
+    } break;
+    default:
+      break;
+    }
+  }
 }
 #endif
 
 #if defined(BFLB_HOST_ASSISTANT)
 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
-int bt_set_flow_control(void)
-{
-    return set_flow_control();
-}
+int bt_set_flow_control(void) { return set_flow_control(); }
 #endif
-int bt_set_event_mask(void)
-{
-    return set_event_mask();
-}
+int bt_set_event_mask(void) { return set_event_mask(); }
 
-int bt_le_set_event_mask(void)
-{
-    return le_set_event_mask();
-}
+int bt_le_set_event_mask(void) { return le_set_event_mask(); }
 
-void bt_hci_reset_complete(struct net_buf *buf)
-{
-    hci_reset_complete(buf);
-}
+void bt_hci_reset_complete(struct net_buf *buf) { hci_reset_complete(buf); }
 
-void bt_register_host_assist_cb(struct blhast_cb *cb)
-{
-    host_assist_cb = cb;
-}
+void bt_register_host_assist_cb(struct blhast_cb *cb) { host_assist_cb = cb; }
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.h
index 488e5311a..2411fc605 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_core.h
@@ -20,10 +20,22 @@
 #define BT_VOICE_CVSD_16BIT 0x0060
 #define BT_VOICE_MSBC_16BIT 0x0063
 
+#if (BFLB_BT_CO_THREAD)
+enum {
+    BT_CMD_SYNC_NONE = 0,
+    BT_CMD_SYNC_TX = 1,
+    BT_CMD_SYNC_TX_DONE = 2
+};
+#endif
+
 /* k_poll event tags */
 enum {
     BT_EVENT_CMD_TX,
     BT_EVENT_CONN_TX_QUEUE,
+#if (BFLB_BT_CO_THREAD)
+    BT_EVENT_RX_QUEUE,
+    BT_EVENT_WORK_QUEUE,
+#endif
 };
 
 /* bt_dev flags: the flags defined here represent BT controller state */
@@ -60,6 +72,10 @@ enum {
     BT_DEV_ADV_ADDRESS_IS_PUBLIC,
 #endif
 
+#if defined(CONFIG_AUTO_PTS)
+    BT_DEV_SETTED_NON_RESOLV_ADDR, //The non-reslovable address have been set.
+#endif
+
 #if defined(BFLB_HOST_ASSISTANT)
     BT_DEV_ASSIST_RUN,
 #endif
@@ -262,8 +278,9 @@ int set_adv_channel_map(u8_t channel);
 int bt_get_local_public_address(bt_addr_le_t *adv_addr);
 int bt_get_local_ramdon_address(bt_addr_le_t *adv_addr);
 int bt_le_set_data_len(struct bt_conn *conn, u16_t tx_octets, u16_t tx_time);
-int hci_le_set_phy(struct bt_conn *conn);
-int hci_le_set_default_phy(struct bt_conn *conn, u8_t default_phy);
+int hci_le_set_phy(struct bt_conn *conn, uint8_t all_phys,
+                   uint8_t pref_tx_phy, uint8_t pref_rx_phy, uint8_t phy_opts);
+int hci_le_set_default_phy(u8_t default_phy);
 
 #if defined(CONFIG_SET_TX_PWR)
 int bt_set_tx_pwr(int8_t power);
@@ -282,4 +299,7 @@ void bt_hci_reset_complete(struct net_buf *buf);
 void bt_register_host_assist_cb(struct blhast_cb *cb);
 #endif
 
+typedef void (*bredr_name_callback)(const char *name);
+int remote_name_req(const bt_addr_t *addr, bredr_name_callback cb);
+
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c
index e9170a8c9..3a8a95b45 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hci_ecc.c
@@ -9,28 +9,28 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
 #include 
-#include 
-#include 
 #include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
+#include 
 
+#include <../include/bluetooth/crypto.h>
 #include 
 #include 
-#include 
 #include 
-#include <../include/bluetooth/crypto.h>
+#include 
 
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE)
 #include "log.h"
 
 #include "hci_ecc.h"
 #ifdef CONFIG_BT_HCI_RAW
-#include 
 #include "hci_raw_internal.h"
+#include 
 #else
 #include "hci_core.h"
 #endif
@@ -41,28 +41,20 @@ static BT_STACK_NOINIT(ecc_thread_stack, 1024);
 #endif
 
 /* based on Core Specification 4.2 Vol 3. Part H 2.3.5.6.1 */
-static const u32_t debug_private_key[8] = {
-    0xcd3c1abd, 0x5899b8a6, 0xeb40b799, 0x4aff607b, 0xd2103f50, 0x74c9b3e3,
-    0xa3c55f38, 0x3f49f6d4
-};
+static const u32_t debug_private_key[8] = {0xcd3c1abd, 0x5899b8a6, 0xeb40b799, 0x4aff607b, 0xd2103f50, 0x74c9b3e3, 0xa3c55f38, 0x3f49f6d4};
 
 #if defined(CONFIG_BT_USE_DEBUG_KEYS)
-static const u8_t debug_public_key[64] = {
-    0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac,
-    0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e,
-    0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, 0x8b, 0xd2, 0x89, 0x15,
-    0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76,
-    0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65,
-    0x49, 0x9c, 0x80, 0xdc
-};
+static const u8_t debug_public_key[64] = {0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83,
+                                          0x2c, 0x5e, 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, 0x8b, 0xd2, 0x89, 0x15, 0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f,
+                                          0xc2, 0x45, 0x63, 0x76, 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65, 0x49, 0x9c, 0x80, 0xdc};
 #endif
 
 enum {
-    PENDING_PUB_KEY,
-    PENDING_DHKEY,
+  PENDING_PUB_KEY,
+  PENDING_DHKEY,
 
-    /* Total number of flags - must be at the end of the enum */
-    NUM_FLAGS,
+  /* Total number of flags - must be at the end of the enum */
+  NUM_FLAGS,
 };
 
 static ATOMIC_DEFINE(flags, NUM_FLAGS);
@@ -70,140 +62,135 @@ static ATOMIC_DEFINE(flags, NUM_FLAGS);
 static K_SEM_DEFINE(cmd_sem, 0, 1);
 
 static struct {
-    u8_t private_key[32];
+  u8_t private_key[32];
 
-    union {
-        u8_t pk[64];
-        u8_t dhkey[32];
-    };
+  union {
+    u8_t pk[64];
+    u8_t dhkey[32];
+  };
 } ecc;
 
-static void send_cmd_status(u16_t opcode, u8_t status)
-{
-    struct bt_hci_evt_cmd_status *evt;
-    struct bt_hci_evt_hdr *hdr;
-    struct net_buf *buf;
+static void send_cmd_status(u16_t opcode, u8_t status) {
+  struct bt_hci_evt_cmd_status *evt;
+  struct bt_hci_evt_hdr        *hdr;
+  struct net_buf               *buf;
 
-    BT_DBG("opcode %x status %x", opcode, status);
+  BT_DBG("opcode %x status %x", opcode, status);
 
-    buf = bt_buf_get_evt(BT_HCI_EVT_CMD_STATUS, false, K_FOREVER);
-    bt_buf_set_type(buf, BT_BUF_EVT);
+  buf = bt_buf_get_evt(BT_HCI_EVT_CMD_STATUS, false, K_FOREVER);
+  bt_buf_set_type(buf, BT_BUF_EVT);
 
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->evt = BT_HCI_EVT_CMD_STATUS;
-    hdr->len = sizeof(*evt);
+  hdr      = net_buf_add(buf, sizeof(*hdr));
+  hdr->evt = BT_HCI_EVT_CMD_STATUS;
+  hdr->len = sizeof(*evt);
 
-    evt = net_buf_add(buf, sizeof(*evt));
-    evt->ncmd = 1U;
-    evt->opcode = sys_cpu_to_le16(opcode);
-    evt->status = status;
+  evt         = net_buf_add(buf, sizeof(*evt));
+  evt->ncmd   = 1U;
+  evt->opcode = sys_cpu_to_le16(opcode);
+  evt->status = status;
 
-    bt_recv_prio(buf);
+  bt_recv_prio(buf);
 }
 
-static u8_t generate_keys(void)
-{
+static u8_t generate_keys(void) {
 #if !defined(CONFIG_BT_USE_DEBUG_KEYS)
-    do {
-        int rc;
+  do {
+    int rc;
 
-        rc = uECC_make_key(ecc.pk, ecc.private_key, &curve_secp256r1);
-        if (rc == TC_CRYPTO_FAIL) {
-            BT_ERR("Failed to create ECC public/private pair");
-            return BT_HCI_ERR_UNSPECIFIED;
-        }
+    rc = uECC_make_key(ecc.pk, ecc.private_key, &curve_secp256r1);
+    if (rc == TC_CRYPTO_FAIL) {
+      BT_ERR("Failed to create ECC public/private pair");
+      return BT_HCI_ERR_UNSPECIFIED;
+    }
 
-        /* make sure generated key isn't debug key */
-    } while (memcmp(ecc.private_key, debug_private_key, 32) == 0);
+    /* make sure generated key isn't debug key */
+  } while (memcmp(ecc.private_key, debug_private_key, 32) == 0);
 #else
-    sys_memcpy_swap(&ecc.pk, debug_public_key, 32);
-    sys_memcpy_swap(&ecc.pk[32], &debug_public_key[32], 32);
-    sys_memcpy_swap(ecc.private_key, debug_private_key, 32);
+  sys_memcpy_swap(&ecc.pk, debug_public_key, 32);
+  sys_memcpy_swap(&ecc.pk[32], &debug_public_key[32], 32);
+  sys_memcpy_swap(ecc.private_key, debug_private_key, 32);
 #endif
-    return 0;
+  return 0;
 }
 
-static void emulate_le_p256_public_key_cmd(void)
-{
-    struct bt_hci_evt_le_p256_public_key_complete *evt;
-    struct bt_hci_evt_le_meta_event *meta;
-    struct bt_hci_evt_hdr *hdr;
-    struct net_buf *buf;
-    u8_t status;
+static void emulate_le_p256_public_key_cmd(void) {
+  struct bt_hci_evt_le_p256_public_key_complete *evt;
+  struct bt_hci_evt_le_meta_event               *meta;
+  struct bt_hci_evt_hdr                         *hdr;
+  struct net_buf                                *buf;
+  u8_t                                           status;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    status = generate_keys();
+  status = generate_keys();
 
-    buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
+  buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
 
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->evt = BT_HCI_EVT_LE_META_EVENT;
-    hdr->len = sizeof(*meta) + sizeof(*evt);
+  hdr      = net_buf_add(buf, sizeof(*hdr));
+  hdr->evt = BT_HCI_EVT_LE_META_EVENT;
+  hdr->len = sizeof(*meta) + sizeof(*evt);
 
-    meta = net_buf_add(buf, sizeof(*meta));
-    meta->subevent = BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE;
+  meta           = net_buf_add(buf, sizeof(*meta));
+  meta->subevent = BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE;
 
-    evt = net_buf_add(buf, sizeof(*evt));
-    evt->status = status;
+  evt         = net_buf_add(buf, sizeof(*evt));
+  evt->status = status;
 
-    if (status) {
-        (void)memset(evt->key, 0, sizeof(evt->key));
-    } else {
-        /* Convert X and Y coordinates from big-endian (provided
-		 * by crypto API) to little endian HCI.
-		 */
-        sys_memcpy_swap(evt->key, ecc.pk, 32);
-        sys_memcpy_swap(&evt->key[32], &ecc.pk[32], 32);
-    }
+  if (status) {
+    (void)memset(evt->key, 0, sizeof(evt->key));
+  } else {
+    /* Convert X and Y coordinates from big-endian (provided
+     * by crypto API) to little endian HCI.
+     */
+    sys_memcpy_swap(evt->key, ecc.pk, 32);
+    sys_memcpy_swap(&evt->key[32], &ecc.pk[32], 32);
+  }
 
-    atomic_clear_bit(flags, PENDING_PUB_KEY);
+  atomic_clear_bit(flags, PENDING_PUB_KEY);
 
-    bt_recv(buf);
+  bt_recv(buf);
 }
 
-static void emulate_le_generate_dhkey(void)
-{
-    struct bt_hci_evt_le_generate_dhkey_complete *evt;
-    struct bt_hci_evt_le_meta_event *meta;
-    struct bt_hci_evt_hdr *hdr;
-    struct net_buf *buf;
-    int ret;
-
-    ret = uECC_valid_public_key(ecc.pk, &curve_secp256r1);
-    if (ret < 0) {
-        BT_ERR("public key is not valid (ret %d)", ret);
-        ret = TC_CRYPTO_FAIL;
-    } else {
-        ret = uECC_shared_secret(ecc.pk, ecc.private_key, ecc.dhkey,
-                                 &curve_secp256r1);
-    }
-
-    buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
-
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->evt = BT_HCI_EVT_LE_META_EVENT;
-    hdr->len = sizeof(*meta) + sizeof(*evt);
-
-    meta = net_buf_add(buf, sizeof(*meta));
-    meta->subevent = BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE;
-
-    evt = net_buf_add(buf, sizeof(*evt));
-
-    if (ret == TC_CRYPTO_FAIL) {
-        evt->status = BT_HCI_ERR_UNSPECIFIED;
-        (void)memset(evt->dhkey, 0, sizeof(evt->dhkey));
-    } else {
-        evt->status = 0U;
-        /* Convert from big-endian (provided by crypto API) to
-		 * little-endian HCI.
-		 */
-        sys_memcpy_swap(evt->dhkey, ecc.dhkey, sizeof(ecc.dhkey));
-    }
-
-    atomic_clear_bit(flags, PENDING_DHKEY);
-
-    bt_recv(buf);
+static void emulate_le_generate_dhkey(void) {
+  struct bt_hci_evt_le_generate_dhkey_complete *evt;
+  struct bt_hci_evt_le_meta_event              *meta;
+  struct bt_hci_evt_hdr                        *hdr;
+  struct net_buf                               *buf;
+  int                                           ret;
+
+  ret = uECC_valid_public_key(ecc.pk, &curve_secp256r1);
+  if (ret < 0) {
+    BT_ERR("public key is not valid (ret %d)", ret);
+    ret = TC_CRYPTO_FAIL;
+  } else {
+    ret = uECC_shared_secret(ecc.pk, ecc.private_key, ecc.dhkey, &curve_secp256r1);
+  }
+
+  buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
+
+  hdr      = net_buf_add(buf, sizeof(*hdr));
+  hdr->evt = BT_HCI_EVT_LE_META_EVENT;
+  hdr->len = sizeof(*meta) + sizeof(*evt);
+
+  meta           = net_buf_add(buf, sizeof(*meta));
+  meta->subevent = BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE;
+
+  evt = net_buf_add(buf, sizeof(*evt));
+
+  if (ret == TC_CRYPTO_FAIL) {
+    evt->status = BT_HCI_ERR_UNSPECIFIED;
+    (void)memset(evt->dhkey, 0, sizeof(evt->dhkey));
+  } else {
+    evt->status = 0U;
+    /* Convert from big-endian (provided by crypto API) to
+     * little-endian HCI.
+     */
+    sys_memcpy_swap(evt->dhkey, ecc.dhkey, sizeof(ecc.dhkey));
+  }
+
+  atomic_clear_bit(flags, PENDING_DHKEY);
+
+  bt_recv(buf);
 }
 
 #if defined(BFLB_BLE)
@@ -212,129 +199,117 @@ static void ecc_thread(void *p1)
 static void ecc_thread(void *p1, void *p2, void *p3)
 #endif
 {
-    while (true) {
-        k_sem_take(&cmd_sem, K_FOREVER);
-
-        if (atomic_test_bit(flags, PENDING_PUB_KEY)) {
-            emulate_le_p256_public_key_cmd();
-        } else if (atomic_test_bit(flags, PENDING_DHKEY)) {
-            emulate_le_generate_dhkey();
-        } else {
-            __ASSERT(0, "Unhandled ECC command");
-        }
+  while (true) {
+    k_sem_take(&cmd_sem, K_FOREVER);
+
+    if (atomic_test_bit(flags, PENDING_PUB_KEY)) {
+      emulate_le_p256_public_key_cmd();
+    } else if (atomic_test_bit(flags, PENDING_DHKEY)) {
+      emulate_le_generate_dhkey();
+    } else {
+      __ASSERT(0, "Unhandled ECC command");
+    }
 #if !defined(BFLB_BLE)
-        STACK_ANALYZE("ecc stack", ecc_thread_stack);
+    STACK_ANALYZE("ecc stack", ecc_thread_stack);
 #endif
-    }
+  }
 }
 
-static void clear_ecc_events(struct net_buf *buf)
-{
-    struct bt_hci_cp_le_set_event_mask *cmd;
+static void clear_ecc_events(struct net_buf *buf) {
+  struct bt_hci_cp_le_set_event_mask *cmd;
 
-    cmd = (void *)(buf->data + sizeof(struct bt_hci_cmd_hdr));
+  cmd = (void *)(buf->data + sizeof(struct bt_hci_cmd_hdr));
 
-    /*
-	 * don't enable controller ECC events as those will be generated from
-	 * emulation code
-	 */
-    cmd->events[0] &= ~0x80; /* LE Read Local P-256 PKey Compl */
-    cmd->events[1] &= ~0x01; /* LE Generate DHKey Compl Event */
+  /*
+   * don't enable controller ECC events as those will be generated from
+   * emulation code
+   */
+  cmd->events[0] &= ~0x80; /* LE Read Local P-256 PKey Compl */
+  cmd->events[1] &= ~0x01; /* LE Generate DHKey Compl Event */
 }
 
-static void le_gen_dhkey(struct net_buf *buf)
-{
-    struct bt_hci_cp_le_generate_dhkey *cmd;
-    u8_t status;
-
-    if (atomic_test_bit(flags, PENDING_PUB_KEY)) {
-        status = BT_HCI_ERR_CMD_DISALLOWED;
-        goto send_status;
-    }
-
-    if (buf->len < sizeof(struct bt_hci_cp_le_generate_dhkey)) {
-        status = BT_HCI_ERR_INVALID_PARAM;
-        goto send_status;
-    }
-
-    if (atomic_test_and_set_bit(flags, PENDING_DHKEY)) {
-        status = BT_HCI_ERR_CMD_DISALLOWED;
-        goto send_status;
-    }
-
-    cmd = (void *)buf->data;
-    /* Convert X and Y coordinates from little-endian HCI to
-	 * big-endian (expected by the crypto API).
-	 */
-    sys_memcpy_swap(ecc.pk, cmd->key, 32);
-    sys_memcpy_swap(&ecc.pk[32], &cmd->key[32], 32);
-    k_sem_give(&cmd_sem);
-    status = BT_HCI_ERR_SUCCESS;
+static void le_gen_dhkey(struct net_buf *buf) {
+  struct bt_hci_cp_le_generate_dhkey *cmd;
+  u8_t                                status;
+
+  if (atomic_test_bit(flags, PENDING_PUB_KEY)) {
+    status = BT_HCI_ERR_CMD_DISALLOWED;
+    goto send_status;
+  }
+
+  if (buf->len < sizeof(struct bt_hci_cp_le_generate_dhkey)) {
+    status = BT_HCI_ERR_INVALID_PARAM;
+    goto send_status;
+  }
+
+  if (atomic_test_and_set_bit(flags, PENDING_DHKEY)) {
+    status = BT_HCI_ERR_CMD_DISALLOWED;
+    goto send_status;
+  }
+
+  cmd = (void *)buf->data;
+  /* Convert X and Y coordinates from little-endian HCI to
+   * big-endian (expected by the crypto API).
+   */
+  sys_memcpy_swap(ecc.pk, cmd->key, 32);
+  sys_memcpy_swap(&ecc.pk[32], &cmd->key[32], 32);
+  k_sem_give(&cmd_sem);
+  status = BT_HCI_ERR_SUCCESS;
 
 send_status:
-    net_buf_unref(buf);
-    send_cmd_status(BT_HCI_OP_LE_GENERATE_DHKEY, status);
+  net_buf_unref(buf);
+  send_cmd_status(BT_HCI_OP_LE_GENERATE_DHKEY, status);
 }
 
-static void le_p256_pub_key(struct net_buf *buf)
-{
-    u8_t status;
+static void le_p256_pub_key(struct net_buf *buf) {
+  u8_t status;
 
-    net_buf_unref(buf);
+  net_buf_unref(buf);
 
-    if (atomic_test_bit(flags, PENDING_DHKEY)) {
-        status = BT_HCI_ERR_CMD_DISALLOWED;
-    } else if (atomic_test_and_set_bit(flags, PENDING_PUB_KEY)) {
-        status = BT_HCI_ERR_CMD_DISALLOWED;
-    } else {
-        k_sem_give(&cmd_sem);
-        status = BT_HCI_ERR_SUCCESS;
-    }
+  if (atomic_test_bit(flags, PENDING_DHKEY)) {
+    status = BT_HCI_ERR_CMD_DISALLOWED;
+  } else if (atomic_test_and_set_bit(flags, PENDING_PUB_KEY)) {
+    status = BT_HCI_ERR_CMD_DISALLOWED;
+  } else {
+    k_sem_give(&cmd_sem);
+    status = BT_HCI_ERR_SUCCESS;
+  }
 
-    send_cmd_status(BT_HCI_OP_LE_P256_PUBLIC_KEY, status);
+  send_cmd_status(BT_HCI_OP_LE_P256_PUBLIC_KEY, status);
 }
 
-int bt_hci_ecc_send(struct net_buf *buf)
-{
-    if (bt_buf_get_type(buf) == BT_BUF_CMD) {
-        struct bt_hci_cmd_hdr *chdr = (void *)buf->data;
-
-        switch (sys_le16_to_cpu(chdr->opcode)) {
-            case BT_HCI_OP_LE_P256_PUBLIC_KEY:
-                net_buf_pull(buf, sizeof(*chdr));
-                le_p256_pub_key(buf);
-                return 0;
-            case BT_HCI_OP_LE_GENERATE_DHKEY:
-                net_buf_pull(buf, sizeof(*chdr));
-                le_gen_dhkey(buf);
-                return 0;
-            case BT_HCI_OP_LE_SET_EVENT_MASK:
-                clear_ecc_events(buf);
-                break;
-            default:
-                break;
-        }
+int bt_hci_ecc_send(struct net_buf *buf) {
+  if (bt_buf_get_type(buf) == BT_BUF_CMD) {
+    struct bt_hci_cmd_hdr *chdr = (void *)buf->data;
+
+    switch (sys_le16_to_cpu(chdr->opcode)) {
+    case BT_HCI_OP_LE_P256_PUBLIC_KEY:
+      net_buf_pull(buf, sizeof(*chdr));
+      le_p256_pub_key(buf);
+      return 0;
+    case BT_HCI_OP_LE_GENERATE_DHKEY:
+      net_buf_pull(buf, sizeof(*chdr));
+      le_gen_dhkey(buf);
+      return 0;
+    case BT_HCI_OP_LE_SET_EVENT_MASK:
+      clear_ecc_events(buf);
+      break;
+    default:
+      break;
     }
+  }
 
-    return bt_dev.drv->send(buf);
+  return bt_dev.drv->send(buf);
 }
 
-int default_CSPRNG(u8_t *dst, unsigned int len)
-{
-    return !bt_rand(dst, len);
-}
+int default_CSPRNG(u8_t *dst, unsigned int len) { return !bt_rand(dst, len); }
 
-void bt_hci_ecc_init(void)
-{
+void bt_hci_ecc_init(void) {
 #if defined(BFLB_BLE)
-    k_sem_init(&cmd_sem, 0, 1);
-    k_thread_create(&ecc_thread_data, "ecc_thread",
-                    CONFIG_BT_HCI_ECC_STACK_SIZE, ecc_thread,
-                    CONFIG_BT_WORK_QUEUE_PRIO);
+  k_sem_init(&cmd_sem, 0, 1);
+  k_thread_create(&ecc_thread_data, "ecc_thread", CONFIG_BT_HCI_ECC_STACK_SIZE, ecc_thread, CONFIG_BT_WORK_QUEUE_PRIO);
 #else
-    k_thread_create(&ecc_thread_data, ecc_thread_stack,
-                    K_THREAD_STACK_SIZEOF(ecc_thread_stack), ecc_thread,
-                    NULL, NULL, NULL, K_PRIO_PREEMPT(10), 0, K_NO_WAIT);
-    k_thread_name_set(&ecc_thread_data, "BT ECC");
+  k_thread_create(&ecc_thread_data, ecc_thread_stack, K_THREAD_STACK_SIZEOF(ecc_thread_stack), ecc_thread, NULL, NULL, NULL, K_PRIO_PREEMPT(10), 0, K_NO_WAIT);
+  k_thread_name_set(&ecc_thread_data, "BT ECC");
 #endif
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c
index a8c715a12..645ed2c81 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/hfp_hf.c
@@ -5,12 +5,12 @@
  *
  * SPDX-License-Identifier: Apache-2.0
  */
-#include 
-#include 
 #include 
 #include 
-#include 
+#include 
 #include 
+#include 
+#include 
 
 #include 
 
@@ -18,25 +18,24 @@
 #define LOG_MODULE_NAME bt_hfp_hf
 #include "log.h"
 
-#include 
 #include 
+#include 
 #include 
 
-#include "hci_core.h"
+#include "at.h"
 #include "conn_internal.h"
+#include "hci_core.h"
+#include "hfp_internal.h"
 #include "l2cap_internal.h"
 #include "rfcomm_internal.h"
-#include "at.h"
-#include "hfp_internal.h"
 
 #define MAX_IND_STR_LEN 17
 
 struct bt_hfp_hf_cb *bt_hf;
-bool hfp_codec_msbc = 0;
+bool                 hfp_codec_msbc = 0;
 
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
-NET_BUF_POOL_FIXED_DEFINE(hf_pool, CONFIG_BT_MAX_CONN + 1,
-                          BT_RFCOMM_BUF_SIZE(BT_HF_CLIENT_MAX_PDU), NULL);
+NET_BUF_POOL_FIXED_DEFINE(hf_pool, CONFIG_BT_MAX_CONN + 1, BT_RFCOMM_BUF_SIZE(BT_HF_CLIENT_MAX_PDU), NULL);
 #else
 struct net_buf_pool hf_pool;
 #endif
@@ -45,54 +44,28 @@ static struct bt_hfp_hf bt_hfp_hf_pool[CONFIG_BT_MAX_CONN];
 
 static struct bt_sdp_attribute hfp_attrs[] = {
     BT_SDP_NEW_SERVICE,
-    BT_SDP_LIST(
-        BT_SDP_ATTR_SVCLASS_ID_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 10),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_HANDSFREE_SVCLASS) }, ) },
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_GENERIC_AUDIO_SVCLASS) }, ) }, )),
-    BT_SDP_LIST(
-        BT_SDP_ATTR_PROTO_DESC_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 12),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_PROTO_L2CAP) }, ) },
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 5),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_PROTO_RFCOMM) },
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UINT8),
-                    BT_SDP_ARRAY_16(BT_RFCOMM_CHAN_HFP_HF) }) }, )),
-    BT_SDP_LIST(
-        BT_SDP_ATTR_PROFILE_DESC_LIST,
-        BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 8),
-        BT_SDP_DATA_ELEM_LIST(
-            { BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6),
-              BT_SDP_DATA_ELEM_LIST(
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
-                    BT_SDP_ARRAY_16(BT_SDP_HANDSFREE_SVCLASS) },
-                  { BT_SDP_TYPE_SIZE(BT_SDP_UINT16),
-                    BT_SDP_ARRAY_16(0x0107) }, ) }, )),
+    BT_SDP_LIST(BT_SDP_ATTR_SVCLASS_ID_LIST, BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 10),
+                BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_HANDSFREE_SVCLASS)}, )},
+                                      {BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_GENERIC_AUDIO_SVCLASS)}, )}, )),
+    BT_SDP_LIST(BT_SDP_ATTR_PROTO_DESC_LIST, BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 12),
+                BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_PROTO_L2CAP)}, )},
+                                      {BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 5), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_PROTO_RFCOMM)},
+                                                                                                   {BT_SDP_TYPE_SIZE(BT_SDP_UINT8), BT_SDP_ARRAY_16(BT_RFCOMM_CHAN_HFP_HF)})}, )),
+    BT_SDP_LIST(BT_SDP_ATTR_PROFILE_DESC_LIST, BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 8),
+                BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 6), BT_SDP_DATA_ELEM_LIST({BT_SDP_TYPE_SIZE(BT_SDP_UUID16), BT_SDP_ARRAY_16(BT_SDP_HANDSFREE_SVCLASS)},
+                                                                                                   {BT_SDP_TYPE_SIZE(BT_SDP_UINT16), BT_SDP_ARRAY_16(0x0107)}, )}, )),
     BT_SDP_SERVICE_NAME("hands-free"),
     /*
-	"SupportedFeatures" attribute bit mapping for the HF
-	bit 0: EC and/or NR function
-	bit 1: Call waiting or three-way calling
-	bit 2: CLI presentation capability
-	bit 3: Voice recognition activation
-	bit 4: Remote volume control
-	bit 5: Wide band speech
-	bit 6: Enhanced Voice Recognition Status
-	bit 7: Voice Recognition Text
-	*/
+        "SupportedFeatures" attribute bit mapping for the HF
+        bit 0: EC and/or NR function
+        bit 1: Call waiting or three-way calling
+        bit 2: CLI presentation capability
+        bit 3: Voice recognition activation
+        bit 4: Remote volume control
+        bit 5: Wide band speech
+        bit 6: Enhanced Voice Recognition Status
+        bit 7: Voice Recognition Text
+        */
     BT_SDP_SUPPORTED_FEATURES(0x0035),
 };
 
@@ -100,788 +73,708 @@ static struct bt_sdp_record hfp_rec = BT_SDP_RECORD(hfp_attrs);
 
 /* The order should follow the enum hfp_hf_ag_indicators */
 static const struct {
-    char *name;
-    uint32_t min;
-    uint32_t max;
+  char    *name;
+  uint32_t min;
+  uint32_t max;
 } ag_ind[] = {
-    { "service", 0, 1 },   /* HF_SERVICE_IND */
-    { "call", 0, 1 },      /* HF_CALL_IND */
-    { "callsetup", 0, 3 }, /* HF_CALL_SETUP_IND */
-    { "callheld", 0, 2 },  /* HF_CALL_HELD_IND */
-    { "signal", 0, 5 },    /* HF_SINGNAL_IND */
-    { "roam", 0, 1 },      /* HF_ROAM_IND */
-    { "battchg", 0, 5 }    /* HF_BATTERY_IND */
+    {  "service", 0, 1}, /* HF_SERVICE_IND */
+    {     "call", 0, 1}, /* HF_CALL_IND */
+    {"callsetup", 0, 3}, /* HF_CALL_SETUP_IND */
+    { "callheld", 0, 2}, /* HF_CALL_HELD_IND */
+    {   "signal", 0, 5}, /* HF_SINGNAL_IND */
+    {     "roam", 0, 1}, /* HF_ROAM_IND */
+    {  "battchg", 0, 5}  /* HF_BATTERY_IND */
 };
 
-static void connected(struct bt_conn *conn)
-{
-    BT_DBG("HFP HF Connected!");
-}
+static void connected(struct bt_conn *conn) { BT_DBG("HFP HF Connected!"); }
 
-static void disconnected(struct bt_conn *conn)
-{
-    BT_DBG("HFP HF Disconnected!");
-}
+static void disconnected(struct bt_conn *conn) { BT_DBG("HFP HF Disconnected!"); }
 
-static void service(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Service indicator value: %u", value);
-}
+static void service(struct bt_conn *conn, uint32_t value) { BT_DBG("Service indicator value: %u", value); }
 
-static void call(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Call indicator value: %u", value);
-}
+static void call(struct bt_conn *conn, uint32_t value) { BT_DBG("Call indicator value: %u", value); }
 
-static void call_setup(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Call Setup indicator value: %u", value);
-}
+static void call_setup(struct bt_conn *conn, uint32_t value) { BT_DBG("Call Setup indicator value: %u", value); }
 
-static void call_held(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Call Held indicator value: %u", value);
-}
+static void call_held(struct bt_conn *conn, uint32_t value) { BT_DBG("Call Held indicator value: %u", value); }
 
-static void signal(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Signal indicator value: %u", value);
-}
+static void signal(struct bt_conn *conn, uint32_t value) { BT_DBG("Signal indicator value: %u", value); }
 
-static void roam(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Roaming indicator value: %u", value);
-}
+static void roam(struct bt_conn *conn, uint32_t value) { BT_DBG("Roaming indicator value: %u", value); }
 
-static void battery(struct bt_conn *conn, uint32_t value)
-{
-    BT_DBG("Battery indicator value: %u", value);
-}
+static void battery(struct bt_conn *conn, uint32_t value) { BT_DBG("Battery indicator value: %u", value); }
 
-static void ring_cb(struct bt_conn *conn)
-{
-    BT_DBG("Incoming Call...");
-}
+static void ring_cb(struct bt_conn *conn) { BT_DBG("Incoming Call..."); }
 
 static struct bt_hfp_hf_cb hf_cb = {
-    .connected = connected,
-    .disconnected = disconnected,
-    .service = service,
-    .call = call,
-    .call_setup = call_setup,
-    .call_held = call_held,
-    .signal = signal,
-    .roam = roam,
-    .battery = battery,
+    .connected       = connected,
+    .disconnected    = disconnected,
+    .service         = service,
+    .call            = call,
+    .call_setup      = call_setup,
+    .call_held       = call_held,
+    .signal          = signal,
+    .roam            = roam,
+    .battery         = battery,
     .ring_indication = ring_cb,
 };
 
-void hf_slc_error(struct at_client *hf_at)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int err;
+void hf_slc_error(struct at_client *hf_at) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               err;
 
-    BT_ERR("SLC error: disconnecting");
-    err = bt_rfcomm_dlc_disconnect(&hf->rfcomm_dlc);
-    if (err) {
-        BT_ERR("Rfcomm: Unable to disconnect :%d", -err);
-    }
+  BT_ERR("SLC error: disconnecting");
+  err = bt_rfcomm_dlc_disconnect(&hf->rfcomm_dlc);
+  if (err) {
+    BT_ERR("Rfcomm: Unable to disconnect :%d", -err);
+  }
 }
 
-int hfp_hf_send_cmd(struct bt_hfp_hf *hf, at_resp_cb_t resp,
-                    at_finish_cb_t finish, const char *format, ...)
-{
-    struct net_buf *buf;
-    va_list vargs;
-    int ret;
+int hfp_hf_send_cmd(struct bt_hfp_hf *hf, at_resp_cb_t resp, at_finish_cb_t finish, const char *format, ...) {
+  struct net_buf *buf;
+  va_list         vargs;
+  int             ret;
 
-    /* register the callbacks */
-    at_register(&hf->at, resp, finish);
+  /* register the callbacks */
+  at_register(&hf->at, resp, finish);
 
-    buf = bt_rfcomm_create_pdu(&hf_pool);
-    if (!buf) {
-        BT_ERR("No Buffers!");
-        return -ENOMEM;
-    }
+  buf = bt_rfcomm_create_pdu(&hf_pool);
+  if (!buf) {
+    BT_ERR("No Buffers!");
+    return -ENOMEM;
+  }
 
-    va_start(vargs, format);
-    ret = vsnprintf((char *)buf->data, (net_buf_tailroom(buf) - 1), format, vargs);
-    if (ret < 0) {
-        BT_ERR("Unable to format variable arguments");
-        return ret;
-    }
-    va_end(vargs);
+  va_start(vargs, format);
+  ret = vsnprintf((char *)buf->data, (net_buf_tailroom(buf) - 1), format, vargs);
+  if (ret < 0) {
+    BT_ERR("Unable to format variable arguments");
+    return ret;
+  }
+  va_end(vargs);
 
-    net_buf_add(buf, ret);
-    net_buf_add_u8(buf, '\r');
+  net_buf_add(buf, ret);
+  net_buf_add_u8(buf, '\r');
 
-    ret = bt_rfcomm_dlc_send(&hf->rfcomm_dlc, buf);
-    if (ret < 0) {
-        BT_ERR("Rfcomm send error :(%d)", ret);
-        return ret;
-    }
+  ret = bt_rfcomm_dlc_send(&hf->rfcomm_dlc, buf);
+  if (ret < 0) {
+    BT_ERR("Rfcomm send error :(%d)", ret);
+    return ret;
+  }
 
-    return 0;
+  return 0;
 }
 
-int brsf_handle(struct at_client *hf_at)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    uint32_t val;
-    int ret;
+int brsf_handle(struct at_client *hf_at) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  uint32_t          val;
+  int               ret;
 
-    ret = at_get_number(hf_at, &val);
-    if (ret < 0) {
-        BT_ERR("Error getting value");
-        return ret;
-    }
+  ret = at_get_number(hf_at, &val);
+  if (ret < 0) {
+    BT_ERR("Error getting value");
+    return ret;
+  }
 
-    hf->ag_features = val;
+  hf->ag_features = val;
 
-    return 0;
+  return 0;
 }
 
-int brsf_resp(struct at_client *hf_at, struct net_buf *buf)
-{
-    int err;
+int brsf_resp(struct at_client *hf_at, struct net_buf *buf) {
+  int err;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    err = at_parse_cmd_input(hf_at, buf, "BRSF", brsf_handle,
-                             AT_CMD_TYPE_NORMAL);
-    if (err < 0) {
-        /* Returning negative value is avoided before SLC connection
-		 * established.
-		 */
-        BT_ERR("Error parsing CMD input");
-        hf_slc_error(hf_at);
-    }
+  err = at_parse_cmd_input(hf_at, buf, "BRSF", brsf_handle, AT_CMD_TYPE_NORMAL);
+  if (err < 0) {
+    /* Returning negative value is avoided before SLC connection
+     * established.
+     */
+    BT_ERR("Error parsing CMD input");
+    hf_slc_error(hf_at);
+  }
 
-    return 0;
+  return 0;
 }
 
-static void cind_handle_values(struct at_client *hf_at, uint32_t index,
-                               char *name, uint32_t min, uint32_t max)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int i;
-
-    BT_DBG("index: %u, name: %s, min: %u, max:%u", index, name, min, max);
+static void cind_handle_values(struct at_client *hf_at, uint32_t index, char *name, uint32_t min, uint32_t max) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               i;
 
-    for (i = 0; i < ARRAY_SIZE(ag_ind); i++) {
-        if (strcmp(name, ag_ind[i].name) != 0) {
-            continue;
-        }
-        if (min != ag_ind[i].min || max != ag_ind[i].max) {
-            BT_ERR("%s indicator min/max value not matching", name);
-        }
+  BT_DBG("index: %u, name: %s, min: %u, max:%u", index, name, min, max);
 
-        hf->ind_table[index] = i;
-        break;
+  for (i = 0; i < ARRAY_SIZE(ag_ind); i++) {
+    if (strcmp(name, ag_ind[i].name) != 0) {
+      continue;
     }
-}
-
-int cind_handle(struct at_client *hf_at)
-{
-    uint32_t index = 0U;
-
-    /* Parsing Example: CIND: ("call",(0,1)) etc.. */
-    while (at_has_next_list(hf_at)) {
-        char name[MAX_IND_STR_LEN];
-        uint32_t min, max;
-
-        if (at_open_list(hf_at) < 0) {
-            BT_ERR("Could not get open list");
-            goto error;
-        }
-
-        if (at_list_get_string(hf_at, name, sizeof(name)) < 0) {
-            BT_ERR("Could not get string");
-            goto error;
-        }
-
-        if (at_open_list(hf_at) < 0) {
-            BT_ERR("Could not get open list");
-            goto error;
-        }
-
-        if (at_list_get_range(hf_at, &min, &max) < 0) {
-            BT_ERR("Could not get range");
-            goto error;
-        }
-
-        if (at_close_list(hf_at) < 0) {
-            BT_ERR("Could not get close list");
-            goto error;
-        }
-
-        if (at_close_list(hf_at) < 0) {
-            BT_ERR("Could not get close list");
-            goto error;
-        }
-
-        cind_handle_values(hf_at, index, name, min, max);
-        index++;
+    if (min != ag_ind[i].min || max != ag_ind[i].max) {
+      BT_ERR("%s indicator min/max value not matching", name);
     }
 
-    return 0;
-error:
-    BT_ERR("Error on CIND response");
-    hf_slc_error(hf_at);
-    return -EINVAL;
+    hf->ind_table[index] = i;
+    break;
+  }
 }
 
-int cind_resp(struct at_client *hf_at, struct net_buf *buf)
-{
-    int err;
+int cind_handle(struct at_client *hf_at) {
+  uint32_t index = 0U;
 
-    err = at_parse_cmd_input(hf_at, buf, "CIND", cind_handle,
-                             AT_CMD_TYPE_NORMAL);
-    if (err < 0) {
-        BT_ERR("Error parsing CMD input");
-        hf_slc_error(hf_at);
-    }
+  /* Parsing Example: CIND: ("call",(0,1)) etc.. */
+  while (at_has_next_list(hf_at)) {
+    char     name[MAX_IND_STR_LEN];
+    uint32_t min, max;
 
-    return 0;
-}
-
-void ag_indicator_handle_values(struct at_client *hf_at, uint32_t index,
-                                uint32_t value)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
+    if (at_open_list(hf_at) < 0) {
+      BT_ERR("Could not get open list");
+      goto error;
+    }
 
-    BT_DBG("Index :%u, Value :%u", index, value);
+    if (at_list_get_string(hf_at, name, sizeof(name)) < 0) {
+      BT_ERR("Could not get string");
+      goto error;
+    }
 
-    if (index >= ARRAY_SIZE(ag_ind)) {
-        BT_ERR("Max only %lu indicators are supported",
-               ARRAY_SIZE(ag_ind));
-        return;
+    if (at_open_list(hf_at) < 0) {
+      BT_ERR("Could not get open list");
+      goto error;
     }
 
-    if (value > ag_ind[hf->ind_table[index]].max ||
-        value < ag_ind[hf->ind_table[index]].min) {
-        BT_ERR("Indicators out of range - value: %u", value);
-        return;
+    if (at_list_get_range(hf_at, &min, &max) < 0) {
+      BT_ERR("Could not get range");
+      goto error;
     }
 
-    switch (hf->ind_table[index]) {
-        case HF_SERVICE_IND:
-            if (bt_hf->service) {
-                bt_hf->service(conn, value);
-            }
-            break;
-        case HF_CALL_IND:
-            if (bt_hf->call) {
-                bt_hf->call(conn, value);
-            }
-            break;
-        case HF_CALL_SETUP_IND:
-            if (bt_hf->call_setup) {
-                bt_hf->call_setup(conn, value);
-            }
-            break;
-        case HF_CALL_HELD_IND:
-            if (bt_hf->call_held) {
-                bt_hf->call_held(conn, value);
-            }
-            break;
-        case HF_SINGNAL_IND:
-            if (bt_hf->signal) {
-                bt_hf->signal(conn, value);
-            }
-            break;
-        case HF_ROAM_IND:
-            if (bt_hf->roam) {
-                bt_hf->roam(conn, value);
-            }
-            break;
-        case HF_BATTERY_IND:
-            if (bt_hf->battery) {
-                bt_hf->battery(conn, value);
-            }
-            break;
-        default:
-            BT_ERR("Unknown AG indicator");
-            break;
+    if (at_close_list(hf_at) < 0) {
+      BT_ERR("Could not get close list");
+      goto error;
     }
-}
 
-int cind_status_handle(struct at_client *hf_at)
-{
-    uint32_t index = 0U;
+    if (at_close_list(hf_at) < 0) {
+      BT_ERR("Could not get close list");
+      goto error;
+    }
 
-    while (at_has_next_list(hf_at)) {
-        uint32_t value;
-        int ret;
+    cind_handle_values(hf_at, index, name, min, max);
+    index++;
+  }
 
-        ret = at_get_number(hf_at, &value);
-        if (ret < 0) {
-            BT_ERR("could not get the value");
-            return ret;
-        }
+  return 0;
+error:
+  BT_ERR("Error on CIND response");
+  hf_slc_error(hf_at);
+  return -EINVAL;
+}
 
-        ag_indicator_handle_values(hf_at, index, value);
+int cind_resp(struct at_client *hf_at, struct net_buf *buf) {
+  int err;
 
-        index++;
-    }
+  err = at_parse_cmd_input(hf_at, buf, "CIND", cind_handle, AT_CMD_TYPE_NORMAL);
+  if (err < 0) {
+    BT_ERR("Error parsing CMD input");
+    hf_slc_error(hf_at);
+  }
 
-    return 0;
+  return 0;
 }
 
-int cind_status_resp(struct at_client *hf_at, struct net_buf *buf)
-{
-    int err;
+void ag_indicator_handle_values(struct at_client *hf_at, uint32_t index, uint32_t value) {
+  struct bt_hfp_hf *hf   = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  struct bt_conn   *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
 
-    err = at_parse_cmd_input(hf_at, buf, "CIND", cind_status_handle,
-                             AT_CMD_TYPE_NORMAL);
-    if (err < 0) {
-        BT_ERR("Error parsing CMD input");
-        hf_slc_error(hf_at);
-    }
+  BT_DBG("Index :%u, Value :%u", index, value);
 
-    return 0;
-}
+  if (index >= ARRAY_SIZE(ag_ind)) {
+    BT_ERR("Max only %lu indicators are supported", ARRAY_SIZE(ag_ind));
+    return;
+  }
 
-int ciev_handle(struct at_client *hf_at)
-{
-    uint32_t index, value;
-    int ret;
+  if (value > ag_ind[hf->ind_table[index]].max || value < ag_ind[hf->ind_table[index]].min) {
+    BT_ERR("Indicators out of range - value: %u", value);
+    return;
+  }
 
-    ret = at_get_number(hf_at, &index);
-    if (ret < 0) {
-        BT_ERR("could not get the Index");
-        return ret;
+  switch (hf->ind_table[index]) {
+  case HF_SERVICE_IND:
+    if (bt_hf->service) {
+      bt_hf->service(conn, value);
+    }
+    break;
+  case HF_CALL_IND:
+    if (bt_hf->call) {
+      bt_hf->call(conn, value);
+    }
+    break;
+  case HF_CALL_SETUP_IND:
+    if (bt_hf->call_setup) {
+      bt_hf->call_setup(conn, value);
+    }
+    break;
+  case HF_CALL_HELD_IND:
+    if (bt_hf->call_held) {
+      bt_hf->call_held(conn, value);
     }
-    /* The first element of the list shall have 1 */
-    if (!index) {
-        BT_ERR("Invalid index value '0'");
-        return 0;
+    break;
+  case HF_SINGNAL_IND:
+    if (bt_hf->signal) {
+      bt_hf->signal(conn, value);
     }
+    break;
+  case HF_ROAM_IND:
+    if (bt_hf->roam) {
+      bt_hf->roam(conn, value);
+    }
+    break;
+  case HF_BATTERY_IND:
+    if (bt_hf->battery) {
+      bt_hf->battery(conn, value);
+    }
+    break;
+  default:
+    BT_ERR("Unknown AG indicator");
+    break;
+  }
+}
+
+int cind_status_handle(struct at_client *hf_at) {
+  uint32_t index = 0U;
+
+  while (at_has_next_list(hf_at)) {
+    uint32_t value;
+    int      ret;
 
     ret = at_get_number(hf_at, &value);
     if (ret < 0) {
-        BT_ERR("could not get the value");
-        return ret;
+      BT_ERR("could not get the value");
+      return ret;
     }
 
-    ag_indicator_handle_values(hf_at, (index - 1), value);
+    ag_indicator_handle_values(hf_at, index, value);
 
-    return 0;
+    index++;
+  }
+
+  return 0;
 }
 
-int ring_handle(struct at_client *hf_at)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
+int cind_status_resp(struct at_client *hf_at, struct net_buf *buf) {
+  int err;
 
-    if (bt_hf->ring_indication) {
-        bt_hf->ring_indication(conn);
-    }
+  err = at_parse_cmd_input(hf_at, buf, "CIND", cind_status_handle, AT_CMD_TYPE_NORMAL);
+  if (err < 0) {
+    BT_ERR("Error parsing CMD input");
+    hf_slc_error(hf_at);
+  }
 
+  return 0;
+}
+
+int ciev_handle(struct at_client *hf_at) {
+  uint32_t index, value;
+  int      ret;
+
+  ret = at_get_number(hf_at, &index);
+  if (ret < 0) {
+    BT_ERR("could not get the Index");
+    return ret;
+  }
+  /* The first element of the list shall have 1 */
+  if (!index) {
+    BT_ERR("Invalid index value '0'");
     return 0;
+  }
+
+  ret = at_get_number(hf_at, &value);
+  if (ret < 0) {
+    BT_ERR("could not get the value");
+    return ret;
+  }
+
+  ag_indicator_handle_values(hf_at, (index - 1), value);
+
+  return 0;
 }
 
-int bcs_handle(struct at_client *hf_at)
-{
-    uint32_t value;
-    int ret;
+int ring_handle(struct at_client *hf_at) {
+  struct bt_hfp_hf *hf   = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  struct bt_conn   *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
 
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  if (bt_hf->ring_indication) {
+    bt_hf->ring_indication(conn);
+  }
 
-    ret = at_get_number(hf_at, &value);
-    if (ret < 0) {
-        BT_ERR("could not get the value");
-        return ret;
+  return 0;
+}
+
+int bcs_handle(struct at_client *hf_at) {
+  uint32_t value;
+  int      ret;
+
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+
+  ret = at_get_number(hf_at, &value);
+  if (ret < 0) {
+    BT_ERR("could not get the value");
+    return ret;
+  }
+  if (value == 1) {
+    if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+BCS=1") < 0) {
+      BT_ERR("Error Sending AT+BCS=1");
     }
-    if (value == 1) {
-        if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+BCS=1") < 0) {
-            BT_ERR("Error Sending AT+BCS=1");
-        }
-    } else if (value == 2) {
-        if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+BCS=2") < 0) {
-            BT_ERR("Error Sending AT+BCS=2");
-        } else {
-            hfp_codec_msbc = 1;
-        }
+  } else if (value == 2) {
+    if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+BCS=2") < 0) {
+      BT_ERR("Error Sending AT+BCS=2");
     } else {
-        BT_WARN("Invail BCS value !");
+      hfp_codec_msbc = 1;
     }
+  } else {
+    BT_WARN("Invail BCS value !");
+  }
 
-    return 0;
+  return 0;
 }
 
 static const struct unsolicited {
-    const char *cmd;
-    enum at_cmd_type type;
-    int (*func)(struct at_client *hf_at);
+  const char      *cmd;
+  enum at_cmd_type type;
+  int (*func)(struct at_client *hf_at);
 } handlers[] = {
-    { "CIEV", AT_CMD_TYPE_UNSOLICITED, ciev_handle },
-    { "RING", AT_CMD_TYPE_OTHER, ring_handle },
-    { "BCS", AT_CMD_TYPE_UNSOLICITED, bcs_handle }
+    {"CIEV", AT_CMD_TYPE_UNSOLICITED, ciev_handle},
+    {"RING",       AT_CMD_TYPE_OTHER, ring_handle},
+    { "BCS", AT_CMD_TYPE_UNSOLICITED,  bcs_handle}
 };
 
-static const struct unsolicited *hfp_hf_unsol_lookup(struct at_client *hf_at)
-{
-    int i;
+static const struct unsolicited *hfp_hf_unsol_lookup(struct at_client *hf_at) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(handlers); i++) {
-        if (!strncmp(hf_at->buf, handlers[i].cmd,
-                     strlen(handlers[i].cmd))) {
-            return &handlers[i];
-        }
+  for (i = 0; i < ARRAY_SIZE(handlers); i++) {
+    if (!strncmp(hf_at->buf, handlers[i].cmd, strlen(handlers[i].cmd))) {
+      return &handlers[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-int unsolicited_cb(struct at_client *hf_at, struct net_buf *buf)
-{
-    const struct unsolicited *handler;
+int unsolicited_cb(struct at_client *hf_at, struct net_buf *buf) {
+  const struct unsolicited *handler;
 
-    handler = hfp_hf_unsol_lookup(hf_at);
-    if (!handler) {
-        BT_ERR("Unhandled unsolicited response");
-        return -ENOMSG;
-    }
+  handler = hfp_hf_unsol_lookup(hf_at);
+  if (!handler) {
+    BT_ERR("Unhandled unsolicited response");
+    return -ENOMSG;
+  }
 
-    if (!at_parse_cmd_input(hf_at, buf, handler->cmd, handler->func,
-                            handler->type)) {
-        return 0;
-    }
+  if (!at_parse_cmd_input(hf_at, buf, handler->cmd, handler->func, handler->type)) {
+    return 0;
+  }
 
-    return -ENOMSG;
+  return -ENOMSG;
 }
 
-int cmd_complete(struct at_client *hf_at, enum at_result result,
-                 enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
-    struct bt_hfp_hf_cmd_complete cmd = { 0 };
-
-    BT_DBG("");
-
-    switch (result) {
-        case AT_RESULT_OK:
-            cmd.type = HFP_HF_CMD_OK;
-            break;
-        case AT_RESULT_ERROR:
-            cmd.type = HFP_HF_CMD_ERROR;
-            break;
-        case AT_RESULT_CME_ERROR:
-            cmd.type = HFP_HF_CMD_CME_ERROR;
-            cmd.cme = cme_err;
-            break;
-        default:
-            BT_ERR("Unknown error code");
-            cmd.type = HFP_HF_CMD_UNKNOWN_ERROR;
-            break;
-    }
+int cmd_complete(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf             *hf   = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  struct bt_conn               *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
+  struct bt_hfp_hf_cmd_complete cmd  = {0};
 
-    if (bt_hf->cmd_complete_cb) {
-        bt_hf->cmd_complete_cb(conn, &cmd);
-    }
+  BT_DBG("");
 
-    return 0;
+  switch (result) {
+  case AT_RESULT_OK:
+    cmd.type = HFP_HF_CMD_OK;
+    break;
+  case AT_RESULT_ERROR:
+    cmd.type = HFP_HF_CMD_ERROR;
+    break;
+  case AT_RESULT_CME_ERROR:
+    cmd.type = HFP_HF_CMD_CME_ERROR;
+    cmd.cme  = cme_err;
+    break;
+  default:
+    BT_ERR("Unknown error code");
+    cmd.type = HFP_HF_CMD_UNKNOWN_ERROR;
+    break;
+  }
+
+  if (bt_hf->cmd_complete_cb) {
+    bt_hf->cmd_complete_cb(conn, &cmd);
+  }
+
+  return 0;
 }
 
-int cmee_finish(struct at_client *hf_at, enum at_result result,
-                enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+int cmee_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
 
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        return -EINVAL;
-    }
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    return -EINVAL;
+  }
 
-    if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+NREC=0") < 0) {
-        BT_ERR("Error Sending AT+NREC");
-    }
+  if (hfp_hf_send_cmd(hf, NULL, NULL, "AT+NREC=0") < 0) {
+    BT_ERR("Error Sending AT+NREC");
+  }
 
-    return 0;
+  return 0;
 }
 
-static void slc_completed(struct at_client *hf_at)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    struct bt_conn *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
+static void slc_completed(struct at_client *hf_at) {
+  struct bt_hfp_hf *hf   = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  struct bt_conn   *conn = hf->rfcomm_dlc.session->br_chan.chan.conn;
 
-    if (bt_hf->connected) {
-        bt_hf->connected(conn);
-    }
+  if (bt_hf->connected) {
+    bt_hf->connected(conn);
+  }
 
-    if (hfp_hf_send_cmd(hf, NULL, cmee_finish, "AT+CMEE=1") < 0) {
-        BT_ERR("Error Sending AT+CMEE");
-    }
+  if (hfp_hf_send_cmd(hf, NULL, cmee_finish, "AT+CMEE=1") < 0) {
+    BT_ERR("Error Sending AT+CMEE");
+  }
 }
 
-int cmer_finish(struct at_client *hf_at, enum at_result result,
-                enum at_cme cme_err)
-{
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        hf_slc_error(hf_at);
-        return -EINVAL;
-    }
+int cmer_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    hf_slc_error(hf_at);
+    return -EINVAL;
+  }
 
-    slc_completed(hf_at);
+  slc_completed(hf_at);
 
-    return 0;
+  return 0;
 }
 
-int cind_status_finish(struct at_client *hf_at, enum at_result result,
-                       enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int err;
+int cind_status_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               err;
 
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        hf_slc_error(hf_at);
-        return -EINVAL;
-    }
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    hf_slc_error(hf_at);
+    return -EINVAL;
+  }
 
-    at_register_unsolicited(hf_at, unsolicited_cb);
-    err = hfp_hf_send_cmd(hf, NULL, cmer_finish, "AT+CMER=3,0,0,1");
-    if (err < 0) {
-        hf_slc_error(hf_at);
-        return err;
-    }
+  at_register_unsolicited(hf_at, unsolicited_cb);
+  err = hfp_hf_send_cmd(hf, NULL, cmer_finish, "AT+CMER=3,0,0,1");
+  if (err < 0) {
+    hf_slc_error(hf_at);
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int cind_finish(struct at_client *hf_at, enum at_result result,
-                enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int err;
+int cind_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               err;
 
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        hf_slc_error(hf_at);
-        return -EINVAL;
-    }
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    hf_slc_error(hf_at);
+    return -EINVAL;
+  }
 
-    err = hfp_hf_send_cmd(hf, cind_status_resp, cind_status_finish,
-                          "AT+CIND?");
-    if (err < 0) {
-        hf_slc_error(hf_at);
-        return err;
-    }
+  err = hfp_hf_send_cmd(hf, cind_status_resp, cind_status_finish, "AT+CIND?");
+  if (err < 0) {
+    hf_slc_error(hf_at);
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int bac_finish(struct at_client *hf_at, enum at_result result,
-               enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int err;
+int bac_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               err;
 
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        hf_slc_error(hf_at);
-        return -EINVAL;
-    }
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    hf_slc_error(hf_at);
+    return -EINVAL;
+  }
 
-    err = hfp_hf_send_cmd(hf, cind_resp, cind_finish, "AT+CIND=?");
-    if (err < 0) {
-        hf_slc_error(hf_at);
-        return err;
-    }
+  err = hfp_hf_send_cmd(hf, cind_resp, cind_finish, "AT+CIND=?");
+  if (err < 0) {
+    hf_slc_error(hf_at);
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int brsf_finish(struct at_client *hf_at, enum at_result result,
-                enum at_cme cme_err)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
-    int err;
+int brsf_finish(struct at_client *hf_at, enum at_result result, enum at_cme cme_err) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(hf_at, struct bt_hfp_hf, at);
+  int               err;
 
-    if (result != AT_RESULT_OK) {
-        BT_ERR("SLC Connection ERROR in response");
-        hf_slc_error(hf_at);
-        return -EINVAL;
-    }
+  if (result != AT_RESULT_OK) {
+    BT_ERR("SLC Connection ERROR in response");
+    hf_slc_error(hf_at);
+    return -EINVAL;
+  }
 
-    err = hfp_hf_send_cmd(hf, NULL, bac_finish, "AT+BAC=1,2");
-    if (err < 0) {
-        hf_slc_error(hf_at);
-        return err;
-    }
+  err = hfp_hf_send_cmd(hf, NULL, bac_finish, "AT+BAC=1,2");
+  if (err < 0) {
+    hf_slc_error(hf_at);
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-int hf_slc_establish(struct bt_hfp_hf *hf)
-{
-    int err;
+int hf_slc_establish(struct bt_hfp_hf *hf) {
+  int err;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    err = hfp_hf_send_cmd(hf, brsf_resp, brsf_finish, "AT+BRSF=%u",
-                          hf->hf_features);
-    if (err < 0) {
-        hf_slc_error(&hf->at);
-        return err;
-    }
+  err = hfp_hf_send_cmd(hf, brsf_resp, brsf_finish, "AT+BRSF=%u", hf->hf_features);
+  if (err < 0) {
+    hf_slc_error(&hf->at);
+    return err;
+  }
 
-    return 0;
+  return 0;
 }
 
-static struct bt_hfp_hf *bt_hfp_hf_lookup_bt_conn(struct bt_conn *conn)
-{
-    int i;
+static struct bt_hfp_hf *bt_hfp_hf_lookup_bt_conn(struct bt_conn *conn) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(bt_hfp_hf_pool); i++) {
-        struct bt_hfp_hf *hf = &bt_hfp_hf_pool[i];
+  for (i = 0; i < ARRAY_SIZE(bt_hfp_hf_pool); i++) {
+    struct bt_hfp_hf *hf = &bt_hfp_hf_pool[i];
 
-        if (hf->rfcomm_dlc.session->br_chan.chan.conn == conn) {
-            return hf;
-        }
+    if (hf->rfcomm_dlc.session->br_chan.chan.conn == conn) {
+      return hf;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-int bt_hfp_hf_send_cmd(struct bt_conn *conn, enum bt_hfp_hf_at_cmd cmd)
-{
-    struct bt_hfp_hf *hf;
-    int err;
+int bt_hfp_hf_send_cmd(struct bt_conn *conn, enum bt_hfp_hf_at_cmd cmd) {
+  struct bt_hfp_hf *hf;
+  int               err;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    if (!conn) {
-        BT_ERR("Invalid connection");
-        return -ENOTCONN;
-    }
+  if (!conn) {
+    BT_ERR("Invalid connection");
+    return -ENOTCONN;
+  }
 
-    hf = bt_hfp_hf_lookup_bt_conn(conn);
-    if (!hf) {
-        BT_ERR("No HF connection found");
-        return -ENOTCONN;
-    }
+  hf = bt_hfp_hf_lookup_bt_conn(conn);
+  if (!hf) {
+    BT_ERR("No HF connection found");
+    return -ENOTCONN;
+  }
 
-    switch (cmd) {
-        case BT_HFP_HF_ATA:
-            err = hfp_hf_send_cmd(hf, NULL, cmd_complete, "ATA");
-            if (err < 0) {
-                BT_ERR("Failed ATA");
-                return err;
-            }
-            break;
-        case BT_HFP_HF_AT_CHUP:
-            err = hfp_hf_send_cmd(hf, NULL, cmd_complete, "AT+CHUP");
-            if (err < 0) {
-                BT_ERR("Failed AT+CHUP");
-                return err;
-            }
-            break;
-        default:
-            BT_ERR("Invalid AT Command");
-            return -EINVAL;
+  switch (cmd) {
+  case BT_HFP_HF_ATA:
+    err = hfp_hf_send_cmd(hf, NULL, cmd_complete, "ATA");
+    if (err < 0) {
+      BT_ERR("Failed ATA");
+      return err;
+    }
+    break;
+  case BT_HFP_HF_AT_CHUP:
+    err = hfp_hf_send_cmd(hf, NULL, cmd_complete, "AT+CHUP");
+    if (err < 0) {
+      BT_ERR("Failed AT+CHUP");
+      return err;
     }
+    break;
+  default:
+    BT_ERR("Invalid AT Command");
+    return -EINVAL;
+  }
 
-    return 0;
+  return 0;
 }
 
-static void hfp_hf_connected(struct bt_rfcomm_dlc *dlc)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(dlc, struct bt_hfp_hf, rfcomm_dlc);
+static void hfp_hf_connected(struct bt_rfcomm_dlc *dlc) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(dlc, struct bt_hfp_hf, rfcomm_dlc);
 
-    BT_DBG("hf connected");
+  BT_DBG("hf connected");
 
-    BT_ASSERT(hf);
-    hf_slc_establish(hf);
+  BT_ASSERT(hf);
+  hf_slc_establish(hf);
 }
 
-static void hfp_hf_disconnected(struct bt_rfcomm_dlc *dlc)
-{
-    struct bt_conn *conn = dlc->session->br_chan.chan.conn;
+static void hfp_hf_disconnected(struct bt_rfcomm_dlc *dlc) {
+  struct bt_conn *conn = dlc->session->br_chan.chan.conn;
 
-    BT_DBG("hf disconnected!");
-    if (bt_hf->disconnected) {
-        bt_hf->disconnected(conn);
-    }
+  BT_DBG("hf disconnected!");
+  if (bt_hf->disconnected) {
+    bt_hf->disconnected(conn);
+  }
 }
 
-static void hfp_hf_recv(struct bt_rfcomm_dlc *dlc, struct net_buf *buf)
-{
-    struct bt_hfp_hf *hf = CONTAINER_OF(dlc, struct bt_hfp_hf, rfcomm_dlc);
+static void hfp_hf_recv(struct bt_rfcomm_dlc *dlc, struct net_buf *buf) {
+  struct bt_hfp_hf *hf = CONTAINER_OF(dlc, struct bt_hfp_hf, rfcomm_dlc);
 
-    if (at_parse_input(&hf->at, buf) < 0) {
-        BT_ERR("Parsing failed");
-    }
+  if (at_parse_input(&hf->at, buf) < 0) {
+    BT_ERR("Parsing failed");
+  }
 }
 
-static int bt_hfp_hf_accept(struct bt_conn *conn, struct bt_rfcomm_dlc **dlc)
-{
-    int i;
-    static struct bt_rfcomm_dlc_ops ops = {
-        .connected = hfp_hf_connected,
-        .disconnected = hfp_hf_disconnected,
-        .recv = hfp_hf_recv,
-    };
-
-    BT_DBG("conn %p", conn);
+static int bt_hfp_hf_accept(struct bt_conn *conn, struct bt_rfcomm_dlc **dlc) {
+  int                             i;
+  static struct bt_rfcomm_dlc_ops ops = {
+      .connected    = hfp_hf_connected,
+      .disconnected = hfp_hf_disconnected,
+      .recv         = hfp_hf_recv,
+  };
 
-    for (i = 0; i < ARRAY_SIZE(bt_hfp_hf_pool); i++) {
-        struct bt_hfp_hf *hf = &bt_hfp_hf_pool[i];
-        int j;
+  BT_DBG("conn %p", conn);
 
-        if (hf->rfcomm_dlc.session) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(bt_hfp_hf_pool); i++) {
+    struct bt_hfp_hf *hf = &bt_hfp_hf_pool[i];
+    int               j;
 
-        hf->at.buf = hf->hf_buffer;
-        hf->at.buf_max_len = HF_MAX_BUF_LEN;
+    if (hf->rfcomm_dlc.session) {
+      continue;
+    }
 
-        hf->rfcomm_dlc.ops = &ops;
-        hf->rfcomm_dlc.mtu = BT_HFP_MAX_MTU;
+    hf->at.buf         = hf->hf_buffer;
+    hf->at.buf_max_len = HF_MAX_BUF_LEN;
 
-        *dlc = &hf->rfcomm_dlc;
+    hf->rfcomm_dlc.ops = &ops;
+    hf->rfcomm_dlc.mtu = BT_HFP_MAX_MTU;
 
-        /* Set the supported features*/
-        hf->hf_features = BT_HFP_HF_SUPPORTED_FEATURES;
+    *dlc = &hf->rfcomm_dlc;
 
-        for (j = 0; j < HF_MAX_AG_INDICATORS; j++) {
-            hf->ind_table[j] = -1;
-        }
+    /* Set the supported features*/
+    hf->hf_features = BT_HFP_HF_SUPPORTED_FEATURES;
 
-        return 0;
+    for (j = 0; j < HF_MAX_AG_INDICATORS; j++) {
+      hf->ind_table[j] = -1;
     }
 
-    BT_ERR("Unable to establish HF connection (%p)", conn);
+    return 0;
+  }
+
+  BT_ERR("Unable to establish HF connection (%p)", conn);
 
-    return -ENOMEM;
+  return -ENOMEM;
 }
 
-int bt_hfp_hf_init(void)
-{
-    int err;
+int bt_hfp_hf_init(void) {
+  int err;
 
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_init(&hf_pool, CONFIG_BT_MAX_CONN + 1, BT_RFCOMM_BUF_SIZE(BT_HF_CLIENT_MAX_PDU), NULL);
+  net_buf_init(&hf_pool, CONFIG_BT_MAX_CONN + 1, BT_RFCOMM_BUF_SIZE(BT_HF_CLIENT_MAX_PDU), NULL);
 #endif
 
-    bt_hf = &hf_cb;
+  bt_hf = &hf_cb;
 
-    static struct bt_rfcomm_server chan = {
-        .channel = BT_RFCOMM_CHAN_HFP_HF,
-        .accept = bt_hfp_hf_accept,
-    };
+  static struct bt_rfcomm_server chan = {
+      .channel = BT_RFCOMM_CHAN_HFP_HF,
+      .accept  = bt_hfp_hf_accept,
+  };
 
-    bt_rfcomm_server_register(&chan);
+  bt_rfcomm_server_register(&chan);
 
-    /* Register SDP record */
-    err = bt_sdp_register_service(&hfp_rec);
-    if (err < 0) {
-        BT_ERR("HFP regist sdp record failed");
-    }
-    BT_DBG("HFP initialized successfully.");
-    return err;
+  /* Register SDP record */
+  err = bt_sdp_register_service(&hfp_rec);
+  if (err < 0) {
+    BT_ERR("HFP regist sdp record failed");
+  }
+  BT_DBG("HFP initialized successfully.");
+  return err;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys.c
index 1988d7aa0..7f1b9864d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys.c
@@ -6,11 +6,11 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
 #include 
 #include 
+#include 
+#include 
+#include 
 
 #include 
 #include 
@@ -19,12 +19,12 @@
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_KEYS)
 #include "log.h"
 
-#include "rpa.h"
 #include "gatt_internal.h"
 #include "hci_core.h"
-#include "smp.h"
-#include "settings.h"
 #include "keys.h"
+#include "rpa.h"
+#include "settings.h"
+#include "smp.h"
 #if defined(BFLB_BLE)
 #if defined(CONFIG_BT_SETTINGS)
 #include "easyflash.h"
@@ -36,419 +36,375 @@ static struct bt_keys key_pool[CONFIG_BT_MAX_PAIRED];
 #define BT_KEYS_STORAGE_LEN_COMPAT (BT_KEYS_STORAGE_LEN - sizeof(uint32_t))
 
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-static u32_t aging_counter_val;
+static u32_t           aging_counter_val;
 static struct bt_keys *last_keys_updated;
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
 
-struct bt_keys *bt_keys_get_addr(u8_t id, const bt_addr_le_t *addr)
-{
-    struct bt_keys *keys;
-    int i;
-    size_t first_free_slot = ARRAY_SIZE(key_pool);
+struct bt_keys *bt_keys_get_addr(u8_t id, const bt_addr_le_t *addr) {
+  struct bt_keys *keys;
+  int             i;
+  size_t          first_free_slot = ARRAY_SIZE(key_pool);
 
-    BT_DBG("%s", bt_addr_le_str(addr));
+  BT_DBG("%s", bt_addr_le_str(addr));
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        keys = &key_pool[i];
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    keys = &key_pool[i];
 
-        if (keys->id == id && !bt_addr_le_cmp(&keys->addr, addr)) {
-            return keys;
-        }
+    if (keys->id == id && !bt_addr_le_cmp(&keys->addr, addr)) {
+      return keys;
+    }
 
-        if (first_free_slot == ARRAY_SIZE(key_pool) &&
-            (!bt_addr_le_cmp(&keys->addr, BT_ADDR_LE_ANY) ||
-             !keys->enc_size)) {
-            first_free_slot = i;
-        }
+    if (first_free_slot == ARRAY_SIZE(key_pool) && (!bt_addr_le_cmp(&keys->addr, BT_ADDR_LE_ANY) || !keys->enc_size)) {
+      first_free_slot = i;
     }
+  }
 
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-    if (first_free_slot == ARRAY_SIZE(key_pool)) {
-        struct bt_keys *oldest = &key_pool[0];
+  if (first_free_slot == ARRAY_SIZE(key_pool)) {
+    struct bt_keys *oldest = &key_pool[0];
 
-        for (i = 1; i < ARRAY_SIZE(key_pool); i++) {
-            struct bt_keys *current = &key_pool[i];
+    for (i = 1; i < ARRAY_SIZE(key_pool); i++) {
+      struct bt_keys *current = &key_pool[i];
 
-            if (current->aging_counter < oldest->aging_counter) {
-                oldest = current;
-            }
-        }
+      if (current->aging_counter < oldest->aging_counter) {
+        oldest = current;
+      }
+    }
 
-        bt_unpair(oldest->id, &oldest->addr);
-        if (!bt_addr_le_cmp(&oldest->addr, BT_ADDR_LE_ANY)) {
-            first_free_slot = oldest - &key_pool[0];
-        }
+    bt_unpair(oldest->id, &oldest->addr);
+    if (!bt_addr_le_cmp(&oldest->addr, BT_ADDR_LE_ANY)) {
+      first_free_slot = oldest - &key_pool[0];
     }
+  }
 
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
-    if (first_free_slot < ARRAY_SIZE(key_pool)) {
-        keys = &key_pool[first_free_slot];
-        keys->id = id;
-        bt_addr_le_copy(&keys->addr, addr);
+  if (first_free_slot < ARRAY_SIZE(key_pool)) {
+    keys     = &key_pool[first_free_slot];
+    keys->id = id;
+    bt_addr_le_copy(&keys->addr, addr);
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-        keys->aging_counter = ++aging_counter_val;
-        last_keys_updated = keys;
+    keys->aging_counter = ++aging_counter_val;
+    last_keys_updated   = keys;
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
-        BT_DBG("created %p for %s", keys, bt_addr_le_str(addr));
-        return keys;
-    }
+    BT_DBG("created %p for %s", keys, bt_addr_le_str(addr));
+    return keys;
+  }
 
-    BT_DBG("unable to create keys for %s", bt_addr_le_str(addr));
+  BT_DBG("unable to create keys for %s", bt_addr_le_str(addr));
 
-    return NULL;
+  return NULL;
 }
 
-void bt_foreach_bond(u8_t id, void (*func)(const struct bt_bond_info *info, void *user_data),
-                     void *user_data)
-{
-    int i;
+void bt_foreach_bond(u8_t id, void (*func)(const struct bt_bond_info *info, void *user_data), void *user_data) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        struct bt_keys *keys = &key_pool[i];
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    struct bt_keys *keys = &key_pool[i];
 
-        if (keys->keys && keys->id == id) {
-            struct bt_bond_info info;
+    if (keys->keys && keys->id == id) {
+      struct bt_bond_info info;
 
-            bt_addr_le_copy(&info.addr, &keys->addr);
-            func(&info, user_data);
-        }
+      bt_addr_le_copy(&info.addr, &keys->addr);
+      func(&info, user_data);
     }
+  }
 }
 
-void bt_keys_foreach(int type, void (*func)(struct bt_keys *keys, void *data),
-                     void *data)
-{
-    int i;
+void bt_keys_foreach(int type, void (*func)(struct bt_keys *keys, void *data), void *data) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        if ((key_pool[i].keys & type)) {
-            func(&key_pool[i], data);
-        }
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    if ((key_pool[i].keys & type)) {
+      func(&key_pool[i], data);
     }
+  }
 }
 
-struct bt_keys *bt_keys_find(int type, u8_t id, const bt_addr_le_t *addr)
-{
-    int i;
+struct bt_keys *bt_keys_find(int type, u8_t id, const bt_addr_le_t *addr) {
+  int i;
 
-    BT_DBG("type %d %s", type, bt_addr_le_str(addr));
+  BT_DBG("type %d %s", type, bt_addr_le_str(addr));
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        if ((key_pool[i].keys & type) && key_pool[i].id == id &&
-            !bt_addr_le_cmp(&key_pool[i].addr, addr)) {
-            return &key_pool[i];
-        }
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    if ((key_pool[i].keys & type) && key_pool[i].id == id && !bt_addr_le_cmp(&key_pool[i].addr, addr)) {
+      return &key_pool[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_keys *bt_keys_get_type(int type, u8_t id, const bt_addr_le_t *addr)
-{
-    struct bt_keys *keys;
+struct bt_keys *bt_keys_get_type(int type, u8_t id, const bt_addr_le_t *addr) {
+  struct bt_keys *keys;
 
-    BT_DBG("type %d %s", type, bt_addr_le_str(addr));
+  BT_DBG("type %d %s", type, bt_addr_le_str(addr));
 
-    keys = bt_keys_find(type, id, addr);
-    if (keys) {
-        return keys;
-    }
+  keys = bt_keys_find(type, id, addr);
+  if (keys) {
+    return keys;
+  }
 
-    keys = bt_keys_get_addr(id, addr);
-    if (!keys) {
-        return NULL;
-    }
+  keys = bt_keys_get_addr(id, addr);
+  if (!keys) {
+    return NULL;
+  }
 
-    bt_keys_add_type(keys, type);
+  bt_keys_add_type(keys, type);
 
-    return keys;
+  return keys;
 }
 
-struct bt_keys *bt_keys_find_irk(u8_t id, const bt_addr_le_t *addr)
-{
-    int i;
+struct bt_keys *bt_keys_find_irk(u8_t id, const bt_addr_le_t *addr) {
+  int i;
+
+  BT_DBG("%s", bt_addr_le_str(addr));
 
-    BT_DBG("%s", bt_addr_le_str(addr));
+  if (!bt_addr_le_is_rpa(addr)) {
+    return NULL;
+  }
 
-    if (!bt_addr_le_is_rpa(addr)) {
-        return NULL;
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    if (!(key_pool[i].keys & BT_KEYS_IRK)) {
+      continue;
     }
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        if (!(key_pool[i].keys & BT_KEYS_IRK)) {
-            continue;
-        }
-
-        if (key_pool[i].id == id &&
-            !bt_addr_cmp(&addr->a, &key_pool[i].irk.rpa)) {
-            BT_DBG("cached RPA %s for %s",
-                   bt_addr_str(&key_pool[i].irk.rpa),
-                   bt_addr_le_str(&key_pool[i].addr));
-            return &key_pool[i];
-        }
+    if (key_pool[i].id == id && !bt_addr_cmp(&addr->a, &key_pool[i].irk.rpa)) {
+      BT_DBG("cached RPA %s for %s", bt_addr_str(&key_pool[i].irk.rpa), bt_addr_le_str(&key_pool[i].addr));
+      return &key_pool[i];
     }
+  }
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        if (!(key_pool[i].keys & BT_KEYS_IRK)) {
-            continue;
-        }
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    if (!(key_pool[i].keys & BT_KEYS_IRK)) {
+      continue;
+    }
 
-        if (key_pool[i].id != id) {
-            continue;
-        }
+    if (key_pool[i].id != id) {
+      continue;
+    }
 
-        if (bt_rpa_irk_matches(key_pool[i].irk.val, &addr->a)) {
-            BT_DBG("RPA %s matches %s",
-                   bt_addr_str(&key_pool[i].irk.rpa),
-                   bt_addr_le_str(&key_pool[i].addr));
+    if (bt_rpa_irk_matches(key_pool[i].irk.val, &addr->a)) {
+      BT_DBG("RPA %s matches %s", bt_addr_str(&key_pool[i].irk.rpa), bt_addr_le_str(&key_pool[i].addr));
 
-            bt_addr_copy(&key_pool[i].irk.rpa, &addr->a);
+      bt_addr_copy(&key_pool[i].irk.rpa, &addr->a);
 
-            return &key_pool[i];
-        }
+      return &key_pool[i];
     }
+  }
 
-    BT_DBG("No IRK for %s", bt_addr_le_str(addr));
+  BT_DBG("No IRK for %s", bt_addr_le_str(addr));
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_keys *bt_keys_find_addr(u8_t id, const bt_addr_le_t *addr)
-{
-    int i;
+struct bt_keys *bt_keys_find_addr(u8_t id, const bt_addr_le_t *addr) {
+  int i;
 
-    BT_DBG("%s", bt_addr_le_str(addr));
+  BT_DBG("%s", bt_addr_le_str(addr));
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        if (key_pool[i].id == id &&
-            !bt_addr_le_cmp(&key_pool[i].addr, addr)) {
-            return &key_pool[i];
-        }
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    if (key_pool[i].id == id && !bt_addr_le_cmp(&key_pool[i].addr, addr)) {
+      return &key_pool[i];
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
 #if defined(CONFIG_BLE_AT_CMD)
-bt_addr_le_t *bt_get_keys_address(u8_t id)
-{
-    bt_addr_le_t addr;
+bt_addr_le_t *bt_get_keys_address(u8_t id) {
+  bt_addr_le_t addr;
 
-    memset(&addr, 0, sizeof(bt_addr_le_t));
-    if (id < ARRAY_SIZE(key_pool)) {
-        if (bt_addr_le_cmp(&key_pool[id].addr, &addr)) {
-            return &key_pool[id].addr;
-        }
+  memset(&addr, 0, sizeof(bt_addr_le_t));
+  if (id < ARRAY_SIZE(key_pool)) {
+    if (bt_addr_le_cmp(&key_pool[id].addr, &addr)) {
+      return &key_pool[id].addr;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 #endif
 
-void bt_keys_add_type(struct bt_keys *keys, int type)
-{
-    keys->keys |= type;
-}
+void bt_keys_add_type(struct bt_keys *keys, int type) { keys->keys |= type; }
 
-void bt_keys_clear(struct bt_keys *keys)
-{
+void bt_keys_clear(struct bt_keys *keys) {
 #if defined(BFLB_BLE)
-    if (keys->keys & BT_KEYS_IRK) {
-        bt_id_del(keys);
-    }
+  if (keys->keys & BT_KEYS_IRK) {
+    bt_id_del(keys);
+  }
 
-    memset(keys, 0, sizeof(*keys));
+  memset(keys, 0, sizeof(*keys));
 
 #if defined(CONFIG_BT_SETTINGS)
-    ef_del_env(NV_KEY_POOL);
+  ef_del_env(NV_KEY_POOL);
 #endif
 #else
-    BT_DBG("%s (keys 0x%04x)", bt_addr_le_str(&keys->addr), keys->keys);
+  BT_DBG("%s (keys 0x%04x)", bt_addr_le_str(&keys->addr), keys->keys);
 
-    if (keys->keys & BT_KEYS_IRK) {
-        bt_id_del(keys);
-    }
+  if (keys->keys & BT_KEYS_IRK) {
+    bt_id_del(keys);
+  }
 
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        char key[BT_SETTINGS_KEY_MAX];
-
-        /* Delete stored keys from flash */
-        if (keys->id) {
-            char id[4];
-
-            u8_to_dec(id, sizeof(id), keys->id);
-            bt_settings_encode_key(key, sizeof(key), "keys",
-                                   &keys->addr, id);
-        } else {
-            bt_settings_encode_key(key, sizeof(key), "keys",
-                                   &keys->addr, NULL);
-        }
-
-        BT_DBG("Deleting key %s", log_strdup(key));
-        settings_delete(key);
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    char key[BT_SETTINGS_KEY_MAX];
+
+    /* Delete stored keys from flash */
+    if (keys->id) {
+      char id[4];
+
+      u8_to_dec(id, sizeof(id), keys->id);
+      bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, id);
+    } else {
+      bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, NULL);
     }
 
-    (void)memset(keys, 0, sizeof(*keys));
+    BT_DBG("Deleting key %s", log_strdup(key));
+    settings_delete(key);
+  }
+
+  (void)memset(keys, 0, sizeof(*keys));
 #endif
 }
 
-static void keys_clear_id(struct bt_keys *keys, void *data)
-{
-    u8_t *id = data;
-
-    if (*id == keys->id) {
-        if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-            bt_gatt_clear(*id, &keys->addr);
-        }
+static void keys_clear_id(struct bt_keys *keys, void *data) {
+  u8_t *id = data;
 
-        bt_keys_clear(keys);
+  if (*id == keys->id) {
+    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+      bt_gatt_clear(*id, &keys->addr);
     }
-}
 
-void bt_keys_clear_all(u8_t id)
-{
-    bt_keys_foreach(BT_KEYS_ALL, keys_clear_id, &id);
+    bt_keys_clear(keys);
+  }
 }
 
+void bt_keys_clear_all(u8_t id) { bt_keys_foreach(BT_KEYS_ALL, keys_clear_id, &id); }
+
 #if defined(CONFIG_BT_SETTINGS)
-int bt_keys_store(struct bt_keys *keys)
-{
+int bt_keys_store(struct bt_keys *keys) {
 #if defined(BFLB_BLE)
-    int err;
-    err = bt_settings_set_bin(NV_KEY_POOL, (const u8_t *)&key_pool[0], sizeof(key_pool));
-    return err;
+  int err;
+  err = bt_settings_set_bin(NV_KEY_POOL, (const u8_t *)&key_pool[0], sizeof(key_pool));
+  return err;
 #else
-    char val[BT_SETTINGS_SIZE(BT_KEYS_STORAGE_LEN)];
-    char key[BT_SETTINGS_KEY_MAX];
-    char *str;
-    int err;
-
-    str = settings_str_from_bytes(keys->storage_start, BT_KEYS_STORAGE_LEN,
-                                  val, sizeof(val));
-    if (!str) {
-        BT_ERR("Unable to encode bt_keys as value");
-        return -EINVAL;
-    }
-
-    if (keys->id) {
-        char id[4];
-
-        u8_to_dec(id, sizeof(id), keys->id);
-        bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr,
-                               id);
-    } else {
-        bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr,
-                               NULL);
-    }
-
-    err = settings_save_one(key, keys->storage_start, BT_KEYS_STORAGE_LEN);
-    if (err) {
-        BT_ERR("Failed to save keys (err %d)", err);
-        return err;
-    }
+  char  val[BT_SETTINGS_SIZE(BT_KEYS_STORAGE_LEN)];
+  char  key[BT_SETTINGS_KEY_MAX];
+  char *str;
+  int   err;
+
+  str = settings_str_from_bytes(keys->storage_start, BT_KEYS_STORAGE_LEN, val, sizeof(val));
+  if (!str) {
+    BT_ERR("Unable to encode bt_keys as value");
+    return -EINVAL;
+  }
+
+  if (keys->id) {
+    char id[4];
+
+    u8_to_dec(id, sizeof(id), keys->id);
+    bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, id);
+  } else {
+    bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, NULL);
+  }
+
+  err = settings_save_one(key, keys->storage_start, BT_KEYS_STORAGE_LEN);
+  if (err) {
+    BT_ERR("Failed to save keys (err %d)", err);
+    return err;
+  }
 
-    BT_DBG("Stored keys for %s (%s)", bt_addr_le_str(&keys->addr),
-           log_strdup(key));
+  BT_DBG("Stored keys for %s (%s)", bt_addr_le_str(&keys->addr), log_strdup(key));
 
-    return 0;
-#endif //BFLB_BLE
+  return 0;
+#endif // BFLB_BLE
 }
 
 #if !defined(BFLB_BLE)
-static int keys_set(const char *name, size_t len_rd, settings_read_cb read_cb,
-                    void *cb_arg)
-{
-    struct bt_keys *keys;
-    bt_addr_le_t addr;
-    u8_t id;
-    size_t len;
-    int err;
-    char val[BT_KEYS_STORAGE_LEN];
-    const char *next;
-
-    if (!name) {
-        BT_ERR("Insufficient number of arguments");
-        return -EINVAL;
-    }
-
-    len = read_cb(cb_arg, val, sizeof(val));
-    if (len < 0) {
-        BT_ERR("Failed to read value (err %zu)", len);
-        return -EINVAL;
-    }
-
-    BT_DBG("name %s val %s", log_strdup(name),
-           (len) ? bt_hex(val, sizeof(val)) : "(null)");
-
-    err = bt_settings_decode_key(name, &addr);
-    if (err) {
-        BT_ERR("Unable to decode address %s", name);
-        return -EINVAL;
-    }
-
-    settings_name_next(name, &next);
-
-    if (!next) {
-        id = BT_ID_DEFAULT;
+static int keys_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) {
+  struct bt_keys *keys;
+  bt_addr_le_t    addr;
+  u8_t            id;
+  size_t          len;
+  int             err;
+  char            val[BT_KEYS_STORAGE_LEN];
+  const char     *next;
+
+  if (!name) {
+    BT_ERR("Insufficient number of arguments");
+    return -EINVAL;
+  }
+
+  len = read_cb(cb_arg, val, sizeof(val));
+  if (len < 0) {
+    BT_ERR("Failed to read value (err %zu)", len);
+    return -EINVAL;
+  }
+
+  BT_DBG("name %s val %s", log_strdup(name), (len) ? bt_hex(val, sizeof(val)) : "(null)");
+
+  err = bt_settings_decode_key(name, &addr);
+  if (err) {
+    BT_ERR("Unable to decode address %s", name);
+    return -EINVAL;
+  }
+
+  settings_name_next(name, &next);
+
+  if (!next) {
+    id = BT_ID_DEFAULT;
+  } else {
+    id = strtol(next, NULL, 10);
+  }
+
+  if (!len) {
+    keys = bt_keys_find(BT_KEYS_ALL, id, &addr);
+    if (keys) {
+      (void)memset(keys, 0, sizeof(*keys));
+      BT_DBG("Cleared keys for %s", bt_addr_le_str(&addr));
     } else {
-        id = strtol(next, NULL, 10);
-    }
-
-    if (!len) {
-        keys = bt_keys_find(BT_KEYS_ALL, id, &addr);
-        if (keys) {
-            (void)memset(keys, 0, sizeof(*keys));
-            BT_DBG("Cleared keys for %s", bt_addr_le_str(&addr));
-        } else {
-            BT_WARN("Unable to find deleted keys for %s",
-                    bt_addr_le_str(&addr));
-        }
-
-        return 0;
+      BT_WARN("Unable to find deleted keys for %s", bt_addr_le_str(&addr));
     }
 
-    keys = bt_keys_get_addr(id, &addr);
-    if (!keys) {
-        BT_ERR("Failed to allocate keys for %s", bt_addr_le_str(&addr));
-        return -ENOMEM;
-    }
-    if (len != BT_KEYS_STORAGE_LEN) {
-        do {
-            /* Load shorter structure for compatibility with old
-			 * records format with no counter.
-			 */
-            if (IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) &&
-                len == BT_KEYS_STORAGE_LEN_COMPAT) {
-                BT_WARN("Keys for %s have no aging counter",
-                        bt_addr_le_str(&addr));
-                memcpy(keys->storage_start, val, len);
-                continue;
-            }
-
-            BT_ERR("Invalid key length %zu != %zu", len,
-                   BT_KEYS_STORAGE_LEN);
-            bt_keys_clear(keys);
-
-            return -EINVAL;
-        } while (0);
-    } else {
+    return 0;
+  }
+
+  keys = bt_keys_get_addr(id, &addr);
+  if (!keys) {
+    BT_ERR("Failed to allocate keys for %s", bt_addr_le_str(&addr));
+    return -ENOMEM;
+  }
+  if (len != BT_KEYS_STORAGE_LEN) {
+    do {
+      /* Load shorter structure for compatibility with old
+       * records format with no counter.
+       */
+      if (IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) && len == BT_KEYS_STORAGE_LEN_COMPAT) {
+        BT_WARN("Keys for %s have no aging counter", bt_addr_le_str(&addr));
         memcpy(keys->storage_start, val, len);
-    }
+        continue;
+      }
+
+      BT_ERR("Invalid key length %zu != %zu", len, BT_KEYS_STORAGE_LEN);
+      bt_keys_clear(keys);
+
+      return -EINVAL;
+    } while (0);
+  } else {
+    memcpy(keys->storage_start, val, len);
+  }
 
-    BT_DBG("Successfully restored keys for %s", bt_addr_le_str(&addr));
+  BT_DBG("Successfully restored keys for %s", bt_addr_le_str(&addr));
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-    if (aging_counter_val < keys->aging_counter) {
-        aging_counter_val = keys->aging_counter;
-    }
+  if (aging_counter_val < keys->aging_counter) {
+    aging_counter_val = keys->aging_counter;
+  }
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
-    return 0;
+  return 0;
 }
 #endif //!(BFLB_BLE)
 
-static void id_add(struct bt_keys *keys, void *user_data)
-{
-    bt_id_add(keys);
-}
+static void id_add(struct bt_keys *keys, void *user_data) { bt_id_add(keys); }
 
 #if defined(BFLB_BLE)
 int keys_commit(void)
@@ -456,51 +412,46 @@ int keys_commit(void)
 static int keys_commit(void)
 #endif
 {
-    BT_DBG("");
+  BT_DBG("");
 
-    /* We do this in commit() rather than add() since add() may get
-	 * called multiple times for the same address, especially if
-	 * the keys were already removed.
-	 */
-    bt_keys_foreach(BT_KEYS_IRK, id_add, NULL);
+  /* We do this in commit() rather than add() since add() may get
+   * called multiple times for the same address, especially if
+   * the keys were already removed.
+   */
+  bt_keys_foreach(BT_KEYS_IRK, id_add, NULL);
 
-    return 0;
+  return 0;
 }
 
-//SETTINGS_STATIC_HANDLER_DEFINE(bt_keys, "bt/keys", NULL, keys_set, keys_commit,
+// SETTINGS_STATIC_HANDLER_DEFINE(bt_keys, "bt/keys", NULL, keys_set, keys_commit,
 //			       NULL);
 
 #if defined(BFLB_BLE)
-int bt_keys_load(void)
-{
-    return bt_settings_get_bin(NV_KEY_POOL, (u8_t *)&key_pool[0], sizeof(key_pool), NULL);
-}
+int bt_keys_load(void) { return bt_settings_get_bin(NV_KEY_POOL, (u8_t *)&key_pool[0], sizeof(key_pool), NULL); }
 #endif
 
 #endif /* CONFIG_BT_SETTINGS */
 
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-void bt_keys_update_usage(u8_t id, const bt_addr_le_t *addr)
-{
-    struct bt_keys *keys = bt_keys_find_addr(id, addr);
+void bt_keys_update_usage(u8_t id, const bt_addr_le_t *addr) {
+  struct bt_keys *keys = bt_keys_find_addr(id, addr);
 
-    if (!keys) {
-        return;
-    }
+  if (!keys) {
+    return;
+  }
 
-    if (last_keys_updated == keys) {
-        return;
-    }
+  if (last_keys_updated == keys) {
+    return;
+  }
 
-    keys->aging_counter = ++aging_counter_val;
-    last_keys_updated = keys;
+  keys->aging_counter = ++aging_counter_val;
+  last_keys_updated   = keys;
 
-    BT_DBG("Aging counter for %s is set to %u", bt_addr_le_str(addr),
-           keys->aging_counter);
+  BT_DBG("Aging counter for %s is set to %u", bt_addr_le_str(addr), keys->aging_counter);
 
-    if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) {
-        bt_keys_store(keys);
-    }
+  if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) {
+    bt_keys_store(keys);
+  }
 }
 
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys_br.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys_br.c
index f5cd4e19e..9949dea15 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys_br.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/keys_br.c
@@ -6,10 +6,10 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
 #include 
+#include 
 #include 
+#include 
 
 #include 
 #include 
@@ -21,45 +21,43 @@
 #include "log.h"
 
 #include "hci_core.h"
-#include "settings.h"
 #include "keys.h"
+#include "settings.h"
 
 static struct bt_keys_link_key key_pool[CONFIG_BT_MAX_PAIRED];
 
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-static uint32_t aging_counter_val;
+static uint32_t                 aging_counter_val;
 static struct bt_keys_link_key *last_keys_updated;
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
 
-struct bt_keys_link_key *bt_keys_find_link_key(const bt_addr_t *addr)
-{
-    struct bt_keys_link_key *key;
-    int i;
+struct bt_keys_link_key *bt_keys_find_link_key(const bt_addr_t *addr) {
+  struct bt_keys_link_key *key;
+  int                      i;
 
-    BT_DBG("%s", bt_addr_str(addr));
+  BT_DBG("%s", bt_addr_str(addr));
 
-    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-        key = &key_pool[i];
+  for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+    key = &key_pool[i];
 
-        if (!bt_addr_cmp(&key->addr, addr)) {
-            return key;
-        }
+    if (!bt_addr_cmp(&key->addr, addr)) {
+      return key;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_keys_link_key *bt_keys_get_link_key(const bt_addr_t *addr)
-{
-    struct bt_keys_link_key *key;
+struct bt_keys_link_key *bt_keys_get_link_key(const bt_addr_t *addr) {
+  struct bt_keys_link_key *key;
 
-    key = bt_keys_find_link_key(addr);
-    if (key) {
-        return key;
-    }
+  key = bt_keys_find_link_key(addr);
+  if (key) {
+    return key;
+  }
 
-    key = bt_keys_find_link_key(BT_ADDR_ANY);
-#if 0 //IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) //MBHJ
+  key = bt_keys_find_link_key(BT_ADDR_ANY);
+#if 0 // IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) //MBHJ
 	if (!key) {
 		int i;
 
@@ -78,60 +76,56 @@ struct bt_keys_link_key *bt_keys_get_link_key(const bt_addr_t *addr)
 	}
 #endif
 
-    if (key) {
-        bt_addr_copy(&key->addr, addr);
-#if 0 //IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) //MBHJ
+  if (key) {
+    bt_addr_copy(&key->addr, addr);
+#if 0 // IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) //MBHJ
 		key->aging_counter = ++aging_counter_val;
 		last_keys_updated = key;
 #endif
-        BT_DBG("created %p for %s", key, bt_addr_str(addr));
-        return key;
-    }
+    BT_DBG("created %p for %s", key, bt_addr_str(addr));
+    return key;
+  }
 
-    BT_DBG("unable to create keys for %s", bt_addr_str(addr));
+  BT_DBG("unable to create keys for %s", bt_addr_str(addr));
 
-    return NULL;
+  return NULL;
 }
 
-void bt_keys_link_key_clear(struct bt_keys_link_key *link_key)
-{
-    if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
-        char key[BT_SETTINGS_KEY_MAX];
-        bt_addr_le_t le_addr;
-
-        le_addr.type = BT_ADDR_LE_PUBLIC;
-        bt_addr_copy(&le_addr.a, &link_key->addr);
-        bt_settings_encode_key(key, sizeof(key), "link_key",
-                               &le_addr, NULL);
-        settings_delete(key);
-    }
+void bt_keys_link_key_clear(struct bt_keys_link_key *link_key) {
+  if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+    char         key[BT_SETTINGS_KEY_MAX];
+    bt_addr_le_t le_addr;
+
+    le_addr.type = BT_ADDR_LE_PUBLIC;
+    bt_addr_copy(&le_addr.a, &link_key->addr);
+    bt_settings_encode_key(key, sizeof(key), "link_key", &le_addr, NULL);
+    settings_delete(key);
+  }
 
-    BT_DBG("%s", bt_addr_str(&link_key->addr));
-    (void)memset(link_key, 0, sizeof(*link_key));
+  BT_DBG("%s", bt_addr_str(&link_key->addr));
+  (void)memset(link_key, 0, sizeof(*link_key));
 }
 
-void bt_keys_link_key_clear_addr(const bt_addr_t *addr)
-{
-    int i;
-    struct bt_keys_link_key *key;
-
-    if (!addr) {
-        for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
-            key = &key_pool[i];
-            bt_keys_link_key_clear(key);
-        }
-        return;
-    }
+void bt_keys_link_key_clear_addr(const bt_addr_t *addr) {
+  int                      i;
+  struct bt_keys_link_key *key;
 
-    key = bt_keys_find_link_key(addr);
-    if (key) {
-        bt_keys_link_key_clear(key);
+  if (!addr) {
+    for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
+      key = &key_pool[i];
+      bt_keys_link_key_clear(key);
     }
+    return;
+  }
+
+  key = bt_keys_find_link_key(addr);
+  if (key) {
+    bt_keys_link_key_clear(key);
+  }
 }
 
-void bt_keys_link_key_store(struct bt_keys_link_key *link_key)
-{
-#if 0 //MBHJ
+void bt_keys_link_key_store(struct bt_keys_link_key *link_key) {
+#if 0 // MBHJ
 	if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
 		int err;
 		char key[BT_SETTINGS_KEY_MAX];
@@ -153,89 +147,78 @@ void bt_keys_link_key_store(struct bt_keys_link_key *link_key)
 
 #if defined(CONFIG_BT_SETTINGS)
 
-static int link_key_set(const char *name, size_t len_rd,
-                        settings_read_cb read_cb, void *cb_arg)
-{
-    int err;
-    ssize_t len;
-    bt_addr_le_t le_addr;
-    struct bt_keys_link_key *link_key;
-    char val[BT_KEYS_LINK_KEY_STORAGE_LEN];
-
-    if (!name) {
-        BT_ERR("Insufficient number of arguments");
-        return -EINVAL;
-    }
-
-    len = read_cb(cb_arg, val, sizeof(val));
-    if (len < 0) {
-        BT_ERR("Failed to read value (err %zu)", len);
-        return -EINVAL;
-    }
-
-    BT_DBG("name %s val %s", log_strdup(name),
-           len ? bt_hex(val, sizeof(val)) : "(null)");
-
-    err = bt_settings_decode_key(name, &le_addr);
-    if (err) {
-        BT_ERR("Unable to decode address %s", name);
-        return -EINVAL;
+static int link_key_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) {
+  int                      err;
+  ssize_t                  len;
+  bt_addr_le_t             le_addr;
+  struct bt_keys_link_key *link_key;
+  char                     val[BT_KEYS_LINK_KEY_STORAGE_LEN];
+
+  if (!name) {
+    BT_ERR("Insufficient number of arguments");
+    return -EINVAL;
+  }
+
+  len = read_cb(cb_arg, val, sizeof(val));
+  if (len < 0) {
+    BT_ERR("Failed to read value (err %zu)", len);
+    return -EINVAL;
+  }
+
+  BT_DBG("name %s val %s", log_strdup(name), len ? bt_hex(val, sizeof(val)) : "(null)");
+
+  err = bt_settings_decode_key(name, &le_addr);
+  if (err) {
+    BT_ERR("Unable to decode address %s", name);
+    return -EINVAL;
+  }
+
+  link_key = bt_keys_get_link_key(&le_addr.a);
+  if (len != BT_KEYS_LINK_KEY_STORAGE_LEN) {
+    if (link_key) {
+      bt_keys_link_key_clear(link_key);
+      BT_DBG("Clear keys for %s", bt_addr_le_str(&le_addr));
+    } else {
+      BT_WARN("Unable to find deleted keys for %s", bt_addr_le_str(&le_addr));
     }
 
-    link_key = bt_keys_get_link_key(&le_addr.a);
-    if (len != BT_KEYS_LINK_KEY_STORAGE_LEN) {
-        if (link_key) {
-            bt_keys_link_key_clear(link_key);
-            BT_DBG("Clear keys for %s", bt_addr_le_str(&le_addr));
-        } else {
-            BT_WARN("Unable to find deleted keys for %s",
-                    bt_addr_le_str(&le_addr));
-        }
-
-        return 0;
-    }
+    return 0;
+  }
 
-    memcpy(link_key->storage_start, val, len);
-    BT_DBG("Successfully restored link key for %s",
-           bt_addr_le_str(&le_addr));
+  memcpy(link_key->storage_start, val, len);
+  BT_DBG("Successfully restored link key for %s", bt_addr_le_str(&le_addr));
 #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
-    if (aging_counter_val < link_key->aging_counter) {
-        aging_counter_val = link_key->aging_counter;
-    }
+  if (aging_counter_val < link_key->aging_counter) {
+    aging_counter_val = link_key->aging_counter;
+  }
 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
 
-    return 0;
+  return 0;
 }
 
-static int link_key_commit(void)
-{
-    return 0;
-}
+static int link_key_commit(void) { return 0; }
 
-SETTINGS_STATIC_HANDLER_DEFINE(bt_link_key, "bt/link_key", NULL, link_key_set,
-                               link_key_commit, NULL);
+SETTINGS_STATIC_HANDLER_DEFINE(bt_link_key, "bt/link_key", NULL, link_key_set, link_key_commit, NULL);
 
-void bt_keys_link_key_update_usage(const bt_addr_t *addr)
-{
-    struct bt_keys_link_key *link_key = bt_keys_find_link_key(addr);
+void bt_keys_link_key_update_usage(const bt_addr_t *addr) {
+  struct bt_keys_link_key *link_key = bt_keys_find_link_key(addr);
 
-    if (!link_key) {
-        return;
-    }
+  if (!link_key) {
+    return;
+  }
 
-    if (last_keys_updated == link_key) {
-        return;
-    }
+  if (last_keys_updated == link_key) {
+    return;
+  }
 
-    link_key->aging_counter = ++aging_counter_val;
-    last_keys_updated = link_key;
+  link_key->aging_counter = ++aging_counter_val;
+  last_keys_updated       = link_key;
 
-    BT_DBG("Aging counter for %s is set to %u", bt_addr_str(addr),
-           link_key->aging_counter);
+  BT_DBG("Aging counter for %s is set to %u", bt_addr_str(addr), link_key->aging_counter);
 
-    if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) {
-        bt_keys_link_key_store(link_key);
-    }
+  if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) {
+    bt_keys_link_key_store(link_key);
+  }
 }
 
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c
index 988365722..9137ee43d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/l2cap.c
@@ -6,24 +6,24 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
-#include 
 #include 
+#include 
 #include 
 #include 
+#include 
+#include 
 
-#include 
 #include 
 #include 
 #include 
+#include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_L2CAP)
 #define LOG_MODULE_NAME bt_l2cap
 #include "log.h"
 
-#include "hci_core.h"
 #include "conn_internal.h"
+#include "hci_core.h"
 #include "l2cap_internal.h"
 
 #include "ble_config.h"
@@ -39,10 +39,9 @@
 #define L2CAP_LE_MAX_CREDITS (CONFIG_BT_RX_BUF_COUNT - 1)
 #endif
 
-#define L2CAP_LE_CID_DYN_START 0x0040
-#define L2CAP_LE_CID_DYN_END   0x007f
-#define L2CAP_LE_CID_IS_DYN(_cid) \
-    (_cid >= L2CAP_LE_CID_DYN_START && _cid <= L2CAP_LE_CID_DYN_END)
+#define L2CAP_LE_CID_DYN_START    0x0040
+#define L2CAP_LE_CID_DYN_END      0x007f
+#define L2CAP_LE_CID_IS_DYN(_cid) (_cid >= L2CAP_LE_CID_DYN_START && _cid <= L2CAP_LE_CID_DYN_END)
 
 #define L2CAP_LE_PSM_FIXED_START 0x0001
 #define L2CAP_LE_PSM_FIXED_END   0x007f
@@ -73,1894 +72,1716 @@ static sys_slist_t servers;
 
 /* L2CAP signalling channel specific context */
 struct bt_l2cap {
-    /* The channel this context is associated with */
-    struct bt_l2cap_le_chan chan;
+  /* The channel this context is associated with */
+  struct bt_l2cap_le_chan chan;
 };
 
 static struct bt_l2cap bt_l2cap_pool[CONFIG_BT_MAX_CONN];
 
-static u8_t get_ident(void)
-{
-    static u8_t ident;
+static u8_t get_ident(void) {
+  static u8_t ident;
 
+  ident++;
+  /* handle integer overflow (0 is not valid) */
+  if (!ident) {
     ident++;
-    /* handle integer overflow (0 is not valid) */
-    if (!ident) {
-        ident++;
-    }
+  }
 
-    return ident;
+  return ident;
 }
 
 #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL)
-void bt_l2cap_le_fixed_chan_register(struct bt_l2cap_fixed_chan *chan)
-{
-    BT_DBG("CID 0x%04x", chan->cid);
+void bt_l2cap_le_fixed_chan_register(struct bt_l2cap_fixed_chan *chan) {
+  BT_DBG("CID 0x%04x", chan->cid);
 
-    sys_slist_append(&le_channels, &chan->node);
+  sys_slist_append(&le_channels, &chan->node);
 }
 #endif
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static struct bt_l2cap_le_chan *l2cap_chan_alloc_cid(struct bt_conn *conn,
-                                                     struct bt_l2cap_chan *chan)
-{
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
-    u16_t cid;
-
-    /*
-	 * No action needed if there's already a CID allocated, e.g. in
-	 * the case of a fixed channel.
-	 */
-    if (ch && ch->rx.cid > 0) {
-        return ch;
-    }
+static struct bt_l2cap_le_chan *l2cap_chan_alloc_cid(struct bt_conn *conn, struct bt_l2cap_chan *chan) {
+  struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
+  u16_t                    cid;
+
+  /*
+   * No action needed if there's already a CID allocated, e.g. in
+   * the case of a fixed channel.
+   */
+  if (ch && ch->rx.cid > 0) {
+    return ch;
+  }
 
-    for (cid = L2CAP_LE_CID_DYN_START; cid <= L2CAP_LE_CID_DYN_END; cid++) {
-        if (ch && !bt_l2cap_le_lookup_rx_cid(conn, cid)) {
-            ch->rx.cid = cid;
-            return ch;
-        }
+  for (cid = L2CAP_LE_CID_DYN_START; cid <= L2CAP_LE_CID_DYN_END; cid++) {
+    if (ch && !bt_l2cap_le_lookup_rx_cid(conn, cid)) {
+      ch->rx.cid = cid;
+      return ch;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-static struct bt_l2cap_le_chan *
-__l2cap_lookup_ident(struct bt_conn *conn, u16_t ident, bool remove)
-{
-    struct bt_l2cap_chan *chan;
-    sys_snode_t *prev = NULL;
+static struct bt_l2cap_le_chan *__l2cap_lookup_ident(struct bt_conn *conn, u16_t ident, bool remove) {
+  struct bt_l2cap_chan *chan;
+  sys_snode_t          *prev = NULL;
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
-        if (chan->ident == ident) {
-            if (remove) {
-                sys_slist_remove(&conn->channels, prev,
-                                 &chan->node);
-            }
-            return BT_L2CAP_LE_CHAN(chan);
-        }
-
-        prev = &chan->node;
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
+    if (chan->ident == ident) {
+      if (remove) {
+        sys_slist_remove(&conn->channels, prev, &chan->node);
+      }
+      return BT_L2CAP_LE_CHAN(chan);
     }
 
-    return NULL;
+    prev = &chan->node;
+  }
+
+  return NULL;
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-void bt_l2cap_chan_remove(struct bt_conn *conn, struct bt_l2cap_chan *ch)
-{
-    struct bt_l2cap_chan *chan;
-    sys_snode_t *prev = NULL;
-
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
-        if (chan == ch) {
-            sys_slist_remove(&conn->channels, prev, &chan->node);
-            return;
-        }
+void bt_l2cap_chan_remove(struct bt_conn *conn, struct bt_l2cap_chan *ch) {
+  struct bt_l2cap_chan *chan;
+  sys_snode_t          *prev = NULL;
 
-        prev = &chan->node;
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
+    if (chan == ch) {
+      sys_slist_remove(&conn->channels, prev, &chan->node);
+      return;
     }
+
+    prev = &chan->node;
+  }
 }
 
-const char *bt_l2cap_chan_state_str(bt_l2cap_chan_state_t state)
-{
-    switch (state) {
-        case BT_L2CAP_DISCONNECTED:
-            return "disconnected";
-        case BT_L2CAP_CONNECT:
-            return "connect";
-        case BT_L2CAP_CONFIG:
-            return "config";
-        case BT_L2CAP_CONNECTED:
-            return "connected";
-        case BT_L2CAP_DISCONNECT:
-            return "disconnect";
-        default:
-            return "unknown";
-    }
+const char *bt_l2cap_chan_state_str(bt_l2cap_chan_state_t state) {
+  switch (state) {
+  case BT_L2CAP_DISCONNECTED:
+    return "disconnected";
+  case BT_L2CAP_CONNECT:
+    return "connect";
+  case BT_L2CAP_CONFIG:
+    return "config";
+  case BT_L2CAP_CONNECTED:
+    return "connected";
+  case BT_L2CAP_DISCONNECT:
+    return "disconnect";
+  default:
+    return "unknown";
+  }
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
 #if defined(CONFIG_BT_DEBUG_L2CAP)
-void bt_l2cap_chan_set_state_debug(struct bt_l2cap_chan *chan,
-                                   bt_l2cap_chan_state_t state,
-                                   const char *func, int line)
-{
-    BT_DBG("chan %p psm 0x%04x %s -> %s", chan, chan->psm,
-           bt_l2cap_chan_state_str(chan->state),
-           bt_l2cap_chan_state_str(state));
-
-    /* check transitions validness */
-    switch (state) {
-        case BT_L2CAP_DISCONNECTED:
-            /* regardless of old state always allows this state */
-            break;
-        case BT_L2CAP_CONNECT:
-            if (chan->state != BT_L2CAP_DISCONNECTED) {
-                BT_WARN("%s()%d: invalid transition", func, line);
-            }
-            break;
-        case BT_L2CAP_CONFIG:
-            if (chan->state != BT_L2CAP_CONNECT) {
-                BT_WARN("%s()%d: invalid transition", func, line);
-            }
-            break;
-        case BT_L2CAP_CONNECTED:
-            if (chan->state != BT_L2CAP_CONFIG &&
-                chan->state != BT_L2CAP_CONNECT) {
-                BT_WARN("%s()%d: invalid transition", func, line);
-            }
-            break;
-        case BT_L2CAP_DISCONNECT:
-            if (chan->state != BT_L2CAP_CONFIG &&
-                chan->state != BT_L2CAP_CONNECTED) {
-                BT_WARN("%s()%d: invalid transition", func, line);
-            }
-            break;
-        default:
-            BT_ERR("%s()%d: unknown (%u) state was set", func, line, state);
-            return;
-    }
-
-    chan->state = state;
+void bt_l2cap_chan_set_state_debug(struct bt_l2cap_chan *chan, bt_l2cap_chan_state_t state, const char *func, int line) {
+  BT_DBG("chan %p psm 0x%04x %s -> %s", chan, chan->psm, bt_l2cap_chan_state_str(chan->state), bt_l2cap_chan_state_str(state));
+
+  /* check transitions validness */
+  switch (state) {
+  case BT_L2CAP_DISCONNECTED:
+    /* regardless of old state always allows this state */
+    break;
+  case BT_L2CAP_CONNECT:
+    if (chan->state != BT_L2CAP_DISCONNECTED) {
+      BT_WARN("%s()%d: invalid transition", func, line);
+    }
+    break;
+  case BT_L2CAP_CONFIG:
+    if (chan->state != BT_L2CAP_CONNECT) {
+      BT_WARN("%s()%d: invalid transition", func, line);
+    }
+    break;
+  case BT_L2CAP_CONNECTED:
+    if (chan->state != BT_L2CAP_CONFIG && chan->state != BT_L2CAP_CONNECT) {
+      BT_WARN("%s()%d: invalid transition", func, line);
+    }
+    break;
+  case BT_L2CAP_DISCONNECT:
+    if (chan->state != BT_L2CAP_CONFIG && chan->state != BT_L2CAP_CONNECTED) {
+      BT_WARN("%s()%d: invalid transition", func, line);
+    }
+    break;
+  default:
+    BT_ERR("%s()%d: unknown (%u) state was set", func, line, state);
+    return;
+  }
+
+  chan->state = state;
 }
 #else
-void bt_l2cap_chan_set_state(struct bt_l2cap_chan *chan,
-                             bt_l2cap_chan_state_t state)
-{
-    chan->state = state;
-}
+void bt_l2cap_chan_set_state(struct bt_l2cap_chan *chan, bt_l2cap_chan_state_t state) { chan->state = state; }
 #endif /* CONFIG_BT_DEBUG_L2CAP */
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-void bt_l2cap_chan_del(struct bt_l2cap_chan *chan)
-{
-    BT_DBG("conn %p chan %p", chan->conn, chan);
+void bt_l2cap_chan_del(struct bt_l2cap_chan *chan) {
+  BT_DBG("conn %p chan %p", chan->conn, chan);
 
-    if (!chan->conn) {
-        goto destroy;
-    }
+  if (!chan->conn) {
+    goto destroy;
+  }
 
-    if (chan->ops->disconnected) {
-        chan->ops->disconnected(chan);
-    }
+  if (chan->ops->disconnected) {
+    chan->ops->disconnected(chan);
+  }
 
-    chan->conn = NULL;
+  chan->conn = NULL;
 
 destroy:
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-    /* Reset internal members of common channel */
-    bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECTED);
-    chan->psm = 0U;
+  /* Reset internal members of common channel */
+  bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECTED);
+  chan->psm = 0U;
 #endif
 
-    if (chan->destroy) {
-        chan->destroy(chan);
-    }
+  if (chan->destroy) {
+    chan->destroy(chan);
+  }
 
 #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS
-    if (chan->rtx_work.timer.timer.hdl)
-        k_delayed_work_del_timer(&chan->rtx_work);
+  if (chan->rtx_work.timer.timer.hdl)
+    k_delayed_work_del_timer(&chan->rtx_work);
 #endif
 }
 
-static void l2cap_rtx_timeout(struct k_work *work)
-{
-    struct bt_l2cap_le_chan *chan = LE_CHAN_RTX(work);
+static void l2cap_rtx_timeout(struct k_work *work) {
+  struct bt_l2cap_le_chan *chan = LE_CHAN_RTX(work);
 
-    BT_ERR("chan %p timeout", chan);
+  BT_ERR("chan %p timeout", chan);
 
-    bt_l2cap_chan_remove(chan->chan.conn, &chan->chan);
-    bt_l2cap_chan_del(&chan->chan);
+  bt_l2cap_chan_remove(chan->chan.conn, &chan->chan);
+  bt_l2cap_chan_del(&chan->chan);
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan,
-                               struct net_buf *buf);
-
-static void l2cap_rx_process(struct k_work *work)
-{
-    struct bt_l2cap_le_chan *ch = CHAN_RX(work);
-    struct net_buf *buf;
-
-    while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) {
-        BT_DBG("ch %p buf %p", ch, buf);
-        l2cap_chan_le_recv(ch, buf);
-        net_buf_unref(buf);
-    }
+static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan, struct net_buf *buf);
+
+static void l2cap_rx_process(struct k_work *work) {
+  struct bt_l2cap_le_chan *ch = CHAN_RX(work);
+  struct net_buf          *buf;
+
+  while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) {
+    BT_DBG("ch %p buf %p", ch, buf);
+    l2cap_chan_le_recv(ch, buf);
+    net_buf_unref(buf);
+  }
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-void bt_l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan,
-                       bt_l2cap_chan_destroy_t destroy)
-{
-    /* Attach channel to the connection */
-    sys_slist_append(&conn->channels, &chan->node);
-    chan->conn = conn;
-    chan->destroy = destroy;
+void bt_l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, bt_l2cap_chan_destroy_t destroy) {
+  /* Attach channel to the connection */
+  sys_slist_append(&conn->channels, &chan->node);
+  chan->conn    = conn;
+  chan->destroy = destroy;
 
-    BT_DBG("conn %p chan %p", conn, chan);
+  BT_DBG("conn %p chan %p", conn, chan);
 }
 
-static bool l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan,
-                           bt_l2cap_chan_destroy_t destroy)
-{
-    struct bt_l2cap_le_chan *ch;
+static bool l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, bt_l2cap_chan_destroy_t destroy) {
+  struct bt_l2cap_le_chan *ch;
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-    ch = l2cap_chan_alloc_cid(conn, chan);
+  ch = l2cap_chan_alloc_cid(conn, chan);
 #else
-    ch = BT_L2CAP_LE_CHAN(chan);
+  ch = BT_L2CAP_LE_CHAN(chan);
 #endif
 
-    if (!ch) {
-        BT_ERR("Unable to allocate L2CAP CID");
-        return false;
-    }
+  if (!ch) {
+    BT_ERR("Unable to allocate L2CAP CID");
+    return false;
+  }
 
-    k_delayed_work_init(&chan->rtx_work, l2cap_rtx_timeout);
+  k_delayed_work_init(&chan->rtx_work, l2cap_rtx_timeout);
 
-    bt_l2cap_chan_add(conn, chan, destroy);
+  bt_l2cap_chan_add(conn, chan, destroy);
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-    if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) {
-        k_work_init(&ch->rx_work, l2cap_rx_process);
-        k_fifo_init(&ch->rx_queue, 20);
-        bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECT);
-    }
+  if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) {
+    k_work_init(&ch->rx_work, l2cap_rx_process);
+    k_fifo_init(&ch->rx_queue, 20);
+    bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECT);
+  }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-    return true;
+  return true;
 }
 
-void bt_l2cap_connected(struct bt_conn *conn)
-{
+void bt_l2cap_connected(struct bt_conn *conn) {
 #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL)
-    struct bt_l2cap_fixed_chan *fchan;
+  struct bt_l2cap_fixed_chan *fchan;
 #endif
-    struct bt_l2cap_chan *chan;
+  struct bt_l2cap_chan *chan;
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        bt_l2cap_br_connected(conn);
-        return;
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    bt_l2cap_br_connected(conn);
+    return;
+  }
 
 #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL)
-    SYS_SLIST_FOR_EACH_CONTAINER(&le_channels, fchan, node)
-    {
+  SYS_SLIST_FOR_EACH_CONTAINER(&le_channels, fchan, node) {
 #else
-    Z_STRUCT_SECTION_FOREACH(bt_l2cap_fixed_chan, fchan)
-    {
+  Z_STRUCT_SECTION_FOREACH(bt_l2cap_fixed_chan, fchan) {
 #endif
-        struct bt_l2cap_le_chan *ch;
+    struct bt_l2cap_le_chan *ch;
 
-        if (fchan->accept(conn, &chan) < 0) {
-            continue;
-        }
+    if (fchan->accept(conn, &chan) < 0) {
+      continue;
+    }
 
-        ch = BT_L2CAP_LE_CHAN(chan);
+    ch = BT_L2CAP_LE_CHAN(chan);
 
-        /* Fill up remaining fixed channel context attached in
-		 * fchan->accept()
-		 */
-        ch->rx.cid = fchan->cid;
-        ch->tx.cid = fchan->cid;
+    /* Fill up remaining fixed channel context attached in
+     * fchan->accept()
+     */
+    ch->rx.cid = fchan->cid;
+    ch->tx.cid = fchan->cid;
 
-        if (!l2cap_chan_add(conn, chan, NULL)) {
-            return;
-        }
+    if (!l2cap_chan_add(conn, chan, NULL)) {
+      return;
+    }
 
-        if (chan->ops->connected) {
-            chan->ops->connected(chan);
-        }
+    if (chan->ops->connected) {
+      chan->ops->connected(chan);
+    }
 
-        /* Always set output status to fixed channels */
-        atomic_set_bit(chan->status, BT_L2CAP_STATUS_OUT);
+    /* Always set output status to fixed channels */
+    atomic_set_bit(chan->status, BT_L2CAP_STATUS_OUT);
 
-        if (chan->ops->status) {
-            chan->ops->status(chan, chan->status);
-        }
+    if (chan->ops->status) {
+      chan->ops->status(chan, chan->status);
     }
+  }
 }
 
-void bt_l2cap_disconnected(struct bt_conn *conn)
-{
-    struct bt_l2cap_chan *chan, *next;
+void bt_l2cap_disconnected(struct bt_conn *conn) {
+  struct bt_l2cap_chan *chan, *next;
 
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&conn->channels, chan, next, node)
-    {
-        bt_l2cap_chan_del(chan);
-    }
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&conn->channels, chan, next, node) { bt_l2cap_chan_del(chan); }
 }
 
-static struct net_buf *l2cap_create_le_sig_pdu(struct net_buf *buf,
-                                               u8_t code, u8_t ident,
-                                               u16_t len)
-{
-    struct bt_l2cap_sig_hdr *hdr;
-
-    /* Don't wait more than the minimum RTX timeout of 2 seconds */
-    buf = bt_l2cap_create_pdu_timeout(NULL, 0, K_SECONDS(2));
-    if (!buf) {
-        /* If it was not possible to allocate a buffer within the
-		 * timeout return NULL.
-		 */
-        BT_ERR("Unable to allocate buffer for op 0x%02x", code);
-        return NULL;
-    }
+static struct net_buf *l2cap_create_le_sig_pdu(struct net_buf *buf, u8_t code, u8_t ident, u16_t len) {
+  struct bt_l2cap_sig_hdr *hdr;
+
+  /* Don't wait more than the minimum RTX timeout of 2 seconds */
+  buf = bt_l2cap_create_pdu_timeout(NULL, 0, K_SECONDS(2));
+  if (!buf) {
+    /* If it was not possible to allocate a buffer within the
+     * timeout return NULL.
+     */
+    BT_ERR("Unable to allocate buffer for op 0x%02x", code);
+    return NULL;
+  }
 
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->code = code;
-    hdr->ident = ident;
-    hdr->len = sys_cpu_to_le16(len);
+  hdr        = net_buf_add(buf, sizeof(*hdr));
+  hdr->code  = code;
+  hdr->ident = ident;
+  hdr->len   = sys_cpu_to_le16(len);
 
-    return buf;
+  return buf;
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static void l2cap_chan_send_req(struct bt_l2cap_le_chan *chan,
-                                struct net_buf *buf, s32_t timeout)
-{
-    /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part A] page 126:
-	 *
-	 * The value of this timer is implementation-dependent but the minimum
-	 * initial value is 1 second and the maximum initial value is 60
-	 * seconds. One RTX timer shall exist for each outstanding signaling
-	 * request, including each Echo Request. The timer disappears on the
-	 * final expiration, when the response is received, or the physical
-	 * link is lost.
-	 */
-    if (timeout) {
-        k_delayed_work_submit(&chan->chan.rtx_work, timeout);
-    } else {
-        k_delayed_work_cancel(&chan->chan.rtx_work);
-    }
+static void l2cap_chan_send_req(struct bt_l2cap_le_chan *chan, struct net_buf *buf, s32_t timeout) {
+  /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part A] page 126:
+   *
+   * The value of this timer is implementation-dependent but the minimum
+   * initial value is 1 second and the maximum initial value is 60
+   * seconds. One RTX timer shall exist for each outstanding signaling
+   * request, including each Echo Request. The timer disappears on the
+   * final expiration, when the response is received, or the physical
+   * link is lost.
+   */
+  if (timeout) {
+    k_delayed_work_submit(&chan->chan.rtx_work, timeout);
+  } else {
+    k_delayed_work_cancel(&chan->chan.rtx_work);
+  }
 
-    bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf);
 }
 
-static int l2cap_le_conn_req(struct bt_l2cap_le_chan *ch)
-{
-    struct net_buf *buf;
-    struct bt_l2cap_le_conn_req *req;
+static int l2cap_le_conn_req(struct bt_l2cap_le_chan *ch) {
+  struct net_buf              *buf;
+  struct bt_l2cap_le_conn_req *req;
 
-    ch->chan.ident = get_ident();
+  ch->chan.ident = get_ident();
 
-    buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_LE_CONN_REQ,
-                                  ch->chan.ident, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_LE_CONN_REQ, ch->chan.ident, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->psm = sys_cpu_to_le16(ch->chan.psm);
-    req->scid = sys_cpu_to_le16(ch->rx.cid);
-    req->mtu = sys_cpu_to_le16(ch->rx.mtu);
-    req->mps = sys_cpu_to_le16(ch->rx.mps);
-    req->credits = sys_cpu_to_le16(ch->rx.init_credits);
+  req          = net_buf_add(buf, sizeof(*req));
+  req->psm     = sys_cpu_to_le16(ch->chan.psm);
+  req->scid    = sys_cpu_to_le16(ch->rx.cid);
+  req->mtu     = sys_cpu_to_le16(ch->rx.mtu);
+  req->mps     = sys_cpu_to_le16(ch->rx.mps);
+  req->credits = sys_cpu_to_le16(ch->rx.init_credits);
 
-    l2cap_chan_send_req(ch, buf, L2CAP_CONN_TIMEOUT);
+  l2cap_chan_send_req(ch, buf, L2CAP_CONN_TIMEOUT);
 
-    return 0;
+  return 0;
 }
 
-static void l2cap_le_encrypt_change(struct bt_l2cap_chan *chan, u8_t status)
-{
-    /* Skip channels already connected or with a pending request */
-    if (chan->state != BT_L2CAP_CONNECT || chan->ident) {
-        return;
-    }
+static void l2cap_le_encrypt_change(struct bt_l2cap_chan *chan, u8_t status) {
+  /* Skip channels already connected or with a pending request */
+  if (chan->state != BT_L2CAP_CONNECT || chan->ident) {
+    return;
+  }
 
-    if (status) {
-        bt_l2cap_chan_remove(chan->conn, chan);
-        bt_l2cap_chan_del(chan);
-        return;
-    }
+  if (status) {
+    bt_l2cap_chan_remove(chan->conn, chan);
+    bt_l2cap_chan_del(chan);
+    return;
+  }
 
-    /* Retry to connect */
-    l2cap_le_conn_req(BT_L2CAP_LE_CHAN(chan));
+  /* Retry to connect */
+  l2cap_le_conn_req(BT_L2CAP_LE_CHAN(chan));
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-void bt_l2cap_encrypt_change(struct bt_conn *conn, u8_t hci_status)
-{
-    struct bt_l2cap_chan *chan;
+void bt_l2cap_encrypt_change(struct bt_conn *conn, u8_t hci_status) {
+  struct bt_l2cap_chan *chan;
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        l2cap_br_encrypt_change(conn, hci_status);
-        return;
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    l2cap_br_encrypt_change(conn, hci_status);
+    return;
+  }
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-        l2cap_le_encrypt_change(chan, hci_status);
+    l2cap_le_encrypt_change(chan, hci_status);
 #endif
 
-        if (chan->ops->encrypt_change) {
-            chan->ops->encrypt_change(chan, hci_status);
-        }
+    if (chan->ops->encrypt_change) {
+      chan->ops->encrypt_change(chan, hci_status);
     }
+  }
 }
 
-struct net_buf *bt_l2cap_create_pdu_timeout(struct net_buf_pool *pool,
-                                            size_t reserve, s32_t timeout)
-{
-    return bt_conn_create_pdu_timeout(pool,
-                                      sizeof(struct bt_l2cap_hdr) + reserve,
-                                      timeout);
-}
+struct net_buf *bt_l2cap_create_pdu_timeout(struct net_buf_pool *pool, size_t reserve, s32_t timeout) { return bt_conn_create_pdu_timeout(pool, sizeof(struct bt_l2cap_hdr) + reserve, timeout); }
 
-int bt_l2cap_send_cb(struct bt_conn *conn, u16_t cid, struct net_buf *buf,
-                     bt_conn_tx_cb_t cb, void *user_data)
-{
-    struct bt_l2cap_hdr *hdr;
+int bt_l2cap_send_cb(struct bt_conn *conn, u16_t cid, struct net_buf *buf, bt_conn_tx_cb_t cb, void *user_data) {
+  struct bt_l2cap_hdr *hdr;
 
-    BT_DBG("conn %p cid %u len %zu", conn, cid, net_buf_frags_len(buf));
+  BT_DBG("conn %p cid %u len %zu", conn, cid, net_buf_frags_len(buf));
 
-    hdr = net_buf_push(buf, sizeof(*hdr));
-    hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr));
-    hdr->cid = sys_cpu_to_le16(cid);
+  hdr      = net_buf_push(buf, sizeof(*hdr));
+  hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr));
+  hdr->cid = sys_cpu_to_le16(cid);
 
-    return bt_conn_send_cb(conn, buf, cb, user_data);
+  return bt_conn_send_cb(conn, buf, cb, user_data);
 }
 
-static void l2cap_send_reject(struct bt_conn *conn, u8_t ident,
-                              u16_t reason, void *data, u8_t data_len)
-{
-    struct bt_l2cap_cmd_reject *rej;
-    struct net_buf *buf;
+static void l2cap_send_reject(struct bt_conn *conn, u8_t ident, u16_t reason, void *data, u8_t data_len) {
+  struct bt_l2cap_cmd_reject *rej;
+  struct net_buf             *buf;
 
-    buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CMD_REJECT, ident,
-                                  sizeof(*rej) + data_len);
-    if (!buf) {
-        return;
-    }
+  buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CMD_REJECT, ident, sizeof(*rej) + data_len);
+  if (!buf) {
+    return;
+  }
 
-    rej = net_buf_add(buf, sizeof(*rej));
-    rej->reason = sys_cpu_to_le16(reason);
+  rej         = net_buf_add(buf, sizeof(*rej));
+  rej->reason = sys_cpu_to_le16(reason);
 
-    if (data) {
-        net_buf_add_mem(buf, data, data_len);
-    }
+  if (data) {
+    net_buf_add_mem(buf, data, data_len);
+  }
 
-    bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
 }
 
-static void le_conn_param_rsp(struct bt_l2cap *l2cap, struct net_buf *buf)
-{
-    struct bt_l2cap_conn_param_rsp *rsp = (void *)buf->data;
+static void le_conn_param_rsp(struct bt_l2cap *l2cap, struct net_buf *buf) {
+  struct bt_l2cap_conn_param_rsp *rsp = (void *)buf->data;
 
-    if (buf->len < sizeof(*rsp)) {
-        BT_ERR("Too small LE conn param rsp");
-        return;
-    }
+  if (buf->len < sizeof(*rsp)) {
+    BT_ERR("Too small LE conn param rsp");
+    return;
+  }
 
-    BT_DBG("LE conn param rsp result %u", sys_le16_to_cpu(rsp->result));
+  BT_DBG("LE conn param rsp result %u", sys_le16_to_cpu(rsp->result));
 }
 
-static void le_conn_param_update_req(struct bt_l2cap *l2cap, u8_t ident,
-                                     struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_le_conn_param param;
-    struct bt_l2cap_conn_param_rsp *rsp;
-    struct bt_l2cap_conn_param_req *req = (void *)buf->data;
-    bool accepted;
+static void le_conn_param_update_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn                 *conn = l2cap->chan.chan.conn;
+  struct bt_le_conn_param         param;
+  struct bt_l2cap_conn_param_rsp *rsp;
+  struct bt_l2cap_conn_param_req *req = (void *)buf->data;
+  bool                            accepted;
 
-    if (buf->len < sizeof(*req)) {
-        BT_ERR("Too small LE conn update param req");
-        return;
-    }
+  if (buf->len < sizeof(*req)) {
+    BT_ERR("Too small LE conn update param req");
+    return;
+  }
 
-    if (conn->role != BT_HCI_ROLE_MASTER) {
-        l2cap_send_reject(conn, ident, BT_L2CAP_REJ_NOT_UNDERSTOOD,
-                          NULL, 0);
-        return;
-    }
+  if (conn->role != BT_HCI_ROLE_MASTER) {
+    l2cap_send_reject(conn, ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0);
+    return;
+  }
 
-    param.interval_min = sys_le16_to_cpu(req->min_interval);
-    param.interval_max = sys_le16_to_cpu(req->max_interval);
-    param.latency = sys_le16_to_cpu(req->latency);
-    param.timeout = sys_le16_to_cpu(req->timeout);
+  param.interval_min = sys_le16_to_cpu(req->min_interval);
+  param.interval_max = sys_le16_to_cpu(req->max_interval);
+  param.latency      = sys_le16_to_cpu(req->latency);
+  param.timeout      = sys_le16_to_cpu(req->timeout);
 
-    BT_DBG("min 0x%04x max 0x%04x latency: 0x%04x timeout: 0x%04x",
-           param.interval_min, param.interval_max, param.latency,
-           param.timeout);
+  BT_DBG("min 0x%04x max 0x%04x latency: 0x%04x timeout: 0x%04x", param.interval_min, param.interval_max, param.latency, param.timeout);
 
-    buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_CONN_PARAM_RSP, ident,
-                                  sizeof(*rsp));
-    if (!buf) {
-        return;
-    }
+  buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_CONN_PARAM_RSP, ident, sizeof(*rsp));
+  if (!buf) {
+    return;
+  }
 
-    accepted = le_param_req(conn, ¶m);
+  accepted = le_param_req(conn, ¶m);
 
-    rsp = net_buf_add(buf, sizeof(*rsp));
-    if (accepted) {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_ACCEPTED);
-    } else {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_REJECTED);
-    }
+  rsp = net_buf_add(buf, sizeof(*rsp));
+  if (accepted) {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_ACCEPTED);
+  } else {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_REJECTED);
+  }
 
-    bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
 
-    if (accepted) {
-        bt_conn_le_conn_update(conn, ¶m);
-    }
+  if (accepted) {
+    bt_conn_le_conn_update(conn, ¶m);
+  }
 }
 
-struct bt_l2cap_chan *bt_l2cap_le_lookup_tx_cid(struct bt_conn *conn,
-                                                u16_t cid)
-{
-    struct bt_l2cap_chan *chan;
+struct bt_l2cap_chan *bt_l2cap_le_lookup_tx_cid(struct bt_conn *conn, u16_t cid) {
+  struct bt_l2cap_chan *chan;
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
-        if (BT_L2CAP_LE_CHAN(chan)->tx.cid == cid) {
-            return chan;
-        }
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
+    if (BT_L2CAP_LE_CHAN(chan)->tx.cid == cid) {
+      return chan;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-struct bt_l2cap_chan *bt_l2cap_le_lookup_rx_cid(struct bt_conn *conn,
-                                                u16_t cid)
-{
-    struct bt_l2cap_chan *chan;
+struct bt_l2cap_chan *bt_l2cap_le_lookup_rx_cid(struct bt_conn *conn, u16_t cid) {
+  struct bt_l2cap_chan *chan;
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
-        if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) {
-            return chan;
-        }
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
+    if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) {
+      return chan;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static struct bt_l2cap_server *l2cap_server_lookup_psm(u16_t psm)
-{
-    struct bt_l2cap_server *server;
-
-    SYS_SLIST_FOR_EACH_CONTAINER(&servers, server, node)
-    {
-        if (server->psm == psm) {
-            return server;
-        }
+static struct bt_l2cap_server *l2cap_server_lookup_psm(u16_t psm) {
+  struct bt_l2cap_server *server;
+
+  SYS_SLIST_FOR_EACH_CONTAINER(&servers, server, node) {
+    if (server->psm == psm) {
+      return server;
     }
+  }
 
-    return NULL;
+  return NULL;
 }
 
-int bt_l2cap_server_register(struct bt_l2cap_server *server)
-{
-    if (!server->accept) {
-        return -EINVAL;
-    }
+int bt_l2cap_server_register(struct bt_l2cap_server *server) {
+  if (!server->accept) {
+    return -EINVAL;
+  }
 
-    if (server->psm) {
-        if (server->psm < L2CAP_LE_PSM_FIXED_START ||
-            server->psm > L2CAP_LE_PSM_DYN_END) {
-            return -EINVAL;
-        }
-
-        /* Check if given PSM is already in use */
-        if (l2cap_server_lookup_psm(server->psm)) {
-            BT_DBG("PSM already registered");
-            return -EADDRINUSE;
-        }
-    } else {
-        u16_t psm;
-
-        for (psm = L2CAP_LE_PSM_DYN_START;
-             psm <= L2CAP_LE_PSM_DYN_END; psm++) {
-            if (!l2cap_server_lookup_psm(psm)) {
-                break;
-            }
-        }
-
-        if (psm > L2CAP_LE_PSM_DYN_END) {
-            BT_WARN("No free dynamic PSMs available");
-            return -EADDRNOTAVAIL;
-        }
-
-        BT_DBG("Allocated PSM 0x%04x for new server", psm);
-        server->psm = psm;
+  if (server->psm) {
+    if (server->psm < L2CAP_LE_PSM_FIXED_START || server->psm > L2CAP_LE_PSM_DYN_END) {
+      return -EINVAL;
     }
 
-    if (server->sec_level > BT_SECURITY_L4) {
-        return -EINVAL;
-    } else if (server->sec_level < BT_SECURITY_L1) {
-        /* Level 0 is only applicable for BR/EDR */
-        server->sec_level = BT_SECURITY_L1;
+    /* Check if given PSM is already in use */
+    if (l2cap_server_lookup_psm(server->psm)) {
+      BT_DBG("PSM already registered");
+      return -EADDRINUSE;
     }
+  } else {
+    u16_t psm;
 
-    BT_DBG("PSM 0x%04x", server->psm);
-
-    sys_slist_append(&servers, &server->node);
-
-    return 0;
-}
-
-static void l2cap_chan_rx_init(struct bt_l2cap_le_chan *chan)
-{
-    BT_DBG("chan %p", chan);
-
-    /* Use existing MTU if defined */
-    if (!chan->rx.mtu) {
-        chan->rx.mtu = L2CAP_MAX_LE_MTU;
+    for (psm = L2CAP_LE_PSM_DYN_START; psm <= L2CAP_LE_PSM_DYN_END; psm++) {
+      if (!l2cap_server_lookup_psm(psm)) {
+        break;
+      }
     }
 
-    /* Use existing credits if defined */
-    if (!chan->rx.init_credits) {
-        if (chan->chan.ops->alloc_buf) {
-            /* Auto tune credits to receive a full packet */
-            chan->rx.init_credits = (chan->rx.mtu +
-                                     (L2CAP_MAX_LE_MPS - 1)) /
-                                    L2CAP_MAX_LE_MPS;
-        } else {
-            chan->rx.init_credits = L2CAP_LE_MAX_CREDITS;
-        }
+    if (psm > L2CAP_LE_PSM_DYN_END) {
+      BT_WARN("No free dynamic PSMs available");
+      return -EADDRNOTAVAIL;
     }
 
-    /* MPS shall not be bigger than MTU + 2 as the remaining bytes cannot
-	 * be used.
-	 */
-    chan->rx.mps = MIN(chan->rx.mtu + 2, L2CAP_MAX_LE_MPS);
-    k_sem_init(&chan->rx.credits, 0, BT_UINT_MAX);
+    BT_DBG("Allocated PSM 0x%04x for new server", psm);
+    server->psm = psm;
+  }
 
-    if (BT_DBG_ENABLED &&
-        chan->rx.init_credits * chan->rx.mps < chan->rx.mtu + 2) {
-        BT_WARN("Not enough credits for a full packet");
-    }
-}
+  if (server->sec_level > BT_SECURITY_L4) {
+    return -EINVAL;
+  } else if (server->sec_level < BT_SECURITY_L1) {
+    /* Level 0 is only applicable for BR/EDR */
+    server->sec_level = BT_SECURITY_L1;
+  }
+
+  BT_DBG("PSM 0x%04x", server->psm);
 
-static void l2cap_chan_tx_init(struct bt_l2cap_le_chan *chan)
-{
-    BT_DBG("chan %p", chan);
+  sys_slist_append(&servers, &server->node);
 
-    (void)memset(&chan->tx, 0, sizeof(chan->tx));
-    k_sem_init(&chan->tx.credits, 0, BT_UINT_MAX);
-    k_fifo_init(&chan->tx_queue, 20);
+  return 0;
 }
 
-static void l2cap_chan_tx_give_credits(struct bt_l2cap_le_chan *chan,
-                                       u16_t credits)
-{
-    BT_DBG("chan %p credits %u", chan, credits);
+static void l2cap_chan_rx_init(struct bt_l2cap_le_chan *chan) {
+  BT_DBG("chan %p", chan);
 
-    while (credits--) {
-        k_sem_give(&chan->tx.credits);
-    }
+  /* Use existing MTU if defined */
+  if (!chan->rx.mtu) {
+    chan->rx.mtu = L2CAP_MAX_LE_MTU;
+  }
 
-    if (atomic_test_and_set_bit(chan->chan.status, BT_L2CAP_STATUS_OUT) &&
-        chan->chan.ops->status) {
-        chan->chan.ops->status(&chan->chan, chan->chan.status);
+  /* Use existing credits if defined */
+  if (!chan->rx.init_credits) {
+    if (chan->chan.ops->alloc_buf) {
+      /* Auto tune credits to receive a full packet */
+      chan->rx.init_credits = (chan->rx.mtu + (L2CAP_MAX_LE_MPS - 1)) / L2CAP_MAX_LE_MPS;
+    } else {
+      chan->rx.init_credits = L2CAP_LE_MAX_CREDITS;
     }
-}
+  }
 
-static void l2cap_chan_rx_give_credits(struct bt_l2cap_le_chan *chan,
-                                       u16_t credits)
-{
-    BT_DBG("chan %p credits %u", chan, credits);
+  /* MPS shall not be bigger than MTU + 2 as the remaining bytes cannot
+   * be used.
+   */
+  chan->rx.mps = MIN(chan->rx.mtu + 2, L2CAP_MAX_LE_MPS);
+  k_sem_init(&chan->rx.credits, 0, BT_UINT_MAX);
 
-    while (credits--) {
-        k_sem_give(&chan->rx.credits);
-    }
+  if (BT_DBG_ENABLED && chan->rx.init_credits * chan->rx.mps < chan->rx.mtu + 2) {
+    BT_WARN("Not enough credits for a full packet");
+  }
 }
 
-static void l2cap_chan_destroy(struct bt_l2cap_chan *chan)
-{
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
-    struct net_buf *buf;
+static void l2cap_chan_tx_init(struct bt_l2cap_le_chan *chan) {
+  BT_DBG("chan %p", chan);
 
-    BT_DBG("chan %p cid 0x%04x", ch, ch->rx.cid);
-
-    /* Cancel ongoing work */
-    k_delayed_work_cancel(&chan->rtx_work);
-
-    if (ch->tx_buf) {
-        net_buf_unref(ch->tx_buf);
-        ch->tx_buf = NULL;
-    }
+  (void)memset(&chan->tx, 0, sizeof(chan->tx));
+  k_sem_init(&chan->tx.credits, 0, BT_UINT_MAX);
+  k_fifo_init(&chan->tx_queue, 20);
+}
 
-    /* Remove buffers on the TX queue */
-    while ((buf = net_buf_get(&ch->tx_queue, K_NO_WAIT))) {
-        net_buf_unref(buf);
-    }
+static void l2cap_chan_tx_give_credits(struct bt_l2cap_le_chan *chan, u16_t credits) {
+  BT_DBG("chan %p credits %u", chan, credits);
 
-    /* Remove buffers on the RX queue */
-    while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) {
-        net_buf_unref(buf);
-    }
+  while (credits--) {
+    k_sem_give(&chan->tx.credits);
+  }
 
-    /* Destroy segmented SDU if it exists */
-    if (ch->_sdu) {
-        net_buf_unref(ch->_sdu);
-        ch->_sdu = NULL;
-        ch->_sdu_len = 0U;
-    }
+  if (atomic_test_and_set_bit(chan->chan.status, BT_L2CAP_STATUS_OUT) && chan->chan.ops->status) {
+    chan->chan.ops->status(&chan->chan, chan->chan.status);
+  }
 }
 
-static u16_t le_err_to_result(int err)
-{
-    switch (err) {
-        case -ENOMEM:
-            return BT_L2CAP_LE_ERR_NO_RESOURCES;
-        case -EACCES:
-            return BT_L2CAP_LE_ERR_AUTHORIZATION;
-        case -EPERM:
-            return BT_L2CAP_LE_ERR_KEY_SIZE;
-        case -ENOTSUP:
-            /* This handle the cases where a fixed channel is registered but
-		 * for some reason (e.g. controller not suporting a feature)
-		 * cannot be used.
-		 */
-            return BT_L2CAP_LE_ERR_PSM_NOT_SUPP;
-        default:
-            return BT_L2CAP_LE_ERR_UNACCEPT_PARAMS;
-    }
+static void l2cap_chan_rx_give_credits(struct bt_l2cap_le_chan *chan, u16_t credits) {
+  BT_DBG("chan %p credits %u", chan, credits);
+
+  while (credits--) {
+    k_sem_give(&chan->rx.credits);
+  }
 }
 
-static void le_conn_req(struct bt_l2cap *l2cap, u8_t ident,
-                        struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_chan *chan;
-    struct bt_l2cap_server *server;
-    struct bt_l2cap_le_conn_req *req = (void *)buf->data;
-    struct bt_l2cap_le_conn_rsp *rsp;
-    u16_t psm, scid, mtu, mps, credits;
-    int err;
-
-    if (buf->len < sizeof(*req)) {
-        BT_ERR("Too small LE conn req packet size");
-        return;
-    }
+static void l2cap_chan_destroy(struct bt_l2cap_chan *chan) {
+  struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
+  struct net_buf          *buf;
 
-    psm = sys_le16_to_cpu(req->psm);
-    scid = sys_le16_to_cpu(req->scid);
-    mtu = sys_le16_to_cpu(req->mtu);
-    mps = sys_le16_to_cpu(req->mps);
-    credits = sys_le16_to_cpu(req->credits);
+  BT_DBG("chan %p cid 0x%04x", ch, ch->rx.cid);
 
-    BT_DBG("psm 0x%02x scid 0x%04x mtu %u mps %u credits %u", psm, scid,
-           mtu, mps, credits);
+  /* Cancel ongoing work */
+  k_delayed_work_cancel(&chan->rtx_work);
 
-    if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MTU) {
-        BT_ERR("Invalid LE-Conn Req params");
-        return;
-    }
+  if (ch->tx_buf) {
+    net_buf_unref(ch->tx_buf);
+    ch->tx_buf = NULL;
+  }
 
-    buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CONN_RSP, ident,
-                                  sizeof(*rsp));
-    if (!buf) {
-        return;
-    }
-
-    rsp = net_buf_add(buf, sizeof(*rsp));
-    (void)memset(rsp, 0, sizeof(*rsp));
+  /* Remove buffers on the TX queue */
+  while ((buf = net_buf_get(&ch->tx_queue, K_NO_WAIT))) {
+    net_buf_unref(buf);
+  }
 
-    /* Check if there is a server registered */
-    server = l2cap_server_lookup_psm(psm);
-    if (!server) {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_PSM_NOT_SUPP);
-        goto rsp;
-    }
+  /* Remove buffers on the RX queue */
+  while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) {
+    net_buf_unref(buf);
+  }
+
+  /* Destroy segmented SDU if it exists */
+  if (ch->_sdu) {
+    net_buf_unref(ch->_sdu);
+    ch->_sdu     = NULL;
+    ch->_sdu_len = 0U;
+  }
+}
+
+static u16_t le_err_to_result(int err) {
+  switch (err) {
+  case -ENOMEM:
+    return BT_L2CAP_LE_ERR_NO_RESOURCES;
+  case -EACCES:
+    return BT_L2CAP_LE_ERR_AUTHORIZATION;
+  case -EPERM:
+    return BT_L2CAP_LE_ERR_KEY_SIZE;
+  case -ENOTSUP:
+    /* This handle the cases where a fixed channel is registered but
+     * for some reason (e.g. controller not suporting a feature)
+     * cannot be used.
+     */
+    return BT_L2CAP_LE_ERR_PSM_NOT_SUPP;
+  default:
+    return BT_L2CAP_LE_ERR_UNACCEPT_PARAMS;
+  }
+}
+
+static void le_conn_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn              *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_chan        *chan;
+  struct bt_l2cap_server      *server;
+  struct bt_l2cap_le_conn_req *req = (void *)buf->data;
+  struct bt_l2cap_le_conn_rsp *rsp;
+  u16_t                        psm, scid, mtu, mps, credits;
+  int                          err;
+
+  if (buf->len < sizeof(*req)) {
+    BT_ERR("Too small LE conn req packet size");
+    return;
+  }
+
+  psm     = sys_le16_to_cpu(req->psm);
+  scid    = sys_le16_to_cpu(req->scid);
+  mtu     = sys_le16_to_cpu(req->mtu);
+  mps     = sys_le16_to_cpu(req->mps);
+  credits = sys_le16_to_cpu(req->credits);
+
+  BT_DBG("psm 0x%02x scid 0x%04x mtu %u mps %u credits %u", psm, scid, mtu, mps, credits);
+
+  if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MTU) {
+    BT_ERR("Invalid LE-Conn Req params");
+    return;
+  }
+
+  buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CONN_RSP, ident, sizeof(*rsp));
+  if (!buf) {
+    return;
+  }
+
+  rsp = net_buf_add(buf, sizeof(*rsp));
+  (void)memset(rsp, 0, sizeof(*rsp));
+
+  /* Check if there is a server registered */
+  server = l2cap_server_lookup_psm(psm);
+  if (!server) {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_PSM_NOT_SUPP);
+    goto rsp;
+  }
 
 /* Check if connection has minimum required security level */
 #if defined(CONFIG_BT_SMP)
-    if (conn->sec_level < server->sec_level) {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_AUTHENTICATION);
-        goto rsp;
-    }
+  if (conn->sec_level < server->sec_level) {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_AUTHENTICATION);
+    goto rsp;
+  }
 #endif
 
-    if (!L2CAP_LE_CID_IS_DYN(scid)) {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_INVALID_SCID);
-        goto rsp;
-    }
-
-    chan = bt_l2cap_le_lookup_tx_cid(conn, scid);
-    if (chan) {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_SCID_IN_USE);
-        goto rsp;
-    }
-
-    /* Request server to accept the new connection and allocate the
-	 * channel.
-	 */
-    err = server->accept(conn, &chan);
-    if (err < 0) {
-        rsp->result = sys_cpu_to_le16(le_err_to_result(err));
-        goto rsp;
-    }
-
-    chan->required_sec_level = server->sec_level;
-
-    if (l2cap_chan_add(conn, chan, l2cap_chan_destroy)) {
-        struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
-
-        /* Init TX parameters */
-        l2cap_chan_tx_init(ch);
-        ch->tx.cid = scid;
-        ch->tx.mps = mps;
-        ch->tx.mtu = mtu;
-        ch->tx.init_credits = credits;
-        l2cap_chan_tx_give_credits(ch, credits);
+  if (!L2CAP_LE_CID_IS_DYN(scid)) {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_INVALID_SCID);
+    goto rsp;
+  }
+
+  chan = bt_l2cap_le_lookup_tx_cid(conn, scid);
+  if (chan) {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_SCID_IN_USE);
+    goto rsp;
+  }
+
+  /* Request server to accept the new connection and allocate the
+   * channel.
+   */
+  err = server->accept(conn, &chan);
+  if (err < 0) {
+    rsp->result = sys_cpu_to_le16(le_err_to_result(err));
+    goto rsp;
+  }
+
+  chan->required_sec_level = server->sec_level;
+
+  if (l2cap_chan_add(conn, chan, l2cap_chan_destroy)) {
+    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
 
-        /* Init RX parameters */
-        l2cap_chan_rx_init(ch);
-        l2cap_chan_rx_give_credits(ch, ch->rx.init_credits);
+    /* Init TX parameters */
+    l2cap_chan_tx_init(ch);
+    ch->tx.cid          = scid;
+    ch->tx.mps          = mps;
+    ch->tx.mtu          = mtu;
+    ch->tx.init_credits = credits;
+    l2cap_chan_tx_give_credits(ch, credits);
 
-        /* Set channel PSM */
-        chan->psm = server->psm;
+    /* Init RX parameters */
+    l2cap_chan_rx_init(ch);
+    l2cap_chan_rx_give_credits(ch, ch->rx.init_credits);
 
-        /* Update state */
-        bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECTED);
+    /* Set channel PSM */
+    chan->psm = server->psm;
 
-        if (chan->ops->connected) {
-            chan->ops->connected(chan);
-        }
+    /* Update state */
+    bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECTED);
 
-        /* Prepare response protocol data */
-        rsp->dcid = sys_cpu_to_le16(ch->rx.cid);
-        rsp->mps = sys_cpu_to_le16(ch->rx.mps);
-        rsp->mtu = sys_cpu_to_le16(ch->rx.mtu);
-        rsp->credits = sys_cpu_to_le16(ch->rx.init_credits);
-        rsp->result = BT_L2CAP_LE_SUCCESS;
-    } else {
-        rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_NO_RESOURCES);
+    if (chan->ops->connected) {
+      chan->ops->connected(chan);
     }
+
+    /* Prepare response protocol data */
+    rsp->dcid    = sys_cpu_to_le16(ch->rx.cid);
+    rsp->mps     = sys_cpu_to_le16(ch->rx.mps);
+    rsp->mtu     = sys_cpu_to_le16(ch->rx.mtu);
+    rsp->credits = sys_cpu_to_le16(ch->rx.init_credits);
+    rsp->result  = BT_L2CAP_LE_SUCCESS;
+  } else {
+    rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_NO_RESOURCES);
+  }
 rsp:
-    bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
 }
 
-static struct bt_l2cap_le_chan *l2cap_remove_rx_cid(struct bt_conn *conn,
-                                                    u16_t cid)
-{
-    struct bt_l2cap_chan *chan;
-    sys_snode_t *prev = NULL;
-
-    /* Protect fixed channels against accidental removal */
-    if (!L2CAP_LE_CID_IS_DYN(cid)) {
-        return NULL;
-    }
+static struct bt_l2cap_le_chan *l2cap_remove_rx_cid(struct bt_conn *conn, u16_t cid) {
+  struct bt_l2cap_chan *chan;
+  sys_snode_t          *prev = NULL;
 
-    SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node)
-    {
-        if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) {
-            sys_slist_remove(&conn->channels, prev, &chan->node);
-            return BT_L2CAP_LE_CHAN(chan);
-        }
+  /* Protect fixed channels against accidental removal */
+  if (!L2CAP_LE_CID_IS_DYN(cid)) {
+    return NULL;
+  }
 
-        prev = &chan->node;
+  SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) {
+    if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) {
+      sys_slist_remove(&conn->channels, prev, &chan->node);
+      return BT_L2CAP_LE_CHAN(chan);
     }
 
-    return NULL;
+    prev = &chan->node;
+  }
+
+  return NULL;
 }
 
-static void le_disconn_req(struct bt_l2cap *l2cap, u8_t ident,
-                           struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_le_chan *chan;
-    struct bt_l2cap_disconn_req *req = (void *)buf->data;
-    struct bt_l2cap_disconn_rsp *rsp;
-    u16_t dcid;
+static void le_disconn_req(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn              *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_le_chan     *chan;
+  struct bt_l2cap_disconn_req *req = (void *)buf->data;
+  struct bt_l2cap_disconn_rsp *rsp;
+  u16_t                        dcid;
 
-    if (buf->len < sizeof(*req)) {
-        BT_ERR("Too small LE conn req packet size");
-        return;
-    }
+  if (buf->len < sizeof(*req)) {
+    BT_ERR("Too small LE conn req packet size");
+    return;
+  }
 
-    dcid = sys_le16_to_cpu(req->dcid);
+  dcid = sys_le16_to_cpu(req->dcid);
 
-    BT_DBG("dcid 0x%04x scid 0x%04x", dcid, sys_le16_to_cpu(req->scid));
+  BT_DBG("dcid 0x%04x scid 0x%04x", dcid, sys_le16_to_cpu(req->scid));
 
-    chan = l2cap_remove_rx_cid(conn, dcid);
-    if (!chan) {
-        struct bt_l2cap_cmd_reject_cid_data data;
+  chan = l2cap_remove_rx_cid(conn, dcid);
+  if (!chan) {
+    struct bt_l2cap_cmd_reject_cid_data data;
 
-        data.scid = req->scid;
-        data.dcid = req->dcid;
+    data.scid = req->scid;
+    data.dcid = req->dcid;
 
-        l2cap_send_reject(conn, ident, BT_L2CAP_REJ_INVALID_CID, &data,
-                          sizeof(data));
-        return;
-    }
+    l2cap_send_reject(conn, ident, BT_L2CAP_REJ_INVALID_CID, &data, sizeof(data));
+    return;
+  }
 
-    buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_DISCONN_RSP, ident,
-                                  sizeof(*rsp));
-    if (!buf) {
-        return;
-    }
+  buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_DISCONN_RSP, ident, sizeof(*rsp));
+  if (!buf) {
+    return;
+  }
 
-    rsp = net_buf_add(buf, sizeof(*rsp));
-    rsp->dcid = sys_cpu_to_le16(chan->rx.cid);
-    rsp->scid = sys_cpu_to_le16(chan->tx.cid);
+  rsp       = net_buf_add(buf, sizeof(*rsp));
+  rsp->dcid = sys_cpu_to_le16(chan->rx.cid);
+  rsp->scid = sys_cpu_to_le16(chan->tx.cid);
 
-    bt_l2cap_chan_del(&chan->chan);
+  bt_l2cap_chan_del(&chan->chan);
 
-    bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
 }
 
 #if defined(CONFIG_BT_SMP)
-static int l2cap_change_security(struct bt_l2cap_le_chan *chan, u16_t err)
-{
-    switch (err) {
-        case BT_L2CAP_LE_ERR_ENCRYPTION:
-            if (chan->chan.required_sec_level >= BT_SECURITY_L2) {
-                return -EALREADY;
-            }
-            chan->chan.required_sec_level = BT_SECURITY_L2;
-            break;
-        case BT_L2CAP_LE_ERR_AUTHENTICATION:
-            if (chan->chan.required_sec_level < BT_SECURITY_L2) {
-                chan->chan.required_sec_level = BT_SECURITY_L2;
-            } else if (chan->chan.required_sec_level < BT_SECURITY_L3) {
-                chan->chan.required_sec_level = BT_SECURITY_L3;
-            } else if (chan->chan.required_sec_level < BT_SECURITY_L4) {
-                chan->chan.required_sec_level = BT_SECURITY_L4;
-            } else {
-                return -EALREADY;
-            }
-            break;
-        default:
-            return -EINVAL;
+static int l2cap_change_security(struct bt_l2cap_le_chan *chan, u16_t err) {
+  switch (err) {
+  case BT_L2CAP_LE_ERR_ENCRYPTION:
+    if (chan->chan.required_sec_level >= BT_SECURITY_L2) {
+      return -EALREADY;
+    }
+    chan->chan.required_sec_level = BT_SECURITY_L2;
+    break;
+  case BT_L2CAP_LE_ERR_AUTHENTICATION:
+    if (chan->chan.required_sec_level < BT_SECURITY_L2) {
+      chan->chan.required_sec_level = BT_SECURITY_L2;
+    } else if (chan->chan.required_sec_level < BT_SECURITY_L3) {
+      chan->chan.required_sec_level = BT_SECURITY_L3;
+    } else if (chan->chan.required_sec_level < BT_SECURITY_L4) {
+      chan->chan.required_sec_level = BT_SECURITY_L4;
+    } else {
+      return -EALREADY;
     }
+    break;
+  default:
+    return -EINVAL;
+  }
 
-    return bt_conn_set_security(chan->chan.conn,
-                                chan->chan.required_sec_level);
+  return bt_conn_set_security(chan->chan.conn, chan->chan.required_sec_level);
 }
-#endif //CONFIG_BT_SMP
+#endif // CONFIG_BT_SMP
 
-static void le_conn_rsp(struct bt_l2cap *l2cap, u8_t ident,
-                        struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_le_chan *chan;
-    struct bt_l2cap_le_conn_rsp *rsp = (void *)buf->data;
-    u16_t dcid, mtu, mps, credits, result;
+static void le_conn_rsp(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn              *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_le_chan     *chan;
+  struct bt_l2cap_le_conn_rsp *rsp = (void *)buf->data;
+  u16_t                        dcid, mtu, mps, credits, result;
 
-    if (buf->len < sizeof(*rsp)) {
-        BT_ERR("Too small LE conn rsp packet size");
-        return;
-    }
+  if (buf->len < sizeof(*rsp)) {
+    BT_ERR("Too small LE conn rsp packet size");
+    return;
+  }
 
-    dcid = sys_le16_to_cpu(rsp->dcid);
-    mtu = sys_le16_to_cpu(rsp->mtu);
-    mps = sys_le16_to_cpu(rsp->mps);
-    credits = sys_le16_to_cpu(rsp->credits);
-    result = sys_le16_to_cpu(rsp->result);
+  dcid    = sys_le16_to_cpu(rsp->dcid);
+  mtu     = sys_le16_to_cpu(rsp->mtu);
+  mps     = sys_le16_to_cpu(rsp->mps);
+  credits = sys_le16_to_cpu(rsp->credits);
+  result  = sys_le16_to_cpu(rsp->result);
 
-    BT_DBG("dcid 0x%04x mtu %u mps %u credits %u result 0x%04x", dcid,
-           mtu, mps, credits, result);
+  BT_DBG("dcid 0x%04x mtu %u mps %u credits %u result 0x%04x", dcid, mtu, mps, credits, result);
 
-    /* Keep the channel in case of security errors */
-    if (result == BT_L2CAP_LE_SUCCESS ||
-        result == BT_L2CAP_LE_ERR_AUTHENTICATION ||
-        result == BT_L2CAP_LE_ERR_ENCRYPTION) {
-        chan = l2cap_lookup_ident(conn, ident);
-    } else {
-        chan = l2cap_remove_ident(conn, ident);
-    }
+  /* Keep the channel in case of security errors */
+  if (result == BT_L2CAP_LE_SUCCESS || result == BT_L2CAP_LE_ERR_AUTHENTICATION || result == BT_L2CAP_LE_ERR_ENCRYPTION) {
+    chan = l2cap_lookup_ident(conn, ident);
+  } else {
+    chan = l2cap_remove_ident(conn, ident);
+  }
 
-    if (!chan) {
-        BT_ERR("Cannot find channel for ident %u", ident);
-        return;
-    }
+  if (!chan) {
+    BT_ERR("Cannot find channel for ident %u", ident);
+    return;
+  }
 
-    /* Cancel RTX work */
-    k_delayed_work_cancel(&chan->chan.rtx_work);
+  /* Cancel RTX work */
+  k_delayed_work_cancel(&chan->chan.rtx_work);
 
-    /* Reset ident since it got a response */
-    chan->chan.ident = 0U;
+  /* Reset ident since it got a response */
+  chan->chan.ident = 0U;
 
-    switch (result) {
-        case BT_L2CAP_LE_SUCCESS:
-            chan->tx.cid = dcid;
-            chan->tx.mtu = mtu;
-            chan->tx.mps = mps;
+  switch (result) {
+  case BT_L2CAP_LE_SUCCESS:
+    chan->tx.cid = dcid;
+    chan->tx.mtu = mtu;
+    chan->tx.mps = mps;
 
-            /* Update state */
-            bt_l2cap_chan_set_state(&chan->chan, BT_L2CAP_CONNECTED);
+    /* Update state */
+    bt_l2cap_chan_set_state(&chan->chan, BT_L2CAP_CONNECTED);
 
-            if (chan->chan.ops->connected) {
-                chan->chan.ops->connected(&chan->chan);
-            }
+    if (chan->chan.ops->connected) {
+      chan->chan.ops->connected(&chan->chan);
+    }
 
-            /* Give credits */
-            l2cap_chan_tx_give_credits(chan, credits);
-            l2cap_chan_rx_give_credits(chan, chan->rx.init_credits);
+    /* Give credits */
+    l2cap_chan_tx_give_credits(chan, credits);
+    l2cap_chan_rx_give_credits(chan, chan->rx.init_credits);
 
-            break;
-        case BT_L2CAP_LE_ERR_AUTHENTICATION:
-        case BT_L2CAP_LE_ERR_ENCRYPTION:
+    break;
+  case BT_L2CAP_LE_ERR_AUTHENTICATION:
+  case BT_L2CAP_LE_ERR_ENCRYPTION:
 #if defined(CONFIG_BT_SMP)
-            /* If security needs changing wait it to be completed */
-            if (l2cap_change_security(chan, result) == 0) {
-                return;
-            }
-#endif
-            bt_l2cap_chan_remove(conn, &chan->chan);
-            __attribute__((fallthrough));
-        default:
-            bt_l2cap_chan_del(&chan->chan);
+    /* If security needs changing wait it to be completed */
+    if (l2cap_change_security(chan, result) == 0) {
+      return;
     }
+#endif
+    bt_l2cap_chan_remove(conn, &chan->chan);
+    __attribute__((fallthrough));
+  default:
+    bt_l2cap_chan_del(&chan->chan);
+  }
 }
 
-static void le_disconn_rsp(struct bt_l2cap *l2cap, u8_t ident,
-                           struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_le_chan *chan;
-    struct bt_l2cap_disconn_rsp *rsp = (void *)buf->data;
-    u16_t scid;
+static void le_disconn_rsp(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn              *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_le_chan     *chan;
+  struct bt_l2cap_disconn_rsp *rsp = (void *)buf->data;
+  u16_t                        scid;
 
-    if (buf->len < sizeof(*rsp)) {
-        BT_ERR("Too small LE disconn rsp packet size");
-        return;
-    }
+  if (buf->len < sizeof(*rsp)) {
+    BT_ERR("Too small LE disconn rsp packet size");
+    return;
+  }
 
-    scid = sys_le16_to_cpu(rsp->scid);
+  scid = sys_le16_to_cpu(rsp->scid);
 
-    BT_DBG("dcid 0x%04x scid 0x%04x", sys_le16_to_cpu(rsp->dcid), scid);
+  BT_DBG("dcid 0x%04x scid 0x%04x", sys_le16_to_cpu(rsp->dcid), scid);
 
-    chan = l2cap_remove_rx_cid(conn, scid);
-    if (!chan) {
-        return;
-    }
+  chan = l2cap_remove_rx_cid(conn, scid);
+  if (!chan) {
+    return;
+  }
 
-    bt_l2cap_chan_del(&chan->chan);
+  bt_l2cap_chan_del(&chan->chan);
 }
 
-static inline struct net_buf *l2cap_alloc_seg(struct net_buf *buf)
-{
-    struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
-    struct net_buf *seg;
+static inline struct net_buf *l2cap_alloc_seg(struct net_buf *buf) {
+  struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
+  struct net_buf      *seg;
 
-    /* Try to use original pool if possible */
-    seg = net_buf_alloc(pool, K_NO_WAIT);
-    if (seg) {
-        net_buf_reserve(seg, BT_L2CAP_CHAN_SEND_RESERVE);
-        return seg;
-    }
+  /* Try to use original pool if possible */
+  seg = net_buf_alloc(pool, K_NO_WAIT);
+  if (seg) {
+    net_buf_reserve(seg, BT_L2CAP_CHAN_SEND_RESERVE);
+    return seg;
+  }
 
-    /* Fallback to using global connection tx pool */
-    return bt_l2cap_create_pdu(NULL, 0);
+  /* Fallback to using global connection tx pool */
+  return bt_l2cap_create_pdu(NULL, 0);
 }
 
-static struct net_buf *l2cap_chan_create_seg(struct bt_l2cap_le_chan *ch,
-                                             struct net_buf *buf,
-                                             size_t sdu_hdr_len)
-{
-    struct net_buf *seg;
-    u16_t headroom;
-    u16_t len;
+static struct net_buf *l2cap_chan_create_seg(struct bt_l2cap_le_chan *ch, struct net_buf *buf, size_t sdu_hdr_len) {
+  struct net_buf *seg;
+  u16_t           headroom;
+  u16_t           len;
 
-    /* Segment if data (+ data headroom) is bigger than MPS */
-    if (buf->len + sdu_hdr_len > ch->tx.mps) {
-        goto segment;
-    }
+  /* Segment if data (+ data headroom) is bigger than MPS */
+  if (buf->len + sdu_hdr_len > ch->tx.mps) {
+    goto segment;
+  }
+
+  headroom = BT_L2CAP_CHAN_SEND_RESERVE + sdu_hdr_len;
 
-    headroom = BT_L2CAP_CHAN_SEND_RESERVE + sdu_hdr_len;
-
-    /* Check if original buffer has enough headroom and don't have any
-	 * fragments.
-	 */
-    if (net_buf_headroom(buf) >= headroom && !buf->frags) {
-        if (sdu_hdr_len) {
-            /* Push SDU length if set */
-            net_buf_push_le16(buf, net_buf_frags_len(buf));
-        }
-        return net_buf_ref(buf);
+  /* Check if original buffer has enough headroom and don't have any
+   * fragments.
+   */
+  if (net_buf_headroom(buf) >= headroom && !buf->frags) {
+    if (sdu_hdr_len) {
+      /* Push SDU length if set */
+      net_buf_push_le16(buf, net_buf_frags_len(buf));
     }
+    return net_buf_ref(buf);
+  }
 
 segment:
-    seg = l2cap_alloc_seg(buf);
-    if (!seg) {
-        return NULL;
-    }
+  seg = l2cap_alloc_seg(buf);
+  if (!seg) {
+    return NULL;
+  }
 
-    if (sdu_hdr_len) {
-        net_buf_add_le16(seg, net_buf_frags_len(buf));
-    }
+  if (sdu_hdr_len) {
+    net_buf_add_le16(seg, net_buf_frags_len(buf));
+  }
 
-    /* Don't send more that TX MPS including SDU length */
-    len = MIN(net_buf_tailroom(seg), ch->tx.mps - sdu_hdr_len);
-    /* Limit if original buffer is smaller than the segment */
-    len = MIN(buf->len, len);
-    net_buf_add_mem(seg, buf->data, len);
-    net_buf_pull(buf, len);
+  /* Don't send more that TX MPS including SDU length */
+  len = MIN(net_buf_tailroom(seg), ch->tx.mps - sdu_hdr_len);
+  /* Limit if original buffer is smaller than the segment */
+  len = MIN(buf->len, len);
+  net_buf_add_mem(seg, buf->data, len);
+  net_buf_pull(buf, len);
 
-    BT_DBG("ch %p seg %p len %u", ch, seg, seg->len);
+  BT_DBG("ch %p seg %p len %u", ch, seg, seg->len);
 
-    return seg;
+  return seg;
 }
 
-void l2cap_chan_sdu_sent(struct bt_conn *conn, void *user_data)
-{
-    struct bt_l2cap_chan *chan = user_data;
+void l2cap_chan_sdu_sent(struct bt_conn *conn, void *user_data) {
+  struct bt_l2cap_chan *chan = user_data;
 
-    BT_DBG("conn %p chan %p", conn, chan);
+  BT_DBG("conn %p chan %p", conn, chan);
 
-    if (chan->ops->sent) {
-        chan->ops->sent(chan);
-    }
+  if (chan->ops->sent) {
+    chan->ops->sent(chan);
+  }
 }
 
-static int l2cap_chan_le_send(struct bt_l2cap_le_chan *ch, struct net_buf *buf,
-                              u16_t sdu_hdr_len)
-{
-    struct net_buf *seg;
-    int len;
+static int l2cap_chan_le_send(struct bt_l2cap_le_chan *ch, struct net_buf *buf, u16_t sdu_hdr_len) {
+  struct net_buf *seg;
+  int             len;
 
-    /* Wait for credits */
-    if (k_sem_take(&ch->tx.credits, K_NO_WAIT)) {
-        BT_DBG("No credits to transmit packet");
-        return -EAGAIN;
-    }
+  /* Wait for credits */
+  if (k_sem_take(&ch->tx.credits, K_NO_WAIT)) {
+    BT_DBG("No credits to transmit packet");
+    return -EAGAIN;
+  }
 
-    seg = l2cap_chan_create_seg(ch, buf, sdu_hdr_len);
-    if (!seg) {
-        return -ENOMEM;
-    }
+  seg = l2cap_chan_create_seg(ch, buf, sdu_hdr_len);
+  if (!seg) {
+    return -ENOMEM;
+  }
 
-    /* Channel may have been disconnected while waiting for a buffer */
-    if (!ch->chan.conn) {
-        net_buf_unref(buf);
-        return -ECONNRESET;
-    }
+  /* Channel may have been disconnected while waiting for a buffer */
+  if (!ch->chan.conn) {
+    net_buf_unref(buf);
+    return -ECONNRESET;
+  }
 
-    BT_DBG("ch %p cid 0x%04x len %u credits %u", ch, ch->tx.cid,
-           seg->len, k_sem_count_get(&ch->tx.credits));
+  BT_DBG("ch %p cid 0x%04x len %u credits %u", ch, ch->tx.cid, seg->len, k_sem_count_get(&ch->tx.credits));
 
-    len = seg->len - sdu_hdr_len;
+  len = seg->len - sdu_hdr_len;
 
-    /* Set a callback if there is no data left in the buffer and sent
-	 * callback has been set.
-	 */
-    if ((buf == seg || !buf->len) && ch->chan.ops->sent) {
-        bt_l2cap_send_cb(ch->chan.conn, ch->tx.cid, seg,
-                         l2cap_chan_sdu_sent, &ch->chan);
-    } else {
-        bt_l2cap_send(ch->chan.conn, ch->tx.cid, seg);
-    }
+  /* Set a callback if there is no data left in the buffer and sent
+   * callback has been set.
+   */
+  if ((buf == seg || !buf->len) && ch->chan.ops->sent) {
+    bt_l2cap_send_cb(ch->chan.conn, ch->tx.cid, seg, l2cap_chan_sdu_sent, &ch->chan);
+  } else {
+    bt_l2cap_send(ch->chan.conn, ch->tx.cid, seg);
+  }
 
-    /* Check if there is no credits left clear output status and notify its
-	 * change.
-	 */
-    if (!k_sem_count_get(&ch->tx.credits)) {
-        atomic_clear_bit(ch->chan.status, BT_L2CAP_STATUS_OUT);
-        if (ch->chan.ops->status) {
-            ch->chan.ops->status(&ch->chan, ch->chan.status);
-        }
+  /* Check if there is no credits left clear output status and notify its
+   * change.
+   */
+  if (!k_sem_count_get(&ch->tx.credits)) {
+    atomic_clear_bit(ch->chan.status, BT_L2CAP_STATUS_OUT);
+    if (ch->chan.ops->status) {
+      ch->chan.ops->status(&ch->chan, ch->chan.status);
     }
+  }
 
-    return len;
+  return len;
 }
 
-static int l2cap_chan_le_send_sdu(struct bt_l2cap_le_chan *ch,
-                                  struct net_buf **buf, u16_t sent)
-{
-    int ret, total_len;
-    struct net_buf *frag;
+static int l2cap_chan_le_send_sdu(struct bt_l2cap_le_chan *ch, struct net_buf **buf, u16_t sent) {
+  int             ret, total_len;
+  struct net_buf *frag;
 
-    total_len = net_buf_frags_len(*buf) + sent;
+  total_len = net_buf_frags_len(*buf) + sent;
 
-    if (total_len > ch->tx.mtu) {
-        return -EMSGSIZE;
-    }
+  if (total_len > ch->tx.mtu) {
+    return -EMSGSIZE;
+  }
 
-    frag = *buf;
-    if (!frag->len && frag->frags) {
-        frag = frag->frags;
+  frag = *buf;
+  if (!frag->len && frag->frags) {
+    frag = frag->frags;
+  }
+
+  if (!sent) {
+    /* Add SDU length for the first segment */
+    ret = l2cap_chan_le_send(ch, frag, BT_L2CAP_SDU_HDR_LEN);
+    if (ret < 0) {
+      if (ret == -EAGAIN) {
+        /* Store sent data into user_data */
+        memcpy(net_buf_user_data(frag), &sent, sizeof(sent));
+      }
+      *buf = frag;
+      return ret;
     }
+    sent = ret;
+  }
 
-    if (!sent) {
-        /* Add SDU length for the first segment */
-        ret = l2cap_chan_le_send(ch, frag, BT_L2CAP_SDU_HDR_LEN);
-        if (ret < 0) {
-            if (ret == -EAGAIN) {
-                /* Store sent data into user_data */
-                memcpy(net_buf_user_data(frag), &sent,
-                       sizeof(sent));
-            }
-            *buf = frag;
-            return ret;
-        }
-        sent = ret;
+  /* Send remaining segments */
+  for (ret = 0; sent < total_len; sent += ret) {
+    /* Proceed to next fragment */
+    if (!frag->len) {
+      frag = net_buf_frag_del(NULL, frag);
     }
 
-    /* Send remaining segments */
-    for (ret = 0; sent < total_len; sent += ret) {
-        /* Proceed to next fragment */
-        if (!frag->len) {
-            frag = net_buf_frag_del(NULL, frag);
-        }
-
-        ret = l2cap_chan_le_send(ch, frag, 0);
-        if (ret < 0) {
-            if (ret == -EAGAIN) {
-                /* Store sent data into user_data */
-                memcpy(net_buf_user_data(frag), &sent,
-                       sizeof(sent));
-            }
-            *buf = frag;
-            return ret;
-        }
+    ret = l2cap_chan_le_send(ch, frag, 0);
+    if (ret < 0) {
+      if (ret == -EAGAIN) {
+        /* Store sent data into user_data */
+        memcpy(net_buf_user_data(frag), &sent, sizeof(sent));
+      }
+      *buf = frag;
+      return ret;
     }
+  }
 
-    BT_DBG("ch %p cid 0x%04x sent %u total_len %u", ch, ch->tx.cid, sent,
-           total_len);
+  BT_DBG("ch %p cid 0x%04x sent %u total_len %u", ch, ch->tx.cid, sent, total_len);
 
-    net_buf_unref(frag);
+  net_buf_unref(frag);
 
-    return ret;
+  return ret;
 }
 
-static struct net_buf *l2cap_chan_le_get_tx_buf(struct bt_l2cap_le_chan *ch)
-{
-    struct net_buf *buf;
+static struct net_buf *l2cap_chan_le_get_tx_buf(struct bt_l2cap_le_chan *ch) {
+  struct net_buf *buf;
 
-    /* Return current buffer */
-    if (ch->tx_buf) {
-        buf = ch->tx_buf;
-        ch->tx_buf = NULL;
-        return buf;
-    }
+  /* Return current buffer */
+  if (ch->tx_buf) {
+    buf        = ch->tx_buf;
+    ch->tx_buf = NULL;
+    return buf;
+  }
 
-    return net_buf_get(&ch->tx_queue, K_NO_WAIT);
+  return net_buf_get(&ch->tx_queue, K_NO_WAIT);
 }
 
-static void l2cap_chan_le_send_resume(struct bt_l2cap_le_chan *ch)
-{
-    struct net_buf *buf;
+static void l2cap_chan_le_send_resume(struct bt_l2cap_le_chan *ch) {
+  struct net_buf *buf;
 
-    /* Resume tx in case there are buffers in the queue */
-    while ((buf = l2cap_chan_le_get_tx_buf(ch))) {
+  /* Resume tx in case there are buffers in the queue */
+  while ((buf = l2cap_chan_le_get_tx_buf(ch))) {
 #if defined(BFLB_BLE)
-        int sent = *((int *)net_buf_user_data(buf));
+    int sent = *((int *)net_buf_user_data(buf));
 #else
-        u16_t sent = *((u16_t *)net_buf_user_data(buf));
+    u16_t sent = *((u16_t *)net_buf_user_data(buf));
 #endif
 
-        BT_DBG("buf %p sent %u", buf, sent);
+    BT_DBG("buf %p sent %u", buf, sent);
 
-        sent = l2cap_chan_le_send_sdu(ch, &buf, sent);
-        if (sent < 0) {
-            if (sent == -EAGAIN) {
-                ch->tx_buf = buf;
-            }
-            break;
-        }
+    sent = l2cap_chan_le_send_sdu(ch, &buf, sent);
+    if (sent < 0) {
+      if (sent == -EAGAIN) {
+        ch->tx_buf = buf;
+      }
+      break;
     }
+  }
 }
 
-static void le_credits(struct bt_l2cap *l2cap, u8_t ident,
-                       struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_chan *chan;
-    struct bt_l2cap_le_credits *ev = (void *)buf->data;
-    struct bt_l2cap_le_chan *ch;
-    u16_t credits, cid;
+static void le_credits(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn             *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_chan       *chan;
+  struct bt_l2cap_le_credits *ev = (void *)buf->data;
+  struct bt_l2cap_le_chan    *ch;
+  u16_t                       credits, cid;
 
-    if (buf->len < sizeof(*ev)) {
-        BT_ERR("Too small LE Credits packet size");
-        return;
-    }
+  if (buf->len < sizeof(*ev)) {
+    BT_ERR("Too small LE Credits packet size");
+    return;
+  }
 
-    cid = sys_le16_to_cpu(ev->cid);
-    credits = sys_le16_to_cpu(ev->credits);
+  cid     = sys_le16_to_cpu(ev->cid);
+  credits = sys_le16_to_cpu(ev->credits);
 
-    BT_DBG("cid 0x%04x credits %u", cid, credits);
+  BT_DBG("cid 0x%04x credits %u", cid, credits);
 
-    chan = bt_l2cap_le_lookup_tx_cid(conn, cid);
-    if (!chan) {
-        BT_ERR("Unable to find channel of LE Credits packet");
-        return;
-    }
+  chan = bt_l2cap_le_lookup_tx_cid(conn, cid);
+  if (!chan) {
+    BT_ERR("Unable to find channel of LE Credits packet");
+    return;
+  }
 
-    ch = BT_L2CAP_LE_CHAN(chan);
+  ch = BT_L2CAP_LE_CHAN(chan);
 
-    if (k_sem_count_get(&ch->tx.credits) + credits > UINT16_MAX) {
-        BT_ERR("Credits overflow");
-        bt_l2cap_chan_disconnect(chan);
-        return;
-    }
+  if (k_sem_count_get(&ch->tx.credits) + credits > UINT16_MAX) {
+    BT_ERR("Credits overflow");
+    bt_l2cap_chan_disconnect(chan);
+    return;
+  }
 
-    l2cap_chan_tx_give_credits(ch, credits);
+  l2cap_chan_tx_give_credits(ch, credits);
 
-    BT_DBG("chan %p total credits %u", ch,
-           k_sem_count_get(&ch->tx.credits));
+  BT_DBG("chan %p total credits %u", ch, k_sem_count_get(&ch->tx.credits));
 
-    l2cap_chan_le_send_resume(ch);
+  l2cap_chan_le_send_resume(ch);
 }
 
-static void reject_cmd(struct bt_l2cap *l2cap, u8_t ident,
-                       struct net_buf *buf)
-{
-    struct bt_conn *conn = l2cap->chan.chan.conn;
-    struct bt_l2cap_le_chan *chan;
+static void reject_cmd(struct bt_l2cap *l2cap, u8_t ident, struct net_buf *buf) {
+  struct bt_conn          *conn = l2cap->chan.chan.conn;
+  struct bt_l2cap_le_chan *chan;
 
-    /* Check if there is a outstanding channel */
-    chan = l2cap_remove_ident(conn, ident);
-    if (!chan) {
-        return;
-    }
+  /* Check if there is a outstanding channel */
+  chan = l2cap_remove_ident(conn, ident);
+  if (!chan) {
+    return;
+  }
 
-    bt_l2cap_chan_del(&chan->chan);
+  bt_l2cap_chan_del(&chan->chan);
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-static int l2cap_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_l2cap *l2cap = CONTAINER_OF(chan, struct bt_l2cap, chan);
-    struct bt_l2cap_sig_hdr *hdr;
-    u16_t len;
+static int l2cap_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_l2cap         *l2cap = CONTAINER_OF(chan, struct bt_l2cap, chan);
+  struct bt_l2cap_sig_hdr *hdr;
+  u16_t                    len;
 
-    if (buf->len < sizeof(*hdr)) {
-        BT_ERR("Too small L2CAP signaling PDU");
-        return 0;
-    }
+  if (buf->len < sizeof(*hdr)) {
+    BT_ERR("Too small L2CAP signaling PDU");
+    return 0;
+  }
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    len = sys_le16_to_cpu(hdr->len);
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  len = sys_le16_to_cpu(hdr->len);
 
-    BT_DBG("Signaling code 0x%02x ident %u len %u", hdr->code,
-           hdr->ident, len);
+  BT_DBG("Signaling code 0x%02x ident %u len %u", hdr->code, hdr->ident, len);
 
-    if (buf->len != len) {
-        BT_ERR("L2CAP length mismatch (%u != %u)", buf->len, len);
-        return 0;
-    }
+  if (buf->len != len) {
+    BT_ERR("L2CAP length mismatch (%u != %u)", buf->len, len);
+    return 0;
+  }
 
-    if (!hdr->ident) {
-        BT_ERR("Invalid ident value in L2CAP PDU");
-        return 0;
-    }
+  if (!hdr->ident) {
+    BT_ERR("Invalid ident value in L2CAP PDU");
+    return 0;
+  }
 
-    switch (hdr->code) {
-        case BT_L2CAP_CONN_PARAM_RSP:
-            le_conn_param_rsp(l2cap, buf);
-            break;
+  switch (hdr->code) {
+  case BT_L2CAP_CONN_PARAM_RSP:
+    le_conn_param_rsp(l2cap, buf);
+    break;
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-        case BT_L2CAP_LE_CONN_REQ:
-            le_conn_req(l2cap, hdr->ident, buf);
-            break;
-        case BT_L2CAP_LE_CONN_RSP:
-            le_conn_rsp(l2cap, hdr->ident, buf);
-            break;
-        case BT_L2CAP_DISCONN_REQ:
-            le_disconn_req(l2cap, hdr->ident, buf);
-            break;
-        case BT_L2CAP_DISCONN_RSP:
-            le_disconn_rsp(l2cap, hdr->ident, buf);
-            break;
-        case BT_L2CAP_LE_CREDITS:
-            le_credits(l2cap, hdr->ident, buf);
-            break;
-        case BT_L2CAP_CMD_REJECT:
-            reject_cmd(l2cap, hdr->ident, buf);
-            break;
+  case BT_L2CAP_LE_CONN_REQ:
+    le_conn_req(l2cap, hdr->ident, buf);
+    break;
+  case BT_L2CAP_LE_CONN_RSP:
+    le_conn_rsp(l2cap, hdr->ident, buf);
+    break;
+  case BT_L2CAP_DISCONN_REQ:
+    le_disconn_req(l2cap, hdr->ident, buf);
+    break;
+  case BT_L2CAP_DISCONN_RSP:
+    le_disconn_rsp(l2cap, hdr->ident, buf);
+    break;
+  case BT_L2CAP_LE_CREDITS:
+    le_credits(l2cap, hdr->ident, buf);
+    break;
+  case BT_L2CAP_CMD_REJECT:
+    reject_cmd(l2cap, hdr->ident, buf);
+    break;
 #else
-        case BT_L2CAP_CMD_REJECT:
-            /* Ignored */
-            break;
+  case BT_L2CAP_CMD_REJECT:
+    /* Ignored */
+    break;
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
-        case BT_L2CAP_CONN_PARAM_REQ:
-            if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
-                le_conn_param_update_req(l2cap, hdr->ident, buf);
-                break;
-            }
+  case BT_L2CAP_CONN_PARAM_REQ:
+    if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
+      le_conn_param_update_req(l2cap, hdr->ident, buf);
+      break;
+    }
 #if defined(BFLB_BLE)
-            __attribute__((fallthrough));
+    __attribute__((fallthrough));
 #endif
 
-        /* Fall-through */
-        default:
-            BT_WARN("Unknown L2CAP PDU code 0x%02x", hdr->code);
-            l2cap_send_reject(chan->conn, hdr->ident,
-                              BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0);
-            break;
-    }
+  /* Fall-through */
+  default:
+    BT_WARN("Unknown L2CAP PDU code 0x%02x", hdr->code);
+    l2cap_send_reject(chan->conn, hdr->ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0);
+    break;
+  }
 
-    return 0;
+  return 0;
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static void l2cap_chan_send_credits(struct bt_l2cap_le_chan *chan,
-                                    struct net_buf *buf, u16_t credits)
-{
-    struct bt_l2cap_le_credits *ev;
-
-    /* Cap the number of credits given */
-    if (credits > chan->rx.init_credits) {
-        credits = chan->rx.init_credits;
-    }
+static void l2cap_chan_send_credits(struct bt_l2cap_le_chan *chan, struct net_buf *buf, u16_t credits) {
+  struct bt_l2cap_le_credits *ev;
 
-    l2cap_chan_rx_give_credits(chan, credits);
+  /* Cap the number of credits given */
+  if (credits > chan->rx.init_credits) {
+    credits = chan->rx.init_credits;
+  }
 
-    buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CREDITS, get_ident(),
-                                  sizeof(*ev));
-    if (!buf) {
-        return;
-    }
+  l2cap_chan_rx_give_credits(chan, credits);
+
+  buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CREDITS, get_ident(), sizeof(*ev));
+  if (!buf) {
+    return;
+  }
 
-    ev = net_buf_add(buf, sizeof(*ev));
-    ev->cid = sys_cpu_to_le16(chan->rx.cid);
-    ev->credits = sys_cpu_to_le16(credits);
+  ev          = net_buf_add(buf, sizeof(*ev));
+  ev->cid     = sys_cpu_to_le16(chan->rx.cid);
+  ev->credits = sys_cpu_to_le16(credits);
 
-    bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf);
 
-    BT_DBG("chan %p credits %u", chan, k_sem_count_get(&chan->rx.credits));
+  BT_DBG("chan %p credits %u", chan, k_sem_count_get(&chan->rx.credits));
 }
 
-static void l2cap_chan_update_credits(struct bt_l2cap_le_chan *chan,
-                                      struct net_buf *buf)
-{
-    s16_t credits;
+static void l2cap_chan_update_credits(struct bt_l2cap_le_chan *chan, struct net_buf *buf) {
+  s16_t credits;
 
-    /* Restore enough credits to complete the sdu */
-    credits = ((chan->_sdu_len - net_buf_frags_len(buf)) +
-               (chan->rx.mps - 1)) /
-              chan->rx.mps;
-    credits -= k_sem_count_get(&chan->rx.credits);
-    if (credits <= 0) {
-        return;
-    }
+  /* Restore enough credits to complete the sdu */
+  credits = ((chan->_sdu_len - net_buf_frags_len(buf)) + (chan->rx.mps - 1)) / chan->rx.mps;
+  credits -= k_sem_count_get(&chan->rx.credits);
+  if (credits <= 0) {
+    return;
+  }
 
-    l2cap_chan_send_credits(chan, buf, credits);
+  l2cap_chan_send_credits(chan, buf, credits);
 }
 
-int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
-    struct bt_conn *conn = chan->conn;
-    u16_t credits;
+int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_l2cap_le_chan *ch   = BT_L2CAP_LE_CHAN(chan);
+  struct bt_conn          *conn = chan->conn;
+  u16_t                    credits;
 
-    __ASSERT_NO_MSG(chan);
-    __ASSERT_NO_MSG(buf);
+  __ASSERT_NO_MSG(chan);
+  __ASSERT_NO_MSG(buf);
 
-    if (!conn) {
-        return -ENOTCONN;
-    }
+  if (!conn) {
+    return -ENOTCONN;
+  }
 
-    if (conn->type != BT_CONN_TYPE_LE) {
-        return -ENOTSUP;
-    }
+  if (conn->type != BT_CONN_TYPE_LE) {
+    return -ENOTSUP;
+  }
 
-    BT_DBG("chan %p buf %p", chan, buf);
+  BT_DBG("chan %p buf %p", chan, buf);
 
-    /* Restore credits used by packet */
-    memcpy(&credits, net_buf_user_data(buf), sizeof(credits));
+  /* Restore credits used by packet */
+  memcpy(&credits, net_buf_user_data(buf), sizeof(credits));
 
-    l2cap_chan_send_credits(ch, buf, credits);
+  l2cap_chan_send_credits(ch, buf, credits);
 
-    net_buf_unref(buf);
+  net_buf_unref(buf);
 
-    return 0;
+  return 0;
 }
 
-static struct net_buf *l2cap_alloc_frag(s32_t timeout, void *user_data)
-{
-    struct bt_l2cap_le_chan *chan = user_data;
-    struct net_buf *frag = NULL;
+static struct net_buf *l2cap_alloc_frag(s32_t timeout, void *user_data) {
+  struct bt_l2cap_le_chan *chan = user_data;
+  struct net_buf          *frag = NULL;
 
-    frag = chan->chan.ops->alloc_buf(&chan->chan);
-    if (!frag) {
-        return NULL;
-    }
+  frag = chan->chan.ops->alloc_buf(&chan->chan);
+  if (!frag) {
+    return NULL;
+  }
 
-    BT_DBG("frag %p tailroom %zu", frag, net_buf_tailroom(frag));
+  BT_DBG("frag %p tailroom %zu", frag, net_buf_tailroom(frag));
 
-    return frag;
+  return frag;
 }
 
-static void l2cap_chan_le_recv_sdu(struct bt_l2cap_le_chan *chan,
-                                   struct net_buf *buf, u16_t seg)
-{
-    int err;
+static void l2cap_chan_le_recv_sdu(struct bt_l2cap_le_chan *chan, struct net_buf *buf, u16_t seg) {
+  int err;
 
-    BT_DBG("chan %p len %zu", chan, net_buf_frags_len(buf));
+  BT_DBG("chan %p len %zu", chan, net_buf_frags_len(buf));
 
-    /* Receiving complete SDU, notify channel and reset SDU buf */
-    err = chan->chan.ops->recv(&chan->chan, buf);
-    if (err < 0) {
-        if (err != -EINPROGRESS) {
-            BT_ERR("err %d", err);
-            bt_l2cap_chan_disconnect(&chan->chan);
-            net_buf_unref(buf);
-        }
-        return;
+  /* Receiving complete SDU, notify channel and reset SDU buf */
+  err = chan->chan.ops->recv(&chan->chan, buf);
+  if (err < 0) {
+    if (err != -EINPROGRESS) {
+      BT_ERR("err %d", err);
+      bt_l2cap_chan_disconnect(&chan->chan);
+      net_buf_unref(buf);
     }
+    return;
+  }
 
-    l2cap_chan_send_credits(chan, buf, seg);
-    net_buf_unref(buf);
+  l2cap_chan_send_credits(chan, buf, seg);
+  net_buf_unref(buf);
 }
 
-static void l2cap_chan_le_recv_seg(struct bt_l2cap_le_chan *chan,
-                                   struct net_buf *buf)
-{
-    u16_t len;
-    u16_t seg = 0U;
+static void l2cap_chan_le_recv_seg(struct bt_l2cap_le_chan *chan, struct net_buf *buf) {
+  u16_t len;
+  u16_t seg = 0U;
 
-    len = net_buf_frags_len(chan->_sdu);
-    if (len) {
-        memcpy(&seg, net_buf_user_data(chan->_sdu), sizeof(seg));
-    }
+  len = net_buf_frags_len(chan->_sdu);
+  if (len) {
+    memcpy(&seg, net_buf_user_data(chan->_sdu), sizeof(seg));
+  }
 
-    if (len + buf->len > chan->_sdu_len) {
-        BT_ERR("SDU length mismatch");
-        bt_l2cap_chan_disconnect(&chan->chan);
-        return;
-    }
+  if (len + buf->len > chan->_sdu_len) {
+    BT_ERR("SDU length mismatch");
+    bt_l2cap_chan_disconnect(&chan->chan);
+    return;
+  }
 
-    seg++;
-    /* Store received segments in user_data */
-    memcpy(net_buf_user_data(chan->_sdu), &seg, sizeof(seg));
+  seg++;
+  /* Store received segments in user_data */
+  memcpy(net_buf_user_data(chan->_sdu), &seg, sizeof(seg));
 
-    BT_DBG("chan %p seg %d len %zu", chan, seg, net_buf_frags_len(buf));
+  BT_DBG("chan %p seg %d len %zu", chan, seg, net_buf_frags_len(buf));
 
-    /* Append received segment to SDU */
-    len = net_buf_append_bytes(chan->_sdu, buf->len, buf->data, K_NO_WAIT,
-                               l2cap_alloc_frag, chan);
-    if (len != buf->len) {
-        BT_ERR("Unable to store SDU");
-        bt_l2cap_chan_disconnect(&chan->chan);
-        return;
-    }
+  /* Append received segment to SDU */
+  len = net_buf_append_bytes(chan->_sdu, buf->len, buf->data, K_NO_WAIT, l2cap_alloc_frag, chan);
+  if (len != buf->len) {
+    BT_ERR("Unable to store SDU");
+    bt_l2cap_chan_disconnect(&chan->chan);
+    return;
+  }
 
-    if (net_buf_frags_len(chan->_sdu) < chan->_sdu_len) {
-        /* Give more credits if remote has run out of them, this
-		 * should only happen if the remote cannot fully utilize the
-		 * MPS for some reason.
-		 */
-        if (!k_sem_count_get(&chan->rx.credits) &&
-            seg == chan->rx.init_credits) {
-            l2cap_chan_update_credits(chan, buf);
-        }
-        return;
+  if (net_buf_frags_len(chan->_sdu) < chan->_sdu_len) {
+    /* Give more credits if remote has run out of them, this
+     * should only happen if the remote cannot fully utilize the
+     * MPS for some reason.
+     */
+    if (!k_sem_count_get(&chan->rx.credits) && seg == chan->rx.init_credits) {
+      l2cap_chan_update_credits(chan, buf);
     }
+    return;
+  }
 
-    buf = chan->_sdu;
-    chan->_sdu = NULL;
-    chan->_sdu_len = 0U;
+  buf            = chan->_sdu;
+  chan->_sdu     = NULL;
+  chan->_sdu_len = 0U;
 
-    l2cap_chan_le_recv_sdu(chan, buf, seg);
+  l2cap_chan_le_recv_sdu(chan, buf, seg);
 }
 
-static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan,
-                               struct net_buf *buf)
-{
-    u16_t sdu_len;
-    int err;
-
-    if (k_sem_take(&chan->rx.credits, K_NO_WAIT)) {
-        BT_ERR("No credits to receive packet");
-        bt_l2cap_chan_disconnect(&chan->chan);
-        return;
-    }
+static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan, struct net_buf *buf) {
+  u16_t sdu_len;
+  int   err;
 
-    /* Check if segments already exist */
-    if (chan->_sdu) {
-        l2cap_chan_le_recv_seg(chan, buf);
-        return;
-    }
+  if (k_sem_take(&chan->rx.credits, K_NO_WAIT)) {
+    BT_ERR("No credits to receive packet");
+    bt_l2cap_chan_disconnect(&chan->chan);
+    return;
+  }
 
-    sdu_len = net_buf_pull_le16(buf);
+  /* Check if segments already exist */
+  if (chan->_sdu) {
+    l2cap_chan_le_recv_seg(chan, buf);
+    return;
+  }
 
-    BT_DBG("chan %p len %u sdu_len %u", chan, buf->len, sdu_len);
+  sdu_len = net_buf_pull_le16(buf);
 
-    if (sdu_len > chan->rx.mtu) {
-        BT_ERR("Invalid SDU length");
-        bt_l2cap_chan_disconnect(&chan->chan);
-        return;
-    }
+  BT_DBG("chan %p len %u sdu_len %u", chan, buf->len, sdu_len);
 
-    /* Always allocate buffer from the channel if supported. */
-    if (chan->chan.ops->alloc_buf) {
-        chan->_sdu = chan->chan.ops->alloc_buf(&chan->chan);
-        if (!chan->_sdu) {
-            BT_ERR("Unable to allocate buffer for SDU");
-            bt_l2cap_chan_disconnect(&chan->chan);
-            return;
-        }
-        chan->_sdu_len = sdu_len;
-        l2cap_chan_le_recv_seg(chan, buf);
-        return;
-    }
+  if (sdu_len > chan->rx.mtu) {
+    BT_ERR("Invalid SDU length");
+    bt_l2cap_chan_disconnect(&chan->chan);
+    return;
+  }
 
-    err = chan->chan.ops->recv(&chan->chan, buf);
-    if (err) {
-        if (err != -EINPROGRESS) {
-            BT_ERR("err %d", err);
-            bt_l2cap_chan_disconnect(&chan->chan);
-        }
-        return;
+  /* Always allocate buffer from the channel if supported. */
+  if (chan->chan.ops->alloc_buf) {
+    chan->_sdu = chan->chan.ops->alloc_buf(&chan->chan);
+    if (!chan->_sdu) {
+      BT_ERR("Unable to allocate buffer for SDU");
+      bt_l2cap_chan_disconnect(&chan->chan);
+      return;
+    }
+    chan->_sdu_len = sdu_len;
+    l2cap_chan_le_recv_seg(chan, buf);
+    return;
+  }
+
+  err = chan->chan.ops->recv(&chan->chan, buf);
+  if (err) {
+    if (err != -EINPROGRESS) {
+      BT_ERR("err %d", err);
+      bt_l2cap_chan_disconnect(&chan->chan);
     }
+    return;
+  }
 
-    l2cap_chan_send_credits(chan, buf, 1);
+  l2cap_chan_send_credits(chan, buf, 1);
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-static void l2cap_chan_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
+static void l2cap_chan_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) {
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-    struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
+  struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan);
 
-    if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) {
-        net_buf_put(&ch->rx_queue, net_buf_ref(buf));
-        k_work_submit(&ch->rx_work);
-        return;
-    }
+  if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) {
+    net_buf_put(&ch->rx_queue, net_buf_ref(buf));
+    k_work_submit(&ch->rx_work);
+    return;
+  }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 
-    BT_DBG("chan %p len %u", chan, buf->len);
+  BT_DBG("chan %p len %u", chan, buf->len);
 
-    chan->ops->recv(chan, buf);
-    net_buf_unref(buf);
+  chan->ops->recv(chan, buf);
+  net_buf_unref(buf);
 }
 
-void bt_l2cap_recv(struct bt_conn *conn, struct net_buf *buf)
-{
-    struct bt_l2cap_hdr *hdr;
-    struct bt_l2cap_chan *chan;
-    u16_t cid;
+void bt_l2cap_recv(struct bt_conn *conn, struct net_buf *buf) {
+  struct bt_l2cap_hdr  *hdr;
+  struct bt_l2cap_chan *chan;
+  u16_t                 cid;
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        bt_l2cap_br_recv(conn, buf);
-        return;
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    bt_l2cap_br_recv(conn, buf);
+    return;
+  }
 
-    if (buf->len < sizeof(*hdr)) {
-        BT_ERR("Too small L2CAP PDU received");
-        net_buf_unref(buf);
-        return;
-    }
+  if (buf->len < sizeof(*hdr)) {
+    BT_ERR("Too small L2CAP PDU received");
+    net_buf_unref(buf);
+    return;
+  }
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    cid = sys_le16_to_cpu(hdr->cid);
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  cid = sys_le16_to_cpu(hdr->cid);
 
-    BT_DBG("Packet for CID %u len %u", cid, buf->len);
+  BT_DBG("Packet for CID %u len %u", cid, buf->len);
 
-    chan = bt_l2cap_le_lookup_rx_cid(conn, cid);
-    if (!chan) {
-        BT_WARN("Ignoring data for unknown CID 0x%04x", cid);
-        net_buf_unref(buf);
-        return;
-    }
+  chan = bt_l2cap_le_lookup_rx_cid(conn, cid);
+  if (!chan) {
+    BT_WARN("Ignoring data for unknown CID 0x%04x", cid);
+    net_buf_unref(buf);
+    return;
+  }
 
-    l2cap_chan_recv(chan, buf);
+  l2cap_chan_recv(chan, buf);
 }
 
-int bt_l2cap_update_conn_param(struct bt_conn *conn,
-                               const struct bt_le_conn_param *param)
-{
-    struct bt_l2cap_conn_param_req *req;
-    struct net_buf *buf;
+int bt_l2cap_update_conn_param(struct bt_conn *conn, const struct bt_le_conn_param *param) {
+  struct bt_l2cap_conn_param_req *req;
+  struct net_buf                 *buf;
 
-    buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CONN_PARAM_REQ,
-                                  get_ident(), sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CONN_PARAM_REQ, get_ident(), sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->min_interval = sys_cpu_to_le16(param->interval_min);
-    req->max_interval = sys_cpu_to_le16(param->interval_max);
-    req->latency = sys_cpu_to_le16(param->latency);
-    req->timeout = sys_cpu_to_le16(param->timeout);
+  req               = net_buf_add(buf, sizeof(*req));
+  req->min_interval = sys_cpu_to_le16(param->interval_min);
+  req->max_interval = sys_cpu_to_le16(param->interval_max);
+  req->latency      = sys_cpu_to_le16(param->latency);
+  req->timeout      = sys_cpu_to_le16(param->timeout);
 
-    bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf);
 
-    return 0;
+  return 0;
 }
 
-static void l2cap_connected(struct bt_l2cap_chan *chan)
-{
-    BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan),
-           BT_L2CAP_LE_CHAN(chan)->rx.cid);
-}
+static void l2cap_connected(struct bt_l2cap_chan *chan) { BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), BT_L2CAP_LE_CHAN(chan)->rx.cid); }
 
-static void l2cap_disconnected(struct bt_l2cap_chan *chan)
-{
-    BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan),
-           BT_L2CAP_LE_CHAN(chan)->rx.cid);
-}
+static void l2cap_disconnected(struct bt_l2cap_chan *chan) { BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), BT_L2CAP_LE_CHAN(chan)->rx.cid); }
 
-static int l2cap_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
-{
-    int i;
-    static struct bt_l2cap_chan_ops ops = {
-        .connected = l2cap_connected,
-        .disconnected = l2cap_disconnected,
-        .recv = l2cap_recv,
-    };
+static int l2cap_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) {
+  int                             i;
+  static struct bt_l2cap_chan_ops ops = {
+      .connected    = l2cap_connected,
+      .disconnected = l2cap_disconnected,
+      .recv         = l2cap_recv,
+  };
 
-    BT_DBG("conn %p handle %u", conn, conn->handle);
+  BT_DBG("conn %p handle %u", conn, conn->handle);
 
-    for (i = 0; i < ARRAY_SIZE(bt_l2cap_pool); i++) {
-        struct bt_l2cap *l2cap = &bt_l2cap_pool[i];
+  for (i = 0; i < ARRAY_SIZE(bt_l2cap_pool); i++) {
+    struct bt_l2cap *l2cap = &bt_l2cap_pool[i];
 
-        if (l2cap->chan.chan.conn) {
-            continue;
-        }
+    if (l2cap->chan.chan.conn) {
+      continue;
+    }
 
-        l2cap->chan.chan.ops = &ops;
-        *chan = &l2cap->chan.chan;
+    l2cap->chan.chan.ops = &ops;
+    *chan                = &l2cap->chan.chan;
 
-        return 0;
-    }
+    return 0;
+  }
 
-    BT_ERR("No available L2CAP context for conn %p", conn);
+  BT_ERR("No available L2CAP context for conn %p", conn);
 
-    return -ENOMEM;
+  return -ENOMEM;
 }
 
 BT_L2CAP_CHANNEL_DEFINE(le_fixed_chan, BT_L2CAP_CID_LE_SIG, l2cap_accept);
 
-void bt_l2cap_init(void)
-{
+void bt_l2cap_init(void) {
 #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL)
-    static struct bt_l2cap_fixed_chan chan = {
-        .cid = BT_L2CAP_CID_LE_SIG,
-        .accept = l2cap_accept,
-    };
+  static struct bt_l2cap_fixed_chan chan = {
+      .cid    = BT_L2CAP_CID_LE_SIG,
+      .accept = l2cap_accept,
+  };
 
-    bt_l2cap_le_fixed_chan_register(&chan);
+  bt_l2cap_le_fixed_chan_register(&chan);
 #endif
-    if (IS_ENABLED(CONFIG_BT_BREDR)) {
-        bt_l2cap_br_init();
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR)) {
+    bt_l2cap_br_init();
+  }
 }
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-static int l2cap_le_connect(struct bt_conn *conn, struct bt_l2cap_le_chan *ch,
-                            u16_t psm)
-{
-    if (psm < L2CAP_LE_PSM_FIXED_START || psm > L2CAP_LE_PSM_DYN_END) {
-        return -EINVAL;
-    }
+static int l2cap_le_connect(struct bt_conn *conn, struct bt_l2cap_le_chan *ch, u16_t psm) {
+  if (psm < L2CAP_LE_PSM_FIXED_START || psm > L2CAP_LE_PSM_DYN_END) {
+    return -EINVAL;
+  }
 
-    l2cap_chan_tx_init(ch);
-    l2cap_chan_rx_init(ch);
+  l2cap_chan_tx_init(ch);
+  l2cap_chan_rx_init(ch);
 
-    if (!l2cap_chan_add(conn, &ch->chan, l2cap_chan_destroy)) {
-        return -ENOMEM;
-    }
+  if (!l2cap_chan_add(conn, &ch->chan, l2cap_chan_destroy)) {
+    return -ENOMEM;
+  }
 
-    ch->chan.psm = psm;
+  ch->chan.psm = psm;
 
-    return l2cap_le_conn_req(ch);
+  return l2cap_le_conn_req(ch);
 }
 
-int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan,
-                          u16_t psm)
-{
-    BT_DBG("conn %p chan %p psm 0x%04x", conn, chan, psm);
+int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, u16_t psm) {
+  BT_DBG("conn %p chan %p psm 0x%04x", conn, chan, psm);
 
-    if (!conn || conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (!conn || conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    if (!chan) {
-        return -EINVAL;
-    }
+  if (!chan) {
+    return -EINVAL;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        return bt_l2cap_br_chan_connect(conn, chan, psm);
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    return bt_l2cap_br_chan_connect(conn, chan, psm);
+  }
 
-    if (chan->required_sec_level > BT_SECURITY_L4) {
-        return -EINVAL;
-    } else if (chan->required_sec_level == BT_SECURITY_L0) {
-        chan->required_sec_level = BT_SECURITY_L1;
-    }
+  if (chan->required_sec_level > BT_SECURITY_L4) {
+    return -EINVAL;
+  } else if (chan->required_sec_level == BT_SECURITY_L0) {
+    chan->required_sec_level = BT_SECURITY_L1;
+  }
 
-    return l2cap_le_connect(conn, BT_L2CAP_LE_CHAN(chan), psm);
+  return l2cap_le_connect(conn, BT_L2CAP_LE_CHAN(chan), psm);
 }
 
-int bt_l2cap_chan_disconnect(struct bt_l2cap_chan *chan)
-{
-    struct bt_conn *conn = chan->conn;
-    struct net_buf *buf;
-    struct bt_l2cap_disconn_req *req;
-    struct bt_l2cap_le_chan *ch;
+int bt_l2cap_chan_disconnect(struct bt_l2cap_chan *chan) {
+  struct bt_conn              *conn = chan->conn;
+  struct net_buf              *buf;
+  struct bt_l2cap_disconn_req *req;
+  struct bt_l2cap_le_chan     *ch;
 
-    if (!conn) {
-        return -ENOTCONN;
-    }
+  if (!conn) {
+    return -ENOTCONN;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        conn->type == BT_CONN_TYPE_BR) {
-        return bt_l2cap_br_chan_disconnect(chan);
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && conn->type == BT_CONN_TYPE_BR) {
+    return bt_l2cap_br_chan_disconnect(chan);
+  }
 
-    ch = BT_L2CAP_LE_CHAN(chan);
+  ch = BT_L2CAP_LE_CHAN(chan);
 
-    BT_DBG("chan %p scid 0x%04x dcid 0x%04x", chan, ch->rx.cid,
-           ch->tx.cid);
+  BT_DBG("chan %p scid 0x%04x dcid 0x%04x", chan, ch->rx.cid, ch->tx.cid);
 
-    ch->chan.ident = get_ident();
+  ch->chan.ident = get_ident();
 
-    buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_DISCONN_REQ,
-                                  ch->chan.ident, sizeof(*req));
-    if (!buf) {
-        return -ENOMEM;
-    }
+  buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_DISCONN_REQ, ch->chan.ident, sizeof(*req));
+  if (!buf) {
+    return -ENOMEM;
+  }
 
-    req = net_buf_add(buf, sizeof(*req));
-    req->dcid = sys_cpu_to_le16(ch->rx.cid);
-    req->scid = sys_cpu_to_le16(ch->tx.cid);
+  req       = net_buf_add(buf, sizeof(*req));
+  req->dcid = sys_cpu_to_le16(ch->rx.cid);
+  req->scid = sys_cpu_to_le16(ch->tx.cid);
 
-    l2cap_chan_send_req(ch, buf, L2CAP_DISC_TIMEOUT);
-    bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECT);
+  l2cap_chan_send_req(ch, buf, L2CAP_DISC_TIMEOUT);
+  bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECT);
 
-    return 0;
+  return 0;
 }
 
-int bt_l2cap_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    int err;
+int bt_l2cap_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  int err;
 
-    if (!buf) {
-        return -EINVAL;
-    }
+  if (!buf) {
+    return -EINVAL;
+  }
 
-    BT_DBG("chan %p buf %p len %zu", chan, buf, net_buf_frags_len(buf));
+  BT_DBG("chan %p buf %p len %zu", chan, buf, net_buf_frags_len(buf));
 
-    if (!chan->conn || chan->conn->state != BT_CONN_CONNECTED) {
-        return -ENOTCONN;
-    }
+  if (!chan->conn || chan->conn->state != BT_CONN_CONNECTED) {
+    return -ENOTCONN;
+  }
 
-    if (IS_ENABLED(CONFIG_BT_BREDR) &&
-        chan->conn->type == BT_CONN_TYPE_BR) {
-        return bt_l2cap_br_chan_send(chan, buf);
-    }
+  if (IS_ENABLED(CONFIG_BT_BREDR) && chan->conn->type == BT_CONN_TYPE_BR) {
+    return bt_l2cap_br_chan_send(chan, buf);
+  }
 
-    err = l2cap_chan_le_send_sdu(BT_L2CAP_LE_CHAN(chan), &buf, 0);
-    if (err < 0) {
-        if (err == -EAGAIN) {
-            /* Queue buffer to be sent later */
-            net_buf_put(&(BT_L2CAP_LE_CHAN(chan))->tx_queue, buf);
-            return *((u16_t *)net_buf_user_data(buf));
-        }
-        BT_ERR("failed to send message %d", err);
+  err = l2cap_chan_le_send_sdu(BT_L2CAP_LE_CHAN(chan), &buf, 0);
+  if (err < 0) {
+    if (err == -EAGAIN) {
+      /* Queue buffer to be sent later */
+      net_buf_put(&(BT_L2CAP_LE_CHAN(chan))->tx_queue, buf);
+      return *((u16_t *)net_buf_user_data(buf));
     }
+    BT_ERR("failed to send message %d", err);
+  }
 
-    return err;
+  return err;
 }
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/monitor.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/monitor.c
index af4ee9c2d..e87f9a6ba 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/monitor.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/monitor.c
@@ -9,20 +9,17 @@
  */
 #if defined(CONFIG_BT_DEBUG_MONITOR)
 
-#include 
-#include 
 #include "monitor.h"
 #include "log.h"
+#include 
+#include 
 
-void bt_monitor_send(uint16_t opcode, const void *data, size_t len)
-{
-    const uint8_t *buf = data;
-
-    BT_WARN("[Hci]:pkt_type:[0x%x],pkt_data:[%s]\r\n", opcode, bt_hex(buf, len));
+void bt_monitor_send(uint16_t opcode, const void *data, size_t len) {
+  const uint8_t *buf = data;
+  unsigned int   key = irq_lock();
+  BT_WARN("[Hci]:pkt_type:[0x%x],pkt_data:[%s]\r\n", opcode, bt_hex(buf, len));
+  irq_unlock(key);
 }
 
-void bt_monitor_new_index(uint8_t type, uint8_t bus, bt_addr_t *addr,
-                          const char *name)
-{
-}
+void bt_monitor_new_index(uint8_t type, uint8_t bus, bt_addr_t *addr, const char *name) {}
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c
index 4a1418789..ded6eeb02 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/multi_adv.c
@@ -2,513 +2,486 @@
  * xx
  */
 
-#include 
 #include 
+#include 
 
-//#include 
+// #include 
 #include 
 #include 
 
+#include "log.h"
 #include "multi_adv.h"
 #include "work_q.h"
 
-static struct multi_adv_instant g_multi_adv_list[MAX_MULTI_ADV_INSTANT];
+static struct multi_adv_instant   g_multi_adv_list[MAX_MULTI_ADV_INSTANT];
 static struct multi_adv_scheduler g_multi_adv_scheduler;
-static struct k_delayed_work g_multi_adv_timer;
+static struct k_delayed_work      g_multi_adv_timer;
 
 void multi_adv_schedule_timeslot(struct multi_adv_scheduler *adv_scheduler);
-int multi_adv_schedule_timer_stop(void);
+int  multi_adv_schedule_timer_stop(void);
 
-int multi_adv_get_instant_num(void)
-{
-    int i, num = 0;
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+int multi_adv_get_instant_num(void) {
+  int                       i, num = 0;
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        if (inst[i].inuse_flag)
-            num++;
-    }
-    return num;
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    if (inst[i].inuse_flag)
+      num++;
+  }
+  return num;
 }
 
-struct multi_adv_instant *multi_adv_alloc_unused_instant(void)
-{
-    int i;
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+struct multi_adv_instant *multi_adv_alloc_unused_instant(void) {
+  int                       i;
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        if (inst[i].inuse_flag == 0) {
-            inst[i].inuse_flag = 1;
-            inst[i].instant_id = i + 1;
-            return &(inst[i]);
-        }
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    if (inst[i].inuse_flag == 0) {
+      inst[i].inuse_flag = 1;
+      inst[i].instant_id = i + 1;
+      return &(inst[i]);
     }
-    return 0;
+  }
+  return 0;
 }
 
-int multi_adv_delete_instant_by_id(int instant_id)
-{
-    int i;
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+int multi_adv_delete_instant_by_id(int instant_id) {
+  int                       i;
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
-            inst[i].inuse_flag = 0;
-            return 0;
-        }
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
+      inst[i].inuse_flag = 0;
+      return 0;
     }
-    return -1;
+  }
+  return -1;
 }
 
-struct multi_adv_instant *multi_adv_find_instant_by_id(int instant_id)
-{
-    int i;
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+struct multi_adv_instant *multi_adv_find_instant_by_id(int instant_id) {
+  int                       i;
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
-            return &(inst[i]);
-        }
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
+      return &(inst[i]);
     }
-    return 0;
+  }
+  return 0;
 }
 
-struct multi_adv_instant *multi_adv_find_instant_by_order(int order)
-{
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+struct multi_adv_instant *multi_adv_find_instant_by_order(int order) {
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    if (inst[order].inuse_flag) {
-        return &(inst[order]);
-    }
-    return 0;
+  if (inst[order].inuse_flag) {
+    return &(inst[order]);
+  }
+  return 0;
 }
 
-int multi_adv_set_ad_data(uint8_t *ad_data, const struct bt_data *ad, size_t ad_len)
-{
-    int i, len;
+int multi_adv_set_ad_data(uint8_t *ad_data, const struct bt_data *ad, size_t ad_len) {
+  int i, len;
 
-    memset(ad_data, 0, MAX_AD_DATA_LEN);
-    len = 0;
-    for (i = 0; i < ad_len; i++) {
-        /* Check if ad fit in the remaining buffer */
-        if (len + ad[i].data_len + 2 > MAX_AD_DATA_LEN) {
-            break;
-        }
+  memset(ad_data, 0, MAX_AD_DATA_LEN);
+  len = 0;
+  for (i = 0; i < ad_len; i++) {
+    /* Check if ad fit in the remaining buffer */
+    if (len + ad[i].data_len + 2 > MAX_AD_DATA_LEN) {
+      break;
+    }
 
-        ad_data[len++] = ad[i].data_len + 1;
-        ad_data[len++] = ad[i].type;
+    ad_data[len++] = ad[i].data_len + 1;
+    ad_data[len++] = ad[i].type;
 
-        memcpy(&ad_data[len], ad[i].data, ad[i].data_len);
-        len += ad[i].data_len;
-    }
+    memcpy(&ad_data[len], ad[i].data, ad[i].data_len);
+    len += ad[i].data_len;
+  }
 
-    return len;
+  return len;
 }
 
-int change_to_tick(int min_interval, int max_interval)
-{
-    int tick;
+int change_to_tick(int min_interval, int max_interval) {
+  int tick;
 
-    if (max_interval / SLOT_PER_PERIOD != min_interval / SLOT_PER_PERIOD) {
-        tick = min_interval / SLOT_PER_PERIOD;
-        if (min_interval % SLOT_PER_PERIOD)
-            tick++;
-    } else {
-        tick = min_interval / SLOT_PER_PERIOD;
-    }
-    if (tick <= 1)
-        tick = 1;
+  if (max_interval / SLOT_PER_PERIOD != min_interval / SLOT_PER_PERIOD) {
+    tick = min_interval / SLOT_PER_PERIOD;
+    if (min_interval % SLOT_PER_PERIOD)
+      tick++;
+  } else {
+    tick = min_interval / SLOT_PER_PERIOD;
+  }
+  if (tick <= 1)
+    tick = 1;
 
-    return tick;
+  return tick;
 }
 
-int calculate_min_multi(int a, int b)
-{
-    int x = a, y = b, z;
+int calculate_min_multi(int a, int b) {
+  int x = a, y = b, z;
 
-    while (y != 0) {
-        z = x % y;
-        x = y;
-        y = z;
-    }
+  while (y != 0) {
+    z = x % y;
+    x = y;
+    y = z;
+  }
 
-    return a * b / x;
+  return a * b / x;
 }
 
-void multi_adv_reorder(int inst_num, uint16_t inst_interval[], uint8_t inst_order[])
-{
-    int i, j;
+void multi_adv_reorder(int inst_num, uint16_t inst_interval[], uint8_t inst_order[]) {
+  int i, j;
 
-    for (i = 0; i < inst_num; i++) {
-        int max = inst_interval[0];
-        int max_idx = 0;
-        int temp;
+  for (i = 0; i < inst_num; i++) {
+    int max     = inst_interval[0];
+    int max_idx = 0;
+    int temp;
 
-        for (j = 1; j < inst_num - i; j++) {
-            if (max < inst_interval[j]) {
-                max = inst_interval[j];
-                max_idx = j;
-            }
-        }
+    for (j = 1; j < inst_num - i; j++) {
+      if (max < inst_interval[j]) {
+        max     = inst_interval[j];
+        max_idx = j;
+      }
+    }
 
-        temp = inst_interval[inst_num - i - 1];
-        inst_interval[inst_num - i - 1] = inst_interval[max_idx];
-        inst_interval[max_idx] = temp;
+    temp                            = inst_interval[inst_num - i - 1];
+    inst_interval[inst_num - i - 1] = inst_interval[max_idx];
+    inst_interval[max_idx]          = temp;
 
-        temp = inst_order[inst_num - i - 1];
-        inst_order[inst_num - i - 1] = inst_order[max_idx];
-        inst_order[max_idx] = temp;
-    }
+    temp                         = inst_order[inst_num - i - 1];
+    inst_order[inst_num - i - 1] = inst_order[max_idx];
+    inst_order[max_idx]          = temp;
+  }
 }
 
-int calculate_offset(uint16_t interval[], uint16_t offset[], int num, int duration)
-{
-    int i, j, k, curr_offset = 0;
-    int curr_max_instants, min_max_instants, instants;
-    int offset_range;
-
-    offset_range = interval[num];
-    if (offset_range > duration)
-        offset_range = duration;
-
-    if (num == 0)
-        return 0;
-
-    min_max_instants = 0x7fffffff;
-    /* using 0-interval-1 as offset */
-    for (i = 0; i < offset_range; i++) {
-        curr_max_instants = 0;
-        /* search slot form 0 - duration to get the max instants number */
-        for (j = 0; j < duration; j++) {
-            /* get instant number in each slot */
-            instants = 0;
-            for (k = 0; k < num; k++) {
-                if (j % interval[k] == offset[k]) {
-                    instants++;
-                }
-            }
-            if (j % interval[num] == i)
-                instants++;
-            if (curr_max_instants < instants) {
-                curr_max_instants = instants;
-            }
-        }
+int calculate_offset(uint16_t interval[], uint16_t offset[], int num, int duration) {
+  int i, j, k, curr_offset = 0;
+  int curr_max_instants, min_max_instants, instants;
+  int offset_range;
 
-        /* check if min max instants */
-        if (min_max_instants > curr_max_instants) {
-            min_max_instants = curr_max_instants;
-            curr_offset = i;
-        }
-    }
-    return curr_offset;
-}
+  offset_range = interval[num];
+  if (offset_range > duration)
+    offset_range = duration;
+
+  if (num == 0)
+    return 0;
 
-void multi_adv_schedule_table(int inst_num, uint16_t inst_interval[], uint16_t inst_offset[])
-{
-    int i, min_multi, last_min_multi;
-    /* calculate min multi */
-    last_min_multi = min_multi = inst_interval[0];
-    for (i = 1; i < inst_num; i++) {
-        min_multi = calculate_min_multi(min_multi, inst_interval[i]);
-        if (min_multi > MAX_MIN_MULTI) {
-            min_multi = last_min_multi;
-            break;
+  min_max_instants = 0x7fffffff;
+  /* using 0-interval-1 as offset */
+  for (i = 0; i < offset_range; i++) {
+    curr_max_instants = 0;
+    /* search slot form 0 - duration to get the max instants number */
+    for (j = 0; j < duration; j++) {
+      /* get instant number in each slot */
+      instants = 0;
+      for (k = 0; k < num; k++) {
+        if (j % interval[k] == offset[k]) {
+          instants++;
         }
-        last_min_multi = min_multi;
+      }
+      if (j % interval[num] == i)
+        instants++;
+      if (curr_max_instants < instants) {
+        curr_max_instants = instants;
+      }
     }
 
-    /* offset calcute for schedule just for small interval range */
-    for (i = 0; i < inst_num; i++) {
-        inst_offset[i] = calculate_offset(inst_interval, inst_offset, i, min_multi);
+    /* check if min max instants */
+    if (min_max_instants > curr_max_instants) {
+      min_max_instants = curr_max_instants;
+      curr_offset      = i;
     }
+  }
+  return curr_offset;
 }
 
-int multi_adv_start_adv_instant(struct multi_adv_instant *adv_instant)
-{
-    int ret;
-
-    ret = bt_le_adv_start_instant(&adv_instant->param,
-                                  adv_instant->ad, adv_instant->ad_len,
-                                  adv_instant->sd, adv_instant->sd_len);
-    if (ret) {
-        BT_WARN("adv start instant failed: inst_id %d, err %d\r\n", adv_instant->instant_id, ret);
+void multi_adv_schedule_table(int inst_num, uint16_t inst_interval[], uint16_t inst_offset[]) {
+  int i, min_multi, last_min_multi;
+  /* calculate min multi */
+  last_min_multi = min_multi = inst_interval[0];
+  for (i = 1; i < inst_num; i++) {
+    min_multi = calculate_min_multi(min_multi, inst_interval[i]);
+    if (min_multi > MAX_MIN_MULTI) {
+      min_multi = last_min_multi;
+      break;
     }
-    return ret;
+    last_min_multi = min_multi;
+  }
+
+  /* offset calcute for schedule just for small interval range */
+  for (i = 0; i < inst_num; i++) {
+    inst_offset[i] = calculate_offset(inst_interval, inst_offset, i, min_multi);
+  }
 }
 
-void multi_adv_schedule_timer_handle(void)
-{
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+int multi_adv_start_adv_instant(struct multi_adv_instant *adv_instant) {
+  int ret;
 
-    multi_adv_schedule_timer_stop();
-    if (adv_scheduler->schedule_state == SCHEDULE_STOP)
-        return;
+  ret = bt_le_adv_start_instant(&adv_instant->param, adv_instant->ad, adv_instant->ad_len, adv_instant->sd, adv_instant->sd_len);
+  if (ret) {
+    BT_WARN("adv start instant failed: inst_id %d, err %d\r\n", adv_instant->instant_id, ret);
+  }
+  return ret;
+}
 
-    adv_scheduler->slot_clock = adv_scheduler->next_slot_clock;
-    adv_scheduler->slot_offset = adv_scheduler->next_slot_offset;
+void multi_adv_schedule_timer_handle(void) {
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
 
-    multi_adv_schedule_timeslot(adv_scheduler);
+  multi_adv_schedule_timer_stop();
+  if (adv_scheduler->schedule_state == SCHEDULE_STOP)
     return;
+
+  adv_scheduler->slot_clock  = adv_scheduler->next_slot_clock;
+  adv_scheduler->slot_offset = adv_scheduler->next_slot_offset;
+
+  multi_adv_schedule_timeslot(adv_scheduler);
+  return;
 }
 
-void multi_adv_schedule_timer_callback(struct k_work *timer)
-{
-    multi_adv_schedule_timer_handle();
-    return;
+void multi_adv_schedule_timer_callback(struct k_work *timer) {
+  multi_adv_schedule_timer_handle();
+  return;
 }
 
-int multi_adv_schedule_timer_start(int timeout)
-{
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
-    multi_adv_schedule_timer_stop();
+int multi_adv_schedule_timer_start(int timeout) {
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+  multi_adv_schedule_timer_stop();
 
-    k_delayed_work_submit(&g_multi_adv_timer, timeout);
-    adv_scheduler->schedule_timer_active = 1;
+  k_delayed_work_submit(&g_multi_adv_timer, timeout);
+  adv_scheduler->schedule_timer_active = 1;
 
-    return 1;
+  return 1;
 }
 
-int multi_adv_schedule_timer_stop(void)
-{
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+int multi_adv_schedule_timer_stop(void) {
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
 
-    if (adv_scheduler->schedule_timer_active) {
-        k_delayed_work_cancel(&g_multi_adv_timer);
-        adv_scheduler->schedule_timer_active = 0;
-    }
-    return 0;
+  if (adv_scheduler->schedule_timer_active) {
+    k_delayed_work_cancel(&g_multi_adv_timer);
+    adv_scheduler->schedule_timer_active = 0;
+  }
+  return 0;
 }
 
-void multi_adv_schedule_timeslot(struct multi_adv_scheduler *adv_scheduler)
-{
-    int i, inst_num;
-    int inst_clk, inst_off, match, insts = 0, next_slot, min_next_slot;
-    struct multi_adv_instant *adv_instant;
-    uint16_t inst_interval[MAX_MULTI_ADV_INSTANT];
-    uint16_t inst_offset[MAX_MULTI_ADV_INSTANT];
-    uint8_t inst_order[MAX_MULTI_ADV_INSTANT];
-    uint8_t match_order[MAX_MULTI_ADV_INSTANT];
-
-    inst_num = 0;
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        adv_instant = multi_adv_find_instant_by_order(i);
-        if (adv_instant) {
-            inst_interval[inst_num] = adv_instant->instant_interval;
-            inst_offset[inst_num] = adv_instant->instant_offset;
-            inst_order[inst_num] = i;
-            inst_num++;
-        }
+void multi_adv_schedule_timeslot(struct multi_adv_scheduler *adv_scheduler) {
+  int                       i, inst_num;
+  int                       inst_clk, inst_off, match, insts = 0, next_slot, min_next_slot;
+  struct multi_adv_instant *adv_instant;
+  uint16_t                  inst_interval[MAX_MULTI_ADV_INSTANT];
+  uint16_t                  inst_offset[MAX_MULTI_ADV_INSTANT];
+  uint8_t                   inst_order[MAX_MULTI_ADV_INSTANT];
+  uint8_t                   match_order[MAX_MULTI_ADV_INSTANT];
+
+  inst_num = 0;
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    adv_instant = multi_adv_find_instant_by_order(i);
+    if (adv_instant) {
+      inst_interval[inst_num] = adv_instant->instant_interval;
+      inst_offset[inst_num]   = adv_instant->instant_offset;
+      inst_order[inst_num]    = i;
+      inst_num++;
     }
-
-    inst_clk = adv_scheduler->slot_clock;
-    inst_off = adv_scheduler->slot_offset;
-    match = 0;
-    for (i = 0; i < inst_num; i++) {
-        if ((inst_clk % inst_interval[i]) == inst_offset[i]) {
-            match_order[match] = i;
-            match++;
-        }
+  }
+
+  inst_clk = adv_scheduler->slot_clock;
+  inst_off = adv_scheduler->slot_offset;
+  match    = 0;
+  for (i = 0; i < inst_num; i++) {
+    if ((inst_clk % inst_interval[i]) == inst_offset[i]) {
+      match_order[match] = i;
+      match++;
     }
+  }
 
-    //    BT_DBG("multi_adv_schedule_timeslot, num = %d, match = %d", inst_num, match);
-    if (match) {
-        int offset_per_instant, diff;
-        offset_per_instant = TIME_PRIOD_MS / match;
-        diff = inst_off - (inst_off + offset_per_instant / 2) / offset_per_instant * offset_per_instant; //TODO may be error
+  BT_DBG("multi_adv_schedule_timeslot, num = %d, match = %d", inst_num, match);
+  if (match) {
+    int offset_per_instant, diff;
+    offset_per_instant = TIME_PRIOD_MS / match;
+    diff               = inst_off - (inst_off + offset_per_instant / 2) / offset_per_instant * offset_per_instant; // TODO may be error
 
-        /* means this is the time to start */
-        if (diff <= 2) {
-            insts = (inst_off + offset_per_instant / 2) / offset_per_instant;
+    /* means this is the time to start */
+    if (diff <= 2) {
+      insts = (inst_off + offset_per_instant / 2) / offset_per_instant;
 
-            /* start instant */
-            adv_instant = multi_adv_find_instant_by_order(inst_order[match_order[insts]]);
-            if (adv_instant)
-                multi_adv_start_adv_instant(adv_instant);
-        }
+      /* start instant */
+      adv_instant = multi_adv_find_instant_by_order(inst_order[match_order[insts]]);
+      if (adv_instant)
+        multi_adv_start_adv_instant(adv_instant);
+    }
 
-        /* next instant in the same slot */
-        if (match - insts > 1) {
-            adv_scheduler->next_slot_offset = adv_scheduler->slot_offset + offset_per_instant;
-            adv_scheduler->next_slot_clock = adv_scheduler->slot_clock;
-
-            if ((adv_scheduler->next_slot_offset >= (TIME_PRIOD_MS - 2)) && (adv_scheduler->slot_offset <= (TIME_PRIOD_MS + 2))) {
-                adv_scheduler->next_slot_clock++;
-                adv_scheduler->next_slot_offset = 0;
-            }
-            multi_adv_schedule_timer_start(offset_per_instant);
-            return;
-        }
+    /* next instant in the same slot */
+    if (match - insts > 1) {
+      adv_scheduler->next_slot_offset = adv_scheduler->slot_offset + offset_per_instant;
+      adv_scheduler->next_slot_clock  = adv_scheduler->slot_clock;
+
+      if ((adv_scheduler->next_slot_offset >= (TIME_PRIOD_MS - 2)) && (adv_scheduler->slot_offset <= (TIME_PRIOD_MS + 2))) {
+        adv_scheduler->next_slot_clock++;
+        adv_scheduler->next_slot_offset = 0;
+      }
+      multi_adv_schedule_timer_start(offset_per_instant);
+      return;
     }
+  }
 
-    /* next instant not in the same slot */
-    min_next_slot = 0x7fffffff;
-    for (i = 0; i < inst_num; i++) {
-        if (inst_clk - inst_offset[i] < 0) {
-            match = 0;
-        } else {
-            match = (inst_clk - inst_offset[i]) / inst_interval[i] + 1;
-        }
-        next_slot = match * inst_interval[i] + inst_offset[i];
-        if (next_slot < min_next_slot) {
-            min_next_slot = next_slot;
-        }
+  /* next instant not in the same slot */
+  min_next_slot = 0x7fffffff;
+  for (i = 0; i < inst_num; i++) {
+    if (inst_clk - inst_offset[i] < 0) {
+      match = 0;
+    } else {
+      match = (inst_clk - inst_offset[i]) / inst_interval[i] + 1;
+    }
+    next_slot = match * inst_interval[i] + inst_offset[i];
+    if (next_slot < min_next_slot) {
+      min_next_slot = next_slot;
     }
-    adv_scheduler->next_slot_offset = 0;
-    adv_scheduler->next_slot_clock = min_next_slot;
+  }
+  adv_scheduler->next_slot_offset = 0;
+  adv_scheduler->next_slot_clock  = min_next_slot;
 
-    next_slot = (adv_scheduler->next_slot_clock - adv_scheduler->slot_clock) * TIME_PRIOD_MS + (adv_scheduler->next_slot_offset - adv_scheduler->slot_offset);
-    multi_adv_schedule_timer_start(next_slot);
-    return;
+  next_slot = (adv_scheduler->next_slot_clock - adv_scheduler->slot_clock) * TIME_PRIOD_MS + (adv_scheduler->next_slot_offset - adv_scheduler->slot_offset);
+  multi_adv_schedule_timer_start(next_slot);
+  return;
 }
 
-void multi_adv_schedule_stop(void)
-{
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+void multi_adv_schedule_stop(void) {
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
 
-    multi_adv_schedule_timer_stop();
-    adv_scheduler->schedule_state = SCHEDULE_STOP;
+  multi_adv_schedule_timer_stop();
+  adv_scheduler->schedule_state = SCHEDULE_STOP;
 }
 
-void multi_adv_schedule_start(void)
-{
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+void multi_adv_schedule_start(void) {
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
 
-    /* get all instant and calculate ticks and */
-    if (adv_scheduler->schedule_state == SCHEDULE_START) {
-        multi_adv_schedule_stop();
-    }
+  /* get all instant and calculate ticks and */
+  if (adv_scheduler->schedule_state == SCHEDULE_START) {
+    multi_adv_schedule_stop();
+  }
 
-    /* reinit scheduler */
-    adv_scheduler->slot_clock = 0;
-    adv_scheduler->slot_offset = 0;
-    adv_scheduler->schedule_state = SCHEDULE_START;
-    multi_adv_schedule_timeslot(adv_scheduler);
+  /* reinit scheduler */
+  adv_scheduler->slot_clock     = 0;
+  adv_scheduler->slot_offset    = 0;
+  adv_scheduler->schedule_state = SCHEDULE_START;
+  multi_adv_schedule_timeslot(adv_scheduler);
 }
 
-void multi_adv_new_schedule(void)
-{
-    int i;
-    struct multi_adv_instant *adv_instant, *high_duty_instant;
-    struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
-    uint16_t inst_offset[MAX_MULTI_ADV_INSTANT];
-    uint16_t inst_interval[MAX_MULTI_ADV_INSTANT];
-    uint8_t inst_order[MAX_MULTI_ADV_INSTANT];
-    int inst_num = 0;
-
-    if (adv_scheduler->schedule_state == SCHEDULE_START) {
-        multi_adv_schedule_stop();
-    }
-    /* get all instant and calculate ticks and */
-    high_duty_instant = 0;
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        adv_instant = multi_adv_find_instant_by_order(i);
-        if (adv_instant) {
-            /* if high duty cycle adv found */
-            if (adv_instant->param.interval_min < HIGH_DUTY_CYCLE_INTERVAL) {
-                high_duty_instant = adv_instant;
-                break;
-            }
-
-            inst_interval[inst_num] = change_to_tick(adv_instant->param.interval_min, adv_instant->param.interval_max);
-            inst_order[inst_num] = i;
-            inst_num++;
-        }
+void multi_adv_new_schedule(void) {
+  int                         i;
+  struct multi_adv_instant   *adv_instant, *high_duty_instant;
+  struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler;
+  uint16_t                    inst_offset[MAX_MULTI_ADV_INSTANT];
+  uint16_t                    inst_interval[MAX_MULTI_ADV_INSTANT];
+  uint8_t                     inst_order[MAX_MULTI_ADV_INSTANT];
+  int                         inst_num = 0;
+
+  if (adv_scheduler->schedule_state == SCHEDULE_START) {
+    multi_adv_schedule_stop();
+  }
+  /* get all instant and calculate ticks and */
+  high_duty_instant = 0;
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    adv_instant = multi_adv_find_instant_by_order(i);
+    if (adv_instant) {
+      /* if high duty cycle adv found */
+      if (adv_instant->param.interval_min < HIGH_DUTY_CYCLE_INTERVAL) {
+        high_duty_instant = adv_instant;
+        break;
+      }
+
+      inst_interval[inst_num] = change_to_tick(adv_instant->param.interval_min, adv_instant->param.interval_max);
+      inst_order[inst_num]    = i;
+      inst_num++;
     }
+  }
 
-    if (high_duty_instant) {
-        //BT_WARN("High Duty Cycle Instants, id = %d, interval = %d\n", adv_instant->instant_id, adv_instant->param.interval_min);
-        multi_adv_start_adv_instant(adv_instant);
-        return;
-    }
-
-    /* instant number equal 0 and 1 */
-    if (inst_num == 0) {
-        bt_le_adv_stop();
-        return;
-    }
-    if (inst_num == 1) {
-        adv_instant = multi_adv_find_instant_by_order(inst_order[0]);
-        if (!adv_instant)
-            return;
-        multi_adv_start_adv_instant(adv_instant);
-        return;
-    }
+  if (high_duty_instant) {
+    BT_WARN("High Duty Cycle Instants, id = %d, interval = %d\n", adv_instant->instant_id, adv_instant->param.interval_min);
+    multi_adv_start_adv_instant(adv_instant);
+    return;
+  }
 
-    /* reorder by inst_interval */
-    multi_adv_reorder(inst_num, inst_interval, inst_order);
+  /* instant number equal 0 and 1 */
+  if (inst_num == 0) {
+    bt_le_adv_stop();
+    return;
+  }
+  if (inst_num == 1) {
+    adv_instant = multi_adv_find_instant_by_order(inst_order[0]);
+    if (!adv_instant)
+      return;
+    multi_adv_start_adv_instant(adv_instant);
+    return;
+  }
 
-    /* calcuate schedule table */
-    multi_adv_schedule_table(inst_num, inst_interval, inst_offset);
+  /* reorder by inst_interval */
+  multi_adv_reorder(inst_num, inst_interval, inst_order);
 
-    /* set interval and offset to instant */
-    for (i = 0; i < inst_num; i++) {
-        adv_instant = multi_adv_find_instant_by_order(inst_order[i]);
-        if (!adv_instant) {
-            continue;
-        }
-        adv_instant->instant_interval = inst_interval[i];
-        adv_instant->instant_offset = inst_offset[i];
+  /* calcuate schedule table */
+  multi_adv_schedule_table(inst_num, inst_interval, inst_offset);
 
-        //BT_WARN("adv_instant id = %d, interval = %d, offset = %d\n", adv_instant->instant_id, adv_instant->instant_interval, adv_instant->instant_offset);
+  /* set interval and offset to instant */
+  for (i = 0; i < inst_num; i++) {
+    adv_instant = multi_adv_find_instant_by_order(inst_order[i]);
+    if (!adv_instant) {
+      continue;
     }
+    adv_instant->instant_interval = inst_interval[i];
+    adv_instant->instant_offset   = inst_offset[i];
 
-    multi_adv_schedule_start();
+    BT_WARN("adv_instant id = %d, interval = %d, offset = %d\n", adv_instant->instant_id, adv_instant->instant_interval, adv_instant->instant_offset);
+  }
+
+  multi_adv_schedule_start();
 }
 
-int bt_le_multi_adv_thread_init(void)
-{
-    /* timer and event init */
-    k_delayed_work_init(&g_multi_adv_timer, multi_adv_schedule_timer_callback);
-    return 0;
+int bt_le_multi_adv_thread_init(void) {
+  /* timer and event init */
+  k_delayed_work_init(&g_multi_adv_timer, multi_adv_schedule_timer_callback);
+  return 0;
 }
 
-int bt_le_multi_adv_start(const struct bt_le_adv_param *param,
-                          const struct bt_data *ad, size_t ad_len,
-                          const struct bt_data *sd, size_t sd_len, int *instant_id)
-{
-    int instant_num;
-    struct multi_adv_instant *adv_instant;
+int bt_le_multi_adv_start(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len, const struct bt_data *sd, size_t sd_len, int *instant_id) {
+  int                       instant_num;
+  struct multi_adv_instant *adv_instant;
 
-    instant_num = multi_adv_get_instant_num();
-    if (instant_num >= MAX_MULTI_ADV_INSTANT)
-        return -1;
+  instant_num = multi_adv_get_instant_num();
+  if (instant_num >= MAX_MULTI_ADV_INSTANT)
+    return -1;
 
-    adv_instant = multi_adv_alloc_unused_instant();
-    if (adv_instant == 0)
-        return -1;
+  adv_instant = multi_adv_alloc_unused_instant();
+  if (adv_instant == 0)
+    return -1;
 
-    memcpy(&(adv_instant->param), param, sizeof(struct bt_le_adv_param));
+  memcpy(&(adv_instant->param), param, sizeof(struct bt_le_adv_param));
 
-    adv_instant->ad_len = multi_adv_set_ad_data(adv_instant->ad, ad, ad_len);
-    adv_instant->sd_len = multi_adv_set_ad_data(adv_instant->sd, sd, sd_len);
+  adv_instant->ad_len = multi_adv_set_ad_data(adv_instant->ad, ad, ad_len);
+  adv_instant->sd_len = multi_adv_set_ad_data(adv_instant->sd, sd, sd_len);
 
-    multi_adv_new_schedule();
+  multi_adv_new_schedule();
 
-    *instant_id = adv_instant->instant_id;
-    return 0;
+  *instant_id = adv_instant->instant_id;
+  return 0;
 }
 
-int bt_le_multi_adv_stop(int instant_id)
-{
-    if (multi_adv_find_instant_by_id(instant_id) == 0)
-        return -1;
+int bt_le_multi_adv_stop(int instant_id) {
+  if (multi_adv_find_instant_by_id(instant_id) == 0)
+    return -1;
 
-    //BT_WARN("%s id[%d]\n", __func__, instant_id);
-    multi_adv_delete_instant_by_id(instant_id);
-    multi_adv_new_schedule();
+  BT_WARN("%s id[%d]\n", __func__, instant_id);
+  multi_adv_delete_instant_by_id(instant_id);
+  multi_adv_new_schedule();
 
-    return 0;
+  return 0;
 }
 
-bool bt_le_multi_adv_id_is_vaild(int instant_id)
-{
-    int i;
-    struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
+bool bt_le_multi_adv_id_is_vaild(int instant_id) {
+  int                       i;
+  struct multi_adv_instant *inst = &(g_multi_adv_list[0]);
 
-    for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
-        if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
-            return true;
-        }
+  for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) {
+    if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) {
+      return true;
     }
-    return false;
+  }
+  return false;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c
index 4cebb5bcc..3ed5bbf98 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/sdp.c
@@ -9,9 +9,9 @@
  */
 
 #include 
-#include 
-#include 
 #include 
+#include 
+#include 
 
 #include <../bluetooth/buf.h>
 #include <../bluetooth/sdp.h>
@@ -20,8 +20,8 @@
 #define LOG_MODULE_NAME bt_sdp
 #include "log.h"
 
-#include "hci_core.h"
 #include "conn_internal.h"
+#include "hci_core.h"
 #include "l2cap_internal.h"
 #include "sdp_internal.h"
 
@@ -58,20 +58,19 @@
 #define SDP_INVALID 0xff
 
 struct bt_sdp {
-    struct bt_l2cap_br_chan chan;
-    struct k_fifo partial_resp_queue;
-    /* TODO: Allow more than one pending request */
+  struct bt_l2cap_br_chan chan;
+  struct k_fifo           partial_resp_queue;
+  /* TODO: Allow more than one pending request */
 };
 
 static struct bt_sdp_record *db;
-static uint8_t num_services;
+static uint8_t               num_services;
 
 static struct bt_sdp bt_sdp_pool[CONFIG_BT_MAX_CONN];
 
 /* Pool for outgoing SDP packets */
 #if !defined(BFLB_DYNAMIC_ALLOC_MEM)
-NET_BUF_POOL_FIXED_DEFINE(sdp_pool, CONFIG_BT_MAX_CONN,
-                          BT_L2CAP_BUF_SIZE(SDP_MTU), NULL);
+NET_BUF_POOL_FIXED_DEFINE(sdp_pool, CONFIG_BT_MAX_CONN, BT_L2CAP_BUF_SIZE(SDP_MTU), NULL);
 #else
 struct net_buf_pool sdp_pool;
 #endif
@@ -81,45 +80,45 @@ struct net_buf_pool sdp_pool;
 #define SDP_CLIENT_MTU 64
 
 struct bt_sdp_client {
-    struct bt_l2cap_br_chan chan;
-    /* list of waiting to be resolved UUID params */
-    sys_slist_t reqs;
-    /* required SDP transaction ID */
-    uint16_t tid;
-    /* UUID params holder being now resolved */
-    const struct bt_sdp_discover_params *param;
-    /* PDU continuation state object */
-    struct bt_sdp_pdu_cstate cstate;
-    /* buffer for collecting record data */
-    struct net_buf *rec_buf;
+  struct bt_l2cap_br_chan chan;
+  /* list of waiting to be resolved UUID params */
+  sys_slist_t reqs;
+  /* required SDP transaction ID */
+  uint16_t tid;
+  /* UUID params holder being now resolved */
+  const struct bt_sdp_discover_params *param;
+  /* PDU continuation state object */
+  struct bt_sdp_pdu_cstate cstate;
+  /* buffer for collecting record data */
+  struct net_buf *rec_buf;
 };
 
 static struct bt_sdp_client bt_sdp_client_pool[CONFIG_BT_MAX_CONN];
 
 enum {
-    BT_SDP_ITER_STOP,
-    BT_SDP_ITER_CONTINUE,
+  BT_SDP_ITER_STOP,
+  BT_SDP_ITER_CONTINUE,
 };
 
 struct search_state {
-    uint16_t att_list_size;
-    uint8_t current_svc;
-    uint8_t last_att;
-    bool pkt_full;
+  uint16_t att_list_size;
+  uint8_t  current_svc;
+  uint8_t  last_att;
+  bool     pkt_full;
 };
 
 struct select_attrs_data {
-    struct bt_sdp_record *rec;
-    struct net_buf *rsp_buf;
-    struct bt_sdp *sdp;
-    struct bt_sdp_data_elem_seq *seq;
-    struct search_state *state;
-    uint32_t *filter;
-    uint16_t max_att_len;
-    uint16_t att_list_len;
-    uint8_t cont_state_size;
-    uint8_t num_filters;
-    bool new_service;
+  struct bt_sdp_record        *rec;
+  struct net_buf              *rsp_buf;
+  struct bt_sdp               *sdp;
+  struct bt_sdp_data_elem_seq *seq;
+  struct search_state         *state;
+  uint32_t                    *filter;
+  uint16_t                     max_att_len;
+  uint16_t                     att_list_len;
+  uint8_t                      cont_state_size;
+  uint8_t                      num_filters;
+  bool                         new_service;
 };
 
 /* @typedef bt_sdp_attr_func_t
@@ -132,8 +131,7 @@ struct select_attrs_data {
  *  @return BT_SDP_ITER_CONTINUE if should continue to the next attribute
  *  or BT_SDP_ITER_STOP to stop.
  */
-typedef uint8_t (*bt_sdp_attr_func_t)(struct bt_sdp_attribute *attr,
-                                      uint8_t att_idx, void *user_data);
+typedef uint8_t (*bt_sdp_attr_func_t)(struct bt_sdp_attribute *attr, uint8_t att_idx, void *user_data);
 
 /* @typedef bt_sdp_svc_func_t
  * @brief SDP service record iterator callback.
@@ -144,8 +142,7 @@ typedef uint8_t (*bt_sdp_attr_func_t)(struct bt_sdp_attribute *attr,
  * @return BT_SDP_ITER_CONTINUE if should continue to the next service record
  *  or BT_SDP_ITER_STOP to stop.
  */
-typedef uint8_t (*bt_sdp_svc_func_t)(struct bt_sdp_record *rec,
-                                     void *user_data);
+typedef uint8_t (*bt_sdp_svc_func_t)(struct bt_sdp_record *rec, void *user_data);
 
 /* @brief Callback for SDP connection
  *
@@ -155,17 +152,14 @@ typedef uint8_t (*bt_sdp_svc_func_t)(struct bt_sdp_record *rec,
  *
  *  @return None
  */
-static void bt_sdp_connected(struct bt_l2cap_chan *chan)
-{
-    struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan,
-                                               struct bt_l2cap_br_chan,
-                                               chan);
+static void bt_sdp_connected(struct bt_l2cap_chan *chan) {
+  struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan);
 
-    struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
+  struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
 
-    BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
+  BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
 
-    k_fifo_init(&sdp->partial_resp_queue, 20); //MBHJ
+  k_fifo_init(&sdp->partial_resp_queue, 20); // MBHJ
 }
 
 /** @brief Callback for SDP disconnection
@@ -176,17 +170,14 @@ static void bt_sdp_connected(struct bt_l2cap_chan *chan)
  *
  *  @return None
  */
-static void bt_sdp_disconnected(struct bt_l2cap_chan *chan)
-{
-    struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan,
-                                               struct bt_l2cap_br_chan,
-                                               chan);
+static void bt_sdp_disconnected(struct bt_l2cap_chan *chan) {
+  struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan);
 
-    struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
+  struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
 
-    BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
+  BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid);
 
-    (void)memset(sdp, 0, sizeof(*sdp));
+  (void)memset(sdp, 0, sizeof(*sdp));
 }
 
 /* @brief Creates an SDP PDU
@@ -197,10 +188,7 @@ static void bt_sdp_disconnected(struct bt_l2cap_chan *chan)
  *
  *  @return Pointer to the net_buf buffer
  */
-static struct net_buf *bt_sdp_create_pdu(void)
-{
-    return bt_l2cap_create_pdu(&sdp_pool, sizeof(struct bt_sdp_hdr));
-}
+static struct net_buf *bt_sdp_create_pdu(void) { return bt_l2cap_create_pdu(&sdp_pool, sizeof(struct bt_sdp_hdr)); }
 
 /* @brief Sends out an SDP PDU
  *
@@ -213,18 +201,16 @@ static struct net_buf *bt_sdp_create_pdu(void)
  *
  *  @return None
  */
-static void bt_sdp_send(struct bt_l2cap_chan *chan, struct net_buf *buf,
-                        uint8_t op, uint16_t tid)
-{
-    struct bt_sdp_hdr *hdr;
-    uint16_t param_len = buf->len;
-
-    hdr = net_buf_push(buf, sizeof(struct bt_sdp_hdr));
-    hdr->op_code = op;
-    hdr->tid = tid;
-    hdr->param_len = sys_cpu_to_be16(param_len);
-
-    bt_l2cap_chan_send(chan, buf);
+static void bt_sdp_send(struct bt_l2cap_chan *chan, struct net_buf *buf, uint8_t op, uint16_t tid) {
+  struct bt_sdp_hdr *hdr;
+  uint16_t           param_len = buf->len;
+
+  hdr            = net_buf_push(buf, sizeof(struct bt_sdp_hdr));
+  hdr->op_code   = op;
+  hdr->tid       = tid;
+  hdr->param_len = sys_cpu_to_be16(param_len);
+
+  bt_l2cap_chan_send(chan, buf);
 }
 
 /* @brief Sends an error response PDU
@@ -237,18 +223,16 @@ static void bt_sdp_send(struct bt_l2cap_chan *chan, struct net_buf *buf,
  *
  *  @return None
  */
-static void send_err_rsp(struct bt_l2cap_chan *chan, uint16_t err,
-                         uint16_t tid)
-{
-    struct net_buf *buf;
+static void send_err_rsp(struct bt_l2cap_chan *chan, uint16_t err, uint16_t tid) {
+  struct net_buf *buf;
 
-    BT_DBG("tid %u, error %u", tid, err);
+  BT_DBG("tid %u, error %u", tid, err);
 
-    buf = bt_sdp_create_pdu();
+  buf = bt_sdp_create_pdu();
 
-    net_buf_add_be16(buf, err);
+  net_buf_add_be16(buf, err);
 
-    bt_sdp_send(chan, buf, BT_SDP_ERROR_RSP, tid);
+  bt_sdp_send(chan, buf, BT_SDP_ERROR_RSP, tid);
 }
 
 /* @brief Parses data elements from a net_buf
@@ -262,65 +246,61 @@ static void send_err_rsp(struct bt_l2cap_chan *chan, uint16_t err,
  *
  * @return 0 for success, or relevant error code
  */
-static uint16_t parse_data_elem(struct net_buf *buf,
-                                struct bt_sdp_data_elem *data_elem)
-{
-    uint8_t size_field_len = 0U; /* Space used to accommodate the size */
-
-    if (buf->len < 1) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
-
-    data_elem->type = net_buf_pull_u8(buf);
-
-    switch (data_elem->type & BT_SDP_TYPE_DESC_MASK) {
-        case BT_SDP_UINT8:
-        case BT_SDP_INT8:
-        case BT_SDP_UUID_UNSPEC:
-        case BT_SDP_BOOL:
-            data_elem->data_size = BIT(data_elem->type &
-                                       BT_SDP_SIZE_DESC_MASK);
-            break;
-        case BT_SDP_TEXT_STR_UNSPEC:
-        case BT_SDP_SEQ_UNSPEC:
-        case BT_SDP_ALT_UNSPEC:
-        case BT_SDP_URL_STR_UNSPEC:
-            size_field_len = BIT((data_elem->type & BT_SDP_SIZE_DESC_MASK) -
-                                 BT_SDP_SIZE_INDEX_OFFSET);
-            if (buf->len < size_field_len) {
-                BT_WARN("Malformed packet");
-                return BT_SDP_INVALID_SYNTAX;
-            }
-            switch (size_field_len) {
-                case 1:
-                    data_elem->data_size = net_buf_pull_u8(buf);
-                    break;
-                case 2:
-                    data_elem->data_size = net_buf_pull_be16(buf);
-                    break;
-                case 4:
-                    data_elem->data_size = net_buf_pull_be32(buf);
-                    break;
-                default:
-                    BT_WARN("Invalid size in remote request");
-                    return BT_SDP_INVALID_SYNTAX;
-            }
-            break;
-        default:
-            BT_WARN("Invalid type in remote request");
-            return BT_SDP_INVALID_SYNTAX;
-    }
-
-    if (buf->len < data_elem->data_size) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
-
-    data_elem->total_size = data_elem->data_size + size_field_len + 1;
-    data_elem->data = buf->data;
-
-    return 0;
+static uint16_t parse_data_elem(struct net_buf *buf, struct bt_sdp_data_elem *data_elem) {
+  uint8_t size_field_len = 0U; /* Space used to accommodate the size */
+
+  if (buf->len < 1) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  data_elem->type = net_buf_pull_u8(buf);
+
+  switch (data_elem->type & BT_SDP_TYPE_DESC_MASK) {
+  case BT_SDP_UINT8:
+  case BT_SDP_INT8:
+  case BT_SDP_UUID_UNSPEC:
+  case BT_SDP_BOOL:
+    data_elem->data_size = BIT(data_elem->type & BT_SDP_SIZE_DESC_MASK);
+    break;
+  case BT_SDP_TEXT_STR_UNSPEC:
+  case BT_SDP_SEQ_UNSPEC:
+  case BT_SDP_ALT_UNSPEC:
+  case BT_SDP_URL_STR_UNSPEC:
+    size_field_len = BIT((data_elem->type & BT_SDP_SIZE_DESC_MASK) - BT_SDP_SIZE_INDEX_OFFSET);
+    if (buf->len < size_field_len) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
+    }
+    switch (size_field_len) {
+    case 1:
+      data_elem->data_size = net_buf_pull_u8(buf);
+      break;
+    case 2:
+      data_elem->data_size = net_buf_pull_be16(buf);
+      break;
+    case 4:
+      data_elem->data_size = net_buf_pull_be32(buf);
+      break;
+    default:
+      BT_WARN("Invalid size in remote request");
+      return BT_SDP_INVALID_SYNTAX;
+    }
+    break;
+  default:
+    BT_WARN("Invalid type in remote request");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  if (buf->len < data_elem->data_size) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  data_elem->total_size = data_elem->data_size + size_field_len + 1;
+  data_elem->data       = buf->data;
+
+  return 0;
 }
 
 /* @brief Searches for an UUID within an attribute
@@ -338,70 +318,66 @@ static uint16_t parse_data_elem(struct net_buf *buf,
  * @return Size of the last data element that has been searched
  *  (used in recursion)
  */
-static uint32_t search_uuid(struct bt_sdp_data_elem *elem, struct bt_uuid *uuid,
-                            bool *found, uint8_t nest_level)
-{
-    const uint8_t *cur_elem;
-    uint32_t seq_size, size;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_32 u32;
-        struct bt_uuid_128 u128;
-    } u;
-
-    if (*found) {
-        return 0;
-    }
-
-    /* Limit recursion depth to avoid stack overflows */
-    if (nest_level == SDP_DATA_ELEM_NEST_LEVEL_MAX) {
-        return 0;
-    }
+static uint32_t search_uuid(struct bt_sdp_data_elem *elem, struct bt_uuid *uuid, bool *found, uint8_t nest_level) {
+  const uint8_t *cur_elem;
+  uint32_t       seq_size, size;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_32  u32;
+    struct bt_uuid_128 u128;
+  } u;
+
+  if (*found) {
+    return 0;
+  }
 
-    seq_size = elem->data_size;
-    cur_elem = elem->data;
-
-    if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UUID_UNSPEC) {
-        if (seq_size == 2U) {
-            u.uuid.type = BT_UUID_TYPE_16;
-            u.u16.val = *((uint16_t *)cur_elem);
-            if (!bt_uuid_cmp(&u.uuid, uuid)) {
-                *found = true;
-            }
-        } else if (seq_size == 4U) {
-            u.uuid.type = BT_UUID_TYPE_32;
-            u.u32.val = *((uint32_t *)cur_elem);
-            if (!bt_uuid_cmp(&u.uuid, uuid)) {
-                *found = true;
-            }
-        } else if (seq_size == 16U) {
-            u.uuid.type = BT_UUID_TYPE_128;
-            memcpy(u.u128.val, cur_elem, seq_size);
-            if (!bt_uuid_cmp(&u.uuid, uuid)) {
-                *found = true;
-            }
-        } else {
-            BT_WARN("Invalid UUID size in local database");
-            BT_ASSERT(0);
-        }
+  /* Limit recursion depth to avoid stack overflows */
+  if (nest_level == SDP_DATA_ELEM_NEST_LEVEL_MAX) {
+    return 0;
+  }
+
+  seq_size = elem->data_size;
+  cur_elem = elem->data;
+
+  if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UUID_UNSPEC) {
+    if (seq_size == 2U) {
+      u.uuid.type = BT_UUID_TYPE_16;
+      u.u16.val   = *((uint16_t *)cur_elem);
+      if (!bt_uuid_cmp(&u.uuid, uuid)) {
+        *found = true;
+      }
+    } else if (seq_size == 4U) {
+      u.uuid.type = BT_UUID_TYPE_32;
+      u.u32.val   = *((uint32_t *)cur_elem);
+      if (!bt_uuid_cmp(&u.uuid, uuid)) {
+        *found = true;
+      }
+    } else if (seq_size == 16U) {
+      u.uuid.type = BT_UUID_TYPE_128;
+      memcpy(u.u128.val, cur_elem, seq_size);
+      if (!bt_uuid_cmp(&u.uuid, uuid)) {
+        *found = true;
+      }
+    } else {
+      BT_WARN("Invalid UUID size in local database");
+      BT_ASSERT(0);
     }
+  }
 
-    if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_SEQ_UNSPEC ||
-        (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_ALT_UNSPEC) {
-        do {
-            /* Recursively parse data elements */
-            size = search_uuid((struct bt_sdp_data_elem *)cur_elem,
-                               uuid, found, nest_level + 1);
-            if (*found) {
-                return 0;
-            }
-            cur_elem += sizeof(struct bt_sdp_data_elem);
-            seq_size -= size;
-        } while (seq_size);
-    }
+  if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_SEQ_UNSPEC || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_ALT_UNSPEC) {
+    do {
+      /* Recursively parse data elements */
+      size = search_uuid((struct bt_sdp_data_elem *)cur_elem, uuid, found, nest_level + 1);
+      if (*found) {
+        return 0;
+      }
+      cur_elem += sizeof(struct bt_sdp_data_elem);
+      seq_size -= size;
+    } while (seq_size);
+  }
 
-    return elem->total_size;
+  return elem->total_size;
 }
 
 /* @brief SDP service record iterator.
@@ -414,19 +390,17 @@ static uint32_t search_uuid(struct bt_sdp_data_elem *elem, struct bt_uuid *uuid,
  * @return Pointer to the record where the iterator stopped, or NULL if all
  *  records are covered
  */
-static struct bt_sdp_record *bt_sdp_foreach_svc(bt_sdp_svc_func_t func,
-                                                void *user_data)
-{
-    struct bt_sdp_record *rec = db;
-
-    while (rec) {
-        if (func(rec, user_data) == BT_SDP_ITER_STOP) {
-            break;
-        }
+static struct bt_sdp_record *bt_sdp_foreach_svc(bt_sdp_svc_func_t func, void *user_data) {
+  struct bt_sdp_record *rec = db;
 
-        rec = rec->next;
+  while (rec) {
+    if (func(rec, user_data) == BT_SDP_ITER_STOP) {
+      break;
     }
-    return rec;
+
+    rec = rec->next;
+  }
+  return rec;
 }
 
 /* @brief Inserts a service record into a record pointer list
@@ -438,13 +412,12 @@ static struct bt_sdp_record *bt_sdp_foreach_svc(bt_sdp_svc_func_t func,
  *
  * @return BT_SDP_ITER_CONTINUE to move on to the next record.
  */
-static uint8_t insert_record(struct bt_sdp_record *rec, void *user_data)
-{
-    struct bt_sdp_record **rec_list = user_data;
+static uint8_t insert_record(struct bt_sdp_record *rec, void *user_data) {
+  struct bt_sdp_record **rec_list = user_data;
 
-    rec_list[rec->index] = rec;
+  rec_list[rec->index] = rec;
 
-    return BT_SDP_ITER_CONTINUE;
+  return BT_SDP_ITER_CONTINUE;
 }
 
 /* @brief Looks for matching UUIDs in a list of service records
@@ -460,108 +433,98 @@ static uint8_t insert_record(struct bt_sdp_record *rec, void *user_data)
  *
  * @return 0 for success, or relevant error code
  */
-static uint16_t find_services(struct net_buf *buf,
-                              struct bt_sdp_record **matching_recs)
-{
-    struct bt_sdp_data_elem data_elem;
-    struct bt_sdp_record *record;
-    uint32_t uuid_list_size;
-    uint16_t res;
-    uint8_t att_idx, rec_idx = 0U;
-    bool found;
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 u16;
-        struct bt_uuid_32 u32;
-        struct bt_uuid_128 u128;
-    } u;
-
+static uint16_t find_services(struct net_buf *buf, struct bt_sdp_record **matching_recs) {
+  struct bt_sdp_data_elem data_elem;
+  struct bt_sdp_record   *record;
+  uint32_t                uuid_list_size;
+  uint16_t                res;
+  uint8_t                 att_idx, rec_idx = 0U;
+  bool                    found;
+  union {
+    struct bt_uuid     uuid;
+    struct bt_uuid_16  u16;
+    struct bt_uuid_32  u32;
+    struct bt_uuid_128 u128;
+  } u;
+
+  res = parse_data_elem(buf, &data_elem);
+  if (res) {
+    return res;
+  }
+
+  if (((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_SEQ_UNSPEC) && ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_ALT_UNSPEC)) {
+    BT_WARN("Invalid type %x in service search pattern", data_elem.type);
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  uuid_list_size = data_elem.data_size;
+
+  bt_sdp_foreach_svc(insert_record, matching_recs);
+
+  /* Go over the sequence of UUIDs, and match one UUID at a time */
+  while (uuid_list_size) {
     res = parse_data_elem(buf, &data_elem);
     if (res) {
-        return res;
+      return res;
     }
 
-    if (((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_SEQ_UNSPEC) &&
-        ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_ALT_UNSPEC)) {
-        BT_WARN("Invalid type %x in service search pattern",
-                data_elem.type);
-        return BT_SDP_INVALID_SYNTAX;
+    if ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_UUID_UNSPEC) {
+      BT_WARN("Invalid type %u in service search pattern", data_elem.type);
+      return BT_SDP_INVALID_SYNTAX;
     }
 
-    uuid_list_size = data_elem.data_size;
+    if (buf->len < data_elem.data_size) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
+    }
 
-    bt_sdp_foreach_svc(insert_record, matching_recs);
+    if (data_elem.data_size == 2U) {
+      u.uuid.type = BT_UUID_TYPE_16;
+      u.u16.val   = net_buf_pull_be16(buf);
+    } else if (data_elem.data_size == 4U) {
+      u.uuid.type = BT_UUID_TYPE_32;
+      u.u32.val   = net_buf_pull_be32(buf);
+    } else if (data_elem.data_size == 16U) {
+      u.uuid.type = BT_UUID_TYPE_128;
+      sys_memcpy_swap(u.u128.val, buf->data, data_elem.data_size);
+      net_buf_pull(buf, data_elem.data_size);
+    } else {
+      BT_WARN("Invalid UUID len %u in service search pattern", data_elem.data_size);
+      net_buf_pull(buf, data_elem.data_size);
+    }
 
-    /* Go over the sequence of UUIDs, and match one UUID at a time */
-    while (uuid_list_size) {
-        res = parse_data_elem(buf, &data_elem);
-        if (res) {
-            return res;
-        }
+    uuid_list_size -= data_elem.total_size;
 
-        if ((data_elem.type & BT_SDP_TYPE_DESC_MASK) !=
-            BT_SDP_UUID_UNSPEC) {
-            BT_WARN("Invalid type %u in service search pattern",
-                    data_elem.type);
-            return BT_SDP_INVALID_SYNTAX;
-        }
+    /* Go over the list of services, and look for a service which
+     * doesn't have this UUID
+     */
+    for (rec_idx = 0U; rec_idx < num_services; rec_idx++) {
+      record = matching_recs[rec_idx];
 
-        if (buf->len < data_elem.data_size) {
-            BT_WARN("Malformed packet");
-            return BT_SDP_INVALID_SYNTAX;
-        }
+      if (!record) {
+        continue;
+      }
 
-        if (data_elem.data_size == 2U) {
-            u.uuid.type = BT_UUID_TYPE_16;
-            u.u16.val = net_buf_pull_be16(buf);
-        } else if (data_elem.data_size == 4U) {
-            u.uuid.type = BT_UUID_TYPE_32;
-            u.u32.val = net_buf_pull_be32(buf);
-        } else if (data_elem.data_size == 16U) {
-            u.uuid.type = BT_UUID_TYPE_128;
-            sys_memcpy_swap(u.u128.val, buf->data,
-                            data_elem.data_size);
-            net_buf_pull(buf, data_elem.data_size);
-        } else {
-            BT_WARN("Invalid UUID len %u in service search pattern",
-                    data_elem.data_size);
-            net_buf_pull(buf, data_elem.data_size);
-        }
+      found = false;
 
-        uuid_list_size -= data_elem.total_size;
-
-        /* Go over the list of services, and look for a service which
-		 * doesn't have this UUID
-		 */
-        for (rec_idx = 0U; rec_idx < num_services; rec_idx++) {
-            record = matching_recs[rec_idx];
-
-            if (!record) {
-                continue;
-            }
-
-            found = false;
-
-            /* Search for the UUID in all the attrs of the svc */
-            for (att_idx = 0U; att_idx < record->attr_count;
-                 att_idx++) {
-                search_uuid(&record->attrs[att_idx].val,
-                            &u.uuid, &found, 1);
-                if (found) {
-                    break;
-                }
-            }
-
-            /* Remove the record from the list if it doesn't have
-			 * the UUID
-			 */
-            if (!found) {
-                matching_recs[rec_idx] = NULL;
-            }
+      /* Search for the UUID in all the attrs of the svc */
+      for (att_idx = 0U; att_idx < record->attr_count; att_idx++) {
+        search_uuid(&record->attrs[att_idx].val, &u.uuid, &found, 1);
+        if (found) {
+          break;
         }
+      }
+
+      /* Remove the record from the list if it doesn't have
+       * the UUID
+       */
+      if (!found) {
+        matching_recs[rec_idx] = NULL;
+      }
     }
+  }
 
-    return 0;
+  return 0;
 }
 
 /* @brief Handler for Service Search Request
@@ -574,129 +537,125 @@ static uint16_t find_services(struct net_buf *buf,
  *
  * @return 0 for success, or relevant error code
  */
-static uint16_t sdp_svc_search_req(struct bt_sdp *sdp, struct net_buf *buf,
-                                   uint16_t tid)
-{
-    struct bt_sdp_svc_rsp *rsp;
-    struct net_buf *resp_buf;
-    struct bt_sdp_record *record;
-    struct bt_sdp_record *matching_recs[BT_SDP_MAX_SERVICES];
-    uint16_t max_rec_count, total_recs = 0U, current_recs = 0U, res;
-    uint8_t cont_state_size, cont_state = 0U, idx = 0U, count = 0U;
-    bool pkt_full = false;
-
-    res = find_services(buf, matching_recs);
-    if (res) {
-        /* Error in parsing */
-        return res;
-    }
+static uint16_t sdp_svc_search_req(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid) {
+  struct bt_sdp_svc_rsp *rsp;
+  struct net_buf        *resp_buf;
+  struct bt_sdp_record  *record;
+  struct bt_sdp_record  *matching_recs[BT_SDP_MAX_SERVICES];
+  uint16_t               max_rec_count, total_recs = 0U, current_recs = 0U, res;
+  uint8_t                cont_state_size, cont_state = 0U, idx = 0U, count = 0U;
+  bool                   pkt_full = false;
 
-    if (buf->len < 3) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
+  res = find_services(buf, matching_recs);
+  if (res) {
+    /* Error in parsing */
+    return res;
+  }
 
-    max_rec_count = net_buf_pull_be16(buf);
-    cont_state_size = net_buf_pull_u8(buf);
+  if (buf->len < 3) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
 
-    /* Zero out the matching services beyond max_rec_count */
-    for (idx = 0U; idx < num_services; idx++) {
-        if (count == max_rec_count) {
-            matching_recs[idx] = NULL;
-            continue;
-        }
+  max_rec_count   = net_buf_pull_be16(buf);
+  cont_state_size = net_buf_pull_u8(buf);
 
-        if (matching_recs[idx]) {
-            count++;
-        }
+  /* Zero out the matching services beyond max_rec_count */
+  for (idx = 0U; idx < num_services; idx++) {
+    if (count == max_rec_count) {
+      matching_recs[idx] = NULL;
+      continue;
     }
 
-    /* We send out only SDP_SS_CONT_STATE_SIZE bytes continuation state in
-	 * responses, so expect only SDP_SS_CONT_STATE_SIZE bytes in requests
-	 */
-    if (cont_state_size) {
-        if (cont_state_size != SDP_SS_CONT_STATE_SIZE) {
-            BT_WARN("Invalid cont state size %u", cont_state_size);
-            return BT_SDP_INVALID_CSTATE;
-        }
-
-        if (buf->len < cont_state_size) {
-            BT_WARN("Malformed packet");
-            return BT_SDP_INVALID_SYNTAX;
-        }
+    if (matching_recs[idx]) {
+      count++;
+    }
+  }
 
-        cont_state = net_buf_pull_u8(buf);
-        /* We include total_recs in the continuation state. We calculate
-		 * it once and preserve it across all the partial responses
-		 */
-        total_recs = net_buf_pull_be16(buf);
+  /* We send out only SDP_SS_CONT_STATE_SIZE bytes continuation state in
+   * responses, so expect only SDP_SS_CONT_STATE_SIZE bytes in requests
+   */
+  if (cont_state_size) {
+    if (cont_state_size != SDP_SS_CONT_STATE_SIZE) {
+      BT_WARN("Invalid cont state size %u", cont_state_size);
+      return BT_SDP_INVALID_CSTATE;
     }
 
-    BT_DBG("max_rec_count %u, cont_state %u", max_rec_count, cont_state);
+    if (buf->len < cont_state_size) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
+    }
 
-    resp_buf = bt_sdp_create_pdu();
-    rsp = net_buf_add(resp_buf, sizeof(*rsp));
+    cont_state = net_buf_pull_u8(buf);
+    /* We include total_recs in the continuation state. We calculate
+     * it once and preserve it across all the partial responses
+     */
+    total_recs = net_buf_pull_be16(buf);
+  }
 
-    for (; cont_state < num_services; cont_state++) {
-        record = matching_recs[cont_state];
+  BT_DBG("max_rec_count %u, cont_state %u", max_rec_count, cont_state);
 
-        if (!record) {
-            continue;
-        }
+  resp_buf = bt_sdp_create_pdu();
+  rsp      = net_buf_add(resp_buf, sizeof(*rsp));
 
-        /* Calculate total recs only if it is first packet */
-        if (!cont_state_size) {
-            total_recs++;
-        }
+  for (; cont_state < num_services; cont_state++) {
+    record = matching_recs[cont_state];
 
-        if (pkt_full) {
-            continue;
-        }
+    if (!record) {
+      continue;
+    }
 
-        /* 4 bytes per Service Record Handle */
-        /* 4 bytes for ContinuationState */
-        if ((MIN(SDP_MTU, sdp->chan.tx.mtu) - resp_buf->len) <
-            (4 + 4 + sizeof(struct bt_sdp_hdr))) {
-            pkt_full = true;
-        }
+    /* Calculate total recs only if it is first packet */
+    if (!cont_state_size) {
+      total_recs++;
+    }
 
-        if (pkt_full) {
-            /* Packet exhausted: Add continuation state and break */
-            BT_DBG("Packet full, num_services_covered %u",
-                   cont_state);
-            net_buf_add_u8(resp_buf, SDP_SS_CONT_STATE_SIZE);
-            net_buf_add_u8(resp_buf, cont_state);
-
-            /* If it is the first packet of a partial response,
-			 * continue dry-running to calculate total_recs.
-			 * Else break
-			 */
-            if (cont_state_size) {
-                break;
-            }
-
-            continue;
-        }
+    if (pkt_full) {
+      continue;
+    }
 
-        /* Add the service record handle to the packet */
-        net_buf_add_be32(resp_buf, record->handle);
-        current_recs++;
+    /* 4 bytes per Service Record Handle */
+    /* 4 bytes for ContinuationState */
+    if ((MIN(SDP_MTU, sdp->chan.tx.mtu) - resp_buf->len) < (4 + 4 + sizeof(struct bt_sdp_hdr))) {
+      pkt_full = true;
     }
 
-    /* Add 0 continuation state if packet is exhausted */
-    if (!pkt_full) {
-        net_buf_add_u8(resp_buf, 0);
-    } else {
-        net_buf_add_be16(resp_buf, total_recs);
+    if (pkt_full) {
+      /* Packet exhausted: Add continuation state and break */
+      BT_DBG("Packet full, num_services_covered %u", cont_state);
+      net_buf_add_u8(resp_buf, SDP_SS_CONT_STATE_SIZE);
+      net_buf_add_u8(resp_buf, cont_state);
+
+      /* If it is the first packet of a partial response,
+       * continue dry-running to calculate total_recs.
+       * Else break
+       */
+      if (cont_state_size) {
+        break;
+      }
+
+      continue;
     }
 
-    rsp->total_recs = sys_cpu_to_be16(total_recs);
-    rsp->current_recs = sys_cpu_to_be16(current_recs);
+    /* Add the service record handle to the packet */
+    net_buf_add_be32(resp_buf, record->handle);
+    current_recs++;
+  }
 
-    BT_DBG("Sending response, len %u", resp_buf->len);
-    bt_sdp_send(&sdp->chan.chan, resp_buf, BT_SDP_SVC_SEARCH_RSP, tid);
+  /* Add 0 continuation state if packet is exhausted */
+  if (!pkt_full) {
+    net_buf_add_u8(resp_buf, 0);
+  } else {
+    net_buf_add_be16(resp_buf, total_recs);
+  }
 
-    return 0;
+  rsp->total_recs   = sys_cpu_to_be16(total_recs);
+  rsp->current_recs = sys_cpu_to_be16(current_recs);
+
+  BT_DBG("Sending response, len %u", resp_buf->len);
+  bt_sdp_send(&sdp->chan.chan, resp_buf, BT_SDP_SVC_SEARCH_RSP, tid);
+
+  return 0;
 }
 
 /* @brief Copies an attribute into an outgoing buffer
@@ -710,66 +669,59 @@ static uint16_t sdp_svc_search_req(struct bt_sdp *sdp, struct net_buf *buf,
  *  @return Size of the last data element that has been searched
  *  (used in recursion)
  */
-static uint32_t copy_attribute(struct bt_sdp_data_elem *elem,
-                               struct net_buf *buf, uint8_t nest_level)
-{
-    const uint8_t *cur_elem;
-    uint32_t size, seq_size, total_size;
-
-    /* Limit recursion depth to avoid stack overflows */
-    if (nest_level == SDP_DATA_ELEM_NEST_LEVEL_MAX) {
-        return 0;
-    }
+static uint32_t copy_attribute(struct bt_sdp_data_elem *elem, struct net_buf *buf, uint8_t nest_level) {
+  const uint8_t *cur_elem;
+  uint32_t       size, seq_size, total_size;
 
-    seq_size = elem->data_size;
-    total_size = elem->total_size;
-    cur_elem = elem->data;
-
-    /* Copy the header */
-    net_buf_add_u8(buf, elem->type);
-
-    switch (total_size - (seq_size + 1U)) {
-        case 1:
-            net_buf_add_u8(buf, elem->data_size);
-            break;
-        case 2:
-            net_buf_add_be16(buf, elem->data_size);
-            break;
-        case 4:
-            net_buf_add_be32(buf, elem->data_size);
-            break;
-    }
-
-    /* Recursively parse (till the last element is not another data element)
-	 * and then fill the elements
-	 */
-    if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_SEQ_UNSPEC ||
-        (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_ALT_UNSPEC) {
-        do {
-            size = copy_attribute((struct bt_sdp_data_elem *)
-                                      cur_elem,
-                                  buf, nest_level + 1);
-            cur_elem += sizeof(struct bt_sdp_data_elem);
-            seq_size -= size;
-        } while (seq_size);
-    } else if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UINT8 ||
-               (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_INT8 ||
-               (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UUID_UNSPEC) {
-        if (seq_size == 1U) {
-            net_buf_add_u8(buf, *((uint8_t *)elem->data));
-        } else if (seq_size == 2U) {
-            net_buf_add_be16(buf, *((uint16_t *)elem->data));
-        } else if (seq_size == 4U) {
-            net_buf_add_be32(buf, *((uint32_t *)elem->data));
-        } else {
-            /* TODO: Convert 32bit and 128bit values to big-endian*/
-            net_buf_add_mem(buf, elem->data, seq_size);
-        }
+  /* Limit recursion depth to avoid stack overflows */
+  if (nest_level == SDP_DATA_ELEM_NEST_LEVEL_MAX) {
+    return 0;
+  }
+
+  seq_size   = elem->data_size;
+  total_size = elem->total_size;
+  cur_elem   = elem->data;
+
+  /* Copy the header */
+  net_buf_add_u8(buf, elem->type);
+
+  switch (total_size - (seq_size + 1U)) {
+  case 1:
+    net_buf_add_u8(buf, elem->data_size);
+    break;
+  case 2:
+    net_buf_add_be16(buf, elem->data_size);
+    break;
+  case 4:
+    net_buf_add_be32(buf, elem->data_size);
+    break;
+  }
+
+  /* Recursively parse (till the last element is not another data element)
+   * and then fill the elements
+   */
+  if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_SEQ_UNSPEC || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_ALT_UNSPEC) {
+    do {
+      size = copy_attribute((struct bt_sdp_data_elem *)cur_elem, buf, nest_level + 1);
+      cur_elem += sizeof(struct bt_sdp_data_elem);
+      seq_size -= size;
+    } while (seq_size);
+  } else if ((elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UINT8 || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_INT8 || (elem->type & BT_SDP_TYPE_DESC_MASK) == BT_SDP_UUID_UNSPEC) {
+    if (seq_size == 1U) {
+      net_buf_add_u8(buf, *((uint8_t *)elem->data));
+    } else if (seq_size == 2U) {
+      net_buf_add_be16(buf, *((uint16_t *)elem->data));
+    } else if (seq_size == 4U) {
+      net_buf_add_be32(buf, *((uint32_t *)elem->data));
     } else {
-        net_buf_add_mem(buf, elem->data, seq_size);
+      /* TODO: Convert 32bit and 128bit values to big-endian*/
+      net_buf_add_mem(buf, elem->data, seq_size);
     }
+  } else {
+    net_buf_add_mem(buf, elem->data, seq_size);
+  }
 
-    return total_size;
+  return total_size;
 }
 
 /* @brief SDP attribute iterator.
@@ -783,17 +735,14 @@ static uint32_t copy_attribute(struct bt_sdp_data_elem *elem,
  *
  *  @return Index of the attribute where the iterator stopped
  */
-static uint8_t bt_sdp_foreach_attr(struct bt_sdp_record *record, uint8_t idx,
-                                   bt_sdp_attr_func_t func, void *user_data)
-{
-    for (; idx < record->attr_count; idx++) {
-        if (func(&record->attrs[idx], idx, user_data) ==
-            BT_SDP_ITER_STOP) {
-            break;
-        }
+static uint8_t bt_sdp_foreach_attr(struct bt_sdp_record *record, uint8_t idx, bt_sdp_attr_func_t func, void *user_data) {
+  for (; idx < record->attr_count; idx++) {
+    if (func(&record->attrs[idx], idx, user_data) == BT_SDP_ITER_STOP) {
+      break;
     }
+  }
 
-    return idx;
+  return idx;
 }
 
 /* @brief Check if an attribute matches a range, and include it in the response
@@ -809,114 +758,105 @@ static uint8_t bt_sdp_foreach_attr(struct bt_sdp_record *record, uint8_t idx,
  *  @return BT_SDP_ITER_CONTINUE if should continue to the next attribute
  *   or BT_SDP_ITER_STOP to stop.
  */
-static uint8_t select_attrs(struct bt_sdp_attribute *attr, uint8_t att_idx,
-                            void *user_data)
-{
-    struct select_attrs_data *sad = user_data;
-    uint16_t att_id_lower, att_id_upper, att_id_cur, space;
-    uint32_t attr_size, seq_size;
-    uint8_t idx_filter;
-
-    for (idx_filter = 0U; idx_filter < sad->num_filters; idx_filter++) {
-        att_id_lower = (sad->filter[idx_filter] >> 16);
-        att_id_upper = (sad->filter[idx_filter]);
-        att_id_cur = attr->id;
-
-        /* Check for range values */
-        if (att_id_lower != 0xffff &&
-            (!IN_RANGE(att_id_cur, att_id_lower, att_id_upper))) {
-            continue;
-        }
+static uint8_t select_attrs(struct bt_sdp_attribute *attr, uint8_t att_idx, void *user_data) {
+  struct select_attrs_data *sad = user_data;
+  uint16_t                  att_id_lower, att_id_upper, att_id_cur, space;
+  uint32_t                  attr_size, seq_size;
+  uint8_t                   idx_filter;
 
-        /* Check for match values */
-        if (att_id_lower == 0xffff && att_id_cur != att_id_upper) {
-            continue;
-        }
+  for (idx_filter = 0U; idx_filter < sad->num_filters; idx_filter++) {
+    att_id_lower = (sad->filter[idx_filter] >> 16);
+    att_id_upper = (sad->filter[idx_filter]);
+    att_id_cur   = attr->id;
 
-        /* Attribute ID matches */
-
-        /* 3 bytes for Attribute ID */
-        attr_size = 3 + attr->val.total_size;
-
-        /* If this is the first attribute of the service, then we need
-		 * to account for the space required to add the per-service
-		 * data element sequence header as well.
-		 */
-        if ((sad->state->current_svc != sad->rec->index) &&
-            sad->new_service) {
-            /* 3 bytes for Per-Service Data Elem Seq declaration */
-            seq_size = attr_size + 3;
-        } else {
-            seq_size = attr_size;
-        }
+    /* Check for range values */
+    if (att_id_lower != 0xffff && (!IN_RANGE(att_id_cur, att_id_lower, att_id_upper))) {
+      continue;
+    }
 
-        if (sad->rsp_buf) {
-            space = MIN(SDP_MTU, sad->sdp->chan.tx.mtu) -
-                    sad->rsp_buf->len - sizeof(struct bt_sdp_hdr);
+    /* Check for match values */
+    if (att_id_lower == 0xffff && att_id_cur != att_id_upper) {
+      continue;
+    }
 
-            if ((!sad->state->pkt_full) &&
-                ((seq_size > sad->max_att_len) ||
-                 (space < seq_size + sad->cont_state_size))) {
-                /* Packet exhausted */
-                sad->state->pkt_full = true;
-            }
-        }
+    /* Attribute ID matches */
 
-        /* Keep filling data only if packet is not exhausted */
-        if (!sad->state->pkt_full && sad->rsp_buf) {
-            /* Add Per-Service Data Element Seq declaration once
-			 * only when we are starting from the first attribute
-			 */
-            if (!sad->seq &&
-                (sad->state->current_svc != sad->rec->index)) {
-                sad->seq = net_buf_add(sad->rsp_buf,
-                                       sizeof(*sad->seq));
-                sad->seq->type = BT_SDP_SEQ16;
-                sad->seq->size = 0U;
-            }
-
-            /* Add attribute ID */
-            net_buf_add_u8(sad->rsp_buf, BT_SDP_UINT16);
-            net_buf_add_be16(sad->rsp_buf, att_id_cur);
-
-            /* Add attribute value */
-            copy_attribute(&attr->val, sad->rsp_buf, 1);
-
-            sad->max_att_len -= seq_size;
-            sad->att_list_len += seq_size;
-            sad->state->last_att = att_idx;
-            sad->state->current_svc = sad->rec->index;
-        }
+    /* 3 bytes for Attribute ID */
+    attr_size = 3 + attr->val.total_size;
 
-        if (sad->seq) {
-            /* Keep adding the sequence size if this packet contains
-			 * the Per-Service Data Element Seq declaration header
-			 */
-            sad->seq->size += attr_size;
-            sad->state->att_list_size += seq_size;
-        } else {
-            /* Keep adding the total attr lists size if:
-			 * It's a dry-run, calculating the total attr lists size
-			 */
-            sad->state->att_list_size += seq_size;
-        }
+    /* If this is the first attribute of the service, then we need
+     * to account for the space required to add the per-service
+     * data element sequence header as well.
+     */
+    if ((sad->state->current_svc != sad->rec->index) && sad->new_service) {
+      /* 3 bytes for Per-Service Data Elem Seq declaration */
+      seq_size = attr_size + 3;
+    } else {
+      seq_size = attr_size;
+    }
 
-        sad->new_service = false;
-        break;
+    if (sad->rsp_buf) {
+      space = MIN(SDP_MTU, sad->sdp->chan.tx.mtu) - sad->rsp_buf->len - sizeof(struct bt_sdp_hdr);
+
+      if ((!sad->state->pkt_full) && ((seq_size > sad->max_att_len) || (space < seq_size + sad->cont_state_size))) {
+        /* Packet exhausted */
+        sad->state->pkt_full = true;
+      }
     }
 
-    /* End the search if:
-	 * 1. We have exhausted the packet
-	 * AND
-	 * 2. This packet doesn't contain the service element declaration header
-	 * AND
-	 * 3. This is not a dry-run (then we look for other attrs that match)
-	 */
-    if (sad->state->pkt_full && !sad->seq && sad->rsp_buf) {
-        return BT_SDP_ITER_STOP;
+    /* Keep filling data only if packet is not exhausted */
+    if (!sad->state->pkt_full && sad->rsp_buf) {
+      /* Add Per-Service Data Element Seq declaration once
+       * only when we are starting from the first attribute
+       */
+      if (!sad->seq && (sad->state->current_svc != sad->rec->index)) {
+        sad->seq       = net_buf_add(sad->rsp_buf, sizeof(*sad->seq));
+        sad->seq->type = BT_SDP_SEQ16;
+        sad->seq->size = 0U;
+      }
+
+      /* Add attribute ID */
+      net_buf_add_u8(sad->rsp_buf, BT_SDP_UINT16);
+      net_buf_add_be16(sad->rsp_buf, att_id_cur);
+
+      /* Add attribute value */
+      copy_attribute(&attr->val, sad->rsp_buf, 1);
+
+      sad->max_att_len -= seq_size;
+      sad->att_list_len += seq_size;
+      sad->state->last_att    = att_idx;
+      sad->state->current_svc = sad->rec->index;
     }
 
-    return BT_SDP_ITER_CONTINUE;
+    if (sad->seq) {
+      /* Keep adding the sequence size if this packet contains
+       * the Per-Service Data Element Seq declaration header
+       */
+      sad->seq->size += attr_size;
+      sad->state->att_list_size += seq_size;
+    } else {
+      /* Keep adding the total attr lists size if:
+       * It's a dry-run, calculating the total attr lists size
+       */
+      sad->state->att_list_size += seq_size;
+    }
+
+    sad->new_service = false;
+    break;
+  }
+
+  /* End the search if:
+   * 1. We have exhausted the packet
+   * AND
+   * 2. This packet doesn't contain the service element declaration header
+   * AND
+   * 3. This is not a dry-run (then we look for other attrs that match)
+   */
+  if (sad->state->pkt_full && !sad->seq && sad->rsp_buf) {
+    return BT_SDP_ITER_STOP;
+  }
+
+  return BT_SDP_ITER_CONTINUE;
 }
 
 /* @brief Creates attribute list in the given buffer
@@ -938,34 +878,30 @@ static uint8_t select_attrs(struct bt_sdp_attribute *attr, uint8_t att_idx,
  *
  *  @return len Length of the attribute list created
  */
-static uint16_t create_attr_list(struct bt_sdp *sdp, struct bt_sdp_record *record,
-                                 uint32_t *filter, uint8_t num_filters,
-                                 uint16_t max_att_len, uint8_t cont_state_size,
-                                 uint8_t next_att, struct search_state *state,
-                                 struct net_buf *rsp_buf)
-{
-    struct select_attrs_data sad;
-    uint8_t idx_att;
-
-    sad.num_filters = num_filters;
-    sad.rec = record;
-    sad.rsp_buf = rsp_buf;
-    sad.sdp = sdp;
-    sad.max_att_len = max_att_len;
-    sad.cont_state_size = cont_state_size;
-    sad.seq = NULL;
-    sad.filter = filter;
-    sad.state = state;
-    sad.att_list_len = 0U;
-    sad.new_service = true;
-
-    idx_att = bt_sdp_foreach_attr(sad.rec, next_att, select_attrs, &sad);
-
-    if (sad.seq) {
-        sad.seq->size = sys_cpu_to_be16(sad.seq->size);
-    }
-
-    return sad.att_list_len;
+static uint16_t create_attr_list(struct bt_sdp *sdp, struct bt_sdp_record *record, uint32_t *filter, uint8_t num_filters, uint16_t max_att_len, uint8_t cont_state_size, uint8_t next_att,
+                                 struct search_state *state, struct net_buf *rsp_buf) {
+  struct select_attrs_data sad;
+  uint8_t                  idx_att;
+
+  sad.num_filters     = num_filters;
+  sad.rec             = record;
+  sad.rsp_buf         = rsp_buf;
+  sad.sdp             = sdp;
+  sad.max_att_len     = max_att_len;
+  sad.cont_state_size = cont_state_size;
+  sad.seq             = NULL;
+  sad.filter          = filter;
+  sad.state           = state;
+  sad.att_list_len    = 0U;
+  sad.new_service     = true;
+
+  idx_att = bt_sdp_foreach_attr(sad.rec, next_att, select_attrs, &sad);
+
+  if (sad.seq) {
+    sad.seq->size = sys_cpu_to_be16(sad.seq->size);
+  }
+
+  return sad.att_list_len;
 }
 
 /* @brief Extracts the attribute search list from a buffer
@@ -982,53 +918,49 @@ static uint16_t create_attr_list(struct bt_sdp *sdp, struct bt_sdp_record *recor
  *
  *  @return 0 for success, or relevant error code
  */
-static uint16_t get_att_search_list(struct net_buf *buf, uint32_t *filter,
-                                    uint8_t *num_filters)
-{
-    struct bt_sdp_data_elem data_elem;
-    uint16_t res;
-    uint32_t size;
-
-    *num_filters = 0U;
-    res = parse_data_elem(buf, &data_elem);
-    if (res) {
-        return res;
-    }
+static uint16_t get_att_search_list(struct net_buf *buf, uint32_t *filter, uint8_t *num_filters) {
+  struct bt_sdp_data_elem data_elem;
+  uint16_t                res;
+  uint32_t                size;
 
-    size = data_elem.data_size;
+  *num_filters = 0U;
+  res          = parse_data_elem(buf, &data_elem);
+  if (res) {
+    return res;
+  }
 
-    while (size) {
-        res = parse_data_elem(buf, &data_elem);
-        if (res) {
-            return res;
-        }
+  size = data_elem.data_size;
 
-        if ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_UINT8) {
-            BT_WARN("Invalid type %u in attribute ID list",
-                    data_elem.type);
-            return BT_SDP_INVALID_SYNTAX;
-        }
+  while (size) {
+    res = parse_data_elem(buf, &data_elem);
+    if (res) {
+      return res;
+    }
 
-        if (buf->len < data_elem.data_size) {
-            BT_WARN("Malformed packet");
-            return BT_SDP_INVALID_SYNTAX;
-        }
+    if ((data_elem.type & BT_SDP_TYPE_DESC_MASK) != BT_SDP_UINT8) {
+      BT_WARN("Invalid type %u in attribute ID list", data_elem.type);
+      return BT_SDP_INVALID_SYNTAX;
+    }
 
-        /* This is an attribute ID */
-        if (data_elem.data_size == 2U) {
-            filter[(*num_filters)++] = 0xffff0000 |
-                                       net_buf_pull_be16(buf);
-        }
+    if (buf->len < data_elem.data_size) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
+    }
 
-        /* This is an attribute ID range */
-        if (data_elem.data_size == 4U) {
-            filter[(*num_filters)++] = net_buf_pull_be32(buf);
-        }
+    /* This is an attribute ID */
+    if (data_elem.data_size == 2U) {
+      filter[(*num_filters)++] = 0xffff0000 | net_buf_pull_be16(buf);
+    }
 
-        size -= data_elem.total_size;
+    /* This is an attribute ID range */
+    if (data_elem.data_size == 4U) {
+      filter[(*num_filters)++] = net_buf_pull_be32(buf);
     }
 
-    return 0;
+    size -= data_elem.total_size;
+  }
+
+  return 0;
 }
 
 /* @brief Check if a given handle matches that of the current service
@@ -1041,15 +973,14 @@ static uint16_t get_att_search_list(struct net_buf *buf, uint32_t *filter,
  *  @return BT_SDP_ITER_CONTINUE if should continue to the next record
  *   or BT_SDP_ITER_STOP to stop.
  */
-static uint8_t find_handle(struct bt_sdp_record *rec, void *user_data)
-{
-    uint32_t *svc_rec_hdl = user_data;
+static uint8_t find_handle(struct bt_sdp_record *rec, void *user_data) {
+  uint32_t *svc_rec_hdl = user_data;
 
-    if (rec->handle == *svc_rec_hdl) {
-        return BT_SDP_ITER_STOP;
-    }
+  if (rec->handle == *svc_rec_hdl) {
+    return BT_SDP_ITER_STOP;
+  }
 
-    return BT_SDP_ITER_CONTINUE;
+  return BT_SDP_ITER_CONTINUE;
 }
 
 /* @brief Handler for Service Attribute Request
@@ -1062,108 +993,99 @@ static uint8_t find_handle(struct bt_sdp_record *rec, void *user_data)
  *
  *  @return 0 for success, or relevant error code
  */
-static uint16_t sdp_svc_att_req(struct bt_sdp *sdp, struct net_buf *buf,
-                                uint16_t tid)
-{
-    uint32_t filter[MAX_NUM_ATT_ID_FILTER];
-    struct search_state state = {
-        .current_svc = SDP_INVALID,
-        .last_att = SDP_INVALID,
-        .pkt_full = false
-    };
-    struct bt_sdp_record *record;
-    struct bt_sdp_att_rsp *rsp;
-    struct net_buf *rsp_buf;
-    uint32_t svc_rec_hdl;
-    uint16_t max_att_len, res, att_list_len;
-    uint8_t num_filters, cont_state_size, next_att = 0U;
-
-    if (buf->len < 6) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
-
-    svc_rec_hdl = net_buf_pull_be32(buf);
-    max_att_len = net_buf_pull_be16(buf);
-
-    /* Set up the filters */
-    res = get_att_search_list(buf, filter, &num_filters);
-    if (res) {
-        /* Error in parsing */
-        return res;
-    }
-
-    if (buf->len < 1) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
-
-    cont_state_size = net_buf_pull_u8(buf);
-
-    /* We only send out 1 byte continuation state in responses,
-	 * so expect only 1 byte in requests
-	 */
-    if (cont_state_size) {
-        if (cont_state_size != SDP_SA_CONT_STATE_SIZE) {
-            BT_WARN("Invalid cont state size %u", cont_state_size);
-            return BT_SDP_INVALID_CSTATE;
-        }
-
-        if (buf->len < cont_state_size) {
-            BT_WARN("Malformed packet");
-            return BT_SDP_INVALID_SYNTAX;
-        }
-
-        state.last_att = net_buf_pull_u8(buf) + 1;
-        next_att = state.last_att;
-    }
-
-    BT_DBG("svc_rec_hdl %u, max_att_len 0x%04x, cont_state %u", svc_rec_hdl,
-           max_att_len, next_att);
-
-    /* Find the service */
-    record = bt_sdp_foreach_svc(find_handle, &svc_rec_hdl);
-
-    if (!record) {
-        BT_WARN("Handle %u not found", svc_rec_hdl);
-        return BT_SDP_INVALID_RECORD_HANDLE;
-    }
-
-    /* For partial responses, restore the search state */
-    if (cont_state_size) {
-        state.current_svc = record->index;
-    }
-
-    rsp_buf = bt_sdp_create_pdu();
-    rsp = net_buf_add(rsp_buf, sizeof(*rsp));
-
-    /* cont_state_size should include 1 byte header */
-    att_list_len = create_attr_list(sdp, record, filter, num_filters,
-                                    max_att_len, SDP_SA_CONT_STATE_SIZE + 1,
-                                    next_att, &state, rsp_buf);
-
-    if (!att_list_len) {
-        /* For empty responses, add an empty data element sequence */
-        net_buf_add_u8(rsp_buf, BT_SDP_SEQ8);
-        net_buf_add_u8(rsp_buf, 0);
-        att_list_len = 2U;
-    }
-
-    /* Add continuation state */
-    if (state.pkt_full) {
-        BT_DBG("Packet full, state.last_att %u", state.last_att);
-        net_buf_add_u8(rsp_buf, 1);
-        net_buf_add_u8(rsp_buf, state.last_att);
-    } else {
-        net_buf_add_u8(rsp_buf, 0);
-    }
-
-    rsp->att_list_len = sys_cpu_to_be16(att_list_len);
-
-    BT_DBG("Sending response, len %u", rsp_buf->len);
-    bt_sdp_send(&sdp->chan.chan, rsp_buf, BT_SDP_SVC_ATTR_RSP, tid);
-
-    return 0;
+static uint16_t sdp_svc_att_req(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid) {
+  uint32_t               filter[MAX_NUM_ATT_ID_FILTER];
+  struct search_state    state = {.current_svc = SDP_INVALID, .last_att = SDP_INVALID, .pkt_full = false};
+  struct bt_sdp_record  *record;
+  struct bt_sdp_att_rsp *rsp;
+  struct net_buf        *rsp_buf;
+  uint32_t               svc_rec_hdl;
+  uint16_t               max_att_len, res, att_list_len;
+  uint8_t                num_filters, cont_state_size, next_att = 0U;
+
+  if (buf->len < 6) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  svc_rec_hdl = net_buf_pull_be32(buf);
+  max_att_len = net_buf_pull_be16(buf);
+
+  /* Set up the filters */
+  res = get_att_search_list(buf, filter, &num_filters);
+  if (res) {
+    /* Error in parsing */
+    return res;
+  }
+
+  if (buf->len < 1) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  cont_state_size = net_buf_pull_u8(buf);
+
+  /* We only send out 1 byte continuation state in responses,
+   * so expect only 1 byte in requests
+   */
+  if (cont_state_size) {
+    if (cont_state_size != SDP_SA_CONT_STATE_SIZE) {
+      BT_WARN("Invalid cont state size %u", cont_state_size);
+      return BT_SDP_INVALID_CSTATE;
+    }
+
+    if (buf->len < cont_state_size) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
+    }
+
+    state.last_att = net_buf_pull_u8(buf) + 1;
+    next_att       = state.last_att;
+  }
+
+  BT_DBG("svc_rec_hdl %u, max_att_len 0x%04x, cont_state %u", svc_rec_hdl, max_att_len, next_att);
+
+  /* Find the service */
+  record = bt_sdp_foreach_svc(find_handle, &svc_rec_hdl);
+
+  if (!record) {
+    BT_WARN("Handle %u not found", svc_rec_hdl);
+    return BT_SDP_INVALID_RECORD_HANDLE;
+  }
+
+  /* For partial responses, restore the search state */
+  if (cont_state_size) {
+    state.current_svc = record->index;
+  }
+
+  rsp_buf = bt_sdp_create_pdu();
+  rsp     = net_buf_add(rsp_buf, sizeof(*rsp));
+
+  /* cont_state_size should include 1 byte header */
+  att_list_len = create_attr_list(sdp, record, filter, num_filters, max_att_len, SDP_SA_CONT_STATE_SIZE + 1, next_att, &state, rsp_buf);
+
+  if (!att_list_len) {
+    /* For empty responses, add an empty data element sequence */
+    net_buf_add_u8(rsp_buf, BT_SDP_SEQ8);
+    net_buf_add_u8(rsp_buf, 0);
+    att_list_len = 2U;
+  }
+
+  /* Add continuation state */
+  if (state.pkt_full) {
+    BT_DBG("Packet full, state.last_att %u", state.last_att);
+    net_buf_add_u8(rsp_buf, 1);
+    net_buf_add_u8(rsp_buf, state.last_att);
+  } else {
+    net_buf_add_u8(rsp_buf, 0);
+  }
+
+  rsp->att_list_len = sys_cpu_to_be16(att_list_len);
+
+  BT_DBG("Sending response, len %u", rsp_buf->len);
+  bt_sdp_send(&sdp->chan.chan, rsp_buf, BT_SDP_SVC_ATTR_RSP, tid);
+
+  return 0;
 }
 
 /* @brief Handler for Service Search Attribute Request
@@ -1176,157 +1098,144 @@ static uint16_t sdp_svc_att_req(struct bt_sdp *sdp, struct net_buf *buf,
  *
  *  @return 0 for success, or relevant error code
  */
-static uint16_t sdp_svc_search_att_req(struct bt_sdp *sdp, struct net_buf *buf,
-                                       uint16_t tid)
-{
-    uint32_t filter[MAX_NUM_ATT_ID_FILTER];
-    struct bt_sdp_record *matching_recs[BT_SDP_MAX_SERVICES];
-    struct search_state state = {
-        .att_list_size = 0,
-        .current_svc = SDP_INVALID,
-        .last_att = SDP_INVALID,
-        .pkt_full = false
-    };
-    struct net_buf *rsp_buf, *rsp_buf_cpy;
-    struct bt_sdp_record *record;
-    struct bt_sdp_att_rsp *rsp;
-    struct bt_sdp_data_elem_seq *seq = NULL;
-    uint16_t max_att_len, res, att_list_len = 0U;
-    uint8_t num_filters, cont_state_size, next_svc = 0U, next_att = 0U;
-    bool dry_run = false;
-
-    res = find_services(buf, matching_recs);
-    if (res) {
-        return res;
-    }
+static uint16_t sdp_svc_search_att_req(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid) {
+  uint32_t                     filter[MAX_NUM_ATT_ID_FILTER];
+  struct bt_sdp_record        *matching_recs[BT_SDP_MAX_SERVICES];
+  struct search_state          state = {.att_list_size = 0, .current_svc = SDP_INVALID, .last_att = SDP_INVALID, .pkt_full = false};
+  struct net_buf              *rsp_buf, *rsp_buf_cpy;
+  struct bt_sdp_record        *record;
+  struct bt_sdp_att_rsp       *rsp;
+  struct bt_sdp_data_elem_seq *seq = NULL;
+  uint16_t                     max_att_len, res, att_list_len         = 0U;
+  uint8_t                      num_filters, cont_state_size, next_svc = 0U, next_att = 0U;
+  bool                         dry_run = false;
 
-    if (buf->len < 2) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
-    }
+  res = find_services(buf, matching_recs);
+  if (res) {
+    return res;
+  }
 
-    max_att_len = net_buf_pull_be16(buf);
+  if (buf->len < 2) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
 
-    /* Set up the filters */
-    res = get_att_search_list(buf, filter, &num_filters);
+  max_att_len = net_buf_pull_be16(buf);
 
-    if (res) {
-        /* Error in parsing */
-        return res;
+  /* Set up the filters */
+  res = get_att_search_list(buf, filter, &num_filters);
+
+  if (res) {
+    /* Error in parsing */
+    return res;
+  }
+
+  if (buf->len < 1) {
+    BT_WARN("Malformed packet");
+    return BT_SDP_INVALID_SYNTAX;
+  }
+
+  cont_state_size = net_buf_pull_u8(buf);
+
+  /* We only send out 2 bytes continuation state in responses,
+   * so expect only 2 bytes in requests
+   */
+  if (cont_state_size) {
+    if (cont_state_size != SDP_SSA_CONT_STATE_SIZE) {
+      BT_WARN("Invalid cont state size %u", cont_state_size);
+      return BT_SDP_INVALID_CSTATE;
     }
 
-    if (buf->len < 1) {
-        BT_WARN("Malformed packet");
-        return BT_SDP_INVALID_SYNTAX;
+    if (buf->len < cont_state_size) {
+      BT_WARN("Malformed packet");
+      return BT_SDP_INVALID_SYNTAX;
     }
 
-    cont_state_size = net_buf_pull_u8(buf);
+    state.current_svc = net_buf_pull_u8(buf);
+    state.last_att    = net_buf_pull_u8(buf) + 1;
+    next_svc          = state.current_svc;
+    next_att          = state.last_att;
+  }
 
-    /* We only send out 2 bytes continuation state in responses,
-	 * so expect only 2 bytes in requests
-	 */
-    if (cont_state_size) {
-        if (cont_state_size != SDP_SSA_CONT_STATE_SIZE) {
-            BT_WARN("Invalid cont state size %u", cont_state_size);
-            return BT_SDP_INVALID_CSTATE;
-        }
+  BT_DBG("max_att_len 0x%04x, state.current_svc %u, state.last_att %u", max_att_len, state.current_svc, state.last_att);
 
-        if (buf->len < cont_state_size) {
-            BT_WARN("Malformed packet");
-            return BT_SDP_INVALID_SYNTAX;
-        }
+  rsp_buf = bt_sdp_create_pdu();
 
-        state.current_svc = net_buf_pull_u8(buf);
-        state.last_att = net_buf_pull_u8(buf) + 1;
-        next_svc = state.current_svc;
-        next_att = state.last_att;
-    }
+  rsp = net_buf_add(rsp_buf, sizeof(*rsp));
 
-    BT_DBG("max_att_len 0x%04x, state.current_svc %u, state.last_att %u",
-           max_att_len, state.current_svc, state.last_att);
+  /* Add headers only if this is not a partial response */
+  if (!cont_state_size) {
+    seq       = net_buf_add(rsp_buf, sizeof(*seq));
+    seq->type = BT_SDP_SEQ16;
+    seq->size = 0U;
 
-    rsp_buf = bt_sdp_create_pdu();
+    /* 3 bytes for Outer Data Element Sequence declaration */
+    att_list_len = 3U;
+  }
 
-    rsp = net_buf_add(rsp_buf, sizeof(*rsp));
+  rsp_buf_cpy = rsp_buf;
 
-    /* Add headers only if this is not a partial response */
-    if (!cont_state_size) {
-        seq = net_buf_add(rsp_buf, sizeof(*seq));
-        seq->type = BT_SDP_SEQ16;
-        seq->size = 0U;
+  for (; next_svc < num_services; next_svc++) {
+    record = matching_recs[next_svc];
 
-        /* 3 bytes for Outer Data Element Sequence declaration */
-        att_list_len = 3U;
+    if (!record) {
+      continue;
     }
 
-    rsp_buf_cpy = rsp_buf;
+    att_list_len += create_attr_list(sdp, record, filter, num_filters, max_att_len, SDP_SSA_CONT_STATE_SIZE + 1, next_att, &state, rsp_buf_cpy);
 
-    for (; next_svc < num_services; next_svc++) {
-        record = matching_recs[next_svc];
+    /* Check if packet is full and not dry run */
+    if (state.pkt_full && !dry_run) {
+      BT_DBG("Packet full, state.last_att %u", state.last_att);
+      dry_run = true;
 
-        if (!record) {
-            continue;
-        }
+      /* Add continuation state */
+      net_buf_add_u8(rsp_buf, 2);
+      net_buf_add_u8(rsp_buf, state.current_svc);
+      net_buf_add_u8(rsp_buf, state.last_att);
 
-        att_list_len += create_attr_list(sdp, record, filter,
-                                         num_filters, max_att_len,
-                                         SDP_SSA_CONT_STATE_SIZE + 1,
-                                         next_att, &state, rsp_buf_cpy);
-
-        /* Check if packet is full and not dry run */
-        if (state.pkt_full && !dry_run) {
-            BT_DBG("Packet full, state.last_att %u",
-                   state.last_att);
-            dry_run = true;
-
-            /* Add continuation state */
-            net_buf_add_u8(rsp_buf, 2);
-            net_buf_add_u8(rsp_buf, state.current_svc);
-            net_buf_add_u8(rsp_buf, state.last_att);
-
-            /* Break if it's not a partial response, else dry-run
-			 * Dry run: Look for other services that match
-			 */
-            if (cont_state_size) {
-                break;
-            }
-
-            rsp_buf_cpy = NULL;
-        }
+      /* Break if it's not a partial response, else dry-run
+       * Dry run: Look for other services that match
+       */
+      if (cont_state_size) {
+        break;
+      }
 
-        next_att = 0U;
+      rsp_buf_cpy = NULL;
     }
 
-    if (!dry_run) {
-        if (!att_list_len) {
-            /* For empty responses, add an empty data elem seq */
-            net_buf_add_u8(rsp_buf, BT_SDP_SEQ8);
-            net_buf_add_u8(rsp_buf, 0);
-            att_list_len = 2U;
-        }
-        /* Search exhausted */
-        net_buf_add_u8(rsp_buf, 0);
-    }
+    next_att = 0U;
+  }
 
-    rsp->att_list_len = sys_cpu_to_be16(att_list_len);
-    if (seq) {
-        seq->size = sys_cpu_to_be16(state.att_list_size);
+  if (!dry_run) {
+    if (!att_list_len) {
+      /* For empty responses, add an empty data elem seq */
+      net_buf_add_u8(rsp_buf, BT_SDP_SEQ8);
+      net_buf_add_u8(rsp_buf, 0);
+      att_list_len = 2U;
     }
+    /* Search exhausted */
+    net_buf_add_u8(rsp_buf, 0);
+  }
 
-    BT_DBG("Sending response, len %u", rsp_buf->len);
-    bt_sdp_send(&sdp->chan.chan, rsp_buf, BT_SDP_SVC_SEARCH_ATTR_RSP,
-                tid);
+  rsp->att_list_len = sys_cpu_to_be16(att_list_len);
+  if (seq) {
+    seq->size = sys_cpu_to_be16(state.att_list_size);
+  }
 
-    return 0;
+  BT_DBG("Sending response, len %u", rsp_buf->len);
+  bt_sdp_send(&sdp->chan.chan, rsp_buf, BT_SDP_SVC_SEARCH_ATTR_RSP, tid);
+
+  return 0;
 }
 
 static const struct {
-    uint8_t op_code;
-    uint16_t (*func)(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid);
+  uint8_t op_code;
+  uint16_t (*func)(struct bt_sdp *sdp, struct net_buf *buf, uint16_t tid);
 } handlers[] = {
-    { BT_SDP_SVC_SEARCH_REQ, sdp_svc_search_req },
-    { BT_SDP_SVC_ATTR_REQ, sdp_svc_att_req },
-    { BT_SDP_SVC_SEARCH_ATTR_REQ, sdp_svc_search_att_req },
+    {     BT_SDP_SVC_SEARCH_REQ,     sdp_svc_search_req},
+    {       BT_SDP_SVC_ATTR_REQ,        sdp_svc_att_req},
+    {BT_SDP_SVC_SEARCH_ATTR_REQ, sdp_svc_search_att_req},
 };
 
 /* @brief Callback for SDP data receive
@@ -1339,46 +1248,44 @@ static const struct {
  *
  *  @return None
  */
-static int bt_sdp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_l2cap_br_chan *ch = CONTAINER_OF(chan,
-                                               struct bt_l2cap_br_chan, chan);
-    struct bt_sdp *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
-    struct bt_sdp_hdr *hdr;
-    uint16_t err = BT_SDP_INVALID_SYNTAX;
-    size_t i;
+static int bt_sdp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_l2cap_br_chan *ch  = CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan);
+  struct bt_sdp           *sdp = CONTAINER_OF(ch, struct bt_sdp, chan);
+  struct bt_sdp_hdr       *hdr;
+  uint16_t                 err = BT_SDP_INVALID_SYNTAX;
+  size_t                   i;
 
-    BT_DBG("chan %p, ch %p, cid 0x%04x", chan, ch, ch->tx.cid);
+  BT_DBG("chan %p, ch %p, cid 0x%04x", chan, ch, ch->tx.cid);
 
-    BT_ASSERT(sdp);
+  BT_ASSERT(sdp);
 
-    if (buf->len < sizeof(*hdr)) {
-        BT_ERR("Too small SDP PDU received");
-        return 0;
-    }
+  if (buf->len < sizeof(*hdr)) {
+    BT_ERR("Too small SDP PDU received");
+    return 0;
+  }
 
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    BT_DBG("Received SDP code 0x%02x len %u", hdr->op_code, buf->len);
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  BT_DBG("Received SDP code 0x%02x len %u", hdr->op_code, buf->len);
 
-    if (sys_cpu_to_be16(hdr->param_len) != buf->len) {
-        err = BT_SDP_INVALID_PDU_SIZE;
-    } else {
-        for (i = 0; i < ARRAY_SIZE(handlers); i++) {
-            if (hdr->op_code != handlers[i].op_code) {
-                continue;
-            }
+  if (sys_cpu_to_be16(hdr->param_len) != buf->len) {
+    err = BT_SDP_INVALID_PDU_SIZE;
+  } else {
+    for (i = 0; i < ARRAY_SIZE(handlers); i++) {
+      if (hdr->op_code != handlers[i].op_code) {
+        continue;
+      }
 
-            err = handlers[i].func(sdp, buf, hdr->tid);
-            break;
-        }
+      err = handlers[i].func(sdp, buf, hdr->tid);
+      break;
     }
+  }
 
-    if (err) {
-        BT_WARN("SDP error 0x%02x", err);
-        send_err_rsp(chan, err, hdr->tid);
-    }
+  if (err) {
+    BT_WARN("SDP error 0x%02x", err);
+    send_err_rsp(chan, err, hdr->tid);
+  }
 
-    return 0;
+  return 0;
 }
 
 /* @brief Callback for SDP connection accept
@@ -1391,1155 +1298,1095 @@ static int bt_sdp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
  *
  *  @return 0 for success, or relevant error code
  */
-static int bt_sdp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
-{
-    static const struct bt_l2cap_chan_ops ops = {
-        .connected = bt_sdp_connected,
-        .disconnected = bt_sdp_disconnected,
-        .recv = bt_sdp_recv,
-    };
-    int i;
-
-    BT_DBG("conn %p", conn);
-
-    for (i = 0; i < ARRAY_SIZE(bt_sdp_pool); i++) {
-        struct bt_sdp *sdp = &bt_sdp_pool[i];
-
-        if (sdp->chan.chan.conn) {
-            continue;
-        }
+static int bt_sdp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) {
+  static const struct bt_l2cap_chan_ops ops = {
+      .connected    = bt_sdp_connected,
+      .disconnected = bt_sdp_disconnected,
+      .recv         = bt_sdp_recv,
+  };
+  int i;
 
-        sdp->chan.chan.ops = &ops;
-        sdp->chan.rx.mtu = SDP_MTU;
+  BT_DBG("conn %p", conn);
 
-        *chan = &sdp->chan.chan;
+  for (i = 0; i < ARRAY_SIZE(bt_sdp_pool); i++) {
+    struct bt_sdp *sdp = &bt_sdp_pool[i];
 
-        return 0;
+    if (sdp->chan.chan.conn) {
+      continue;
     }
 
-    BT_ERR("No available SDP context for conn %p", conn);
+    sdp->chan.chan.ops = &ops;
+    sdp->chan.rx.mtu   = SDP_MTU;
 
-    return -ENOMEM;
+    *chan = &sdp->chan.chan;
+
+    return 0;
+  }
+
+  BT_ERR("No available SDP context for conn %p", conn);
+
+  return -ENOMEM;
 }
 
-void bt_sdp_init(void)
-{
+void bt_sdp_init(void) {
 #if defined(BFLB_DYNAMIC_ALLOC_MEM)
-    net_buf_init(&sdp_pool, CONFIG_BT_MAX_CONN, BT_L2CAP_BUF_SIZE(SDP_MTU), NULL);
+  net_buf_init(&sdp_pool, CONFIG_BT_MAX_CONN, BT_L2CAP_BUF_SIZE(SDP_MTU), NULL);
 #endif
-    static struct bt_l2cap_server server = {
-        .psm = SDP_PSM,
-        .accept = bt_sdp_accept,
-        .sec_level = BT_SECURITY_L0,
-    };
-    int res;
-
-    res = bt_l2cap_br_server_register(&server);
-    if (res) {
-        BT_ERR("L2CAP server registration failed with error %d", res);
-    }
+  static struct bt_l2cap_server server = {
+      .psm       = SDP_PSM,
+      .accept    = bt_sdp_accept,
+      .sec_level = BT_SECURITY_L0,
+  };
+  int res;
+
+  res = bt_l2cap_br_server_register(&server);
+  if (res) {
+    BT_ERR("L2CAP server registration failed with error %d", res);
+  }
 }
 
-int bt_sdp_register_service(struct bt_sdp_record *service)
-{
-    uint32_t handle = SDP_SERVICE_HANDLE_BASE;
+int bt_sdp_register_service(struct bt_sdp_record *service) {
+  uint32_t handle = SDP_SERVICE_HANDLE_BASE;
 
-    if (!service) {
-        BT_ERR("No service record specified");
-        return 0;
-    }
+  if (!service) {
+    BT_ERR("No service record specified");
+    return 0;
+  }
 
-    if (num_services == BT_SDP_MAX_SERVICES) {
-        BT_ERR("Reached max allowed registrations");
-        return -ENOMEM;
-    }
+  if (num_services == BT_SDP_MAX_SERVICES) {
+    BT_ERR("Reached max allowed registrations");
+    return -ENOMEM;
+  }
 
-    if (db) {
-        handle = db->handle + 1;
-    }
+  if (db) {
+    handle = db->handle + 1;
+  }
 
-    service->next = db;
-    service->index = num_services++;
-    service->handle = handle;
-    *((uint32_t *)(service->attrs[0].val.data)) = handle;
-    db = service;
+  service->next                               = db;
+  service->index                              = num_services++;
+  service->handle                             = handle;
+  *((uint32_t *)(service->attrs[0].val.data)) = handle;
+  db                                          = service;
 
-    BT_DBG("Service registered at %u", handle);
+  BT_DBG("Service registered at %u", handle);
 
-    return 0;
+  return 0;
 }
 
-#define GET_PARAM(__node) \
-    CONTAINER_OF(__node, struct bt_sdp_discover_params, _node)
+#define GET_PARAM(__node) CONTAINER_OF(__node, struct bt_sdp_discover_params, _node)
 
 /* ServiceSearchAttribute PDU, ref to BT Core 4.2, Vol 3, part B, 4.7.1 */
-static int sdp_client_ssa_search(struct bt_sdp_client *session)
-{
-    const struct bt_sdp_discover_params *param;
-    struct bt_sdp_hdr *hdr;
-    struct net_buf *buf;
-
-    /*
-	 * Select proper user params, if session->param is invalid it means
-	 * getting new UUID from top of to be resolved params list. Otherwise
-	 * the context is in a middle of partial SDP PDU responses and cached
-	 * value from context can be used.
-	 */
-    if (!session->param) {
-        param = GET_PARAM(sys_slist_peek_head(&session->reqs));
-    } else {
-        param = session->param;
-    }
-
-    if (!param) {
-        BT_WARN("No UUIDs to be resolved on remote");
-        return -EINVAL;
-    }
-
-    buf = bt_l2cap_create_pdu(&sdp_pool, 0);
-
-    hdr = net_buf_add(buf, sizeof(*hdr));
-
-    hdr->op_code = BT_SDP_SVC_SEARCH_ATTR_REQ;
-    /* BT_SDP_SEQ8 means length of sequence is on additional next byte */
-    net_buf_add_u8(buf, BT_SDP_SEQ8);
-
-    switch (param->uuid->type) {
-        case BT_UUID_TYPE_16:
-            /* Seq length */
-            net_buf_add_u8(buf, 0x03);
-            /* Seq type */
-            net_buf_add_u8(buf, BT_SDP_UUID16);
-            /* Seq value */
-            net_buf_add_be16(buf, BT_UUID_16(param->uuid)->val);
-            break;
-        case BT_UUID_TYPE_32:
-            net_buf_add_u8(buf, 0x05);
-            net_buf_add_u8(buf, BT_SDP_UUID32);
-            net_buf_add_be32(buf, BT_UUID_32(param->uuid)->val);
-            break;
-        case BT_UUID_TYPE_128:
-            net_buf_add_u8(buf, 0x11);
-            net_buf_add_u8(buf, BT_SDP_UUID128);
-            net_buf_add_mem(buf, BT_UUID_128(param->uuid)->val,
-                            ARRAY_SIZE(BT_UUID_128(param->uuid)->val));
-            break;
-        default:
-            BT_ERR("Unknown UUID type %u", param->uuid->type);
-            return -EINVAL;
-    }
-
-    /* Set attribute max bytes count to be returned from server */
-    net_buf_add_be16(buf, BT_SDP_MAX_ATTR_LEN);
-    /*
-	 * Sequence definition where data is sequence of elements and where
-	 * additional next byte points the size of elements within
-	 */
-    net_buf_add_u8(buf, BT_SDP_SEQ8);
+static int sdp_client_ssa_search(struct bt_sdp_client *session) {
+  const struct bt_sdp_discover_params *param;
+  struct bt_sdp_hdr                   *hdr;
+  struct net_buf                      *buf;
+
+  /*
+   * Select proper user params, if session->param is invalid it means
+   * getting new UUID from top of to be resolved params list. Otherwise
+   * the context is in a middle of partial SDP PDU responses and cached
+   * value from context can be used.
+   */
+  if (!session->param) {
+    param = GET_PARAM(sys_slist_peek_head(&session->reqs));
+  } else {
+    param = session->param;
+  }
+
+  if (!param) {
+    BT_WARN("No UUIDs to be resolved on remote");
+    return -EINVAL;
+  }
+
+  buf = bt_l2cap_create_pdu(&sdp_pool, 0);
+
+  hdr = net_buf_add(buf, sizeof(*hdr));
+
+  hdr->op_code = BT_SDP_SVC_SEARCH_ATTR_REQ;
+  /* BT_SDP_SEQ8 means length of sequence is on additional next byte */
+  net_buf_add_u8(buf, BT_SDP_SEQ8);
+
+  switch (param->uuid->type) {
+  case BT_UUID_TYPE_16:
+    /* Seq length */
+    net_buf_add_u8(buf, 0x03);
+    /* Seq type */
+    net_buf_add_u8(buf, BT_SDP_UUID16);
+    /* Seq value */
+    net_buf_add_be16(buf, BT_UUID_16(param->uuid)->val);
+    break;
+  case BT_UUID_TYPE_32:
     net_buf_add_u8(buf, 0x05);
-    /* Data element definition for two following 16bits range elements */
-    net_buf_add_u8(buf, BT_SDP_UINT32);
-    /* Get all attributes. It enables filter out wanted only attributes */
-    net_buf_add_be16(buf, 0x0000);
-    net_buf_add_be16(buf, 0xffff);
+    net_buf_add_u8(buf, BT_SDP_UUID32);
+    net_buf_add_be32(buf, BT_UUID_32(param->uuid)->val);
+    break;
+  case BT_UUID_TYPE_128:
+    net_buf_add_u8(buf, 0x11);
+    net_buf_add_u8(buf, BT_SDP_UUID128);
+    net_buf_add_mem(buf, BT_UUID_128(param->uuid)->val, ARRAY_SIZE(BT_UUID_128(param->uuid)->val));
+    break;
+  default:
+    BT_ERR("Unknown UUID type %u", param->uuid->type);
+    return -EINVAL;
+  }
+
+  /* Set attribute max bytes count to be returned from server */
+  net_buf_add_be16(buf, BT_SDP_MAX_ATTR_LEN);
+  /*
+   * Sequence definition where data is sequence of elements and where
+   * additional next byte points the size of elements within
+   */
+  net_buf_add_u8(buf, BT_SDP_SEQ8);
+  net_buf_add_u8(buf, 0x05);
+  /* Data element definition for two following 16bits range elements */
+  net_buf_add_u8(buf, BT_SDP_UINT32);
+  /* Get all attributes. It enables filter out wanted only attributes */
+  net_buf_add_be16(buf, 0x0000);
+  net_buf_add_be16(buf, 0xffff);
+
+  /*
+   * Update and validate PDU ContinuationState. Initial SSA Request has
+   * zero length continuation state since no interaction has place with
+   * server so far, otherwise use the original state taken from remote's
+   * last response PDU that is cached by SDP client context.
+   */
+  if (session->cstate.length == 0U) {
+    net_buf_add_u8(buf, 0x00);
+  } else {
+    net_buf_add_u8(buf, session->cstate.length);
+    net_buf_add_mem(buf, session->cstate.data, session->cstate.length);
+  }
+
+  /* set overall PDU length */
+  hdr->param_len = sys_cpu_to_be16(buf->len - sizeof(*hdr));
+
+  /* Update context param to the one being resolving now */
+  session->param = param;
+  session->tid++;
+  hdr->tid = sys_cpu_to_be16(session->tid);
+
+  return bt_l2cap_chan_send(&session->chan.chan, buf);
+}
 
-    /*
-	 * Update and validate PDU ContinuationState. Initial SSA Request has
-	 * zero length continuation state since no interaction has place with
-	 * server so far, otherwise use the original state taken from remote's
-	 * last response PDU that is cached by SDP client context.
-	 */
-    if (session->cstate.length == 0U) {
-        net_buf_add_u8(buf, 0x00);
-    } else {
-        net_buf_add_u8(buf, session->cstate.length);
-        net_buf_add_mem(buf, session->cstate.data,
-                        session->cstate.length);
+static void sdp_client_params_iterator(struct bt_sdp_client *session) {
+  struct bt_l2cap_chan          *chan = &session->chan.chan;
+  struct bt_sdp_discover_params *param, *tmp;
+
+  SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&session->reqs, param, tmp, _node) {
+    if (param != session->param) {
+      continue;
     }
 
-    /* set overall PDU length */
-    hdr->param_len = sys_cpu_to_be16(buf->len - sizeof(*hdr));
+    BT_DBG("");
 
-    /* Update context param to the one being resolving now */
-    session->param = param;
-    session->tid++;
-    hdr->tid = sys_cpu_to_be16(session->tid);
+    /* Remove already checked UUID node */
+    sys_slist_remove(&session->reqs, NULL, ¶m->_node);
+    /* Invalidate cached param in context */
+    session->param = NULL;
+    /* Reset continuation state in current context */
+    (void)memset(&session->cstate, 0, sizeof(session->cstate));
+
+    /* Check if there's valid next UUID */
+    if (!sys_slist_is_empty(&session->reqs)) {
+      sdp_client_ssa_search(session);
+      return;
+    }
 
-    return bt_l2cap_chan_send(&session->chan.chan, buf);
+    /* No UUID items, disconnect channel */
+    bt_l2cap_chan_disconnect(chan);
+    break;
+  }
 }
 
-static void sdp_client_params_iterator(struct bt_sdp_client *session)
-{
-    struct bt_l2cap_chan *chan = &session->chan.chan;
-    struct bt_sdp_discover_params *param, *tmp;
+static uint16_t sdp_client_get_total(struct bt_sdp_client *session, struct net_buf *buf, uint16_t *total) {
+  uint16_t pulled;
+  uint8_t  seq;
+
+  /*
+   * Pull value of total octets of all attributes available to be
+   * collected when response gets completed for given UUID. Such info can
+   * be get from the very first response frame after initial SSA request
+   * was sent. For subsequent calls related to the same SSA request input
+   * buf and in/out function parameters stays neutral.
+   */
+  if (session->cstate.length == 0U) {
+    seq    = net_buf_pull_u8(buf);
+    pulled = 1U;
+    switch (seq) {
+    case BT_SDP_SEQ8:
+      *total = net_buf_pull_u8(buf);
+      pulled += 1U;
+      break;
+    case BT_SDP_SEQ16:
+      *total = net_buf_pull_be16(buf);
+      pulled += 2U;
+      break;
+    default:
+      BT_WARN("Sequence type 0x%02x not handled", seq);
+      *total = 0U;
+      break;
+    }
+
+    BT_DBG("Total %u octets of all attributes", *total);
+  } else {
+    pulled = 0U;
+    *total = 0U;
+  }
+
+  return pulled;
+}
 
-    SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&session->reqs, param, tmp, _node)
-    {
-        if (param != session->param) {
-            continue;
-        }
+static uint16_t get_record_len(struct net_buf *buf) {
+  uint16_t len;
+  uint8_t  seq;
 
-        BT_DBG("");
+  seq = net_buf_pull_u8(buf);
 
-        /* Remove already checked UUID node */
-        sys_slist_remove(&session->reqs, NULL, ¶m->_node);
-        /* Invalidate cached param in context */
-        session->param = NULL;
-        /* Reset continuation state in current context */
-        (void)memset(&session->cstate, 0, sizeof(session->cstate));
+  switch (seq) {
+  case BT_SDP_SEQ8:
+    len = net_buf_pull_u8(buf);
+    break;
+  case BT_SDP_SEQ16:
+    len = net_buf_pull_be16(buf);
+    break;
+  default:
+    BT_WARN("Sequence type 0x%02x not handled", seq);
+    len = 0U;
+    break;
+  }
 
-        /* Check if there's valid next UUID */
-        if (!sys_slist_is_empty(&session->reqs)) {
-            sdp_client_ssa_search(session);
-            return;
-        }
+  BT_DBG("Record len %u", len);
 
-        /* No UUID items, disconnect channel */
-        bt_l2cap_chan_disconnect(chan);
-        break;
-    }
+  return len;
 }
 
-static uint16_t sdp_client_get_total(struct bt_sdp_client *session,
-                                     struct net_buf *buf, uint16_t *total)
-{
-    uint16_t pulled;
-    uint8_t seq;
+enum uuid_state {
+  UUID_NOT_RESOLVED,
+  UUID_RESOLVED,
+};
 
-    /*
-	 * Pull value of total octets of all attributes available to be
-	 * collected when response gets completed for given UUID. Such info can
-	 * be get from the very first response frame after initial SSA request
-	 * was sent. For subsequent calls related to the same SSA request input
-	 * buf and in/out function parameters stays neutral.
-	 */
-    if (session->cstate.length == 0U) {
-        seq = net_buf_pull_u8(buf);
-        pulled = 1U;
-        switch (seq) {
-            case BT_SDP_SEQ8:
-                *total = net_buf_pull_u8(buf);
-                pulled += 1U;
-                break;
-            case BT_SDP_SEQ16:
-                *total = net_buf_pull_be16(buf);
-                pulled += 2U;
-                break;
-            default:
-                BT_WARN("Sequence type 0x%02x not handled", seq);
-                *total = 0U;
-                break;
-        }
+static void sdp_client_notify_result(struct bt_sdp_client *session, enum uuid_state state) {
+  struct bt_conn             *conn = session->chan.chan.conn;
+  struct bt_sdp_client_result result;
+  uint16_t                    rec_len;
+  uint8_t                     user_ret;
 
-        BT_DBG("Total %u octets of all attributes", *total);
-    } else {
-        pulled = 0U;
-        *total = 0U;
-    }
-
-    return pulled;
-}
+  result.uuid = session->param->uuid;
 
-static uint16_t get_record_len(struct net_buf *buf)
-{
-    uint16_t len;
-    uint8_t seq;
+  if (state == UUID_NOT_RESOLVED) {
+    result.resp_buf         = NULL;
+    result.next_record_hint = false;
+    session->param->func(conn, &result);
+    return;
+  }
 
-    seq = net_buf_pull_u8(buf);
+  while (session->rec_buf->len) {
+    struct net_buf_simple_state buf_state;
 
-    switch (seq) {
-        case BT_SDP_SEQ8:
-            len = net_buf_pull_u8(buf);
-            break;
-        case BT_SDP_SEQ16:
-            len = net_buf_pull_be16(buf);
-            break;
-        default:
-            BT_WARN("Sequence type 0x%02x not handled", seq);
-            len = 0U;
-            break;
+    rec_len = get_record_len(session->rec_buf);
+    /* tell the user about multi record resolution */
+    if (session->rec_buf->len > rec_len) {
+      result.next_record_hint = true;
+    } else {
+      result.next_record_hint = false;
     }
 
-    BT_DBG("Record len %u", len);
+    /* save the original session buffer */
+    net_buf_simple_save(&session->rec_buf->b, &buf_state);
+    /* initialize internal result buffer instead of memcpy */
+    result.resp_buf = session->rec_buf;
+    /*
+     * Set user internal result buffer length as same as record
+     * length to fake user. User will see the individual record
+     * length as rec_len insted of whole session rec_buf length.
+     */
+    result.resp_buf->len = rec_len;
 
-    return len;
-}
+    user_ret = session->param->func(conn, &result);
 
-enum uuid_state {
-    UUID_NOT_RESOLVED,
-    UUID_RESOLVED,
-};
+    /* restore original session buffer */
+    net_buf_simple_restore(&session->rec_buf->b, &buf_state);
+    /*
+     * sync session buffer data length with next record chunk not
+     * send to user so far
+     */
+    net_buf_pull(session->rec_buf, rec_len);
+    if (user_ret == BT_SDP_DISCOVER_UUID_STOP) {
+      break;
+    }
+  }
+}
 
-static void sdp_client_notify_result(struct bt_sdp_client *session,
-                                     enum uuid_state state)
-{
-    struct bt_conn *conn = session->chan.chan.conn;
-    struct bt_sdp_client_result result;
-    uint16_t rec_len;
-    uint8_t user_ret;
+static int sdp_client_receive(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_sdp_client     *session = SDP_CLIENT_CHAN(chan);
+  struct bt_sdp_hdr        *hdr;
+  struct bt_sdp_pdu_cstate *cstate;
+  uint16_t                  len, tid, frame_len;
+  uint16_t                  total;
 
-    result.uuid = session->param->uuid;
+  BT_DBG("session %p buf %p", session, buf);
 
-    if (state == UUID_NOT_RESOLVED) {
-        result.resp_buf = NULL;
-        result.next_record_hint = false;
-        session->param->func(conn, &result);
-        return;
-    }
+  if (buf->len < sizeof(*hdr)) {
+    BT_ERR("Too small SDP PDU");
+    return 0;
+  }
 
-    while (session->rec_buf->len) {
-        struct net_buf_simple_state buf_state;
+  hdr = net_buf_pull_mem(buf, sizeof(*hdr));
+  if (hdr->op_code == BT_SDP_ERROR_RSP) {
+    BT_INFO("Error SDP PDU response");
+    return 0;
+  }
 
-        rec_len = get_record_len(session->rec_buf);
-        /* tell the user about multi record resolution */
-        if (session->rec_buf->len > rec_len) {
-            result.next_record_hint = true;
-        } else {
-            result.next_record_hint = false;
-        }
+  len = sys_be16_to_cpu(hdr->param_len);
+  tid = sys_be16_to_cpu(hdr->tid);
 
-        /* save the original session buffer */
-        net_buf_simple_save(&session->rec_buf->b, &buf_state);
-        /* initialize internal result buffer instead of memcpy */
-        result.resp_buf = session->rec_buf;
-        /*
-		 * Set user internal result buffer length as same as record
-		 * length to fake user. User will see the individual record
-		 * length as rec_len insted of whole session rec_buf length.
-		 */
-        result.resp_buf->len = rec_len;
-
-        user_ret = session->param->func(conn, &result);
-
-        /* restore original session buffer */
-        net_buf_simple_restore(&session->rec_buf->b, &buf_state);
-        /*
-		 * sync session buffer data length with next record chunk not
-		 * send to user so far
-		 */
-        net_buf_pull(session->rec_buf, rec_len);
-        if (user_ret == BT_SDP_DISCOVER_UUID_STOP) {
-            break;
-        }
-    }
-}
+  BT_DBG("SDP PDU tid %u len %u", tid, len);
 
-static int sdp_client_receive(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
-    struct bt_sdp_hdr *hdr;
-    struct bt_sdp_pdu_cstate *cstate;
-    uint16_t len, tid, frame_len;
-    uint16_t total;
+  if (buf->len != len) {
+    BT_ERR("SDP PDU length mismatch (%u != %u)", buf->len, len);
+    return 0;
+  }
 
-    BT_DBG("session %p buf %p", session, buf);
+  if (tid != session->tid) {
+    BT_ERR("Mismatch transaction ID value in SDP PDU");
+    return 0;
+  }
 
-    if (buf->len < sizeof(*hdr)) {
-        BT_ERR("Too small SDP PDU");
-        return 0;
+  switch (hdr->op_code) {
+  case BT_SDP_SVC_SEARCH_ATTR_RSP:
+    /* Get number of attributes in this frame. */
+    frame_len = net_buf_pull_be16(buf);
+    /* Check valid buf len for attribute list and cont state */
+    if (buf->len < frame_len + SDP_CONT_STATE_LEN_SIZE) {
+      BT_ERR("Invalid frame payload length");
+      return 0;
     }
-
-    hdr = net_buf_pull_mem(buf, sizeof(*hdr));
-    if (hdr->op_code == BT_SDP_ERROR_RSP) {
-        BT_INFO("Error SDP PDU response");
-        return 0;
+    /* Check valid range of attributes length */
+    if (frame_len < 2) {
+      BT_ERR("Invalid attributes data length");
+      return 0;
     }
 
-    len = sys_be16_to_cpu(hdr->param_len);
-    tid = sys_be16_to_cpu(hdr->tid);
+    /* Get PDU continuation state */
+    cstate = (struct bt_sdp_pdu_cstate *)(buf->data + frame_len);
 
-    BT_DBG("SDP PDU tid %u len %u", tid, len);
+    if (cstate->length > BT_SDP_MAX_PDU_CSTATE_LEN) {
+      BT_ERR("Invalid SDP PDU Continuation State length %u", cstate->length);
+      return 0;
+    }
 
-    if (buf->len != len) {
-        BT_ERR("SDP PDU length mismatch (%u != %u)", buf->len, len);
-        return 0;
+    if ((frame_len + SDP_CONT_STATE_LEN_SIZE + cstate->length) > buf->len) {
+      BT_ERR("Invalid frame payload length");
+      return 0;
     }
 
-    if (tid != session->tid) {
-        BT_ERR("Mismatch transaction ID value in SDP PDU");
-        return 0;
+    /*
+     * No record found for given UUID. The check catches case when
+     * current response frame has Continuation State shortest and
+     * valid and this is the first response frame as well.
+     */
+    if (frame_len == 2U && cstate->length == 0U && session->cstate.length == 0U) {
+      BT_DBG("record for UUID 0x%s not found", bt_uuid_str(session->param->uuid));
+      /* Call user UUID handler */
+      sdp_client_notify_result(session, UUID_NOT_RESOLVED);
+      net_buf_pull(buf, frame_len + sizeof(cstate->length));
+      goto iterate;
     }
 
-    switch (hdr->op_code) {
-        case BT_SDP_SVC_SEARCH_ATTR_RSP:
-            /* Get number of attributes in this frame. */
-            frame_len = net_buf_pull_be16(buf);
-            /* Check valid buf len for attribute list and cont state */
-            if (buf->len < frame_len + SDP_CONT_STATE_LEN_SIZE) {
-                BT_ERR("Invalid frame payload length");
-                return 0;
-            }
-            /* Check valid range of attributes length */
-            if (frame_len < 2) {
-                BT_ERR("Invalid attributes data length");
-                return 0;
-            }
-
-            /* Get PDU continuation state */
-            cstate = (struct bt_sdp_pdu_cstate *)(buf->data + frame_len);
-
-            if (cstate->length > BT_SDP_MAX_PDU_CSTATE_LEN) {
-                BT_ERR("Invalid SDP PDU Continuation State length %u",
-                       cstate->length);
-                return 0;
-            }
-
-            if ((frame_len + SDP_CONT_STATE_LEN_SIZE + cstate->length) >
-                buf->len) {
-                BT_ERR("Invalid frame payload length");
-                return 0;
-            }
-
-            /*
-		 * No record found for given UUID. The check catches case when
-		 * current response frame has Continuation State shortest and
-		 * valid and this is the first response frame as well.
-		 */
-            if (frame_len == 2U && cstate->length == 0U &&
-                session->cstate.length == 0U) {
-                BT_DBG("record for UUID 0x%s not found",
-                       bt_uuid_str(session->param->uuid));
-                /* Call user UUID handler */
-                sdp_client_notify_result(session, UUID_NOT_RESOLVED);
-                net_buf_pull(buf, frame_len + sizeof(cstate->length));
-                goto iterate;
-            }
-
-            /* Get total value of all attributes to be collected */
-            frame_len -= sdp_client_get_total(session, buf, &total);
-
-            if (total > net_buf_tailroom(session->rec_buf)) {
-                BT_WARN("Not enough room for getting records data");
-                goto iterate;
-            }
-
-            net_buf_add_mem(session->rec_buf, buf->data, frame_len);
-            net_buf_pull(buf, frame_len);
-
-            /*
-		 * check if current response says there's next portion to be
-		 * fetched
-		 */
-            if (cstate->length) {
-                /* Cache original Continuation State in context */
-                memcpy(&session->cstate, cstate,
-                       sizeof(struct bt_sdp_pdu_cstate));
-
-                net_buf_pull(buf, cstate->length +
-                                      sizeof(cstate->length));
-
-                /* Request for next portion of attributes data */
-                sdp_client_ssa_search(session);
-                break;
-            }
-
-            net_buf_pull(buf, sizeof(cstate->length));
-
-            BT_DBG("UUID 0x%s resolved", bt_uuid_str(session->param->uuid));
-            sdp_client_notify_result(session, UUID_RESOLVED);
-        iterate:
-            /* Get next UUID and start resolving it */
-            sdp_client_params_iterator(session);
-            break;
-        default:
-            BT_DBG("PDU 0x%0x response not handled", hdr->op_code);
-            break;
+    /* Get total value of all attributes to be collected */
+    frame_len -= sdp_client_get_total(session, buf, &total);
+
+    if (total > net_buf_tailroom(session->rec_buf)) {
+      BT_WARN("Not enough room for getting records data");
+      goto iterate;
     }
 
-    return 0;
-}
+    net_buf_add_mem(session->rec_buf, buf->data, frame_len);
+    net_buf_pull(buf, frame_len);
 
-static int sdp_client_chan_connect(struct bt_sdp_client *session)
-{
-    return bt_l2cap_br_chan_connect(session->chan.chan.conn,
-                                    &session->chan.chan, SDP_PSM);
+    /*
+     * check if current response says there's next portion to be
+     * fetched
+     */
+    if (cstate->length) {
+      /* Cache original Continuation State in context */
+      memcpy(&session->cstate, cstate, sizeof(struct bt_sdp_pdu_cstate));
+
+      net_buf_pull(buf, cstate->length + sizeof(cstate->length));
+
+      /* Request for next portion of attributes data */
+      sdp_client_ssa_search(session);
+      break;
+    }
+
+    net_buf_pull(buf, sizeof(cstate->length));
+
+    BT_DBG("UUID 0x%s resolved", bt_uuid_str(session->param->uuid));
+    sdp_client_notify_result(session, UUID_RESOLVED);
+  iterate:
+    /* Get next UUID and start resolving it */
+    sdp_client_params_iterator(session);
+    break;
+  default:
+    BT_DBG("PDU 0x%0x response not handled", hdr->op_code);
+    break;
+  }
+
+  return 0;
 }
 
-static struct net_buf *sdp_client_alloc_buf(struct bt_l2cap_chan *chan)
-{
-    struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
-    struct net_buf *buf;
+static int sdp_client_chan_connect(struct bt_sdp_client *session) { return bt_l2cap_br_chan_connect(session->chan.chan.conn, &session->chan.chan, SDP_PSM); }
 
-    BT_DBG("session %p chan %p", session, chan);
+static struct net_buf *sdp_client_alloc_buf(struct bt_l2cap_chan *chan) {
+  struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
+  struct net_buf       *buf;
 
-    session->param = GET_PARAM(sys_slist_peek_head(&session->reqs));
+  BT_DBG("session %p chan %p", session, chan);
 
-    buf = net_buf_alloc(session->param->pool, K_FOREVER);
-    __ASSERT_NO_MSG(buf);
+  session->param = GET_PARAM(sys_slist_peek_head(&session->reqs));
 
-    return buf;
+  buf = net_buf_alloc(session->param->pool, K_FOREVER);
+  __ASSERT_NO_MSG(buf);
+
+  return buf;
 }
 
-static void sdp_client_connected(struct bt_l2cap_chan *chan)
-{
-    struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
+static void sdp_client_connected(struct bt_l2cap_chan *chan) {
+  struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
 
-    BT_DBG("session %p chan %p connected", session, chan);
+  BT_DBG("session %p chan %p connected", session, chan);
 
-    session->rec_buf = chan->ops->alloc_buf(chan);
+  session->rec_buf = chan->ops->alloc_buf(chan);
 
-    sdp_client_ssa_search(session);
+  sdp_client_ssa_search(session);
 }
 
-static void sdp_client_disconnected(struct bt_l2cap_chan *chan)
-{
-    struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
+static void sdp_client_disconnected(struct bt_l2cap_chan *chan) {
+  struct bt_sdp_client *session = SDP_CLIENT_CHAN(chan);
 
-    BT_DBG("session %p chan %p disconnected", session, chan);
+  BT_DBG("session %p chan %p disconnected", session, chan);
 
-    net_buf_unref(session->rec_buf);
+  net_buf_unref(session->rec_buf);
 
-    /*
-	 * Reset session excluding L2CAP channel member. Let's the channel
-	 * resets autonomous.
-	 */
-    (void)memset(&session->reqs, 0,
-                 sizeof(*session) - sizeof(session->chan));
+  /*
+   * Reset session excluding L2CAP channel member. Let's the channel
+   * resets autonomous.
+   */
+  (void)memset(&session->reqs, 0, sizeof(*session) - sizeof(session->chan));
 }
 
 static const struct bt_l2cap_chan_ops sdp_client_chan_ops = {
-    .connected = sdp_client_connected,
+    .connected    = sdp_client_connected,
     .disconnected = sdp_client_disconnected,
-    .recv = sdp_client_receive,
-    .alloc_buf = sdp_client_alloc_buf,
+    .recv         = sdp_client_receive,
+    .alloc_buf    = sdp_client_alloc_buf,
 };
 
-static struct bt_sdp_client *sdp_client_new_session(struct bt_conn *conn)
-{
-    int i;
+static struct bt_sdp_client *sdp_client_new_session(struct bt_conn *conn) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(bt_sdp_client_pool); i++) {
-        struct bt_sdp_client *session = &bt_sdp_client_pool[i];
-        int err;
+  for (i = 0; i < ARRAY_SIZE(bt_sdp_client_pool); i++) {
+    struct bt_sdp_client *session = &bt_sdp_client_pool[i];
+    int                   err;
 
-        if (session->chan.chan.conn) {
-            continue;
-        }
-
-        sys_slist_init(&session->reqs);
+    if (session->chan.chan.conn) {
+      continue;
+    }
 
-        session->chan.chan.ops = &sdp_client_chan_ops;
-        session->chan.chan.conn = conn;
-        session->chan.rx.mtu = SDP_CLIENT_MTU;
+    sys_slist_init(&session->reqs);
 
-        err = sdp_client_chan_connect(session);
-        if (err) {
-            (void)memset(session, 0, sizeof(*session));
-            BT_ERR("Cannot connect %d", err);
-            return NULL;
-        }
+    session->chan.chan.ops  = &sdp_client_chan_ops;
+    session->chan.chan.conn = conn;
+    session->chan.rx.mtu    = SDP_CLIENT_MTU;
 
-        return session;
+    err = sdp_client_chan_connect(session);
+    if (err) {
+      (void)memset(session, 0, sizeof(*session));
+      BT_ERR("Cannot connect %d", err);
+      return NULL;
     }
 
-    BT_ERR("No available SDP client context");
+    return session;
+  }
+
+  BT_ERR("No available SDP client context");
 
-    return NULL;
+  return NULL;
 }
 
-static struct bt_sdp_client *sdp_client_get_session(struct bt_conn *conn)
-{
-    int i;
+static struct bt_sdp_client *sdp_client_get_session(struct bt_conn *conn) {
+  int i;
 
-    for (i = 0; i < ARRAY_SIZE(bt_sdp_client_pool); i++) {
-        if (bt_sdp_client_pool[i].chan.chan.conn == conn) {
-            return &bt_sdp_client_pool[i];
-        }
+  for (i = 0; i < ARRAY_SIZE(bt_sdp_client_pool); i++) {
+    if (bt_sdp_client_pool[i].chan.chan.conn == conn) {
+      return &bt_sdp_client_pool[i];
     }
+  }
 
-    /*
-	 * Try to allocate session context since not found in pool and attempt
-	 * connect to remote SDP endpoint.
-	 */
-    return sdp_client_new_session(conn);
+  /*
+   * Try to allocate session context since not found in pool and attempt
+   * connect to remote SDP endpoint.
+   */
+  return sdp_client_new_session(conn);
 }
 
-int bt_sdp_discover(struct bt_conn *conn,
-                    const struct bt_sdp_discover_params *params)
-{
-    struct bt_sdp_client *session;
+int bt_sdp_discover(struct bt_conn *conn, const struct bt_sdp_discover_params *params) {
+  struct bt_sdp_client *session;
 
-    if (!params || !params->uuid || !params->func || !params->pool) {
-        BT_WARN("Invalid user params");
-        return -EINVAL;
-    }
+  if (!params || !params->uuid || !params->func || !params->pool) {
+    BT_WARN("Invalid user params");
+    return -EINVAL;
+  }
 
-    session = sdp_client_get_session(conn);
-    if (!session) {
-        return -ENOMEM;
-    }
+  session = sdp_client_get_session(conn);
+  if (!session) {
+    return -ENOMEM;
+  }
 
-    sys_slist_append(&session->reqs, (sys_snode_t *)¶ms->_node);
+  sys_slist_append(&session->reqs, (sys_snode_t *)¶ms->_node);
 
-    return 0;
+  return 0;
 }
 
 /* Helper getting length of data determined by DTD for integers */
-static inline ssize_t sdp_get_int_len(const uint8_t *data, size_t len)
-{
-    BT_ASSERT(data);
-
-    switch (data[0]) {
-        case BT_SDP_DATA_NIL:
-            return 1;
-        case BT_SDP_BOOL:
-        case BT_SDP_INT8:
-        case BT_SDP_UINT8:
-            if (len < 2) {
-                break;
-            }
-
-            return 2;
-        case BT_SDP_INT16:
-        case BT_SDP_UINT16:
-            if (len < 3) {
-                break;
-            }
-
-            return 3;
-        case BT_SDP_INT32:
-        case BT_SDP_UINT32:
-            if (len < 5) {
-                break;
-            }
-
-            return 5;
-        case BT_SDP_INT64:
-        case BT_SDP_UINT64:
-            if (len < 9) {
-                break;
-            }
-
-            return 9;
-        case BT_SDP_INT128:
-        case BT_SDP_UINT128:
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
-            return -EINVAL;
-    }
-
-    BT_ERR("Too short buffer length %zu", len);
-    return -EMSGSIZE;
+static inline ssize_t sdp_get_int_len(const uint8_t *data, size_t len) {
+  BT_ASSERT(data);
+
+  switch (data[0]) {
+  case BT_SDP_DATA_NIL:
+    return 1;
+  case BT_SDP_BOOL:
+  case BT_SDP_INT8:
+  case BT_SDP_UINT8:
+    if (len < 2) {
+      break;
+    }
+
+    return 2;
+  case BT_SDP_INT16:
+  case BT_SDP_UINT16:
+    if (len < 3) {
+      break;
+    }
+
+    return 3;
+  case BT_SDP_INT32:
+  case BT_SDP_UINT32:
+    if (len < 5) {
+      break;
+    }
+
+    return 5;
+  case BT_SDP_INT64:
+  case BT_SDP_UINT64:
+    if (len < 9) {
+      break;
+    }
+
+    return 9;
+  case BT_SDP_INT128:
+  case BT_SDP_UINT128:
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
+    return -EINVAL;
+  }
+
+  BT_ERR("Too short buffer length %zu", len);
+  return -EMSGSIZE;
 }
 
 /* Helper getting length of data determined by DTD for UUID */
-static inline ssize_t sdp_get_uuid_len(const uint8_t *data, size_t len)
-{
-    BT_ASSERT(data);
-
-    switch (data[0]) {
-        case BT_SDP_UUID16:
-            if (len < 3) {
-                break;
-            }
-
-            return 3;
-        case BT_SDP_UUID32:
-            if (len < 5) {
-                break;
-            }
-
-            return 5;
-        case BT_SDP_UUID128:
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
-            return -EINVAL;
-    }
-
-    BT_ERR("Too short buffer length %zu", len);
-    return -EMSGSIZE;
+static inline ssize_t sdp_get_uuid_len(const uint8_t *data, size_t len) {
+  BT_ASSERT(data);
+
+  switch (data[0]) {
+  case BT_SDP_UUID16:
+    if (len < 3) {
+      break;
+    }
+
+    return 3;
+  case BT_SDP_UUID32:
+    if (len < 5) {
+      break;
+    }
+
+    return 5;
+  case BT_SDP_UUID128:
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
+    return -EINVAL;
+  }
+
+  BT_ERR("Too short buffer length %zu", len);
+  return -EMSGSIZE;
 }
 
 /* Helper getting length of data determined by DTD for strings */
-static inline ssize_t sdp_get_str_len(const uint8_t *data, size_t len)
-{
-    const uint8_t *pnext;
+static inline ssize_t sdp_get_str_len(const uint8_t *data, size_t len) {
+  const uint8_t *pnext;
 
-    BT_ASSERT(data);
+  BT_ASSERT(data);
 
-    /* validate len for pnext safe use to read next 8bit value */
-    if (len < 2) {
-        goto err;
-    }
-
-    pnext = data + sizeof(uint8_t);
+  /* validate len for pnext safe use to read next 8bit value */
+  if (len < 2) {
+    goto err;
+  }
 
-    switch (data[0]) {
-        case BT_SDP_TEXT_STR8:
-        case BT_SDP_URL_STR8:
-            if (len < (2 + pnext[0])) {
-                break;
-            }
+  pnext = data + sizeof(uint8_t);
 
-            return 2 + pnext[0];
-        case BT_SDP_TEXT_STR16:
-        case BT_SDP_URL_STR16:
-            /* validate len for pnext safe use to read 16bit value */
-            if (len < 3) {
-                break;
-            }
+  switch (data[0]) {
+  case BT_SDP_TEXT_STR8:
+  case BT_SDP_URL_STR8:
+    if (len < (2 + pnext[0])) {
+      break;
+    }
 
-            if (len < (3 + sys_get_be16(pnext))) {
-                break;
-            }
+    return 2 + pnext[0];
+  case BT_SDP_TEXT_STR16:
+  case BT_SDP_URL_STR16:
+    /* validate len for pnext safe use to read 16bit value */
+    if (len < 3) {
+      break;
+    }
 
-            return 3 + sys_get_be16(pnext);
-        case BT_SDP_TEXT_STR32:
-        case BT_SDP_URL_STR32:
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
-            return -EINVAL;
+    if (len < (3 + sys_get_be16(pnext))) {
+      break;
     }
+
+    return 3 + sys_get_be16(pnext);
+  case BT_SDP_TEXT_STR32:
+  case BT_SDP_URL_STR32:
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
+    return -EINVAL;
+  }
 err:
-    BT_ERR("Too short buffer length %zu", len);
-    return -EMSGSIZE;
+  BT_ERR("Too short buffer length %zu", len);
+  return -EMSGSIZE;
 }
 
 /* Helper getting length of data determined by DTD for sequences */
-static inline ssize_t sdp_get_seq_len(const uint8_t *data, size_t len)
-{
-    const uint8_t *pnext;
-
-    BT_ASSERT(data);
+static inline ssize_t sdp_get_seq_len(const uint8_t *data, size_t len) {
+  const uint8_t *pnext;
 
-    /* validate len for pnext safe use to read 8bit bit value */
-    if (len < 2) {
-        goto err;
-    }
+  BT_ASSERT(data);
 
-    pnext = data + sizeof(uint8_t);
+  /* validate len for pnext safe use to read 8bit bit value */
+  if (len < 2) {
+    goto err;
+  }
 
-    switch (data[0]) {
-        case BT_SDP_SEQ8:
-        case BT_SDP_ALT8:
-            if (len < (2 + pnext[0])) {
-                break;
-            }
+  pnext = data + sizeof(uint8_t);
 
-            return 2 + pnext[0];
-        case BT_SDP_SEQ16:
-        case BT_SDP_ALT16:
-            /* validate len for pnext safe use to read 16bit value */
-            if (len < 3) {
-                break;
-            }
+  switch (data[0]) {
+  case BT_SDP_SEQ8:
+  case BT_SDP_ALT8:
+    if (len < (2 + pnext[0])) {
+      break;
+    }
 
-            if (len < (3 + sys_get_be16(pnext))) {
-                break;
-            }
+    return 2 + pnext[0];
+  case BT_SDP_SEQ16:
+  case BT_SDP_ALT16:
+    /* validate len for pnext safe use to read 16bit value */
+    if (len < 3) {
+      break;
+    }
 
-            return 3 + sys_get_be16(pnext);
-        case BT_SDP_SEQ32:
-        case BT_SDP_ALT32:
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
-            return -EINVAL;
+    if (len < (3 + sys_get_be16(pnext))) {
+      break;
     }
+
+    return 3 + sys_get_be16(pnext);
+  case BT_SDP_SEQ32:
+  case BT_SDP_ALT32:
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x", data[0]);
+    return -EINVAL;
+  }
 err:
-    BT_ERR("Too short buffer length %zu", len);
-    return -EMSGSIZE;
+  BT_ERR("Too short buffer length %zu", len);
+  return -EMSGSIZE;
 }
 
 /* Helper getting length of attribute value data */
-static ssize_t sdp_get_attr_value_len(const uint8_t *data, size_t len)
-{
-    BT_ASSERT(data);
-
-    BT_DBG("Attr val DTD 0x%02x", data[0]);
-
-    switch (data[0]) {
-        case BT_SDP_DATA_NIL:
-        case BT_SDP_BOOL:
-        case BT_SDP_UINT8:
-        case BT_SDP_UINT16:
-        case BT_SDP_UINT32:
-        case BT_SDP_UINT64:
-        case BT_SDP_UINT128:
-        case BT_SDP_INT8:
-        case BT_SDP_INT16:
-        case BT_SDP_INT32:
-        case BT_SDP_INT64:
-        case BT_SDP_INT128:
-            return sdp_get_int_len(data, len);
-        case BT_SDP_UUID16:
-        case BT_SDP_UUID32:
-        case BT_SDP_UUID128:
-            return sdp_get_uuid_len(data, len);
-        case BT_SDP_TEXT_STR8:
-        case BT_SDP_TEXT_STR16:
-        case BT_SDP_TEXT_STR32:
-        case BT_SDP_URL_STR8:
-        case BT_SDP_URL_STR16:
-        case BT_SDP_URL_STR32:
-            return sdp_get_str_len(data, len);
-        case BT_SDP_SEQ8:
-        case BT_SDP_SEQ16:
-        case BT_SDP_SEQ32:
-        case BT_SDP_ALT8:
-        case BT_SDP_ALT16:
-        case BT_SDP_ALT32:
-            return sdp_get_seq_len(data, len);
-        default:
-            BT_ERR("Unknown DTD 0x%02x", data[0]);
-            return -EINVAL;
-    }
+static ssize_t sdp_get_attr_value_len(const uint8_t *data, size_t len) {
+  BT_ASSERT(data);
+
+  BT_DBG("Attr val DTD 0x%02x", data[0]);
+
+  switch (data[0]) {
+  case BT_SDP_DATA_NIL:
+  case BT_SDP_BOOL:
+  case BT_SDP_UINT8:
+  case BT_SDP_UINT16:
+  case BT_SDP_UINT32:
+  case BT_SDP_UINT64:
+  case BT_SDP_UINT128:
+  case BT_SDP_INT8:
+  case BT_SDP_INT16:
+  case BT_SDP_INT32:
+  case BT_SDP_INT64:
+  case BT_SDP_INT128:
+    return sdp_get_int_len(data, len);
+  case BT_SDP_UUID16:
+  case BT_SDP_UUID32:
+  case BT_SDP_UUID128:
+    return sdp_get_uuid_len(data, len);
+  case BT_SDP_TEXT_STR8:
+  case BT_SDP_TEXT_STR16:
+  case BT_SDP_TEXT_STR32:
+  case BT_SDP_URL_STR8:
+  case BT_SDP_URL_STR16:
+  case BT_SDP_URL_STR32:
+    return sdp_get_str_len(data, len);
+  case BT_SDP_SEQ8:
+  case BT_SDP_SEQ16:
+  case BT_SDP_SEQ32:
+  case BT_SDP_ALT8:
+  case BT_SDP_ALT16:
+  case BT_SDP_ALT32:
+    return sdp_get_seq_len(data, len);
+  default:
+    BT_ERR("Unknown DTD 0x%02x", data[0]);
+    return -EINVAL;
+  }
 }
 
 /* Type holding UUID item and related to it specific information. */
 struct bt_sdp_uuid_desc {
-    union {
-        struct bt_uuid uuid;
-        struct bt_uuid_16 uuid16;
-        struct bt_uuid_32 uuid32;
-    };
-    uint16_t attr_id;
-    uint8_t *params;
-    uint16_t params_len;
+  union {
+    struct bt_uuid    uuid;
+    struct bt_uuid_16 uuid16;
+    struct bt_uuid_32 uuid32;
+  };
+  uint16_t attr_id;
+  uint8_t *params;
+  uint16_t params_len;
 };
 
 /* Generic attribute item collector. */
 struct bt_sdp_attr_item {
-    /*  Attribute identifier. */
-    uint16_t attr_id;
-    /*  Address of beginning attribute value taken from original buffer
-	 *  holding response from server.
-	 */
-    uint8_t *val;
-    /*  Says about the length of attribute value. */
-    uint16_t len;
+  /*  Attribute identifier. */
+  uint16_t attr_id;
+  /*  Address of beginning attribute value taken from original buffer
+   *  holding response from server.
+   */
+  uint8_t *val;
+  /*  Says about the length of attribute value. */
+  uint16_t len;
 };
 
-static int bt_sdp_get_attr(const struct net_buf *buf,
-                           struct bt_sdp_attr_item *attr, uint16_t attr_id)
-{
-    uint8_t *data;
-    uint16_t id;
+static int bt_sdp_get_attr(const struct net_buf *buf, struct bt_sdp_attr_item *attr, uint16_t attr_id) {
+  uint8_t *data;
+  uint16_t id;
 
-    data = buf->data;
-    while (data - buf->data < buf->len) {
-        ssize_t dlen;
+  data = buf->data;
+  while (data - buf->data < buf->len) {
+    ssize_t dlen;
 
-        /* data need to point to attribute id descriptor field (DTD)*/
-        if (data[0] != BT_SDP_UINT16) {
-            BT_ERR("Invalid descriptor 0x%02x", data[0]);
-            return -EINVAL;
-        }
-
-        data += sizeof(uint8_t);
-        id = sys_get_be16(data);
-        BT_DBG("Attribute ID 0x%04x", id);
-        data += sizeof(uint16_t);
+    /* data need to point to attribute id descriptor field (DTD)*/
+    if (data[0] != BT_SDP_UINT16) {
+      BT_ERR("Invalid descriptor 0x%02x", data[0]);
+      return -EINVAL;
+    }
 
-        dlen = sdp_get_attr_value_len(data,
-                                      buf->len - (data - buf->data));
-        if (dlen < 0) {
-            BT_ERR("Invalid attribute value data");
-            return -EINVAL;
-        }
+    data += sizeof(uint8_t);
+    id = sys_get_be16(data);
+    BT_DBG("Attribute ID 0x%04x", id);
+    data += sizeof(uint16_t);
 
-        if (id == attr_id) {
-            BT_DBG("Attribute ID 0x%04x Value found", id);
-            /*
-			 * Initialize attribute value buffer data using selected
-			 * data slice from original buffer.
-			 */
-            attr->val = data;
-            attr->len = dlen;
-            attr->attr_id = id;
-            return 0;
-        }
+    dlen = sdp_get_attr_value_len(data, buf->len - (data - buf->data));
+    if (dlen < 0) {
+      BT_ERR("Invalid attribute value data");
+      return -EINVAL;
+    }
 
-        data += dlen;
+    if (id == attr_id) {
+      BT_DBG("Attribute ID 0x%04x Value found", id);
+      /*
+       * Initialize attribute value buffer data using selected
+       * data slice from original buffer.
+       */
+      attr->val     = data;
+      attr->len     = dlen;
+      attr->attr_id = id;
+      return 0;
     }
 
-    return -ENOENT;
+    data += dlen;
+  }
+
+  return -ENOENT;
 }
 
 /* reads SEQ item length, moves input buffer data reader forward */
-static ssize_t sdp_get_seq_len_item(uint8_t **data, size_t len)
-{
-    const uint8_t *pnext;
+static ssize_t sdp_get_seq_len_item(uint8_t **data, size_t len) {
+  const uint8_t *pnext;
 
-    BT_ASSERT(data);
-    BT_ASSERT(*data);
+  BT_ASSERT(data);
+  BT_ASSERT(*data);
 
-    /* validate len for pnext safe use to read 8bit bit value */
-    if (len < 2) {
-        goto err;
-    }
-
-    pnext = *data + sizeof(uint8_t);
-
-    switch (*data[0]) {
-        case BT_SDP_SEQ8:
-            if (len < (2 + pnext[0])) {
-                break;
-            }
-
-            *data += 2;
-            return pnext[0];
-        case BT_SDP_SEQ16:
-            /* validate len for pnext safe use to read 16bit value */
-            if (len < 3) {
-                break;
-            }
-
-            if (len < (3 + sys_get_be16(pnext))) {
-                break;
-            }
-
-            *data += 3;
-            return sys_get_be16(pnext);
-        case BT_SDP_SEQ32:
-            /* validate len for pnext safe use to read 32bit value */
-            if (len < 5) {
-                break;
-            }
-
-            if (len < (5 + sys_get_be32(pnext))) {
-                break;
-            }
-
-            *data += 5;
-            return sys_get_be32(pnext);
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x", *data[0]);
-            return -EINVAL;
-    }
-err:
-    BT_ERR("Too short buffer length %zu", len);
-    return -EMSGSIZE;
-}
+  /* validate len for pnext safe use to read 8bit bit value */
+  if (len < 2) {
+    goto err;
+  }
 
-static int sdp_get_uuid_data(const struct bt_sdp_attr_item *attr,
-                             struct bt_sdp_uuid_desc *pd,
-                             uint16_t proto_profile)
-{
-    /* get start address of attribute value */
-    uint8_t *p = attr->val;
-    ssize_t slen;
+  pnext = *data + sizeof(uint8_t);
 
-    BT_ASSERT(p);
+  switch (*data[0]) {
+  case BT_SDP_SEQ8:
+    if (len < (2 + pnext[0])) {
+      break;
+    }
 
-    /* Attribute value is a SEQ, get length of parent SEQ frame */
-    slen = sdp_get_seq_len_item(&p, attr->len);
-    if (slen < 0) {
-        return slen;
+    *data += 2;
+    return pnext[0];
+  case BT_SDP_SEQ16:
+    /* validate len for pnext safe use to read 16bit value */
+    if (len < 3) {
+      break;
     }
 
-    /* start reading stacked UUIDs in analyzed sequences tree */
-    while (p - attr->val < attr->len) {
-        size_t to_end, left = 0;
+    if (len < (3 + sys_get_be16(pnext))) {
+      break;
+    }
 
-        /* to_end tells how far to the end of input buffer */
-        to_end = attr->len - (p - attr->val);
-        /* how long is current UUID's item data associated to */
-        slen = sdp_get_seq_len_item(&p, to_end);
-        if (slen < 0) {
-            return slen;
-        }
+    *data += 3;
+    return sys_get_be16(pnext);
+  case BT_SDP_SEQ32:
+    /* validate len for pnext safe use to read 32bit value */
+    if (len < 5) {
+      break;
+    }
 
-        /* left tells how far is to the end of current UUID */
-        left = slen;
+    if (len < (5 + sys_get_be32(pnext))) {
+      break;
+    }
 
-        /* check if at least DTD + UUID16 can be read safely */
-        if (left < 3) {
-            return -EMSGSIZE;
-        }
+    *data += 5;
+    return sys_get_be32(pnext);
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x", *data[0]);
+    return -EINVAL;
+  }
+err:
+  BT_ERR("Too short buffer length %zu", len);
+  return -EMSGSIZE;
+}
 
-        /* check DTD and get stacked UUID value */
-        switch (p[0]) {
-            case BT_SDP_UUID16:
-                memcpy(&pd->uuid16,
-                       BT_UUID_DECLARE_16(sys_get_be16(++p)),
-                       sizeof(struct bt_uuid_16));
-                p += sizeof(uint16_t);
-                left -= sizeof(uint16_t);
-                break;
-            case BT_SDP_UUID32:
-                /* check if valid UUID32 can be read safely */
-                if (left < 5) {
-                    return -EMSGSIZE;
-                }
-
-                memcpy(&pd->uuid32,
-                       BT_UUID_DECLARE_32(sys_get_be32(++p)),
-                       sizeof(struct bt_uuid_32));
-                p += sizeof(uint32_t);
-                left -= sizeof(uint32_t);
-                break;
-            default:
-                BT_ERR("Invalid/unhandled DTD 0x%02x\n", p[0]);
-                return -EINVAL;
-        }
+static int sdp_get_uuid_data(const struct bt_sdp_attr_item *attr, struct bt_sdp_uuid_desc *pd, uint16_t proto_profile) {
+  /* get start address of attribute value */
+  uint8_t *p = attr->val;
+  ssize_t  slen;
 
-        /* include last DTD in p[0] size itself updating left */
-        left -= sizeof(p[0]);
+  BT_ASSERT(p);
 
-        /*
-		 * Check if current UUID value matches input one given by user.
-		 * If found save it's location and length and return.
-		 */
-        if ((proto_profile == BT_UUID_16(&pd->uuid)->val) ||
-            (proto_profile == BT_UUID_32(&pd->uuid)->val)) {
-            pd->params = p;
-            pd->params_len = left;
+  /* Attribute value is a SEQ, get length of parent SEQ frame */
+  slen = sdp_get_seq_len_item(&p, attr->len);
+  if (slen < 0) {
+    return slen;
+  }
 
-            BT_DBG("UUID 0x%s found", bt_uuid_str(&pd->uuid));
-            return 0;
-        }
+  /* start reading stacked UUIDs in analyzed sequences tree */
+  while (p - attr->val < attr->len) {
+    size_t to_end, left = 0;
 
-        /* skip left octets to point beginning of next UUID in tree */
-        p += left;
+    /* to_end tells how far to the end of input buffer */
+    to_end = attr->len - (p - attr->val);
+    /* how long is current UUID's item data associated to */
+    slen = sdp_get_seq_len_item(&p, to_end);
+    if (slen < 0) {
+      return slen;
     }
 
-    BT_DBG("Value 0x%04x not found", proto_profile);
-    return -ENOENT;
-}
+    /* left tells how far is to the end of current UUID */
+    left = slen;
 
-/*
- * Helper extracting specific parameters associated with UUID node given in
- * protocol descriptor list or profile descriptor list.
- */
-static int sdp_get_param_item(struct bt_sdp_uuid_desc *pd_item, uint16_t *param)
-{
-    const uint8_t *p = pd_item->params;
-    bool len_err = false;
-
-    BT_ASSERT(p);
-
-    BT_DBG("Getting UUID's 0x%s params", bt_uuid_str(&pd_item->uuid));
+    /* check if at least DTD + UUID16 can be read safely */
+    if (left < 3) {
+      return -EMSGSIZE;
+    }
 
+    /* check DTD and get stacked UUID value */
     switch (p[0]) {
-        case BT_SDP_UINT8:
-            /* check if 8bits value can be read safely */
-            if (pd_item->params_len < 2) {
-                len_err = true;
-                break;
-            }
-            *param = (++p)[0];
-            p += sizeof(uint8_t);
-            break;
-        case BT_SDP_UINT16:
-            /* check if 16bits value can be read safely */
-            if (pd_item->params_len < 3) {
-                len_err = true;
-                break;
-            }
-            *param = sys_get_be16(++p);
-            p += sizeof(uint16_t);
-            break;
-        case BT_SDP_UINT32:
-            /* check if 32bits value can be read safely */
-            if (pd_item->params_len < 5) {
-                len_err = true;
-                break;
-            }
-            *param = sys_get_be32(++p);
-            p += sizeof(uint32_t);
-            break;
-        default:
-            BT_ERR("Invalid/unhandled DTD 0x%02x\n", p[0]);
-            return -EINVAL;
-    }
-    /*
-	 * Check if no more data than already read is associated with UUID. In
-	 * valid case after getting parameter we should reach data buf end.
-	 */
-    if (p - pd_item->params != pd_item->params_len || len_err) {
-        BT_DBG("Invalid param buffer length");
+    case BT_SDP_UUID16:
+      memcpy(&pd->uuid16, BT_UUID_DECLARE_16(sys_get_be16(++p)), sizeof(struct bt_uuid_16));
+      p += sizeof(uint16_t);
+      left -= sizeof(uint16_t);
+      break;
+    case BT_SDP_UUID32:
+      /* check if valid UUID32 can be read safely */
+      if (left < 5) {
         return -EMSGSIZE;
+      }
+
+      memcpy(&pd->uuid32, BT_UUID_DECLARE_32(sys_get_be32(++p)), sizeof(struct bt_uuid_32));
+      p += sizeof(uint32_t);
+      left -= sizeof(uint32_t);
+      break;
+    default:
+      BT_ERR("Invalid/unhandled DTD 0x%02x\n", p[0]);
+      return -EINVAL;
     }
 
-    return 0;
-}
+    /* include last DTD in p[0] size itself updating left */
+    left -= sizeof(p[0]);
 
-int bt_sdp_get_proto_param(const struct net_buf *buf, enum bt_sdp_proto proto,
-                           uint16_t *param)
-{
-    struct bt_sdp_attr_item attr;
-    struct bt_sdp_uuid_desc pd;
-    int res;
+    /*
+     * Check if current UUID value matches input one given by user.
+     * If found save it's location and length and return.
+     */
+    if ((proto_profile == BT_UUID_16(&pd->uuid)->val) || (proto_profile == BT_UUID_32(&pd->uuid)->val)) {
+      pd->params     = p;
+      pd->params_len = left;
 
-    if (proto != BT_SDP_PROTO_RFCOMM && proto != BT_SDP_PROTO_L2CAP) {
-        BT_ERR("Invalid protocol specifier");
-        return -EINVAL;
+      BT_DBG("UUID 0x%s found", bt_uuid_str(&pd->uuid));
+      return 0;
     }
 
-    res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_PROTO_DESC_LIST);
-    if (res < 0) {
-        BT_WARN("Attribute 0x%04x not found, err %d",
-                BT_SDP_ATTR_PROTO_DESC_LIST, res);
-        return res;
-    }
+    /* skip left octets to point beginning of next UUID in tree */
+    p += left;
+  }
 
-    res = sdp_get_uuid_data(&attr, &pd, proto);
-    if (res < 0) {
-        BT_WARN("Protocol specifier 0x%04x not found, err %d", proto,
-                res);
-        return res;
-    }
+  BT_DBG("Value 0x%04x not found", proto_profile);
+  return -ENOENT;
+}
 
-    return sdp_get_param_item(&pd, param);
+/*
+ * Helper extracting specific parameters associated with UUID node given in
+ * protocol descriptor list or profile descriptor list.
+ */
+static int sdp_get_param_item(struct bt_sdp_uuid_desc *pd_item, uint16_t *param) {
+  const uint8_t *p       = pd_item->params;
+  bool           len_err = false;
+
+  BT_ASSERT(p);
+
+  BT_DBG("Getting UUID's 0x%s params", bt_uuid_str(&pd_item->uuid));
+
+  switch (p[0]) {
+  case BT_SDP_UINT8:
+    /* check if 8bits value can be read safely */
+    if (pd_item->params_len < 2) {
+      len_err = true;
+      break;
+    }
+    *param = (++p)[0];
+    p += sizeof(uint8_t);
+    break;
+  case BT_SDP_UINT16:
+    /* check if 16bits value can be read safely */
+    if (pd_item->params_len < 3) {
+      len_err = true;
+      break;
+    }
+    *param = sys_get_be16(++p);
+    p += sizeof(uint16_t);
+    break;
+  case BT_SDP_UINT32:
+    /* check if 32bits value can be read safely */
+    if (pd_item->params_len < 5) {
+      len_err = true;
+      break;
+    }
+    *param = sys_get_be32(++p);
+    p += sizeof(uint32_t);
+    break;
+  default:
+    BT_ERR("Invalid/unhandled DTD 0x%02x\n", p[0]);
+    return -EINVAL;
+  }
+  /*
+   * Check if no more data than already read is associated with UUID. In
+   * valid case after getting parameter we should reach data buf end.
+   */
+  if (p - pd_item->params != pd_item->params_len || len_err) {
+    BT_DBG("Invalid param buffer length");
+    return -EMSGSIZE;
+  }
+
+  return 0;
 }
 
-int bt_sdp_get_profile_version(const struct net_buf *buf, uint16_t profile,
-                               uint16_t *version)
-{
-    struct bt_sdp_attr_item attr;
-    struct bt_sdp_uuid_desc pd;
-    int res;
+int bt_sdp_get_proto_param(const struct net_buf *buf, enum bt_sdp_proto proto, uint16_t *param) {
+  struct bt_sdp_attr_item attr;
+  struct bt_sdp_uuid_desc pd;
+  int                     res;
+
+  if (proto != BT_SDP_PROTO_RFCOMM && proto != BT_SDP_PROTO_L2CAP) {
+    BT_ERR("Invalid protocol specifier");
+    return -EINVAL;
+  }
+
+  res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_PROTO_DESC_LIST);
+  if (res < 0) {
+    BT_WARN("Attribute 0x%04x not found, err %d", BT_SDP_ATTR_PROTO_DESC_LIST, res);
+    return res;
+  }
+
+  res = sdp_get_uuid_data(&attr, &pd, proto);
+  if (res < 0) {
+    BT_WARN("Protocol specifier 0x%04x not found, err %d", proto, res);
+    return res;
+  }
+
+  return sdp_get_param_item(&pd, param);
+}
 
-    res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_PROFILE_DESC_LIST);
-    if (res < 0) {
-        BT_WARN("Attribute 0x%04x not found, err %d",
-                BT_SDP_ATTR_PROFILE_DESC_LIST, res);
-        return res;
-    }
+int bt_sdp_get_profile_version(const struct net_buf *buf, uint16_t profile, uint16_t *version) {
+  struct bt_sdp_attr_item attr;
+  struct bt_sdp_uuid_desc pd;
+  int                     res;
 
-    res = sdp_get_uuid_data(&attr, &pd, profile);
-    if (res < 0) {
-        BT_WARN("Profile 0x%04x not found, err %d", profile, res);
-        return res;
-    }
+  res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_PROFILE_DESC_LIST);
+  if (res < 0) {
+    BT_WARN("Attribute 0x%04x not found, err %d", BT_SDP_ATTR_PROFILE_DESC_LIST, res);
+    return res;
+  }
+
+  res = sdp_get_uuid_data(&attr, &pd, profile);
+  if (res < 0) {
+    BT_WARN("Profile 0x%04x not found, err %d", profile, res);
+    return res;
+  }
 
-    return sdp_get_param_item(&pd, version);
+  return sdp_get_param_item(&pd, version);
 }
 
-int bt_sdp_get_features(const struct net_buf *buf, uint16_t *features)
-{
-    struct bt_sdp_attr_item attr;
-    const uint8_t *p;
-    int res;
+int bt_sdp_get_features(const struct net_buf *buf, uint16_t *features) {
+  struct bt_sdp_attr_item attr;
+  const uint8_t          *p;
+  int                     res;
 
-    res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_SUPPORTED_FEATURES);
-    if (res < 0) {
-        BT_WARN("Attribute 0x%04x not found, err %d",
-                BT_SDP_ATTR_SUPPORTED_FEATURES, res);
-        return res;
-    }
+  res = bt_sdp_get_attr(buf, &attr, BT_SDP_ATTR_SUPPORTED_FEATURES);
+  if (res < 0) {
+    BT_WARN("Attribute 0x%04x not found, err %d", BT_SDP_ATTR_SUPPORTED_FEATURES, res);
+    return res;
+  }
 
-    p = attr.val;
-    BT_ASSERT(p);
+  p = attr.val;
+  BT_ASSERT(p);
 
-    if (p[0] != BT_SDP_UINT16) {
-        BT_ERR("Invalid DTD 0x%02x", p[0]);
-        return -EINVAL;
-    }
+  if (p[0] != BT_SDP_UINT16) {
+    BT_ERR("Invalid DTD 0x%02x", p[0]);
+    return -EINVAL;
+  }
 
-    /* assert 16bit can be read safely */
-    if (attr.len < 3) {
-        BT_ERR("Data length too short %u", attr.len);
-        return -EMSGSIZE;
-    }
+  /* assert 16bit can be read safely */
+  if (attr.len < 3) {
+    BT_ERR("Data length too short %u", attr.len);
+    return -EMSGSIZE;
+  }
 
-    *features = sys_get_be16(++p);
-    p += sizeof(uint16_t);
+  *features = sys_get_be16(++p);
+  p += sizeof(uint16_t);
 
-    if (p - attr.val != attr.len) {
-        BT_ERR("Invalid data length %u", attr.len);
-        return -EMSGSIZE;
-    }
+  if (p - attr.val != attr.len) {
+    BT_ERR("Invalid data length %u", attr.len);
+    return -EMSGSIZE;
+  }
 
-    return 0;
+  return 0;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c
index 1eaffca7b..0f6725a6d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/settings.c
@@ -4,425 +4,347 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
 #include 
 #include 
+#include 
+#include 
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_SETTINGS)
 #define LOG_MODULE_NAME bt_settings
 #include "log.h"
 
+#include "gatt.h"
 #include "hci_core.h"
-#include "settings.h"
 #include "keys.h"
-#include "gatt.h"
+#include "settings.h"
 #if defined(BFLB_BLE)
 #include 
 #if defined(CONFIG_BT_SETTINGS)
 #include "easyflash.h"
 #endif
-#include 
 #include "portable.h"
+#include 
 #endif
 
 #if defined(CONFIG_BT_SETTINGS_USE_PRINTK)
-void bt_settings_encode_key(char *path, size_t path_size, const char *subsys,
-                            bt_addr_le_t *addr, const char *key)
-{
-    if (key) {
-        snprintk(path, path_size,
-                 "bt/%s/%02x%02x%02x%02x%02x%02x%u/%s", subsys,
-                 addr->a.val[5], addr->a.val[4], addr->a.val[3],
-                 addr->a.val[2], addr->a.val[1], addr->a.val[0],
-                 addr->type, key);
-    } else {
-        snprintk(path, path_size,
-                 "bt/%s/%02x%02x%02x%02x%02x%02x%u", subsys,
-                 addr->a.val[5], addr->a.val[4], addr->a.val[3],
-                 addr->a.val[2], addr->a.val[1], addr->a.val[0],
-                 addr->type);
-    }
-
-    BT_DBG("Encoded path %s", log_strdup(path));
+void bt_settings_encode_key(char *path, size_t path_size, const char *subsys, bt_addr_le_t *addr, const char *key) {
+  if (key) {
+    snprintk(path, path_size, "bt/%s/%02x%02x%02x%02x%02x%02x%u/%s", subsys, addr->a.val[5], addr->a.val[4], addr->a.val[3], addr->a.val[2], addr->a.val[1], addr->a.val[0], addr->type, key);
+  } else {
+    snprintk(path, path_size, "bt/%s/%02x%02x%02x%02x%02x%02x%u", subsys, addr->a.val[5], addr->a.val[4], addr->a.val[3], addr->a.val[2], addr->a.val[1], addr->a.val[0], addr->type);
+  }
+
+  BT_DBG("Encoded path %s", log_strdup(path));
 }
 #else
-void bt_settings_encode_key(char *path, size_t path_size, const char *subsys,
-                            bt_addr_le_t *addr, const char *key)
-{
-    size_t len = 3;
-
-    /* Skip if path_size is less than 3; strlen("bt/") */
+void bt_settings_encode_key(char *path, size_t path_size, const char *subsys, bt_addr_le_t *addr, const char *key) {
+  size_t len = 3;
+
+  /* Skip if path_size is less than 3; strlen("bt/") */
+  if (len < path_size) {
+    /* Key format:
+     *  "bt///", "/" is optional
+     */
+    strcpy(path, "bt/");
+    strncpy(&path[len], subsys, path_size - len);
+    len = strlen(path);
     if (len < path_size) {
-        /* Key format:
-		 *  "bt///", "/" is optional
-		 */
-        strcpy(path, "bt/");
-        strncpy(&path[len], subsys, path_size - len);
-        len = strlen(path);
-        if (len < path_size) {
-            path[len] = '/';
-            len++;
-        }
-
-        for (s8_t i = 5; i >= 0 && len < path_size; i--) {
-            len += bin2hex(&addr->a.val[i], 1, &path[len],
-                           path_size - len);
-        }
-
-        if (len < path_size) {
-            /* Type can be either BT_ADDR_LE_PUBLIC or
-			 * BT_ADDR_LE_RANDOM (value 0 or 1)
-			 */
-            path[len] = '0' + addr->type;
-            len++;
-        }
-
-        if (key && len < path_size) {
-            path[len] = '/';
-            len++;
-            strncpy(&path[len], key, path_size - len);
-            len += strlen(&path[len]);
-        }
-
-        if (len >= path_size) {
-            /* Truncate string */
-            path[path_size - 1] = '\0';
-        }
-    } else if (path_size > 0) {
-        *path = '\0';
+      path[len] = '/';
+      len++;
     }
 
-    BT_DBG("Encoded path %s", log_strdup(path));
-}
-#endif
+    for (s8_t i = 5; i >= 0 && len < path_size; i--) {
+      len += bin2hex(&addr->a.val[i], 1, &path[len], path_size - len);
+    }
 
-#if !defined(BFLB_BLE)
-int bt_settings_decode_key(const char *key, bt_addr_le_t *addr)
-{
-    if (settings_name_next(key, NULL) != 13) {
-        return -EINVAL;
+    if (len < path_size) {
+      /* Type can be either BT_ADDR_LE_PUBLIC or
+       * BT_ADDR_LE_RANDOM (value 0 or 1)
+       */
+      path[len] = '0' + addr->type;
+      len++;
     }
 
-    if (key[12] == '0') {
-        addr->type = BT_ADDR_LE_PUBLIC;
-    } else if (key[12] == '1') {
-        addr->type = BT_ADDR_LE_RANDOM;
-    } else {
-        return -EINVAL;
+    if (key && len < path_size) {
+      path[len] = '/';
+      len++;
+      strncpy(&path[len], key, path_size - len);
+      len += strlen(&path[len]);
     }
 
-    for (u8_t i = 0; i < 6; i++) {
-        hex2bin(&key[i * 2], 2, &addr->a.val[5 - i], 1);
+    if (len >= path_size) {
+      /* Truncate string */
+      path[path_size - 1] = '\0';
     }
+  } else if (path_size > 0) {
+    *path = '\0';
+  }
 
-    BT_DBG("Decoded %s as %s", log_strdup(key), bt_addr_le_str(addr));
+  BT_DBG("Encoded path %s", log_strdup(path));
+}
+#endif
 
-    return 0;
+#if !defined(BFLB_BLE)
+int bt_settings_decode_key(const char *key, bt_addr_le_t *addr) {
+  if (settings_name_next(key, NULL) != 13) {
+    return -EINVAL;
+  }
+
+  if (key[12] == '0') {
+    addr->type = BT_ADDR_LE_PUBLIC;
+  } else if (key[12] == '1') {
+    addr->type = BT_ADDR_LE_RANDOM;
+  } else {
+    return -EINVAL;
+  }
+
+  for (u8_t i = 0; i < 6; i++) {
+    hex2bin(&key[i * 2], 2, &addr->a.val[5 - i], 1);
+  }
+
+  BT_DBG("Decoded %s as %s", log_strdup(key), bt_addr_le_str(addr));
+
+  return 0;
 }
 
-static int set(const char *name, size_t len_rd, settings_read_cb read_cb,
-               void *cb_arg)
-{
-    ssize_t len;
-    const char *next;
+static int set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg) {
+  ssize_t     len;
+  const char *next;
+
+  if (!name) {
+    BT_ERR("Insufficient number of arguments");
+    return -ENOENT;
+  }
+
+  len = settings_name_next(name, &next);
 
-    if (!name) {
-        BT_ERR("Insufficient number of arguments");
-        return -ENOENT;
+  if (!strncmp(name, "id", len)) {
+    /* Any previously provided identities supersede flash */
+    if (atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) {
+      BT_WARN("Ignoring identities stored in flash");
+      return 0;
     }
 
-    len = settings_name_next(name, &next);
-
-    if (!strncmp(name, "id", len)) {
-        /* Any previously provided identities supersede flash */
-        if (atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) {
-            BT_WARN("Ignoring identities stored in flash");
-            return 0;
-        }
-
-        len = read_cb(cb_arg, &bt_dev.id_addr, sizeof(bt_dev.id_addr));
-        if (len < sizeof(bt_dev.id_addr[0])) {
-            if (len < 0) {
-                BT_ERR("Failed to read ID address from storage"
-                       " (err %zu)",
-                       len);
-            } else {
-                BT_ERR("Invalid length ID address in storage");
-                BT_HEXDUMP_DBG(&bt_dev.id_addr, len,
-                               "data read");
-            }
-            (void)memset(bt_dev.id_addr, 0,
-                         sizeof(bt_dev.id_addr));
-            bt_dev.id_count = 0U;
-        } else {
-            int i;
-
-            bt_dev.id_count = len / sizeof(bt_dev.id_addr[0]);
-            for (i = 0; i < bt_dev.id_count; i++) {
-                BT_DBG("ID[%d] %s", i,
-                       bt_addr_le_str(&bt_dev.id_addr[i]));
-            }
-        }
-
-        return 0;
+    len = read_cb(cb_arg, &bt_dev.id_addr, sizeof(bt_dev.id_addr));
+    if (len < sizeof(bt_dev.id_addr[0])) {
+      if (len < 0) {
+        BT_ERR("Failed to read ID address from storage"
+               " (err %zu)",
+               len);
+      } else {
+        BT_ERR("Invalid length ID address in storage");
+        BT_HEXDUMP_DBG(&bt_dev.id_addr, len, "data read");
+      }
+      (void)memset(bt_dev.id_addr, 0, sizeof(bt_dev.id_addr));
+      bt_dev.id_count = 0U;
+    } else {
+      int i;
+
+      bt_dev.id_count = len / sizeof(bt_dev.id_addr[0]);
+      for (i = 0; i < bt_dev.id_count; i++) {
+        BT_DBG("ID[%d] %s", i, bt_addr_le_str(&bt_dev.id_addr[i]));
+      }
     }
 
+    return 0;
+  }
+
 #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC)
-    if (!strncmp(name, "name", len)) {
-        len = read_cb(cb_arg, &bt_dev.name, sizeof(bt_dev.name) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read device name from storage"
-                   " (err %zu)",
-                   len);
-        } else {
-            bt_dev.name[len] = '\0';
-
-            BT_DBG("Name set to %s", log_strdup(bt_dev.name));
-        }
-        return 0;
+  if (!strncmp(name, "name", len)) {
+    len = read_cb(cb_arg, &bt_dev.name, sizeof(bt_dev.name) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read device name from storage"
+             " (err %zu)",
+             len);
+    } else {
+      bt_dev.name[len] = '\0';
+
+      BT_DBG("Name set to %s", log_strdup(bt_dev.name));
     }
+    return 0;
+  }
 #endif
 
 #if defined(CONFIG_BT_PRIVACY)
-    if (!strncmp(name, "irk", len)) {
-        len = read_cb(cb_arg, bt_dev.irk, sizeof(bt_dev.irk));
-        if (len < sizeof(bt_dev.irk[0])) {
-            if (len < 0) {
-                BT_ERR("Failed to read IRK from storage"
-                       " (err %zu)",
-                       len);
-            } else {
-                BT_ERR("Invalid length IRK in storage");
-                (void)memset(bt_dev.irk, 0, sizeof(bt_dev.irk));
-            }
-        } else {
-            int i, count;
-
-            count = len / sizeof(bt_dev.irk[0]);
-            for (i = 0; i < count; i++) {
-                BT_DBG("IRK[%d] %s", i,
-                       bt_hex(bt_dev.irk[i], 16));
-            }
-        }
-
-        return 0;
+  if (!strncmp(name, "irk", len)) {
+    len = read_cb(cb_arg, bt_dev.irk, sizeof(bt_dev.irk));
+    if (len < sizeof(bt_dev.irk[0])) {
+      if (len < 0) {
+        BT_ERR("Failed to read IRK from storage"
+               " (err %zu)",
+               len);
+      } else {
+        BT_ERR("Invalid length IRK in storage");
+        (void)memset(bt_dev.irk, 0, sizeof(bt_dev.irk));
+      }
+    } else {
+      int i, count;
+
+      count = len / sizeof(bt_dev.irk[0]);
+      for (i = 0; i < count; i++) {
+        BT_DBG("IRK[%d] %s", i, bt_hex(bt_dev.irk[i], 16));
+      }
     }
+
+    return 0;
+  }
 #endif /* CONFIG_BT_PRIVACY */
 
-    return -ENOENT;
+  return -ENOENT;
 }
 
 #define ID_DATA_LEN(array) (bt_dev.id_count * sizeof(array[0]))
 
-static void save_id(struct k_work *work)
-{
-    int err;
-    BT_INFO("Saving ID");
-    err = settings_save_one("bt/id", &bt_dev.id_addr,
-                            ID_DATA_LEN(bt_dev.id_addr));
-    if (err) {
-        BT_ERR("Failed to save ID (err %d)", err);
-    }
+static void save_id(struct k_work *work) {
+  int err;
+  BT_INFO("Saving ID");
+  err = settings_save_one("bt/id", &bt_dev.id_addr, ID_DATA_LEN(bt_dev.id_addr));
+  if (err) {
+    BT_ERR("Failed to save ID (err %d)", err);
+  }
 
 #if defined(CONFIG_BT_PRIVACY)
-    err = settings_save_one("bt/irk", bt_dev.irk, ID_DATA_LEN(bt_dev.irk));
-    if (err) {
-        BT_ERR("Failed to save IRK (err %d)", err);
-    }
+  err = settings_save_one("bt/irk", bt_dev.irk, ID_DATA_LEN(bt_dev.irk));
+  if (err) {
+    BT_ERR("Failed to save IRK (err %d)", err);
+  }
 #endif
 }
 
 K_WORK_DEFINE(save_id_work, save_id);
-#endif //!BFLB_BLE
+#endif //! BFLB_BLE
 #if defined(BFLB_BLE)
 #if defined(CONFIG_BT_SETTINGS)
 bool ef_ready_flag = false;
-int bt_check_if_ef_ready()
-{
-    int err = 0;
-
-    if (!ef_ready_flag) {
-        err = easyflash_init();
-        if (!err)
-            ef_ready_flag = true;
-    }
-
-    return err;
-}
-
-int bt_settings_set_bin(const char *key, const uint8_t *value, size_t length)
-{
-    const char *lookup = "0123456789abcdef";
-    char *str_value;
-    int err;
-
-    err = bt_check_if_ef_ready();
-    if (err)
-        return err;
-
-    str_value = pvPortMalloc(length * 2 + 1);
+int  bt_check_if_ef_ready() {
+  int err = 0;
 
-    BT_ASSERT(str_value != NULL);
+  if (!ef_ready_flag) {
+    err = easyflash_init();
+    if (!err)
+      ef_ready_flag = true;
+  }
 
-    for (size_t i = 0; i < length; i++) {
-        str_value[(i * 2) + 0] = lookup[(value[i] >> 4) & 0x0F];
-        str_value[(i * 2) + 1] = lookup[value[i] & 0x0F];
-    }
-    str_value[length * 2] = '\0';
-
-    err = ef_set_env(key, (const char *)str_value);
+  return err;
+}
 
-    vPortFree(str_value);
+int bt_settings_set_bin(const char *key, const uint8_t *value, size_t length) {
+  int err;
 
+  err = bt_check_if_ef_ready();
+  if (err)
     return err;
-}
 
-int bt_settings_get_bin(const char *key, u8_t *value, size_t exp_len, size_t *real_len)
-{
-    char *str_value;
-    size_t str_value_len;
-    char rand[3];
-    int err;
+  err = ef_set_env_blob(key, value, length);
 
-    err = bt_check_if_ef_ready();
-    if (err)
-        return err;
+  return err;
+}
 
-    str_value = ef_get_env(key);
-    if (str_value == NULL) {
-        return -1;
-    }
+int bt_settings_get_bin(const char *key, u8_t *value, size_t exp_len, size_t *real_len) {
+  int    err;
+  size_t rlen;
 
-    str_value_len = strlen(str_value);
+  err = bt_check_if_ef_ready();
+  if (err)
+    return err;
 
-    if ((str_value_len % 2) != 0 || (exp_len > 0 && str_value_len > exp_len * 2)) {
-        return -1;
-    }
+  rlen = ef_get_env_blob(key, value, exp_len, NULL);
 
-    if (real_len)
-        *real_len = str_value_len / 2;
+  if (real_len)
+    *real_len = rlen;
 
-    for (size_t i = 0; i < str_value_len / 2; i++) {
-        strncpy(rand, str_value + 2 * i, 2);
-        rand[2] = '\0';
-        value[i] = strtol(rand, NULL, 16);
-    }
-
-    return 0;
+  return 0;
 }
 
-int settings_delete(const char *key)
-{
-    return ef_del_env(key);
-}
+int settings_delete(const char *key) { return ef_del_env(key); }
 
-int settings_save_one(const char *key, const u8_t *value, size_t length)
-{
-    return bt_settings_set_bin(key, value, length);
-}
-#endif //CONFIG_BT_SETTINGS
+int settings_save_one(const char *key, const u8_t *value, size_t length) { return bt_settings_set_bin(key, value, length); }
+#endif // CONFIG_BT_SETTINGS
 #endif
 
-void bt_settings_save_id(void)
-{
+void bt_settings_save_id(void) {
 #if defined(BFLB_BLE)
 #if defined(CONFIG_BT_SETTINGS)
-    if (bt_check_if_ef_ready())
-        return;
-    bt_settings_set_bin(NV_LOCAL_ID_ADDR, (const u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t) * CONFIG_BT_ID_MAX);
+  if (bt_check_if_ef_ready())
+    return;
+  bt_settings_set_bin(NV_LOCAL_ID_ADDR, (const u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t) * CONFIG_BT_ID_MAX);
 #if defined(CONFIG_BT_PRIVACY)
-    bt_settings_set_bin(NV_LOCAL_IRK, (const u8_t *)&bt_dev.irk[0], 16 * CONFIG_BT_ID_MAX);
-#endif //CONFIG_BT_PRIVACY
-#endif //CONFIG_BT_SETTINGS
+  bt_settings_set_bin(NV_LOCAL_IRK, (const u8_t *)&bt_dev.irk[0], 16 * CONFIG_BT_ID_MAX);
+#endif // CONFIG_BT_PRIVACY
+#endif // CONFIG_BT_SETTINGS
 #else
-    k_work_submit(&save_id_work);
+  k_work_submit(&save_id_work);
 #endif
 }
 
 #if defined(BFLB_BLE)
 #if defined(CONFIG_BT_SETTINGS)
-void bt_settings_save_name(void)
-{
-    if (bt_check_if_ef_ready())
-        return;
-
-    ef_set_env(NV_LOCAL_NAME, bt_dev.name);
-}
+void bt_settings_save_name(void) { bt_settings_set_bin(NV_LOCAL_NAME, (u8_t *)bt_dev.name, strlen(bt_dev.name) + 1); }
 
-void bt_local_info_load(void)
-{
-    if (bt_check_if_ef_ready())
-        return;
+void bt_local_info_load(void) {
+  if (bt_check_if_ef_ready())
+    return;
 #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC)
-    char *dev_name;
-    uint8_t len;
-    dev_name = ef_get_env(NV_LOCAL_NAME);
-    if (dev_name != NULL) {
-        len = ((strlen(dev_name) + 1) < CONFIG_BT_DEVICE_NAME_MAX) ? (strlen(dev_name) + 1) : CONFIG_BT_DEVICE_NAME_MAX;
-        memcpy(bt_dev.name, dev_name, len);
-    }
+  bt_settings_get_bin(NV_LOCAL_NAME, (u8_t *)bt_dev.name, CONFIG_BT_DEVICE_NAME_MAX, NULL);
 #endif
-    bt_settings_get_bin(NV_LOCAL_ID_ADDR, (u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t) * CONFIG_BT_ID_MAX, NULL);
+  bt_settings_get_bin(NV_LOCAL_ID_ADDR, (u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t) * CONFIG_BT_ID_MAX, NULL);
 #if defined(CONFIG_BT_PRIVACY)
-    bt_settings_get_bin(NV_LOCAL_IRK, (u8_t *)&bt_dev.irk[0][0], 16 * CONFIG_BT_ID_MAX, NULL);
+  bt_settings_get_bin(NV_LOCAL_IRK, (u8_t *)&bt_dev.irk[0][0], 16 * CONFIG_BT_ID_MAX, NULL);
 #endif
 }
-#endif //CONFIG_BT_SETTINGS
+#endif // CONFIG_BT_SETTINGS
 #endif
 
 #if !defined(BFLB_BLE)
-static int commit(void)
-{
-    BT_DBG("");
+static int commit(void) {
+  BT_DBG("");
 
 #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC)
-    if (bt_dev.name[0] == '\0') {
-        bt_set_name(CONFIG_BT_DEVICE_NAME);
-    }
+  if (bt_dev.name[0] == '\0') {
+    bt_set_name(CONFIG_BT_DEVICE_NAME);
+  }
 #endif
-    if (!bt_dev.id_count) {
-        int err;
-
-        err = bt_setup_id_addr();
-        if (err) {
-            BT_ERR("Unable to setup an identity address");
-            return err;
-        }
-    }
+  if (!bt_dev.id_count) {
+    int err;
 
-    /* Make sure that the identities created by bt_id_create after
-	 * bt_enable is saved to persistent storage. */
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) {
-        bt_settings_save_id();
+    err = bt_setup_id_addr();
+    if (err) {
+      BT_ERR("Unable to setup an identity address");
+      return err;
     }
+  }
 
-    if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
-        bt_finalize_init();
-    }
+  /* Make sure that the identities created by bt_id_create after
+   * bt_enable is saved to persistent storage. */
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) {
+    bt_settings_save_id();
+  }
 
-    return 0;
+  if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+    bt_finalize_init();
+  }
+
+  return 0;
 }
 
 SETTINGS_STATIC_HANDLER_DEFINE(bt, "bt", NULL, set, commit, NULL);
 
-#endif //!BFLB_BLE
+#endif //! BFLB_BLE
 
-int bt_settings_init(void)
-{
+int bt_settings_init(void) {
 #if defined(BFLB_BLE)
-    return 0;
+  return 0;
 #else
-    int err;
+  int err;
 
-    BT_DBG("");
+  BT_DBG("");
 
-    err = settings_subsys_init();
-    if (err) {
-        BT_ERR("settings_subsys_init failed (err %d)", err);
-        return err;
-    }
+  err = settings_subsys_init();
+  if (err) {
+    BT_ERR("settings_subsys_init failed (err %d)", err);
+    return err;
+  }
 
-    return 0;
+  return 0;
 #endif
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/smp_null.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/smp_null.c
index e0b2f74bd..24bcfdbf9 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/smp_null.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/smp_null.c
@@ -9,93 +9,82 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
-#include 
 #include 
+#include 
 #include 
+#include 
 
+#include <../include/bluetooth/buf.h>
 #include 
 #include 
-#include <../include/bluetooth/buf.h>
 
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_HCI_CORE)
 #define LOG_MODULE_NAME bt_smp
 #include "log.h"
 
-#include "hci_core.h"
 #include "conn_internal.h"
+#include "hci_core.h"
 #include "l2cap_internal.h"
 #include "smp.h"
 
 static struct bt_l2cap_le_chan bt_smp_pool[CONFIG_BT_MAX_CONN];
 
-int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf)
-{
-    return -ENOTSUP;
-}
+int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf) { return -ENOTSUP; }
 
-int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf)
-{
-    return -ENOTSUP;
-}
+int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf) { return -ENOTSUP; }
 
-static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
-{
-    struct bt_conn *conn = chan->conn;
-    struct bt_smp_pairing_fail *rsp;
-    struct bt_smp_hdr *hdr;
+static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) {
+  struct bt_conn             *conn = chan->conn;
+  struct bt_smp_pairing_fail *rsp;
+  struct bt_smp_hdr          *hdr;
 
-    /* If a device does not support pairing then it shall respond with
-	 * a Pairing Failed command with the reason set to "Pairing Not
-	 * Supported" when any command is received.
-	 * Core Specification Vol. 3, Part H, 3.3
-	 */
+  /* If a device does not support pairing then it shall respond with
+   * a Pairing Failed command with the reason set to "Pairing Not
+   * Supported" when any command is received.
+   * Core Specification Vol. 3, Part H, 3.3
+   */
 
-    buf = bt_l2cap_create_pdu(NULL, 0);
-    /* NULL is not a possible return due to K_FOREVER */
+  buf = bt_l2cap_create_pdu(NULL, 0);
+  /* NULL is not a possible return due to K_FOREVER */
 
-    hdr = net_buf_add(buf, sizeof(*hdr));
-    hdr->code = BT_SMP_CMD_PAIRING_FAIL;
+  hdr       = net_buf_add(buf, sizeof(*hdr));
+  hdr->code = BT_SMP_CMD_PAIRING_FAIL;
 
-    rsp = net_buf_add(buf, sizeof(*rsp));
-    rsp->reason = BT_SMP_ERR_PAIRING_NOTSUPP;
+  rsp         = net_buf_add(buf, sizeof(*rsp));
+  rsp->reason = BT_SMP_ERR_PAIRING_NOTSUPP;
 
-    bt_l2cap_send(conn, BT_L2CAP_CID_SMP, buf);
+  bt_l2cap_send(conn, BT_L2CAP_CID_SMP, buf);
 
-    return 0;
+  return 0;
 }
 
-static int bt_smp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
-{
-    int i;
-    static struct bt_l2cap_chan_ops ops = {
-        .recv = bt_smp_recv,
-    };
+static int bt_smp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) {
+  int                             i;
+  static struct bt_l2cap_chan_ops ops = {
+      .recv = bt_smp_recv,
+  };
 
-    BT_DBG("conn %p handle %u", conn, conn->handle);
+  BT_DBG("conn %p handle %u", conn, conn->handle);
 
-    for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
-        struct bt_l2cap_le_chan *smp = &bt_smp_pool[i];
+  for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) {
+    struct bt_l2cap_le_chan *smp = &bt_smp_pool[i];
 
-        if (smp->chan.conn) {
-            continue;
-        }
+    if (smp->chan.conn) {
+      continue;
+    }
 
-        smp->chan.ops = &ops;
+    smp->chan.ops = &ops;
 
-        *chan = &smp->chan;
+    *chan = &smp->chan;
 
-        return 0;
-    }
+    return 0;
+  }
 
-    BT_ERR("No available SMP context for conn %p", conn);
+  BT_ERR("No available SMP context for conn %p", conn);
 
-    return -ENOMEM;
+  return -ENOMEM;
 }
 
 BT_L2CAP_CHANNEL_DEFINE(smp_fixed_chan, BT_L2CAP_CID_SMP, bt_smp_accept);
 
-int bt_smp_init(void)
-{
-    return 0;
-}
+int bt_smp_init(void) { return 0; }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/uuid.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/uuid.c
index dee135043..d0cca1533 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/uuid.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/uuid.c
@@ -6,10 +6,10 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
 #include 
 #include 
 #include 
+#include 
 
 #include 
 
@@ -22,118 +22,105 @@
  *  little endian 0x2800 : [00 28] -> no swapping required
  *  big endian 0x2800    : [28 00] -> swapping required
  */
-static const struct bt_uuid_128 uuid128_base = {
-    .uuid = { BT_UUID_TYPE_128 },
-    .val = { BT_UUID_128_ENCODE(
-        0x00000000, 0x0000, 0x1000, 0x8000, 0x00805F9B34FB) }
-};
-
-static void uuid_to_uuid128(const struct bt_uuid *src, struct bt_uuid_128 *dst)
-{
-    switch (src->type) {
-        case BT_UUID_TYPE_16:
-            *dst = uuid128_base;
-            sys_put_le16(BT_UUID_16(src)->val,
-                         &dst->val[UUID_16_BASE_OFFSET]);
-            return;
-        case BT_UUID_TYPE_32:
-            *dst = uuid128_base;
-            sys_put_le32(BT_UUID_32(src)->val,
-                         &dst->val[UUID_16_BASE_OFFSET]);
-            return;
-        case BT_UUID_TYPE_128:
-            memcpy(dst, src, sizeof(*dst));
-            return;
-    }
+static const struct bt_uuid_128 uuid128_base = {.uuid = {BT_UUID_TYPE_128}, .val = {BT_UUID_128_ENCODE(0x00000000, 0x0000, 0x1000, 0x8000, 0x00805F9B34FB)}};
+
+static void uuid_to_uuid128(const struct bt_uuid *src, struct bt_uuid_128 *dst) {
+  switch (src->type) {
+  case BT_UUID_TYPE_16:
+    *dst = uuid128_base;
+    sys_put_le16(BT_UUID_16(src)->val, &dst->val[UUID_16_BASE_OFFSET]);
+    return;
+  case BT_UUID_TYPE_32:
+    *dst = uuid128_base;
+    sys_put_le32(BT_UUID_32(src)->val, &dst->val[UUID_16_BASE_OFFSET]);
+    return;
+  case BT_UUID_TYPE_128:
+    memcpy(dst, src, sizeof(*dst));
+    return;
+  }
 }
 
-static int uuid128_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2)
-{
-    struct bt_uuid_128 uuid1, uuid2;
+static int uuid128_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2) {
+  struct bt_uuid_128 uuid1, uuid2;
 
-    uuid_to_uuid128(u1, &uuid1);
-    uuid_to_uuid128(u2, &uuid2);
+  uuid_to_uuid128(u1, &uuid1);
+  uuid_to_uuid128(u2, &uuid2);
 
-    return memcmp(uuid1.val, uuid2.val, 16);
+  return memcmp(uuid1.val, uuid2.val, 16);
 }
 
-int bt_uuid_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2)
-{
-    /* Convert to 128 bit if types don't match */
-    if (u1->type != u2->type) {
-        return uuid128_cmp(u1, u2);
-    }
-
-    switch (u1->type) {
-        case BT_UUID_TYPE_16:
-            return (int)BT_UUID_16(u1)->val - (int)BT_UUID_16(u2)->val;
-        case BT_UUID_TYPE_32:
-            return (int)BT_UUID_32(u1)->val - (int)BT_UUID_32(u2)->val;
-        case BT_UUID_TYPE_128:
-            return memcmp(BT_UUID_128(u1)->val, BT_UUID_128(u2)->val, 16);
-    }
-
-    return -EINVAL;
+int bt_uuid_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2) {
+  /* Convert to 128 bit if types don't match */
+  if (u1->type != u2->type) {
+    return uuid128_cmp(u1, u2);
+  }
+
+  switch (u1->type) {
+  case BT_UUID_TYPE_16:
+    return (int)BT_UUID_16(u1)->val - (int)BT_UUID_16(u2)->val;
+  case BT_UUID_TYPE_32:
+    return (int)BT_UUID_32(u1)->val - (int)BT_UUID_32(u2)->val;
+  case BT_UUID_TYPE_128:
+    return memcmp(BT_UUID_128(u1)->val, BT_UUID_128(u2)->val, 16);
+  }
+
+  return -EINVAL;
 }
 
-bool bt_uuid_create(struct bt_uuid *uuid, const u8_t *data, u8_t data_len)
-{
-    /* Copy UUID from packet data/internal variable to internal bt_uuid */
-    switch (data_len) {
-        case 2:
-            uuid->type = BT_UUID_TYPE_16;
-            BT_UUID_16(uuid)->val = sys_get_le16(data);
-            break;
-        case 4:
-            uuid->type = BT_UUID_TYPE_32;
-            BT_UUID_32(uuid)->val = sys_get_le32(data);
-            break;
-        case 16:
-            uuid->type = BT_UUID_TYPE_128;
-            memcpy(&BT_UUID_128(uuid)->val, data, 16);
-            break;
-        default:
-            return false;
-    }
-    return true;
+bool bt_uuid_create(struct bt_uuid *uuid, const u8_t *data, u8_t data_len) {
+  /* Copy UUID from packet data/internal variable to internal bt_uuid */
+  switch (data_len) {
+  case 2:
+    uuid->type            = BT_UUID_TYPE_16;
+    BT_UUID_16(uuid)->val = sys_get_le16(data);
+    break;
+  case 4:
+    uuid->type            = BT_UUID_TYPE_32;
+    BT_UUID_32(uuid)->val = sys_get_le32(data);
+    break;
+  case 16:
+    uuid->type = BT_UUID_TYPE_128;
+    memcpy(&BT_UUID_128(uuid)->val, data, 16);
+    break;
+  default:
+    return false;
+  }
+  return true;
 }
 
 #if defined(CONFIG_BT_DEBUG)
-void bt_uuid_to_str(const struct bt_uuid *uuid, char *str, size_t len)
-{
-    u32_t tmp1, tmp5;
-    u16_t tmp0, tmp2, tmp3, tmp4;
-
-    switch (uuid->type) {
-        case BT_UUID_TYPE_16:
-            snprintk(str, len, "%04x", BT_UUID_16(uuid)->val);
-            break;
-        case BT_UUID_TYPE_32:
-            snprintk(str, len, "%04x", BT_UUID_32(uuid)->val);
-            break;
-        case BT_UUID_TYPE_128:
-            memcpy(&tmp0, &BT_UUID_128(uuid)->val[0], sizeof(tmp0));
-            memcpy(&tmp1, &BT_UUID_128(uuid)->val[2], sizeof(tmp1));
-            memcpy(&tmp2, &BT_UUID_128(uuid)->val[6], sizeof(tmp2));
-            memcpy(&tmp3, &BT_UUID_128(uuid)->val[8], sizeof(tmp3));
-            memcpy(&tmp4, &BT_UUID_128(uuid)->val[10], sizeof(tmp4));
-            memcpy(&tmp5, &BT_UUID_128(uuid)->val[12], sizeof(tmp5));
-
-            snprintk(str, len, "%08x-%04x-%04x-%04x-%08x%04x",
-                     tmp5, tmp4, tmp3, tmp2, tmp1, tmp0);
-            break;
-        default:
-            (void)memset(str, 0, len);
-            return;
-    }
+void bt_uuid_to_str(const struct bt_uuid *uuid, char *str, size_t len) {
+  u32_t tmp1, tmp5;
+  u16_t tmp0, tmp2, tmp3, tmp4;
+
+  switch (uuid->type) {
+  case BT_UUID_TYPE_16:
+    snprintk(str, len, "%04x", BT_UUID_16(uuid)->val);
+    break;
+  case BT_UUID_TYPE_32:
+    snprintk(str, len, "%04x", BT_UUID_32(uuid)->val);
+    break;
+  case BT_UUID_TYPE_128:
+    memcpy(&tmp0, &BT_UUID_128(uuid)->val[0], sizeof(tmp0));
+    memcpy(&tmp1, &BT_UUID_128(uuid)->val[2], sizeof(tmp1));
+    memcpy(&tmp2, &BT_UUID_128(uuid)->val[6], sizeof(tmp2));
+    memcpy(&tmp3, &BT_UUID_128(uuid)->val[8], sizeof(tmp3));
+    memcpy(&tmp4, &BT_UUID_128(uuid)->val[10], sizeof(tmp4));
+    memcpy(&tmp5, &BT_UUID_128(uuid)->val[12], sizeof(tmp5));
+
+    snprintk(str, len, "%08x-%04x-%04x-%04x-%08x%04x", tmp5, tmp4, tmp3, tmp2, tmp1, tmp0);
+    break;
+  default:
+    (void)memset(str, 0, len);
+    return;
+  }
 }
 
-const char *bt_uuid_str_real(const struct bt_uuid *uuid)
-{
-    static char str[37];
+const char *bt_uuid_str_real(const struct bt_uuid *uuid) {
+  static char str[37];
 
-    bt_uuid_to_str(uuid, str, sizeof(str));
+  bt_uuid_to_str(uuid, str, sizeof(str));
 
-    return str;
+  return str;
 }
 #endif /* CONFIG_BT_DEBUG */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/addr.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/addr.h
index 768f3189c..016181f6e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/addr.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/addr.h
@@ -21,12 +21,6 @@ extern "C" {
 #define BT_ADDR_LE_PUBLIC_ID 0x02
 #define BT_ADDR_LE_RANDOM_ID 0x03
 
-#if defined(CONFIG_BT_STACK_PTS)
-//for app layer to deliver the address type:non rpa ,rpa
-#define BT_ADDR_TYPE_NON_RPA 0x01
-#define BT_ADDR_TYPE_RPA     0x02
-#endif
-
 /** Bluetooth Device Address */
 typedef struct {
     u8_t val[6];
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/bluetooth.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/bluetooth.h
index ec0a5d520..826d4ec5c 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/bluetooth.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/bluetooth.h
@@ -315,7 +315,7 @@ struct bt_le_adv_param {
     /** Maximum Advertising Interval (N * 0.625) */
     u16_t interval_max;
 
-#if defined(CONFIG_BT_STACK_PTS)
+#if defined(CONFIG_BT_STACK_PTS) || defined(CONFIG_AUTO_PTS)
     u8_t addr_type;
 #endif
 };
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h
index 98ba3c8c9..66376abc5 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/conn.h
@@ -106,6 +106,7 @@ struct bt_conn *bt_conn_lookup_addr_le(u8_t id, const bt_addr_le_t *peer);
 
 #if defined(BFLB_BLE)
 bool le_check_valid_conn(void);
+void notify_disconnected(struct bt_conn *conn);
 #if defined(BFLB_HOST_ASSISTANT)
 void bt_notify_disconnected(void);
 #endif
@@ -490,6 +491,17 @@ struct bt_conn_cb {
 	 */
     void (*le_param_updated)(struct bt_conn *conn, u16_t interval,
                              u16_t latency, u16_t timeout);
+
+    /** @brief The PHY of the connection has changed.
+	 *
+	 *  This callback notifies the application that the PHY of the
+	 *  connection has changed.
+	 *
+	 *  @param conn Connection object.
+	 *  @param tx_phy Transmit phy.
+	 *  @param rx_phy Receive phy.
+	 */
+    void (*le_phy_updated)(struct bt_conn *conn, u8_t tx_phy, u8_t rx_phy);
 #if defined(CONFIG_BT_SMP)
     /** @brief Remote Identity Address has been resolved.
 	 *
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/gatt.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/gatt.h
index 709e8bc21..20b9391c1 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/gatt.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/gatt.h
@@ -529,6 +529,13 @@ ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn,
                                const struct bt_gatt_attr *attr, void *buf,
                                u16_t len, u16_t offset);
 
+#define BT_GATT_CHRC_INIT(_uuid, _handle, _props) \
+    {                                             \
+        .uuid = _uuid,                            \
+        .value_handle = _handle,                  \
+        .properties = _props,                     \
+    }
+
 /** @def BT_GATT_CHARACTERISTIC
  *  @brief Characteristic and Value Declaration Macro.
  *
@@ -545,10 +552,8 @@ ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn,
 #define BT_GATT_CHARACTERISTIC(_uuid, _props, _perm, _read, _write, _value) \
     BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ,                 \
                       bt_gatt_attr_read_chrc, NULL,                         \
-                      (&(struct bt_gatt_chrc){                              \
-                          .uuid = _uuid,                                    \
-                          .value_handle = 0U,                               \
-                          .properties = _props,                             \
+                      ((struct bt_gatt_chrc[]){                             \
+                          BT_GATT_CHRC_INIT(_uuid, 0U, _props),             \
                       })),                                                  \
         BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value)
 
@@ -784,10 +789,11 @@ ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn,
 #define BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value) \
     {                                                          \
         .uuid = _uuid,                                         \
-        .perm = _perm,                                         \
         .read = _read,                                         \
         .write = _write,                                       \
         .user_data = _value,                                   \
+        .handle = 0,                                           \
+        .perm = _perm,                                         \
     }
 
 /** @brief Notification complete result callback.
@@ -1370,7 +1376,12 @@ void bt_gatt_cancel(struct bt_conn *conn, void *params);
 typedef void (*bt_gatt_mtu_changed_cb_t)(struct bt_conn *conn, int mtu);
 void bt_gatt_register_mtu_callback(bt_gatt_mtu_changed_cb_t cb);
 #endif
-
+#if defined(CONFIG_BT_GATT_CLIENT)
+#if defined(BFLB_BLE_NOTIFY_ALL)
+typedef void (*bt_notification_all_cb_t)(struct bt_conn *conn, u16_t handle, const void *data, u16_t length);
+void bt_gatt_register_notification_callback(bt_notification_all_cb_t cb);
+#endif
+#endif
 #if defined(BFLB_BLE)
 /** @brief load gatt ccc from flash
  *
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/hci_host.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/hci_host.h
index 5d79f000e..b1c514b97 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/hci_host.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/hci_host.h
@@ -476,6 +476,17 @@ struct bt_hci_write_local_name {
 #define BT_BREDR_SCAN_INQUIRY       0x01
 #define BT_BREDR_SCAN_PAGE          0x02
 
+#define BT_HCI_OP_WRITE_INQUIRY_SCAN_ACTIVITY BT_OP(BT_OGF_BASEBAND, 0x001e)
+struct bt_hci_cp_write_inquiry_scan_activity {
+    u16_t interval;
+    u16_t window;
+} __packed;
+
+#define BT_HCI_OP_WRITE_CLASS_OF_DEVICE BT_OP(BT_OGF_BASEBAND, 0x0024)
+struct bt_hci_cp_write_class_of_device {
+    u8_t cod[3];
+} __packed;
+
 #define BT_TX_POWER_LEVEL_CURRENT     0x00
 #define BT_TX_POWER_LEVEL_MAX         0x01
 #define BT_HCI_OP_READ_TX_POWER_LEVEL BT_OP(BT_OGF_BASEBAND, 0x002d)
@@ -516,11 +527,21 @@ struct bt_hci_cp_host_num_completed_packets {
     struct bt_hci_handle_count h[0];
 } __packed;
 
+#define BT_HCI_OP_WRITE_INQUIRY_SCAN_TYPE BT_OP(BT_OGF_BASEBAND, 0x0043)
+struct bt_hci_cp_write_inquiry_scan_type {
+    u8_t type;
+} __packed;
+
 #define BT_HCI_OP_WRITE_INQUIRY_MODE BT_OP(BT_OGF_BASEBAND, 0x0045)
 struct bt_hci_cp_write_inquiry_mode {
     u8_t mode;
 } __packed;
 
+#define BT_HCI_OP_WRITE_PAGE_SCAN_TYPE BT_OP(BT_OGF_BASEBAND, 0x0047)
+struct bt_hci_cp_write_page_scan_type {
+    u8_t type;
+} __packed;
+
 #define BT_HCI_OP_WRITE_EXT_INQUIRY_RESP BT_OP(BT_OGF_BASEBAND, 0x0052)
 struct bt_hci_cp_write_ext_inquiry_resp {
     u8_t rec;
@@ -2617,6 +2638,10 @@ typedef bool bt_hci_vnd_evt_cb_t(struct net_buf_simple *buf);
   */
 int bt_hci_register_vnd_evt_cb(bt_hci_vnd_evt_cb_t cb);
 
+#if (BFLB_BT_CO_THREAD)
+struct k_thread *bt_get_co_thread(void);
+#endif
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/iso.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/iso.h
index b24988a8b..c48295c96 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/iso.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/iso.h
@@ -21,15 +21,17 @@
 extern "C" {
 #endif
 
+#include 
 #include 
 #include 
 #include 
-#include 
 
 /** @def BT_ISO_CHAN_SEND_RESERVE
  *  @brief Headroom needed for outgoing buffers
  */
-#define BT_ISO_CHAN_SEND_RESERVE (CONFIG_BT_HCI_RESERVE + BT_HCI_ISO_HDR_SIZE + BT_HCI_ISO_DATA_HDR_SIZE)
+#define BT_ISO_CHAN_SEND_RESERVE (CONFIG_BT_HCI_RESERVE + \
+                                  BT_HCI_ISO_HDR_SIZE +   \
+                                  BT_HCI_ISO_DATA_HDR_SIZE)
 
 struct bt_iso_chan;
 
@@ -38,136 +40,140 @@ struct bt_iso_chan;
  *  context.
  */
 enum {
-  /** Channel disconnected */
-  BT_ISO_DISCONNECTED,
-  /** Channel bound to a connection */
-  BT_ISO_BOUND,
-  /** Channel in connecting state */
-  BT_ISO_CONNECT,
-  /** Channel ready for upper layer traffic on it */
-  BT_ISO_CONNECTED,
-  /** Channel in disconnecting state */
-  BT_ISO_DISCONNECT,
+    /** Channel disconnected */
+    BT_ISO_DISCONNECTED,
+    /** Channel bound to a connection */
+    BT_ISO_BOUND,
+    /** Channel in connecting state */
+    BT_ISO_CONNECT,
+    /** Channel ready for upper layer traffic on it */
+    BT_ISO_CONNECTED,
+    /** Channel in disconnecting state */
+    BT_ISO_DISCONNECT,
 };
 
 /** @brief ISO Channel structure. */
 struct bt_iso_chan {
-  /** Channel connection reference */
-  struct bt_conn *conn;
-  /** Channel operations reference */
-  struct bt_iso_chan_ops *ops;
-  /** Channel QoS reference */
-  struct bt_iso_chan_qos *qos;
-  /** Channel data path reference*/
-  struct bt_iso_chan_path *path;
-  sys_snode_t              node;
-  uint8_t                  state;
-  bt_security_t            required_sec_level;
+    /** Channel connection reference */
+    struct bt_conn *conn;
+    /** Channel operations reference */
+    struct bt_iso_chan_ops *ops;
+    /** Channel QoS reference */
+    struct bt_iso_chan_qos *qos;
+    /** Channel data path reference*/
+    struct bt_iso_chan_path *path;
+    sys_snode_t node;
+    uint8_t state;
+    bt_security_t required_sec_level;
 };
 
 /** @brief Audio QoS direction */
-enum { BT_ISO_CHAN_QOS_IN, BT_ISO_CHAN_QOS_OUT, BT_ISO_CHAN_QOS_INOUT };
+enum {
+    BT_ISO_CHAN_QOS_IN,
+    BT_ISO_CHAN_QOS_OUT,
+    BT_ISO_CHAN_QOS_INOUT
+};
 
 /** @brief ISO Channel QoS structure. */
 struct bt_iso_chan_qos {
-  /** @brief Channel direction
-   *
-   *  Possible values: BT_ISO_CHAN_QOS_IN, BT_ISO_CHAN_QOS_OUT or
-   *  BT_ISO_CHAN_QOS_INOUT.
-   */
-  uint8_t dir;
-  /** Channel interval */
-  uint32_t interval;
-  /** Channel SCA */
-  uint8_t sca;
-  /** Channel packing mode */
-  uint8_t packing;
-  /** Channel framing mode */
-  uint8_t framing;
-  /** Channel Latency */
-  uint16_t latency;
-  /** Channel SDU */
-  uint8_t sdu;
-  /** Channel PHY */
-  uint8_t phy;
-  /** Channel Retransmission Number */
-  uint8_t rtn;
+    /** @brief Channel direction
+	 *
+	 *  Possible values: BT_ISO_CHAN_QOS_IN, BT_ISO_CHAN_QOS_OUT or
+	 *  BT_ISO_CHAN_QOS_INOUT.
+	 */
+    uint8_t dir;
+    /** Channel interval */
+    uint32_t interval;
+    /** Channel SCA */
+    uint8_t sca;
+    /** Channel packing mode */
+    uint8_t packing;
+    /** Channel framing mode */
+    uint8_t framing;
+    /** Channel Latency */
+    uint16_t latency;
+    /** Channel SDU */
+    uint8_t sdu;
+    /** Channel PHY */
+    uint8_t phy;
+    /** Channel Retransmission Number */
+    uint8_t rtn;
 };
 
 /** @brief ISO Channel Data Path structure. */
 struct bt_iso_chan_path {
-  /** Default path ID */
-  uint8_t pid;
-  /** Coding Format */
-  uint8_t format;
-  /** Company ID */
-  uint16_t cid;
-  /** Vendor-defined Codec ID */
-  uint16_t vid;
-  /** Controller Delay */
-  uint32_t delay;
-  /** Codec Configuration length*/
-  uint8_t cc_len;
-  /** Codec Configuration */
-  uint8_t cc[0];
+    /** Default path ID */
+    uint8_t pid;
+    /** Coding Format */
+    uint8_t format;
+    /** Company ID */
+    uint16_t cid;
+    /** Vendor-defined Codec ID */
+    uint16_t vid;
+    /** Controller Delay */
+    uint32_t delay;
+    /** Codec Configuration length*/
+    uint8_t cc_len;
+    /** Codec Configuration */
+    uint8_t cc[0];
 };
 
 /** @brief ISO Channel operations structure. */
 struct bt_iso_chan_ops {
-  /** @brief Channel connected callback
-   *
-   *  If this callback is provided it will be called whenever the
-   *  connection completes.
-   *
-   *  @param chan The channel that has been connected
-   */
-  void (*connected)(struct bt_iso_chan *chan);
-
-  /** @brief Channel disconnected callback
-   *
-   *  If this callback is provided it will be called whenever the
-   *  channel is disconnected, including when a connection gets
-   *  rejected.
-   *
-   *  @param chan The channel that has been Disconnected
-   */
-  void (*disconnected)(struct bt_iso_chan *chan);
-
-  /** @brief Channel alloc_buf callback
-   *
-   *  If this callback is provided the channel will use it to allocate
-   *  buffers to store incoming data.
-   *
-   *  @param chan The channel requesting a buffer.
-   *
-   *  @return Allocated buffer.
-   */
-  struct net_buf *(*alloc_buf)(struct bt_iso_chan *chan);
-
-  /** @brief Channel recv callback
-   *
-   *  @param chan The channel receiving data.
-   *  @param buf Buffer containing incoming data.
-   */
-  void (*recv)(struct bt_iso_chan *chan, struct net_buf *buf);
+    /** @brief Channel connected callback
+	 *
+	 *  If this callback is provided it will be called whenever the
+	 *  connection completes.
+	 *
+	 *  @param chan The channel that has been connected
+	 */
+    void (*connected)(struct bt_iso_chan *chan);
+
+    /** @brief Channel disconnected callback
+	 *
+	 *  If this callback is provided it will be called whenever the
+	 *  channel is disconnected, including when a connection gets
+	 *  rejected.
+	 *
+	 *  @param chan The channel that has been Disconnected
+	 */
+    void (*disconnected)(struct bt_iso_chan *chan);
+
+    /** @brief Channel alloc_buf callback
+	 *
+	 *  If this callback is provided the channel will use it to allocate
+	 *  buffers to store incoming data.
+	 *
+	 *  @param chan The channel requesting a buffer.
+	 *
+	 *  @return Allocated buffer.
+	 */
+    struct net_buf *(*alloc_buf)(struct bt_iso_chan *chan);
+
+    /** @brief Channel recv callback
+	 *
+	 *  @param chan The channel receiving data.
+	 *  @param buf Buffer containing incoming data.
+	 */
+    void (*recv)(struct bt_iso_chan *chan, struct net_buf *buf);
 };
 
 /** @brief ISO Server structure. */
 struct bt_iso_server {
-  /** Required minimim security level */
-  bt_security_t sec_level;
-
-  /** @brief Server accept callback
-   *
-   *  This callback is called whenever a new incoming connection requires
-   *  authorization.
-   *
-   *  @param conn The connection that is requesting authorization
-   *  @param chan Pointer to receive the allocated channel
-   *
-   *  @return 0 in case of success or negative value in case of error.
-   */
-  int (*accept)(struct bt_conn *conn, struct bt_iso_chan **chan);
+    /** Required minimim security level */
+    bt_security_t sec_level;
+
+    /** @brief Server accept callback
+	 *
+	 *  This callback is called whenever a new incoming connection requires
+	 *  authorization.
+	 *
+	 *  @param conn The connection that is requesting authorization
+	 *  @param chan Pointer to receive the allocated channel
+	 *
+	 *  @return 0 in case of success or negative value in case of error.
+	 */
+    int (*accept)(struct bt_conn *conn, struct bt_iso_chan **chan);
 };
 
 /** @brief Register ISO server.
@@ -194,7 +200,8 @@ int bt_iso_server_register(struct bt_iso_server *server);
  *
  *  @return 0 in case of success or negative value in case of error.
  */
-int bt_iso_chan_bind(struct bt_conn **conns, uint8_t num_conns, struct bt_iso_chan **chans);
+int bt_iso_chan_bind(struct bt_conn **conns, uint8_t num_conns,
+                     struct bt_iso_chan **chans);
 
 /** @brief Connect ISO channels
  *
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/l2cap.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/l2cap.h
index 759344391..12db69e7f 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/l2cap.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/l2cap.h
@@ -18,7 +18,6 @@
  */
 
 #include <../bluetooth/buf.h>
-#include 
 #include 
 #include 
 #ifdef __cplusplus
@@ -37,7 +36,9 @@ extern "C" {
  *
  *   @return Needed buffer size to match the requested L2CAP MTU.
  */
-#define BT_L2CAP_BUF_SIZE(mtu) (BT_BUF_RESERVE + BT_HCI_ACL_HDR_SIZE + BT_L2CAP_HDR_SIZE + (mtu))
+#define BT_L2CAP_BUF_SIZE(mtu) (BT_BUF_RESERVE +                          \
+                                BT_HCI_ACL_HDR_SIZE + BT_L2CAP_HDR_SIZE + \
+                                (mtu))
 
 struct bt_l2cap_chan;
 
@@ -53,82 +54,82 @@ typedef void (*bt_l2cap_chan_destroy_t)(struct bt_l2cap_chan *chan);
  *  context.
  */
 typedef enum bt_l2cap_chan_state {
-  /** Channel disconnected */
-  BT_L2CAP_DISCONNECTED,
-  /** Channel in connecting state */
-  BT_L2CAP_CONNECT,
-  /** Channel in config state, BR/EDR specific */
-  BT_L2CAP_CONFIG,
-  /** Channel ready for upper layer traffic on it */
-  BT_L2CAP_CONNECTED,
-  /** Channel in disconnecting state */
-  BT_L2CAP_DISCONNECT,
+    /** Channel disconnected */
+    BT_L2CAP_DISCONNECTED,
+    /** Channel in connecting state */
+    BT_L2CAP_CONNECT,
+    /** Channel in config state, BR/EDR specific */
+    BT_L2CAP_CONFIG,
+    /** Channel ready for upper layer traffic on it */
+    BT_L2CAP_CONNECTED,
+    /** Channel in disconnecting state */
+    BT_L2CAP_DISCONNECT,
 
 } __packed bt_l2cap_chan_state_t;
 
 /** @brief Status of L2CAP channel. */
 typedef enum bt_l2cap_chan_status {
-  /** Channel output status */
-  BT_L2CAP_STATUS_OUT,
+    /** Channel output status */
+    BT_L2CAP_STATUS_OUT,
 
-  /* Total number of status - must be at the end of the enum */
-  BT_L2CAP_NUM_STATUS,
+    /* Total number of status - must be at the end of the enum */
+    BT_L2CAP_NUM_STATUS,
 } __packed bt_l2cap_chan_status_t;
 
 /** @brief L2CAP Channel structure. */
 struct bt_l2cap_chan {
-  /** Channel connection reference */
-  struct bt_conn *conn;
-  /** Channel operations reference */
-  struct bt_l2cap_chan_ops *ops;
-  sys_snode_t               node;
-  bt_l2cap_chan_destroy_t   destroy;
-  /* Response Timeout eXpired (RTX) timer */
-  struct k_delayed_work rtx_work;
-  ATOMIC_DEFINE(status, BT_L2CAP_NUM_STATUS);
+    /** Channel connection reference */
+    struct bt_conn *conn;
+    /** Channel operations reference */
+    struct bt_l2cap_chan_ops *ops;
+    sys_snode_t node;
+    bt_l2cap_chan_destroy_t destroy;
+    /* Response Timeout eXpired (RTX) timer */
+    struct k_delayed_work rtx_work;
+    ATOMIC_DEFINE(status, BT_L2CAP_NUM_STATUS);
 
 #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
-  bt_l2cap_chan_state_t state;
-  /** Remote PSM to be connected */
-  u16_t psm;
-  /** Helps match request context during CoC */
-  u8_t          ident;
-  bt_security_t required_sec_level;
+    bt_l2cap_chan_state_t state;
+    /** Remote PSM to be connected */
+    u16_t psm;
+    /** Helps match request context during CoC */
+    u8_t ident;
+    bt_security_t required_sec_level;
 #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
 };
 
 /** @brief LE L2CAP Endpoint structure. */
 struct bt_l2cap_le_endpoint {
-  /** Endpoint CID */
-  u16_t cid;
-  /** Endpoint Maximum Transmission Unit */
-  u16_t mtu;
-  /** Endpoint Maximum PDU payload Size */
-  u16_t mps;
-  /** Endpoint initial credits */
-  u16_t init_credits;
-  /** Endpoint credits */
-  struct k_sem credits;
+    /** Endpoint CID */
+    u16_t cid;
+    /** Endpoint Maximum Transmission Unit */
+    u16_t mtu;
+    /** Endpoint Maximum PDU payload Size */
+    u16_t mps;
+    /** Endpoint initial credits */
+    u16_t init_credits;
+    /** Endpoint credits */
+    struct k_sem credits;
 };
 
 /** @brief LE L2CAP Channel structure. */
 struct bt_l2cap_le_chan {
-  /** Common L2CAP channel reference object */
-  struct bt_l2cap_chan chan;
-  /** Channel Receiving Endpoint */
-  struct bt_l2cap_le_endpoint rx;
-  /** Channel Transmission Endpoint */
-  struct bt_l2cap_le_endpoint tx;
-  /** Channel Transmission queue */
-  struct k_fifo tx_queue;
-  /** Channel Pending Transmission buffer  */
-  struct net_buf *tx_buf;
-  /** Segment SDU packet from upper layer */
-  struct net_buf *_sdu;
-  u16_t           _sdu_len;
-
-  struct k_work rx_work;
-  struct k_fifo rx_queue;
+    /** Common L2CAP channel reference object */
+    struct bt_l2cap_chan chan;
+    /** Channel Receiving Endpoint */
+    struct bt_l2cap_le_endpoint rx;
+    /** Channel Transmission Endpoint */
+    struct bt_l2cap_le_endpoint tx;
+    /** Channel Transmission queue */
+    struct k_fifo tx_queue;
+    /** Channel Pending Transmission buffer  */
+    struct net_buf *tx_buf;
+    /** Segment SDU packet from upper layer */
+    struct net_buf *_sdu;
+    u16_t _sdu_len;
+
+    struct k_work rx_work;
+    struct k_fifo rx_queue;
 };
 
 /** @def BT_L2CAP_LE_CHAN(_ch)
@@ -144,107 +145,107 @@ struct bt_l2cap_le_chan {
 
 /** @brief BREDR L2CAP Endpoint structure. */
 struct bt_l2cap_br_endpoint {
-  /** Endpoint CID */
-  u16_t cid;
-  /** Endpoint Maximum Transmission Unit */
-  u16_t mtu;
+    /** Endpoint CID */
+    u16_t cid;
+    /** Endpoint Maximum Transmission Unit */
+    u16_t mtu;
 };
 
 /** @brief BREDR L2CAP Channel structure. */
 struct bt_l2cap_br_chan {
-  /** Common L2CAP channel reference object */
-  struct bt_l2cap_chan chan;
-  /** Channel Receiving Endpoint */
-  struct bt_l2cap_br_endpoint rx;
-  /** Channel Transmission Endpoint */
-  struct bt_l2cap_br_endpoint tx;
-  /* For internal use only */
-  atomic_t flags[1];
+    /** Common L2CAP channel reference object */
+    struct bt_l2cap_chan chan;
+    /** Channel Receiving Endpoint */
+    struct bt_l2cap_br_endpoint rx;
+    /** Channel Transmission Endpoint */
+    struct bt_l2cap_br_endpoint tx;
+    /* For internal use only */
+    atomic_t flags[1];
 };
 
 /** @brief L2CAP Channel operations structure. */
 struct bt_l2cap_chan_ops {
-  /** Channel connected callback
-   *
-   *  If this callback is provided it will be called whenever the
-   *  connection completes.
-   *
-   *  @param chan The channel that has been connected
-   */
-  void (*connected)(struct bt_l2cap_chan *chan);
-
-  /** Channel disconnected callback
-   *
-   *  If this callback is provided it will be called whenever the
-   *  channel is disconnected, including when a connection gets
-   *  rejected.
-   *
-   *  @param chan The channel that has been Disconnected
-   */
-  void (*disconnected)(struct bt_l2cap_chan *chan);
-
-  /** Channel encrypt_change callback
-   *
-   *  If this callback is provided it will be called whenever the
-   *  security level changed (indirectly link encryption done) or
-   *  authentication procedure fails. In both cases security initiator
-   *  and responder got the final status (HCI status) passed by
-   *  related to encryption and authentication events from local host's
-   *  controller.
-   *
-   *  @param chan The channel which has made encryption status changed.
-   *  @param status HCI status of performed security procedure caused
-   *  by channel security requirements. The value is populated
-   *  by HCI layer and set to 0 when success and to non-zero (reference to
-   *  HCI Error Codes) when security/authentication failed.
-   */
-  void (*encrypt_change)(struct bt_l2cap_chan *chan, u8_t hci_status);
-
-  /** Channel alloc_buf callback
-   *
-   *  If this callback is provided the channel will use it to allocate
-   *  buffers to store incoming data.
-   *
-   *  @param chan The channel requesting a buffer.
-   *
-   *  @return Allocated buffer.
-   */
-  struct net_buf *(*alloc_buf)(struct bt_l2cap_chan *chan);
-
-  /** Channel recv callback
-   *
-   *  @param chan The channel receiving data.
-   *  @param buf Buffer containing incoming data.
-   *
-   *  @return 0 in case of success or negative value in case of error.
-   *  If -EINPROGRESS is returned user has to confirm once the data has
-   *  been processed by calling bt_l2cap_chan_recv_complete passing back
-   *  the buffer received with its original user_data which contains the
-   *  number of segments/credits used by the packet.
-   */
-  int (*recv)(struct bt_l2cap_chan *chan, struct net_buf *buf);
-
-  /*  Channel sent callback
-   *
-   *  If this callback is provided it will be called whenever a SDU has
-   *  been completely sent.
-   *
-   *  @param chan The channel which has sent data.
-   */
-  void (*sent)(struct bt_l2cap_chan *chan);
-
-  /*  Channel status callback
-   *
-   *  If this callback is provided it will be called whenever the
-   *  channel status changes.
-   *
-   *  @param chan The channel which status changed
-   *  @param status The channel status
-   */
-  void (*status)(struct bt_l2cap_chan *chan, atomic_t *status);
+    /** Channel connected callback
+	 *
+	 *  If this callback is provided it will be called whenever the
+	 *  connection completes.
+	 *
+	 *  @param chan The channel that has been connected
+	 */
+    void (*connected)(struct bt_l2cap_chan *chan);
+
+    /** Channel disconnected callback
+	 *
+	 *  If this callback is provided it will be called whenever the
+	 *  channel is disconnected, including when a connection gets
+	 *  rejected.
+	 *
+	 *  @param chan The channel that has been Disconnected
+	 */
+    void (*disconnected)(struct bt_l2cap_chan *chan);
+
+    /** Channel encrypt_change callback
+	 *
+	 *  If this callback is provided it will be called whenever the
+	 *  security level changed (indirectly link encryption done) or
+	 *  authentication procedure fails. In both cases security initiator
+	 *  and responder got the final status (HCI status) passed by
+	 *  related to encryption and authentication events from local host's
+	 *  controller.
+	 *
+	 *  @param chan The channel which has made encryption status changed.
+	 *  @param status HCI status of performed security procedure caused
+	 *  by channel security requirements. The value is populated
+	 *  by HCI layer and set to 0 when success and to non-zero (reference to
+	 *  HCI Error Codes) when security/authentication failed.
+	 */
+    void (*encrypt_change)(struct bt_l2cap_chan *chan, u8_t hci_status);
+
+    /** Channel alloc_buf callback
+	 *
+	 *  If this callback is provided the channel will use it to allocate
+	 *  buffers to store incoming data.
+	 *
+	 *  @param chan The channel requesting a buffer.
+	 *
+	 *  @return Allocated buffer.
+	 */
+    struct net_buf *(*alloc_buf)(struct bt_l2cap_chan *chan);
+
+    /** Channel recv callback
+	 *
+	 *  @param chan The channel receiving data.
+	 *  @param buf Buffer containing incoming data.
+	 *
+	 *  @return 0 in case of success or negative value in case of error.
+	 *  If -EINPROGRESS is returned user has to confirm once the data has
+	 *  been processed by calling bt_l2cap_chan_recv_complete passing back
+	 *  the buffer received with its original user_data which contains the
+	 *  number of segments/credits used by the packet.
+	 */
+    int (*recv)(struct bt_l2cap_chan *chan, struct net_buf *buf);
+
+    /*  Channel sent callback
+	 *
+	 *  If this callback is provided it will be called whenever a SDU has
+	 *  been completely sent.
+	 *
+	 *  @param chan The channel which has sent data.
+	 */
+    void (*sent)(struct bt_l2cap_chan *chan);
+
+    /*  Channel status callback
+	 *
+	 *  If this callback is provided it will be called whenever the
+	 *  channel status changes.
+	 *
+	 *  @param chan The channel which status changed
+	 *  @param status The channel status
+	 */
+    void (*status)(struct bt_l2cap_chan *chan, atomic_t *status);
 
 #if defined(BFLB_BLE_MTU_CHANGE_CB)
-  void (*mtu_changed)(struct bt_l2cap_chan *chan, u16_t mtu);
+    void (*mtu_changed)(struct bt_l2cap_chan *chan, u16_t mtu);
 #endif
 };
 
@@ -255,40 +256,40 @@ struct bt_l2cap_chan_ops {
 
 /** @brief L2CAP Server structure. */
 struct bt_l2cap_server {
-  /** Server PSM. Possible values:
-   *
-   *  0               A dynamic value will be auto-allocated when
-   *                  bt_l2cap_server_register() is called.
-   *
-   *  0x0001-0x007f   Standard, Bluetooth SIG-assigned fixed values.
-   *
-   *  0x0080-0x00ff   Dynamically allocated. May be pre-set by the
-   *                  application before server registration (not
-   *                  recommended however), or auto-allocated by the
-   *                  stack if the app gave 0 as the value.
-   */
-  u16_t psm;
-
-  /** Required minimim security level */
-  bt_security_t sec_level;
-
-  /** Server accept callback
-   *
-   *  This callback is called whenever a new incoming connection requires
-   *  authorization.
-   *
-   *  @param conn The connection that is requesting authorization
-   *  @param chan Pointer to received the allocated channel
-   *
-   *  @return 0 in case of success or negative value in case of error.
-   *  Possible return values:
-   *  -ENOMEM if no available space for new channel.
-   *  -EACCES if application did not authorize the connection.
-   *  -EPERM if encryption key size is too short.
-   */
-  int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan);
-
-  sys_snode_t node;
+    /** Server PSM. Possible values:
+	 *
+	 *  0               A dynamic value will be auto-allocated when
+	 *                  bt_l2cap_server_register() is called.
+	 *
+	 *  0x0001-0x007f   Standard, Bluetooth SIG-assigned fixed values.
+	 *
+	 *  0x0080-0x00ff   Dynamically allocated. May be pre-set by the
+	 *                  application before server registration (not
+	 *                  recommended however), or auto-allocated by the
+	 *                  stack if the app gave 0 as the value.
+	 */
+    u16_t psm;
+
+    /** Required minimim security level */
+    bt_security_t sec_level;
+
+    /** Server accept callback
+	 *
+	 *  This callback is called whenever a new incoming connection requires
+	 *  authorization.
+	 *
+	 *  @param conn The connection that is requesting authorization
+	 *  @param chan Pointer to received the allocated channel
+	 *
+	 *  @return 0 in case of success or negative value in case of error.
+	 *  Possible return values:
+	 *  -ENOMEM if no available space for new channel.
+	 *  -EACCES if application did not authorize the connection.
+	 *  -EPERM if encryption key size is too short.
+	 */
+    int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan);
+
+    sys_snode_t node;
 };
 
 /** @brief Register L2CAP server.
@@ -342,7 +343,8 @@ int bt_l2cap_br_server_register(struct bt_l2cap_server *server);
  *
  *  @return 0 in case of success or negative value in case of error.
  */
-int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, u16_t psm);
+int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan,
+                          u16_t psm);
 
 /** @brief Disconnect L2CAP channel
  *
@@ -380,7 +382,8 @@ int bt_l2cap_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf);
  *
  *  @return 0 in case of success or negative value in case of error.
  */
-int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan, struct net_buf *buf);
+int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan,
+                                struct net_buf *buf);
 
 #ifdef __cplusplus
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/uuid.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/uuid.h
index dcfbc92ee..8483b16e2 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/uuid.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/bluetooth/uuid.h
@@ -69,11 +69,11 @@ struct bt_uuid_128 {
     }
 
 #define BT_UUID_DECLARE_16(value) \
-    ((struct bt_uuid *)(&(struct bt_uuid_16)BT_UUID_INIT_16(value)))
+    ((struct bt_uuid *)((struct bt_uuid_16[]){ BT_UUID_INIT_16(value) }))
 #define BT_UUID_DECLARE_32(value) \
-    ((struct bt_uuid *)(&(struct bt_uuid_32)BT_UUID_INIT_32(value)))
+    ((struct bt_uuid *)((struct bt_uuid_32[]){ BT_UUID_INIT_32(value) }))
 #define BT_UUID_DECLARE_128(value...) \
-    ((struct bt_uuid *)(&(struct bt_uuid_128)BT_UUID_INIT_128(value)))
+    ((struct bt_uuid *)((struct bt_uuid_128[]){ BT_UUID_INIT_128(value) }))
 
 #define BT_UUID_16(__u)  CONTAINER_OF(__u, struct bt_uuid_16, uuid)
 #define BT_UUID_32(__u)  CONTAINER_OF(__u, struct bt_uuid_32, uuid)
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/drivers/bluetooth/hci_driver.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/drivers/bluetooth/hci_driver.h
index 2cb23d061..3bc5d40b4 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/drivers/bluetooth/hci_driver.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/include/drivers/bluetooth/hci_driver.h
@@ -194,10 +194,6 @@ void hci_driver_enque_recvq(struct net_buf *buf);
 
 int hci_driver_init(void);
 
-#if (BFLB_BLE_CO_THREAD)
-void co_tx_thread();
-#endif
-
 #endif //#if (BFLB_BLE)
 
 #ifdef __cplusplus
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/bl_port.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/bl_port.c
index ccc1568d0..a4b407b86 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/bl_port.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/bl_port.c
@@ -1,384 +1,337 @@
-#include 
-#include 
 #include 
+#include 
+#include 
 
 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BLUETOOTH_DEBUG_CORE)
 
+#include "atomic.h"
 #include 
 #include 
 #include 
 #include 
-#include "atomic.h"
 
 #include "errno.h"
 #include 
-#include 
 #include 
-#include 
 #include 
+#include 
+#include 
 
 #if defined(BL_MCU_SDK)
 #define TRNG_LOOP_COUNTER (17)
 extern BL_Err_Type Sec_Eng_Trng_Get_Random(uint8_t *data, uint32_t len);
 extern BL_Err_Type Sec_Eng_Trng_Enable(void);
-int bl_rand();
+int                bl_rand();
 #else
 extern int bl_rand();
 #endif
 
-int ble_rand()
-{
+int ble_rand() {
 #if defined(CONFIG_HW_SEC_ENG_DISABLE)
-    extern long random(void);
-    return random();
+  return random();
 #else
-    return bl_rand();
+  return bl_rand();
 #endif
 }
 
 #if defined(BL_MCU_SDK)
-int bl_rand()
-{
-    unsigned int val;
-    int counter = 0;
-    int32_t ret = 0;
-    do {
-        ret = Sec_Eng_Trng_Get_Random((uint8_t *)&val, 4);
-        if (ret < -1) {
-            return -1;
-        }
-        if ((counter++) > TRNG_LOOP_COUNTER) {
-            break;
-        }
-    } while (0 == val);
-    val >>= 1; //leave signe bit alone
-    return val;
+int bl_rand() {
+  unsigned int val;
+  int          counter = 0;
+  int32_t      ret     = 0;
+  do {
+    ret = Sec_Eng_Trng_Get_Random((uint8_t *)&val, 4);
+    if (ret < -1) {
+      return -1;
+    }
+    if ((counter++) > TRNG_LOOP_COUNTER) {
+      break;
+    }
+  } while (0 == val);
+  val >>= 1; // leave signe bit alone
+  return val;
 }
 #endif
 
-void k_queue_init(struct k_queue *queue, int size)
-{
-    //int size = 20;
-    uint8_t blk_size = sizeof(void *) + 1;
+void k_queue_init(struct k_queue *queue, int size) {
+  // int size = 20;
+  uint8_t blk_size = sizeof(void *);
 
-    queue->hdl = xQueueCreate(size, blk_size);
-    BT_ASSERT(queue->hdl != NULL);
+  queue->hdl = xQueueCreate(size, blk_size);
+  BT_ASSERT(queue->hdl != NULL);
 
-    sys_dlist_init(&queue->poll_events);
+  sys_dlist_init(&queue->poll_events);
 }
 
-void k_queue_insert(struct k_queue *queue, void *prev, void *data)
-{
-    BaseType_t ret;
-    (void)ret;
-
-    ret = xQueueSend(queue->hdl, &data, portMAX_DELAY);
-    BT_ASSERT(ret == pdPASS);
-}
+void k_queue_insert(struct k_queue *queue, void *prev, void *data) {
+  BaseType_t ret;
+  (void)ret;
 
-void k_queue_append(struct k_queue *queue, void *data)
-{
-    k_queue_insert(queue, NULL, data);
+  ret = xQueueSend(queue->hdl, &data, portMAX_DELAY);
+  BT_ASSERT(ret == pdPASS);
 }
 
-void k_queue_insert_from_isr(struct k_queue *queue, void *prev, void *data)
-{
-    BaseType_t xHigherPriorityTaskWoken;
+void k_queue_append(struct k_queue *queue, void *data) { k_queue_insert(queue, NULL, data); }
 
-    xQueueSendFromISR(queue->hdl, &data, &xHigherPriorityTaskWoken);
-    if (xHigherPriorityTaskWoken == pdTRUE) {
-        portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
-    }
-}
+void k_queue_insert_from_isr(struct k_queue *queue, void *prev, void *data) {
+  BaseType_t xHigherPriorityTaskWoken;
 
-void k_queue_append_from_isr(struct k_queue *queue, void *data)
-{
-    k_queue_insert_from_isr(queue, NULL, data);
+  xQueueSendFromISR(queue->hdl, &data, &xHigherPriorityTaskWoken);
+  if (xHigherPriorityTaskWoken == pdTRUE) {
+    portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
+  }
 }
 
-void k_queue_free(struct k_queue *queue)
-{
-    if (NULL == queue || NULL == queue->hdl) {
-        BT_ERR("Queue is NULL\n");
-        return;
-    }
+void k_queue_append_from_isr(struct k_queue *queue, void *data) { k_queue_insert_from_isr(queue, NULL, data); }
 
-    vQueueDelete(queue->hdl);
-    queue->hdl = NULL;
+void k_queue_free(struct k_queue *queue) {
+  if (NULL == queue || NULL == queue->hdl) {
+    BT_ERR("Queue is NULL\n");
     return;
-}
+  }
 
-void k_queue_prepend(struct k_queue *queue, void *data)
-{
-    k_queue_insert(queue, NULL, data);
+  vQueueDelete(queue->hdl);
+  queue->hdl = NULL;
+  return;
 }
 
-void k_queue_append_list(struct k_queue *queue, void *head, void *tail)
-{
-    struct net_buf *buf_tail = (struct net_buf *)head;
+void k_queue_prepend(struct k_queue *queue, void *data) { k_queue_insert(queue, NULL, data); }
 
-    for (buf_tail = (struct net_buf *)head; buf_tail; buf_tail = buf_tail->frags) {
-        k_queue_append(queue, buf_tail);
-    }
+void k_queue_append_list(struct k_queue *queue, void *head, void *tail) {
+  struct net_buf *buf_tail = (struct net_buf *)head;
+
+  for (buf_tail = (struct net_buf *)head; buf_tail; buf_tail = buf_tail->frags) {
+    k_queue_append(queue, buf_tail);
+  }
 }
 
-void *k_queue_get(struct k_queue *queue, s32_t timeout)
-{
-    void *msg = NULL;
-    unsigned int t = timeout;
-    BaseType_t ret;
+void *k_queue_get(struct k_queue *queue, s32_t timeout) {
+  void        *msg = NULL;
+  unsigned int t   = timeout;
+  BaseType_t   ret;
 
-    (void)ret;
+  (void)ret;
 
-    if (timeout == K_FOREVER) {
-        t = BL_WAIT_FOREVER;
-    } else if (timeout == K_NO_WAIT) {
-        t = BL_NO_WAIT;
-    }
+  if (timeout == K_FOREVER) {
+    t = BL_WAIT_FOREVER;
+  } else if (timeout == K_NO_WAIT) {
+    t = BL_NO_WAIT;
+  }
 
-    ret = xQueueReceive(queue->hdl, &msg, t == BL_WAIT_FOREVER ? portMAX_DELAY : ms2tick(t));
-    if (ret == pdPASS) {
-        return msg;
-    } else {
-        return NULL;
-    }
+  ret = xQueueReceive(queue->hdl, &msg, t == BL_WAIT_FOREVER ? portMAX_DELAY : ms2tick(t));
+  if (ret == pdPASS) {
+    return msg;
+  } else {
+    return NULL;
+  }
 }
 
-int k_queue_is_empty(struct k_queue *queue)
-{
-    return uxQueueMessagesWaiting(queue->hdl) ? 0 : 1;
-}
+int k_queue_is_empty(struct k_queue *queue) { return uxQueueMessagesWaiting(queue->hdl) ? 0 : 1; }
 
-int k_queue_get_cnt(struct k_queue *queue)
-{
-    return uxQueueMessagesWaiting(queue->hdl);
-}
+int k_queue_get_cnt(struct k_queue *queue) { return uxQueueMessagesWaiting(queue->hdl); }
 
-int k_sem_init(struct k_sem *sem, unsigned int initial_count, unsigned int limit)
-{
-    if (NULL == sem) {
-        BT_ERR("sem is NULL\n");
-        return -EINVAL;
-    }
+int k_sem_init(struct k_sem *sem, unsigned int initial_count, unsigned int limit) {
+  if (NULL == sem) {
+    BT_ERR("sem is NULL\n");
+    return -EINVAL;
+  }
 
-    sem->sem.hdl = xSemaphoreCreateCounting(limit, initial_count);
-    sys_dlist_init(&sem->poll_events);
-    return 0;
+  sem->sem.hdl = xSemaphoreCreateCounting(limit, initial_count);
+  sys_dlist_init(&sem->poll_events);
+  return 0;
 }
 
-int k_sem_take(struct k_sem *sem, uint32_t timeout)
-{
-    BaseType_t ret;
-    unsigned int t = timeout;
+int k_sem_take(struct k_sem *sem, uint32_t timeout) {
+  BaseType_t   ret;
+  unsigned int t = timeout;
 
-    (void)ret;
-    if (timeout == K_FOREVER) {
-        t = BL_WAIT_FOREVER;
-    } else if (timeout == K_NO_WAIT) {
-        t = BL_NO_WAIT;
-    }
+  (void)ret;
+  if (timeout == K_FOREVER) {
+    t = BL_WAIT_FOREVER;
+  } else if (timeout == K_NO_WAIT) {
+    t = BL_NO_WAIT;
+  }
 
-    if (NULL == sem) {
-        return -1;
-    }
+  if (NULL == sem) {
+    return -1;
+  }
 
-    ret = xSemaphoreTake(sem->sem.hdl, t == BL_WAIT_FOREVER ? portMAX_DELAY : ms2tick(t));
-    return ret == pdPASS ? 0 : -1;
+  ret = xSemaphoreTake(sem->sem.hdl, t == BL_WAIT_FOREVER ? portMAX_DELAY : ms2tick(t));
+  return ret == pdPASS ? 0 : -1;
 }
 
-int k_sem_give(struct k_sem *sem)
-{
-    BaseType_t ret;
-    (void)ret;
+int k_sem_give(struct k_sem *sem) {
+  BaseType_t ret;
+  (void)ret;
 
-    if (NULL == sem) {
-        BT_ERR("sem is NULL\n");
-        return -EINVAL;
-    }
+  if (NULL == sem) {
+    BT_ERR("sem is NULL\n");
+    return -EINVAL;
+  }
 
-    ret = xSemaphoreGive(sem->sem.hdl);
-    return ret == pdPASS ? 0 : -1;
+  ret = xSemaphoreGive(sem->sem.hdl);
+  return ret == pdPASS ? 0 : -1;
 }
 
-int k_sem_delete(struct k_sem *sem)
-{
-    if (NULL == sem || NULL == sem->sem.hdl) {
-        BT_ERR("sem is NULL\n");
-        return -EINVAL;
-    }
+int k_sem_delete(struct k_sem *sem) {
+  if (NULL == sem || NULL == sem->sem.hdl) {
+    BT_ERR("sem is NULL\n");
+    return -EINVAL;
+  }
 
-    vSemaphoreDelete(sem->sem.hdl);
-    sem->sem.hdl = NULL;
-    return 0;
+  vSemaphoreDelete(sem->sem.hdl);
+  sem->sem.hdl = NULL;
+  return 0;
 }
 
-unsigned int k_sem_count_get(struct k_sem *sem)
-{
-    return uxQueueMessagesWaiting(sem->sem.hdl);
-}
+unsigned int k_sem_count_get(struct k_sem *sem) { return uxQueueMessagesWaiting(sem->sem.hdl); }
 
-void k_mutex_init(struct k_mutex *mutex)
-{
-    if (NULL == mutex) {
-        BT_ERR("mutex is NULL\n");
-        return;
-    }
+void k_mutex_init(struct k_mutex *mutex) {
+  if (NULL == mutex) {
+    BT_ERR("mutex is NULL\n");
+    return;
+  }
 
-    mutex->mutex.hdl = xSemaphoreCreateMutex();
-    BT_ASSERT(mutex->mutex.hdl != NULL);
-    sys_dlist_init(&mutex->poll_events);
+  mutex->mutex.hdl = xSemaphoreCreateMutex();
+  BT_ASSERT(mutex->mutex.hdl != NULL);
+  sys_dlist_init(&mutex->poll_events);
 }
 
-int64_t k_uptime_get()
-{
-    return k_now_ms();
-}
+int64_t k_uptime_get() { return k_now_ms(); }
 
-u32_t k_uptime_get_32(void)
-{
-    return (u32_t)k_now_ms();
-}
+u32_t k_uptime_get_32(void) { return (u32_t)k_now_ms(); }
 
-int k_thread_create(struct k_thread *new_thread, const char *name,
-                    size_t stack_size, k_thread_entry_t entry,
-                    int prio)
-{
-    stack_size /= sizeof(StackType_t);
-    xTaskCreate(entry, name, stack_size, NULL, prio, (void *)(&new_thread->task));
+int k_thread_create(struct k_thread *new_thread, const char *name, size_t stack_size, k_thread_entry_t entry, int prio) {
+  stack_size /= sizeof(StackType_t);
+  xTaskCreate(entry, name, stack_size, NULL, prio, (void *)(&new_thread->task));
 
-    return new_thread->task ? 0 : -1;
+  return new_thread->task ? 0 : -1;
 }
 
-void k_thread_delete(struct k_thread *new_thread)
-{
-    if (NULL == new_thread || 0 == new_thread->task) {
-        BT_ERR("task is NULL\n");
-        return;
-    }
-
-    vTaskDelete((void *)(new_thread->task));
-    new_thread->task = 0;
+void k_thread_delete(struct k_thread *thread) {
+  if (NULL == thread || 0 == thread->task) {
+    BT_ERR("task is NULL\n");
     return;
+  }
+
+  vTaskDelete((void *)(thread->task));
+  thread->task = 0;
+  return;
 }
 
-int k_yield(void)
-{
-    taskYIELD();
-    return 0;
+bool k_is_current_thread(struct k_thread *thread) {
+  eTaskState thread_state = eTaskGetState((void *)(thread->task));
+  if (thread_state == eRunning)
+    return true;
+  else
+    return false;
 }
 
-void k_sleep(s32_t dur_ms)
-{
-    TickType_t ticks;
-    ticks = pdMS_TO_TICKS(dur_ms);
-    vTaskDelay(ticks);
+int k_yield(void) {
+  taskYIELD();
+  return 0;
 }
 
-unsigned int irq_lock(void)
-{
-    taskENTER_CRITICAL();
-    return 1;
+void k_sleep(s32_t dur_ms) {
+  TickType_t ticks;
+  ticks = pdMS_TO_TICKS(dur_ms);
+  vTaskDelay(ticks);
 }
 
-void irq_unlock(unsigned int key)
-{
-    taskEXIT_CRITICAL();
+unsigned int irq_lock(void) {
+  taskENTER_CRITICAL();
+  return 1;
 }
 
-int k_is_in_isr(void)
-{
+void irq_unlock(unsigned int key) { taskEXIT_CRITICAL(); }
+
+int k_is_in_isr(void) {
 #if defined(ARCH_RISCV)
-    return (xPortIsInsideInterrupt());
+  return (xPortIsInsideInterrupt());
 #else
-    /* IRQs + PendSV (14) + SYSTICK (15) are interrupts. */
-    return (__get_IPSR() > 13);
+  /* IRQs + PendSV (14) + SYSTICK (15) are interrupts. */
+  return (__get_IPSR() > 13);
 #endif
 
-    return 0;
+  return 0;
 }
 
-void k_timer_init(k_timer_t *timer, k_timer_handler_t handle, void *args)
-{
-    BT_ASSERT(timer != NULL);
-    timer->handler = handle;
-    timer->args = args;
-    /* Set args as timer id */
-    timer->timer.hdl = xTimerCreate("Timer", pdMS_TO_TICKS(1000), 0, args, (TimerCallbackFunction_t)(timer->handler));
-    BT_ASSERT(timer->timer.hdl != NULL);
+void k_timer_init(k_timer_t *timer, k_timer_handler_t handle, void *args) {
+  BT_ASSERT(timer != NULL);
+  timer->handler = handle;
+  timer->args    = args;
+  /* Set args as timer id */
+  timer->timer.hdl = xTimerCreate("Timer", pdMS_TO_TICKS(1000), 0, args, (TimerCallbackFunction_t)(timer->handler));
+  BT_ASSERT(timer->timer.hdl != NULL);
 }
 
-void *k_timer_get_id(void *hdl)
-{
-    return pvTimerGetTimerID((TimerHandle_t)hdl);
-}
+void *k_timer_get_id(void *hdl) { return pvTimerGetTimerID((TimerHandle_t)hdl); }
 
-void k_timer_start(k_timer_t *timer, uint32_t timeout)
-{
-    BaseType_t ret;
-    (void)ret;
+void k_timer_start(k_timer_t *timer, uint32_t timeout) {
+  BaseType_t ret;
+  (void)ret;
 
-    BT_ASSERT(timer != NULL);
-    timer->timeout = timeout;
-    timer->start_ms = k_now_ms();
+  BT_ASSERT(timer != NULL);
+  timer->timeout  = timeout;
+  timer->start_ms = k_now_ms();
 
-    ret = xTimerChangePeriod(timer->timer.hdl, pdMS_TO_TICKS(timeout), 0);
-    BT_ASSERT(ret == pdPASS);
-    ret = xTimerStart(timer->timer.hdl, 0);
-    BT_ASSERT(ret == pdPASS);
+  ret = xTimerChangePeriod(timer->timer.hdl, pdMS_TO_TICKS(timeout), 0);
+  BT_ASSERT(ret == pdPASS);
+  ret = xTimerStart(timer->timer.hdl, 0);
+  BT_ASSERT(ret == pdPASS);
 }
 
-void k_timer_reset(k_timer_t *timer)
-{
-    BaseType_t ret;
+void k_timer_reset(k_timer_t *timer) {
+  BaseType_t ret;
 
-    (void)ret;
-    BT_ASSERT(timer != NULL);
+  (void)ret;
+  BT_ASSERT(timer != NULL);
 
-    ret = xTimerReset(timer->timer.hdl, 0);
-    BT_ASSERT(ret == pdPASS);
+  ret = xTimerReset(timer->timer.hdl, 0);
+  BT_ASSERT(ret == pdPASS);
 }
 
-void k_timer_stop(k_timer_t *timer)
-{
-    BaseType_t ret;
+void k_timer_stop(k_timer_t *timer) {
+  BaseType_t ret;
 
-    (void)ret;
-    BT_ASSERT(timer != NULL);
+  (void)ret;
+  BT_ASSERT(timer != NULL);
 
-    ret = xTimerStop(timer->timer.hdl, 0);
-    BT_ASSERT(ret == pdPASS);
+  ret = xTimerStop(timer->timer.hdl, 0);
+  BT_ASSERT(ret == pdPASS);
 }
 
-void k_timer_delete(k_timer_t *timer)
-{
-    BaseType_t ret;
-    (void)ret;
+void k_timer_delete(k_timer_t *timer) {
+  BaseType_t ret;
+  (void)ret;
 
-    BT_ASSERT(timer != NULL);
+  BT_ASSERT(timer != NULL);
 
-    ret = xTimerDelete(timer->timer.hdl, 0);
-    BT_ASSERT(ret == pdPASS);
+  ret = xTimerDelete(timer->timer.hdl, 0);
+  BT_ASSERT(ret == pdPASS);
 }
 
-long long k_now_ms(void)
-{
-    return (long long)(xTaskGetTickCount() * 1000) / configTICK_RATE_HZ;
-}
+long long k_now_ms(void) { return (long long)(xTaskGetTickCount() * 1000) / configTICK_RATE_HZ; }
 
-void k_get_random_byte_array(uint8_t *buf, size_t len)
-{
-    // bl_rand() return a word, but *buf may not be word-aligned
-    for (int i = 0; i < len; i++) {
-        *(buf + i) = (uint8_t)(ble_rand() & 0xFF);
-    }
+void k_get_random_byte_array(uint8_t *buf, size_t len) {
+  // ble_rand() return a word, but *buf may not be word-aligned
+  for (int i = 0; i < len; i++) {
+    *(buf + i) = (uint8_t)(ble_rand() & 0xFF);
+  }
 }
 
-void *k_malloc(size_t size)
-{
-    return pvPortMalloc(size);
+void *k_malloc(size_t size) {
+#if defined(CFG_USE_PSRAM)
+  return pvPortMallocPsram(size);
+#else
+  return pvPortMalloc(size);
+#endif /* CFG_USE_PSRAM */
 }
 
-void k_free(void *buf)
-{
-    return vPortFree(buf);
+void k_free(void *buf) {
+#if defined(CFG_USE_PSRAM)
+  return vPortFreePsram(buf);
+#else
+  return vPortFree(buf);
+#endif
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/bl_port.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/bl_port.h
index 266aa530c..8a45fe31b 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/bl_port.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/bl_port.h
@@ -3,13 +3,14 @@
 #if defined(BL_MCU_SDK)
 #include "misc.h"
 #endif
-#include 
+#include "ble_config.h"
 #include 
 #include 
 #include 
 #include 
+#include 
 #include 
-#include "types.h"
+#include 
 #include "bl_port.h"
 
 #define BT_UINT_MAX     0xffffffff
@@ -242,6 +243,8 @@ int k_thread_create(struct k_thread *new_thread, const char *name,
 
 void k_thread_delete(struct k_thread *new_thread);
 
+bool k_is_current_thread(struct k_thread *thread);
+
 /**
  * @brief Yield the current thread.
  */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/ble_config.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/ble_config.h
index 9c4d83d67..6bb803e3e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/ble_config.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/ble_config.h
@@ -2,16 +2,13 @@
 #define BLE_CONFIG_H
 
 #include "FreeRTOSConfig.h"
-#ifdef __cplusplus
-extern "C" {
-#endif
 
 /**
  * CONFIG_BLUETOOTH: Enable the bluetooh stack
  */
-//#ifndef CONFIG_BLUETOOTH
-//#error "CONFIG_BLUETOOTH not defined,this header shoudn't include"
-//#endif
+// #ifndef CONFIG_BLUETOOTH
+// #error "CONFIG_BLUETOOTH not defined,this header shoudn't include"
+// #endif
 
 #ifdef CONFIG_BT_BONDABLE
 #undef CONFIG_BT_BONDABLE
@@ -26,25 +23,25 @@ extern "C" {
 #define PTS_CHARC_LEN_EQUAL_MTU_SIZE
 #endif
 
-//#ifndef  CONFIG_BT_STACK_PTS_SM_SLA_KDU_BI_01
-//#define  CONFIG_BT_STACK_PTS_SM_SLA_KDU_BI_01
-//#endif
+// #ifndef  CONFIG_BT_STACK_PTS_SM_SLA_KDU_BI_01
+// #define  CONFIG_BT_STACK_PTS_SM_SLA_KDU_BI_01
+// #endif
 
-//#ifndef  PTS_GAP_SLAVER_CONFIG_READ_CHARC
-//#define  PTS_GAP_SLAVER_CONFIG_READ_CHARC
-//#endif
+// #ifndef  PTS_GAP_SLAVER_CONFIG_READ_CHARC
+// #define  PTS_GAP_SLAVER_CONFIG_READ_CHARC
+// #endif
 
-//#ifndef  PTS_GAP_SLAVER_CONFIG_WRITE_CHARC
-//#define  PTS_GAP_SLAVER_CONFIG_WRITE_CHARC
-//#endif
+// #ifndef  PTS_GAP_SLAVER_CONFIG_WRITE_CHARC
+// #define  PTS_GAP_SLAVER_CONFIG_WRITE_CHARC
+// #endif
 
-//#ifndef  PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC
-//#define  PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC
-//#endif
+// #ifndef  PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC
+// #define  PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC
+// #endif
 
-//#ifndef  PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC
-//#define  PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC
-//#endif
+// #ifndef  PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC
+// #define  PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC
+// #endif
 #define CONFIG_BT_GATT_READ_MULTIPLE 1
 #endif
 
@@ -55,13 +52,31 @@ extern "C" {
 #define CONFIG_BT_HCI_RX_STACK_SIZE 512
 #endif
 
+/**
+ * BL_BLE_CO_THREAD: combine tx rx thread
+ */
+#define BFLB_BT_CO_THREAD 1
+
+#if (BFLB_BT_CO_THREAD)
+#define CONFIG_BT_CO_TASK_PRIO (configMAX_PRIORITIES - 3)
+#if defined(CONFIG_BT_MESH)
+#define CONFIG_BT_CO_STACK_SIZE 3072 // 2048//1536//1024
+#else
+#define CONFIG_BT_CO_STACK_SIZE 2048 // 2048//1536//1024
+#endif
+#endif
+
 #ifndef CONFIG_BT_RX_STACK_SIZE
 #if defined(CONFIG_BT_MESH)
 #define CONFIG_BT_RX_STACK_SIZE 3072 // 2048//1536//1024
 #else
+#if !defined(CONFIG_BT_CONN)
+#define CONFIG_BT_RX_STACK_SIZE 1024
+#else
 #define CONFIG_BT_RX_STACK_SIZE 2048 // 1536//1024
 #endif
 #endif
+#endif
 
 #ifndef CONFIG_BT_CTLR_RX_PRIO_STACK_SIZE
 #define CONFIG_BT_CTLR_RX_PRIO_STACK_SIZE 156
@@ -77,8 +92,12 @@ extern "C" {
  */
 
 #ifndef CONFIG_BT_HCI_TX_STACK_SIZE
+#if !defined(CONFIG_BT_CONN)
+#define CONFIG_BT_HCI_TX_STACK_SIZE 1024
+#else
 #define CONFIG_BT_HCI_TX_STACK_SIZE 1536 // 1024//200
 #endif
+#endif
 
 /**
  * CONFIG_BT_HCI_TX_PRIO: tx thread priority
@@ -91,13 +110,6 @@ extern "C" {
 #define CONFIG_BT_CTLR_RX_PRIO (configMAX_PRIORITIES - 4)
 #endif
 
-/**
- * BL_BLE_CO_THREAD: combine tx rx thread
- */
-#ifndef BFLB_BLE_CO_THREAD
-#define BFLB_BLE_CO_THREAD 0
-#endif
-
 /**
  * CONFIG_BT_HCI_CMD_COUNT: hci cmd buffer count,range 2 to 64
  */
@@ -291,9 +303,13 @@ extern "C" {
  * range 1 to 65535,seconds
  */
 #ifndef CONFIG_BT_RPA_TIMEOUT
+#if defined(CONFIG_AUTO_PTS)
+#define CONFIG_BT_RPA_TIMEOUT 60
+#else
 #define CONFIG_BT_RPA_TIMEOUT 900
 #endif
 #endif
+#endif
 
 /**
  *  CONFIG_BT_GATT_DYNAMIC_DB:enables GATT services to be added dynamically to database
@@ -355,7 +371,7 @@ extern "C" {
 #elif defined(BL702)
 #define CONFIG_BT_DEVICE_NAME "BL702-BLE-DEV"
 #else
-#define CONFIG_BT_DEVICE_NAME "BL606P-BTBLE"
+#define CONFIG_BT_DEVICE_NAME "BTBLE-DEV"
 #endif
 #endif
 #endif
@@ -384,9 +400,13 @@ extern "C" {
 #ifndef CONFIG_BT_MESH
 #define CONFIG_BT_WORK_QUEUE_STACK_SIZE 1536 // 1280//512
 #else
+#if !defined(CONFIG_BT_CONN)
+#define CONFIG_BT_WORK_QUEUE_STACK_SIZE 1024
+#else
 #define CONFIG_BT_WORK_QUEUE_STACK_SIZE 2048
 #endif /* CONFIG_BT_MESH */
 #endif
+#endif
 
 /**
  *  CONFIG_BT_WORK_QUEUE_PRIO:Work queue priority.
@@ -520,7 +540,7 @@ extern "C" {
 #define CONFIG_BT_ID_MAX 1
 #endif
 
-//#define PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC 1
+// #define PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC 1
 
 #ifndef CONFIG_BT_L2CAP_TX_FRAG_COUNT
 #define CONFIG_BT_L2CAP_TX_FRAG_COUNT 0
@@ -543,6 +563,10 @@ extern "C" {
 #define CONFIG_BT_PERIPHERAL_PREF_TIMEOUT       400
 #endif
 
+#ifndef CONFIG_BT_PHY_UPDATE
+#define CONFIG_BT_PHY_UPDATE 1
+#endif
+
 #if defined(CONFIG_BT_BREDR)
 #define CONFIG_BT_PAGE_TIMEOUT 0x2000 // 5.12s
 #define CONFIG_BT_L2CAP_RX_MTU 672
@@ -564,17 +588,25 @@ extern "C" {
 
 /*******************************Bouffalo Lab Modification******************************/
 
-//#define BFLB_BLE_DISABLE_STATIC_ATTR
-//#define BFLB_BLE_DISABLE_STATIC_CHANNEL
+// #define BFLB_BLE_DISABLE_STATIC_ATTR
+// #define BFLB_BLE_DISABLE_STATIC_CHANNEL
 #define BFLB_DISABLE_BT
 #define BFLB_FIXED_IRK 0
 #define BFLB_DYNAMIC_ALLOC_MEM
+#if defined(CFG_BLE_PDS) && defined(BL702) && defined(BFLB_BLE) && defined(BFLB_DYNAMIC_ALLOC_MEM)
+#define BFLB_STATIC_ALLOC_MEM 1
+#else
+#define BFLB_STATIC_ALLOC_MEM 0
+#endif
+#define CONFIG_BT_SCAN_WITH_IDENTITY 1
+
 #if defined(CONFIG_AUTO_PTS)
+#define CONFIG_BT_L2CAP_DYNAMIC_CHANNEL
 #define CONFIG_BT_DEVICE_NAME_GATT_WRITABLE 1
 #define CONFIG_BT_GATT_SERVICE_CHANGED      1
 #define CONFIG_BT_GATT_CACHING              1
 #define CONFIG_BT_SCAN_WITH_IDENTITY        1
-//#define CONFIG_BT_ADV_WITH_PUBLIC_ADDR 1
+// #define CONFIG_BT_ADV_WITH_PUBLIC_ADDR 1
 #define CONFIG_BT_ATT_PREPARE_COUNT 64
 #endif
 #endif // BFLB_BLE
@@ -590,9 +622,11 @@ happens, which cause memory leak issue.*/
 /*To avoid duplicated pubkey callback.*/
 #define BFLB_BLE_PATCH_AVOID_DUPLI_PUBKEY_CB
 /*The flag @conn_ref is not clean up after disconnect*/
-#define BFLB_BLE_PATCH_CLEAN_UP_CONNECT_REF
+// #define BFLB_BLE_PATCH_CLEAN_UP_CONNECT_REF
+#if !defined(CONFIG_AUTO_PTS)
 /*To avoid sevice changed indication sent at the very beginning, without any new service added.*/
 #define BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE
+#endif
 #ifdef CONFIG_BT_SETTINGS
 /*Semaphore is used during flash operation. Make sure that freertos has already run up when it
   intends to write information to flash.*/
@@ -610,10 +644,14 @@ BT_SMP_DIST_ENC_KEY bit is not cleared while remote ENC_KEY is received.*/
 #define BFLB_BLE_PATCH_CLEAR_REMOTE_KEY_BIT
 
 #if defined(CONFIG_BT_CENTRAL) || defined(CONFIG_BT_OBSERVER)
-// #define BFLB_BLE_NOTIFY_ADV_DISCARDED
+#if defined(BL602) || defined(BL702)
+#define BFLB_BLE_NOTIFY_ADV_DISCARDED
 #endif
-#ifdef __cplusplus
-};
+#endif
+
+#if defined(CONFIG_BT_CENTRAL)
+#define BFLB_BLE_NOTIFY_ALL
+#define BFLB_BLE_DISCOVER_ONGOING
 #endif
 
 #endif /* BLE_CONFIG_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/zephyr.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/zephyr.h
index 8282ed76c..2b0641121 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/zephyr.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/port/include/zephyr.h
@@ -2,7 +2,6 @@
 #define ZEPHYR_H
 #include 
 #include 
-#include 
 
 #include 
 #include 
@@ -129,7 +128,11 @@ struct k_poll_signal {
     }
 
 extern int k_poll_signal_raise(struct k_poll_signal *signal, int result);
+#if (BFLB_BT_CO_THREAD)
+extern int k_poll(struct k_poll_event *events, int num_events, int total_evt_array_cnt, s32_t timeout, u8_t *to_process);
+#else
 extern int k_poll(struct k_poll_event *events, int num_events, s32_t timeout);
+#endif
 extern void k_poll_event_init(struct k_poll_event *event, u32_t type, int mode, void *obj);
 
 /* public - polling modes */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/alloc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/alloc.c
deleted file mode 100644
index 8e59674b0..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/alloc.c
+++ /dev/null
@@ -1,82 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-#include 
-#include 
-
-#if defined(SBC_DEC_INCLUDED)
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-PRIVATE OI_STATUS OI_CODEC_SBC_Alloc(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                                     OI_UINT32 *codecDataAligned,
-                                     OI_UINT32 codecDataBytes,
-                                     OI_UINT8 maxChannels,
-                                     OI_UINT8 pcmStride)
-{
-    int i;
-    size_t filterBufferCount;
-    size_t subdataSize;
-    OI_BYTE *codecData = (OI_BYTE *)codecDataAligned;
-
-    if (maxChannels < 1 || maxChannels > 2) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    if (pcmStride < 1 || pcmStride > maxChannels) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    common->maxChannels = maxChannels;
-    common->pcmStride = pcmStride;
-
-    /* Compute sizes needed for the memory regions, and bail if we don't have
-     * enough memory for them. */
-    subdataSize = maxChannels * sizeof(common->subdata[0]) * SBC_MAX_BANDS * SBC_MAX_BLOCKS;
-    if (subdataSize > codecDataBytes) {
-        return OI_STATUS_OUT_OF_MEMORY;
-    }
-
-    filterBufferCount = (codecDataBytes - subdataSize) / (sizeof(common->filterBuffer[0][0]) * SBC_MAX_BANDS * maxChannels);
-    if (filterBufferCount < SBC_CODEC_MIN_FILTER_BUFFERS) {
-        return OI_STATUS_OUT_OF_MEMORY;
-    }
-    common->filterBufferLen = filterBufferCount * SBC_MAX_BANDS;
-
-    /* Allocate memory for the subband data */
-    common->subdata = (OI_INT32 *)codecData;
-    codecData += subdataSize;
-    OI_ASSERT(codecDataBytes >= subdataSize);
-    codecDataBytes -= subdataSize;
-
-    /* Allocate memory for the synthesis buffers */
-    for (i = 0; i < maxChannels; ++i) {
-        size_t allocSize = common->filterBufferLen * sizeof(common->filterBuffer[0][0]);
-        common->filterBuffer[i] = (SBC_BUFFER_T *)codecData;
-        OI_ASSERT(codecDataBytes >= allocSize);
-        codecData += allocSize;
-        codecDataBytes -= allocSize;
-    }
-
-    return OI_OK;
-}
-
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc-sbc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc-sbc.c
deleted file mode 100644
index 6eedd26b5..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc-sbc.c
+++ /dev/null
@@ -1,164 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/** @file
-@ingroup codec_internal
-*/
-
-/**@addgroup codec_internal*/
-/**@{*/
-#include 
-
-#if defined(SBC_DEC_INCLUDED)
-
-static void dualBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    OI_UINT bitcountL;
-    OI_UINT bitcountR;
-    OI_UINT bitpoolPreferenceL = 0;
-    OI_UINT bitpoolPreferenceR = 0;
-    BITNEED_UNION1 bitneedsL;
-    BITNEED_UNION1 bitneedsR;
-
-    bitcountL = computeBitneed(common, bitneedsL.uint8, 0, &bitpoolPreferenceL);
-    bitcountR = computeBitneed(common, bitneedsR.uint8, 1, &bitpoolPreferenceR);
-
-    oneChannelBitAllocation(common, &bitneedsL, 0, bitcountL);
-    oneChannelBitAllocation(common, &bitneedsR, 1, bitcountR);
-}
-
-static void stereoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    const OI_UINT nrof_subbands = common->frameInfo.nrof_subbands;
-    BITNEED_UNION2 bitneeds;
-    OI_UINT excess;
-    OI_INT bitadjust;
-    OI_UINT bitcount;
-    OI_UINT sbL;
-    OI_UINT sbR;
-    OI_UINT bitpoolPreference = 0;
-
-    bitcount = computeBitneed(common, &bitneeds.uint8[0], 0, &bitpoolPreference);
-    bitcount += computeBitneed(common, &bitneeds.uint8[nrof_subbands], 1, &bitpoolPreference);
-
-    {
-        OI_UINT ex;
-        bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds.uint32, 2 * nrof_subbands, bitcount, &ex);
-        /* We want the compiler to put excess into a register */
-        excess = ex;
-    }
-    sbL = 0;
-    sbR = nrof_subbands;
-    while (sbL < nrof_subbands) {
-        excess = allocAdjustedBits(&common->bits.uint8[sbL], bitneeds.uint8[sbL] + bitadjust, excess);
-        ++sbL;
-        excess = allocAdjustedBits(&common->bits.uint8[sbR], bitneeds.uint8[sbR] + bitadjust, excess);
-        ++sbR;
-    }
-    sbL = 0;
-    sbR = nrof_subbands;
-    while (excess) {
-        excess = allocExcessBits(&common->bits.uint8[sbL], excess);
-        ++sbL;
-        if (!excess) {
-            break;
-        }
-        excess = allocExcessBits(&common->bits.uint8[sbR], excess);
-        ++sbR;
-    }
-}
-
-static const BIT_ALLOC balloc[] = {
-    monoBitAllocation,   /* SBC_MONO */
-    dualBitAllocation,   /* SBC_DUAL_CHANNEL */
-    stereoBitAllocation, /* SBC_STEREO */
-    stereoBitAllocation  /* SBC_JOINT_STEREO */
-};
-
-PRIVATE void OI_SBC_ComputeBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    OI_ASSERT(common->frameInfo.bitpool <= OI_SBC_MaxBitpool(&common->frameInfo));
-    OI_ASSERT(common->frameInfo.mode < OI_ARRAYSIZE(balloc));
-
-    /*
-     * Using an array of function pointers prevents the compiler from creating a suboptimal
-     * monolithic inlined bit allocation function.
-     */
-    balloc[common->frameInfo.mode](common);
-}
-
-OI_UINT32 OI_CODEC_SBC_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    return internal_CalculateBitrate(frame);
-}
-
-/*
- * Return the current maximum bitneed and clear it.
- */
-OI_UINT8 OI_CODEC_SBC_GetMaxBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    OI_UINT8 max = common->maxBitneed;
-
-    common->maxBitneed = 0;
-    return max;
-}
-
-/*
- * Calculates the bitpool size for a given frame length
- */
-OI_UINT16 OI_CODEC_SBC_CalculateBitpool(OI_CODEC_SBC_FRAME_INFO *frame,
-                                        OI_UINT16 frameLen)
-{
-    OI_UINT16 nrof_subbands = frame->nrof_subbands;
-    OI_UINT16 nrof_blocks = frame->nrof_blocks;
-    OI_UINT16 hdr;
-    OI_UINT16 bits;
-
-    if (frame->mode == SBC_JOINT_STEREO) {
-        hdr = 9 * nrof_subbands;
-    } else {
-        if (frame->mode == SBC_MONO) {
-            hdr = 4 * nrof_subbands;
-        } else {
-            hdr = 8 * nrof_subbands;
-        }
-        if (frame->mode == SBC_DUAL_CHANNEL) {
-            nrof_blocks *= 2;
-        }
-    }
-    bits = 8 * (frameLen - SBC_HEADER_LEN) - hdr;
-    return DIVIDE(bits, nrof_blocks);
-}
-
-OI_UINT16 OI_CODEC_SBC_CalculatePcmBytes(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    return sizeof(OI_INT16) * common->pcmStride * common->frameInfo.nrof_subbands * common->frameInfo.nrof_blocks;
-}
-
-OI_UINT16 OI_CODEC_SBC_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    return internal_CalculateFramelen(frame);
-}
-
-/**@}*/
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c
deleted file mode 100644
index 7b8b4586f..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitalloc.c
+++ /dev/null
@@ -1,393 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
- ***********************************************************************************/
-
-/**
-@file
-
-The functions in this file relate to the allocation of available bits to
-subbands within the SBC/eSBC frame, along with support functions for computing
-frame length and bitrate.
-
-@ingroup codec_internal
-*/
-
-/**
-@addtogroup codec_internal
-@{
-*/
-
-#include "oi_utils.h"
-#include 
-
-#if defined(SBC_DEC_INCLUDED)
-
-OI_UINT32 OI_SBC_MaxBitpool(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    switch (frame->mode) {
-        case SBC_MONO:
-        case SBC_DUAL_CHANNEL:
-            return 16 * frame->nrof_subbands;
-        case SBC_STEREO:
-        case SBC_JOINT_STEREO:
-            return 32 * frame->nrof_subbands;
-    }
-
-    ERROR(("Invalid frame mode %d", frame->mode));
-    OI_ASSERT(FALSE);
-    return 0; /* Should never be reached */
-}
-
-PRIVATE OI_UINT16 internal_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    OI_UINT16 nbits = frame->nrof_blocks * frame->bitpool;
-    OI_UINT16 nrof_subbands = frame->nrof_subbands;
-    OI_UINT16 result = nbits;
-
-    if (frame->mode == SBC_JOINT_STEREO) {
-        result += nrof_subbands + (8 * nrof_subbands);
-    } else {
-        if (frame->mode == SBC_DUAL_CHANNEL) {
-            result += nbits;
-        }
-        if (frame->mode == SBC_MONO) {
-            result += 4 * nrof_subbands;
-        } else {
-            result += 8 * nrof_subbands;
-        }
-    }
-    return SBC_HEADER_LEN + (result + 7) / 8;
-}
-
-PRIVATE OI_UINT32 internal_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    OI_UINT blocksbands;
-    blocksbands = frame->nrof_subbands * frame->nrof_blocks;
-
-    return DIVIDE(8 * internal_CalculateFramelen(frame) * frame->frequency, blocksbands);
-}
-
-INLINE OI_UINT16 OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO *frame, OI_UINT *headerLen_)
-{
-    OI_UINT headerLen = SBC_HEADER_LEN + frame->nrof_subbands * frame->nrof_channels / 2;
-
-    if (frame->mode == SBC_JOINT_STEREO) {
-        headerLen++;
-    }
-
-    *headerLen_ = headerLen;
-    return internal_CalculateFramelen(frame);
-}
-
-#define MIN(x, y) ((x) < (y) ? (x) : (y))
-
-/*
- * Computes the bit need for each sample and as also returns a counts of bit needs that are greater
- * than one. This count is used in the first phase of bit allocation.
- *
- * We also compute a preferred bitpool value that this is the minimum bitpool needed to guarantee
- * lossless representation of the audio data. The preferred bitpool may be larger than the bits
- * actually required but the only input we have are the scale factors. For example, it takes 2 bits
- * to represent values in the range -1 .. +1 but the scale factor is 0. To guarantee lossless
- * representation we add 2 to each scale factor and sum them to come up with the preferred bitpool.
- * This is not ideal because 0 requires 0 bits but we currently have no way of knowing this.
- *
- * @param bitneed       Array to return bitneeds for each subband
- *
- * @param ch            Channel 0 or 1
- *
- * @param preferredBitpool  Returns the number of reserved bits
- *
- * @return              The SBC bit need
- *
- */
-OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                       OI_UINT8 *bitneeds,
-                       OI_UINT ch,
-                       OI_UINT *preferredBitpool)
-{
-    static const OI_INT8 offset4[4][4] = {
-        { -1, 0, 0, 0 },
-        { -2, 0, 0, 1 },
-        { -2, 0, 0, 1 },
-        { -2, 0, 0, 1 }
-    };
-
-    static const OI_INT8 offset8[4][8] = {
-        { -2, 0, 0, 0, 0, 0, 0, 1 },
-        { -3, 0, 0, 0, 0, 0, 1, 2 },
-        { -4, 0, 0, 0, 0, 0, 1, 2 },
-        { -4, 0, 0, 0, 0, 0, 1, 2 }
-    };
-
-    const OI_UINT nrof_subbands = common->frameInfo.nrof_subbands;
-    OI_UINT sb;
-    OI_INT8 *scale_factor = &common->scale_factor[ch ? nrof_subbands : 0];
-    OI_UINT bitcount = 0;
-    OI_UINT8 maxBits = 0;
-    OI_UINT8 prefBits = 0;
-
-    if (common->frameInfo.alloc == SBC_SNR) {
-        for (sb = 0; sb < nrof_subbands; sb++) {
-            OI_INT bits = scale_factor[sb];
-            if (bits > maxBits) {
-                maxBits = bits;
-            }
-            if ((bitneeds[sb] = bits) > 1) {
-                bitcount += bits;
-            }
-            prefBits += 2 + bits;
-        }
-    } else {
-        const OI_INT8 *offset;
-        if (nrof_subbands == 4) {
-            offset = offset4[common->frameInfo.freqIndex];
-        } else {
-            offset = offset8[common->frameInfo.freqIndex];
-        }
-        for (sb = 0; sb < nrof_subbands; sb++) {
-            OI_INT bits = scale_factor[sb];
-            if (bits > maxBits) {
-                maxBits = bits;
-            }
-            prefBits += 2 + bits;
-            if (bits) {
-                bits -= offset[sb];
-                if (bits > 0) {
-                    bits /= 2;
-                }
-                bits += 5;
-            }
-            if ((bitneeds[sb] = bits) > 1) {
-                bitcount += bits;
-            }
-        }
-    }
-    common->maxBitneed = OI_MAX(maxBits, common->maxBitneed);
-    *preferredBitpool += prefBits;
-    return bitcount;
-}
-
-/*
- * Explanation of the adjustToFitBitpool inner loop.
- *
- * The inner loop computes the effect of adjusting the bit allocation up or
- * down. Allocations must be 0 or in the range 2..16. This is accomplished by
- * the following code:
- *
- *           for (s = bands - 1; s >= 0; --s) {
- *              OI_INT bits = bitadjust + bitneeds[s];
- *              bits = bits < 2 ? 0 : bits;
- *              bits = bits > 16 ? 16 : bits;
- *              count += bits;
- *          }
- *
- * This loop can be optimized to perform 4 operations at a time as follows:
- *
- * Adjustment is computed as a 7 bit signed value and added to the bitneed.
- *
- * Negative allocations are zeroed by masking. (n & 0x40) >> 6 puts the
- * sign bit into bit 0, adding this to 0x7F give us a mask of 0x80
- * for -ve values and 0x7F for +ve values.
- *
- * n &= 0x7F + (n & 0x40) >> 6)
- *
- * Allocations greater than 16 are truncated to 16. Adjusted allocations are in
- * the range 0..31 so we know that bit 4 indicates values >= 16. We use this bit
- * to create a mask that zeroes bits 0 .. 3 if bit 4 is set.
- *
- * n &= (15 + (n >> 4))
- *
- * Allocations of 1 are disallowed. Add and shift creates a mask that
- * eliminates the illegal value
- *
- * n &= ((n + 14) >> 4) | 0x1E
- *
- * These operations can be performed in 8 bits without overflowing so we can
- * operate on 4 values at once.
- */
-
-/*
- * Encoder/Decoder
- *
- * Computes adjustment +/- of bitneeds to fill bitpool and returns overall
- * adjustment and excess bits.
- *
- * @param bitpool   The bitpool we have to work within
- *
- * @param bitneeds  An array of bit needs (more acturately allocation prioritities) for each
- *                  subband across all blocks in the SBC frame
- *
- * @param subbands  The number of subbands over which the adkustment is calculated. For mono and
- *                  dual mode this is 4 or 8, for stereo or joint stereo this is 8 or 16.
- *
- * @param bitcount  A starting point for the adjustment
- *
- * @param excess    Returns the excess bits after the adjustment
- *
- * @return   The adjustment.
- */
-OI_INT adjustToFitBitpool(const OI_UINT bitpool,
-                          OI_UINT32 *bitneeds,
-                          const OI_UINT subbands,
-                          OI_UINT bitcount,
-                          OI_UINT *excess)
-{
-    OI_INT maxBitadjust = 0;
-    OI_INT bitadjust = (bitcount > bitpool) ? -8 : 8;
-    OI_INT chop = 8;
-
-    /*
-     * This is essentially a binary search for the optimal adjustment value.
-     */
-    while ((bitcount != bitpool) && chop) {
-        OI_UINT32 total = 0;
-        OI_UINT count;
-        OI_UINT32 adjust4;
-        OI_INT i;
-
-        adjust4 = bitadjust & 0x7F;
-        adjust4 |= (adjust4 << 8);
-        adjust4 |= (adjust4 << 16);
-
-        for (i = (subbands / 4 - 1); i >= 0; --i) {
-            OI_UINT32 mask;
-            OI_UINT32 n = bitneeds[i] + adjust4;
-            mask = 0x7F7F7F7F + ((n & 0x40404040) >> 6);
-            n &= mask;
-            mask = 0x0F0F0F0F + ((n & 0x10101010) >> 4);
-            n &= mask;
-            mask = (((n + 0x0E0E0E0E) >> 4) | 0x1E1E1E1E);
-            n &= mask;
-            total += n;
-        }
-
-        count = (total & 0xFFFF) + (total >> 16);
-        count = (count & 0xFF) + (count >> 8);
-
-        chop >>= 1;
-        if (count > bitpool) {
-            bitadjust -= chop;
-        } else {
-            maxBitadjust = bitadjust;
-            bitcount = count;
-            bitadjust += chop;
-        }
-    }
-
-    *excess = bitpool - bitcount;
-
-    return maxBitadjust;
-}
-
-/*
- * The bit allocator trys to avoid single bit allocations except as a last resort. So in the case
- * where a bitneed of 1 was passed over during the adsjustment phase 2 bits are now allocated.
- */
-INLINE OI_INT allocAdjustedBits(OI_UINT8 *dest,
-                                OI_INT bits,
-                                OI_INT excess)
-{
-    if (bits < 16) {
-        if (bits > 1) {
-            if (excess) {
-                ++bits;
-                --excess;
-            }
-        } else if ((bits == 1) && (excess > 1)) {
-            bits = 2;
-            excess -= 2;
-        } else {
-            bits = 0;
-        }
-    } else {
-        bits = 16;
-    }
-    *dest = (OI_UINT8)bits;
-    return excess;
-}
-
-/*
- * Excess bits not allocated by allocaAdjustedBits are allocated round-robin.
- */
-INLINE OI_INT allocExcessBits(OI_UINT8 *dest,
-                              OI_INT excess)
-{
-    if (*dest < 16) {
-        *dest += 1;
-        return excess - 1;
-    } else {
-        return excess;
-    }
-}
-
-void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                             BITNEED_UNION1 *bitneeds,
-                             OI_UINT ch,
-                             OI_UINT bitcount)
-{
-    const OI_UINT8 nrof_subbands = common->frameInfo.nrof_subbands;
-    OI_UINT excess;
-    OI_UINT sb;
-    OI_INT bitadjust;
-    OI_UINT8 RESTRICT *allocBits;
-
-    {
-        OI_UINT ex;
-        bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds->uint32, nrof_subbands, bitcount, &ex);
-        /* We want the compiler to put excess into a register */
-        excess = ex;
-    }
-
-    /*
-     * Allocate adjusted bits
-     */
-    allocBits = &common->bits.uint8[ch ? nrof_subbands : 0];
-
-    sb = 0;
-    while (sb < nrof_subbands) {
-        excess = allocAdjustedBits(&allocBits[sb], bitneeds->uint8[sb] + bitadjust, excess);
-        ++sb;
-    }
-    sb = 0;
-    while (excess) {
-        excess = allocExcessBits(&allocBits[sb], excess);
-        ++sb;
-    }
-}
-
-void monoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common)
-{
-    BITNEED_UNION1 bitneeds;
-    OI_UINT bitcount;
-    OI_UINT bitpoolPreference = 0;
-
-    bitcount = computeBitneed(common, bitneeds.uint8, 0, &bitpoolPreference);
-
-    oneChannelBitAllocation(common, &bitneeds, 0, bitcount);
-}
-
-/**
-@}
-*/
-
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitstream-decode.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitstream-decode.c
deleted file mode 100644
index da20e3149..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/bitstream-decode.c
+++ /dev/null
@@ -1,94 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/**
-@file
-Functions for manipulating input bitstreams.
-
-@ingroup codec_internal
-*/
-
-/**
-@addtogroup codec_internal
-@{
-*/
-
-#include "oi_stddefs.h"
-#include "oi_bitstream.h"
-#include "oi_assert.h"
-
-#if defined(SBC_DEC_INCLUDED)
-
-PRIVATE void OI_BITSTREAM_ReadInit(OI_BITSTREAM *bs,
-                                   const OI_BYTE *buffer)
-{
-    bs->value = ((OI_INT32)buffer[0] << 16) | ((OI_INT32)buffer[1] << 8) | (buffer[2]);
-    bs->ptr.r = buffer + 3;
-    bs->bitPtr = 8;
-}
-
-PRIVATE OI_UINT32 OI_BITSTREAM_ReadUINT(OI_BITSTREAM *bs, OI_UINT bits)
-{
-    OI_UINT32 result;
-
-    OI_BITSTREAM_READUINT(result, bits, bs->ptr.r, bs->value, bs->bitPtr);
-
-    return result;
-}
-
-PRIVATE OI_UINT8 OI_BITSTREAM_ReadUINT4Aligned(OI_BITSTREAM *bs)
-{
-    OI_UINT32 result;
-
-    OI_ASSERT(bs->bitPtr < 16);
-    OI_ASSERT(bs->bitPtr % 4 == 0);
-
-    if (bs->bitPtr == 8) {
-        result = bs->value << 8;
-        bs->bitPtr = 12;
-    } else {
-        result = bs->value << 12;
-        bs->value = (bs->value << 8) | *bs->ptr.r++;
-        bs->bitPtr = 8;
-    }
-    result >>= 28;
-    OI_ASSERT(result < (1u << 4));
-    return (OI_UINT8)result;
-}
-
-PRIVATE OI_UINT8 OI_BITSTREAM_ReadUINT8Aligned(OI_BITSTREAM *bs)
-{
-    OI_UINT32 result;
-    OI_ASSERT(bs->bitPtr == 8);
-
-    result = bs->value >> 16;
-    bs->value = (bs->value << 8) | *bs->ptr.r++;
-
-    return (OI_UINT8)result;
-}
-
-/**
-@}
-*/
-
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-oina.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-oina.c
deleted file mode 100644
index bc57ead00..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-oina.c
+++ /dev/null
@@ -1,137 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2006 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
- ***********************************************************************************/
-
-/**
-@file
-This file exposes OINA-specific interfaces to decoder functions.
-
-@ingroup codec_internal
-*/
-
-/**
-@addtogroup codec_internal
-@{
-*/
-
-#include 
-
-#if defined(SBC_DEC_INCLUDED)
-
-OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                           OI_BOOL enhanced,
-                                           OI_UINT8 frequency,
-                                           OI_UINT8 mode,
-                                           OI_UINT8 subbands,
-                                           OI_UINT8 blocks,
-                                           OI_UINT8 alloc,
-                                           OI_UINT8 maxBitpool)
-{
-    if (frequency > SBC_FREQ_48000) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    if (enhanced) {
-#ifdef SBC_ENHANCED
-        if (subbands != SBC_SUBBANDS_8) {
-            return OI_STATUS_INVALID_PARAMETERS;
-        }
-#else
-        return OI_STATUS_INVALID_PARAMETERS;
-#endif
-    }
-
-    if (mode > SBC_JOINT_STEREO) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    if (subbands > SBC_SUBBANDS_8) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    if (blocks > SBC_BLOCKS_16) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    if (alloc > SBC_SNR) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-#ifdef SBC_ENHANCED
-    context->common.frameInfo.enhanced = enhanced;
-#else
-    context->common.frameInfo.enhanced = FALSE;
-#endif
-    context->common.frameInfo.freqIndex = frequency;
-    context->common.frameInfo.mode = mode;
-    context->common.frameInfo.subbands = subbands;
-    context->common.frameInfo.blocks = blocks;
-    context->common.frameInfo.alloc = alloc;
-    context->common.frameInfo.bitpool = maxBitpool;
-
-    OI_SBC_ExpandFrameFields(&context->common.frameInfo);
-
-    if (context->common.frameInfo.nrof_channels >= context->common.pcmStride) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    return OI_OK;
-}
-
-OI_STATUS OI_CODEC_SBC_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                 OI_UINT8 bitpool,
-                                 const OI_BYTE **frameData,
-                                 OI_UINT32 *frameBytes,
-                                 OI_INT16 *pcmData,
-                                 OI_UINT32 *pcmBytes)
-{
-    return internal_DecodeRaw(context,
-                              bitpool,
-                              frameData,
-                              frameBytes,
-                              pcmData,
-                              pcmBytes);
-}
-
-OI_STATUS OI_CODEC_SBC_DecoderLimit(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                    OI_BOOL enhanced,
-                                    OI_UINT8 subbands)
-{
-    if (enhanced) {
-#ifdef SBC_ENHANCED
-        context->enhancedEnabled = TRUE;
-#else
-        context->enhancedEnabled = FALSE;
-#endif
-    } else {
-        context->enhancedEnabled = FALSE;
-    }
-    context->restrictSubbands = subbands;
-    context->limitFrameFormat = TRUE;
-    return OI_OK;
-}
-
-/**
-@}
-*/
-
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-private.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-private.c
deleted file mode 100644
index 0c7ff1256..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-private.c
+++ /dev/null
@@ -1,254 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
- ***********************************************************************************/
-
-/**
-@file
-This file drives SBC decoding.
-
-@ingroup codec_internal
-*/
-
-/**
-@addtogroup codec_internal
-@{
-*/
-
-#include "oi_codec_sbc_private.h"
-#include "oi_bitstream.h"
-#include 
-
-#if defined(SBC_DEC_INCLUDED)
-
-OI_CHAR *const OI_Codec_Copyright = "Copyright 2002-2007 Open Interface North America, Inc. All rights reserved";
-
-INLINE OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                       OI_UINT32 *decoderData,
-                                       OI_UINT32 decoderDataBytes,
-                                       OI_BYTE maxChannels,
-                                       OI_BYTE pcmStride,
-                                       OI_BOOL enhanced,
-                                       OI_BOOL msbc_enable)
-{
-    OI_UINT i;
-    OI_STATUS status;
-
-    for (i = 0; i < sizeof(*context); i++) {
-        ((char *)context)[i] = 0;
-    }
-
-#ifdef SBC_ENHANCED
-    context->enhancedEnabled = enhanced ? TRUE : FALSE;
-#else
-    context->enhancedEnabled = FALSE;
-    if (enhanced) {
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-#endif
-
-    if (msbc_enable) {
-        context->sbc_mode = OI_SBC_MODE_MSBC;
-    } else {
-        context->sbc_mode = OI_SBC_MODE_STD;
-    }
-
-    status = OI_CODEC_SBC_Alloc(&context->common, decoderData, decoderDataBytes, maxChannels, pcmStride);
-
-    if (!OI_SUCCESS(status)) {
-        return status;
-    }
-
-    context->common.codecInfo = OI_Codec_Copyright;
-    context->common.maxBitneed = 0;
-    context->limitFrameFormat = FALSE;
-    OI_SBC_ExpandFrameFields(&context->common.frameInfo);
-
-    /*PLATFORM_DECODER_RESET(context);*/
-
-    return OI_OK;
-}
-
-/**
- * Read the SBC header up to but not including the joint stereo mask.  The syncword has already been
- * examined, and the enhanced mode flag set, by FindSyncword.
- */
-INLINE void OI_SBC_ReadHeader(OI_CODEC_SBC_COMMON_CONTEXT *common, const OI_BYTE *data)
-{
-    OI_CODEC_SBC_FRAME_INFO *frame = &common->frameInfo;
-    OI_UINT8 d1;
-
-    OI_ASSERT(data[0] == OI_SBC_SYNCWORD || data[0] == OI_SBC_ENHANCED_SYNCWORD || data[0] == OI_mSBC_SYNCWORD);
-
-    /**
-     * For mSBC, just set those parameters
-     */
-    if (data[0] == OI_mSBC_SYNCWORD) {
-        frame->freqIndex = 0;
-        frame->frequency = 16000;
-
-        frame->blocks = 4;
-        frame->nrof_blocks = 15;
-
-        frame->mode = 0;
-        frame->nrof_channels = 1;
-
-        frame->alloc = SBC_LOUDNESS;
-
-        frame->subbands = 1;
-        frame->nrof_subbands = 8;
-
-        frame->cachedInfo = 0;
-
-        frame->bitpool = 26;
-        frame->crc = data[3];
-        return;
-    }
-
-    /* Avoid filling out all these strucutures if we already remember the values
-     * from last time. Just in case we get a stream corresponding to data[1] ==
-     * 0, DecoderReset is responsible for ensuring the lookup table entries have
-     * already been populated
-     */
-    d1 = data[1];
-    if (d1 != frame->cachedInfo) {
-        frame->freqIndex = (d1 & (BIT7 | BIT6)) >> 6;
-        frame->frequency = freq_values[frame->freqIndex];
-
-        frame->blocks = (d1 & (BIT5 | BIT4)) >> 4;
-        frame->nrof_blocks = block_values[frame->blocks];
-
-        frame->mode = (d1 & (BIT3 | BIT2)) >> 2;
-        frame->nrof_channels = channel_values[frame->mode];
-
-        frame->alloc = (d1 & BIT1) >> 1;
-
-        frame->subbands = (d1 & BIT0);
-        frame->nrof_subbands = band_values[frame->subbands];
-
-        frame->cachedInfo = d1;
-    }
-    /*
-     * For decode, the bit allocator needs to know the bitpool value
-     */
-    frame->bitpool = data[2];
-    frame->crc = data[3];
-}
-
-#define LOW(x)  ((x)&0xf)
-#define HIGH(x) ((x) >> 4)
-
-/*
- * Read scalefactor values and prepare the bitstream for OI_SBC_ReadSamples
- */
-PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                                     const OI_BYTE *b,
-                                     OI_BITSTREAM *bs)
-{
-    OI_UINT i = common->frameInfo.nrof_subbands * common->frameInfo.nrof_channels;
-    OI_INT8 *scale_factor = common->scale_factor;
-    OI_UINT f;
-
-    if (common->frameInfo.nrof_subbands == 8 || common->frameInfo.mode != SBC_JOINT_STEREO) {
-        if (common->frameInfo.mode == SBC_JOINT_STEREO) {
-            common->frameInfo.join = *b++;
-        } else {
-            common->frameInfo.join = 0;
-        }
-        i /= 2;
-        do {
-            *scale_factor++ = HIGH(f = *b++);
-            *scale_factor++ = LOW(f);
-        } while (--i);
-        /*
-         * In this case we know that the scale factors end on a byte boundary so all we need to do
-         * is initialize the bitstream.
-         */
-        OI_BITSTREAM_ReadInit(bs, b);
-    } else {
-        OI_ASSERT(common->frameInfo.nrof_subbands == 4 && common->frameInfo.mode == SBC_JOINT_STEREO);
-        common->frameInfo.join = HIGH(f = *b++);
-        i = (i - 1) / 2;
-        do {
-            *scale_factor++ = LOW(f);
-            *scale_factor++ = HIGH(f = *b++);
-        } while (--i);
-        *scale_factor++ = LOW(f);
-        /*
-         * In 4-subband joint stereo mode, the joint stereo information ends on a half-byte
-         * boundary, so it's necessary to use the bitstream abstraction to read it, since
-         * OI_SBC_ReadSamples will need to pick up in mid-byte.
-         */
-        OI_BITSTREAM_ReadInit(bs, b);
-        *scale_factor++ = OI_BITSTREAM_ReadUINT4Aligned(bs);
-    }
-}
-
-/** Read quantized subband samples from the input bitstream and expand them. */
-PRIVATE void OI_SBC_ReadSamples(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs)
-{
-    OI_CODEC_SBC_COMMON_CONTEXT *common = &context->common;
-    OI_UINT nrof_blocks = common->frameInfo.nrof_blocks;
-    OI_INT32 *RESTRICT s = common->subdata;
-    OI_UINT8 *ptr = global_bs->ptr.w;
-    OI_UINT32 value = global_bs->value;
-    OI_UINT bitPtr = global_bs->bitPtr;
-
-    const OI_UINT iter_count = common->frameInfo.nrof_channels * common->frameInfo.nrof_subbands / 4;
-    do {
-        OI_UINT i;
-        for (i = 0; i < iter_count; ++i) {
-            OI_UINT32 sf_by4 = ((OI_UINT32 *)common->scale_factor)[i];
-            OI_UINT32 bits_by4 = common->bits.uint32[i];
-            OI_UINT n;
-            for (n = 0; n < 4; ++n) {
-                OI_INT32 dequant;
-                OI_UINT bits;
-                OI_INT sf;
-
-                if (OI_CPU_BYTE_ORDER == OI_LITTLE_ENDIAN_BYTE_ORDER) {
-                    bits = bits_by4 & 0xFF;
-                    bits_by4 >>= 8;
-                    sf = sf_by4 & 0xFF;
-                    sf_by4 >>= 8;
-                } else {
-                    bits = (bits_by4 >> 24) & 0xFF;
-                    bits_by4 <<= 8;
-                    sf = (sf_by4 >> 24) & 0xFF;
-                    sf_by4 <<= 8;
-                }
-                if (bits) {
-                    OI_UINT32 raw;
-                    OI_BITSTREAM_READUINT(raw, bits, ptr, value, bitPtr);
-                    dequant = OI_SBC_Dequant(raw, sf, bits);
-                } else {
-                    dequant = 0;
-                }
-                *s++ = dequant;
-            }
-        }
-    } while (--nrof_blocks);
-}
-
-/**
-@}
-*/
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-sbc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-sbc.c
deleted file mode 100644
index ee3c45131..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/decoder-sbc.c
+++ /dev/null
@@ -1,468 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2006 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
- ***********************************************************************************/
-
-/** @file
-@ingroup codec_internal
-*/
-
-/**@addtogroup codec_internal */
-/**@{*/
-
-#include "oi_codec_sbc_private.h"
-#include "oi_bitstream.h"
-
-#if defined(SBC_DEC_INCLUDED)
-
-#define SPECIALIZE_READ_SAMPLES_JOINT
-
-/**
- * Scans through a buffer looking for a codec syncword. If the decoder has been
- * set for enhanced operation using OI_CODEC_SBC_DecoderReset(), it will search
- * for both a standard and an enhanced syncword.
- */
-PRIVATE OI_STATUS FindSyncword(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                               const OI_BYTE **frameData,
-                               OI_UINT32 *frameBytes)
-{
-#ifdef SBC_ENHANCED
-    OI_BYTE search1 = OI_SBC_SYNCWORD;
-    OI_BYTE search2 = OI_SBC_ENHANCED_SYNCWORD;
-#endif // SBC_ENHANCED
-
-    if (*frameBytes == 0) {
-        return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
-    }
-
-#ifdef SBC_ENHANCED
-    if (context->limitFrameFormat && context->enhancedEnabled) {
-        /* If the context is restricted, only search for specified SYNCWORD */
-        search1 = search2;
-    } else if (context->enhancedEnabled == FALSE) {
-        /* If enhanced is not enabled, only search for classic SBC SYNCWORD*/
-        search2 = search1;
-    }
-    while (*frameBytes && (**frameData != search1) && (**frameData != search2)) {
-        (*frameBytes)--;
-        (*frameData)++;
-    }
-    if (*frameBytes) {
-        /* Syncword found, *frameData points to it, and *frameBytes correctly
-         * reflects the number of bytes available to read, including the
-         * syncword. */
-        context->common.frameInfo.enhanced = (**frameData == OI_SBC_ENHANCED_SYNCWORD);
-        return OI_OK;
-    } else {
-        /* No syncword was found anywhere in the provided input data.
-         * *frameData points past the end of the original input, and
-         * *frameBytes is 0. */
-        return OI_CODEC_SBC_NO_SYNCWORD;
-    }
-#else  // SBC_ENHANCED
-    while (*frameBytes && (!(context->sbc_mode == OI_SBC_MODE_STD && **frameData == OI_SBC_SYNCWORD)) && (!(context->sbc_mode == OI_SBC_MODE_MSBC && **frameData == OI_mSBC_SYNCWORD))) {
-        (*frameBytes)--;
-        (*frameData)++;
-    }
-    if (*frameBytes) {
-        /* Syncword found, *frameData points to it, and *frameBytes correctly
-         * reflects the number of bytes available to read, including the
-         * syncword. */
-        context->common.frameInfo.enhanced = FALSE;
-        return OI_OK;
-    } else {
-        /* No syncword was found anywhere in the provided input data.
-         * *frameData points past the end of the original input, and
-         * *frameBytes is 0. */
-        return OI_CODEC_SBC_NO_SYNCWORD;
-    }
-#endif // SBC_ENHANCED
-}
-
-static OI_STATUS DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                            const OI_BYTE *bodyData,
-                            OI_INT16 *pcmData,
-                            OI_UINT32 *pcmBytes,
-                            OI_BOOL allowPartial)
-{
-    OI_BITSTREAM bs;
-    OI_UINT frameSamples = context->common.frameInfo.nrof_blocks * context->common.frameInfo.nrof_subbands;
-    OI_UINT decode_block_count;
-
-    /*
-     * Based on the header data, make sure that there is enough room to write the output samples.
-     */
-    if (*pcmBytes < (sizeof(OI_INT16) * frameSamples * context->common.pcmStride) && !allowPartial) {
-        /* If we're not allowing partial decodes, we need room for the entire
-         * codec frame */
-        TRACE(("-OI_CODEC_SBC_Decode: OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA"));
-        return OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA;
-    } else if (*pcmBytes < sizeof(OI_INT16) * context->common.frameInfo.nrof_subbands * context->common.pcmStride) {
-        /* Even if we're allowing partials, we can still only decode on a frame
-         * boundary */
-        return OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA;
-    }
-
-    if (context->bufferedBlocks == 0) {
-        TRACE(("Reading scalefactors"));
-        OI_SBC_ReadScalefactors(&context->common, bodyData, &bs);
-
-        TRACE(("Computing bit allocation"));
-        OI_SBC_ComputeBitAllocation(&context->common);
-
-        TRACE(("Reading samples"));
-        if (context->common.frameInfo.mode == SBC_JOINT_STEREO) {
-            OI_SBC_ReadSamplesJoint(context, &bs);
-        } else {
-            OI_SBC_ReadSamples(context, &bs);
-        }
-
-        context->bufferedBlocks = context->common.frameInfo.nrof_blocks;
-    }
-
-    if (allowPartial) {
-        decode_block_count = *pcmBytes / sizeof(OI_INT16) / context->common.pcmStride / context->common.frameInfo.nrof_subbands;
-
-        if (decode_block_count > context->bufferedBlocks) {
-            decode_block_count = context->bufferedBlocks;
-        }
-
-    } else {
-        decode_block_count = context->common.frameInfo.nrof_blocks;
-    }
-
-    TRACE(("Synthesizing frame"));
-    {
-        OI_UINT start_block = context->common.frameInfo.nrof_blocks - context->bufferedBlocks;
-        OI_SBC_SynthFrame(context, pcmData, start_block, decode_block_count);
-    }
-
-    OI_ASSERT(context->bufferedBlocks >= decode_block_count);
-    context->bufferedBlocks -= decode_block_count;
-
-    frameSamples = decode_block_count * context->common.frameInfo.nrof_subbands;
-
-    /*
-     * When decoding mono into a stride-2 array, copy pcm data to second channel
-     */
-    if (context->common.frameInfo.nrof_channels == 1 && context->common.pcmStride == 2) {
-        OI_UINT i;
-        for (i = 0; i < frameSamples; ++i) {
-            pcmData[2 * i + 1] = pcmData[2 * i];
-        }
-    }
-
-    /*
-     * Return number of pcm bytes generated by the decode operation.
-     */
-    *pcmBytes = frameSamples * sizeof(OI_INT16) * context->common.pcmStride;
-    if (context->bufferedBlocks > 0) {
-        return OI_CODEC_SBC_PARTIAL_DECODE;
-    } else {
-        return OI_OK;
-    }
-}
-
-PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                     OI_UINT8 bitpool,
-                                     const OI_BYTE **frameData,
-                                     OI_UINT32 *frameBytes,
-                                     OI_INT16 *pcmData,
-                                     OI_UINT32 *pcmBytes)
-{
-    OI_STATUS status;
-    OI_UINT bodyLen;
-
-    TRACE(("+OI_CODEC_SBC_DecodeRaw"));
-
-    if (context->bufferedBlocks == 0) {
-        /*
-         * The bitallocator needs to know the bitpool value.
-         */
-        context->common.frameInfo.bitpool = bitpool;
-        /*
-         * Compute the frame length and check we have enough frame data to proceed
-         */
-        bodyLen = OI_CODEC_SBC_CalculateFramelen(&context->common.frameInfo) - SBC_HEADER_LEN;
-        if (*frameBytes < bodyLen) {
-            TRACE(("-OI_CODEC_SBC_Decode: OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA"));
-            return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
-        }
-    } else {
-        bodyLen = 0;
-    }
-    /*
-     * Decode the SBC data. Pass TRUE to DecodeBody to allow partial decoding of
-     * tones.
-     */
-    status = DecodeBody(context, *frameData, pcmData, pcmBytes, TRUE);
-    if (OI_SUCCESS(status) || status == OI_CODEC_SBC_PARTIAL_DECODE) {
-        *frameData += bodyLen;
-        *frameBytes -= bodyLen;
-    }
-    TRACE(("-OI_CODEC_SBC_DecodeRaw: %d", status));
-    return status;
-}
-
-OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                    OI_UINT32 *decoderData,
-                                    OI_UINT32 decoderDataBytes,
-                                    OI_UINT8 maxChannels,
-                                    OI_UINT8 pcmStride,
-                                    OI_BOOL enhanced,
-                                    OI_BOOL msbc_enable)
-{
-    return internal_DecoderReset(context, decoderData, decoderDataBytes, maxChannels, pcmStride, enhanced, msbc_enable);
-}
-
-OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                   const OI_BYTE **frameData,
-                                   OI_UINT32 *frameBytes,
-                                   OI_INT16 *pcmData,
-                                   OI_UINT32 *pcmBytes)
-{
-    OI_STATUS status;
-    OI_UINT framelen;
-    OI_UINT8 crc;
-
-    TRACE(("+OI_CODEC_SBC_DecodeFrame"));
-
-    TRACE(("Finding syncword"));
-    status = FindSyncword(context, frameData, frameBytes);
-    if (!OI_SUCCESS(status)) {
-        return status;
-    }
-
-    /* Make sure enough data remains to read the header. */
-    if (*frameBytes < SBC_HEADER_LEN) {
-        TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA"));
-        return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
-    }
-
-    TRACE(("Reading Header"));
-    OI_SBC_ReadHeader(&context->common, *frameData);
-
-    /*
-     * Some implementations load the decoder into RAM and use overlays for 4 vs 8 subbands. We need
-     * to ensure that the SBC parameters for this frame are compatible with the restrictions imposed
-     * by the loaded overlays.
-     */
-    if (context->limitFrameFormat && (context->common.frameInfo.subbands != context->restrictSubbands)) {
-        ERROR(("SBC parameters incompatible with loaded overlay"));
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    if (context->common.frameInfo.nrof_channels > context->common.maxChannels) {
-        ERROR(("SBC parameters incompatible with number of channels specified during reset"));
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    if (context->common.pcmStride < 1 || context->common.pcmStride > 2) {
-        ERROR(("PCM stride not set correctly during reset"));
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-
-    /*
-     * At this point a header has been read. However, it's possible that we found a false syncword,
-     * so the header data might be invalid. Make sure we have enough bytes to read in the
-     * CRC-protected header, but don't require we have the whole frame. That way, if it turns out
-     * that we're acting on bogus header data, we don't stall the decoding process by waiting for
-     * data that we don't actually need.
-     */
-    framelen = OI_CODEC_SBC_CalculateFramelen(&context->common.frameInfo);
-    if (*frameBytes < framelen) {
-        TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA"));
-        return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
-    }
-
-    TRACE(("Calculating checksum"));
-
-    crc = OI_SBC_CalculateChecksum(&context->common.frameInfo, *frameData);
-    if (crc != context->common.frameInfo.crc) {
-        TRACE(("CRC Mismatch:  calc=%02x read=%02x\n", crc, context->common.frameInfo.crc));
-        TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_CHECKSUM_MISMATCH"));
-        return OI_CODEC_SBC_CHECKSUM_MISMATCH;
-    }
-
-#ifdef OI_DEBUG
-    /*
-     * Make sure the bitpool values are sane.
-     */
-    if ((context->common.frameInfo.bitpool < SBC_MIN_BITPOOL) && !context->common.frameInfo.enhanced) {
-        ERROR(("Bitpool too small: %d (must be >= 2)", context->common.frameInfo.bitpool));
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-    if (context->common.frameInfo.bitpool > OI_SBC_MaxBitpool(&context->common.frameInfo)) {
-        ERROR(("Bitpool too large: %d (must be <= %ld)", context->common.frameInfo.bitpool, OI_SBC_MaxBitpool(&context->common.frameInfo)));
-        return OI_STATUS_INVALID_PARAMETERS;
-    }
-#endif
-
-    /*
-     * Now decode the SBC data. Partial decode is not yet implemented for an SBC
-     * stream, so pass FALSE to decode body to have it enforce the old rule that
-     * you have to decode a whole packet at a time.
-     */
-    status = DecodeBody(context, *frameData + SBC_HEADER_LEN, pcmData, pcmBytes, FALSE);
-    if (OI_SUCCESS(status)) {
-        *frameData += framelen;
-        *frameBytes -= framelen;
-    }
-    TRACE(("-OI_CODEC_SBC_DecodeFrame: %d", status));
-
-    return status;
-}
-
-OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                 const OI_BYTE **frameData,
-                                 OI_UINT32 *frameBytes)
-{
-    OI_STATUS status;
-    OI_UINT framelen;
-    OI_UINT headerlen;
-    OI_UINT8 crc;
-
-    status = FindSyncword(context, frameData, frameBytes);
-    if (!OI_SUCCESS(status)) {
-        return status;
-    }
-    if (*frameBytes < SBC_HEADER_LEN) {
-        return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
-    }
-    OI_SBC_ReadHeader(&context->common, *frameData);
-    framelen = OI_SBC_CalculateFrameAndHeaderlen(&context->common.frameInfo, &headerlen);
-    if (*frameBytes < headerlen) {
-        return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA;
-    }
-    crc = OI_SBC_CalculateChecksum(&context->common.frameInfo, *frameData);
-    if (crc != context->common.frameInfo.crc) {
-        return OI_CODEC_SBC_CHECKSUM_MISMATCH;
-    }
-    if (*frameBytes < framelen) {
-        return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA;
-    }
-    context->bufferedBlocks = 0;
-    *frameData += framelen;
-    *frameBytes -= framelen;
-    return OI_OK;
-}
-
-OI_UINT8 OI_CODEC_SBC_FrameCount(OI_BYTE *frameData,
-                                 OI_UINT32 frameBytes)
-{
-    OI_UINT8 mode;
-    OI_UINT8 blocks;
-    OI_UINT8 subbands;
-    OI_UINT8 frameCount = 0;
-    OI_UINT frameLen;
-
-    while (frameBytes) {
-        while (frameBytes && ((frameData[0] & 0xFE) != 0x9C)) {
-            frameData++;
-            frameBytes--;
-        }
-
-        if (frameBytes < SBC_HEADER_LEN) {
-            return frameCount;
-        }
-
-        /* Extract and translate required fields from Header */
-        subbands = mode = blocks = frameData[1];
-        ;
-        mode = (mode & (BIT3 | BIT2)) >> 2;
-        blocks = block_values[(blocks & (BIT5 | BIT4)) >> 4];
-        subbands = band_values[(subbands & BIT0)];
-
-        /* Inline logic to avoid corrupting context */
-        frameLen = blocks * frameData[2];
-        switch (mode) {
-            case SBC_JOINT_STEREO:
-                frameLen += subbands + (8 * subbands);
-                break;
-
-            case SBC_DUAL_CHANNEL:
-                frameLen *= 2;
-                /* fall through */
-
-            default:
-                if (mode == SBC_MONO) {
-                    frameLen += 4 * subbands;
-                } else {
-                    frameLen += 8 * subbands;
-                }
-        }
-
-        frameCount++;
-        frameLen = SBC_HEADER_LEN + (frameLen + 7) / 8;
-        if (frameBytes > frameLen) {
-            frameBytes -= frameLen;
-            frameData += frameLen;
-        } else {
-            frameBytes = 0;
-        }
-    }
-    return frameCount;
-}
-
-/** Read quantized subband samples from the input bitstream and expand them. */
-
-#ifdef SPECIALIZE_READ_SAMPLES_JOINT
-
-PRIVATE void OI_SBC_ReadSamplesJoint4(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs){
-#define NROF_SUBBANDS 4
-#include "readsamplesjoint.inc"
-#undef NROF_SUBBANDS
-}
-
-PRIVATE void OI_SBC_ReadSamplesJoint8(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs)
-{
-#define NROF_SUBBANDS 8
-#include "readsamplesjoint.inc"
-#undef NROF_SUBBANDS
-}
-
-typedef void (*READ_SAMPLES)(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs);
-
-static const READ_SAMPLES SpecializedReadSamples[] = {
-    OI_SBC_ReadSamplesJoint4,
-    OI_SBC_ReadSamplesJoint8
-};
-
-#endif /* SPECIALIZE_READ_SAMPLES_JOINT */
-
-PRIVATE void OI_SBC_ReadSamplesJoint(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_BITSTREAM *global_bs)
-{
-    OI_CODEC_SBC_COMMON_CONTEXT *common = &context->common;
-    OI_UINT nrof_subbands = common->frameInfo.nrof_subbands;
-#ifdef SPECIALIZE_READ_SAMPLES_JOINT
-    OI_ASSERT((nrof_subbands >> 3u) <= 1u);
-    SpecializedReadSamples[nrof_subbands >> 3](context, global_bs);
-#else
-
-#define NROF_SUBBANDS nrof_subbands
-#include "readsamplesjoint.inc"
-#undef NROF_SUBBANDS
-#endif /* SPECIALIZE_READ_SAMPLES_JOINT */
-}
-
-/**@}*/
-
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/dequant.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/dequant.c
deleted file mode 100644
index a134d45e7..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/dequant.c
+++ /dev/null
@@ -1,211 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/**
- @file
-
- Dequantizer for SBC decoder; reconstructs quantized representation of subband samples.
-
- @ingroup codec_internal
- */
-
-/**
-@addtogroup codec_internal
-@{
-*/
-
-/**
- This function is a fixed-point approximation of a modification of the following
- dequantization operation defined in the spec, as inferred from section 12.6.4:
-
- @code
- dequant = 2^(scale_factor+1) * ((raw * 2.0 + 1.0) / ((2^bits) - 1) - 1)
-
- 2 <= bits <= 16
- 0 <= raw < (2^bits)-1   (the -1 is because quantized values with all 1's are forbidden)
-
- -65535 < dequant < 65535
- @endcode
-
- The code below computes the dequantized value divided by a scaling constant
- equal to about 1.38. This constant is chosen to ensure that the entry in the
- dequant_long_scaled table for 16 bits is as accurate as possible, since it has
- the least relative precision available to it due to its small magnitude.
-
- This routine outputs in Q16.15 format.
-
- The helper array dequant_long is defined as follows:
-
- @code
- dequant_long_long[bits] = round(2^31 * 1/((2^bits - 1) / 1.38...)  for 2 <= bits <= 16
- @endcode
-
-
- Additionally, the table entries have the following property:
-
- @code
- dequant_long_scaled[bits] <= 2^31 / ((2^bits - 1))  for 2 <= bits <= 16
- @endcode
-
- Therefore
-
- @code
- d = 2 * raw + 1              1 <= d <= 2^bits - 2
-
- d' = d * dequant_long[bits]
-
-                  d * dequant_long_scaled[bits] <= (2^bits - 2) * (2^31 / (2^bits - 1))
-                  d * dequant_long_scaled[bits] <= 2^31 * (2^bits - 2)/(2^bits - 1) < 2^31
- @endcode
-
- Therefore, d' doesn't overflow a signed 32-bit value.
-
- @code
-
- d' =~ 2^31 * (raw * 2.0 + 1.0) / (2^bits - 1) / 1.38...
-
- result = d' - 2^31/1.38... =~ 2^31 * ((raw * 2.0 + 1.0) / (2^bits - 1) - 1) / 1.38...
-
- result is therefore a scaled approximation to dequant. It remains only to
- turn 2^31 into 2^(scale_factor+1). Since we're aiming for Q16.15 format,
- this is achieved by shifting right by (15-scale_factor):
-
-  (2^31 * x) >> (15-scale_factor) =~ 2^(31-15+scale_factor) * x = 2^15 * 2^(1+scale_factor) * x
- @endcode
-
- */
-
-#include 
-
-#if defined(SBC_DEC_INCLUDED)
-
-#ifndef SBC_DEQUANT_LONG_SCALED_OFFSET
-#define SBC_DEQUANT_LONG_SCALED_OFFSET 1555931970
-#endif
-
-#ifndef SBC_DEQUANT_LONG_UNSCALED_OFFSET
-#define SBC_DEQUANT_LONG_UNSCALED_OFFSET 2147483648
-#endif
-
-#ifndef SBC_DEQUANT_SCALING_FACTOR
-#define SBC_DEQUANT_SCALING_FACTOR 1.38019122262781f
-#endif
-
-const OI_UINT32 dequant_long_scaled[17];
-const OI_UINT32 dequant_long_unscaled[17];
-
-/** Scales x by y bits to the right, adding a rounding factor.
- */
-#ifndef SCALE
-#define SCALE(x, y) (((x) + (1 << ((y)-1))) >> (y))
-#endif
-
-#ifdef DEBUG_DEQUANTIZATION
-
-#include 
-
-static INLINE float dequant_float(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits)
-{
-    float result = (1 << (scale_factor + 1)) * ((raw * 2.0f + 1.0f) / ((1 << bits) - 1.0f) - 1.0f);
-
-    result /= SBC_DEQUANT_SCALING_FACTOR;
-
-    /* Unless the encoder screwed up, all correct dequantized values should
-     * satisfy this inequality. Non-compliant encoders which generate quantized
-     * values with all 1-bits set can, theoretically, trigger this assert. This
-     * is unlikely, however, and only an issue in debug mode.
-     */
-    OI_ASSERT(fabs(result) < 32768 * 1.6);
-
-    return result;
-}
-
-#endif
-
-INLINE OI_INT32 OI_SBC_Dequant(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits)
-{
-    OI_UINT32 d;
-    OI_INT32 result;
-
-    OI_ASSERT(scale_factor <= 15);
-    OI_ASSERT(bits <= 16);
-
-    if (bits <= 1) {
-        return 0;
-    }
-
-    d = (raw * 2) + 1;
-    d *= dequant_long_scaled[bits];
-    result = d - SBC_DEQUANT_LONG_SCALED_OFFSET;
-
-#ifdef DEBUG_DEQUANTIZATION
-    {
-        OI_INT32 integerized_float_result;
-        float float_result;
-
-        float_result = dequant_float(raw, scale_factor, bits);
-        integerized_float_result = (OI_INT32)floor(0.5f + float_result * (1 << 15));
-
-        /* This detects overflow */
-        OI_ASSERT(((result >= 0) && (integerized_float_result >= 0)) ||
-                  ((result <= 0) && (integerized_float_result <= 0)));
-    }
-#endif
-    return result >> (15 - scale_factor);
-}
-
-/* This version of Dequant does not incorporate the scaling factor of 1.38. It
- * is intended for use with implementations of the filterbank which are
- * hard-coded into a DSP. Output is Q16.4 format, so that after joint stereo
- * processing (which leaves the most significant bit equal to the sign bit if
- * the encoder is conformant) the result will fit a 24 bit fixed point signed
- * value.*/
-
-INLINE OI_INT32 OI_SBC_Dequant_Unscaled(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits)
-{
-    OI_UINT32 d;
-    OI_INT32 result;
-
-    OI_ASSERT(scale_factor <= 15);
-    OI_ASSERT(bits <= 16);
-
-    if (bits <= 1) {
-        return 0;
-    }
-    if (bits == 16) {
-        result = (raw << 16) + raw - 0x7fff7fff;
-        return SCALE(result, 24 - scale_factor);
-    }
-
-    d = (raw * 2) + 1;
-    d *= dequant_long_unscaled[bits];
-    result = d - 0x80000000;
-
-    return SCALE(result, 24 - scale_factor);
-}
-
-/**
-@}
-*/
-
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing-sbc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing-sbc.c
deleted file mode 100644
index ec9437553..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing-sbc.c
+++ /dev/null
@@ -1,58 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/** @file
-@ingroup codec_internal
-*/
-
-/**@addgroup codec_internal*/
-/**@{*/
-
-#include "oi_codec_sbc_private.h"
-
-#if defined(SBC_DEC_INCLUDED)
-
-const OI_CHAR *const OI_CODEC_SBC_FreqText[] = { "SBC_FREQ_16000", "SBC_FREQ_32000", "SBC_FREQ_44100", "SBC_FREQ_48000" };
-const OI_CHAR *const OI_CODEC_SBC_ModeText[] = { "SBC_MONO", "SBC_DUAL_CHANNEL", "SBC_STEREO", "SBC_JOINT_STEREO" };
-const OI_CHAR *const OI_CODEC_SBC_SubbandsText[] = { "SBC_SUBBANDS_4", "SBC_SUBBANDS_8" };
-const OI_CHAR *const OI_CODEC_SBC_BlocksText[] = { "SBC_BLOCKS_4", "SBC_BLOCKS_8", "SBC_BLOCKS_12", "SBC_BLOCKS_16" };
-const OI_CHAR *const OI_CODEC_SBC_AllocText[] = { "SBC_LOUDNESS", "SBC_SNR" };
-
-#ifdef OI_DEBUG
-void OI_CODEC_SBC_DumpConfig(OI_CODEC_SBC_FRAME_INFO *frameInfo)
-{
-    BT_WARN("SBC configuration\n");
-    BT_WARN("  enhanced:  %s\n", frameInfo->enhanced ? "TRUE" : "FALSE");
-    BT_WARN("  frequency: %d\n", frameInfo->frequency);
-    BT_WARN("  subbands:  %d\n", frameInfo->nrof_subbands);
-    BT_WARN("  blocks:    %d\n", frameInfo->nrof_blocks);
-    BT_WARN("  channels:  %d\n", frameInfo->nrof_channels);
-    BT_WARN("  mode:      %s\n", OI_CODEC_SBC_ModeText[frameInfo->mode]);
-    BT_WARN("  alloc:     %s\n", OI_CODEC_SBC_AllocText[frameInfo->alloc]);
-    BT_WARN("  bitpool:   %d\n", frameInfo->bitpool);
-}
-#endif /* OI_DEBUG */
-
-/**@}*/
-
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c
deleted file mode 100644
index d962eaa05..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/framing.c
+++ /dev/null
@@ -1,376 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/**
-@file
-Checksum and header-related functions.
-
-@ingroup codec_internal
-*/
-
-/**
-@addtogroup codec_internal
-@{
-*/
-
-#include "oi_codec_sbc_private.h"
-#include "oi_assert.h"
-
-#if defined(SBC_DEC_INCLUDED)
-
-/* asdasd */
-
-#define USE_NIBBLEWISE_CRC
-
-/* #define PRINT_SAMPLES */
-/* #define PRINT_SCALEFACTORS */
-/* #define DEBUG_CRC */
-
-/*
- * CRC-8 table for X^8 + X^4 + X^3 + X^2 + 1; byte-wise lookup
- */
-#ifdef USE_WIDE_CRC
-/* Save space if a char is 16 bits, such as on the C54x */
-const OI_BYTE crc8_wide[128] = {
-    0x001d,
-    0x3a27,
-    0x7469,
-    0x4e53,
-    0xe8f5,
-    0xd2cf,
-    0x9c81,
-    0xa6bb,
-    0xcdd0,
-    0xf7ea,
-    0xb9a4,
-    0x839e,
-    0x2538,
-    0x1f02,
-    0x514c,
-    0x6b76,
-    0x879a,
-    0xbda0,
-    0xf3ee,
-    0xc9d4,
-    0x6f72,
-    0x5548,
-    0x1b06,
-    0x213c,
-    0x4a57,
-    0x706d,
-    0x3e23,
-    0x0419,
-    0xa2bf,
-    0x9885,
-    0xd6cb,
-    0xecf1,
-    0x130e,
-    0x2934,
-    0x677a,
-    0x5d40,
-    0xfbe6,
-    0xc1dc,
-    0x8f92,
-    0xb5a8,
-    0xdec3,
-    0xe4f9,
-    0xaab7,
-    0x908d,
-    0x362b,
-    0x0c11,
-    0x425f,
-    0x7865,
-    0x9489,
-    0xaeb3,
-    0xe0fd,
-    0xdac7,
-    0x7c61,
-    0x465b,
-    0x0815,
-    0x322f,
-    0x5944,
-    0x637e,
-    0x2d30,
-    0x170a,
-    0xb1ac,
-    0x8b96,
-    0xc5d8,
-    0xffe2,
-    0x263b,
-    0x1c01,
-    0x524f,
-    0x6875,
-    0xced3,
-    0xf4e9,
-    0xbaa7,
-    0x809d,
-    0xebf6,
-    0xd1cc,
-    0x9f82,
-    0xa5b8,
-    0x031e,
-    0x3924,
-    0x776a,
-    0x4d50,
-    0xa1bc,
-    0x9b86,
-    0xd5c8,
-    0xeff2,
-    0x4954,
-    0x736e,
-    0x3d20,
-    0x071a,
-    0x6c71,
-    0x564b,
-    0x1805,
-    0x223f,
-    0x8499,
-    0xbea3,
-    0xf0ed,
-    0xcad7,
-    0x3528,
-    0x0f12,
-    0x415c,
-    0x7b66,
-    0xddc0,
-    0xe7fa,
-    0xa9b4,
-    0x938e,
-    0xf8e5,
-    0xc2df,
-    0x8c91,
-    0xb6ab,
-    0x100d,
-    0x2a37,
-    0x6479,
-    0x5e43,
-    0xb2af,
-    0x8895,
-    0xc6db,
-    0xfce1,
-    0x5a47,
-    0x607d,
-    0x2e33,
-    0x1409,
-    0x7f62,
-    0x4558,
-    0x0b16,
-    0x312c,
-    0x978a,
-    0xadb0,
-    0xe3fe,
-    0xd9c4,
-};
-#elif defined(USE_NIBBLEWISE_CRC)
-const OI_BYTE crc8_narrow[16] = {
-    0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, 0xbb
-};
-#else
-const OI_BYTE crc8_narrow[256] = {
-    0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, 0xbb, 0xcd, 0xd0, 0xf7, 0xea, 0xb9, 0xa4, 0x83, 0x9e, 0x25, 0x38, 0x1f, 0x02, 0x51, 0x4c, 0x6b, 0x76, 0x87, 0x9a, 0xbd, 0xa0, 0xf3, 0xee, 0xc9, 0xd4, 0x6f, 0x72, 0x55, 0x48, 0x1b, 0x06, 0x21, 0x3c, 0x4a, 0x57, 0x70, 0x6d, 0x3e, 0x23, 0x04, 0x19, 0xa2, 0xbf, 0x98, 0x85, 0xd6, 0xcb, 0xec, 0xf1, 0x13, 0x0e, 0x29, 0x34, 0x67, 0x7a, 0x5d, 0x40, 0xfb, 0xe6, 0xc1, 0xdc, 0x8f, 0x92, 0xb5, 0xa8, 0xde, 0xc3, 0xe4, 0xf9, 0xaa, 0xb7, 0x90, 0x8d, 0x36, 0x2b, 0x0c, 0x11, 0x42, 0x5f, 0x78, 0x65, 0x94, 0x89, 0xae, 0xb3, 0xe0, 0xfd, 0xda, 0xc7, 0x7c, 0x61, 0x46, 0x5b, 0x08, 0x15, 0x32, 0x2f, 0x59, 0x44, 0x63, 0x7e, 0x2d, 0x30, 0x17, 0x0a, 0xb1, 0xac, 0x8b, 0x96, 0xc5, 0xd8, 0xff, 0xe2, 0x26, 0x3b, 0x1c, 0x01, 0x52, 0x4f, 0x68, 0x75, 0xce, 0xd3, 0xf4, 0xe9, 0xba, 0xa7, 0x80, 0x9d, 0xeb, 0xf6, 0xd1, 0xcc, 0x9f, 0x82, 0xa5, 0xb8, 0x03, 0x1e, 0x39, 0x24, 0x77, 0x6a, 0x4d, 0x50, 0xa1, 0xbc, 0x9b, 0x86, 0xd5, 0xc8, 0xef, 0xf2, 0x49, 0x54, 0x73, 0x6e, 0x3d, 0x20, 0x07, 0x1a, 0x6c, 0x71, 0x56, 0x4b, 0x18, 0x05, 0x22, 0x3f, 0x84, 0x99, 0xbe, 0xa3, 0xf0, 0xed, 0xca, 0xd7, 0x35, 0x28, 0x0f, 0x12, 0x41, 0x5c, 0x7b, 0x66, 0xdd, 0xc0, 0xe7, 0xfa, 0xa9, 0xb4, 0x93, 0x8e, 0xf8, 0xe5, 0xc2, 0xdf, 0x8c, 0x91, 0xb6, 0xab, 0x10, 0x0d, 0x2a, 0x37, 0x64, 0x79, 0x5e, 0x43, 0xb2, 0xaf, 0x88, 0x95, 0xc6, 0xdb, 0xfc, 0xe1, 0x5a, 0x47, 0x60, 0x7d, 0x2e, 0x33, 0x14, 0x09, 0x7f, 0x62, 0x45, 0x58, 0x0b, 0x16, 0x31, 0x2c, 0x97, 0x8a, 0xad, 0xb0, 0xe3, 0xfe, 0xd9, 0xc4
-};
-#endif
-const OI_UINT32 dequant_long_scaled[17] = {
-    0,
-    0,
-    0x1ee9e116, /* bits=2  0.24151243  1/3      * (1/1.38019122262781) (0x00000008)*/
-    0x0d3fa99c, /* bits=3  0.10350533  1/7      * (1/1.38019122262781) (0x00000013)*/
-    0x062ec69e, /* bits=4  0.04830249  1/15     * (1/1.38019122262781) (0x00000029)*/
-    0x02fddbfa, /* bits=5  0.02337217  1/31     * (1/1.38019122262781) (0x00000055)*/
-    0x0178d9f5, /* bits=6  0.01150059  1/63     * (1/1.38019122262781) (0x000000ad)*/
-    0x00baf129, /* bits=7  0.00570502  1/127    * (1/1.38019122262781) (0x0000015e)*/
-    0x005d1abe, /* bits=8  0.00284132  1/255    * (1/1.38019122262781) (0x000002bf)*/
-    0x002e760d, /* bits=9  0.00141788  1/511    * (1/1.38019122262781) (0x00000582)*/
-    0x00173536, /* bits=10 0.00070825  1/1023   * (1/1.38019122262781) (0x00000b07)*/
-    0x000b9928, /* bits=11 0.00035395  1/2047   * (1/1.38019122262781) (0x00001612)*/
-    0x0005cc37, /* bits=12 0.00017693  1/4095   * (1/1.38019122262781) (0x00002c27)*/
-    0x0002e604, /* bits=13 0.00008846  1/8191   * (1/1.38019122262781) (0x00005852)*/
-    0x000172fc, /* bits=14 0.00004422  1/16383  * (1/1.38019122262781) (0x0000b0a7)*/
-    0x0000b97d, /* bits=15 0.00002211  1/32767  * (1/1.38019122262781) (0x00016150)*/
-    0x00005cbe, /* bits=16 0.00001106  1/65535  * (1/1.38019122262781) (0x0002c2a5)*/
-};
-
-const OI_UINT32 dequant_long_unscaled[17] = {
-    0,
-    0,
-    0x2aaaaaab, /* bits=2  0.33333333  1/3      (0x00000005)*/
-    0x12492492, /* bits=3  0.14285714  1/7      (0x0000000e)*/
-    0x08888889, /* bits=4  0.06666667  1/15     (0x0000001d)*/
-    0x04210842, /* bits=5  0.03225806  1/31     (0x0000003e)*/
-    0x02082082, /* bits=6  0.01587302  1/63     (0x0000007e)*/
-    0x01020408, /* bits=7  0.00787402  1/127    (0x000000fe)*/
-    0x00808081, /* bits=8  0.00392157  1/255    (0x000001fd)*/
-    0x00402010, /* bits=9  0.00195695  1/511    (0x000003fe)*/
-    0x00200802, /* bits=10 0.00097752  1/1023   (0x000007fe)*/
-    0x00100200, /* bits=11 0.00048852  1/2047   (0x00000ffe)*/
-    0x00080080, /* bits=12 0.00024420  1/4095   (0x00001ffe)*/
-    0x00040020, /* bits=13 0.00012209  1/8191   (0x00003ffe)*/
-    0x00020008, /* bits=14 0.00006104  1/16383  (0x00007ffe)*/
-    0x00010002, /* bits=15 0.00003052  1/32767  (0x0000fffe)*/
-    0x00008001, /* bits=16 0.00001526  1/65535  (0x0001fffc)*/
-};
-
-#if defined(OI_DEBUG) || defined(PRINT_SAMPLES) || defined(PRINT_SCALEFACTORS)
-#include 
-#endif
-
-#ifdef USE_WIDE_CRC
-static INLINE OI_CHAR crc_iterate(OI_UINT8 oldcrc, OI_UINT8 next)
-{
-    OI_UINT crc;
-    OI_UINT idx;
-    idx = oldcrc ^ next;
-    crc = crc8_wide[idx >> 1];
-    if (idx % 2) {
-        crc &= 0xff;
-    } else {
-        crc >>= 8;
-    }
-
-    return crc;
-}
-
-static INLINE OI_CHAR crc_iterate_top4(OI_UINT8 oldcrc, OI_UINT8 next)
-{
-    OI_UINT crc;
-    OI_UINT idx;
-    idx = (oldcrc ^ next) >> 4;
-    crc = crc8_wide[idx >> 1];
-    if (idx % 2) {
-        crc &= 0xff;
-    } else {
-        crc >>= 8;
-    }
-
-    return (oldcrc << 4) ^ crc;
-}
-
-#else // USE_WIDE_CRC
-
-static INLINE OI_UINT8 crc_iterate_top4(OI_UINT8 oldcrc, OI_UINT8 next)
-{
-    return (oldcrc << 4) ^ crc8_narrow[(oldcrc ^ next) >> 4];
-}
-
-#ifdef USE_NIBBLEWISE_CRC
-static INLINE OI_UINT8 crc_iterate(OI_UINT8 crc, OI_UINT8 next)
-{
-    crc = (crc << 4) ^ crc8_narrow[(crc ^ next) >> 4];
-    crc = (crc << 4) ^ crc8_narrow[((crc >> 4) ^ next) & 0xf];
-
-    return crc;
-}
-
-#else // USE_NIBBLEWISE_CRC
-static INLINE OI_UINT8 crc_iterate(OI_UINT8 crc, OI_UINT8 next)
-{
-    return crc8_narrow[crc ^ next];
-}
-
-#endif // USE_NIBBLEWISE_CRC
-
-#endif // USE_WIDE_CRC
-
-PRIVATE OI_UINT8 OI_SBC_CalculateChecksum(OI_CODEC_SBC_FRAME_INFO *frame, OI_BYTE const *data)
-{
-    OI_UINT i;
-    OI_UINT8 crc = 0x0f;
-    /* Count is the number of whole bytes subject to CRC. Actually, it's one
-     * more than this number, because data[3] is the CRC field itself, which is
-     * explicitly skipped. Since crc_iterate (should be) inlined, it's cheaper
-     * spacewise to include the check in the loop. This shouldn't be much of a
-     * bottleneck routine in the first place. */
-    OI_UINT count = (frame->nrof_subbands * frame->nrof_channels / 2u) + 4;
-
-    if (frame->mode == SBC_JOINT_STEREO && frame->nrof_subbands == 8) {
-        count++;
-    }
-
-    for (i = 1; i < count; i++) {
-        if (i != 3) {
-            crc = crc_iterate(crc, data[i]);
-        }
-    }
-
-    if (frame->mode == SBC_JOINT_STEREO && frame->nrof_subbands == 4) {
-        crc = crc_iterate_top4(crc, data[i]);
-    }
-
-    return crc;
-}
-
-void OI_SBC_ExpandFrameFields(OI_CODEC_SBC_FRAME_INFO *frame)
-{
-    frame->nrof_blocks = block_values[frame->blocks];
-    frame->nrof_subbands = band_values[frame->subbands];
-
-    frame->frequency = freq_values[frame->freqIndex];
-    frame->nrof_channels = channel_values[frame->mode];
-}
-
-/**
- * Unrolled macro to copy 4 32-bit aligned 32-bit values backward in memory
- */
-#define COPY4WORDS_BACK(_dest, _src) \
-    do {                             \
-        OI_INT32 _a, _b, _c, _d;     \
-        _a = *--_src;                \
-        _b = *--_src;                \
-        _c = *--_src;                \
-        _d = *--_src;                \
-        *--_dest = _a;               \
-        *--_dest = _b;               \
-        *--_dest = _c;               \
-        *--_dest = _d;               \
-    } while (0)
-
-#if defined(USE_PLATFORM_MEMMOVE) || defined(USE_PLATFORM_MEMCPY)
-#include 
-#endif
-PRIVATE void shift_buffer(SBC_BUFFER_T *dest, SBC_BUFFER_T *src, OI_UINT wordCount)
-{
-#ifdef USE_PLATFORM_MEMMOVE
-    memmove(dest, src, wordCount * sizeof(SBC_BUFFER_T));
-#elif defined(USE_PLATFORM_MEMCPY)
-    OI_ASSERT(((OI_CHAR *)(dest) - (OI_CHAR *)(src)) >= wordCount * sizeof(*dest));
-    memcpy(dest, src, wordCount * sizeof(SBC_BUFFER_T));
-#else
-    OI_UINT n;
-    OI_INT32 *d;
-    OI_INT32 *s;
-    n = wordCount / 4 / (sizeof(OI_INT32) / sizeof(*dest));
-    OI_ASSERT((n * 4 * (sizeof(OI_INT32) / sizeof(*dest))) == wordCount);
-
-    d = (void *)(dest + wordCount);
-    s = (void *)(src + wordCount);
-
-    do {
-        COPY4WORDS_BACK(d, s);
-    } while (--n);
-#endif
-}
-/**
-@}
-*/
-
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_assert.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_assert.h
deleted file mode 100644
index 54939c75f..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_assert.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_ASSERT_H
-#define _OI_ASSERT_H
-/** @file
-  This file provides macros and functions for compile-time and run-time assertions.
-
-  When the OI_DEBUG preprocessor value is defined, the macro OI_ASSERT is compiled into
-  the program, providing for a runtime assertion failure check.
-  C_ASSERT is a macro that can be used to perform compile time checks.
-*/
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/** \addtogroup Debugging Debugging APIs */
-/**@{*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef OI_DEBUG
-
-/** The macro OI_ASSERT takes a condition argument. If the asserted condition
-    does not evaluate to true, the OI_ASSERT macro calls the host-dependent function,
-    OI_AssertFail(), which reports the failure and generates a runtime error.
-*/
-void OI_AssertFail(char *file, int line, char *reason);
-
-#define OI_ASSERT(condition)                               \
-    {                                                      \
-        if (!(condition))                                  \
-            OI_AssertFail(__FILE__, __LINE__, #condition); \
-    }
-
-#define OI_ASSERT_FAIL(msg)                     \
-    {                                           \
-        OI_AssertFail(__FILE__, __LINE__, msg); \
-    }
-
-#else
-
-#define OI_ASSERT(condition)
-#define OI_ASSERT_FAIL(msg)
-
-#endif
-
-/**
-   C_ASSERT() can be used to perform many compile-time assertions: type sizes, field offsets, etc.
-   An assertion failure results in compile time error C2118: negative subscript.
-   Unfortunately, this elegant macro doesn't work with GCC, so it's all commented out
-   for now. Perhaps later.....
-*/
-
-#ifndef C_ASSERT
-// #define C_ASSERT(e) typedef char __C_ASSERT__[(e)?1:-1]
-// #define C_ASSERT(e)
-#endif
-
-/*****************************************************************************/
-#ifdef __cplusplus
-}
-#endif
-
-/**@}*/
-
-#endif /* _OI_ASSERT_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_bitstream.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_bitstream.h
deleted file mode 100644
index 886eb6e94..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_bitstream.h
+++ /dev/null
@@ -1,121 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_BITSTREAM_H
-#define _OI_BITSTREAM_H
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/**
-@file
-Function prototypes and macro definitions for manipulating input and output
-bitstreams.
-
-@ingroup codec_internal
-*/
-
-/**
-@addtogroup codec_internal
-@{
-*/
-
-#include "oi_codec_sbc_private.h"
-#include "oi_stddefs.h"
-
-INLINE void OI_BITSTREAM_ReadInit(OI_BITSTREAM *bs, const OI_BYTE *buffer);
-
-INLINE void OI_BITSTREAM_WriteInit(OI_BITSTREAM *bs, OI_BYTE *buffer);
-
-INLINE OI_UINT32 OI_BITSTREAM_ReadUINT(OI_BITSTREAM *bs, OI_UINT bits);
-
-INLINE OI_UINT8 OI_BITSTREAM_ReadUINT4Aligned(OI_BITSTREAM *bs);
-
-INLINE OI_UINT8 OI_BITSTREAM_ReadUINT8Aligned(OI_BITSTREAM *bs);
-
-INLINE void OI_BITSTREAM_WriteUINT(OI_BITSTREAM *bs,
-                                   OI_UINT16 value,
-                                   OI_UINT bits);
-
-/*
- * Use knowledge that the bitstream is aligned to optimize the write of a byte
- */
-PRIVATE void OI_BITSTREAM_WriteUINT8Aligned(OI_BITSTREAM *bs,
-                                            OI_UINT8 datum);
-
-/*
- * Use knowledge that the bitstream is aligned to optimize the write pair of nibbles
- */
-PRIVATE void OI_BITSTREAM_Write2xUINT4Aligned(OI_BITSTREAM *bs,
-                                              OI_UINT8 datum1,
-                                              OI_UINT8 datum2);
-
-/** Internally the bitstream looks ahead in the stream. When
- * OI_SBC_ReadScalefactors() goes to temporarily break the abstraction, it will
- * need to know where the "logical" pointer is in the stream.
- */
-#define OI_BITSTREAM_GetWritePtr(bs) ((bs)->ptr.w - 3)
-#define OI_BITSTREAM_GetReadPtr(bs)  ((bs)->ptr.r - 3)
-
-/** This is declared here as a macro because decoder.c breaks the bitsream
- * encapsulation for efficiency reasons.
- */
-#define OI_BITSTREAM_READUINT(result, bits, ptr, value, bitPtr) \
-    do {                                                        \
-        OI_ASSERT((bits) <= 16);                                \
-        OI_ASSERT((bitPtr) < 16);                               \
-        OI_ASSERT((bitPtr) >= 8);                               \
-                                                                \
-        result = (value) << (bitPtr);                           \
-        result >>= 32 - (bits);                                 \
-                                                                \
-        bitPtr += (bits);                                       \
-        while (bitPtr >= 16) {                                  \
-            value = ((value) << 8) | *ptr++;                    \
-            bitPtr -= 8;                                        \
-        }                                                       \
-        OI_ASSERT((bits == 0) || (result < (1u << (bits))));    \
-    } while (0)
-
-#define OI_BITSTREAM_WRITEUINT(ptr, value, bitPtr, datum, bits) \
-    do {                                                        \
-        bitPtr -= bits;                                         \
-        value |= datum << bitPtr;                               \
-                                                                \
-        while (bitPtr <= 16) {                                  \
-            bitPtr += 8;                                        \
-            *ptr++ = (OI_UINT8)(value >> 24);                   \
-            value <<= 8;                                        \
-        }                                                       \
-    } while (0)
-
-#define OI_BITSTREAM_WRITEFLUSH(ptr, value, bitPtr) \
-    do {                                            \
-        while (bitPtr < 32) {                       \
-            bitPtr += 8;                            \
-            *ptr++ = (OI_UINT8)(value >> 24);       \
-            value <<= 8;                            \
-        }                                           \
-    } while (0)
-
-/**
-@}
-*/
-
-#endif /* _OI_BITSTREAM_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_bt_spec.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_bt_spec.h
deleted file mode 100644
index 75776399d..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_bt_spec.h
+++ /dev/null
@@ -1,225 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_BT_SPEC_H
-#define _OI_BT_SPEC_H
-/**
- * @file
- *
- * This file contains common definitions from the Bluetooth specification.
- *
- */
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-#include "oi_stddefs.h"
-
-/** \addtogroup Misc Miscellaneous APIs */
-/**@{*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/** The maximum number of active slaves in a piconet. */
-#define OI_BT_MAX_ACTIVE_SLAVES 7
-
-/** the number of bytes in a Bluetooth device address (BD_ADDR) */
-#define OI_BD_ADDR_BYTE_SIZE 6
-
-/**
- * 48-bit Bluetooth device address
- *
- * Because 48-bit integers may not be supported on all platforms, the
- * address is defined as an array of bytes. This array is big-endian,
- * meaning that
- *  - array[0] contains bits 47-40,
- *  - array[1] contains bits 39-32,
- *  - array[2] contains bits 31-24,
- *  - array[3] contains bits 23-16,
- *  - array[4] contains bits 15-8, and
- *  - array[5] contains bits 7-0.
- */
-typedef struct {
-    OI_UINT8 addr[OI_BD_ADDR_BYTE_SIZE]; /**< Bluetooth device address represented as an array of 8-bit values */
-} OI_BD_ADDR;
-
-/**
- * @name Data types for working with UUIDs
- * UUIDs are 16 bytes (128 bits).
- *
- * To avoid having to pass around 128-bit values all the time, 32-bit and 16-bit
- * UUIDs are defined, along with a mapping from the shorter versions to the full
- * version.
- *
- * @{
- */
-
-/**
- * 16-bit representation of a 128-bit UUID
- */
-typedef OI_UINT16 OI_UUID16;
-
-/**
- * 32-bit representation of a 128-bit UUID
- */
-typedef OI_UINT32 OI_UUID32;
-
-/**
- * number of bytes in a 128 bit UUID
- */
-#define OI_BT_UUID128_SIZE 16
-
-/**
- * number of bytes in IPv6 style addresses
- */
-#define OI_BT_IPV6ADDR_SIZE 16
-
-/**
- * type definition for a 128-bit UUID
- *
- * To simplify conversion between 128-bit UUIDs and 16-bit and 32-bit UUIDs,
- * the most significant 32 bits are stored with the same endian-ness as is
- * native on the target (local) device. The remainder of the 128-bit UUID is
- * stored as bytes in big-endian order.
- */
-typedef struct {
-    OI_UINT32 ms32bits;                                    /**< most significant 32 bits of 128-bit UUID */
-    OI_UINT8 base[OI_BT_UUID128_SIZE - sizeof(OI_UINT32)]; /**< remainder of 128-bit UUID, array of 8-bit values */
-} OI_UUID128;
-
-/** @} */
-
-/** number of bytes in a link key */
-#define OI_BT_LINK_KEY_SIZE 16
-
-/**
- * type definition for a baseband link key
- *
- * Because 128-bit integers may not be supported on all platforms, we define
- * link keys as an array of bytes. Unlike the Bluetooth device address,
- * the link key is stored in little-endian order, meaning that
- *  - array[0]  contains bits 0  - 7,
- *  - array[1]  contains bits 8  - 15,
- *  - array[2]  contains bits 16 - 23,
- *  - array[3]  contains bits 24 - 31,
- *  - array[4]  contains bits 32 - 39,
- *  - array[5]  contains bits 40 - 47,
- *  - array[6]  contains bits 48 - 55,
- *  - array[7]  contains bits 56 - 63,
- *  - array[8]  contains bits 64 - 71,
- *  - array[9]  contains bits 72 - 79,
- *  - array[10] contains bits 80 - 87,
- *  - array[11] contains bits 88 - 95,
- *  - array[12] contains bits 96 - 103,
- *  - array[13] contains bits 104- 111,
- *  - array[14] contains bits 112- 119, and
- *  - array[15] contains bits 120- 127.
- */
-typedef struct {
-    OI_UINT8 key[OI_BT_LINK_KEY_SIZE]; /**< link key represented as an array of 8-bit values */
-} OI_LINK_KEY;
-
-/** Out-of-band data size - C and R values are 16-bytes each */
-#define OI_BT_OOB_NUM_BYTES 16
-
-typedef struct {
-    OI_UINT8 value[OI_BT_OOB_NUM_BYTES]; /**< same struct used for C and R values */
-} OI_OOB_DATA;
-
-/**
- * link key types
- */
-typedef enum {
-    OI_LINK_KEY_TYPE_COMBO = 0,           /**< combination key */
-    OI_LINK_KEY_TYPE_LOCAL_UNIT = 1,      /**< local unit key */
-    OI_LINK_KEY_TYPE_REMOTE_UNIT = 2,     /**< remote unit key */
-    OI_LINK_KEY_TYPE_DEBUG_COMBO = 3,     /**< debug combination key */
-    OI_LINK_KEY_TYPE_UNAUTHENTICATED = 4, /**< Unauthenticated */
-    OI_LINK_KEY_TYPE_AUTHENTICATED = 5,   /**< Authenticated */
-    OI_LINK_KEY_TYPE_CHANGED_COMBO = 6    /**< Changed */
-
-} OI_BT_LINK_KEY_TYPE;
-
-/** amount of space allocated for a PIN (personal indentification number) in bytes */
-#define OI_BT_PIN_CODE_SIZE 16
-
-/** data type for a PIN (PINs are treated as strings, so endianness does not apply.) */
-typedef struct {
-    OI_UINT8 pin[OI_BT_PIN_CODE_SIZE]; /**< PIN represented as an array of 8-bit values */
-} OI_PIN_CODE;
-
-/** maximum number of SCO connections per device, which is 3 as of version 2.0+EDR
-    of the Bluetooth specification (see sec 4.3 of vol 2 part B) */
-#define OI_BT_MAX_SCO_CONNECTIONS 3
-
-/** data type for clock offset */
-typedef OI_UINT16 OI_BT_CLOCK_OFFSET;
-
-/** data type for a LM handle */
-typedef OI_UINT16 OI_HCI_LM_HANDLE;
-
-/** opaque data type for a SCO or ACL connection handle */
-typedef struct _OI_HCI_CONNECTION *OI_HCI_CONNECTION_HANDLE;
-
-/** data type for HCI Error Code, as defined in oi_hcispec.h */
-typedef OI_UINT8 OI_HCI_ERROR_CODE;
-
-/**
- * The Bluetooth device type is indicated by a 24-bit bitfield, represented as a
- * 32-bit number in the stack. The bit layout and values for device class are specified
- * in the file oi_bt_assigned_nos.h and in the Bluetooth "Assigned Numbers" specification
- * at http://www.bluetooth.org/assigned-numbers/.
- */
-typedef OI_UINT32 OI_BT_DEVICE_CLASS;
-
-#define OI_BT_DEV_CLASS_FORMAT_MASK        0x000003 /**< Bits 0-1 contain format type. */
-#define OI_BT_DEV_CLASS_MINOR_DEVICE_MASK  0x0000FC /**< Bits 2-7 contain minor device class value. */
-#define OI_BT_DEV_CLASS_MAJOR_DEVICE_MASK  0x001F00 /**< Bits 8-12 contain major device class value. */
-#define OI_BT_DEV_CLASS_MAJOR_SERVICE_MASK 0xFFE000 /**< Bits 13-23 contain major service class value. */
-
-/** There is currently only one device class format defined, type 00. */
-#define OI_BT_DEV_CLASS_FORMAT_TYPE 00
-
-/** Bit 13 in device class indicates limited discoverability mode (GAP v2.0+EDR, section 4.1.2.2) */
-#define OI_BT_DEV_CLASS_LIMITED_DISCO_BIT BIT13
-
-/** macro to test validity of the Device Class Format */
-#define OI_BT_VALID_DEVICE_CLASS_FORMAT(class) (OI_BT_DEV_CLASS_FORMAT_TYPE == ((class) & OI_BT_DEV_CLASS_FORMAT_MASK))
-
-/** the time between baseband clock ticks, currently 625 microseconds (one slot) */
-#define OI_BT_TICK 625
-/** some macros to convert to/from baseband clock ticks - use no floating point! */
-#define OI_SECONDS_TO_BT_TICKS(secs)  ((secs)*1600)
-#define OI_BT_TICKS_TO_SECONDS(ticks) ((ticks) / 1600)
-#define OI_MSECS_TO_BT_TICKS(msecs)   (((msecs)*8) / 5)
-#define OI_BT_TICKS_TO_MSECS(ticks)   (((ticks)*5) / 8)
-
-/** EIR byte order */
-#define OI_EIR_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER
-
-#ifdef __cplusplus
-}
-#endif
-
-/**@}*/
-
-/*****************************************************************************/
-#endif /* _OI_BT_SPEC_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_sbc.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_sbc.h
deleted file mode 100644
index d8b7206b7..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_sbc.h
+++ /dev/null
@@ -1,478 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-#ifndef _OI_CODEC_SBC_CORE_H
-#define _OI_CODEC_SBC_CORE_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
-@file
-Declarations of codec functions, data types, and macros.
-
-@ingroup codec_lib
-*/
-
-/**
-@addtogroup codec_lib
-@{
-*/
-
-/* Non-BM3 users of of the codec must include oi_codec_sbc_bm3defs.h prior to
- * including this file, or else these includes will fail because the BM3 SDK is
- * not in the include path */
-#ifndef _OI_CODEC_SBC_BM3DEFS_H
-#include "oi_stddefs.h"
-#include "oi_status.h"
-#endif
-
-#include 
-
-#define SBC_MAX_CHANNELS        2
-#define SBC_MAX_BANDS           8
-#define SBC_MAX_BLOCKS          16
-#define SBC_MIN_BITPOOL         2   /**< Minimum size of the bit allocation pool used to encode the stream */
-#define SBC_MAX_BITPOOL         250 /**< Maximum size of the bit allocation pool used to encode the stream */
-#define SBC_MAX_ONE_CHANNEL_BPS 320000
-#define SBC_MAX_TWO_CHANNEL_BPS 512000
-
-#define SBC_WBS_BITRATE           62000
-#define SBC_WBS_BITPOOL           27
-#define SBC_WBS_NROF_BLOCKS       16
-#define SBC_WBS_FRAME_LEN         62
-#define SBC_WBS_SAMPLES_PER_FRAME 128
-
-#define SBC_HEADER_LEN    4
-#define SBC_MAX_FRAME_LEN (SBC_HEADER_LEN +                          \
-                           ((SBC_MAX_BANDS * SBC_MAX_CHANNELS / 2) + \
-                            (SBC_MAX_BANDS + SBC_MAX_BLOCKS * SBC_MAX_BITPOOL + 7) / 8))
-#define SBC_MAX_SAMPLES_PER_FRAME (SBC_MAX_BANDS * SBC_MAX_BLOCKS)
-
-#define SBC_MAX_SCALEFACTOR_BYTES ((4 * (SBC_MAX_CHANNELS * SBC_MAX_BANDS) + 7) / 8)
-
-#define OI_SBC_SYNCWORD          0x9c
-#define OI_SBC_ENHANCED_SYNCWORD 0x9d
-#define OI_mSBC_SYNCWORD         0xad
-
-#define OI_SBC_MODE_STD  0
-#define OI_SBC_MODE_MSBC 1
-
-/**@name Sampling frequencies */
-/**@{*/
-#define SBC_FREQ_16000 0 /**< The sampling frequency is 16 kHz. One possible value for the @a frequency parameter of OI_CODEC_SBC_EncoderConfigure() */
-#define SBC_FREQ_32000 1 /**< The sampling frequency is 32 kHz. One possible value for the @a frequency parameter of OI_CODEC_SBC_EncoderConfigure() */
-#define SBC_FREQ_44100 2 /**< The sampling frequency is 44.1 kHz. One possible value for the @a frequency parameter of OI_CODEC_SBC_EncoderConfigure() */
-#define SBC_FREQ_48000 3 /**< The sampling frequency is 48 kHz. One possible value for the @a frequency parameter of OI_CODEC_SBC_EncoderConfigure() */
-/**@}*/
-
-/**@name Channel modes */
-/**@{*/
-#define SBC_MONO         0 /**< The mode of the encoded channel is mono. One possible value for the @a mode parameter of OI_CODEC_SBC_EncoderConfigure() */
-#define SBC_DUAL_CHANNEL 1 /**< The mode of the encoded channel is dual-channel. One possible value for the @a mode parameter of OI_CODEC_SBC_EncoderConfigure() */
-#define SBC_STEREO       2 /**< The mode of the encoded channel is stereo. One possible value for the @a mode parameter of OI_CODEC_SBC_EncoderConfigure() */
-#define SBC_JOINT_STEREO 3 /**< The mode of the encoded channel is joint stereo. One possible value for the @a mode parameter of OI_CODEC_SBC_EncoderConfigure() */
-/**@}*/
-
-/**@name Subbands */
-/**@{*/
-#define SBC_SUBBANDS_4 0 /**< The encoded stream has 4 subbands. One possible value for the @a subbands parameter of OI_CODEC_SBC_EncoderConfigure()*/
-#define SBC_SUBBANDS_8 1 /**< The encoded stream has 8 subbands. One possible value for the @a subbands parameter of OI_CODEC_SBC_EncoderConfigure() */
-/**@}*/
-
-/**@name Block lengths */
-/**@{*/
-#define SBC_BLOCKS_4  0 /**< A block size of 4 blocks was used to encode the stream. One possible value for the @a blocks parameter of OI_CODEC_SBC_EncoderConfigure() */
-#define SBC_BLOCKS_8  1 /**< A block size of 8 blocks was used to encode the stream is. One possible value for the @a blocks parameter of OI_CODEC_SBC_EncoderConfigure() */
-#define SBC_BLOCKS_12 2 /**< A block size of 12 blocks was used to encode the stream. One possible value for the @a blocks parameter of OI_CODEC_SBC_EncoderConfigure() */
-#define SBC_BLOCKS_16 3 /**< A block size of 16 blocks was used to encode the stream. One possible value for the @a blocks parameter of OI_CODEC_SBC_EncoderConfigure() */
-/**@}*/
-
-/**@name Bit allocation methods */
-/**@{*/
-#define SBC_LOUDNESS 0 /**< The bit allocation method. One possible value for the @a loudness parameter of OI_CODEC_SBC_EncoderConfigure() */
-#define SBC_SNR      1 /**< The bit allocation method. One possible value for the @a loudness parameter of OI_CODEC_SBC_EncoderConfigure() */
-/**@}*/
-
-/**
-@}
-
-@addtogroup codec_internal
-@{
-*/
-
-typedef OI_INT16 SBC_BUFFER_T;
-
-/** Used internally. */
-typedef struct {
-    OI_UINT16 frequency; /**< The sampling frequency. Input parameter. */
-    OI_UINT8 freqIndex;
-
-    OI_UINT8 nrof_blocks; /**< The block size used to encode the stream. Input parameter. */
-    OI_UINT8 blocks;
-
-    OI_UINT8 nrof_subbands; /**< The number of subbands of the encoded stream. Input parameter. */
-    OI_UINT8 subbands;
-
-    OI_UINT8 mode;          /**< The mode of the encoded channel. Input parameter. */
-    OI_UINT8 nrof_channels; /**< The number of channels of the encoded stream. */
-
-    OI_UINT8 alloc;   /**< The bit allocation method. Input parameter. */
-    OI_UINT8 bitpool; /**< Size of the bit allocation pool used to encode the stream. Input parameter. */
-    OI_UINT8 crc;     /**< Parity check byte used for error detection. */
-    OI_UINT8 join;    /**< Whether joint stereo has been used. */
-    OI_UINT8 enhanced;
-    OI_UINT8 min_bitpool; /**< This value is only used when encoding. SBC_MAX_BITPOOL if variable
-                                 bitpools are disallowed, otherwise the minimum bitpool size that will
-                                 be used by the bit allocator.  */
-
-    OI_UINT8 cachedInfo; /**< Information about the previous frame */
-} OI_CODEC_SBC_FRAME_INFO;
-
-/** Used internally. */
-typedef struct {
-    const OI_CHAR *codecInfo;
-    OI_CODEC_SBC_FRAME_INFO frameInfo;
-    OI_INT8 scale_factor[SBC_MAX_CHANNELS * SBC_MAX_BANDS];
-    OI_UINT32 frameCount;
-    OI_INT32 *subdata;
-
-    SBC_BUFFER_T *filterBuffer[SBC_MAX_CHANNELS];
-    OI_INT32 filterBufferLen;
-    OI_UINT filterBufferOffset;
-
-    union {
-        OI_UINT8 uint8[SBC_MAX_CHANNELS * SBC_MAX_BANDS];
-        OI_UINT32 uint32[SBC_MAX_CHANNELS * SBC_MAX_BANDS / 4];
-    } bits;
-    OI_UINT8 maxBitneed; /**< Running maximum bitneed */
-    OI_BYTE formatByte;
-    OI_UINT8 pcmStride;
-    OI_UINT8 maxChannels;
-} OI_CODEC_SBC_COMMON_CONTEXT;
-
-/*
- * A smaller value reduces RAM usage at the expense of increased CPU usage. Values in the range
- * 27..50 are recommended, beyond 50 there is a diminishing return on reduced CPU usage.
- */
-#define SBC_CODEC_MIN_FILTER_BUFFERS  16
-#define SBC_CODEC_FAST_FILTER_BUFFERS 27
-
-/* Expands to the number of OI_UINT32s needed to ensure enough memory to encode
- * or decode streams of numChannels channels, using numBuffers buffers.
- * Example:
- * OI_UINT32 decoderData[CODEC_DATA_WORDS(SBC_MAX_CHANNELS, SBC_DECODER_FAST_SYNTHESIS_BUFFERS)];
- * */
-#define CODEC_DATA_WORDS(numChannels, numBuffers)                                                                                                                                \
-    ((                                                                                                                                                                           \
-         (sizeof(OI_INT32) * SBC_MAX_BLOCKS * numChannels * SBC_MAX_BANDS) + (sizeof(SBC_BUFFER_T) * SBC_MAX_CHANNELS * SBC_MAX_BANDS * numBuffers) + (sizeof(OI_UINT32) - 1)) / \
-     sizeof(OI_UINT32))
-
-/** Opaque parameter to decoding functions; maintains decoder context. */
-typedef struct {
-    OI_CODEC_SBC_COMMON_CONTEXT common;
-    OI_UINT8 limitFrameFormat; /* Boolean, set by OI_CODEC_SBC_DecoderLimit() */
-    OI_UINT8 restrictSubbands;
-    OI_UINT8 enhancedEnabled;
-    OI_UINT8 bufferedBlocks;
-    OI_UINT8 sbc_mode; /* OI_SBC_MODE_STD or OI_SBC_MODE_MSBC */
-} OI_CODEC_SBC_DECODER_CONTEXT;
-
-typedef struct {
-    OI_UINT32 data[CODEC_DATA_WORDS(1, SBC_CODEC_FAST_FILTER_BUFFERS)];
-} OI_CODEC_SBC_CODEC_DATA_MONO;
-
-typedef struct {
-    OI_UINT32 data[CODEC_DATA_WORDS(2, SBC_CODEC_FAST_FILTER_BUFFERS)];
-} OI_CODEC_SBC_CODEC_DATA_STEREO;
-
-/**
-@}
-
-@addtogroup codec_lib
-@{
-*/
-
-/**
- * This function resets the decoder. The context must be reset when
- * changing streams, or if the following stream parameters change:
- * number of subbands, stereo mode, or frequency.
- *
- * @param context   Pointer to the decoder context structure to be reset.
- *
- * @param enhanced  If true, enhanced SBC operation is enabled. If enabled,
- *                  the codec will recognize the alternative syncword for
- *                  decoding an enhanced SBC stream. Enhancements should not
- *                  be enabled unless the stream is known to be generated
- *                  by an enhanced encoder, or there is a small possibility
- *                  for decoding glitches if synchronization were to be lost.
- */
-OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                    OI_UINT32 *decoderData,
-                                    OI_UINT32 decoderDataBytes,
-                                    OI_UINT8 maxChannels,
-                                    OI_UINT8 pcmStride,
-                                    OI_BOOL enhanced,
-                                    OI_BOOL msbc_enable);
-
-/**
- * This function restricts the kind of SBC frames that the Decoder will
- * process.  Its use is optional.  If used, it must be called after
- * calling OI_CODEC_SBC_DecoderReset(). After it is called, any calls
- * to OI_CODEC_SBC_DecodeFrame() with SBC frames that do not conform
- * to the Subband and Enhanced SBC setting will be rejected with an
- * OI_STATUS_INVALID_PARAMETERS return.
- *
- * @param context   Pointer to the decoder context structure to be limited.
- *
- * @param enhanced  If true, all frames passed to the decoder must be
- *                  Enhanced SBC frames. If false, all frames must be
- *                  standard SBC frames.
- *
- * @param subbands  May be set to SBC_SUBBANDS_4 or SBC_SUBBANDS_8. All
- *                  frames passed to the decoder must be encoded with
- *                  the requested number of subbands.
- *
- */
-OI_STATUS OI_CODEC_SBC_DecoderLimit(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                    OI_BOOL enhanced,
-                                    OI_UINT8 subbands);
-
-/**
- * This function sets the decoder parameters for a raw decode where the decoder parameters are not
- * available in the sbc data stream. OI_CODEC_SBC_DecoderReset must be called
- * prior to calling this function.
- *
- * @param context        Decoder context structure. This must be the context must be
- *                       used each time a frame is decoded.
- *
- * @param enhanced       Set to TRUE to enable Qualcomm proprietary
- *                       quality enhancements.
- *
- * @param frequency      One of SBC_FREQ_16000, SBC_FREQ_32000, SBC_FREQ_44100,
- *                       SBC_FREQ_48000
- *
- * @param mode           One of SBC_MONO, SBC_DUAL_CHANNEL, SBC_STEREO,
- *                       SBC_JOINT_STEREO
- *
- * @param subbands       One of SBC_SUBBANDS_4, SBC_SUBBANDS_8
- *
- * @param blocks         One of SBC_BLOCKS_4, SBC_BLOCKS_8, SBC_BLOCKS_12,
- *                       SBC_BLOCKS_16
- *
- * @param alloc          One of SBC_LOUDNESS, SBC_SNR
- *
- * @param maxBitpool     The maximum bitpool size for this context
- */
-OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                           OI_BOOL enhanced,
-                                           OI_UINT8 frequency,
-                                           OI_UINT8 mode,
-                                           OI_UINT8 subbands,
-                                           OI_UINT8 blocks,
-                                           OI_UINT8 alloc,
-                                           OI_UINT8 maxBitpool);
-
-/**
- * Decode one SBC frame. The frame has no header bytes. The context must have been previously
- * initialized by calling  OI_CODEC_SBC_DecoderConfigureRaw().
- *
- * @param context       Pointer to a decoder context structure. The same context
- *                      must be used each time when decoding from the same stream.
- *
- * @param bitpool       The actual bitpool size for this frame. Must be <= the maxbitpool specified
- *                      in the call to OI_CODEC_SBC_DecoderConfigureRaw(),
- *
- * @param frameData     Address of a pointer to the SBC data to decode. This
- *                      value will be updated to point to the next frame after
- *                      successful decoding.
- *
- * @param frameBytes    Pointer to a UINT32 containing the number of available
- *                      bytes of frame data. This value will be updated to reflect
- *                      the number of bytes remaining after a decoding operation.
- *
- * @param pcmData       Address of an array of OI_INT16 pairs, which will be
- *                      populated with the decoded audio data. This address
- *                      is not updated.
- *
- * @param pcmBytes      Pointer to a UINT32 in/out parameter. On input, it
- *                      should contain the number of bytes available for pcm
- *                      data. On output, it will contain the number of bytes
- *                      written. Note that this differs from the semantics of
- *                      frameBytes.
- */
-OI_STATUS OI_CODEC_SBC_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                 OI_UINT8 bitpool,
-                                 const OI_BYTE **frameData,
-                                 OI_UINT32 *frameBytes,
-                                 OI_INT16 *pcmData,
-                                 OI_UINT32 *pcmBytes);
-
-/**
- * Decode one SBC frame.
- *
- * @param context       Pointer to a decoder context structure. The same context
- *                      must be used each time when decoding from the same stream.
- *
- * @param frameData     Address of a pointer to the SBC data to decode. This
- *                      value will be updated to point to the next frame after
- *                      successful decoding.
- *
- * @param frameBytes    Pointer to a UINT32 containing the number of available
- *                      bytes of frame data. This value will be updated to reflect
- *                      the number of bytes remaining after a decoding operation.
- *
- * @param pcmData       Address of an array of OI_INT16 pairs, which will be
- *                      populated with the decoded audio data. This address
- *                      is not updated.
- *
- * @param pcmBytes      Pointer to a UINT32 in/out parameter. On input, it
- *                      should contain the number of bytes available for pcm
- *                      data. On output, it will contain the number of bytes
- *                      written. Note that this differs from the semantics of
- *                      frameBytes.
- */
-OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                   const OI_BYTE **frameData,
-                                   OI_UINT32 *frameBytes,
-                                   OI_INT16 *pcmData,
-                                   OI_UINT32 *pcmBytes);
-
-/**
- * Calculate the number of SBC frames but don't decode. CRC's are not checked,
- * but the Sync word is found prior to count calculation.
- *
- * @param frameData     Pointer to the SBC data.
- *
- * @param frameBytes    Number of bytes avaiable in the frameData buffer
- *
- */
-OI_UINT8 OI_CODEC_SBC_FrameCount(OI_BYTE *frameData,
-                                 OI_UINT32 frameBytes);
-
-/**
- * Analyze an SBC frame but don't do the decode.
- *
- * @param context       Pointer to a decoder context structure. The same context
- *                      must be used each time when decoding from the same stream.
- *
- * @param frameData     Address of a pointer to the SBC data to decode. This
- *                      value will be updated to point to the next frame after
- *                      successful decoding.
- *
- * @param frameBytes    Pointer to a UINT32 containing the number of available
- *                      bytes of frame data. This value will be updated to reflect
- *                      the number of bytes remaining after a decoding operation.
- *
- */
-OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                 const OI_BYTE **frameData,
-                                 OI_UINT32 *frameBytes);
-
-/* Common functions */
-
-/**
-  Calculate the frame length.
-
-  @param frame The frame whose length to calculate
-
-  @return the length of an individual encoded frame in
-  bytes
-  */
-OI_UINT16 OI_CODEC_SBC_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame);
-
-/**
- * Calculate the maximum bitpool size that fits within a given frame length.
- *
- * @param frame     The frame to calculate the bitpool size for
- * @param frameLen  The frame length to fit the bitpool to
- *
- * @return the maximum bitpool that will fit in the specified frame length
- */
-OI_UINT16 OI_CODEC_SBC_CalculateBitpool(OI_CODEC_SBC_FRAME_INFO *frame,
-                                        OI_UINT16 frameLen);
-
-/**
-  Calculate the bit rate.
-
-  @param frame The frame whose bit rate to calculate
-
-  @return the approximate bit rate in bits per second,
-  assuming that stream parameters are constant
-  */
-OI_UINT32 OI_CODEC_SBC_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame);
-
-/**
-  Calculate decoded audio data length for one frame.
-
-  @param frame The frame whose audio data length to calculate
-
-  @return length of decoded audio data for a
-  single frame, in bytes
-  */
-OI_UINT16 OI_CODEC_SBC_CalculatePcmBytes(OI_CODEC_SBC_COMMON_CONTEXT *common);
-
-/**
- * Get the codec version text.
- *
- * @return  pointer to text string containing codec version text
- *
- */
-OI_CHAR *OI_CODEC_Version(void);
-
-/**
-@}
-
-@addtogroup codec_internal
-@{
-*/
-
-extern const OI_CHAR *const OI_CODEC_SBC_FreqText[];
-extern const OI_CHAR *const OI_CODEC_SBC_ModeText[];
-extern const OI_CHAR *const OI_CODEC_SBC_SubbandsText[];
-extern const OI_CHAR *const OI_CODEC_SBC_BlocksText[];
-extern const OI_CHAR *const OI_CODEC_SBC_AllocText[];
-
-/**
-@}
-
-@addtogroup codec_lib
-@{
-*/
-
-#ifdef OI_DEBUG
-void OI_CODEC_SBC_DumpConfig(OI_CODEC_SBC_FRAME_INFO *frameInfo);
-#else
-#define OI_CODEC_SBC_DumpConfig(f)
-#endif
-
-/**
-@}
-*/
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _OI_CODEC_SBC_CORE_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_sbc_private.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_sbc_private.h
deleted file mode 100644
index 09b2efc66..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_sbc_private.h
+++ /dev/null
@@ -1,234 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_CODEC_SBC_PRIVATE_H
-#define _OI_CODEC_SBC_PRIVATE_H
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/**
-@file
-Function prototypes and macro definitions used internally by the codec.
-
-@ingroup codec_internal
-*/
-
-/**
-@addtogroup codec_internal
-@{
-*/
-
-#ifdef USE_RESTRICT_KEYWORD
-#define RESTRICT restrict
-#else
-#define RESTRICT
-#endif
-
-#ifdef CODEC_DEBUG
-#include 
-#define ERROR(x)       \
-    do {               \
-        BT_WARN x;     \
-        BT_WARN("\n"); \
-    } while (0)
-#else
-#define ERROR(x)
-#endif
-
-#ifdef TRACE_EXECUTION
-#define TRACE(x)       \
-    do {               \
-        BT_WARN x;     \
-        BT_WARN("\n"); \
-    } while (0)
-#else
-#define TRACE(x)
-#endif
-
-#ifndef PRIVATE
-#define PRIVATE
-#endif
-
-#ifndef INLINE
-#define INLINE
-#endif
-
-#include "oi_assert.h"
-#include "oi_codec_sbc.h"
-
-#ifndef OI_SBC_SYNCWORD
-#define OI_SBC_SYNCWORD 0x9c
-#endif
-
-#ifndef DIVIDE
-#define DIVIDE(a, b) ((a) / (b))
-#endif
-
-typedef union {
-    OI_UINT8 uint8[SBC_MAX_BANDS];
-    OI_UINT32 uint32[SBC_MAX_BANDS / 4];
-} BITNEED_UNION1;
-
-typedef union {
-    OI_UINT8 uint8[2 * SBC_MAX_BANDS];
-    OI_UINT32 uint32[2 * SBC_MAX_BANDS / 4];
-} BITNEED_UNION2;
-
-static const OI_UINT16 freq_values[] = { 16000, 32000, 44100, 48000 };
-static const OI_UINT8 block_values[] = { 4, 8, 12, 16 };
-static const OI_UINT8 channel_values[] = { 1, 2, 2, 2 };
-static const OI_UINT8 band_values[] = { 4, 8 };
-
-#define TEST_MODE_SENTINEL        "OINA"
-#define TEST_MODE_SENTINEL_LENGTH 4
-
-/** Used internally. */
-typedef struct {
-    union {
-        const OI_UINT8 *r;
-        OI_UINT8 *w;
-    } ptr;
-    OI_UINT32 value;
-    OI_UINT bitPtr;
-} OI_BITSTREAM;
-
-#define VALID_INT16(x) (((x) >= OI_INT16_MIN) && ((x) <= OI_INT16_MAX))
-#define VALID_INT32(x) (((x) >= OI_INT32_MIN) && ((x) <= OI_INT32_MAX))
-
-#define DCTII_8_SHIFT_IN  0
-#define DCTII_8_SHIFT_OUT 16 - DCTII_8_SHIFT_IN
-
-#define DCTII_8_SHIFT_0 (DCTII_8_SHIFT_OUT)
-#define DCTII_8_SHIFT_1 (DCTII_8_SHIFT_OUT)
-#define DCTII_8_SHIFT_2 (DCTII_8_SHIFT_OUT)
-#define DCTII_8_SHIFT_3 (DCTII_8_SHIFT_OUT)
-#define DCTII_8_SHIFT_4 (DCTII_8_SHIFT_OUT)
-#define DCTII_8_SHIFT_5 (DCTII_8_SHIFT_OUT)
-#define DCTII_8_SHIFT_6 (DCTII_8_SHIFT_OUT - 1)
-#define DCTII_8_SHIFT_7 (DCTII_8_SHIFT_OUT - 2)
-
-#define DCT_SHIFT 15
-
-#define DCTIII_4_SHIFT_IN  2
-#define DCTIII_4_SHIFT_OUT 15
-
-#define DCTIII_8_SHIFT_IN  3
-#define DCTIII_8_SHIFT_OUT 14
-
-OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                       OI_UINT8 *bitneeds,
-                       OI_UINT ch,
-                       OI_UINT *preferredBitpool);
-
-void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                             BITNEED_UNION1 *bitneeds,
-                             OI_UINT ch,
-                             OI_UINT bitcount);
-
-OI_INT adjustToFitBitpool(const OI_UINT bitpool,
-                          OI_UINT32 *bitneeds,
-                          const OI_UINT subbands,
-                          OI_UINT bitcount,
-                          OI_UINT *excess);
-
-OI_INT allocAdjustedBits(OI_UINT8 *dest,
-                         OI_INT bits,
-                         OI_INT excess);
-
-OI_INT allocExcessBits(OI_UINT8 *dest,
-                       OI_INT excess);
-
-PRIVATE OI_UINT32 internal_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO *frame);
-
-PRIVATE OI_UINT16 internal_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO *frame);
-
-void monoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *common);
-
-typedef void (*BIT_ALLOC)(OI_CODEC_SBC_COMMON_CONTEXT *common);
-
-PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                     OI_UINT8 bitpool,
-                                     const OI_BYTE **frameData,
-                                     OI_UINT32 *frameBytes,
-                                     OI_INT16 *pcmData,
-                                     OI_UINT32 *pcmBytes);
-
-OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT *context,
-                                OI_UINT32 *decoderData,
-                                OI_UINT32 decoderDataBytes,
-                                OI_BYTE maxChannels,
-                                OI_BYTE pcmStride,
-                                OI_BOOL enhanced,
-                                OI_BOOL msbc_enable);
-
-OI_UINT16 OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO *frame, OI_UINT *headerLen_);
-
-PRIVATE OI_UINT32 OI_SBC_MaxBitpool(OI_CODEC_SBC_FRAME_INFO *frame);
-
-PRIVATE void OI_SBC_ComputeBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT *frame);
-PRIVATE OI_UINT8 OI_SBC_CalculateChecksum(OI_CODEC_SBC_FRAME_INFO *frame, OI_BYTE const *data);
-
-/* Transform functions */
-PRIVATE void shift_buffer(SBC_BUFFER_T *dest, SBC_BUFFER_T *src, OI_UINT wordCount);
-PRIVATE void cosineModulateSynth4(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT in);
-PRIVATE void SynthWindow40_int32_int32_symmetry_with_sum(OI_INT16 *pcm, SBC_BUFFER_T buffer[80], OI_UINT strideShift);
-
-void dct3_4(OI_INT32 *RESTRICT out, OI_INT32 const *RESTRICT in);
-PRIVATE void analyze4_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 40],
-                                OI_INT16 *pcm,
-                                OI_UINT strideShift,
-                                OI_INT32 subband[4]);
-
-void dct3_8(OI_INT32 *RESTRICT out, OI_INT32 const *RESTRICT in);
-
-PRIVATE void analyze8_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 80],
-                                OI_INT16 *pcm,
-                                OI_UINT strideShift,
-                                OI_INT32 subband[8]);
-
-#ifdef SBC_ENHANCED
-PRIVATE void analyze8_enhanced_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 112],
-                                         OI_INT16 *pcm,
-                                         OI_UINT strideShift,
-                                         OI_INT32 subband[8]);
-#endif
-
-/* Decoder functions */
-
-void OI_SBC_ReadHeader(OI_CODEC_SBC_COMMON_CONTEXT *common, const OI_BYTE *data);
-PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT *common, const OI_BYTE *b, OI_BITSTREAM *bs);
-PRIVATE void OI_SBC_ReadSamples(OI_CODEC_SBC_DECODER_CONTEXT *common, OI_BITSTREAM *ob);
-PRIVATE void OI_SBC_ReadSamplesJoint(OI_CODEC_SBC_DECODER_CONTEXT *common, OI_BITSTREAM *global_bs);
-PRIVATE void OI_SBC_SynthFrame(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT start_block, OI_UINT nrof_blocks);
-OI_INT32 OI_SBC_Dequant(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits);
-PRIVATE OI_BOOL OI_SBC_ExamineCommandPacket(OI_CODEC_SBC_DECODER_CONTEXT *context, const OI_BYTE *data, OI_UINT32 len);
-PRIVATE void OI_SBC_GenerateTestSignal(OI_INT16 pcmData[][2], OI_UINT32 sampleCount);
-
-PRIVATE void OI_SBC_ExpandFrameFields(OI_CODEC_SBC_FRAME_INFO *frame);
-PRIVATE OI_STATUS OI_CODEC_SBC_Alloc(OI_CODEC_SBC_COMMON_CONTEXT *common,
-                                     OI_UINT32 *codecDataAligned,
-                                     OI_UINT32 codecDataBytes,
-                                     OI_UINT8 maxChannels,
-                                     OI_UINT8 pcmStride);
-/**
-@}
-*/
-
-#endif /* _OI_CODEC_SBC_PRIVATE_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_version.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_version.c
deleted file mode 100644
index 697ef102f..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_codec_version.c
+++ /dev/null
@@ -1,60 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**
-@file
-This file contains a single function, which returns a string indicating the
-version number of the eSBC codec
-
-@ingroup codec_internal
-*/
-
-/**
-@addtogroup codec_internal
-@{
-*/
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-#include "oi_stddefs.h"
-#include "oi_codec_sbc_private.h"
-
-#if defined(SBC_DEC_INCLUDED)
-/** Version string for the BLUEmagic 3.0 protocol stack and profiles */
-PRIVATE OI_CHAR *const codecVersion = "v1.5"
-#ifdef OI_SBC_EVAL
-                                      " (Evaluation version)"
-#endif
-    ;
-
-/** This function returns the version string for the BLUEmagic 3.0 protocol stack
-    and profiles */
-OI_CHAR *OI_CODEC_Version(void)
-{
-    return codecVersion;
-}
-
-/**********************************************************************************/
-
-/**
-@}
-*/
-
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_common.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_common.h
deleted file mode 100644
index 39eda8f7e..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_common.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_COMMON_H
-#define _OI_COMMON_H
-/**
- * @file
- *
- * This file is used to group commonly used BLUEmagic 3.0 software
- * header files.
- *
- * This file should be included in application source code along with the header
- * files for the specific modules of the protocol stack being used.
- */
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-#include "oi_bt_spec.h"
-#include "oi_stddefs.h"
-#include "oi_status.h"
-#include "oi_time.h"
-#include "oi_osinterface.h"
-
-/*****************************************************************************/
-#endif /* _OI_COMMON_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_cpu_dep.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_cpu_dep.h
deleted file mode 100644
index 04d412663..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_cpu_dep.h
+++ /dev/null
@@ -1,498 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_CPU_DEP_H
-#define _OI_CPU_DEP_H
-/**
- * @file
- * This file contains definitions for characteristics of the target CPU and
- * compiler, including primitive data types and endianness.
- *
- * This file defines the byte order and primitive data types for various
- * CPU families. The preprocessor symbol 'CPU' must be defined to be an
- * appropriate value or this header will generate a compile-time error.
- *
- * @note The documentation for this header file uses the x86 family of processors
- * as an illustrative example for CPU/compiler-dependent data type definitions.
- * Go to the source code of this header file to see the details of primitive type
- * definitions for each platform.
- *
- * Additional information is available in the @ref data_types_docpage section.
- */
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/** \addtogroup Misc Miscellaneous APIs */
-/**@{*/
-
-/** @name Definitions indicating family of target OI_CPU_TYPE
- *  @{
- */
-
-#define OI_CPU_X86        1  /**< x86 processor family */
-#define OI_CPU_ARM        2  /**< ARM processor family.
-                                  @deprecated Use #OI_CPU_ARM7_LEND or
-                                  #OI_CPU_ARM7_BEND. */
-#define OI_CPU_ARC        3  /**< ARC processor family.
-                                  @deprecated Use #OI_CPU_ARC_LEND or
-                                  #OI_CPU_ARC_BEND. */
-#define OI_CPU_SH3        4  /**< Hitachi SH-3 processor family */
-#define OI_CPU_H8         5  /**< Hitachi H8 processor family */
-#define OI_CPU_MIPS       6  /**< MIPS processor family */
-#define OI_CPU_SPARC      7  /**< SPARC processor family */
-#define OI_CPU_M68000     8  /**< Motorola M68000 processor family */
-#define OI_CPU_PPC        9  /**< PowerPC (PPC) processor family */
-#define OI_CPU_SH4_7750   10 /**< Hitachi SH7750 series in SH-4 processor family */
-#define OI_CPU_SH2        11 /**< Hitachi SH-2 processor family */
-#define OI_CPU_ARM7_LEND  12 /**< ARM7, little-endian */
-#define OI_CPU_ARM7_BEND  13 /**< ARM7, big-endian */
-#define OI_CPU_GDM1202    14 /**< GCT GDM1202 */
-#define OI_CPU_ARC_LEND   15 /**< ARC processor family, little-endian */
-#define OI_CPU_ARC_BEND   16 /**< ARC processor family, big-endian */
-#define OI_CPU_M30833F    17 /**< Mitsubishi M308 processor family */
-#define OI_CPU_CR16C      18 /**< National Semiconductor 16 bit processor family */
-#define OI_CPU_M64111     19 /**< Renesas M64111 processor (M32R family) */
-#define OI_CPU_ARMV5_LEND 20 //*< ARM5, little-endian */
-
-#define OI_CPU_TYPE 12
-
-#ifndef OI_CPU_TYPE
-#error "OI_CPU_TYPE type not defined"
-#endif
-
-/**@}*/
-
-/** @name Definitions indicating byte-wise endianness of target CPU
- *  @{
- */
-
-#define OI_BIG_ENDIAN_BYTE_ORDER    0 /**< Multiple-byte values are stored in memory beginning with the most significant byte at the lowest address.  */
-#define OI_LITTLE_ENDIAN_BYTE_ORDER 1 /**< Multiple-byte values are stored in memory beginning with the least significant byte at the lowest address. */
-
-/**@}*/
-
-/** @name  CPU/compiler-independent primitive data type definitions
- *  @{
- */
-
-typedef int OI_BOOL;           /**< Boolean values use native integer data type for target CPU. */
-typedef int OI_INT;            /**< Integer values use native integer data type for target CPU. */
-typedef unsigned int OI_UINT;  /**< Unsigned integer values use native unsigned integer data type for target CPU. */
-typedef unsigned char OI_BYTE; /**< Raw bytes type uses native character data type for target CPU. */
-
-/**@}*/
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_X86
-
-#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER /**< x86 platform byte ordering is little-endian */
-
-/** @name CPU/compiler-dependent primitive data type definitions for x86 processor family
- *  @{
- */
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for x86 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for x86 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for x86 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for x86 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for x86 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for x86 processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_ARM
-/* This CPU type is deprecated (removed from use). Instead, use OI_CPU_ARM7_LEND or OI_CPU_ARM7_BEND for
-   little-endian or big-endian configurations of the ARM7, respectively. */
-#error OI_CPU_ARM is deprecated
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_ARC
-/* This CPU type is deprecated (removed from use). Instead, use OI_CPU_ARC_LEND or OI_CPU_ARC_BEND for
-   little-endian or big-endian configurations of the ARC, respectively. */
-#error OI_CPU_ARC is deprecated
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_SH3
-/* The Hitachi SH C compiler defines _LIT or _BIG, depending on the endianness
-    specified to the compiler on the command line. */
-#if defined(_LIT)
-#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER /**< If _LIT is defined, SH-3 platform byte ordering is little-endian. */
-#elif defined(_BIG)
-#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER /**< If _BIG is defined, SH-3 platform byte ordering is big-endian. */
-#else
-#error SH compiler endianness undefined
-#endif
-
-/** @name CPU/compiler-dependent primitive data type definitions for SH-3 processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for SH-3 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for SH-3 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for SH-3 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for SH-3 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for SH-3 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for SH-3 processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-
-#endif
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_SH2
-
-#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER /**< SH-2 platform byte ordering is big-endian. */
-
-/** @name  CPU/compiler-dependent primitive data type definitions for SH-2 processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for SH-2 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for SH-2 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for SH-2 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for SH-2 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for SH-2 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for SH-2 processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-
-#endif
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_H8
-#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER
-#error basic types not defined
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_MIPS
-#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER
-/** @name  CPU/compiler-dependent primitive data type definitions for MIPS processor family
- *  @{
- */
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for ARM7 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for ARM7 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for ARM7 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for ARM7 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARM7 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for ARM7 processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_SPARC
-#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER
-#error basic types not defined
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_M68000
-#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER /**< M68000 platform byte ordering is big-endian. */
-
-/** @name  CPU/compiler-dependent primitive data type definitions for M68000 processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for M68000 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for M68000 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for M68000 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for M68000 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for M68000 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for M68000 processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_PPC
-#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER
-
-/** @name  CPU/compiler-dependent primitive data type definitions for PPC 8XX processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for PPC8XX processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for PPC8XX processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for PPC8XX processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for PPC8XX processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for PPC8XX processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for PPC8XX processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_SH4_7750
-#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER /**< SH7750 platform byte ordering is big-endian. */
-
-/** @name   CPU/compiler-dependent primitive data type definitions for SH7750 processor series of the SH-4 processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for SH7750 SH-4 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for SH7750 SH-4 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for SH7750 SH-4 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for SH7750 SH-4 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for SH7750 SH-4 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for SH7750 SH-4 processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_ARM7_LEND
-#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER
-
-/** @name   little-endian CPU/compiler-dependent primitive data type definitions for the ARM7 processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for ARM7 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for ARM7 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for ARM7 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for ARM7 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARM7 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for ARM7 processor. */
-
-typedef void *OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_ARM7_BEND
-#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER
-/** @name   big-endian CPU/compiler-dependent primitive data type definitions for the ARM7 processor family
- *  @{
- */
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for ARM7 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for ARM7 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for ARM7 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for ARM7 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARM7 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for ARM7 processor. */
-
-typedef void *OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_GDM1202
-#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_ARC_LEND
-
-#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER
-
-/** @name CPU/compiler-dependent primitive data type definitions for ARC processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for ARC processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for ARC processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for ARC processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for ARC processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARC processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for ARC processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_ARC_BEND
-
-#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER
-
-/** @name CPU/compiler-dependent primitive data type definitions for ARC processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for ARC processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for ARC processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for ARC processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for ARC processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARC processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for ARC processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_M30833F
-
-#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER
-
-/** @name CPU/compiler-dependent primitive data type definitions for Mitsubishi M308 processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for M308 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for M308 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for M308 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for M308 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for M308 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for M308 processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_CR16C
-
-#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER
-
-/** @name CPU/compiler-dependent primitive data type definitions for National Semicnductor processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for CR16C processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for CR16C processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for CR16C processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for CR16C processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for CR16C processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for CR16C processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_M64111
-
-#define OI_CPU_BYTE_ORDER OI_BIG_ENDIAN_BYTE_ORDER
-
-/** @name CPU/compiler-dependent primitive data type definitions for Renesas M32R processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for M64111 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for M64111 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for M64111 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for M64111 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for M64111 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for M64111 processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-#endif
-
-/*********************************************************************************/
-
-#if OI_CPU_TYPE == OI_CPU_ARMV5_LEND
-#define OI_CPU_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER
-
-/** @name   little-endian CPU/compiler-dependent primitive data type definitions for the ARM7 processor family
- *  @{
- */
-
-typedef signed char OI_INT8;      /**< 8-bit signed integer values use native signed character data type for ARM7 processor. */
-typedef signed short OI_INT16;    /**< 16-bit signed integer values use native signed short integer data type for ARM7 processor. */
-typedef signed long OI_INT32;     /**< 32-bit signed integer values use native signed long integer data type for ARM7 processor. */
-typedef unsigned char OI_UINT8;   /**< 8-bit unsigned integer values use native unsigned character data type for ARM7 processor. */
-typedef unsigned short OI_UINT16; /**< 16-bit unsigned integer values use native unsigned short integer data type for ARM7 processor. */
-typedef unsigned long OI_UINT32;  /**< 32-bit unsigned integer values use native unsigned long integer data type for ARM7 processor. */
-
-typedef OI_UINT32 OI_ELEMENT_UNION; /**< Type for first element of a union to support all data types up to pointer width. */
-
-/**@}*/
-
-#endif
-
-/*********************************************************************************/
-
-#ifndef OI_CPU_BYTE_ORDER
-#error "Byte order (endian-ness) not defined"
-#endif
-
-/**@}*/
-
-#ifdef __cplusplus
-}
-#endif
-
-/*********************************************************************************/
-#endif /* _OI_CPU_DEP_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_modules.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_modules.h
deleted file mode 100644
index 90e998ce4..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_modules.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_MODULES_H
-#define _OI_MODULES_H
-/**
- * @file
- *
- * Enumeration type defining the inidivual stack components.
- *
- */
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/** \addtogroup Misc Miscellaneous APIs */
-/**@{*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * This enumeration lists constants for referencing the components of
- * the BLUEmagic 3.0 protocol stack, profiles, and other functionalities.
- *
- * In order to distinguish types of modules, items are grouped with markers to
- * delineate start and end of the groups
- *
- * The module type is used for various purposes:
- *      identification in debug print statements
- *      access to initialization flags
- *      access to the configuration table
- */
-
-typedef enum {
-    /* profiles and protocols  --> Updates to oi_debug.c and oi_config_table.c */
-
-    /*   XX --> Keep Enum values up-to-date! */
-    OI_MODULE_AT,           /**< 00 AT command processing */
-    OI_MODULE_A2DP,         /**< 01 Advanced Audio Distribution Profile */
-    OI_MODULE_AVCTP,        /**< 02 Audio-Visual Control Transport Profile */
-    OI_MODULE_AVDTP,        /**< 03 Audio-Visual Distribution Protocol */
-    OI_MODULE_AVRCP,        /**< 04 Audio-Visual Remote Control Profile */
-    OI_MODULE_BIP_CLI,      /**< 05 Basic Imaging Profile protocol client */
-    OI_MODULE_BIP_SRV,      /**< 06 Basic Imaging Profile protocol server */
-    OI_MODULE_BNEP,         /**< 07 Bluetooth Network Encapsulation Protocol */
-    OI_MODULE_BPP_SENDER,   /**< 08 Basic Printing Profile */
-    OI_MODULE_BPP_PRINTER,  /**< 09 Basic Printing Profile */
-    OI_MODULE_CTP,          /**< 10 Cordless Telephony Profile */
-    OI_MODULE_DUN,          /**< 11 Dial-Up Networking Profile */
-    OI_MODULE_FAX,          /**< 12 Fax Profile */
-    OI_MODULE_FTP_CLI,      /**< 13 File Transfer Profile protocol client */
-    OI_MODULE_FTP_SRV,      /**< 14 File Transfer Profile protocol server */
-    OI_MODULE_HANDSFREE,    /**< 15 Hands-Free Profile */
-    OI_MODULE_HANDSFREE_AG, /**< 16 Hands-Free Profile */
-    OI_MODULE_HCRP_CLI,     /**< 17 Hardcopy Cable Replacement Profile */
-    OI_MODULE_HCRP_SRV,     /**< 18 Hardcopy Cable Replacement Profile */
-    OI_MODULE_HEADSET,      /**< 19 Headset Profile */
-    OI_MODULE_HEADSET_AG,   /**< 20 Headset Profile */
-    OI_MODULE_HID,          /**< 21 Human Interface Device profile */
-    OI_MODULE_INTERCOM,     /**< 22 Intercom Profile */
-    OI_MODULE_OBEX_CLI,     /**< 23 OBEX protocol client, Generic Object Exchange Profile */
-    OI_MODULE_OBEX_SRV,     /**< 24 OBEX protocol server, Generic Object Exchange Profile */
-    OI_MODULE_OPP_CLI,      /**< 25 Object Push Profile protocol client */
-    OI_MODULE_OPP_SRV,      /**< 26 Object Push Profile protocol server */
-    OI_MODULE_PAN,          /**< 27 PAN profile */
-    OI_MODULE_PBAP_CLI,     /**< 28 Phonebook Access Profile client */
-    OI_MODULE_PBAP_SRV,     /**< 29 Phonebook Access Profile server */
-    OI_MODULE_SAP_CLI,      /**< 30 SIM Access Profile */
-    OI_MODULE_SAP_SRV,      /**< 31 SIM Access Profile */
-    OI_MODULE_SPP,          /**< 32 Serial Port Profile */
-    OI_MODULE_SYNC_CLI,     /**< 33 Synchronization Profile */
-    OI_MODULE_SYNC_SRV,     /**< 34 Synchronization Profile */
-    OI_MODULE_SYNC_CMD_CLI, /**< 35 Synchronization Profile */
-    OI_MODULE_SYNC_CMD_SRV, /**< 36 Synchronization Profile */
-    OI_MODULE_SYNCML,       /**< 37 SyncML Profile */
-    OI_MODULE_TCS,          /**< 38 TCS Binary */
-    OI_MODULE_VDP,          /**< 39 Video Distribution Profile */
-
-    /* corestack components   --> Updates to oi_debug.c and oi_config_table.c */
-
-    OI_MODULE_COMMON_CONFIG, /**< 40 Common configuration, module has no meaning other than for config struct */
-    OI_MODULE_CMDCHAIN,      /**< 41 Command chaining utility */
-    OI_MODULE_DISPATCH,      /**< 42 Dispatcher */
-    OI_MODULE_DATAELEM,      /**< 43 Data Elements, marshaller */
-    OI_MODULE_DEVMGR,        /**< 44 Device Manager */
-    OI_MODULE_DEVMGR_MODES,  /**< 45 Device Manager connectability/discoverability modes */
-    OI_MODULE_HCI,           /**< 46 Host Controller Interface command layer */
-    OI_MODULE_L2CAP,         /**< 47 L2CAP */
-    OI_MODULE_MEMMGR,        /**< 48 modules that do memory management */
-    OI_MODULE_POLICYMGR,     /**< 49 Policy Manager */
-    OI_MODULE_RFCOMM,        /**< 50 RFCOMM */
-    OI_MODULE_RFCOMM_SD,     /**< 51 RFCOMM Service discovery */
-    OI_MODULE_SDP_CLI,       /**< 52 Service Discovery Protocol client */
-    OI_MODULE_SDP_SRV,       /**< 53 Service Discovery Protocol server */
-    OI_MODULE_SDPDB,         /**< 54 Service Discovery Protocol database */
-    OI_MODULE_SECMGR,        /**< 55 Security Manager */
-    OI_MODULE_SNIFFLOG,      /**< 56 sniff log */
-    OI_MODULE_SUPPORT,       /**< 57 support functions, including CThru Dispatcher, time functions, and stack initialization */
-    OI_MODULE_TRANSPORT,     /**< 58 transport layer between HCI command layer and driver */
-    OI_MODULE_TEST,          /**< 59 used to debug output from internal test programs */
-    OI_MODULE_XML,           /**< 60 XML/CSS parser */
-
-    OI_MODULE_DI, /**< 61 Device Identification Profile */
-
-    // bhapi components  --> Updates to oi_debug.c
-
-    OI_MODULE_BHAPI,           /**< 62 BLUEmagic Host API generic */
-    OI_MODULE_BHCLI,           /**< 63 BLUEmagic Host API client side */
-    OI_MODULE_BHSRV,           /**< 64 BLUEmagic Host API server side */
-    OI_MODULE_MSGQ,            /**< 65 module that handles message queuing */
-    OI_MODULE_BHAPI_TRANSPORT, /**< 66 module that handles message queuing */
-    OI_MODULE_BLST_SRV,        /**< 67 module that provides server side BHAPI Lightweight Serial Transport */
-    OI_MODULE_BLST_CLI,        /**< 68 module that provides client side BHAPI Lightweight Serial Transport */
-
-    // OEM files --> Updates to oi_debug.c
-    OI_MODULE_OEM, /**< 69 Application Memory allocation */
-
-    // Application glue --> Updates to oi_debug.c
-    OI_MODULE_APP, /**< 70 Application Memory allocation */
-
-    /* various pieces of code depend on these last 2 elements occuring in a specific order:
-       OI_MODULE_ALL must be the 2nd to last element
-       OI_MODULE_UNKNOWN must be the last element
-       */
-    OI_MODULE_ALL,    /**< 71 special value identifying all modules - used for control of debug print statements */
-    OI_MODULE_UNKNOWN /**< 72 special value - used for debug print statements */
-} OI_MODULE;
-
-/**
- * This constant is the number of actual modules in the list.  ALL and UNKNOWN are
- * special values that are not actually modules.
- * Used for debug print and memmgr profiling
- */
-#define OI_NUM_MODULES OI_MODULE_ALL
-
-/**
- * This constant is the number of profile and core components.  It is used to size
- * the initialization and configuration tables.
- */
-#define OI_NUM_STACK_MODULES OI_MODULE_BHAPI
-
-#ifdef __cplusplus
-}
-#endif
-
-/**@}*/
-
-#endif /* _OI_MODULES_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_osinterface.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_osinterface.h
deleted file mode 100644
index dfd425a90..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_osinterface.h
+++ /dev/null
@@ -1,196 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_OSINTERFACE_H
-#define _OI_OSINTERFACE_H
-/**
- @file
- * This file provides the platform-independent interface for functions for which
- * implementation is platform-specific.
- *
- * The functions in this header file define the operating system or hardware
- * services needed by the BLUEmagic 3.0 protocol stack. The
- * actual implementation of these services is platform-dependent.
- *
- */
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-#include "oi_stddefs.h"
-#include "oi_time.h"
-#include "oi_status.h"
-#include "oi_modules.h"
-
-/** \addtogroup Misc Miscellaneous APIs */
-/**@{*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Terminates execution.
- *
- * @param reason  Reason for termination
- */
-void OI_FatalError(OI_STATUS reason);
-
-/**
- * This function logs an error.
- *
- * When built for release mode, BLUEmagic 3 errors are logged to
- * this function. (in debug mode, errors are logged via
- * OI_Print()).
- *
- * @param module Module in which the error was detected (see
- *                oi_modules.h)
- * @param lineno Line number of the C file OI_SLOG_ERROR called
- * @param status Status code associated with the error event
- */
-void OI_LogError(OI_MODULE module, OI_INT lineno, OI_STATUS status);
-
-/**
- * This function initializes the debug code handling.
- *
- * When built for debug mode, this function performs platform
- * dependent initialization to handle message codes passed in
- * via OI_SetMsgCode().
- */
-void OI_InitDebugCodeHandler(void);
-
-/**
- * This function reads the time from the real time clock.
- *
- * All timing in BM3 is relative, typically a granularity
- * of 5 or 10 msecs is adequate.
- *
- * @param[out] now  Pointer to the buffer to which the current
- *       time will be returned
- */
-void OI_Time_Now(OI_TIME *now);
-
-/**
- * This function causes the current thread to sleep for the
- * specified amount of time. This function must be called
- * without the stack access token.
- *
- * @note BM3 corestack and profiles never suspend and never call
- * OI_Sleep. The use of OI_Sleep is limited to applications and
- * platform-specific code.
- *
- * If your port and applications never use OI_Sleep, this function can be left unimplemented.
- *
- * @param milliseconds  Number of milliseconds to sleep
- */
-void OI_Sleep(OI_UINT32 milliseconds);
-
-/**
- * Defines for message type codes.
- */
-#define OI_MSG_CODE_APPLICATION 0 /**< Application output */
-#define OI_MSG_CODE_ERROR       1 /**< Error message output */
-#define OI_MSG_CODE_WARNING     2 /**< Warning message output */
-#define OI_MSG_CODE_TRACE       3 /**< User API function trace output */
-#define OI_MSG_CODE_PRINT1      4 /**< Catagory 1 debug print output */
-#define OI_MSG_CODE_PRINT2      5 /**< Catagory 2 debug print output */
-#define OI_MSG_CODE_HEADER      6 /**< Error/Debug output header */
-
-/**
- * This function is used to indicate the type of text being output with
- * OI_Print(). For the Linux and Win32 platforms, it will set
- * the color of the text. Other possible uses could be to insert
- * HTML style tags, add some other message type indication, or
- * be completely ignored altogether.
- *
- * @param code  OI_MSG_CODE_* indicating setting the message type.
- */
-void OI_SetMsgCode(OI_UINT8 code);
-
-/**
- * All output from OI_Printf() and all debug output is sent to OI_Print.
- * Typically, if the platform has a console, OI_Print() is sent to stdout.
- * Embedded platforms typically send OI_Print() output to a serial port.
- *
- * @param str  String to print
- */
-void OI_Print(OI_CHAR const *str);
-
-/**
- *  In cases where OI_Print() is sending output to a logfile in addition to console,
- *  it is desirable to also put console input into the logfile.
- *  This function can be called by the console input process.
- *
- *  @note This is an optional API which is strictly
- *  between the platform-specific stack_console and osinterface
- *  modules. This API need only be implemented on those
- *  platforms where is serves a useful purpose, e.g., win32.
- *
- * @param str  Console input string
- */
-
-void OI_Print_ConsoleInput(OI_CHAR const *str);
-
-/**
- *  This function computes the CRC16 of the program image.
- */
-OI_UINT16 OI_ProgramImageCRC16(void);
-
-/**
- * Writes an integer to stdout in hex. This macro is intended
- * for selective use when debugging in small memory
- * configurations or other times when it is not possible to use
- * OI_DBGPRINT.
- *
- * @param n  the integer to print
- */
-
-#define OI_Print_Int(n)                                      \
-    {                                                        \
-        static const OI_CHAR _digits[] = "0123456789ABCDEF"; \
-        OI_CHAR _buf[9];                                     \
-        OI_CHAR *_str = &_buf[8];                            \
-        OI_UINT32 _i = n;                                    \
-        *_str = 0;                                           \
-        do {                                                 \
-            *(--_str) = _digits[(_i & 0xF)];                 \
-            _i >>= 4;                                        \
-        } while (_i);                                        \
-        OI_Print(_str);                                      \
-    }
-
-/**
- *  Application Dynamic Memory allocation.
- *
- *  These APIs are provided for application use on those
- *  platforms which have no dynamic memory support. Memory is
- *  allocated from the pool-based heap managed by the stack's
- *  internal memory manager.
- */
-void *OI_APP_Malloc(OI_INT32 size);
-void OI_APP_Free(void *ptr);
-
-/*****************************************************************************/
-#ifdef __cplusplus
-}
-#endif
-
-/**@}*/
-
-#endif /* _OI_OSINTERFACE_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_status.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_status.h
deleted file mode 100644
index b2a397954..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_status.h
+++ /dev/null
@@ -1,572 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_STATUS_H
-#define _OI_STATUS_H
-/**
- * @file
- * This file contains status codes for BLUEmagic 3.0 software.
- */
-
-#include "oi_stddefs.h"
-
-/** \addtogroup Misc Miscellaneous APIs */
-/**@{*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/** test it **/
-
-/**
- * OI_STATUS must fit in 16 bits, so status codes can range from 0 to 66535, inclusive.
- */
-
-typedef enum {
-    OI_STATUS_SUCCESS = 0,                  /**< function call succeeded alias for #OI_OK */
-    OI_OK = 0,                              /**< function call succeeded alias for #OI_STATUS_SUCCESS */
-    OI_STATUS_INVALID_PARAMETERS = 101,     /**< invalid function input parameters */
-    OI_STATUS_NOT_IMPLEMENTED = 102,        /**< attempt to use an unimplemented function */
-    OI_STATUS_NOT_INITIALIZED = 103,        /**< data not initialized */
-    OI_STATUS_NO_RESOURCES = 104,           /**< generic resource allocation failure status */
-    OI_STATUS_INTERNAL_ERROR = 105,         /**< internal inconsistency */
-    OI_STATUS_OUT_OF_MEMORY = 106,          /**< generally, OI_Malloc failed */
-    OI_ILLEGAL_REENTRANT_CALL = 107,        /**< violation of non-reentrant module policy */
-    OI_STATUS_INITIALIZATION_FAILED = 108,  /**< module initialization failed */
-    OI_STATUS_INITIALIZATION_PENDING = 109, /**< inititialization not yet complete */
-    OI_STATUS_NO_SCO_SUPPORT = 110,         /**< SCO operation rejected; system not configured for SCO */
-    OI_STATUS_OUT_OF_STATIC_MEMORY = 111,   /**< static malloc failed */
-    OI_TIMEOUT = 112,                       /**< generic timeout */
-    OI_OS_ERROR = 113,                      /**< some operating system error */
-    OI_FAIL = 114,                          /**< generic failure */
-    OI_STRING_FORMAT_ERROR = 115,           /**< error in VarString formatting string */
-    OI_STATUS_PENDING = 116,                /**< The operation is pending. */
-    OI_STATUS_INVALID_COMMAND = 117,        /**< The command was invalid. */
-    OI_BUSY_FAIL = 118,                     /**< command rejected due to busy */
-    OI_STATUS_ALREADY_REGISTERED = 119,     /**< The registration has already been performed. */
-    OI_STATUS_NOT_FOUND = 120,              /**< The referenced resource was not found. */
-    OI_STATUS_NOT_REGISTERED = 121,         /**< not registered */
-    OI_STATUS_NOT_CONNECTED = 122,          /**< not connected */
-    OI_CALLBACK_FUNCTION_REQUIRED = 123,    /**< A callback function parameter was required. */
-    OI_STATUS_MBUF_OVERFLOW = 124,          /**< There is no room to add another buffer to an mbuf. */
-    OI_STATUS_MBUF_UNDERFLOW = 125,         /**< There was an attempt to pull too many bytes from an mbuf. */
-    OI_STATUS_CONNECTION_EXISTS = 126,      /**< connection exists */
-    OI_STATUS_NOT_CONFIGURED = 127,         /**< module not configured */
-    OI_LOWER_STACK_ERROR = 128,             /**< An error was reported by lower stack API. This is used for embedded platforms. */
-    OI_STATUS_RESET_IN_PROGRESS = 129,      /**< Request failed/rejected because we're busy resetting. */
-    OI_STATUS_ACCESS_DENIED = 130,          /**< Generic access denied error. */
-    OI_STATUS_DATA_ERROR = 131,             /**< Generic data error. */
-    OI_STATUS_INVALID_ROLE = 132,           /**< The requested role was invalid. */
-    OI_STATUS_ALREADY_CONNECTED = 133,      /**< The requested connection is already established. */
-    OI_STATUS_PARSE_ERROR = 134,            /**< Parse error */
-    OI_STATUS_END_OF_FILE = 135,            /**< End of file */
-    OI_STATUS_READ_ERROR = 136,             /**< Generic read error */
-    OI_STATUS_WRITE_ERROR = 137,            /**< Generic write error */
-    OI_STATUS_NEGOTIATION_FAILURE = 138,    /**< Error in negotiation */
-    OI_STATUS_READ_IN_PROGRESS = 139,       /**< A read is already in progress */
-    OI_STATUS_ALREADY_INITIALIZED = 140,    /**< Initialization has already been done */
-    OI_STATUS_STILL_CONNECTED = 141,        /**< The service cannot be shutdown because there are still active connections. */
-    OI_STATUS_MTU_EXCEEDED = 142,           /**< The packet is too big */
-    OI_STATUS_LINK_TERMINATED = 143,        /**< The link was terminated */
-    OI_STATUS_PIN_CODE_TOO_LONG = 144,      /**< Application gave us a pin code that is too long */
-    OI_STATUS_STILL_REGISTERED = 145,       /**< The service cannot be shutdown because there are still active registrations. */
-    OI_STATUS_SPEC_VIOLATION = 146,         /**< Some application behavior contrary to BT specifications */
-
-    OI_STATUS_PSM_ALREADY_REGISTERED = 402,  /**< L2CAP: The specified PSM has already been registered. */
-    OI_STATUS_INVALID_CID = 403,             /**< L2CAP: CID is invalid or no longer valid (connection terminated) */
-    OI_STATUS_CID_NOT_FOUND = 404,           /**< L2CAP: CID does not represent a current connection */
-    OI_STATUS_CHANNEL_NOT_FOUND = 406,       /**< L2CAP: CID does not represent a current connection */
-    OI_STATUS_PSM_NOT_FOUND = 407,           /**< L2CAP: PSM not found */
-    OI_STATUS_INVALID_STATE = 408,           /**< L2CAP: invalid state */
-    OI_STATUS_WRITE_IN_PROGRESS = 410,       /**< L2CAP: write in progress */
-    OI_STATUS_INVALID_PACKET = 411,          /**< L2CAP: invalid packet */
-    OI_STATUS_SEND_COMPLETE = 412,           /**< L2CAP: send is complete */
-    OI_STATUS_INVALID_HANDLE = 414,          /**< L2CAP: handle is invalid */
-    OI_STATUS_GROUP_FULL = 418,              /**< L2CAP: No more members can be added to the specified group. */
-    OI_STATUS_DEVICE_ALREADY_IN_GROUP = 423, /**< L2CAP: The device already exists in the group. */
-    OI_STATUS_DUPLICATE_GROUP = 425,         /**< L2CAP: attempt to add more than one group */
-    OI_STATUS_EMPTY_GROUP = 426,             /**< L2CAP: group is empty */
-    OI_STATUS_PACKET_NOT_FOUND = 427,        /**< L2CAP: packet not found */
-    OI_STATUS_BUFFER_TOO_SMALL = 428,        /**< L2CAP: The buffer size is too small. */
-    OI_STATUS_IDENTIFIER_NOT_FOUND = 429,    /**< L2CAP: identifier not found */
-
-    OI_L2CAP_DISCONNECT_LOWER_LAYER = 430,     /**< L2CAP: The lower level forced a disconnect. */
-    OI_L2CAP_DISCONNECT_REMOTE_REQUEST = 431,  /**< L2CAP: The remote device requested a disconnect. */
-    OI_L2CAP_GROUP_ADD_CONNECT_FAIL = 433,     /**< L2CAP: Group add connect faiL */
-    OI_L2CAP_GROUP_REMOVE_FAILURE = 434,       /**< L2CAP: Group remove failure */
-    OI_L2CAP_DATA_WRITE_ERROR_LINK_TERM = 435, /**< L2CAP: Data write error LINK_TERM */
-    OI_L2CAP_DISCONNECT_LOCAL_REQUEST = 436,   /**< L2CAP: Disconnect local request */
-
-    OI_L2CAP_CONNECT_TIMEOUT = 437,    /**< L2CAP: Connect timeout */
-    OI_L2CAP_DISCONNECT_TIMEOUT = 439, /**< L2CAP: Disconnect timeout */
-    OI_L2CAP_PING_TIMEOUT = 440,       /**< L2CAP: Ping timeout */
-    OI_L2CAP_GET_INFO_TIMEOUT = 441,   /**< L2CAP: Get info timeout */
-    OI_L2CAP_INVALID_ADDRESS = 444,    /**< L2CAP: Invalid address */
-    OI_L2CAP_CMD_REJECT_RCVD = 445,    /**< L2CAP: remote sent us 'command reject' response */
-
-    OI_L2CAP_CONNECT_BASE = 450,                 /**< L2CAP: Connect base */
-    OI_L2CAP_CONNECT_PENDING = 451,              /**< L2CAP: Connect pending */
-    OI_L2CAP_CONNECT_REFUSED_INVALID_PSM = 452,  /**< L2CAP: Connect refused invalid PSM */
-    OI_L2CAP_CONNECT_REFUSED_SECURITY = 453,     /**< L2CAP: Connect refused security */
-    OI_L2CAP_CONNECT_REFUSED_NO_RESOURCES = 454, /**< L2CAP: Connect refused no resources */
-
-    OI_L2CAP_CONFIG_BASE = 460,                    /**< L2CAP: Config base */
-    OI_L2CAP_CONFIG_FAIL_INVALID_PARAMETERS = 461, /**< L2CAP: Config fail invalid parameters */
-    OI_L2CAP_CONFIG_FAIL_NO_REASON = 462,          /**< L2CAP: Config fail no reason */
-    OI_L2CAP_CONFIG_FAIL_UNKNOWN_OPTIONS = 463,    /**< L2CAP: Config fail unknown options */
-
-    OI_L2CAP_GET_INFO_BASE = 470,          /**< L2CAP: Get info base */
-    OI_L2CAP_GET_INFO_NOT_SUPPORTED = 471, /**< L2CAP: Get info not supported */
-    OI_L2CAP_MTU_EXCEEDED = 472,           /**< L2CAP: The MTU of the channel was exceeded */
-    OI_L2CAP_INVALID_PSM = 482,            /**< L2CAP: Invalid PSM */
-    OI_L2CAP_INVALID_MTU = 483,            /**< L2CAP: Invalid MTU */
-    OI_L2CAP_INVALID_FLUSHTO = 484,        /**< L2CAP: Invalid flush timeout */
-
-    OI_HCI_NO_SUCH_CONNECTION = 601,      /**< HCI: caller specified a non-existent connection handle */
-    OI_HCI_CB_LIST_FULL = 603,            /**< HCI: callback list is full, cannot attempt to send command */
-    OI_HCI_EVENT_UNDERRUN = 605,          /**< HCI: parsing event packet, premature end-of-parameters */
-    OI_HCI_UNKNOWN_EVENT_CODE = 607,      /**< HCI: event received - event code is unknown */
-    OI_HCI_BAD_EVENT_PARM_LEN = 608,      /**< HCI: event - parameter length is incorrect */
-    OI_HCI_CMD_QUEUE_FULL = 611,          /**< HCI: command queue is full */
-    OI_HCI_SHORT_EVENT = 612,             /**< HCI: event received, missing event code and/or parm len */
-    OI_HCI_TRANSMIT_NOT_READY = 613,      /**< HCI: ACL/SCO transmit request failed - busy or no buffers available */
-    OI_HCI_ORPHAN_SENT_EVENT = 614,       /**< HCI: got spurious 'sent' event from transport layer */
-    OI_HCI_CMD_TABLE_ERROR = 615,         /**< HCI: inconsistency in the internal command table */
-    OI_HCI_UNKNOWN_CMD_ID = 616,          /**< HCI: HciApi Command - unknown command id */
-    OI_HCI_UNEXPECTED_EVENT = 619,        /**< HCI: event received which only occurs in response to our cmd */
-    OI_HCI_EVENT_TABLE_ERROR = 620,       /**< HCI: inconsistency in the internal event table */
-    OI_HCI_EXPECTED_EVENT_TIMOUT = 621,   /**< HCI: timed out waiting for an expected event */
-    OI_HCI_NO_CMD_DESC_FOR_OPCODE = 622,  /**< HCI: event opcode is not known */
-    OI_HCI_INVALID_OPCODE_ERROR = 623,    /**< HCI: command opcode is invalid */
-    OI_HCI_FLOW_CONTROL_DISABLED = 624,   /**< HCI: can not use host flow control APIs if disabled in configuration */
-    OI_HCI_TX_COMPLETE = 625,             /**< HCI: packet delivery to Host Controler complete */
-    OI_HCI_TX_ERROR = 626,                /**< HCI: failed to deliver packet to Host Controler */
-    OI_HCI_DEVICE_NOT_INITIALIZED = 627,  /**< HCI: commands from upper layers disallowed until device is up and running */
-    OI_HCI_UNSUPPORTED_COMMAND = 628,     /**< HCI: command requested is not supported by local device */
-    OI_HCI_PASSTHROUGH_ERROR = 629,       /**< HCI: Error processing passthrough command */
-    OI_HCI_PASSTHROUGH_ALREADY_SET = 630, /**< HCI: Passthrough mode already enabled */
-    OI_HCI_RESET_FAILURE = 631,           /**< HCI: failed to reset the device/baseband */
-    OI_HCI_TRANSPORT_RESET = 632,         /**< HCI: some operation failed because of a reset in the transport */
-    OI_HCIERR_HCIIFC_INIT_FAILURE = 633,  /**< HCI: failed to initialize transport layer interface */
-
-    OI_HCIERR_FIRST_ERROR_VALUE = 701,              /**< marker for first HCI protocol error */
-    OI_HCIERR_UNKNOWN_HCI_COMMAND = 701,            /**< HCI: protocol error 0x01 */
-    OI_HCIERR_NO_CONNECTION = 702,                  /**< HCI: protocol error 0x02 */
-    OI_HCIERR_HARDWARE_FAILURE = 703,               /**< HCI: protocol error 0x03 */
-    OI_HCIERR_PAGE_TIMEOUT = 704,                   /**< HCI: protocol error 0x04 */
-    OI_HCIERR_AUTHENTICATION_FAILURE = 705,         /**< HCI: protocol error 0x05 */
-    OI_HCIERR_KEY_MISSING = 706,                    /**< HCI: protocol error 0x06 */
-    OI_HCIERR_MEMORY_FULL = 707,                    /**< HCI: protocol error 0x07 */
-    OI_HCIERR_CONNECTION_TIMEOUT = 708,             /**< HCI: protocol error 0x08 */
-    OI_HCIERR_MAX_NUM_OF_CONNECTIONS = 709,         /**< HCI: protocol error 0x09 */
-    OI_HCIERR_MAX_NUM_OF_SCO_CONNECTIONS = 710,     /**< HCI: protocol error 0x0A */
-    OI_HCIERR_ACL_CONNECTION_ALREADY_EXISTS = 711,  /**< HCI: protocol error 0x0B */
-    OI_HCIERR_COMMAND_DISALLOWED = 712,             /**< HCI: protocol error 0x0C */
-    OI_HCIERR_HOST_REJECTED_RESOURCES = 713,        /**< HCI: protocol error 0x0D */
-    OI_HCIERR_HOST_REJECTED_SECURITY = 714,         /**< HCI: protocol error 0x0E */
-    OI_HCIERR_HOST_REJECTED_PERSONAL_DEVICE = 715,  /**< HCI: protocol error 0x0F */
-    OI_HCIERR_HOST_TIMEOUT = 716,                   /**< HCI: protocol error 0x10 */
-    OI_HCIERR_UNSUPPORTED = 717,                    /**< HCI: protocol error 0x11 */
-    OI_HCIERR_INVALID_PARAMETERS = 718,             /**< HCI: protocol error 0x12 */
-    OI_HCIERR_OTHER_END_USER_DISCONNECT = 719,      /**< HCI: protocol error 0x13 */
-    OI_HCIERR_OTHER_END_LOW_RESOURCES = 720,        /**< HCI: protocol error 0x14 */
-    OI_HCIERR_OTHER_END_POWERING_OFF = 721,         /**< HCI: protocol error 0x15 */
-    OI_HCIERR_CONNECTION_TERMINATED_LOCALLY = 722,  /**< HCI: protocol error 0x16 */
-    OI_HCIERR_REPEATED_ATTEMPTS = 723,              /**< HCI: protocol error 0x17 */
-    OI_HCIERR_PAIRING_NOT_ALLOWED = 724,            /**< HCI: protocol error 0x18 */
-    OI_HCIERR_UNKNOWN_LMP_PDU = 725,                /**< HCI: protocol error 0x19 */
-    OI_HCIERR_UNSUPPORTED_REMOTE_FEATURE = 726,     /**< HCI: protocol error 0x1A */
-    OI_HCIERR_SCO_OFFSET_REJECTED = 727,            /**< HCI: protocol error 0x1B */
-    OI_HCIERR_SCO_INTERVAL_REJECTED = 728,          /**< HCI: protocol error 0x1C */
-    OI_HCIERR_SCO_AIR_MODE_REJECTED = 729,          /**< HCI: protocol error 0x1D */
-    OI_HCIERR_INVALID_LMP_PARMS = 730,              /**< HCI: protocol error 0x1E */
-    OI_HCIERR_UNSPECIFIED_ERROR = 731,              /**< HCI: protocol error 0x1F */
-    OI_HCIERR_UNSUPPORTED_LMP_PARAMETERS = 732,     /**< HCI: protocol error 0x20 */
-    OI_HCIERR_ROLE_CHANGE_NOT_ALLOWED = 733,        /**< HCI: protocol error 0x21 */
-    OI_HCIERR_LMP_RESPONSE_TIMEOUT = 734,           /**< HCI: protocol error 0x22 */
-    OI_HCIERR_LMP_ERROR_TRANS_COLLISION = 735,      /**< HCI: protocol error 0x23 */
-    OI_HCIERR_LMP_PDU_NOT_ALLOWED = 736,            /**< HCI: protocol error 0x24 */
-    OI_HCIERR_ENCRYPTION_MODE_NOT_ACCEPTABLE = 737, /**< HCI: protocol error 0x25 */
-    OI_HCIERR_UNIT_KEY_USED = 738,                  /**< HCI: protocol error 0x26 */
-    OI_HCIERR_QOS_NOT_SUPPORTED = 739,              /**< HCI: protocol error 0x27 */
-    OI_HCIERR_INSTANT_PASSED = 740,                 /**< HCI: protocol error 0x28 */
-    OI_HCIERR_UNIT_KEY_PAIRING_UNSUPPORTED = 741,   /**< HCI: protocol error 0x29 */
-    OI_HCIERR_DIFFERENT_TRANS_COLLISION = 742,      /**< HCI: protocol error 0x2A */
-    OI_HCIERR_RESERVED_2B = 743,                    /**< HCI: protocol error 0x2B */
-    OI_HCIERR_QOS_UNACCEPTABLE_PARAMETER = 744,     /**< HCI: protocol error 0x2C */
-    OI_HCIERR_QOS_REJECTED = 745,                   /**< HCI: protocol error 0x2D */
-    OI_HCIERR_CHANNEL_CLASSIFICATION_NS = 746,      /**< HCI: protocol error 0x2E */
-    OI_HCIERR_INSUFFICIENT_SECURITY = 747,          /**< HCI: protocol error 0x2F */
-    OI_HCIERR_PARM_OUT_OF_MANDATORY_RANGE = 748,    /**< HCI: protocol error 0x30 */
-    OI_HCIERR_RESERVED_31 = 749,                    /**< HCI: protocol error 0x31 */
-    OI_HCIERR_ROLE_SWITCH_PENDING = 750,            /**< HCI: protocol error 0x32 */
-    OI_HCIERR_RESERVED_33 = 751,                    /**< HCI: protocol error 0x33 */
-    OI_HCIERR_RESERVED_SLOT_VIOLATION = 752,        /**< HCI: protocol error 0x34 */
-    OI_HCIERR_ROLE_SWITCH_FAILED = 753,             /**< HCI: protocol error 0x35 */
-    OI_HCIERR_EIR_TOO_LARGE = 754,                  /**< HCI: protocol error 0x36 */
-    OI_HCIERR_SSP_NOT_SUPPORTED_BY_HOST = 755,      /**< HCI: protocol error 0x37 */
-    OI_HCIERR_HOST_BUSY_PAIRING = 756,              /**< HCI: protocol error 0x38 */
-
-    OI_HCIERR_UNKNOWN_ERROR = 757,    /**< HCI: unknown error code */
-    OI_HCIERR_LAST_ERROR_VALUE = 757, /**< marker for last HCI protocol error */
-
-    OI_SDP_SPEC_ERROR = 800,                                        /**< SDP: Base error status for mapping OI_STATUS codes to SDP errors */
-    OI_SDP_INVALID_SERVICE_RECORD_HANDLE = (OI_SDP_SPEC_ERROR + 2), /**< SDP: protocol error Invalid Service Record Handle */
-    OI_SDP_INVALID_REQUEST_SYNTAX = (OI_SDP_SPEC_ERROR + 3),        /**< SDP: protocol error Invalid Request Syntax */
-    OI_SDP_INVALID_PDU_SIZE = (OI_SDP_SPEC_ERROR + 4),              /**< SDP: protocol error Invalid PDU Size */
-    OI_SDP_INVALID_CONTINUATION_STATE = (OI_SDP_SPEC_ERROR + 5),    /**< SDP: protocol error Invalid Continuation State */
-    OI_SDP_INSUFFICIENT_RESOURCES = (OI_SDP_SPEC_ERROR + 6),        /**< SDP: protocol error Insufficient Resources */
-    OI_SDP_ERROR = 807,                                             /**< SDP: server returned an error code */
-    OI_SDP_CORRUPT_DATA_ELEMENT = 808,                              /**< SDP: Invalid or corrupt data element representation */
-    OI_SDP_SERVER_NOT_CONNECTED = 810,                              /**< SDP: Attempt to disconnect from an unconnected server */
-    OI_SDP_ACCESS_DENIED = 811,                                     /**< SDP: Server denied access to server */
-    OI_SDP_ATTRIBUTES_OUT_OF_ORDER = 812,                           /**< SDP: Attributes in attribute list not in ascending order */
-    OI_SDP_DEVICE_DOES_NOT_SUPPORT_SDP = 813,                       /**< SDP: Tried to connect to a device that does not support SDP */
-    OI_SDP_NO_MORE_DATA = 815,                                      /**< SDP: Server does not have more continuation data */
-    OI_SDP_REQUEST_PARAMS_TOO_LONG = 816,                           /**< SDP: Parameters for a request exceed the L2CAP buffer size */
-    OI_SDP_REQUEST_PENDING = 817,                                   /**< SDP: Cannot make a request when another request is being processed */
-    OI_SDP_SERVER_CONNECT_FAILED = 819,                             /**< SDP: Failed attempt to connect to an SDP server */
-    OI_SDP_SERVER_TOO_MANY_CONNECTIONS = 821,                       /**< SDP: Exceeded maximum number of simultaneous server connections */
-    OI_SDP_NO_MATCHING_SERVICE_RECORD = 823,                        /**< SDP: No service record matched the UUID list */
-    OI_SDP_PARTIAL_RESPONSE = 824,                                  /**< SDP: Internal use only */
-    OI_SDP_ILLEGAL_ARGUMENT = 825,                                  /**< SDP: Illegal argument passed to an SDP function */
-    OI_SDP_ATTRIBUTE_NOT_FOUND = 826,                               /**< SDP: A requested attribute was not found in a service record */
-    OI_SDP_DATABASE_OUT_OF_RESOURCES = 827,                         /**< SDP: server database is out of memory */
-    OI_SDP_SHORT_PDU = 829,                                         /**< SDP: Not enough bytes in the packet */
-    OI_SDP_TRANSACTION_ID_MISMATCH = 830,                           /**< SDP: Transaction Id was not as expected */
-    OI_SDP_UNEXPECTED_RESPONSE_PDU_ID = 831,                        /**< SDP: Did not expect this response PDU */
-    OI_SDP_REQUEST_TIMEOUT = 832,                                   /**< SDP: Did not get a response within the timeout period */
-    OI_SDP_INVALID_RESPONSE_SYNTAX = 833,                           /**< SDP: Response is not correctly formatted */
-    OI_SDP_CONNECTION_TIMEOUT = 834,                                /**< SDP: Connection attempt timed out at a lower layer */
-    OI_SDP_RESPONSE_DATA_ERROR = 835,                               /**< SDP: Response to a service request appears to be corrupt */
-    OI_SDP_TOO_MANY_ATTRIBUTE_BYTES = 836,                          /**< SDP: Response contained more bytes than requested. */
-    OI_SDP_TOO_MANY_SERVICE_RECORDS = 837,                          /**< SDP: Response contained more service records than requested. */
-    OI_SDP_INVALID_CONNECTION_ID = 838,                             /**< SDP: Invalid connection ID in an SDP request */
-    OI_SDP_CANNOT_SET_ATTRIBUTE = 839,                              /**< SDP: Attempt to set a dynamic attribute value failed */
-    OI_SDP_BADLY_FORMED_ATTRIBUTE_VALUE = 840,                      /**< SDP: An attribute value has the wrong type or structure */
-    OI_SDP_NO_ATTRIBUTE_LIST_TO_REMOVE = 841,                       /**< SDP: Attempt to remove a non-existent attribute list from a service record */
-    OI_SDP_ATTRIBUTE_LIST_ALREADY_ADDED = 842,                      /**< SDP: An attribute list has already been added to the service record */
-    OI_SDP_DATA_ELEMENT_TRUNCATED = 843,                            /**< SDP: Data element truncated (too few bytes) */
-
-    OI_RFCOMM_WRITE_IN_PROGRESS = 901,          /**< RFCOMM: Write in progress */
-    OI_RFCOMM_INVALID_BAUDRATE = 903,           /**< RFCOMM: Invalid baudrate */
-    OI_RFCOMM_INVALID_DATABIT = 904,            /**< RFCOMM: Invalid databit */
-    OI_RFCOMM_INVALID_STOPBIT = 905,            /**< RFCOMM: Invalid stopbit */
-    OI_RFCOMM_INVALID_PARITY = 906,             /**< RFCOMM: Invalid parity */
-    OI_RFCOMM_INVALID_PARITYTYPE = 907,         /**< RFCOMM: Invalid paritytype */
-    OI_RFCOMM_INVALID_FLOWCONTROL = 908,        /**< RFCOMM: Invalid flowcontrol */
-    OI_RFCOMM_SESSION_EXISTS = 909,             /**< RFCOMM: Session exists */
-    OI_RFCOMM_INVALID_CHANNEL = 910,            /**< RFCOMM: Invalid channel */
-    OI_RFCOMM_DLCI_EXISTS = 911,                /**< RFCOMM: DLCI exists */
-    OI_RFCOMM_LINK_NOT_FOUND = 912,             /**< RFCOMM: Link not found */
-    OI_RFCOMM_REMOTE_REJECT = 913,              /**< RFCOMM: Remote reject */
-    OI_RFCOMM_TEST_IN_PROGRESS = 915,           /**< RFCOMM: Test in progress */
-    OI_RFCOMM_SESSION_NOT_FOUND = 916,          /**< RFCOMM: Session not found */
-    OI_RFCOMM_INVALID_PACKET = 917,             /**< RFCOMM: Invalid packet */
-    OI_RFCOMM_FRAMESIZE_EXCEEDED = 918,         /**< RFCOMM: Framesize exceeded */
-    OI_RFCOMM_INVALID_DLCI = 920,               /**< RFCOMM: Invalid dlci */
-    OI_RFCOMM_SERVER_NOT_REGISTERED = 921,      /**< RFCOMM: Server not registered */
-    OI_RFCOMM_CREDIT_ERROR = 922,               /**< RFCOMM: Credit error */
-    OI_RFCOMM_NO_CHANNEL_NUMBER = 923,          /**< RFCOMM: No channel number */
-    OI_RFCOMM_QUERY_IN_PROGRESS = 924,          /**< RFCOMM: Query in progress */
-    OI_RFCOMM_SESSION_SHUTDOWN = 925,           /**< RFCOMM: Session shutdown */
-    OI_RFCOMM_LOCAL_DEVICE_DISCONNECTED = 926,  /**< RFCOMM: Local device disconnected */
-    OI_RFCOMM_REMOTE_DEVICE_DISCONNECTED = 927, /**< RFCOMM: Remote device disconnected */
-    OI_RFCOMM_OUT_OF_SERVER_CHANNELS = 928,     /**< RFCOMM: Out of server channels */
-
-    OI_DISPATCH_INVALID_CB_HANDLE = 1001, /**< Dispatcher was handed an invalid callback handle */
-    OI_DISPATCH_TABLE_OVERFLOW = 1002,    /**< Dispatcher table is full */
-
-    OI_TEST_UNKNOWN_TEST = 1101, /**< TEST: Unknown test */
-    OI_TEST_FAIL = 1102,         /**< TEST: Fail */
-
-    OI_HCITRANS_CANNOT_CONNECT_TO_DEVICE = 1201, /**< TRANSPORT: Cannot connect to device */
-    OI_HCITRANS_BUFFER_TOO_SMALL = 1203,         /**< TRANSPORT: Buffer too small */
-    OI_HCITRANS_NULL_DEVICE_HANDLE = 1204,       /**< TRANSPORT: Null device handle */
-    OI_HCITRANS_IO_ERROR = 1205,                 /**< TRANSPORT: IO error */
-    OI_HCITRANS_DEVICE_NOT_READY = 1206,         /**< TRANSPORT: Device not ready */
-    OI_HCITRANS_FUNCTION_NOT_SUPPORTED = 1207,   /**< TRANSPORT: Function not supporteD */
-    OI_HCITRANS_ACCESS_DENIED = 1209,            /**< TRANSPORT: win32 */
-    OI_HCITRANS_ACL_DATA_ERROR = 1210,           /**< TRANSPORT: ACL data error */
-    OI_HCITRANS_SCO_DATA_ERROR = 1211,           /**< TRANSPORT: SCO data error */
-    OI_HCITRANS_EVENT_DATA_ERROR = 1212,         /**< TRANSPORT: HCI event data error */
-    OI_HCITRANS_INTERNAL_ERROR = 1214,           /**< TRANSPORT: Internal error in the transport */
-    OI_HCITRANS_LINK_NOT_ACTIVE = 1215,          /**< TRANSPORT: Link to the device is not currently active */
-    OI_HCITRANS_INITIALIZING = 1216,             /**< TRANSPORT: Transport is initializing */
-
-    OI_DEVMGR_NO_CONNECTION = 1301,                /**< DEVMGR: No connection */
-    OI_DEVMGR_HARDWARE_ERROR = 1305,               /**< DEVMGR: error reported by HCI */
-    OI_DEVMGR_PENDING_CONNECT_LIST_FULL = 1307,    /**< DEVMGR: Pending connect list full */
-    OI_DEVMGR_CONNECTION_LIST_FULL = 1309,         /**< DEVMGR: Connection list full */
-    OI_DEVMGR_NO_SUCH_CONNECTION = 1310,           /**< DEVMGR: No such connection */
-    OI_DEVMGR_INQUIRY_IN_PROGRESS = 1311,          /**< DEVMGR: Inquiry in progress */
-    OI_DEVMGR_PERIODIC_INQUIRY_ACTIVE = 1312,      /**< DEVMGR: Periodic inquiry active */
-    OI_DEVMGR_NO_INQUIRIES_ACTIVE = 1313,          /**< DEVMGR: can not cancel/exit if not active */
-    OI_DEVMGR_DUPLICATE_CONNECTION = 1314,         /**< DEVMGR: internal error */
-    OI_DEVMGR_DUPLICATE_EVENT_CALLBACK = 1316,     /**< DEVMGR: attempt to register same callback twice */
-    OI_DEVMGR_EVENT_CALLBACK_LIST_FULL = 1317,     /**< DEVMGR: can not register event callback, list is full */
-    OI_DEVMGR_EVENT_CALLBACK_NOT_FOUND = 1318,     /**< DEVMGR: attempt to unregister callback failed */
-    OI_DEVMGR_BUSY = 1319,                         /**< DEVMGR: some operations can only execute one at a time */
-    OI_DEVMGR_ENUM_UNEXPECTED_INQ_COMPLETE = 1320, /**< DEVMGR: inquiry complete event in inappropriate enumeration state */
-    OI_DEVMGR_ENUM_UNEXPECTED_INQ_RESULT = 1321,   /**< DEVMGR: inquiry result event in inappropriate enumeration state */
-    OI_DEVMGR_ENUM_DATABASE_FULL = 1322,           /**< DEVMGR: device enumeration, database is full, couldn't add a new device */
-    OI_DEVMGR_ENUM_INQUIRIES_OVERLAP = 1323,       /**< DEVMGR: device enumeration, periodic inquiries occurring too close together */
-    OI_DEVMGR_UNKNOWN_LINK_TYPE = 1324,            /**< DEVMGR: HCI connect request with unkown link type */
-    OI_DEVMGR_PARAM_IO_ACTIVE = 1325,              /**< DEVMGR: request for parameter read/write while param read/write active */
-    OI_DEVMGR_UNKNOWN_IAC_LAP = 1326,              /**< DEVMGR: unrecognized IAC LAP */
-    OI_DEVMGR_SCO_ALREADY_REGISTERED = 1327,       /**< DEVMGR: only one application can use SCO */
-    OI_DEVMGR_SCO_NOT_REGISTERED = 1328,           /**< DEVMGR: SCO applications must register before using the API */
-    OI_DEVMGR_SCO_WITHOUT_ACL = 1329,              /**< DEVMGR: Got SCO connection but there is no underlying ACL connection */
-    OI_DEVMGR_NO_SUPPORT = 1330,                   /**< DEVMGR: Request is not supported by the device */
-    OI_DEVMGR_WRITE_POLICY_FAILED = 1331,          /**< DEVMGR: connection attempt failed - unable to write link policy */
-    OI_DEVMGR_NOT_IN_MASTER_MODE = 1332,           /**< DEVMGR: OI_DEVMGR EndMasterMode without prior OI_DEVMGR_BeginMasterMode */
-    OI_DEVMGR_POLICY_VIOLATION = 1333,             /**< DEVMGR: low-power request is rejected - link policy does not allow it */
-    OI_DEVMGR_BUSY_TIMEOUT = 1334,                 /**< DEVMGR: queued operation timed out while in the queue; \n
-        timeout configurable via @ref OI_CONFIG_DEVMGR::connectQueueTimeoutSecs "connectQueueTimeoutSecs" */
-    OI_DEVMGR_REENCRYPT_FAILED = 1335,             /**< DEVMGR: failed to re-encrypt link after role switch */
-    OI_DEVMGR_ROLE_POLICY_CONFLICT = 1336,         /**< DEVMGR: requested role conflicts with current policy */
-    OI_DEVMGR_BAD_INTERVAL = 1337,                 /**< DEVMGR: current linkTO outside range of requested min/max interval */
-    OI_DEVMGR_INVALID_SCO_HANDLE = 1338,           /**< DEVMGR: HCI SCO event, invalid handle */
-    OI_DEVMGR_CONNECTION_OVERLAP = 1339,           /**< DEVMGR: Connection failed due to race condition with remote side */
-    OI_DEVMGR_ORPHAN_SUBRATE_COMPLETE = 1340,      /**< DEVMGR: sniff subrate complete, but no callback */
-    OI_DEVMGR_EIR_RESPONSE_2_LARGE = 1341,         /**< DEVMGR: eir builder, response length would exceed spec max */
-
-    OI_SECMGR_NO_POLICY = 1401,              /**< SECMGR: no security policy has been established */
-    OI_SECMGR_INTERNAL_ERROR = 1402,         /**< SECMGR: internal inconsistency */
-    OI_SECMGR_ORPHANED_CALLBACK = 1403,      /**< SECMGR: we've been called back, but CB context is gone */
-    OI_SECMGR_BUSY = 1404,                   /**< SECMGR: configure and access request cannot be concurrent */
-    OI_SECMGR_DEVICE_NOT_TRUSTED = 1405,     /**< SECMGR: l2cap access denied - device is not trusted */
-    OI_SECMGR_DEVICE_ENCRYPT_FAIL = 1407,    /**< SECMGR: l2cap access denied - failed to start encryption */
-    OI_SECMGR_DISCONNECTED_FAIL = 1408,      /**< SECMGR: l2cap access denied - disconnected */
-    OI_SECMGR_ACCESS_PENDING = 1409,         /**< SECMGR: l2cap access request is still pending  */
-    OI_SECMGR_PIN_CODE_TOO_SHORT = 1410,     /**< SECMGR: Higher-layer process gave us a pin code that is too short */
-    OI_SECMGR_UNKNOWN_ENCRYPT_VALUE = 1411,  /**< SECMGR: got EncryptionChange event, unknown encryption enable value */
-    OI_SECMGR_INVALID_POLICY = 1412,         /**< SECMGR: the specified security policy is not valid for security mode */
-    OI_SECMGR_AUTHORIZATION_FAILED = 1413,   /**< SECMGR: device authorization failed */
-    OI_SECMGR_ENCRYPTION_FAILED = 1414,      /**< SECMGR: device encryption failed */
-    OI_SECMGR_UNIT_KEY_UNSUPPORTED = 1415,   /**< SECMGR: authentication failed due to non-support of unit keys */
-    OI_SECMGR_NOT_REGISTERED = 1416,         /**< SECMGR: required registrations have not yet occurred */
-    OI_SECMGR_ILLEGAL_WRITE_SSP_MODE = 1417, /**< SECMGR: 2.1 HCI spec does not allow SSP mode to be disabled */
-    OI_SECMGR_INVALID_SEC_LEVEL = 1418,      /**< SECMGR: security level for a service is not a valid value */
-    OI_SECMGR_INSUFFICIENT_LINK_KEY = 1419,  /**< SECMGR: link key type is not sufficient to meet service requirements */
-    OI_SECMGR_INVALID_KEY_TYPE = 1420,       /**< SECMGR: link key type is not a valid value */
-    OI_SECMGR_SSP_NOT_ENCRYPTED = 1421,      /**< SECMGR: ssp required encryption on incoming link */
-    OI_SECMGR_ORPHAN_EVENT = 1422,           /**< SECMGR: some HCI security event unrelated to current processes */
-    OI_SECMGR_NOT_BONDABLE = 1423,           /**< SECMGR: not in bondable mode */
-
-    OI_TCS_INVALID_ELEMENT_TYPE = 1602, /**< TCS: element type is invalid */
-    OI_TCS_INVALID_PACKET = 1603,       /**< TCS: packet is invalide */
-    OI_TCS_CALL_IN_PROGRESS = 1604,     /**< TCS: call is in progress */
-    OI_TCS_NO_CALL_IN_PROGRESS = 1605,  /**< TCS: no call in progress */
-
-    OI_OBEX_CONTINUE = 1701,                    /**< OBEX: Continue processing OBEX request */
-    OI_OBEX_COMMAND_ERROR = 1702,               /**< OBEX: An unrecognized OBEX command opcode */
-    OI_OBEX_CONNECTION_TIMEOUT = 1703,          /**< OBEX: Timeout waiting for a response to a request */
-    OI_OBEX_CONNECT_FAILED = 1704,              /**< OBEX: An OBEX connection request did not succeed */
-    OI_OBEX_DISCONNECT_FAILED = 1705,           /**< OBEX: A disconnect failed probably because the connection did not exist */
-    OI_OBEX_ERROR = 1706,                       /**< OBEX: Unspecified OBEX error */
-    OI_OBEX_INCOMPLETE_PACKET = 1707,           /**< OBEX: Packet too short or corrupt */
-    OI_OBEX_LENGTH_REQUIRED = 1708,             /**< OBEX: Length header required in OBEX command */
-    OI_OBEX_NOT_CONNECTED = 1709,               /**< OBEX: No connection to OBEX server */
-    OI_OBEX_NO_MORE_CONNECTIONS = 1710,         /**< OBEX: Reached max connections limit */
-    OI_OBEX_OPERATION_IN_PROGRESS = 1711,       /**< OBEX: Another operation is still in progress on a connection */
-    OI_OBEX_PUT_RESPONSE_ERROR = 1712,          /**< OBEX: An error in the response to a PUT command */
-    OI_OBEX_GET_RESPONSE_ERROR = 1713,          /**< OBEX: An error in the response to a GET command */
-    OI_OBEX_REQUIRED_HEADER_NOT_FOUND = 1714,   /**< OBEX: packet was missing a required header */
-    OI_OBEX_SERVICE_UNAVAILABLE = 1715,         /**< OBEX: Unown OBEX target or required service */
-    OI_OBEX_TOO_MANY_HEADER_BYTES = 1716,       /**< OBEX: Headers will not fit in single OBEX packet */
-    OI_OBEX_UNKNOWN_COMMAND = 1717,             /**< OBEX: Unrecognized OBEX command */
-    OI_OBEX_UNSUPPORTED_VERSION = 1718,         /**< OBEX: Version mismatch */
-    OI_OBEX_CLIENT_ABORTED_COMMAND = 1719,      /**< OBEX: server received abort command */
-    OI_OBEX_BAD_PACKET = 1720,                  /**< OBEX: Any malformed OBEX packet */
-    OI_OBEX_BAD_REQUEST = 1721,                 /**< OBEX: Maps to OBEX response of the same name */
-    OI_OBEX_OBJECT_OVERFLOW = 1723,             /**< OBEX: Too many bytes received. */
-    OI_OBEX_NOT_FOUND = 1724,                   /**< OBEX: Maps to obex response of same name */
-    OI_OBEX_ACCESS_DENIED = 1735,               /**< OBEX: Object could not be read or written. */
-    OI_OBEX_VALUE_NOT_ACCEPTABLE = 1736,        /**< OBEX: Value in a command was not in the acceptable range. */
-    OI_OBEX_PACKET_OVERFLOW = 1737,             /**< OBEX: Buffer will not fit in a single OBEX packet. */
-    OI_OBEX_NO_SUCH_FOLDER = 1738,              /**< OBEX: Error returned by a setpath operation. */
-    OI_OBEX_NAME_REQUIRED = 1739,               /**< OBEX: Name must be non-null and non-empty. */
-    OI_OBEX_PASSWORD_TOO_LONG = 1740,           /**< OBEX: Password exceeds implementation imposed length limit. */
-    OI_OBEX_PRECONDITION_FAILED = 1741,         /**< OBEX: response Precondition Failed */
-    OI_OBEX_UNAUTHORIZED = 1742,                /**< OBEX: authentication was not successful. */
-    OI_OBEX_NOT_IMPLEMENTED = 1743,             /**< OBEX: Unimplemented feature. */
-    OI_OBEX_INVALID_AUTH_DIGEST = 1744,         /**< OBEX: An authentication digest was bad. */
-    OI_OBEX_INVALID_OPERATION = 1745,           /**< OBEX: Operation not allowed at this time. */
-    OI_OBEX_DATABASE_FULL = 1746,               /**< OBEX: Sync database full. */
-    OI_OBEX_DATABASE_LOCKED = 1747,             /**< OBEX: Sync database locked. */
-    OI_OBEX_INTERNAL_SERVER_ERROR = 1748,       /**< OBEX: response Internal Server Error */
-    OI_OBEX_UNSUPPORTED_MEDIA_TYPE = 1749,      /**< OBEX: response Unsupported Media Type */
-    OI_OBEX_PARTIAL_CONTENT = 1750,             /**< OBEX: response Partial Content */
-    OI_OBEX_METHOD_NOT_ALLOWED = 1751,          /**< OBEX: response Method Not Allowed */
-    OI_OBEXSRV_INCOMPLETE_GET = 1752,           /**< OBEX: Indicates to a GET handler that the request phase is still in progress */
-    OI_OBEX_FOLDER_BROWSING_NOT_ALLOWED = 1753, /**< OBEX: Indicates that an FTP server does not allow folder browsing */
-    OI_OBEX_SERVER_FORCED_DISCONNECT = 1754,    /**< OBEX: connection was forcibly terminated by the server */
-    OI_OBEX_OFS_ERROR = 1755,                   /**< OBEX: OPP object file system error occurred */
-    OI_OBEX_FILEOP_ERROR = 1756,                /**< OBEX: FTP/PBAP file operation system error occurred */
-    OI_OBEX_USERID_TOO_LONG = 1757,             /**< OBEX: User Id exceeds spec limited length limit. */
-
-    OI_HANDSFREE_EVENT_REPORTING_DISABLED = 1801, /**< HANDSFREE: Event reporting disabled */
-    OI_HANDSFREE_NOT_CONNECTED = 1802,            /**< HANDSFREE: Not connected */
-    OI_HANDSFREE_SERVICE_NOT_STARTED = 1803,      /**< HANDSFREE: Cannot connect to handsfree AG if handsfree service not started */
-    OI_HANDSFREE_AG_SERVICE_NOT_STARTED = 1804,   /**< HANDSFREE: Cannot connect to handsfree device if handsfree AG service not started */
-    OI_HANDSFREE_COMMAND_IN_PROGRESS = 1805,      /**< HANDSFREE: Cannot accept a command at this time */
-    OI_HANDSFREE_AUDIO_ALREADY_CONNECTED = 1806,  /**< HANDSFREE: Audio is already connected */
-    OI_HANDSFREE_AUDIO_NOT_CONNECTED = 1807,      /**< HANDSFREE: Audio is not connected */
-    OI_HANDSFREE_FEATURE_NOT_SUPPORTED = 1808,    /**< HANDSFREE: Local or remote feature not supported for requested command */
-
-    OI_HEADSET_SERVICE_NOT_STARTED = 1901,    /**< HEADSET: Cannot connect to headset AG if headset service not started */
-    OI_HEADSET_AG_SERVICE_NOT_STARTED = 1902, /**< HEADSET: Cannot connect to headset device if headset AG service not started */
-    OI_HEADSET_COMMAND_IN_PROGRESS = 1903,    /**< HEADSET: Cannot accept a command at this time */
-
-    OI_BNEP_INVALID_MTU = 2001,                             /**< BNEP: The remote device cannot support the minimum BNEP MTU */
-    OI_BNEP_SETUP_TIMEOUT = 2002,                           /**< BNEP: The setup request timed out. */
-    OI_BNEP_SERVICE_NOT_REGISTERED = 2003,                  /**< BNEP: The requested service was not found. */
-    OI_BNEP_INVALID_HANDLE = 2004,                          /**< BNEP: The specified connection handle is not valid. */
-    OI_BNEP_RESPONSE_TIMEOUT = 2005,                        /**< BNEP: The timer for receiving a response has expired. */
-    OI_BNEP_INVALID_CONNECTION = 2006,                      /**< BNEP: Invalid connection */
-    OI_BNEP_INVALID_FILTER = 2007,                          /**< BNEP: The supplied filter was invalid. */
-    OI_BNEP_CONNECTION_EXISTS = 2008,                       /**< BNEP: An attempt was made to create a duplicate connection. */
-    OI_BNEP_NOT_INITIALIZED = 2009,                         /**< BNEP: Init has not been called */
-    OI_BNEP_CONNECT_BASE = 2010,                            /**< BNEP: connection response codes */
-    OI_BNEP_CONNECT_FAILED_INVALID_DEST_UUID = 2011,        /**< BNEP: connect response code Invalid Dest UUID */
-    OI_BNEP_CONNECT_FAILED_INVALID_SOURCE_UUID = 2012,      /**< BNEP: connect response code Invalid Source UUID */
-    OI_BNEP_CONNECT_FAILED_INVALID_UUID_SIZE = 2013,        /**< BNEP: connect response code Invalid UUID Size */
-    OI_BNEP_CONNECT_FAILED_NOT_ALLOWED = 2014,              /**< BNEP: connect response code Not Allowed */
-    OI_BNEP_FILTER_NET_BASE = 2020,                         /**< BNEP: filter response codes */
-    OI_BNEP_FILTER_NET_UNSUPPORTED_REQUEST = 2021,          /**< BNEP: filter response code Unsupported Request */
-    OI_BNEP_FILTER_NET_FAILED_INVALID_PROTOCOL_TYPE = 2022, /**< BNEP: filter response code Invalid Protocol Type */
-    OI_BNEP_FILTER_NET_FAILED_MAX_LIMIT_REACHED = 2023,     /**< BNEP: filter response code Max Limit Reached */
-    OI_BNEP_FILTER_NET_FAILED_SECURITY = 2024,              /**< BNEP: filter response code Security */
-    OI_BNEP_FILTER_MULTI_BASE = 2030,                       /**< BNEP: multicast response codes */
-    OI_BNEP_FILTER_MULTI_UNSUPPORTED_REQUEST = 2031,        /**< BNEP: multicast response code Unsupported Request */
-    OI_BNEP_FILTER_MULTI_FAILED_INVALID_ADDRESS = 2032,     /**< BNEP: multicast response code Invalid Address */
-    OI_BNEP_FILTER_MULTI_FAILED_MAX_LIMIT_REACHED = 2033,   /**< BNEP: multicast response code Max Limit Reached */
-    OI_BNEP_FILTER_MULTI_FAILED_SECURITY = 2034,            /**< BNEP: multicast response code Security */
-    OI_BNEP_LOCAL_DEVICE_MUST_BE_MASTER = 2040,             /**< BNEP: Device must be master of the piconet for this function */
-    OI_BNEP_PACKET_FILTERED_OUT = 2041,                     /**< BNEP: Packet did not pass current filters */
-
-    OI_NETIFC_UP_FAILED = 2101,               /**< NETIFC: Could not bring up network interface */
-    OI_NETIFC_COULD_NOT_CREATE_THREAD = 2102, /**< NETIFC: Network interface could not create a read thread */
-    OI_NETIFC_INITIALIZATION_FAILED = 2103,   /**< NETIFC: Error in network interface initialization */
-    OI_NETIFC_INTERFACE_ALREADY_UP = 2104,    /**< NETIFC: Network interface is already up */
-    OI_NETIFC_INTERFACE_NOT_UP = 2105,        /**< NETIFC: Network interface is not up */
-    OI_NETIFC_PACKET_TOO_BIG = 2106,          /**< NETIFC: The packet is too big */
-
-    OI_PAN_ROLE_ALREADY_REGISTERED = 2201, /**< PAN: This PAN role was already registered */
-    OI_PAN_ROLE_NOT_ALLOWED = 2202,        /**< PAN: The PAN role is not currently allowed */
-    OI_PAN_INCOMPATIBLE_ROLES = 2203,      /**< PAN: Only certain local and remote role combinations are permitted */
-    OI_PAN_INVALID_ROLE = 2204,            /**< PAN: Role specified is not one the defined PAN roles */
-    OI_PAN_CONNECTION_IN_PROGRESS = 2205,  /**< PAN: A PAN connection is currently being established */
-    OI_PAN_USER_ALREADY_CONNECTED = 2206,  /**< PAN: PAN user role only allows a single connection */
-    OI_PAN_DEVICE_CONNECTED = 2207,        /**< PAN: A PAN connection already exists to specified device */
-
-    OI_CODEC_SBC_NO_SYNCWORD = 2301,            /**< CODEC: Couldn't find an SBC SYNCWORD */
-    OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA = 2302, /**< CODEC: Not enough data provided to decode an SBC header */
-    OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA = 2303,   /**< CODEC: Decoded the header, but not enough data to contain the rest of the frame */
-    OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA = 2304,  /**< CODEC: Not enough audio data for this frame */
-    OI_CODEC_SBC_CHECKSUM_MISMATCH = 2305,      /**< CODEC: The frame header didn't match the checksum */
-    OI_CODEC_SBC_PARTIAL_DECODE = 2306,         /**< CODEC: Decoding was successful, but frame data still remains. Next call will provide audio without consuming input data. */
-
-    OI_FIFOQ_QUEUE_NOT_ALIGNED = 2401, /**< FIFOQ: queue must be 32-bit aligned */
-    OI_FIFOQ_INVALID_Q = 2402,         /**< FIFOQ: queue parameter is not a valid queue */
-    OI_FIFOQ_BUF_TOO_LARGE = 2403,     /**< FIFOQ: attempt to queue a buffer which is too large */
-    OI_FIFOQ_FULL = 2404,              /**< FIFOQ: enqueue() failed, queue is full */
-    OI_FIFOQ_NOT_ALLOCATED = 2405,     /**< FIFOQ: Enqueue QBuf() failed, buffer not allocated */
-    OI_FIFOQ_INVALID_DATA_PTR = 2406,  /**< FIFOQ: Enqueue QBuf() failed, data pointer does not match */
-
-    OI_HID_HOST_SERVICE_NOT_STARTED = 2601,   /**< HID: Cannot connect to a HID device unless HID host is started */
-    OI_HID_DEVICE_SERVICE_NOT_STARTED = 2602, /**< HID: Cannot connect to a HID host unless HID device is started */
-
-    OI_AT_ERROR = 2701,       /**< AT: ERROR response */
-    OI_AT_NO_CARRIER = 2702,  /**< AT: NO CARRIER response */
-    OI_AT_BUSY = 2703,        /**< AT: BUSY response */
-    OI_AT_NO_ANSWER = 2704,   /**< AT: NO ANSWER response */
-    OI_AT_DELAYED = 2705,     /**< AT: DELAYED response */
-    OI_AT_BLACKLISTED = 2706, /**< AT: BLACKLISTED response */
-    OI_AT_CME_ERROR = 2707,   /**< AT: +CME ERROR response */
-    OI_AT_CMS_ERROR = 2708,   /**< AT: +CMS ERROR response */
-
-    OI_BLST_CHARACTER_TIMEOUT = 2801,  /**< BLST: Timeout expired while waiting for a character from the client. */
-    OI_BLST_ACKNOWLDGE_TIMEOUT = 2802, /**< BLST: Timeout expired while waiting for event acknowledgment from the client */
-    OI_BLST_TX_NOT_READY = 2803,       /**< BLST: BLST is not ready to send a BHAPI message to the client. */
-    OI_BLST_TX_BUSY = 2804,            /**< BLST: BLST transmit buffer is in use. */
-
-    OI_AVDTP_CONNECTION_SEQ_ERROR = 2901, /**< AVDTP: sequencing of signalling/media channel connections broken. */
-    OI_AVDTP_OUT_OF_RESOURCES = 2902,     /**< AVDTP: Tried to allocate too many endpoints or signalling channels. */
-
-    OI_PBAP_REPOSITORY_NOT_SET = 3001, /**< PBAP: Phonebook repository must be set for operation to complete. */
-    OI_PBAP_PHONEBOOK_NOT_SET = 3002,  /**< PBAP: Phonebook be set for operation to complete. */
-
-    OI_AADP_BAD_ENDPOINT = 3101, /**< AADP: Invalid local endpoint specified */
-    OI_AADP_BAD_STATE = 3102,    /**< AADP: AADP State is not correct for this operation. */
-
-    OI_UNICODE_INVALID_SOURCE = 3200,        /**< Unicode Conversion: Source string has invalid character encoding. */
-    OI_UNICODE_SOURCE_EXHAUSTED = 3201,      /**< Unicode Conversion: Incomplete Unicode character at end of source buffer. */
-    OI_UNICODE_DESTINATION_EXHAUSTED = 3202, /**< Unicode Conversion: Destination buffer not large enough to hold resulting Unicode string. */
-
-    OI_AVRCP_TOO_MANY_CONNECTIONS = 3300,         /**< AVRCP: Exceeded maximum number of simultaneous AVCTP connections. */
-    OI_AVRCP_NOT_IMPLEMENTED = 3301,              /**< AVRCP: The target does not implement the command specified by the opcode and operand. */
-    OI_AVRCP_REJECTED = 3302,                     /**< AVRCP: The target cannot respond because of invalid operands in command packet. */
-    OI_AVRCP_INVALID_RESPONSE = 3303,             /**< AVRCP: The controller received the response with invalid parameters */
-    OI_AVRCP_RESPONSE_PACKET_OVERFLOW = 3304,     /**< AVRCP: The response message does not fir in one AVRCP packet (512 bytes), has to be fragmented. */
-    OI_AVRCP_RESPONSE_INVALID_PDU = 3305,         /**< AVRCP: Command rejected: target received a PDU that it did not understand. */
-    OI_AVRCP_RESPONSE_INVALID_PARAMETER = 3306,   /**< AVRCP: Command rejected: target received a PDU with a parameter ID that it did not understand. */
-    OI_AVRCP_RESPONSE_PARAMETER_NOT_FOUND = 3307, /**< AVRCP: Command rejected: specified parameter not found, sent if the parameter ID is understood, but content is wrong or corrupted.*/
-    OI_AVRCP_RESPONSE_INTERNAL_ERROR = 3308,      /**< AVRCP: Command rejected: target detected other error conditions. */
-    OI_MAX_BM3_STATUS_VAL,                        /* Maximum BM3 status code */
-
-    /* Status code values reserved for BM3 SDK platform-specific implementations */
-    OI_STATUS_RESERVED_FOR_BCOT = 9000,
-
-    /* Status code values reserved for BHAPI products */
-    OI_STATUS_RESERVED_FOR_BHAPI = 9200,
-
-    /* Status code values reserved for Soundabout products */
-    OI_STATUS_RESERVED_FOR_SOUNDABOUT = 9400,
-
-    /*
-     * Status code values greater than or equal to this value are reserved for use by applications.
-     * However, because of differences between compilers, and differences between 16-bit and 32-bit
-     * platforms custom status codes should be in the 16-bit range, so status codes can range from 0
-     * to 65534, inclusive (65535 is reserved)
-     */
-    OI_STATUS_RESERVED_FOR_APPS = 10000,
-
-    OI_STATUS_NONE = 0xffff /**< Special status code to indicate that there is no status. (Only to be used for special cases involving OI_SLOG_ERROR() and OI_SLOG_WARNING().) */
-
-} OI_STATUS;
-
-/* Remeber to update the #define below when new reserved blocks are added to
- * the list above. */
-#define OI_NUM_RESERVED_STATUS_BLOCKS 4 /**< Number of status code blocks reserved, including user apps */
-
-/**
- * Test for success
- */
-#define OI_SUCCESS(x) ((x) == OI_OK)
-
-/*****************************************************************************/
-#ifdef __cplusplus
-}
-#endif
-
-/**@}*/
-
-#endif /* _OI_STATUS_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_stddefs.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_stddefs.h
deleted file mode 100644
index 8f210200c..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_stddefs.h
+++ /dev/null
@@ -1,252 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef OI_STDDEFS_H
-#define OI_STDDEFS_H
-/**
- * @file
- * This file contains BM3 standard type definitions.
- *
- */
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-#include "oi_cpu_dep.h"
-
-/** \addtogroup Misc Miscellaneous APIs */
-/**@{*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef FALSE
-#define FALSE 0 /**< This define statement sets FALSE as a preprocessor alias for 0. */
-#endif
-
-#ifndef TRUE
-#define TRUE (!FALSE) /**< This define statement sets TRUE as a preprocessor alias for !FALSE. */
-#endif
-
-#ifdef HEW_TOOLCHAIN
-#ifdef NULL
-#undef NULL /**< Override HEW toolchain NULL definition */
-#endif
-#define NULL 0 /**< HEW toolchain does not allow us to compare (void*) type to function pointer */
-#else
-#ifndef NULL
-#define NULL ((void *)0) /**< This define statement sets NULL as a preprocessor alias for (void*)0 */
-#endif
-#endif
-
-/**
- * @name  Maximum and minimum values for basic types
- * @{
- */
-#define OI_INT8_MIN   ((OI_INT8)0x80)         /**< decimal value: -128 */
-#define OI_INT8_MAX   ((OI_INT8)0x7F)         /**< decimal value: 127 */
-#define OI_INT16_MIN  ((OI_INT16)0x8000)      /**< decimal value: -32768 */
-#define OI_INT16_MAX  ((OI_INT16)0x7FFF)      /**< decimal value: 32767 */
-#define OI_INT32_MIN  ((OI_INT32)0x80000000)  /**< decimal value: -2,147,483,648 */
-#define OI_INT32_MAX  ((OI_INT32)0x7FFFFFFF)  /**< decimal value: 2,147,483,647 */
-#define OI_UINT8_MIN  ((OI_UINT8)0)           /**< decimal value: 0 */
-#define OI_UINT8_MAX  ((OI_UINT8)0xFF)        /**< decimal value: 255 */
-#define OI_UINT16_MIN ((OI_UINT16)0)          /**< decimal value: 0 */
-#define OI_UINT16_MAX ((OI_UINT16)0xFFFF)     /**< decimal value: 65535 */
-#define OI_UINT32_MIN ((OI_UINT32)0)          /**< decimal value: 0 */
-#define OI_UINT32_MAX ((OI_UINT32)0xFFFFFFFF) /**< decimal value: 4,294,967,295 */
-
-/**
- * @}
- */
-
-/**
- * @name  Integer types required by the Service Discovery Protocol
- * @{
- */
-
-/** unsigned 64-bit integer as a structure of two unsigned 32-bit integers */
-typedef struct {
-    OI_UINT32 I1; /**< most significant 32 bits */
-    OI_UINT32 I2; /**< least significant 32 bits */
-} OI_UINT64;
-
-#define OI_UINT64_MIN                                \
-    {                                                \
-        (OI_UINT32)0x00000000, (OI_UINT32)0x00000000 \
-    }
-#define OI_UINT64_MAX                                \
-    {                                                \
-        (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF \
-    }
-
-/** signed 64-bit integer as a structure of one unsigned 32-bit integer and one signed 32-bit integer */
-typedef struct {
-    OI_INT32 I1;  /**< most significant 32 bits  as a signed integer */
-    OI_UINT32 I2; /**< least significant 32 bits as an unsigned integer */
-} OI_INT64;
-
-#define OI_INT64_MIN                                \
-    {                                               \
-        (OI_INT32)0x80000000, (OI_UINT32)0x00000000 \
-    }
-#define OI_INT64_MAX                                \
-    {                                               \
-        (OI_INT32)0X7FFFFFFF, (OI_UINT32)0XFFFFFFFF \
-    }
-
-/** unsigned 128-bit integer as a structure of four unsigned 32-bit integers */
-typedef struct {
-    OI_UINT32 I1; /**< most significant 32 bits */
-    OI_UINT32 I2; /**< second-most significant 32 bits */
-    OI_UINT32 I3; /**< third-most significant 32 bits */
-    OI_UINT32 I4; /**< least significant 32 bits */
-} OI_UINT128;
-
-#define OI_UINT128_MIN                                                                             \
-    {                                                                                              \
-        (OI_UINT32)0x00000000, (OI_UINT32)0x00000000, (OI_UINT32)0x00000000, (OI_UINT32)0x00000000 \
-    }
-#define OI_UINT128_MAX                                                                             \
-    {                                                                                              \
-        (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF \
-    }
-
-/** signed 128-bit integer as a structure of three unsigned 32-bit integers and one signed 32-bit integer */
-typedef struct {
-    OI_INT32 I1;  /**< most significant 32 bits as a signed integer */
-    OI_UINT32 I2; /**< second-most significant 32 bits as an unsigned integer */
-    OI_UINT32 I3; /**< third-most significant 32 bits as an unsigned integer */
-    OI_UINT32 I4; /**< least significant 32 bits as an unsigned integer */
-} OI_INT128;
-
-#define OI_INT128_MIN                                                                              \
-    {                                                                                              \
-        (OI_UINT32)0x80000000, (OI_UINT32)0x00000000, (OI_UINT32)0x00000000, (OI_UINT32)0x00000000 \
-    }
-#define OI_INT128_MAX                                                                              \
-    {                                                                                              \
-        (OI_UINT32)0X7FFFFFFF, (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF, (OI_UINT32)0XFFFFFFFF \
-    }
-
-/**
- * @}
- */
-
-/**
- * type for ASCII character data items
- */
-typedef char OI_CHAR;
-
-/**
- * type for double-byte character data items
- */
-typedef OI_UINT16 OI_CHAR16;
-
-/**
- * types for UTF encoded strings.
- */
-typedef OI_UINT8 OI_UTF8;
-typedef OI_UINT16 OI_UTF16;
-typedef OI_UINT32 OI_UTF32;
-
-/**
- * @name Single-bit operation macros
- * @{
- * In these macros, x is the data item for which a bit is to be tested or set and y specifies which bit
- * is to be tested or set.
- */
-
-/** This macro's value is TRUE if the bit specified by y is set in data item x. */
-#define OI_BIT_TEST(x, y) ((x) & (y))
-
-/** This macro's value is TRUE if the bit specified by y is not set in data item x. */
-#define OI_BIT_CLEAR_TEST(x, y) (((x) & (y)) == 0)
-
-/** This macro sets the bit specified by y in data item x. */
-#define OI_BIT_SET(x, y) ((x) |= (y))
-
-/** This macro clears the bit specified by y in data item x. */
-#define OI_BIT_CLEAR(x, y) ((x) &= ~(y))
-
-/** @} */
-
-/**
- * The OI_ARRAYSIZE macro is set to the number of elements in an array
- * (instead of the number of bytes, which is returned by sizeof()).
- */
-
-#ifndef OI_ARRAYSIZE
-#define OI_ARRAYSIZE(a) (sizeof(a) / sizeof(a[0]))
-#endif
-
-/**
- * @name Preprocessor aliases for individual bit positions
- *      Bits are defined here only if they are not already defined.
- * @{
- */
-
-#ifndef BIT0
-
-#define BIT0  0x00000001 /**< preprocessor alias for 32-bit value with bit 0 set, used to specify this single bit */
-#define BIT1  0x00000002 /**< preprocessor alias for 32-bit value with bit 1 set, used to specify this single bit */
-#define BIT2  0x00000004 /**< preprocessor alias for 32-bit value with bit 2 set, used to specify this single bit */
-#define BIT3  0x00000008 /**< preprocessor alias for 32-bit value with bit 3 set, used to specify this single bit */
-#define BIT4  0x00000010 /**< preprocessor alias for 32-bit value with bit 4 set, used to specify this single bit */
-#define BIT5  0x00000020 /**< preprocessor alias for 32-bit value with bit 5 set, used to specify this single bit */
-#define BIT6  0x00000040 /**< preprocessor alias for 32-bit value with bit 6 set, used to specify this single bit */
-#define BIT7  0x00000080 /**< preprocessor alias for 32-bit value with bit 7 set, used to specify this single bit */
-#define BIT8  0x00000100 /**< preprocessor alias for 32-bit value with bit 8 set, used to specify this single bit */
-#define BIT9  0x00000200 /**< preprocessor alias for 32-bit value with bit 9 set, used to specify this single bit */
-#define BIT10 0x00000400 /**< preprocessor alias for 32-bit value with bit 10 set, used to specify this single bit */
-#define BIT11 0x00000800 /**< preprocessor alias for 32-bit value with bit 11 set, used to specify this single bit */
-#define BIT12 0x00001000 /**< preprocessor alias for 32-bit value with bit 12 set, used to specify this single bit */
-#define BIT13 0x00002000 /**< preprocessor alias for 32-bit value with bit 13 set, used to specify this single bit */
-#define BIT14 0x00004000 /**< preprocessor alias for 32-bit value with bit 14 set, used to specify this single bit */
-#define BIT15 0x00008000 /**< preprocessor alias for 32-bit value with bit 15 set, used to specify this single bit */
-#define BIT16 0x00010000 /**< preprocessor alias for 32-bit value with bit 16 set, used to specify this single bit */
-#define BIT17 0x00020000 /**< preprocessor alias for 32-bit value with bit 17 set, used to specify this single bit */
-#define BIT18 0x00040000 /**< preprocessor alias for 32-bit value with bit 18 set, used to specify this single bit */
-#define BIT19 0x00080000 /**< preprocessor alias for 32-bit value with bit 19 set, used to specify this single bit */
-#define BIT20 0x00100000 /**< preprocessor alias for 32-bit value with bit 20 set, used to specify this single bit */
-#define BIT21 0x00200000 /**< preprocessor alias for 32-bit value with bit 21 set, used to specify this single bit */
-#define BIT22 0x00400000 /**< preprocessor alias for 32-bit value with bit 22 set, used to specify this single bit */
-#define BIT23 0x00800000 /**< preprocessor alias for 32-bit value with bit 23 set, used to specify this single bit */
-#define BIT24 0x01000000 /**< preprocessor alias for 32-bit value with bit 24 set, used to specify this single bit */
-#define BIT25 0x02000000 /**< preprocessor alias for 32-bit value with bit 25 set, used to specify this single bit */
-#define BIT26 0x04000000 /**< preprocessor alias for 32-bit value with bit 26 set, used to specify this single bit */
-#define BIT27 0x08000000 /**< preprocessor alias for 32-bit value with bit 27 set, used to specify this single bit */
-#define BIT28 0x10000000 /**< preprocessor alias for 32-bit value with bit 28 set, used to specify this single bit */
-#define BIT29 0x20000000 /**< preprocessor alias for 32-bit value with bit 29 set, used to specify this single bit */
-#define BIT30 0x40000000 /**< preprocessor alias for 32-bit value with bit 30 set, used to specify this single bit */
-#define BIT31 0x80000000 /**< preprocessor alias for 32-bit value with bit 31 set, used to specify this single bit */
-
-#endif /* BIT0 et al */
-
-/** @} */
-
-#ifdef __cplusplus
-}
-#endif
-
-/**@}*/
-
-/*****************************************************************************/
-#endif /* OI_STDDEFS_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_string.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_string.h
deleted file mode 100644
index 68e6aad22..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_string.h
+++ /dev/null
@@ -1,200 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef OI_STRING_H
-#define OI_STRING_H
-/**
- * @file
- * This file contains BM3 supplied portable string.h functions
- *
- */
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-#include "oi_cpu_dep.h"
-#include "oi_stddefs.h"
-
-#if defined(USE_NATIVE_MEMCPY) || defined(USE_NATIVE_MALLOC)
-#include 
-#endif
-
-/** \addtogroup Misc Miscellaneous APIs */
-/**@{*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * If we are using Native malloc(), we must also use
- * native Ansi string.h functions for memory manipulation.
- */
-#ifdef USE_NATIVE_MALLOC
-#ifndef USE_NATIVE_MEMCPY
-#define USE_NATIVE_MEMCPY
-#endif
-#endif
-
-#ifdef USE_NATIVE_MEMCPY
-
-#define OI_MemCopy(to, from, size)  memcpy((to), (from), (size))
-#define OI_MemSet(block, val, size) memset((block), (val), (size))
-#define OI_MemZero(block, size)     memset((block), 0, (size))
-#define OI_MemCmp(s1, s2, n)        memcmp((s1), (s2), (n))
-#define OI_Strcpy(dest, src)        strcpy((dest), (src))
-#define OI_Strcat(dest, src)        strcat((dest), (src))
-#define OI_StrLen(str)              strlen((str))
-#define OI_Strcmp(s1, s2)           strcmp((s1), (s2))
-#define OI_Strncmp(s1, s2, n)       strncmp((s1), (s2), (n))
-
-#else
-
-/*
- * OI_MemCopy
- *
- * Copy an arbitrary number of bytes from one memory address to another.
- * The underlying implementation is the ANSI memmove() or equivalant, so
- * overlapping memory copies will work correctly.
- */
-void OI_MemCopy(void *To, void const *From, OI_UINT32 Size);
-
-/*
- * OI_MemSet
- *
- * Sets all bytes in a block of memory to the same value
- */
-void OI_MemSet(void *Block, OI_UINT8 Val, OI_UINT32 Size);
-
-/*
- * OI_MemZero
- *
- * Sets all bytes in a block of memory to zero
- */
-void OI_MemZero(void *Block, OI_UINT32 Size);
-
-/*
- * OI_MemCmp
- *
- * Compare two blocks of memory
- *
- * Returns:
- *        0, if s1 == s2
- *      < 0, if s1 < s2
- *      > 0, if s2 > s2
- */
-OI_INT OI_MemCmp(void const *s1, void const *s2, OI_UINT32 n);
-
-/*
- * OI_Strcpy
- *
- * Copies the Null terminated string from pStr to pDest, and
- * returns pDest.
- */
-
-OI_CHAR *OI_Strcpy(OI_CHAR *pDest,
-                   OI_CHAR const *pStr);
-
-/*
- * OI_Strcat
- *
- * Concatonates the pStr string to the end of pDest, and
- * returns pDest.
- */
-
-OI_CHAR *OI_Strcat(OI_CHAR *pDest,
-                   OI_CHAR const *pStr);
-
-/*
- * OI_StrLen
- *
- * Calculates the number of OI_CHARs in pStr (not including
- * the Null terminator) and returns the value.
- */
-OI_UINT OI_StrLen(OI_CHAR const *pStr);
-
-/*
- * OI_Strcmp
- *
- * Compares two Null terminated strings
- *
- * Returns:
- *        0, if s1 == s2
- *      < 0, if s1 < s2
- *      > 0, if s2 > s2
- */
-OI_INT OI_Strcmp(OI_CHAR const *s1,
-                 OI_CHAR const *s2);
-
-/*
- * OI_Strncmp
- *
- * Compares the first "len" OI_CHARs of strings s1 and s2.
- *
- * Returns:
- *        0, if s1 == s2
- *      < 0, if s1 < s2
- *      > 0, if s2 > s2
- */
-OI_INT OI_Strncmp(OI_CHAR const *s1,
-                  OI_CHAR const *s2,
-                  OI_UINT32 len);
-
-#endif /* USE_NATIVE_MEMCPY */
-
-/*
- * OI_StrcmpInsensitive
- *
- * Compares two Null terminated strings, treating
- * the Upper and Lower case of 'A' through 'Z' as
- * equivilent.
- *
- * Returns:
- *        0, if s1 == s2
- *      < 0, if s1 < s2
- *      > 0, if s2 > s2
- */
-OI_INT OI_StrcmpInsensitive(OI_CHAR const *s1,
-                            OI_CHAR const *s2);
-
-/*
- * OI_StrncmpInsensitive
- *
- * Compares the first "len" OI_CHARs of strings s1 and s2,
- * treating the Upper and Lower case of 'A' through 'Z' as
- * equivilent.
- *
- *
- * Returns:
- *        0, if s1 == s2
- *      < 0, if s1 < s2
- *      > 0, if s2 > s2
- */
-OI_INT OI_StrncmpInsensitive(OI_CHAR const *s1,
-                             OI_CHAR const *s2,
-                             OI_UINT len);
-
-#ifdef __cplusplus
-}
-#endif
-
-/** @} */
-
-/*****************************************************************************/
-#endif /* OI_STRING_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_time.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_time.h
deleted file mode 100644
index b1ef52613..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_time.h
+++ /dev/null
@@ -1,188 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_TIME_H
-#define _OI_TIME_H
-/** @file
- *
- * This file provides time type definitions and interfaces to time-related functions.
- *
- * The stack maintains a 64-bit real-time millisecond clock. The choice of
- * milliseconds is for convenience, not accuracy.
- *
- * Timeouts are specified as tenths of seconds in a 32-bit value. Timeout values
- * specified by the Bluetooth specification are usually muliple seconds, so
- * accuracy to a tenth of a second is more than adequate.
- *
- * This file also contains macros to convert between seconds and the Link
- * Manager's 1.28-second units.
- *
- */
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-#include "oi_stddefs.h"
-
-/** \addtogroup Misc Miscellaneous APIs */
-/**@{*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Within the core stack timeouts are specified in intervals of tenths of seconds
- */
-
-typedef OI_UINT16 OI_INTERVAL;
-#define OI_INTERVALS_PER_SECOND 10
-#define MSECS_PER_OI_INTERVAL   (1000 / OI_INTERVALS_PER_SECOND)
-
-/** maximum interval (54 min 36.7 sec) */
-#define OI_MAX_INTERVAL 0x7fff
-
-/**
- * Macro to convert seconds to OI_INTERVAL time units
- */
-
-#define OI_SECONDS(n) ((OI_INTERVAL)((n)*OI_INTERVALS_PER_SECOND))
-
-/**
- * Macro to convert milliseconds to OI_INTERVAL time units (Rounded Up)
- */
-
-#define OI_MSECONDS(n) ((OI_INTERVAL)((n + MSECS_PER_OI_INTERVAL - 1) / MSECS_PER_OI_INTERVAL))
-
-/**
- * Macro to convert minutes to OI_INTERVAL time units
- */
-
-#define OI_MINUTES(n) ((OI_INTERVAL)((n)*OI_SECONDS(60)))
-
-/** Convert an OI_INTERVAL to milliseconds. */
-#define OI_INTERVAL_TO_MILLISECONDS(i) ((i)*MSECS_PER_OI_INTERVAL)
-
-/**
- * The stack depends on relative not absolute time. Any mapping between the
- * stack's real-time clock and absolute time and date is implementation-dependent.
- */
-
-typedef struct {
-    OI_INT32 seconds;
-    OI_INT16 mseconds;
-} OI_TIME;
-
-/**
- * Convert an OI_TIME to milliseconds.
- *
- * @param t  the time to convert
- *
- * @return the time in milliseconds
- */
-OI_UINT32 OI_Time_ToMS(OI_TIME *t);
-
-/**
- * This function compares two time values.
- *
- * @param T1 first time to compare.
- *
- * @param T2 second time to compare.
- *
- * @return
- @verbatim
-     -1 if t1 < t2
-      0 if t1 = t2
-     +1 if t1 > t2
- @endverbatim
- */
-
-OI_INT16 OI_Time_Compare(OI_TIME *T1,
-                         OI_TIME *T2);
-
-/**
- * This function returns the interval between two times to a granularity of 0.1 seconds.
- *
- * @param Sooner a time value more recent that Later
- *
- * @param Later a time value later than Sooner
- *
- * @note The result is an OI_INTERVAL value so this function only works for time intervals
- * that are less than about 71 minutes.
- *
- * @return the time interval between the two times = (Later - Sooner)
- */
-
-OI_INTERVAL OI_Time_Interval(OI_TIME *Sooner,
-                             OI_TIME *Later);
-
-/**
- * This function returns the interval between two times to a granularity of milliseconds.
- *
- * @param Sooner a time value more recent that Later
- *
- * @param Later a time value later than Sooner
- *
- * @note The result is an OI_UINT32 value so this function only works for time intervals
- * that are less than about 50 days.
- *
- * @return the time interval between the two times = (Later - Sooner)
- */
-
-OI_UINT32 OI_Time_IntervalMsecs(OI_TIME *Sooner,
-                                OI_TIME *Later);
-
-/**
- * This function answers the question, Have we reached or gone past the target time?
- *
- * @param pTargetTime   target time
- *
- * @return  TRUE means time now is at or past target time
- *          FALSE means target time is still some time in the future
- */
-
-OI_BOOL OI_Time_NowReachedTime(OI_TIME *pTargetTime);
-
-/**
- *  Convert seconds to the Link Manager 1.28-second units
- *  Approximate by using 1.25 conversion factor.
- */
-
-#define OI_SECONDS_TO_LM_TIME_UNITS(lmUnits) ((lmUnits) < 4 ? (lmUnits) : (lmUnits) - ((lmUnits) >> 2))
-
-/**
- *  Convert Link Manager 1.28-second units to seconds.
- *  Approximate by using 1.25 conversion factor.
- */
-
-#define OI_LM_TIME_UNITS_TO_SECONDS(lmUnits) ((lmUnits) + ((lmUnits) >> 2))
-
-#ifdef __cplusplus
-}
-#endif
-
-/**@}*/
-
-/* Include for OI_Time_Now() prototype
- * Must be included at end to obtain OI_TIME typedef
- */
-#include "oi_osinterface.h"
-
-/*****************************************************************************/
-#endif /* _OI_TIME_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_utils.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_utils.h
deleted file mode 100644
index 764b2680d..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/oi_utils.h
+++ /dev/null
@@ -1,362 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2002 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-#ifndef _OI_UTILS_H
-#define _OI_UTILS_H
-/**
- * @file
- *
- * This file provides the interface for utility functions.
- * Among the utilities are strlen (string length), strcmp (string compare), and
- * other string manipulation functions. These are provided for those plaforms
- * where this functionality is not available in stdlib.
- */
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-#include 
-#include "oi_common.h"
-#include "oi_string.h"
-#include "oi_bt_spec.h"
-
-/** \addtogroup Misc Miscellaneous APIs */
-/**@{*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Opaque type for a callback function handle. See OI_ScheduleCallbackFunction()
- */
-typedef OI_UINT32 OI_CALLBACK_HANDLE;
-
-/**
- * Function prototype for a timed procedure callback.
- *
- * @param arg                 Value that was passed into the OI_ScheduleCallback() function
- *
- */
-typedef void (*OI_SCHEDULED_CALLBACK)(void *arg);
-
-/**
- * Registers a function to be called when a timeout expires. This API uses BLUEmagic's internal
- * function dispatch mechanism, so applications that make extensive use of this facility may need to
- * increase the value of DispatchTableSize in the configuration block for the dispatcher (see
- * oi_bt_stack_config.h).
- *
- * @param callbackFunction    The function that will be called when the timeout expires
- *
- * @param arg                 Value that will be returned as the parameter to the callback function.
- *
- * @param timeout             A timeout expressed in OI_INTERVALs (tenths of seconds). This can be
- *                            zero in which case the callback function will be called as soon as
- *                            possible.
- *
- * @param handle              NULL or a pointer receive the callback handle.
- *
- * @return                    OI_OK if the function was reqistered, or an error status.
- */
-OI_STATUS OI_ScheduleCallbackFunction(OI_SCHEDULED_CALLBACK callbackFunction,
-                                      void *arg,
-                                      OI_INTERVAL timeout,
-                                      OI_CALLBACK_HANDLE *handle);
-
-/**
- * Cancels a function registered with OI_ScheduleCallbackFunction() before its timer expires.
- *
- * @param handle              handle returned by  OI_ScheduleCallbackFunction().
- *
- * @return                    OI_OK if the function was cancelled, or an error status.
- */
-OI_STATUS OI_CancelCallbackFunction(OI_CALLBACK_HANDLE handle);
-
-/**
- * Registers a function to be called when a timeout expires. This version does not return a handle
- * so can only be canceled by calling OI_CancelCallback().
- *
- * @param callbackFunction    The function that will be called when the timeout expires
- *
- * @param arg                 Value that will be returned as the parameter to the callback function.
- *
- * @param timeout             A timeout expressed in OI_INTERVALs (tenths of seconds). This can be
- *                            zero in which case the callback function will be called as soon as
- *                            possible.
- *
- * @return                    OI_OK if the function was reqistered, or an error status.
- */
-#define OI_ScheduleCallback(f, a, t) OI_ScheduleCallbackFunction(f, a, t, NULL);
-
-/**
- * Cancels a function registered with OI_ScheduleCallback() before its timer expires. This
- * function will cancel the first entry matches the indicated callback function pointer.
- *
- * @param callbackFunction    The function that was originally registered
- *
- * @return                    OI_OK if the function was cancelled, or an error status.
- */
-OI_STATUS OI_CancelCallback(OI_SCHEDULED_CALLBACK callbackFunction);
-
-/**
- * Parse a Bluetooth device address from the specified string.
- *
- * @param str   the string to parse
- * @param addr  the parsed address, if successful
- *
- * @return TRUE if an address was successfully parsed, FALSE otherwise
- */
-
-OI_BOOL OI_ParseBdAddr(const OI_CHAR *str,
-                       OI_BD_ADDR *addr);
-
-/**
- * Printf function for platforms which have no stdio or printf available.
- * OI_Printf supports the basic formatting types, with the exception of
- * floating point types. Additionally, OI_Printf supports several formats
- * specific to BLUEmagic 3.0 software:
- *
- * \%!   prints the string for an #OI_STATUS value.
- *       @code OI_Printf("There was an error %!", status); @endcode
- *
- * \%@   prints a hex dump of a buffer.
- *       Requires a pointer to the buffer and a signed integer length
- *       (0 for default length). If the buffer is large, only an excerpt will
- *       be printed.
- *       @code OI_Printf("Contents of buffer %@", buffer, sizeof(buffer)); @endcode
- *
- * \%:   prints a Bluetooth address in the form "HH:HH:HH:HH:HH:HH".
- *       Requires a pointer to an #OI_BD_ADDR.
- *       @code OI_Printf("Bluetooth address %:", &bdaddr); @endcode
- *
- * \%^   decodes and prints a data element as formatted XML.
- *       Requires a pointer to an #OI_DATAELEM.
- *       @code OI_Printf("Service attribute list is:\n%^", &attributes); @endcode
- *
- * \%/   prints the base file name of a path, that is, the final substring
- *       following a '/' or '\\' character. Requires a pointer to a null
- *       terminated string.
- *       @code OI_Printf("File %/", "c:\\dir1\\dir2\\file.txt"); @endcode
- *
- * \%~   prints a string, escaping characters as needed to display it in
- *       ASCII. Requires a pointer to an #OI_PSTR and an #OI_UNICODE_ENCODING
- *       parameter.
- *       @code OI_Printf("Identifier %~", &id, OI_UNICODE_UTF16_BE); @endcode
- *
- * \%[   inserts an ANSI color escape sequence. Requires a single character
- *       identifying the color to select. Colors are red (r/R), green (g/G),
- *       blue (b/B), yellow (y/Y), cyan (c/C), magenta (m/M), white (W),
- *       light-gray (l/L), dark-gray (d/D), and black (0). The lower case is
- *       dim, the upper case is bright (except in the case of light-gray and
- *       dark-gray, where bright and dim are identical). Any other value will
- *       select the default color.
- *       @code OI_Printf("%[red text %[black %[normal\n", 'r', '0', 0); @endcode
- *
- * \%a   same as \%s, except '\\r' and '\\n' are output as "" and "".
- *       \%?a is valid, but \%la is not.
- *
- * \%b   prints an integer in base 2.
- *       @code OI_Printf("Bits are %b", I); @endcode
- *
- * \%lb  prints a long integer in base 2.
- *
- * \%?b  prints the least significant N bits of an integer (or long integer)
- *       in base 2. Requires the integer and a length N.
- *       @code OI_Printf("Bottom 4 bits are: %?b", I, 4); @endcode
- *
- * \%B   prints an integer as boolean text, "TRUE" or "FALSE".
- *       @code OI_Printf("The value 0 is %B, the value 1 is %B", 0, 1); @endcode
- *
- * \%?s  prints a substring up to a specified maximum length.
- *       Requires a pointer to a string and a length parameter.
- *       @code OI_Printf("String prefix is %?s", str, 3); @endcode
- *
- * \%ls  same as \%S.
- *
- * \%S   prints a UTF16 string as UTF8 (plain ASCII, plus 8-bit char sequences
- *       where needed). Requires a pointer to #OI_CHAR16. \%?S is valid. The
- *       length parameter is in OI_CHAR16 characters.
- *
- * \%T   prints time, formatted as "secs.msecs".
- *       Requires pointer to #OI_TIME struct, NULL pointer prints current time.
- *       @code OI_Printf("The time now is %T", NULL); @endcode
- *
- *  @param format   The format string
- *
- */
-void OI_Printf(const OI_CHAR *format, ...);
-
-/**
- * Var-args version OI_Printf
- *
- * @param format   Same as for OI_Printf.
- *
- * @param argp     Var-args list.
- */
-void OI_VPrintf(const OI_CHAR *format, va_list argp);
-
-/**
- * Writes a formatted string to a buffer. This function supports the same format specifiers as
- * OI_Printf().
- *
- * @param buffer   Destination buffer for the formatted string.
- *
- * @param bufLen   The length of the destination buffer.
- *
- * @param format   The format string
- *
- * @return   Number of characters written or -1 in the case of an error.
- */
-OI_INT32 OI_SNPrintf(OI_CHAR *buffer,
-                     OI_UINT16 bufLen,
-                     const OI_CHAR *format, ...);
-
-/**
- * Var-args version OI_SNPrintf
- *
- * @param buffer   Destination buffer for the formatted string.
- *
- * @param bufLen   The length of the destination buffer.
- *
- * @param format   The format string
- *
- * @param argp     Var-args list.
- *
- * @return   Number of characters written or -1 in the case of an error.
- */
-OI_INT32 OI_VSNPrintf(OI_CHAR *buffer,
-                      OI_UINT16 bufLen,
-                      const OI_CHAR *format, va_list argp);
-
-/**
- * Convert a string to an integer.
- *
- * @param str  the string to parse
- *
- * @return the integer value of the string or 0 if the string could not be parsed
- */
-OI_INT OI_atoi(const OI_CHAR *str);
-
-/**
- * Parse a signed integer in a string.
- *
- * Skips leading whitespace (space and tabs only) and parses a decimal or hex string. Hex string
- * must be prefixed by "0x". Returns pointer to first character following the integer. Returns the
- * pointer passed in if the string does not describe an integer.
- *
- * @param str    String to parse.
- *
- * @param val    Pointer to receive the parsed integer value.
- *
- * @return       A pointer to the first character following the integer or the pointer passed in.
- */
-const OI_CHAR *OI_ScanInt(const OI_CHAR *str,
-                          OI_INT32 *val);
-
-/**
- * Parse an unsigned integer in a string.
- *
- * Skips leading whitespace (space and tabs only) and parses a decimal or hex string. Hex string
- * must be prefixed by "0x". Returns pointer to first character following the integer. Returns the
- * pointer passed in if the string does not describe an integer.
- *
- * @param str    String to parse.
- *
- * @param val    Pointer to receive the parsed unsigned integer value.
- *
- * @return       A pointer to the first character following the unsigned integer or the pointer passed in.
- */
-const OI_CHAR *OI_ScanUInt(const OI_CHAR *str,
-                           OI_UINT32 *val);
-
-/**
- * Parse a whitespace delimited substring out of a string.
- *
- * @param str     Input string to parse.
- * @param outStr  Buffer to return the substring
- * @param len     Length of outStr
- *
- *
- * @return       A pointer to the first character following the substring or the pointer passed in.
- */
-const OI_CHAR *OI_ScanStr(const OI_CHAR *str,
-                          OI_CHAR *outStr,
-                          OI_UINT16 len);
-
-/**
- * Parse a string for one of a set of alternative value. Skips leading whitespace (space and tabs
- * only) and parses text matching one of the alternative strings. Returns pointer to first character
- * following the matched text.
- *
- * @param str    String to parse.
- *
- * @param alts   Alternative matching strings separated by '|'
- *
- * @param index  Pointer to receive the index of the matching alternative, return value is -1 if
- *               there is no match.
- *
- * @return       A pointer to the first character following the matched value or the pointer passed in
- *               if there was no matching text.
- */
-const OI_CHAR *OI_ScanAlt(const OI_CHAR *str,
-                          const OI_CHAR *alts,
-                          OI_INT *index);
-
-/**
- * Parse a string for a BD Addr. Skips leading whitespace (space and tabs only) and parses a
- * Bluetooth device address with nibbles optionally separated by colons. Return pointet to first
- * character following the BD Addr.
- *
- * @param str    String to parse.
- *
- * @param addr   Pointer to receive the Bluetooth device address
- *
- * @return       A pointer to the first character following the BD Addr or the pointer passed in.
- */
-const OI_CHAR *OI_ScanBdAddr(const OI_CHAR *str,
-                             OI_BD_ADDR *addr);
-
-/** Get a character from a digit integer value (0 - 9). */
-#define OI_DigitToChar(d) ((d) + '0')
-
-/**
- * Determine Maximum and Minimum between two arguments.
- *
- * @param a  1st value
- * @param b  2nd value
- *
- * @return the max or min value between a & b
- */
-#define OI_MAX(a, b) (((a) < (b)) ? (b) : (a))
-#define OI_MIN(a, b) (((a) > (b)) ? (b) : (a))
-
-/**
- * Compare two BD_ADDRs
- * SAME_BD_ADDR - Boolean: TRUE if they are the same address
- */
-
-#define SAME_BD_ADDR(x, y) (0 == OI_MemCmp((x), (y), OI_BD_ADDR_BYTE_SIZE))
-
-#ifdef __cplusplus
-}
-#endif
-
-/**@}*/
-
-#endif /* _OI_UTILS_H */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/readsamplesjoint.inc b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/readsamplesjoint.inc
deleted file mode 100644
index 875a39497..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/readsamplesjoint.inc
+++ /dev/null
@@ -1,111 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/*******************************************************************************
- * @file readsamplesjoint.inc
- *
- * This is the body of the generic version of OI_SBC_ReadSamplesJoint().
- * It is designed to be \#included into a function as follows:
-    \code
-    void OI_SBC_ReadSamplesJoint4(OI_CODEC_SBC_COMMON_CONTEXT *common, OI_BITSTREAM *global_bs)
-    {
-        #define NROF_SUBBANDS 4
-        #include "readsamplesjoint.inc"
-        #undef NROF_SUBBANDS
-    }
-
-    void OI_SBC_ReadSamplesJoint8(OI_CODEC_SBC_COMMON_CONTEXT *common, OI_BITSTREAM *global_bs)
-    {
-        #define NROF_SUBBANDS 8
-        #include "readsamplesjoint.inc"
-        #undef NROF_SUBBANDS
-    }
-    \endcode
- * Or to make a generic version:
-    \code
-    void OI_SBC_ReadSamplesJoint(OI_CODEC_SBC_COMMON_CONTEXT *common, OI_BITSTREAM *global_bs)
-    {
-        OI_UINT nrof_subbands = common->frameInfo.nrof_subbands;
-
-        #define NROF_SUBBANDS nrof_subbands
-        #include "readsamplesjoint.inc"
-        #undef NROF_SUBBANDS
-    }
-    \endcode
- * @ingroup codec_internal
- *******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-{
-    OI_CODEC_SBC_COMMON_CONTEXT *common = &context->common;
-    OI_UINT bl = common->frameInfo.nrof_blocks;
-    OI_INT32 * RESTRICT s = common->subdata;
-    OI_UINT8 *ptr = global_bs->ptr.w;
-    OI_UINT32 value = global_bs->value;
-    OI_UINT bitPtr = global_bs->bitPtr;
-    OI_UINT8 jmask = common->frameInfo.join << (8 - NROF_SUBBANDS);
-
-    do {
-        OI_INT8 *sf_array = &common->scale_factor[0];
-        OI_UINT8 *bits_array = &common->bits.uint8[0];
-        OI_UINT8 joint = jmask;
-        OI_UINT sb;
-        /*
-         * Left channel
-         */
-        sb = NROF_SUBBANDS;
-        do {
-            OI_UINT32 raw;
-            OI_INT32 dequant;
-            OI_UINT8 bits = *bits_array++;
-            OI_INT sf = *sf_array++;
-
-            OI_BITSTREAM_READUINT(raw, bits, ptr, value, bitPtr);
-            dequant = OI_SBC_Dequant(raw, sf, bits);
-            *s++ = dequant;
-        } while (--sb);
-        /*
-         * Right channel
-         */
-        sb = NROF_SUBBANDS;
-        do {
-            OI_UINT32 raw;
-            OI_INT32 dequant;
-            OI_UINT8 bits = *bits_array++;
-            OI_INT sf = *sf_array++;
-
-            OI_BITSTREAM_READUINT(raw, bits, ptr, value, bitPtr);
-            dequant = OI_SBC_Dequant(raw, sf, bits);
-            /*
-             * Check if we need to do mid/side
-             */
-            if (joint & 0x80) {
-                OI_INT32 mid = *(s - NROF_SUBBANDS);
-                OI_INT32 side = dequant;
-                *(s - NROF_SUBBANDS) = mid + side;
-                dequant = mid - side;
-            }
-            joint <<= 1;
-            *s++ = dequant;
-        } while (--sb);
-    } while (--bl);
-}
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c
deleted file mode 100644
index 71ff6a9e0..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-8-generated.c
+++ /dev/null
@@ -1,161 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**
- @file
-
- DO NOT EDIT THIS FILE DIRECTLY
-
- This file is automatically generated by the "synthesis-gen.pl" script.
- Any changes to this generated file will be lost when the script is re-run.
-
- These functions are called by functions in synthesis.c to perform the synthesis
- filterbank computations for the SBC decoder.
-
-
- */
-#include 
-
-#if defined(SBC_DEC_INCLUDED)
-
-#ifndef CLIP_INT16
-#define CLIP_INT16(x)                  \
-    do {                               \
-        if (x > OI_INT16_MAX) {        \
-            x = OI_INT16_MAX;          \
-        } else if (x < OI_INT16_MIN) { \
-            x = OI_INT16_MIN;          \
-        }                              \
-    } while (0)
-#endif
-
-#define MUL_16S_16S(_x, _y) ((_x) * (_y))
-
-PRIVATE void SynthWindow80_generated(OI_INT16 *pcm, SBC_BUFFER_T const *RESTRICT buffer, OI_UINT strideShift)
-{
-    OI_INT32 pcm_a, pcm_b;
-    /* 1 - stage 0 */ pcm_b = 0;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(8235, buffer[12])) >> 3;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(-23167, buffer[20])) >> 3;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(26479, buffer[28])) >> 2;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(-17397, buffer[36])) << 1;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(9399, buffer[44])) << 3;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(17397, buffer[52])) << 1;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(26479, buffer[60])) >> 2;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(23167, buffer[68])) >> 3;
-    /* 1 - stage 0 */ pcm_b += (MUL_16S_16S(8235, buffer[76])) >> 3;
-    /* 1 - stage 0 */ pcm_b /= 32768;
-    CLIP_INT16(pcm_b);
-    pcm[0 << strideShift] = (OI_INT16)pcm_b;
-    /* 1 - stage 1 */ pcm_a = 0;
-    /* 1 - stage 1 */ pcm_b = 0;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(-3263, buffer[5])) >> 5;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(9293, buffer[5])) >> 3;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(29293, buffer[11])) >> 5;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(-6087, buffer[11])) >> 2;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(-5229, buffer[21]));
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(1247, buffer[21])) << 3;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(30835, buffer[27])) >> 3;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(-2893, buffer[27])) << 3;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(-27021, buffer[37])) << 1;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(23671, buffer[37])) << 2;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(31633, buffer[43])) << 1;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(18055, buffer[43])) << 1;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(17319, buffer[53])) << 1;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(11537, buffer[53])) >> 1;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(26663, buffer[59])) >> 2;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(1747, buffer[59])) << 1;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(4555, buffer[69])) >> 1;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(685, buffer[69])) << 1;
-    /* 1 - stage 1 */ pcm_a += (MUL_16S_16S(12419, buffer[75])) >> 4;
-    /* 1 - stage 1 */ pcm_b += (MUL_16S_16S(8721, buffer[75])) >> 7;
-    /* 1 - stage 1 */ pcm_a /= 32768;
-    CLIP_INT16(pcm_a);
-    pcm[1 << strideShift] = (OI_INT16)pcm_a;
-    /* 1 - stage 1 */ pcm_b /= 32768;
-    CLIP_INT16(pcm_b);
-    pcm[7 << strideShift] = (OI_INT16)pcm_b;
-    /* 1 - stage 2 */ pcm_a = 0;
-    /* 1 - stage 2 */ pcm_b = 0;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(-10385, buffer[6])) >> 6;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(11167, buffer[6])) >> 4;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(24995, buffer[10])) >> 5;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(-10337, buffer[10])) >> 4;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(-309, buffer[22])) << 4;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(1917, buffer[22])) << 2;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(9161, buffer[26])) >> 3;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(-30605, buffer[26])) >> 1;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(-23063, buffer[38])) << 1;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(8317, buffer[38])) << 3;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(27561, buffer[42])) << 1;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(9553, buffer[42])) << 2;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(2309, buffer[54])) << 3;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(22117, buffer[54])) >> 4;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(12705, buffer[58])) >> 1;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(16383, buffer[58])) >> 2;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(6239, buffer[70])) >> 3;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(7543, buffer[70])) >> 3;
-    /* 1 - stage 2 */ pcm_a += (MUL_16S_16S(9251, buffer[74])) >> 4;
-    /* 1 - stage 2 */ pcm_b += (MUL_16S_16S(8603, buffer[74])) >> 6;
-    /* 1 - stage 2 */ pcm_a /= 32768;
-    CLIP_INT16(pcm_a);
-    pcm[2 << strideShift] = (OI_INT16)pcm_a;
-    /* 1 - stage 2 */ pcm_b /= 32768;
-    CLIP_INT16(pcm_b);
-    pcm[6 << strideShift] = (OI_INT16)pcm_b;
-    /* 1 - stage 3 */ pcm_a = 0;
-    /* 1 - stage 3 */ pcm_b = 0;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-16457, buffer[7])) >> 6;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(16913, buffer[7])) >> 5;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(19083, buffer[9])) >> 5;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(-8443, buffer[9])) >> 7;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-23641, buffer[23])) >> 2;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(3687, buffer[23])) << 1;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-29015, buffer[25])) >> 4;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(-301, buffer[25])) << 5;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(-12889, buffer[39])) << 2;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(15447, buffer[39])) << 2;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(6145, buffer[41])) << 3;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(10255, buffer[41])) << 2;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(24211, buffer[55])) >> 1;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(-18233, buffer[55])) >> 3;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(23469, buffer[57])) >> 2;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(9405, buffer[57])) >> 1;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(21223, buffer[71])) >> 8;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(1499, buffer[71])) >> 1;
-    /* 1 - stage 3 */ pcm_a += (MUL_16S_16S(26913, buffer[73])) >> 6;
-    /* 1 - stage 3 */ pcm_b += (MUL_16S_16S(26189, buffer[73])) >> 7;
-    /* 1 - stage 3 */ pcm_a /= 32768;
-    CLIP_INT16(pcm_a);
-    pcm[3 << strideShift] = (OI_INT16)pcm_a;
-    /* 1 - stage 3 */ pcm_b /= 32768;
-    CLIP_INT16(pcm_b);
-    pcm[5 << strideShift] = (OI_INT16)pcm_b;
-    /* 1 - stage 4 */ pcm_a = 0;
-    /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(10445, buffer[8])) >> 4;
-    /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(-5297, buffer[24])) << 1;
-    /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(22299, buffer[40])) << 2;
-    /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(10603, buffer[56]));
-    /* 1 - stage 4 */ pcm_a += (MUL_16S_16S(9539, buffer[72])) >> 4;
-    /* 1 - stage 4 */ pcm_a /= 32768;
-    CLIP_INT16(pcm_a);
-    pcm[4 << strideShift] = (OI_INT16)pcm_a;
-}
-
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c
deleted file mode 100644
index aa70d3bc3..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-dct8.c
+++ /dev/null
@@ -1,349 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/** @file
-@ingroup codec_internal
-*/
-
-/**@addgroup codec_internal*/
-/**@{*/
-
-/*
- * Performs an 8-point Type-II scaled DCT using the Arai-Agui-Nakajima
- * factorization. The scaling factors are folded into the windowing
- * constants. 29 adds and 5 16x32 multiplies per 8 samples.
- */
-#include "oi_codec_sbc_private.h"
-
-#if defined(SBC_DEC_INCLUDED)
-
-#define AAN_C4_FIX (759250125) /* S1.30  759250125   0.707107*/
-
-#define AAN_C6_FIX (410903207) /* S1.30  410903207   0.382683*/
-
-#define AAN_Q0_FIX (581104888) /* S1.30  581104888   0.541196*/
-
-#define AAN_Q1_FIX (1402911301) /* S1.30 1402911301   1.306563*/
-
-/** Scales x by y bits to the right, adding a rounding factor.
- */
-#ifndef SCALE
-#define SCALE(x, y) (((x) + (1 << ((y)-1))) >> (y))
-#endif
-
-/**
- * Default C language implementation of a 32x32->32 multiply. This function may
- * be replaced by a platform-specific version for speed.
- *
- * @param u A signed 32-bit multiplicand
- * @param v A signed 32-bit multiplier
-
- * @return  A signed 32-bit value corresponding to the 32 most significant bits
- * of the 64-bit product of u and v.
- */
-static INLINE OI_INT32 default_mul_32s_32s_hi(OI_INT32 u, OI_INT32 v)
-{
-    OI_UINT32 u0, v0;
-    OI_INT32 u1, v1, w1, w2, t;
-
-    u0 = u & 0xFFFF;
-    u1 = u >> 16;
-    v0 = v & 0xFFFF;
-    v1 = v >> 16;
-    t = u0 * v0;
-    t = u1 * v0 + ((OI_UINT32)t >> 16);
-    w1 = t & 0xFFFF;
-    w2 = t >> 16;
-    w1 = u0 * v1 + w1;
-    return u1 * v1 + w2 + (w1 >> 16);
-}
-
-#define MUL_32S_32S_HI(_x, _y) default_mul_32s_32s_hi(_x, _y)
-
-#ifdef DEBUG_DCT
-PRIVATE void float_dct2_8(float *RESTRICT out, OI_INT32 const *RESTRICT in)
-{
-#define FIX(x, bits) (((int)floor(0.5f + ((x) * ((float)(1 << bits))))) / ((float)(1 << bits)))
-#define FLOAT_BUTTERFLY(x, y)  \
-    x += y;                    \
-    y = x - (y * 2);           \
-    OI_ASSERT(VALID_INT32(x)); \
-    OI_ASSERT(VALID_INT32(y));
-#define FLOAT_MULT_DCT(K, sample) (FIX(K, 20) * sample)
-#define FLOAT_SCALE(x, y)         (((x) / (double)(1 << (y))))
-
-    double L00, L01, L02, L03, L04, L05, L06, L07;
-    double L25;
-
-    double in0, in1, in2, in3;
-    double in4, in5, in6, in7;
-
-    in0 = FLOAT_SCALE(in[0], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in0));
-    in1 = FLOAT_SCALE(in[1], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in1));
-    in2 = FLOAT_SCALE(in[2], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in2));
-    in3 = FLOAT_SCALE(in[3], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in3));
-    in4 = FLOAT_SCALE(in[4], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in4));
-    in5 = FLOAT_SCALE(in[5], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in5));
-    in6 = FLOAT_SCALE(in[6], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in6));
-    in7 = FLOAT_SCALE(in[7], DCTII_8_SHIFT_IN);
-    OI_ASSERT(VALID_INT32(in7));
-
-    L00 = (in0 + in7);
-    OI_ASSERT(VALID_INT32(L00));
-    L01 = (in1 + in6);
-    OI_ASSERT(VALID_INT32(L01));
-    L02 = (in2 + in5);
-    OI_ASSERT(VALID_INT32(L02));
-    L03 = (in3 + in4);
-    OI_ASSERT(VALID_INT32(L03));
-
-    L04 = (in3 - in4);
-    OI_ASSERT(VALID_INT32(L04));
-    L05 = (in2 - in5);
-    OI_ASSERT(VALID_INT32(L05));
-    L06 = (in1 - in6);
-    OI_ASSERT(VALID_INT32(L06));
-    L07 = (in0 - in7);
-    OI_ASSERT(VALID_INT32(L07));
-
-    FLOAT_BUTTERFLY(L00, L03);
-    FLOAT_BUTTERFLY(L01, L02);
-
-    L02 += L03;
-    OI_ASSERT(VALID_INT32(L02));
-
-    L02 = FLOAT_MULT_DCT(AAN_C4_FLOAT, L02);
-    OI_ASSERT(VALID_INT32(L02));
-
-    FLOAT_BUTTERFLY(L00, L01);
-
-    out[0] = (float)FLOAT_SCALE(L00, DCTII_8_SHIFT_0);
-    OI_ASSERT(VALID_INT16(out[0]));
-    out[4] = (float)FLOAT_SCALE(L01, DCTII_8_SHIFT_4);
-    OI_ASSERT(VALID_INT16(out[4]));
-
-    FLOAT_BUTTERFLY(L03, L02);
-    out[6] = (float)FLOAT_SCALE(L02, DCTII_8_SHIFT_6);
-    OI_ASSERT(VALID_INT16(out[6]));
-    out[2] = (float)FLOAT_SCALE(L03, DCTII_8_SHIFT_2);
-    OI_ASSERT(VALID_INT16(out[2]));
-
-    L04 += L05;
-    OI_ASSERT(VALID_INT32(L04));
-    L05 += L06;
-    OI_ASSERT(VALID_INT32(L05));
-    L06 += L07;
-    OI_ASSERT(VALID_INT32(L06));
-
-    L04 /= 2;
-    L05 /= 2;
-    L06 /= 2;
-    L07 /= 2;
-
-    L05 = FLOAT_MULT_DCT(AAN_C4_FLOAT, L05);
-    OI_ASSERT(VALID_INT32(L05));
-
-    L25 = L06 - L04;
-    OI_ASSERT(VALID_INT32(L25));
-    L25 = FLOAT_MULT_DCT(AAN_C6_FLOAT, L25);
-    OI_ASSERT(VALID_INT32(L25));
-
-    L04 = FLOAT_MULT_DCT(AAN_Q0_FLOAT, L04);
-    OI_ASSERT(VALID_INT32(L04));
-    L04 -= L25;
-    OI_ASSERT(VALID_INT32(L04));
-
-    L06 = FLOAT_MULT_DCT(AAN_Q1_FLOAT, L06);
-    OI_ASSERT(VALID_INT32(L06));
-    L06 -= L25;
-    OI_ASSERT(VALID_INT32(L25));
-
-    FLOAT_BUTTERFLY(L07, L05);
-
-    FLOAT_BUTTERFLY(L05, L04);
-    out[3] = (float)(FLOAT_SCALE(L04, DCTII_8_SHIFT_3 - 1));
-    OI_ASSERT(VALID_INT16(out[3]));
-    out[5] = (float)(FLOAT_SCALE(L05, DCTII_8_SHIFT_5 - 1));
-    OI_ASSERT(VALID_INT16(out[5]));
-
-    FLOAT_BUTTERFLY(L07, L06);
-    out[7] = (float)(FLOAT_SCALE(L06, DCTII_8_SHIFT_7 - 1));
-    OI_ASSERT(VALID_INT16(out[7]));
-    out[1] = (float)(FLOAT_SCALE(L07, DCTII_8_SHIFT_1 - 1));
-    OI_ASSERT(VALID_INT16(out[1]));
-}
-#undef BUTTERFLY
-#endif
-
-/*
- * This function calculates the AAN DCT. Its inputs are in S16.15 format, as
- * returned by OI_SBC_Dequant. In practice, abs(in[x]) < 52429.0 / 1.38
- * (1244918057 integer). The function it computes is an approximation to the array defined
- * by:
- *
- * diag(aan_s) * AAN= C2
- *
- *   or
- *
- * AAN = diag(1/aan_s) * C2
- *
- * where C2 is as it is defined in the comment at the head of this file, and
- *
- * aan_s[i] = aan_s = 1/(2*cos(i*pi/16)) with i = 1..7, aan_s[0] = 1;
- *
- * aan_s[i] = [ 1.000  0.510  0.541  0.601  0.707  0.900  1.307  2.563 ]
- *
- * The output ranges are shown as follows:
- *
- * Let Y[0..7] = AAN * X[0..7]
- *
- * Without loss of generality, assume the input vector X consists of elements
- * between -1 and 1. The maximum possible value of a given output element occurs
- * with some particular combination of input vector elements each of which is -1
- * or 1. Consider the computation of Y[i]. Y[i] = sum t=0..7 of AAN[t,i]*X[i]. Y is
- * maximized if the sign of X[i] matches the sign of AAN[t,i], ensuring a
- * positive contribution to the sum. Equivalently, one may simply sum
- * abs(AAN)[t,i] over t to get the maximum possible value of Y[i].
- *
- * This yields approximately [8.00  10.05   9.66   8.52   8.00   5.70   4.00   2.00]
- *
- * Given the maximum magnitude sensible input value of +/-37992, this yields the
- * following vector of maximum output magnitudes:
- *
- * [ 303936  381820  367003  323692  303936  216555  151968   75984 ]
- *
- * Ultimately, these values must fit into 16 bit signed integers, so they must
- * be scaled. A non-uniform scaling helps maximize the kept precision. The
- * relative number of extra bits of precision maintainable with respect to the
- * largest value is given here:
- *
- * [ 0  0  0  0  0  0  1  2 ]
- *
- */
-PRIVATE void dct2_8(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT in)
-{
-#define BUTTERFLY(x, y) \
-    x += y;             \
-    y = x - (y << 1);
-#define FIX_MULT_DCT(K, x) (MUL_32S_32S_HI(K, x) << 2)
-
-    OI_INT32 L00, L01, L02, L03, L04, L05, L06, L07;
-    OI_INT32 L25;
-
-    OI_INT32 in0, in1, in2, in3;
-    OI_INT32 in4, in5, in6, in7;
-
-#if DCTII_8_SHIFT_IN != 0
-    in0 = SCALE(in[0], DCTII_8_SHIFT_IN);
-    in1 = SCALE(in[1], DCTII_8_SHIFT_IN);
-    in2 = SCALE(in[2], DCTII_8_SHIFT_IN);
-    in3 = SCALE(in[3], DCTII_8_SHIFT_IN);
-    in4 = SCALE(in[4], DCTII_8_SHIFT_IN);
-    in5 = SCALE(in[5], DCTII_8_SHIFT_IN);
-    in6 = SCALE(in[6], DCTII_8_SHIFT_IN);
-    in7 = SCALE(in[7], DCTII_8_SHIFT_IN);
-#else
-    in0 = in[0];
-    in1 = in[1];
-    in2 = in[2];
-    in3 = in[3];
-    in4 = in[4];
-    in5 = in[5];
-    in6 = in[6];
-    in7 = in[7];
-#endif
-
-    L00 = in0 + in7;
-    L01 = in1 + in6;
-    L02 = in2 + in5;
-    L03 = in3 + in4;
-
-    L04 = in3 - in4;
-    L05 = in2 - in5;
-    L06 = in1 - in6;
-    L07 = in0 - in7;
-
-    BUTTERFLY(L00, L03);
-    BUTTERFLY(L01, L02);
-
-    L02 += L03;
-
-    L02 = FIX_MULT_DCT(AAN_C4_FIX, L02);
-
-    BUTTERFLY(L00, L01);
-
-    out[0] = (OI_INT16)SCALE(L00, DCTII_8_SHIFT_0);
-    out[4] = (OI_INT16)SCALE(L01, DCTII_8_SHIFT_4);
-
-    BUTTERFLY(L03, L02);
-    out[6] = (OI_INT16)SCALE(L02, DCTII_8_SHIFT_6);
-    out[2] = (OI_INT16)SCALE(L03, DCTII_8_SHIFT_2);
-
-    L04 += L05;
-    L05 += L06;
-    L06 += L07;
-
-    L04 /= 2;
-    L05 /= 2;
-    L06 /= 2;
-    L07 /= 2;
-
-    L05 = FIX_MULT_DCT(AAN_C4_FIX, L05);
-
-    L25 = L06 - L04;
-    L25 = FIX_MULT_DCT(AAN_C6_FIX, L25);
-
-    L04 = FIX_MULT_DCT(AAN_Q0_FIX, L04);
-    L04 -= L25;
-
-    L06 = FIX_MULT_DCT(AAN_Q1_FIX, L06);
-    L06 -= L25;
-
-    BUTTERFLY(L07, L05);
-
-    BUTTERFLY(L05, L04);
-    out[3] = (OI_INT16)SCALE(L04, DCTII_8_SHIFT_3 - 1);
-    out[5] = (OI_INT16)SCALE(L05, DCTII_8_SHIFT_5 - 1);
-
-    BUTTERFLY(L07, L06);
-    out[7] = (OI_INT16)SCALE(L06, DCTII_8_SHIFT_7 - 1);
-    out[1] = (OI_INT16)SCALE(L07, DCTII_8_SHIFT_1 - 1);
-#undef BUTTERFLY
-
-#ifdef DEBUG_DCT
-    {
-        float float_out[8];
-        float_dct2_8(float_out, in);
-    }
-#endif
-}
-
-/**@}*/
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c
deleted file mode 100644
index e343cf3db..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/dec/synthesis-sbc.c
+++ /dev/null
@@ -1,524 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 2014 The Android Open Source Project
- *  Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/**********************************************************************************
-  $Revision: #1 $
-***********************************************************************************/
-
-/** @file
-
-This file, along with synthesis-generated.c, contains the synthesis
-filterbank routines. The operations performed correspond to the
-operations described in A2DP Appendix B, Figure 12.3. Several
-mathematical optimizations are performed, particularly for the
-8-subband case.
-
-One important optimization is to note that the "matrixing" operation
-can be decomposed into the product of a type II discrete cosine kernel
-and another, sparse matrix.
-
-According to Fig 12.3, in the 8-subband case,
-@code
-    N[k][i] = cos((i+0.5)*(k+4)*pi/8), k = 0..15 and i = 0..7
-@endcode
-
-N can be factored as R * C2, where C2 is an 8-point type II discrete
-cosine kernel given by
-@code
-    C2[k][i] = cos((i+0.5)*k*pi/8)), k = 0..7 and i = 0..7
-@endcode
-
-R turns out to be a sparse 16x8 matrix with the following non-zero
-entries:
-@code
-    R[k][k+4]        =  1,   k = 0..3
-    R[k][abs(12-k)]  = -1,   k = 5..15
-@endcode
-
-The spec describes computing V[0..15] as N * R.
-@code
-    V[0..15] = N * R = (R * C2) * R = R * (C2 * R)
-@endcode
-
-C2 * R corresponds to computing the discrete cosine transform of R, so
-V[0..15] can be computed by taking the DCT of R followed by assignment
-and selective negation of the DCT result into V.
-
-        Although this was derived empirically using GNU Octave, it is
-        formally demonstrated in, e.g., Liu, Chi-Min and Lee,
-        Wen-Chieh. "A Unified Fast Algorithm for Cosine Modulated
-        Filter Banks in Current Audio Coding Standards." Journal of
-        the AES 47 (December 1999): 1061.
-
-Given the shift operation performed prior to computing V[0..15], it is
-clear that V[0..159] represents a rolling history of the 10 most
-recent groups of blocks input to the synthesis operation. Interpreting
-the matrix N in light of its factorization into C2 and R, R's
-sparseness has implications for interpreting the values in V. In
-particular, there is considerable redundancy in the values stored in
-V. Furthermore, since R[4][0..7] are all zeros, one out of every 16
-values in V will be zero regardless of the input data. Within each
-block of 16 values in V, fully half of them are redundant or
-irrelevant:
-
-@code
-    V[ 0] =  DCT[4]
-    V[ 1] =  DCT[5]
-    V[ 2] =  DCT[6]
-    V[ 3] =  DCT[7]
-    V[ 4] = 0
-    V[ 5] = -DCT[7] = -V[3] (redundant)
-    V[ 6] = -DCT[6] = -V[2] (redundant)
-    V[ 7] = -DCT[5] = -V[1] (redundant)
-    V[ 8] = -DCT[4] = -V[0] (redundant)
-    V[ 9] = -DCT[3]
-    V[10] = -DCT[2]
-    V[11] = -DCT[1]
-    V[12] = -DCT[0]
-    V[13] = -DCT[1] = V[11] (redundant)
-    V[14] = -DCT[2] = V[10] (redundant)
-    V[15] = -DCT[3] = V[ 9] (redundant)
-@endcode
-
-Since the elements of V beyond 15 were originally computed the same
-way during a previous run, what holds true for V[x] also holds true
-for V[x+16]. Thus, so long as care is taken to maintain the mapping,
-we need only actually store the unique values, which correspond to the
-output of the DCT, in some cases inverted. In fact, instead of storing
-V[0..159], we could store DCT[0..79] which would contain a history of
-DCT results. More on this in a bit.
-
-Going back to figure 12.3 in the spec, it should be clear that the
-vector U need not actually be explicitly constructed, but that with
-suitable indexing into V during the window operation, the same end can
-be accomplished. In the same spirit of the pseudocode shown in the
-figure, the following is the construction of W without using U:
-
-@code
-    for i=0 to 79 do
-        W[i] = D[i]*VSIGN(i)*V[remap_V(i)] where remap_V(i) = 32*(int(i/16)) + (i % 16) + (i % 16 >= 8 ? 16 : 0)
-                                             and VSIGN(i) maps i%16 into {1, 1, 1, 1, 0, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1 }
-                                             These values correspond to the
-                                             signs of the redundant values as
-                                             shown in the explanation three
-                                             paragraphs above.
-@endcode
-
-We saw above how V[4..8,13..15] (and by extension
-V[(4..8,13..15)+16*n]) can be defined in terms of other elements
-within the subblock of V. V[0..3,9..12] correspond to DCT elements.
-
-@code
-    for i=0 to 79 do
-        W[i] = D[i]*DSIGN(i)*DCT[remap_DCT(i)]
-@endcode
-
-The DCT is calculated using the Arai-Agui-Nakajima factorization,
-which saves some computation by producing output that needs to be
-multiplied by scaling factors before being used.
-
-@code
-    for i=0 to 79 do
-        W[i] = D[i]*SCALE[i%8]*AAN_DCT[remap_DCT(i)]
-@endcode
-
-D can be premultiplied with the DCT scaling factors to yield
-
-@code
-    for i=0 to 79 do
-        W[i] = DSCALED[i]*AAN_DCT[remap_DCT(i)] where DSCALED[i] = D[i]*SCALE[i%8]
-@endcode
-
-The output samples X[0..7] are defined as sums of W:
-
-@code
-        X[j] = sum{i=0..9}(W[j+8*i])
-@endcode
-
-@ingroup codec_internal
-*/
-
-/**
-@addtogroup codec_internal
-@{
-*/
-#include "oi_codec_sbc_private.h"
-
-#if defined(SBC_DEC_INCLUDED)
-
-const OI_INT32 dec_window_4[21] = {
-    0,      /* +0.00000000E+00 */
-    97,     /* +5.36548976E-04 */
-    270,    /* +1.49188357E-03 */
-    495,    /* +2.73370904E-03 */
-    694,    /* +3.83720193E-03 */
-    704,    /* +3.89205149E-03 */
-    338,    /* +1.86581691E-03 */
-    -554,   /* -3.06012286E-03 */
-    1974,   /* +1.09137620E-02 */
-    3697,   /* +2.04385087E-02 */
-    5224,   /* +2.88757392E-02 */
-    5824,   /* +3.21939290E-02 */
-    4681,   /* +2.58767811E-02 */
-    1109,   /* +6.13245186E-03 */
-    -5214,  /* -2.88217274E-02 */
-    -14047, /* -7.76463494E-02 */
-    24529,  /* +1.35593274E-01 */
-    35274,  /* +1.94987841E-01 */
-    44618,  /* +2.46636662E-01 */
-    50984,  /* +2.81828203E-01 */
-    53243,  /* +2.94315332E-01 */
-};
-
-#define DCTII_4_K06_FIX (11585) /* S1.14      11585   0.707107*/
-
-#define DCTII_4_K08_FIX (21407) /* S1.14      21407   1.306563*/
-
-#define DCTII_4_K09_FIX (-15137) /* S1.14     -15137  -0.923880*/
-
-#define DCTII_4_K10_FIX (-8867) /* S1.14      -8867  -0.541196*/
-
-/** Scales x by y bits to the right, adding a rounding factor.
- */
-#ifndef SCALE
-#define SCALE(x, y) (((x) + (1 << ((y)-1))) >> (y))
-#endif
-
-#ifndef CLIP_INT16
-#define CLIP_INT16(x)                  \
-    do {                               \
-        if (x > OI_INT16_MAX) {        \
-            x = OI_INT16_MAX;          \
-        } else if (x < OI_INT16_MIN) { \
-            x = OI_INT16_MIN;          \
-        }                              \
-    } while (0)
-#endif
-
-/**
- * Default C language implementation of a 16x32->32 multiply. This function may
- * be replaced by a platform-specific version for speed.
- *
- * @param u A signed 16-bit multiplicand
- * @param v A signed 32-bit multiplier
-
- * @return  A signed 32-bit value corresponding to the 32 most significant bits
- * of the 48-bit product of u and v.
- */
-static INLINE OI_INT32 default_mul_16s_32s_hi(OI_INT16 u, OI_INT32 v)
-{
-    OI_UINT16 v0;
-    OI_INT16 v1;
-
-    OI_INT32 w, x;
-
-    v0 = (OI_UINT16)(v & 0xffff);
-    v1 = (OI_INT16)(v >> 16);
-
-    w = v1 * u;
-    x = u * v0;
-
-    return w + (x >> 16);
-}
-
-#define MUL_16S_32S_HI(_x, _y) default_mul_16s_32s_hi(_x, _y)
-
-#define LONG_MULT_DCT(K, sample) (MUL_16S_32S_HI(K, sample) << 2)
-
-PRIVATE void SynthWindow80_generated(OI_INT16 *pcm, SBC_BUFFER_T const *RESTRICT buffer, OI_UINT strideShift);
-PRIVATE void SynthWindow112_generated(OI_INT16 *pcm, SBC_BUFFER_T const *RESTRICT buffer, OI_UINT strideShift);
-PRIVATE void dct2_8(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT x);
-
-typedef void (*SYNTH_FRAME)(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount);
-
-#ifndef COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS
-#define COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(dest, src) \
-    do {                                                    \
-        shift_buffer(dest, src, 72);                        \
-    } while (0)
-#endif
-
-#ifndef DCT2_8
-#define DCT2_8(dst, src) dct2_8(dst, src)
-#endif
-
-#ifndef SYNTH80
-#define SYNTH80 SynthWindow80_generated
-#endif
-
-#ifndef SYNTH112
-#define SYNTH112 SynthWindow112_generated
-#endif
-
-PRIVATE void OI_SBC_SynthFrame_80(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount)
-{
-    OI_UINT blk;
-    OI_UINT ch;
-    OI_UINT nrof_channels = context->common.frameInfo.nrof_channels;
-    OI_UINT pcmStrideShift = context->common.pcmStride == 1 ? 0 : 1;
-    OI_UINT offset = context->common.filterBufferOffset;
-    OI_INT32 *s = context->common.subdata + 8 * nrof_channels * blkstart;
-    OI_UINT blkstop = blkstart + blkcount;
-
-    for (blk = blkstart; blk < blkstop; blk++) {
-        if (offset == 0) {
-            COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[0] + context->common.filterBufferLen - 72, context->common.filterBuffer[0]);
-            if (nrof_channels == 2) {
-                COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[1] + context->common.filterBufferLen - 72, context->common.filterBuffer[1]);
-            }
-            offset = context->common.filterBufferLen - 80;
-        } else {
-            offset -= 1 * 8;
-        }
-
-        for (ch = 0; ch < nrof_channels; ch++) {
-            DCT2_8(context->common.filterBuffer[ch] + offset, s);
-            SYNTH80(pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift);
-            s += 8;
-        }
-        pcm += (8 << pcmStrideShift);
-    }
-    context->common.filterBufferOffset = offset;
-}
-
-PRIVATE void OI_SBC_SynthFrame_4SB(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount)
-{
-    OI_UINT blk;
-    OI_UINT ch;
-    OI_UINT nrof_channels = context->common.frameInfo.nrof_channels;
-    OI_UINT pcmStrideShift = context->common.pcmStride == 1 ? 0 : 1;
-    OI_UINT offset = context->common.filterBufferOffset;
-    OI_INT32 *s = context->common.subdata + 8 * nrof_channels * blkstart;
-    OI_UINT blkstop = blkstart + blkcount;
-
-    for (blk = blkstart; blk < blkstop; blk++) {
-        if (offset == 0) {
-            COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[0] + context->common.filterBufferLen - 72, context->common.filterBuffer[0]);
-            if (nrof_channels == 2) {
-                COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(context->common.filterBuffer[1] + context->common.filterBufferLen - 72, context->common.filterBuffer[1]);
-            }
-            offset = context->common.filterBufferLen - 80;
-        } else {
-            offset -= 8;
-        }
-        for (ch = 0; ch < nrof_channels; ch++) {
-            cosineModulateSynth4(context->common.filterBuffer[ch] + offset, s);
-            SynthWindow40_int32_int32_symmetry_with_sum(pcm + ch,
-                                                        context->common.filterBuffer[ch] + offset,
-                                                        pcmStrideShift);
-            s += 4;
-        }
-        pcm += (4 << pcmStrideShift);
-    }
-    context->common.filterBufferOffset = offset;
-}
-
-#ifdef SBC_ENHANCED
-
-PRIVATE void OI_SBC_SynthFrame_Enhanced(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT blkstart, OI_UINT blkcount)
-{
-    OI_UINT blk;
-    OI_UINT ch;
-    OI_UINT nrof_channels = context->common.frameInfo.nrof_channels;
-    OI_UINT pcmStrideShift = context->common.pcmStride == 1 ? 0 : 1;
-    OI_UINT offset = context->common.filterBufferOffset;
-    OI_INT32 *s = context->common.subdata + 8 * nrof_channels * blkstart;
-    OI_UINT blkstop = blkstart + blkcount;
-
-    for (blk = blkstart; blk < blkstop; blk++) {
-        if (offset == 0) {
-            COPY_BACKWARD_32BIT_ALIGNED_104_HALFWORDS(context->common.filterBuffer[0] + context->common.filterBufferLen - 104, context->common.filterBuffer[0]);
-            if (nrof_channels == 2) {
-                COPY_BACKWARD_32BIT_ALIGNED_104_HALFWORDS(context->common.filterBuffer[1] + context->common.filterBufferLen - 104, context->common.filterBuffer[1]);
-            }
-            offset = context->common.filterBufferLen - 112;
-        } else {
-            offset -= 8;
-        }
-        for (ch = 0; ch < nrof_channels; ++ch) {
-            DCT2_8(context->common.filterBuffer[ch] + offset, s);
-            SYNTH112(pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift);
-            s += 8;
-        }
-        pcm += (8 << pcmStrideShift);
-    }
-    context->common.filterBufferOffset = offset;
-}
-
-static const SYNTH_FRAME SynthFrameEnhanced[] = {
-    NULL,                       /* invalid */
-    OI_SBC_SynthFrame_Enhanced, /* mono */
-    OI_SBC_SynthFrame_Enhanced  /* stereo */
-};
-
-#endif
-
-static const SYNTH_FRAME SynthFrame8SB[] = {
-    NULL,                 /* invalid */
-    OI_SBC_SynthFrame_80, /* mono */
-    OI_SBC_SynthFrame_80  /* stereo */
-};
-
-static const SYNTH_FRAME SynthFrame4SB[] = {
-    NULL,                  /* invalid */
-    OI_SBC_SynthFrame_4SB, /* mono */
-    OI_SBC_SynthFrame_4SB  /* stereo */
-};
-
-PRIVATE void OI_SBC_SynthFrame(OI_CODEC_SBC_DECODER_CONTEXT *context, OI_INT16 *pcm, OI_UINT start_block, OI_UINT nrof_blocks)
-{
-    OI_UINT nrof_subbands = context->common.frameInfo.nrof_subbands;
-    OI_UINT nrof_channels = context->common.frameInfo.nrof_channels;
-
-    OI_ASSERT(nrof_subbands == 4 || nrof_subbands == 8);
-    if (nrof_subbands == 4) {
-        SynthFrame4SB[nrof_channels](context, pcm, start_block, nrof_blocks);
-#ifdef SBC_ENHANCED
-    } else if (context->common.frameInfo.enhanced) {
-        SynthFrameEnhanced[nrof_channels](context, pcm, start_block, nrof_blocks);
-#endif /* SBC_ENHANCED */
-    } else {
-        SynthFrame8SB[nrof_channels](context, pcm, start_block, nrof_blocks);
-    }
-}
-
-void SynthWindow40_int32_int32_symmetry_with_sum(OI_INT16 *pcm, SBC_BUFFER_T buffer[80], OI_UINT strideShift)
-{
-    OI_INT32 pa;
-    OI_INT32 pb;
-
-    /* These values should be zero, since out[2] of the 4-band cosine modulation
-     * is always zero. */
-    OI_ASSERT(buffer[2] == 0);
-    OI_ASSERT(buffer[10] == 0);
-    OI_ASSERT(buffer[18] == 0);
-    OI_ASSERT(buffer[26] == 0);
-    OI_ASSERT(buffer[34] == 0);
-    OI_ASSERT(buffer[42] == 0);
-    OI_ASSERT(buffer[50] == 0);
-    OI_ASSERT(buffer[58] == 0);
-    OI_ASSERT(buffer[66] == 0);
-    OI_ASSERT(buffer[74] == 0);
-
-    pa = dec_window_4[4] * (buffer[12] + buffer[76]);
-    pa += dec_window_4[8] * (buffer[16] - buffer[64]);
-    pa += dec_window_4[12] * (buffer[28] + buffer[60]);
-    pa += dec_window_4[16] * (buffer[32] - buffer[48]);
-    pa += dec_window_4[20] * buffer[44];
-    pa = SCALE(-pa, 15);
-    CLIP_INT16(pa);
-    pcm[0 << strideShift] = (OI_INT16)pa;
-
-    pa = dec_window_4[1] * buffer[1];
-    pb = dec_window_4[1] * buffer[79];
-    pb += dec_window_4[3] * buffer[3];
-    pa += dec_window_4[3] * buffer[77];
-    pa += dec_window_4[5] * buffer[13];
-    pb += dec_window_4[5] * buffer[67];
-    pb += dec_window_4[7] * buffer[15];
-    pa += dec_window_4[7] * buffer[65];
-    pa += dec_window_4[9] * buffer[17];
-    pb += dec_window_4[9] * buffer[63];
-    pb += dec_window_4[11] * buffer[19];
-    pa += dec_window_4[11] * buffer[61];
-    pa += dec_window_4[13] * buffer[29];
-    pb += dec_window_4[13] * buffer[51];
-    pb += dec_window_4[15] * buffer[31];
-    pa += dec_window_4[15] * buffer[49];
-    pa += dec_window_4[17] * buffer[33];
-    pb += dec_window_4[17] * buffer[47];
-    pb += dec_window_4[19] * buffer[35];
-    pa += dec_window_4[19] * buffer[45];
-    pa = SCALE(-pa, 15);
-    CLIP_INT16(pa);
-    pcm[1 << strideShift] = (OI_INT16)(pa);
-    pb = SCALE(-pb, 15);
-    CLIP_INT16(pb);
-    pcm[3 << strideShift] = (OI_INT16)(pb);
-
-    pa = dec_window_4[2] * (/*buffer[ 2] + */ buffer[78]);   /* buffer[ 2] is always zero */
-    pa += dec_window_4[6] * (buffer[14] /* + buffer[66]*/);  /* buffer[66] is always zero */
-    pa += dec_window_4[10] * (/*buffer[18] + */ buffer[62]); /* buffer[18] is always zero */
-    pa += dec_window_4[14] * (buffer[30] /* + buffer[50]*/); /* buffer[50] is always zero */
-    pa += dec_window_4[18] * (/*buffer[34] + */ buffer[46]); /* buffer[34] is always zero */
-    pa = SCALE(-pa, 15);
-    CLIP_INT16(pa);
-    pcm[2 << strideShift] = (OI_INT16)(pa);
-}
-
-/**
-  This routine implements the cosine modulation matrix for 4-subband
-  synthesis. This is called "matrixing" in the SBC specification. This
-  matrix, M4,  can be factored into an 8-point Type II Discrete Cosine
-  Transform, DCTII_4 and a matrix S4, given here:
-
-  @code
-        __               __
-       |   0   0   1   0   |
-       |   0   0   0   1   |
-       |   0   0   0   0   |
-       |   0   0   0  -1   |
-  S4 = |   0   0  -1   0   |
-       |   0  -1   0   0   |
-       |  -1   0   0   0   |
-       |__ 0  -1   0   0 __|
-
-  M4 * in = S4 * (DCTII_4 * in)
-  @endcode
-
-  (DCTII_4 * in) is computed using a Fast Cosine Transform. The algorithm
-  here is based on an implementation computed by the SPIRAL computer
-  algebra system, manually converted to fixed-point arithmetic. S4 can be
-  implemented using only assignment and negation.
-  */
-PRIVATE void cosineModulateSynth4(SBC_BUFFER_T *RESTRICT out, OI_INT32 const *RESTRICT in)
-{
-    OI_INT32 f0, f1, f2, f3, f4, f7, f8, f9, f10;
-    OI_INT32 y0, y1, y2, y3;
-
-    f0 = (in[0] - in[3]);
-    f1 = (in[0] + in[3]);
-    f2 = (in[1] - in[2]);
-    f3 = (in[1] + in[2]);
-
-    f4 = f1 - f3;
-
-    y0 = -SCALE(f1 + f3, DCT_SHIFT);
-    y2 = -SCALE(LONG_MULT_DCT(DCTII_4_K06_FIX, f4), DCT_SHIFT);
-    f7 = f0 + f2;
-    f8 = LONG_MULT_DCT(DCTII_4_K08_FIX, f0);
-    f9 = LONG_MULT_DCT(DCTII_4_K09_FIX, f7);
-    f10 = LONG_MULT_DCT(DCTII_4_K10_FIX, f2);
-    y3 = -SCALE(f8 + f9, DCT_SHIFT);
-    y1 = -SCALE(f10 - f9, DCT_SHIFT);
-
-    out[0] = (OI_INT16)-y2;
-    out[1] = (OI_INT16)-y3;
-    out[2] = (OI_INT16)0;
-    out[3] = (OI_INT16)y3;
-    out[4] = (OI_INT16)y2;
-    out[5] = (OI_INT16)y1;
-    out[6] = (OI_INT16)y0;
-    out[7] = (OI_INT16)y1;
-}
-
-/**
-@}
-*/
-#endif /* #if defined(SBC_DEC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c
deleted file mode 100644
index 0a548ab8b..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_analysis.c
+++ /dev/null
@@ -1,1160 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains the code that performs Analysis of the input audio
- *  stream.
- *
- ******************************************************************************/
-#include 
-#include 
-#include "sbc_encoder.h"
-#include "sbc_enc_func_declare.h"
-//#include "osi/allocator.h"
-/*#include */
-#if defined(SBC_ENC_INCLUDED)
-
-#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-#define WIND_4_SUBBANDS_0_1 (SINT32)0x01659F45 /* gas32CoeffFor4SBs[8] = -gas32CoeffFor4SBs[32] = 0x01659F45 */
-#define WIND_4_SUBBANDS_0_2 (SINT32)0x115B1ED2 /* gas32CoeffFor4SBs[16] = -gas32CoeffFor4SBs[24] = 0x115B1ED2 */
-#define WIND_4_SUBBANDS_1_0 (SINT32)0x001194E6 /* gas32CoeffFor4SBs[1 et 39] = 0x001194E6 */
-#define WIND_4_SUBBANDS_1_1 (SINT32)0x029DBAA3 /* gas32CoeffFor4SBs[9 et 31] = 0x029DBAA3 */
-#define WIND_4_SUBBANDS_1_2 (SINT32)0x18F55C90 /* gas32CoeffFor4SBs[17 et 23] = 0x18F55C90 */
-#define WIND_4_SUBBANDS_1_3 (SINT32)0xF60FAF37 /* gas32CoeffFor4SBs[15 et 25] = 0xF60FAF37 */
-#define WIND_4_SUBBANDS_1_4 (SINT32)0xFF9BB9D5 /* gas32CoeffFor4SBs[7 et 33] = 0xFF9BB9D5 */
-#define WIND_4_SUBBANDS_2_0 (SINT32)0x0030E2D3 /* gas32CoeffFor4SBs[2 et 38] = 0x0030E2D3 */
-#define WIND_4_SUBBANDS_2_1 (SINT32)0x03B23341 /* gas32CoeffFor4SBs[10 et 30] = 0x03B23341 */
-#define WIND_4_SUBBANDS_2_2 (SINT32)0x1F91CA46 /* gas32CoeffFor4SBs[18 et 22] = 0x1F91CA46 */
-#define WIND_4_SUBBANDS_2_3 (SINT32)0xFC4F91D4 /* gas32CoeffFor4SBs[14 et 26] = 0xFC4F91D4 */
-#define WIND_4_SUBBANDS_2_4 (SINT32)0x003D239B /* gas32CoeffFor4SBs[6 et 34] = 0x003D239B */
-#define WIND_4_SUBBANDS_3_0 (SINT32)0x00599403 /* gas32CoeffFor4SBs[3 et 37] = 0x00599403 */
-#define WIND_4_SUBBANDS_3_1 (SINT32)0x041EEE40 /* gas32CoeffFor4SBs[11 et 29] = 0x041EEE40 */
-#define WIND_4_SUBBANDS_3_2 (SINT32)0x2412F251 /* gas32CoeffFor4SBs[19 et 21] = 0x2412F251 */
-#define WIND_4_SUBBANDS_3_3 (SINT32)0x00C8F2BC /* gas32CoeffFor4SBs[13 et 27] = 0x00C8F2BC */
-#define WIND_4_SUBBANDS_3_4 (SINT32)0x007F88E4 /* gas32CoeffFor4SBs[5 et 35] = 0x007F88E4 */
-#define WIND_4_SUBBANDS_4_0 (SINT32)0x007DBCC8 /* gas32CoeffFor4SBs[4 et 36] = 0x007DBCC8 */
-#define WIND_4_SUBBANDS_4_1 (SINT32)0x034FEE2C /* gas32CoeffFor4SBs[12 et 28] = 0x034FEE2C */
-#define WIND_4_SUBBANDS_4_2 (SINT32)0x25AC1FF2 /* gas32CoeffFor4SBs[20] = 0x25AC1FF2 */
-
-#define WIND_8_SUBBANDS_0_1 (SINT32)0x00B97348 /* 16 0x00B97348 */
-#define WIND_8_SUBBANDS_0_2 (SINT32)0x08B4307A /* 32 0x08B4307A */
-#define WIND_8_SUBBANDS_1_0 (SINT32)0x00052173 /* 1 et 79 = 0x00052173 */
-#define WIND_8_SUBBANDS_1_1 (SINT32)0x01071B96 /* 17 et 63 = 0x01071B96 */
-#define WIND_8_SUBBANDS_1_2 (SINT32)0x0A9F3E9A /* 33 et 47 = 0x0A9F3E9A*/
-#define WIND_8_SUBBANDS_1_3 (SINT32)0xF9312891 /* 31 et 49 = 0xF9312891 */
-#define WIND_8_SUBBANDS_1_4 (SINT32)0xFF8D6793 /* 15 et 65 = 0xFF8D6793 */
-#define WIND_8_SUBBANDS_2_0 (SINT32)0x000B3F71 /* 2 et 78 = 0x000B3F71 */
-#define WIND_8_SUBBANDS_2_1 (SINT32)0x0156B3CA /* 18 et 62 = 0x0156B3CA */
-#define WIND_8_SUBBANDS_2_2 (SINT32)0x0C7D59B6 /* 34 et 46 = 0x0C7D59B6 */
-#define WIND_8_SUBBANDS_2_3 (SINT32)0xFAFF95FC /* 30 et 50 = 0xFAFF95FC */
-#define WIND_8_SUBBANDS_2_4 (SINT32)0xFFC9F10E /* 14 et 66 = 0xFFC9F10E */
-#define WIND_8_SUBBANDS_3_0 (SINT32)0x00122C7D /* 3 et 77 = 0x00122C7D*/
-#define WIND_8_SUBBANDS_3_1 (SINT32)0x01A1B38B /* 19 et 61 = 0x01A1B38B */
-#define WIND_8_SUBBANDS_3_2 (SINT32)0x0E3BB16F /* 35 et 45 = 0x0E3BB16F */
-#define WIND_8_SUBBANDS_3_3 (SINT32)0xFCA86E7E /* 29 et 51 = 0xFCA86E7E */
-#define WIND_8_SUBBANDS_3_4 (SINT32)0xFFFA2413 /* 13 et 67 = 0xFFFA2413 */
-#define WIND_8_SUBBANDS_4_0 (SINT32)0x001AFF89 /* 4 et 66 = 0x001AFF89 */
-#define WIND_8_SUBBANDS_4_1 (SINT32)0x01E0224C /* 20 et 60 = 0x01E0224C */
-#define WIND_8_SUBBANDS_4_2 (SINT32)0x0FC721F9 /* 36 et 44 = 0x0FC721F9 */
-#define WIND_8_SUBBANDS_4_3 (SINT32)0xFE20435D /* 28 et 52 = 0xFE20435D */
-#define WIND_8_SUBBANDS_4_4 (SINT32)0x001D8FD2 /* 12 et 68 = 0x001D8FD2 */
-#define WIND_8_SUBBANDS_5_0 (SINT32)0x00255A62 /* 5 et 75 = 0x00255A62 */
-#define WIND_8_SUBBANDS_5_1 (SINT32)0x0209291F /* 21 et 59 = 0x0209291F */
-#define WIND_8_SUBBANDS_5_2 (SINT32)0x110ECEF0 /* 37 et 43 = 0x110ECEF0 */
-#define WIND_8_SUBBANDS_5_3 (SINT32)0xFF5EEB73 /* 27 et  53 = 0xFF5EEB73 */
-#define WIND_8_SUBBANDS_5_4 (SINT32)0x0034F8B6 /* 11 et 69 = 0x0034F8B6 */
-#define WIND_8_SUBBANDS_6_0 (SINT32)0x003060F4 /* 6 et 74 = 0x003060F4 */
-#define WIND_8_SUBBANDS_6_1 (SINT32)0x02138653 /* 22 et 58 = 0x02138653 */
-#define WIND_8_SUBBANDS_6_2 (SINT32)0x120435FA /* 38 et 42 = 0x120435FA */
-#define WIND_8_SUBBANDS_6_3 (SINT32)0x005FD0FF /* 26 et 54 = 0x005FD0FF */
-#define WIND_8_SUBBANDS_6_4 (SINT32)0x00415B75 /* 10 et 70 = 0x00415B75 */
-#define WIND_8_SUBBANDS_7_0 (SINT32)0x003A72E7 /* 7 et 73 = 0x003A72E7 */
-#define WIND_8_SUBBANDS_7_1 (SINT32)0x01F5F424 /* 23 et 57 = 0x01F5F424 */
-#define WIND_8_SUBBANDS_7_2 (SINT32)0x129C226F /* 39 et 41 = 0x129C226F */
-#define WIND_8_SUBBANDS_7_3 (SINT32)0x01223EBA /* 25 et 55 = 0x01223EBA */
-#define WIND_8_SUBBANDS_7_4 (SINT32)0x0044EF48 /* 9 et 71 = 0x0044EF48 */
-#define WIND_8_SUBBANDS_8_0 (SINT32)0x0041EC6A /* 8 et 72 = 0x0041EC6A */
-#define WIND_8_SUBBANDS_8_1 (SINT32)0x01A7ECEF /* 24 et 56 = 0x01A7ECEF */
-#define WIND_8_SUBBANDS_8_2 (SINT32)0x12CF6C75 /* 40 = 0x12CF6C75 */
-#else
-#define WIND_4_SUBBANDS_0_1 (SINT16)0x0166 /* gas32CoeffFor4SBs[8] = -gas32CoeffFor4SBs[32] = 0x01659F45 */
-#define WIND_4_SUBBANDS_0_2 (SINT16)0x115B /* gas32CoeffFor4SBs[16] = -gas32CoeffFor4SBs[24] = 0x115B1ED2 */
-#define WIND_4_SUBBANDS_1_0 (SINT16)0x0012 /* gas32CoeffFor4SBs[1 et 39] = 0x001194E6 */
-#define WIND_4_SUBBANDS_1_1 (SINT16)0x029E /* gas32CoeffFor4SBs[9 et 31] = 0x029DBAA3 */
-#define WIND_4_SUBBANDS_1_2 (SINT16)0x18F5 /* gas32CoeffFor4SBs[17 et 23] = 0x18F55C90 */
-#define WIND_4_SUBBANDS_1_3 (SINT16)0xF610 /* gas32CoeffFor4SBs[15 et 25] = 0xF60FAF37 */
-#define WIND_4_SUBBANDS_1_4 (SINT16)0xFF9C /* gas32CoeffFor4SBs[7 et 33] = 0xFF9BB9D5 */
-#define WIND_4_SUBBANDS_2_0 (SINT16)0x0031 /* gas32CoeffFor4SBs[2 et 38] = 0x0030E2D3 */
-#define WIND_4_SUBBANDS_2_1 (SINT16)0x03B2 /* gas32CoeffFor4SBs[10 et 30] = 0x03B23341 */
-#define WIND_4_SUBBANDS_2_2 (SINT16)0x1F91 /* gas32CoeffFor4SBs[18 et 22] = 0x1F91CA46 */
-#define WIND_4_SUBBANDS_2_3 (SINT16)0xFC50 /* gas32CoeffFor4SBs[14 et 26] = 0xFC4F91D4 */
-#define WIND_4_SUBBANDS_2_4 (SINT16)0x003D /* gas32CoeffFor4SBs[6 et 34] = 0x003D239B */
-#define WIND_4_SUBBANDS_3_0 (SINT16)0x005A /* gas32CoeffFor4SBs[3 et 37] = 0x00599403 */
-#define WIND_4_SUBBANDS_3_1 (SINT16)0x041F /* gas32CoeffFor4SBs[11 et 29] = 0x041EEE40 */
-#define WIND_4_SUBBANDS_3_2 (SINT16)0x2413 /* gas32CoeffFor4SBs[19 et 21] = 0x2412F251 */
-#define WIND_4_SUBBANDS_3_3 (SINT16)0x00C9 /* gas32CoeffFor4SBs[13 et 27] = 0x00C8F2BC */
-#define WIND_4_SUBBANDS_3_4 (SINT16)0x0080 /* gas32CoeffFor4SBs[5 et 35] = 0x007F88E4 */
-#define WIND_4_SUBBANDS_4_0 (SINT16)0x007E /* gas32CoeffFor4SBs[4 et 36] = 0x007DBCC8 */
-#define WIND_4_SUBBANDS_4_1 (SINT16)0x0350 /* gas32CoeffFor4SBs[12 et 28] = 0x034FEE2C */
-#define WIND_4_SUBBANDS_4_2 (SINT16)0x25AC /* gas32CoeffFor4SBs[20] = 25AC1FF2 */
-
-#define WIND_8_SUBBANDS_0_1 (SINT16)0x00B9 /* 16 0x12CF6C75 */
-#define WIND_8_SUBBANDS_0_2 (SINT16)0x08B4 /* 32 0x08B4307A */
-#define WIND_8_SUBBANDS_1_0 (SINT16)0x0005 /* 1 et 79 = 0x00052173 */
-#define WIND_8_SUBBANDS_1_1 (SINT16)0x0107 /* 17 et 63 = 0x01071B96 */
-#define WIND_8_SUBBANDS_1_2 (SINT16)0x0A9F /* 33 et 47 = 0x0A9F3E9A*/
-#define WIND_8_SUBBANDS_1_3 (SINT16)0xF931 /* 31 et 49 = 0xF9312891 */
-#define WIND_8_SUBBANDS_1_4 (SINT16)0xFF8D /* 15 et 65 = 0xFF8D6793 */
-#define WIND_8_SUBBANDS_2_0 (SINT16)0x000B /* 2 et 78 = 0x000B3F71 */
-#define WIND_8_SUBBANDS_2_1 (SINT16)0x0157 /* 18 et 62 = 0x0156B3CA */
-#define WIND_8_SUBBANDS_2_2 (SINT16)0x0C7D /* 34 et 46 = 0x0C7D59B6 */
-#define WIND_8_SUBBANDS_2_3 (SINT16)0xFB00 /* 30 et 50 = 0xFAFF95FC */
-#define WIND_8_SUBBANDS_2_4 (SINT16)0xFFCA /* 14 et 66 = 0xFFC9F10E */
-#define WIND_8_SUBBANDS_3_0 (SINT16)0x0012 /* 3 et 77 = 0x00122C7D*/
-#define WIND_8_SUBBANDS_3_1 (SINT16)0x01A2 /* 19 et 61 = 0x01A1B38B */
-#define WIND_8_SUBBANDS_3_2 (SINT16)0x0E3C /* 35 et 45 = 0x0E3BB16F */
-#define WIND_8_SUBBANDS_3_3 (SINT16)0xFCA8 /* 29 et 51 = 0xFCA86E7E */
-#define WIND_8_SUBBANDS_3_4 (SINT16)0xFFFA /* 13 et 67 = 0xFFFA2413 */
-#define WIND_8_SUBBANDS_4_0 (SINT16)0x001B /* 4 et 66 = 0x001AFF89 */
-#define WIND_8_SUBBANDS_4_1 (SINT16)0x01E0 /* 20 et 60 = 0x01E0224C */
-#define WIND_8_SUBBANDS_4_2 (SINT16)0x0FC7 /* 36 et 44 = 0x0FC721F9 */
-#define WIND_8_SUBBANDS_4_3 (SINT16)0xFE20 /* 28 et 52 = 0xFE20435D */
-#define WIND_8_SUBBANDS_4_4 (SINT16)0x001E /* 12 et 68 = 0x001D8FD2 */
-#define WIND_8_SUBBANDS_5_0 (SINT16)0x0025 /* 5 et 75 = 0x00255A62 */
-#define WIND_8_SUBBANDS_5_1 (SINT16)0x0209 /* 21 et 59 = 0x0209291F */
-#define WIND_8_SUBBANDS_5_2 (SINT16)0x110F /* 37 et 43 = 0x110ECEF0 */
-#define WIND_8_SUBBANDS_5_3 (SINT16)0xFF5F /* 27 et  53 = 0xFF5EEB73 */
-#define WIND_8_SUBBANDS_5_4 (SINT16)0x0035 /* 11 et 69 = 0x0034F8B6 */
-#define WIND_8_SUBBANDS_6_0 (SINT16)0x0030 /* 6 et 74 = 0x003060F4 */
-#define WIND_8_SUBBANDS_6_1 (SINT16)0x0214 /* 22 et 58 = 0x02138653 */
-#define WIND_8_SUBBANDS_6_2 (SINT16)0x1204 /* 38 et 42 = 0x120435FA */
-#define WIND_8_SUBBANDS_6_3 (SINT16)0x0060 /* 26 et 54 = 0x005FD0FF */
-#define WIND_8_SUBBANDS_6_4 (SINT16)0x0041 /* 10 et 70 = 0x00415B75 */
-#define WIND_8_SUBBANDS_7_0 (SINT16)0x003A /* 7 et 73 = 0x003A72E7 */
-#define WIND_8_SUBBANDS_7_1 (SINT16)0x01F6 /* 23 et 57 = 0x01F5F424 */
-#define WIND_8_SUBBANDS_7_2 (SINT16)0x129C /* 39 et 41 = 0x129C226F */
-#define WIND_8_SUBBANDS_7_3 (SINT16)0x0122 /* 25 et 55 = 0x01223EBA */
-#define WIND_8_SUBBANDS_7_4 (SINT16)0x0045 /* 9 et 71 = 0x0044EF48 */
-#define WIND_8_SUBBANDS_8_0 (SINT16)0x0042 /* 8 et 72 = 0x0041EC6A */
-#define WIND_8_SUBBANDS_8_1 (SINT16)0x01A8 /* 24 et 56 = 0x01A7ECEF */
-#define WIND_8_SUBBANDS_8_2 (SINT16)0x12CF /* 40 = 0x12CF6C75 */
-#endif
-
-#if (SBC_USE_ARM_PRAGMA == TRUE)
-#pragma arm section zidata = "sbc_s32_analysis_section"
-#endif
-#if BT_BLE_DYNAMIC_ENV_MEMORY == FALSE
-static SINT32 s32DCTY[16] = { 0 };
-static SINT32 s32X[ENC_VX_BUFFER_SIZE / 2];
-static SINT16 *s16X = (SINT16 *)s32X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
-#else
-static SINT32 *s32DCTY;
-static SINT32 *s32X;
-static SINT16 *s16X; /* s16X must be 32 bits aligned cf  SHIFTUP_X8_2*/
-#endif //BT_BLE_DYNAMIC_ENV_MEMORY == FALSE
-
-#if (SBC_USE_ARM_PRAGMA == TRUE)
-#pragma arm section zidata
-#endif
-
-/* This macro is for 4 subbands */
-#define SHIFTUP_X4                                          \
-    {                                                       \
-        ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 38); \
-        for (i = 0; i < 9; i++) {                           \
-            *ps32X = *(ps32X - 2 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-            *ps32X = *(ps32X - 2 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-        }                                                   \
-    }
-#define SHIFTUP_X4_2                                                \
-    {                                                               \
-        ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 38);         \
-        ps32X2 = (SINT32 *)(s16X + (EncMaxShiftCounter << 1) + 78); \
-        for (i = 0; i < 9; i++) {                                   \
-            *ps32X = *(ps32X - 2 - (ShiftCounter >> 1));            \
-            *(ps32X2) = *(ps32X2 - 2 - (ShiftCounter >> 1));        \
-            ps32X--;                                                \
-            ps32X2--;                                               \
-            *ps32X = *(ps32X - 2 - (ShiftCounter >> 1));            \
-            *(ps32X2) = *(ps32X2 - 2 - (ShiftCounter >> 1));        \
-            ps32X--;                                                \
-            ps32X2--;                                               \
-        }                                                           \
-    }
-
-/* This macro is for 8 subbands */
-#define SHIFTUP_X8                                          \
-    {                                                       \
-        ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 78); \
-        for (i = 0; i < 9; i++) {                           \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));    \
-            ps32X--;                                        \
-        }                                                   \
-    }
-#define SHIFTUP_X8_2                                                 \
-    {                                                                \
-        ps32X = (SINT32 *)(s16X + EncMaxShiftCounter + 78);          \
-        ps32X2 = (SINT32 *)(s16X + (EncMaxShiftCounter << 1) + 158); \
-        for (i = 0; i < 9; i++) {                                    \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));             \
-            *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));         \
-            ps32X--;                                                 \
-            ps32X2--;                                                \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));             \
-            *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));         \
-            ps32X--;                                                 \
-            ps32X2--;                                                \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));             \
-            *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));         \
-            ps32X--;                                                 \
-            ps32X2--;                                                \
-            *ps32X = *(ps32X - 4 - (ShiftCounter >> 1));             \
-            *(ps32X2) = *(ps32X2 - 4 - (ShiftCounter >> 1));         \
-            ps32X--;                                                 \
-            ps32X2--;                                                \
-        }                                                            \
-    }
-
-#if (SBC_ARM_ASM_OPT == TRUE)
-#define WINDOW_ACCU_8_0 \
-    {                   \
-        __asm {\
-        MUL s32Hi,WIND_8_SUBBANDS_0_1,(s16X[ChOffset+16]-s16X[ChOffset+64]);\
-        MLA s32Hi,WIND_8_SUBBANDS_0_2,(s16X[ChOffset+32]-s16X[ChOffset+48]),s32Hi;\
-        MOV s32DCTY[0],s32Hi;        \
-        }               \
-    }
-#define WINDOW_ACCU_8_1_15 \
-    {                      \
-        __asm {\
-        MUL s32Hi,WIND_8_SUBBANDS_1_0,s16X[ChOffset+1];\
-        MUL s32Hi2,WIND_8_SUBBANDS_1_0,s16X[ChOffset+64+15];\
-        MLA s32Hi,WIND_8_SUBBANDS_1_1,s16X[ChOffset+16+1],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_1_1,s16X[ChOffset+48+15],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_1_2,s16X[ChOffset+32+1],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_1_2,s16X[ChOffset+32+15],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_1_3,s16X[ChOffset+48+1],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_1_3,s16X[ChOffset+16+15],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_1_4,s16X[ChOffset+64+1],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_1_4,s16X[ChOffset+15],s32Hi2;\
-        MOV s32DCTY[1],s32Hi;\
-        MOV s32DCTY[15],s32Hi2;           \
-        }                  \
-    }
-#define WINDOW_ACCU_8_2_14 \
-    {                      \
-        __asm {\
-        MUL s32Hi,WIND_8_SUBBANDS_2_0,s16X[ChOffset+2];\
-        MUL s32Hi2,WIND_8_SUBBANDS_2_0,s16X[ChOffset+64+14];\
-        MLA s32Hi,WIND_8_SUBBANDS_2_1,s16X[ChOffset+16+2],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_2_1,s16X[ChOffset+48+14],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_2_2,s16X[ChOffset+32+2],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_2_2,s16X[ChOffset+32+14],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_2_3,s16X[ChOffset+48+2],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_2_3,s16X[ChOffset+16+14],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_2_4,s16X[ChOffset+64+2],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_2_4,s16X[ChOffset+14],s32Hi2;\
-        MOV s32DCTY[2],s32Hi;\
-        MOV s32DCTY[14],s32Hi2;           \
-        }                  \
-    }
-#define WINDOW_ACCU_8_3_13 \
-    {                      \
-        __asm {\
-        MUL s32Hi,WIND_8_SUBBANDS_3_0,s16X[ChOffset+3];\
-        MUL s32Hi2,WIND_8_SUBBANDS_3_0,s16X[ChOffset+64+13];\
-        MLA s32Hi,WIND_8_SUBBANDS_3_1,s16X[ChOffset+16+3],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_3_1,s16X[ChOffset+48+13],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_3_2,s16X[ChOffset+32+3],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_3_2,s16X[ChOffset+32+13],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_3_3,s16X[ChOffset+48+3],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_3_3,s16X[ChOffset+16+13],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_3_4,s16X[ChOffset+64+3],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_3_4,s16X[ChOffset+13],s32Hi2;\
-        MOV s32DCTY[3],s32Hi;\
-        MOV s32DCTY[13],s32Hi2;           \
-        }                  \
-    }
-#define WINDOW_ACCU_8_4_12 \
-    {                      \
-        __asm {\
-        MUL s32Hi,WIND_8_SUBBANDS_4_0,s16X[ChOffset+4];\
-        MUL s32Hi2,WIND_8_SUBBANDS_4_0,s16X[ChOffset+64+12];\
-        MLA s32Hi,WIND_8_SUBBANDS_4_1,s16X[ChOffset+16+4],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_4_1,s16X[ChOffset+48+12],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_4_2,s16X[ChOffset+32+4],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_4_2,s16X[ChOffset+32+12],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_4_3,s16X[ChOffset+48+4],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_4_3,s16X[ChOffset+16+12],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_4_4,s16X[ChOffset+64+4],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_4_4,s16X[ChOffset+12],s32Hi2;\
-        MOV s32DCTY[4],s32Hi;\
-        MOV s32DCTY[12],s32Hi2;           \
-        }                  \
-    }
-#define WINDOW_ACCU_8_5_11 \
-    {                      \
-        __asm {\
-        MUL s32Hi,WIND_8_SUBBANDS_5_0,s16X[ChOffset+5];\
-        MUL s32Hi2,WIND_8_SUBBANDS_5_0,s16X[ChOffset+64+11];\
-        MLA s32Hi,WIND_8_SUBBANDS_5_1,s16X[ChOffset+16+5],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_5_1,s16X[ChOffset+48+11],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_5_2,s16X[ChOffset+32+5],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_5_2,s16X[ChOffset+32+11],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_5_3,s16X[ChOffset+48+5],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_5_3,s16X[ChOffset+16+11],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_5_4,s16X[ChOffset+64+5],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_5_4,s16X[ChOffset+11],s32Hi2;\
-        MOV s32DCTY[5],s32Hi;\
-        MOV s32DCTY[11],s32Hi2;           \
-        }                  \
-    }
-#define WINDOW_ACCU_8_6_10 \
-    {                      \
-        __asm {\
-        MUL s32Hi,WIND_8_SUBBANDS_6_0,s16X[ChOffset+6];\
-        MUL s32Hi2,WIND_8_SUBBANDS_6_0,s16X[ChOffset+64+10];\
-        MLA s32Hi,WIND_8_SUBBANDS_6_1,s16X[ChOffset+16+6],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_6_1,s16X[ChOffset+48+10],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_6_2,s16X[ChOffset+32+6],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_6_2,s16X[ChOffset+32+10],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_6_3,s16X[ChOffset+48+6],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_6_3,s16X[ChOffset+16+10],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_6_4,s16X[ChOffset+64+6],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_6_4,s16X[ChOffset+10],s32Hi2;\
-        MOV s32DCTY[6],s32Hi;\
-        MOV s32DCTY[10],s32Hi2;           \
-        }                  \
-    }
-#define WINDOW_ACCU_8_7_9 \
-    {                     \
-        __asm {\
-        MUL s32Hi,WIND_8_SUBBANDS_7_0,s16X[ChOffset+7];\
-        MUL s32Hi2,WIND_8_SUBBANDS_7_0,s16X[ChOffset+64+9];\
-        MLA s32Hi,WIND_8_SUBBANDS_7_1,s16X[ChOffset+16+7],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_7_1,s16X[ChOffset+48+9],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_7_2,s16X[ChOffset+32+7],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_7_2,s16X[ChOffset+32+9],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_7_3,s16X[ChOffset+48+7],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_7_3,s16X[ChOffset+16+9],s32Hi2;\
-        MLA s32Hi,WIND_8_SUBBANDS_7_4,s16X[ChOffset+64+7],s32Hi;\
-        MLA s32Hi2,WIND_8_SUBBANDS_7_4,s16X[ChOffset+9],s32Hi2;\
-        MOV s32DCTY[7],s32Hi;\
-        MOV s32DCTY[9],s32Hi2;          \
-        }                 \
-    }
-#define WINDOW_ACCU_8_8 \
-    {                   \
-        __asm {\
-        MUL s32Hi,WIND_8_SUBBANDS_8_0,(s16X[ChOffset+8]+s16X[ChOffset+8+64]);\
-        MLA s32Hi,WIND_8_SUBBANDS_8_1,(s16X[ChOffset+8+16]+s16X[ChOffset+8+64]),s32Hi;\
-        MLA s32Hi,WIND_8_SUBBANDS_8_2,s16X[ChOffset+8+32],s32Hi;\
-        MOV s32DCTY[8],s32Hi;        \
-        }               \
-    }
-#define WINDOW_ACCU_4_0 \
-    {                   \
-        __asm {\
-        MUL s32Hi,WIND_4_SUBBANDS_0_1,(s16X[ChOffset+8]-s16X[ChOffset+32]);\
-        MLA s32Hi,WIND_4_SUBBANDS_0_2,(s16X[ChOffset+16]-s16X[ChOffset+24]),s32Hi;\
-        MOV s32DCTY[0],s32Hi;        \
-        }               \
-    }
-#define WINDOW_ACCU_4_1_7 \
-    {                     \
-        __asm {\
-        MUL s32Hi,WIND_4_SUBBANDS_1_0,s16X[ChOffset+1];\
-        MUL s32Hi2,WIND_4_SUBBANDS_1_0,s16X[ChOffset+32+7];\
-        MLA s32Hi,WIND_4_SUBBANDS_1_1,s16X[ChOffset+8+1],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_1_1,s16X[ChOffset+24+7],s32Hi2;\
-        MLA s32Hi,WIND_4_SUBBANDS_1_2,s16X[ChOffset+16+1],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_1_2,s16X[ChOffset+16+7],s32Hi2;\
-        MLA s32Hi,WIND_4_SUBBANDS_1_3,s16X[ChOffset+24+1],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_1_3,s16X[ChOffset+8+7],s32Hi2;\
-        MLA s32Hi,WIND_4_SUBBANDS_1_4,s16X[ChOffset+32+1],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_1_4,s16X[ChOffset+7],s32Hi2;\
-        MOV s32DCTY[1],s32Hi;\
-        MOV s32DCTY[7],s32Hi2;          \
-        }                 \
-    }
-#define WINDOW_ACCU_4_2_6 \
-    {                     \
-        __asm {\
-        MUL s32Hi,WIND_4_SUBBANDS_2_0,s16X[ChOffset+2];\
-        MUL s32Hi2,WIND_4_SUBBANDS_2_0,s16X[ChOffset+32+6];\
-        MLA s32Hi,WIND_4_SUBBANDS_2_1,s16X[ChOffset+8+2],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_2_1,s16X[ChOffset+24+6],s32Hi2;\
-        MLA s32Hi,WIND_4_SUBBANDS_2_2,s16X[ChOffset+16+2],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_2_2,s16X[ChOffset+16+6],s32Hi2;\
-        MLA s32Hi,WIND_4_SUBBANDS_2_3,s16X[ChOffset+24+2],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_2_3,s16X[ChOffset+8+6],s32Hi2;\
-        MLA s32Hi,WIND_4_SUBBANDS_2_4,s16X[ChOffset+32+2],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_2_4,s16X[ChOffset+6],s32Hi2;\
-        MOV s32DCTY[2],s32Hi;\
-        MOV s32DCTY[6],s32Hi2;          \
-        }                 \
-    }
-#define WINDOW_ACCU_4_3_5 \
-    {                     \
-        __asm {\
-        MUL s32Hi,WIND_4_SUBBANDS_3_0,s16X[ChOffset+3];\
-        MUL s32Hi2,WIND_4_SUBBANDS_3_0,s16X[ChOffset+32+5];\
-        MLA s32Hi,WIND_4_SUBBANDS_3_1,s16X[ChOffset+8+3],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_3_1,s16X[ChOffset+24+5],s32Hi2;\
-        MLA s32Hi,WIND_4_SUBBANDS_3_2,s16X[ChOffset+16+3],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_3_2,s16X[ChOffset+16+5],s32Hi2;\
-        MLA s32Hi,WIND_4_SUBBANDS_3_3,s16X[ChOffset+24+3],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_3_3,s16X[ChOffset+8+5],s32Hi2;\
-        MLA s32Hi,WIND_4_SUBBANDS_3_4,s16X[ChOffset+32+3],s32Hi;\
-        MLA s32Hi2,WIND_4_SUBBANDS_3_4,s16X[ChOffset+5],s32Hi2;\
-        MOV s32DCTY[3],s32Hi;\
-        MOV s32DCTY[5],s32Hi2;          \
-        }                 \
-    }
-#define WINDOW_ACCU_4_4 \
-    {                   \
-        __asm {\
-        MUL s32Hi,WIND_4_SUBBANDS_4_0,(s16X[ChOffset+4]+s16X[ChOffset+4+32]);\
-        MLA s32Hi,WIND_4_SUBBANDS_4_1,(s16X[ChOffset+4+8]+s16X[ChOffset+4+24]),s32Hi;\
-        MLA s32Hi,WIND_4_SUBBANDS_4_2,s16X[ChOffset+4+16],s32Hi;\
-        MOV s32DCTY[4],s32Hi;        \
-        }               \
-    }
-
-#define WINDOW_PARTIAL_4   \
-    {                      \
-        WINDOW_ACCU_4_0;   \
-        WINDOW_ACCU_4_1_7; \
-        WINDOW_ACCU_4_2_6; \
-        WINDOW_ACCU_4_3_5; \
-        WINDOW_ACCU_4_4;   \
-    }
-
-#define WINDOW_PARTIAL_8    \
-    {                       \
-        WINDOW_ACCU_8_0;    \
-        WINDOW_ACCU_8_1_15; \
-        WINDOW_ACCU_8_2_14; \
-        WINDOW_ACCU_8_3_13; \
-        WINDOW_ACCU_8_4_12; \
-        WINDOW_ACCU_8_5_11; \
-        WINDOW_ACCU_8_6_10; \
-        WINDOW_ACCU_8_7_9;  \
-        WINDOW_ACCU_8_8;    \
-    }
-
-#else
-#if (SBC_IPAQ_OPT == TRUE)
-
-#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-#define WINDOW_ACCU_8_0                                                                               \
-    {                                                                                                 \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_0_1 * (SINT64)(s16X[ChOffset + 16] - s16X[ChOffset + 64]);  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_0_2 * (SINT64)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \
-        s32DCTY[0] = (SINT32)(s64Temp >> 16);                                                         \
-    }
-#define WINDOW_ACCU_8_1_15                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 1];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 64 + 15];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 16 + 1];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 48 + 15]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 32 + 1];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 32 + 15]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 48 + 1];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 16 + 15]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 64 + 1];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 15];      \
-        s32DCTY[1] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[15] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_2_14                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 2];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 64 + 14];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 16 + 2];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 48 + 14]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 32 + 2];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 32 + 14]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 48 + 2];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 16 + 14]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 64 + 2];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 14];      \
-        s32DCTY[2] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[14] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_3_13                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 3];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 64 + 13];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 16 + 3];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 48 + 13]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 32 + 3];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 32 + 13]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 48 + 3];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 16 + 13]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 64 + 3];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 13];      \
-        s32DCTY[3] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[13] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_4_12                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_4_0 * (SINT64)s16X[ChOffset + 4];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_4_0 * (SINT64)s16X[ChOffset + 64 + 12];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_4_1 * (SINT64)s16X[ChOffset + 16 + 4];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_1 * (SINT64)s16X[ChOffset + 48 + 12]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 32 + 4];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 32 + 12]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_4_3 * (SINT64)s16X[ChOffset + 48 + 4];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_3 * (SINT64)s16X[ChOffset + 16 + 12]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_4_4 * (SINT64)s16X[ChOffset + 64 + 4];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_4_4 * (SINT64)s16X[ChOffset + 12];      \
-        s32DCTY[4] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[12] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_5_11                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_5_0 * (SINT64)s16X[ChOffset + 5];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_5_0 * (SINT64)s16X[ChOffset + 64 + 11];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_5_1 * (SINT64)s16X[ChOffset + 16 + 5];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_1 * (SINT64)s16X[ChOffset + 48 + 11]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_5_2 * (SINT64)s16X[ChOffset + 32 + 5];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_2 * (SINT64)s16X[ChOffset + 32 + 11]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_5_3 * (SINT64)s16X[ChOffset + 48 + 5];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_3 * (SINT64)s16X[ChOffset + 16 + 11]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_5_4 * (SINT64)s16X[ChOffset + 64 + 5];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_5_4 * (SINT64)s16X[ChOffset + 11];      \
-        s32DCTY[5] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[11] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_6_10                                                          \
-    {                                                                               \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_6_0 * (SINT64)s16X[ChOffset + 6];         \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_6_0 * (SINT64)s16X[ChOffset + 64 + 10];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_6_1 * (SINT64)s16X[ChOffset + 16 + 6];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_1 * (SINT64)s16X[ChOffset + 48 + 10]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_6_2 * (SINT64)s16X[ChOffset + 32 + 6];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_2 * (SINT64)s16X[ChOffset + 32 + 10]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_6_3 * (SINT64)s16X[ChOffset + 48 + 6];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_3 * (SINT64)s16X[ChOffset + 16 + 10]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_6_4 * (SINT64)s16X[ChOffset + 64 + 6];   \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_6_4 * (SINT64)s16X[ChOffset + 10];      \
-        s32DCTY[6] = (SINT32)(s64Temp >> 16);                                       \
-        s32DCTY[10] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_7_9                                                          \
-    {                                                                              \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_7_0 * (SINT64)s16X[ChOffset + 7];        \
-        s64Temp2 = (SINT64)WIND_8_SUBBANDS_7_0 * (SINT64)s16X[ChOffset + 64 + 9];  \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_7_1 * (SINT64)s16X[ChOffset + 16 + 7];  \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_1 * (SINT64)s16X[ChOffset + 48 + 9]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_7_2 * (SINT64)s16X[ChOffset + 32 + 7];  \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_2 * (SINT64)s16X[ChOffset + 32 + 9]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_7_3 * (SINT64)s16X[ChOffset + 48 + 7];  \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_3 * (SINT64)s16X[ChOffset + 16 + 9]; \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_7_4 * (SINT64)s16X[ChOffset + 64 + 7];  \
-        s64Temp2 += (SINT64)WIND_8_SUBBANDS_7_4 * (SINT64)s16X[ChOffset + 9];      \
-        s32DCTY[7] = (SINT32)(s64Temp >> 16);                                      \
-        s32DCTY[9] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_8_8                                                                                       \
-    {                                                                                                         \
-        s64Temp = (SINT64)WIND_8_SUBBANDS_8_0 * (SINT64)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]);       \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_8_1 * (SINT64)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \
-        s64Temp += (SINT64)WIND_8_SUBBANDS_8_2 * (SINT64)s16X[ChOffset + 32 + 8];                             \
-        s32DCTY[8] = (SINT32)(s64Temp >> 16);                                                                 \
-    }
-#define WINDOW_ACCU_4_0                                                                               \
-    {                                                                                                 \
-        s64Temp = (SINT64)WIND_4_SUBBANDS_0_1 * (SINT64)(s16X[ChOffset + 8] - s16X[ChOffset + 32]);   \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_0_2 * (SINT64)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \
-        s32DCTY[0] = (SINT32)(s64Temp >> 16);                                                         \
-    }
-#define WINDOW_ACCU_4_1_7                                                          \
-    {                                                                              \
-        s64Temp = (SINT64)WIND_4_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 1];        \
-        s64Temp2 = (SINT64)WIND_4_SUBBANDS_1_0 * (SINT64)s16X[ChOffset + 32 + 7];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 8 + 1];   \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_1 * (SINT64)s16X[ChOffset + 24 + 7]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 16 + 1];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_2 * (SINT64)s16X[ChOffset + 16 + 7]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 24 + 1];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_3 * (SINT64)s16X[ChOffset + 8 + 7];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 32 + 1];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_1_4 * (SINT64)s16X[ChOffset + 7];      \
-        s32DCTY[1] = (SINT32)(s64Temp >> 16);                                      \
-        s32DCTY[7] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_4_2_6                                                          \
-    {                                                                              \
-        s64Temp = (SINT64)WIND_4_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 2];        \
-        s64Temp2 = (SINT64)WIND_4_SUBBANDS_2_0 * (SINT64)s16X[ChOffset + 32 + 6];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 8 + 2];   \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_1 * (SINT64)s16X[ChOffset + 24 + 6]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 16 + 2];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_2 * (SINT64)s16X[ChOffset + 16 + 6]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 24 + 2];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_3 * (SINT64)s16X[ChOffset + 8 + 6];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 32 + 2];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_2_4 * (SINT64)s16X[ChOffset + 6];      \
-        s32DCTY[2] = (SINT32)(s64Temp >> 16);                                      \
-        s32DCTY[6] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-#define WINDOW_ACCU_4_3_5                                                          \
-    {                                                                              \
-        s64Temp = (SINT64)WIND_4_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 3];        \
-        s64Temp2 = (SINT64)WIND_4_SUBBANDS_3_0 * (SINT64)s16X[ChOffset + 32 + 5];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 8 + 3];   \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_1 * (SINT64)s16X[ChOffset + 24 + 5]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 16 + 3];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_2 * (SINT64)s16X[ChOffset + 16 + 5]; \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 24 + 3];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_3 * (SINT64)s16X[ChOffset + 8 + 5];  \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 32 + 3];  \
-        s64Temp2 += (SINT64)WIND_4_SUBBANDS_3_4 * (SINT64)s16X[ChOffset + 5];      \
-        s32DCTY[3] = (SINT32)(s64Temp >> 16);                                      \
-        s32DCTY[5] = (SINT32)(s64Temp2 >> 16);                                     \
-    }
-
-#define WINDOW_ACCU_4_4                                                                                      \
-    {                                                                                                        \
-        s64Temp = (SINT64)WIND_4_SUBBANDS_4_0 * (SINT64)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]);      \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_4_1 * (SINT64)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \
-        s64Temp += (SINT64)WIND_4_SUBBANDS_4_2 * (SINT64)s16X[ChOffset + 4 + 16];                            \
-        s32DCTY[4] = (SINT32)(s64Temp >> 16);                                                                \
-    }
-#else /* SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE */
-#define WINDOW_ACCU_8_0                                                                               \
-    {                                                                                                 \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_0_1 * (SINT32)(s16X[ChOffset + 16] - s16X[ChOffset + 64]);  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_0_2 * (SINT32)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \
-        s32DCTY[0] = (SINT32)s32Temp;                                                                 \
-    }
-#define WINDOW_ACCU_8_1_15                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 1];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 64 + 15];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 16 + 1];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 48 + 15]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 32 + 1];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 32 + 15]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 48 + 1];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 16 + 15]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 64 + 1];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 15];      \
-        s32DCTY[1] = (SINT32)s32Temp;                                               \
-        s32DCTY[15] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_2_14                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 2];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 64 + 14];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 16 + 2];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 48 + 14]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 32 + 2];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 32 + 14]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 48 + 2];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 16 + 14]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 64 + 2];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 14];      \
-        s32DCTY[2] = (SINT32)s32Temp;                                               \
-        s32DCTY[14] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_3_13                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 3];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 64 + 13];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 16 + 3];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 48 + 13]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 32 + 3];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 32 + 13]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 48 + 3];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 16 + 13]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 64 + 3];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 13];      \
-        s32DCTY[3] = (SINT32)s32Temp;                                               \
-        s32DCTY[13] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_4_12                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_4_0 * (SINT32)s16X[ChOffset + 4];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_4_0 * (SINT32)s16X[ChOffset + 64 + 12];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_4_1 * (SINT32)s16X[ChOffset + 16 + 4];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_1 * (SINT32)s16X[ChOffset + 48 + 12]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 32 + 4];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 32 + 12]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_4_3 * (SINT32)s16X[ChOffset + 48 + 4];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_3 * (SINT32)s16X[ChOffset + 16 + 12]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_4_4 * (SINT32)s16X[ChOffset + 64 + 4];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_4_4 * (SINT32)s16X[ChOffset + 12];      \
-        s32DCTY[4] = (SINT32)s32Temp;                                               \
-        s32DCTY[12] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_5_11                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_5_0 * (SINT32)s16X[ChOffset + 5];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_5_0 * (SINT32)s16X[ChOffset + 64 + 11];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_5_1 * (SINT32)s16X[ChOffset + 16 + 5];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_1 * (SINT32)s16X[ChOffset + 48 + 11]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_5_2 * (SINT32)s16X[ChOffset + 32 + 5];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_2 * (SINT32)s16X[ChOffset + 32 + 11]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_5_3 * (SINT32)s16X[ChOffset + 48 + 5];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_3 * (SINT32)s16X[ChOffset + 16 + 11]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_5_4 * (SINT32)s16X[ChOffset + 64 + 5];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_5_4 * (SINT32)s16X[ChOffset + 11];      \
-        s32DCTY[5] = (SINT32)s32Temp;                                               \
-        s32DCTY[11] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_6_10                                                          \
-    {                                                                               \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_6_0 * (SINT32)s16X[ChOffset + 6];         \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_6_0 * (SINT32)s16X[ChOffset + 64 + 10];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_6_1 * (SINT32)s16X[ChOffset + 16 + 6];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_1 * (SINT32)s16X[ChOffset + 48 + 10]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_6_2 * (SINT32)s16X[ChOffset + 32 + 6];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_2 * (SINT32)s16X[ChOffset + 32 + 10]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_6_3 * (SINT32)s16X[ChOffset + 48 + 6];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_3 * (SINT32)s16X[ChOffset + 16 + 10]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_6_4 * (SINT32)s16X[ChOffset + 64 + 6];   \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_6_4 * (SINT32)s16X[ChOffset + 10];      \
-        s32DCTY[6] = (SINT32)s32Temp;                                               \
-        s32DCTY[10] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_7_9                                                          \
-    {                                                                              \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_7_0 * (SINT32)s16X[ChOffset + 7];        \
-        s32Temp2 = (SINT32)WIND_8_SUBBANDS_7_0 * (SINT32)s16X[ChOffset + 64 + 9];  \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_7_1 * (SINT32)s16X[ChOffset + 16 + 7];  \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_1 * (SINT32)s16X[ChOffset + 48 + 9]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_7_2 * (SINT32)s16X[ChOffset + 32 + 7];  \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_2 * (SINT32)s16X[ChOffset + 32 + 9]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_7_3 * (SINT32)s16X[ChOffset + 48 + 7];  \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_3 * (SINT32)s16X[ChOffset + 16 + 9]; \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_7_4 * (SINT32)s16X[ChOffset + 64 + 7];  \
-        s32Temp2 += (SINT32)WIND_8_SUBBANDS_7_4 * (SINT32)s16X[ChOffset + 9];      \
-        s32DCTY[7] = (SINT32)s32Temp;                                              \
-        s32DCTY[9] = (SINT32)s32Temp2;                                             \
-    }
-#define WINDOW_ACCU_8_8                                                                                       \
-    {                                                                                                         \
-        s32Temp = (SINT32)WIND_8_SUBBANDS_8_0 * (SINT32)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]);       \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_8_1 * (SINT32)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \
-        s32Temp += (SINT32)WIND_8_SUBBANDS_8_2 * (SINT32)s16X[ChOffset + 32 + 8];                             \
-        s32DCTY[8] = (SINT32)s32Temp;                                                                         \
-    }
-#define WINDOW_ACCU_4_0                                                                               \
-    {                                                                                                 \
-        s32Temp = (SINT32)WIND_4_SUBBANDS_0_1 * (SINT32)(s16X[ChOffset + 8] - s16X[ChOffset + 32]);   \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_0_2 * (SINT32)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \
-        s32DCTY[0] = (SINT32)(s32Temp);                                                               \
-    }
-#define WINDOW_ACCU_4_1_7                                                          \
-    {                                                                              \
-        s32Temp = (SINT32)WIND_4_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 1];        \
-        s32Temp2 = (SINT32)WIND_4_SUBBANDS_1_0 * (SINT32)s16X[ChOffset + 32 + 7];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 8 + 1];   \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_1 * (SINT32)s16X[ChOffset + 24 + 7]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 16 + 1];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_2 * (SINT32)s16X[ChOffset + 16 + 7]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 24 + 1];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_3 * (SINT32)s16X[ChOffset + 8 + 7];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 32 + 1];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_1_4 * (SINT32)s16X[ChOffset + 7];      \
-        s32DCTY[1] = (SINT32)(s32Temp);                                            \
-        s32DCTY[7] = (SINT32)(s32Temp2);                                           \
-    }
-#define WINDOW_ACCU_4_2_6                                                          \
-    {                                                                              \
-        s32Temp = (SINT32)WIND_4_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 2];        \
-        s32Temp2 = (SINT32)WIND_4_SUBBANDS_2_0 * (SINT32)s16X[ChOffset + 32 + 6];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 8 + 2];   \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_1 * (SINT32)s16X[ChOffset + 24 + 6]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 16 + 2];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_2 * (SINT32)s16X[ChOffset + 16 + 6]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 24 + 2];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_3 * (SINT32)s16X[ChOffset + 8 + 6];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 32 + 2];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_2_4 * (SINT32)s16X[ChOffset + 6];      \
-        s32DCTY[2] = (SINT32)(s32Temp);                                            \
-        s32DCTY[6] = (SINT32)(s32Temp2);                                           \
-    }
-#define WINDOW_ACCU_4_3_5                                                          \
-    {                                                                              \
-        s32Temp = (SINT32)WIND_4_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 3];        \
-        s32Temp2 = (SINT32)WIND_4_SUBBANDS_3_0 * (SINT32)s16X[ChOffset + 32 + 5];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 8 + 3];   \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_1 * (SINT32)s16X[ChOffset + 24 + 5]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 16 + 3];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_2 * (SINT32)s16X[ChOffset + 16 + 5]; \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 24 + 3];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_3 * (SINT32)s16X[ChOffset + 8 + 5];  \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 32 + 3];  \
-        s32Temp2 += (SINT32)WIND_4_SUBBANDS_3_4 * (SINT32)s16X[ChOffset + 5];      \
-        s32DCTY[3] = (SINT32)(s32Temp);                                            \
-        s32DCTY[5] = (SINT32)(s32Temp2);                                           \
-    }
-
-#define WINDOW_ACCU_4_4                                                                                      \
-    {                                                                                                        \
-        s32Temp = (SINT32)WIND_4_SUBBANDS_4_0 * (SINT32)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]);      \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_4_1 * (SINT32)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \
-        s32Temp += (SINT32)WIND_4_SUBBANDS_4_2 * (SINT32)s16X[ChOffset + 4 + 16];                            \
-        s32DCTY[4] = (SINT32)(s32Temp);                                                                      \
-    }
-#endif
-#define WINDOW_PARTIAL_4   \
-    {                      \
-        WINDOW_ACCU_4_0;   \
-        WINDOW_ACCU_4_1_7; \
-        WINDOW_ACCU_4_2_6; \
-        WINDOW_ACCU_4_3_5; \
-        WINDOW_ACCU_4_4;   \
-    }
-
-#define WINDOW_PARTIAL_8    \
-    {                       \
-        WINDOW_ACCU_8_0;    \
-        WINDOW_ACCU_8_1_15; \
-        WINDOW_ACCU_8_2_14; \
-        WINDOW_ACCU_8_3_13; \
-        WINDOW_ACCU_8_4_12; \
-        WINDOW_ACCU_8_5_11; \
-        WINDOW_ACCU_8_6_10; \
-        WINDOW_ACCU_8_7_9;  \
-        WINDOW_ACCU_8_8;    \
-    }
-#else
-#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-#define WINDOW_ACCU_4(i)                                                                    \
-    {                                                                                       \
-        s64Temp = ((SINT64)gas32CoeffFor4SBs[i] * (SINT64)s16X[ChOffset + i]);              \
-        s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 8)] * (SINT64)s16X[ChOffset + i + 8]);   \
-        s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 16)] * (SINT64)s16X[ChOffset + i + 16]); \
-        s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 24)] * (SINT64)s16X[ChOffset + i + 24]); \
-        s64Temp += ((SINT64)gas32CoeffFor4SBs[(i + 32)] * (SINT64)s16X[ChOffset + i + 32]); \
-        s32DCTY[i] = (SINT32)(s64Temp >> 16);                                               \
-        /*BT_WARN("s32DCTY4: 0x%x \n", s32DCTY[i]);*/                                       \
-    }
-#else
-#define WINDOW_ACCU_4(i)                                                                                                                                                         \
-    {                                                                                                                                                                            \
-        s32DCTY[i] = (gas32CoeffFor4SBs[i * 2] * s16X[ChOffset + i]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16);                          \
-        s32DCTY[i] += (gas32CoeffFor4SBs[(i + 8) * 2] * s16X[ChOffset + i + 8]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 8) * 2) + 1]) * s16X[ChOffset + i + 8]) >> 16);     \
-        s32DCTY[i] += (gas32CoeffFor4SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 16) * 2) + 1]) * s16X[ChOffset + i + 16]) >> 16); \
-        s32DCTY[i] += (gas32CoeffFor4SBs[(i + 24) * 2] * s16X[ChOffset + i + 24]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 24) * 2) + 1]) * s16X[ChOffset + i + 24]) >> 16); \
-        s32DCTY[i] += (gas32CoeffFor4SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + (((SINT32)(UINT16)(gas32CoeffFor4SBs[((i + 32) * 2) + 1]) * s16X[ChOffset + i + 32]) >> 16); \
-    }
-#endif
-#define WINDOW_PARTIAL_4  \
-    {                     \
-        WINDOW_ACCU_4(0); \
-        WINDOW_ACCU_4(1); \
-        WINDOW_ACCU_4(2); \
-        WINDOW_ACCU_4(3); \
-        WINDOW_ACCU_4(4); \
-        WINDOW_ACCU_4(5); \
-        WINDOW_ACCU_4(6); \
-        WINDOW_ACCU_4(7); \
-    }
-
-#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-#define WINDOW_ACCU_8(i)                                                                              \
-    {                                                                                                 \
-        s64Temp = ((((SINT64)gas32CoeffFor8SBs[i] * (SINT64)s16X[ChOffset + i])));                    \
-        s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 16)] * (SINT64)s16X[ChOffset + i + 16])));       \
-        s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 32)] * (SINT64)s16X[ChOffset + i + 32])));       \
-        s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 48)] * (SINT64)s16X[ChOffset + i + 48])));       \
-        s64Temp += ((((SINT64)gas32CoeffFor8SBs[(i + 64)] * (SINT64)s16X[ChOffset + i + 64])));       \
-        /*BT_WARN("s32DCTY8: %d= 0x%x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i], s16X[ChOffset+i]);*/ \
-        s32DCTY[i] = (SINT32)(s64Temp >> 16);                                                         \
-    }
-#else
-#define WINDOW_ACCU_8(i)                                                                                                                                                         \
-    {                                                                                                                                                                            \
-        s32DCTY[i] = (gas32CoeffFor8SBs[i * 2] * s16X[ChOffset + i]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16);                          \
-        s32DCTY[i] += (gas32CoeffFor8SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 16) * 2) + 1]) * s16X[ChOffset + i + 16]) >> 16); \
-        s32DCTY[i] += (gas32CoeffFor8SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 32) * 2) + 1]) * s16X[ChOffset + i + 32]) >> 16); \
-        s32DCTY[i] += (gas32CoeffFor8SBs[(i + 48) * 2] * s16X[ChOffset + i + 48]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 48) * 2) + 1]) * s16X[ChOffset + i + 48]) >> 16); \
-        s32DCTY[i] += (gas32CoeffFor8SBs[(i + 64) * 2] * s16X[ChOffset + i + 64]) + (((SINT32)(UINT16)(gas32CoeffFor8SBs[((i + 64) * 2) + 1]) * s16X[ChOffset + i + 64]) >> 16); \
-        /*BT_WARN("s32DCTY8: %d = 0x%4x%4x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i * 2], (gas32CoeffFor8SBs[(i * 2) + 1]), s16X[ChOffset+i]);*/                                 \
-        /*s32DCTY[i]=(SINT32)(s64Temp>>16);*/                                                                                                                                    \
-    }
-#endif
-#define WINDOW_PARTIAL_8   \
-    {                      \
-        WINDOW_ACCU_8(0);  \
-        WINDOW_ACCU_8(1);  \
-        WINDOW_ACCU_8(2);  \
-        WINDOW_ACCU_8(3);  \
-        WINDOW_ACCU_8(4);  \
-        WINDOW_ACCU_8(5);  \
-        WINDOW_ACCU_8(6);  \
-        WINDOW_ACCU_8(7);  \
-        WINDOW_ACCU_8(8);  \
-        WINDOW_ACCU_8(9);  \
-        WINDOW_ACCU_8(10); \
-        WINDOW_ACCU_8(11); \
-        WINDOW_ACCU_8(12); \
-        WINDOW_ACCU_8(13); \
-        WINDOW_ACCU_8(14); \
-        WINDOW_ACCU_8(15); \
-    }
-#endif
-#endif
-
-static SINT16 ShiftCounter = 0;
-extern SINT16 EncMaxShiftCounter;
-/****************************************************************************
-* SbcAnalysisFilter - performs Analysis of the input audio stream
-*
-* RETURNS : N/A
-*/
-void SbcAnalysisFilter4(SBC_ENC_PARAMS *pstrEncParams)
-{
-    SINT16 *ps16PcmBuf;
-    SINT32 *ps32SbBuf;
-    SINT32 s32Blk, s32Ch;
-    SINT32 s32NumOfChannels, s32NumOfBlocks;
-    SINT32 i, *ps32X, *ps32X2;
-    SINT32 Offset, Offset2, ChOffset;
-#if (SBC_ARM_ASM_OPT == TRUE)
-    register SINT32 s32Hi, s32Hi2;
-#else
-#if (SBC_IPAQ_OPT == TRUE)
-#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-    register SINT64 s64Temp, s64Temp2;
-#else
-    register SINT32 s32Temp, s32Temp2;
-#endif
-#else
-
-#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-    SINT64 s64Temp;
-#endif
-
-#endif
-#endif
-
-    s32NumOfChannels = pstrEncParams->s16NumOfChannels;
-    s32NumOfBlocks = pstrEncParams->s16NumOfBlocks;
-
-    ps16PcmBuf = pstrEncParams->ps16NextPcmBuffer;
-
-    ps32SbBuf = pstrEncParams->s32SbBuffer;
-    Offset2 = (SINT32)(EncMaxShiftCounter + 40);
-    for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
-        Offset = (SINT32)(EncMaxShiftCounter - ShiftCounter);
-        /* Store new samples */
-        if (s32NumOfChannels == 1) {
-            s16X[3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-        } else {
-            s16X[3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-        }
-        for (s32Ch = 0; s32Ch < s32NumOfChannels; s32Ch++) {
-            ChOffset = s32Ch * Offset2 + Offset;
-
-            WINDOW_PARTIAL_4
-
-            SBC_FastIDCT4(s32DCTY, ps32SbBuf);
-
-            ps32SbBuf += SUB_BANDS_4;
-        }
-        if (s32NumOfChannels == 1) {
-            if (ShiftCounter >= EncMaxShiftCounter) {
-                SHIFTUP_X4;
-                ShiftCounter = 0;
-            } else {
-                ShiftCounter += SUB_BANDS_4;
-            }
-        } else {
-            if (ShiftCounter >= EncMaxShiftCounter) {
-                SHIFTUP_X4_2;
-                ShiftCounter = 0;
-            } else {
-                ShiftCounter += SUB_BANDS_4;
-            }
-        }
-    }
-}
-
-/* //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// */
-void SbcAnalysisFilter8(SBC_ENC_PARAMS *pstrEncParams)
-{
-    SINT16 *ps16PcmBuf;
-    SINT32 *ps32SbBuf;
-    SINT32 s32Blk, s32Ch; /* counter for block*/
-    SINT32 Offset, Offset2;
-    SINT32 s32NumOfChannels, s32NumOfBlocks;
-    SINT32 i, *ps32X, *ps32X2;
-    SINT32 ChOffset;
-#if (SBC_ARM_ASM_OPT == TRUE)
-    register SINT32 s32Hi, s32Hi2;
-#else
-#if (SBC_IPAQ_OPT == TRUE)
-#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-    register SINT64 s64Temp, s64Temp2;
-#else
-    register SINT32 s32Temp, s32Temp2;
-#endif
-#else
-#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE)
-    SINT64 s64Temp;
-#endif
-#endif
-#endif
-
-    s32NumOfChannels = pstrEncParams->s16NumOfChannels;
-    s32NumOfBlocks = pstrEncParams->s16NumOfBlocks;
-
-    ps16PcmBuf = pstrEncParams->ps16NextPcmBuffer;
-
-    ps32SbBuf = pstrEncParams->s32SbBuffer;
-    Offset2 = (SINT32)(EncMaxShiftCounter + 80);
-    for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
-        Offset = (SINT32)(EncMaxShiftCounter - ShiftCounter);
-        /* Store new samples */
-        if (s32NumOfChannels == 1) {
-            s16X[7 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[6 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[5 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[4 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-        } else {
-            s16X[7 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 7 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[6 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 6 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[5 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 5 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[4 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 4 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 3 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 2 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 1 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-            s16X[Offset2 + 0 + Offset] = *ps16PcmBuf;
-            ps16PcmBuf++;
-        }
-        for (s32Ch = 0; s32Ch < s32NumOfChannels; s32Ch++) {
-            ChOffset = s32Ch * Offset2 + Offset;
-
-            WINDOW_PARTIAL_8
-
-            SBC_FastIDCT8(s32DCTY, ps32SbBuf);
-
-            ps32SbBuf += SUB_BANDS_8;
-        }
-        if (s32NumOfChannels == 1) {
-            if (ShiftCounter >= EncMaxShiftCounter) {
-                SHIFTUP_X8;
-                ShiftCounter = 0;
-            } else {
-                ShiftCounter += SUB_BANDS_8;
-            }
-        } else {
-            if (ShiftCounter >= EncMaxShiftCounter) {
-                SHIFTUP_X8_2;
-                ShiftCounter = 0;
-            } else {
-                ShiftCounter += SUB_BANDS_8;
-            }
-        }
-    }
-}
-
-void SbcAnalysisInit(void)
-{
-    static bool loaded = false;
-    if (!loaded) {
-        loaded = true;
-#if BT_BLE_DYNAMIC_ENV_MEMORY == TRUE
-        s32X = (SINT32 *)osi_malloc(sizeof(SINT32) * (ENC_VX_BUFFER_SIZE / 2));
-        s32DCTY = (SINT32 *)osi_malloc(sizeof(SINT32) * 16);
-        assert(s32X);
-        assert(s32DCTY);
-        memset(s32X, 0, sizeof(SINT16) * ENC_VX_BUFFER_SIZE);
-        memset(s32DCTY, 0, sizeof(SINT32) * 16);
-        s16X = (SINT16 *)s32X;
-#endif
-    }
-    memset(s16X, 0, ENC_VX_BUFFER_SIZE * sizeof(SINT16));
-    ShiftCounter = 0;
-}
-
-#endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct.c
deleted file mode 100644
index a9b8baf77..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct.c
+++ /dev/null
@@ -1,241 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  source file for fast dct operations
- *
- ******************************************************************************/
-#include "sbc_encoder.h"
-#include "sbc_enc_func_declare.h"
-#include "sbc_dct.h"
-
-#if defined(SBC_ENC_INCLUDED)
-
-/*******************************************************************************
-**
-** Function         SBC_FastIDCT8
-**
-** Description      implementation of fast DCT algorithm by Feig and Winograd
-**
-**
-** Returns          y = dct(pInVect)
-**
-**
-*******************************************************************************/
-
-#if (SBC_IS_64_MULT_IN_IDCT == FALSE)
-#define SBC_COS_PI_SUR_4       (0x00005a82) /* ((0x8000) * 0.7071)     = cos(pi/4) */
-#define SBC_COS_PI_SUR_8       (0x00007641) /* ((0x8000) * 0.9239)     = (cos(pi/8)) */
-#define SBC_COS_3PI_SUR_8      (0x000030fb) /* ((0x8000) * 0.3827)     = (cos(3*pi/8)) */
-#define SBC_COS_PI_SUR_16      (0x00007d8a) /* ((0x8000) * 0.9808))     = (cos(pi/16)) */
-#define SBC_COS_3PI_SUR_16     (0x00006a6d) /* ((0x8000) * 0.8315))     = (cos(3*pi/16)) */
-#define SBC_COS_5PI_SUR_16     (0x0000471c) /* ((0x8000) * 0.5556))     = (cos(5*pi/16)) */
-#define SBC_COS_7PI_SUR_16     (0x000018f8) /* ((0x8000) * 0.1951))     = (cos(7*pi/16)) */
-#define SBC_IDCT_MULT(a, b, c) SBC_MULT_32_16_SIMPLIFIED(a, b, c)
-#else
-#define SBC_COS_PI_SUR_4       (0x5A827999) /* ((0x80000000) * 0.707106781)      = (cos(pi/4)   ) */
-#define SBC_COS_PI_SUR_8       (0x7641AF3C) /* ((0x80000000) * 0.923879533)      = (cos(pi/8)   ) */
-#define SBC_COS_3PI_SUR_8      (0x30FBC54D) /* ((0x80000000) * 0.382683432)      = (cos(3*pi/8) ) */
-#define SBC_COS_PI_SUR_16      (0x7D8A5F3F) /* ((0x80000000) * 0.98078528 ))     = (cos(pi/16)  ) */
-#define SBC_COS_3PI_SUR_16     (0x6A6D98A4) /* ((0x80000000) * 0.831469612))     = (cos(3*pi/16)) */
-#define SBC_COS_5PI_SUR_16     (0x471CECE6) /* ((0x80000000) * 0.555570233))     = (cos(5*pi/16)) */
-#define SBC_COS_7PI_SUR_16     (0x18F8B83C) /* ((0x80000000) * 0.195090322))     = (cos(7*pi/16)) */
-#define SBC_IDCT_MULT(a, b, c) SBC_MULT_32_32(a, b, c)
-#endif /* SBC_IS_64_MULT_IN_IDCT */
-
-#if (SBC_FAST_DCT == FALSE)
-extern const SINT16 gas16AnalDCTcoeff8[];
-extern const SINT16 gas16AnalDCTcoeff4[];
-#endif
-
-void SBC_FastIDCT8(SINT32 *pInVect, SINT32 *pOutVect)
-{
-#if (SBC_FAST_DCT == TRUE)
-#if (SBC_ARM_ASM_OPT == TRUE)
-#else
-#if (SBC_IPAQ_OPT == TRUE)
-#if (SBC_IS_64_MULT_IN_IDCT == TRUE)
-    SINT64 s64Temp;
-#endif
-#else
-#if (SBC_IS_64_MULT_IN_IDCT == TRUE)
-    SINT32 s32HiTemp;
-#else
-    SINT32 s32In2Temp;
-    register SINT32 s32In1Temp;
-#endif
-#endif
-#endif
-
-    register SINT32 x0, x1, x2, x3, x4, x5, x6, x7, temp;
-    SINT32 res_even[4], res_odd[4];
-    /*x0= (pInVect[4])/2 ;*/
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, pInVect[4], x0);
-    /*BT_WARN("x0 0x%x = %d = %d * %d\n", x0, x0, SBC_COS_PI_SUR_4, pInVect[4]);*/
-
-    x1 = (pInVect[3] + pInVect[5]) >> 1;
-    x2 = (pInVect[2] + pInVect[6]) >> 1;
-    x3 = (pInVect[1] + pInVect[7]) >> 1;
-    x4 = (pInVect[0] + pInVect[8]) >> 1;
-    x5 = (pInVect[9] - pInVect[15]) >> 1;
-    x6 = (pInVect[10] - pInVect[14]) >> 1;
-    x7 = (pInVect[11] - pInVect[13]) >> 1;
-
-    /* 2-point IDCT of x0 and x4 as in (11) */
-    temp = x0;
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, (x0 + x4), x0);   /*x0 = ( x0 + x4 ) * cos(1*pi/4) ; */
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, (temp - x4), x4); /*x4 = ( temp - x4 ) * cos(1*pi/4) ; */
-
-    /* rearrangement of x2 and x6 as in (15) */
-    x2 -= x6;
-    x6 <<= 1;
-
-    /* 2-point IDCT of x2 and x6 and post-multiplication as in (15) */
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, x6, x6); /*x6 = x6 * cos(1*pi/4) ; */
-    temp = x2;
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_8, (x2 + x6), x2);    /*x2 = ( x2 + x6 ) * cos(1*pi/8) ; */
-    SBC_IDCT_MULT(SBC_COS_3PI_SUR_8, (temp - x6), x6); /*x6 = ( temp - x6 ) * cos(3*pi/8) ;*/
-
-    /* 4-point IDCT of x0,x2,x4 and x6 as in (11) */
-    res_even[0] = x0 + x2;
-    res_even[1] = x4 + x6;
-    res_even[2] = x4 - x6;
-    res_even[3] = x0 - x2;
-
-    /* rearrangement of x1,x3,x5,x7 as in (15) */
-    x7 <<= 1;
-    x5 = (x5 << 1) - x7;
-    x3 = (x3 << 1) - x5;
-    x1 -= x3 >> 1;
-
-    /* two-dimensional IDCT of x1 and x5 */
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, x5, x5); /*x5 = x5 * cos(1*pi/4) ; */
-    temp = x1;
-    x1 = x1 + x5;
-    x5 = temp - x5;
-
-    /* rearrangement of x3 and x7 as in (15) */
-    x3 -= x7;
-    x7 <<= 1;
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_4, x7, x7); /*x7 = x7 * cos(1*pi/4) ; */
-
-    /* 2-point IDCT of x3 and x7 and post-multiplication as in (15) */
-    temp = x3;
-    SBC_IDCT_MULT(SBC_COS_PI_SUR_8, (x3 + x7), x3);    /*x3 = ( x3 + x7 ) * cos(1*pi/8)  ; */
-    SBC_IDCT_MULT(SBC_COS_3PI_SUR_8, (temp - x7), x7); /*x7 = ( temp - x7 ) * cos(3*pi/8) ;*/
-
-    /* 4-point IDCT of x1,x3,x5 and x7 and post multiplication by diagonal matrix as in (14) */
-    SBC_IDCT_MULT((SBC_COS_PI_SUR_16), (x1 + x3), res_odd[0]);  /*res_odd[ 0 ] = ( x1 + x3 ) * cos(1*pi/16) ; */
-    SBC_IDCT_MULT((SBC_COS_3PI_SUR_16), (x5 + x7), res_odd[1]); /*res_odd[ 1 ] = ( x5 + x7 ) * cos(3*pi/16) ; */
-    SBC_IDCT_MULT((SBC_COS_5PI_SUR_16), (x5 - x7), res_odd[2]); /*res_odd[ 2 ] = ( x5 - x7 ) * cos(5*pi/16) ; */
-    SBC_IDCT_MULT((SBC_COS_7PI_SUR_16), (x1 - x3), res_odd[3]); /*res_odd[ 3 ] = ( x1 - x3 ) * cos(7*pi/16) ; */
-
-    /* additions and subtractions as in (9) */
-    pOutVect[0] = (res_even[0] + res_odd[0]);
-    pOutVect[1] = (res_even[1] + res_odd[1]);
-    pOutVect[2] = (res_even[2] + res_odd[2]);
-    pOutVect[3] = (res_even[3] + res_odd[3]);
-    pOutVect[7] = (res_even[0] - res_odd[0]);
-    pOutVect[6] = (res_even[1] - res_odd[1]);
-    pOutVect[5] = (res_even[2] - res_odd[2]);
-    pOutVect[4] = (res_even[3] - res_odd[3]);
-#else
-    UINT8 Index, k;
-    SINT32 temp;
-    /*Calculate 4 subband samples by matrixing*/
-    for (Index = 0; Index < 8; Index++) {
-        temp = 0;
-        for (k = 0; k < 16; k++) {
-            /*temp += (SINT32)(((SINT64)M[(Index*strEncParams->numOfSubBands*2)+k] * Y[k]) >> 16 );*/
-            temp += (gas16AnalDCTcoeff8[(Index * 8 * 2) + k] * (pInVect[k] >> 16));
-            temp += ((gas16AnalDCTcoeff8[(Index * 8 * 2) + k] * (pInVect[k] & 0xFFFF)) >> 16);
-        }
-        pOutVect[Index] = temp;
-    }
-#endif
-    /*    BT_WARN("pOutVect: 0x%x;0x%x;0x%x;0x%x;0x%x;0x%x;0x%x;0x%x\n",\
-            pOutVect[0],pOutVect[1],pOutVect[2],pOutVect[3],pOutVect[4],pOutVect[5],pOutVect[6],pOutVect[7]);*/
-}
-
-/*******************************************************************************
-**
-** Function         SBC_FastIDCT4
-**
-** Description      implementation of fast DCT algorithm by Feig and Winograd
-**
-**
-** Returns          y = dct(x0)
-**
-**
-*******************************************************************************/
-void SBC_FastIDCT4(SINT32 *pInVect, SINT32 *pOutVect)
-{
-#if (SBC_FAST_DCT == TRUE)
-#if (SBC_ARM_ASM_OPT == TRUE)
-#else
-#if (SBC_IPAQ_OPT == TRUE)
-#if (SBC_IS_64_MULT_IN_IDCT == TRUE)
-    SINT64 s64Temp;
-#endif
-#else
-#if (SBC_IS_64_MULT_IN_IDCT == TRUE)
-    SINT32 s32HiTemp;
-#else
-    UINT16 s32In2Temp;
-    SINT32 s32In1Temp;
-#endif
-#endif
-#endif
-    SINT32 temp, x2;
-    SINT32 tmp[8];
-
-    x2 = pInVect[2] >> 1;
-    temp = (pInVect[0] + pInVect[4]);
-    SBC_IDCT_MULT((SBC_COS_PI_SUR_4 >> 1), temp, tmp[0]);
-    tmp[1] = x2 - tmp[0];
-    tmp[0] += x2;
-    temp = (pInVect[1] + pInVect[3]);
-    SBC_IDCT_MULT((SBC_COS_3PI_SUR_8 >> 1), temp, tmp[3]);
-    SBC_IDCT_MULT((SBC_COS_PI_SUR_8 >> 1), temp, tmp[2]);
-    temp = (pInVect[5] - pInVect[7]);
-    SBC_IDCT_MULT((SBC_COS_3PI_SUR_8 >> 1), temp, tmp[5]);
-    SBC_IDCT_MULT((SBC_COS_PI_SUR_8 >> 1), temp, tmp[4]);
-    tmp[6] = tmp[2] + tmp[5];
-    tmp[7] = tmp[3] - tmp[4];
-    pOutVect[0] = (tmp[0] + tmp[6]);
-    pOutVect[1] = (tmp[1] + tmp[7]);
-    pOutVect[2] = (tmp[1] - tmp[7]);
-    pOutVect[3] = (tmp[0] - tmp[6]);
-#else
-    UINT8 Index, k;
-    SINT32 temp;
-    /*Calculate 4 subband samples by matrixing*/
-    for (Index = 0; Index < 4; Index++) {
-        temp = 0;
-        for (k = 0; k < 8; k++) {
-            /*temp += (SINT32)(((SINT64)M[(Index*strEncParams->numOfSubBands*2)+k] * Y[k]) >> 16 ); */
-            temp += (gas16AnalDCTcoeff4[(Index * 4 * 2) + k] * (pInVect[k] >> 16));
-            temp += ((gas16AnalDCTcoeff4[(Index * 4 * 2) + k] * (pInVect[k] & 0xFFFF)) >> 16);
-        }
-        pOutVect[Index] = temp;
-    }
-#endif
-}
-
-#endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct.h
deleted file mode 100644
index 78671b357..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Definitions for the fast DCT.
- *
- ******************************************************************************/
-
-#ifndef SBC_DCT_H
-#define SBC_DCT_H
-
-#if (SBC_ARM_ASM_OPT == TRUE)
-#define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1, s32OutLow)                                    \
-    {                                                                                           \
-        __asm {                                                                               \
-    MUL s32OutLow,(SINT32)s16In2, (s32In1>>15) \
-        }                                                                                       \
-    }
-#else
-#if (SBC_DSP_OPT == TRUE)
-#define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1, s32OutLow) s32OutLow = SBC_Multiply_32_16_Simplified((SINT32)s16In2, s32In1);
-#else
-#if (SBC_IPAQ_OPT == TRUE)
-/*#define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1 , s32OutLow) s32OutLow=(SINT32)((SINT32)(s16In2)*(SINT32)(s32In1>>15)); */
-#define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1, s32OutLow) s32OutLow = (SINT32)(((SINT64)s16In2 * (SINT64)s32In1) >> 15);
-#if (SBC_IS_64_MULT_IN_IDCT == TRUE)
-#define SBC_MULT_32_32(s32In2, s32In1, s32OutLow)            \
-    {                                                        \
-        s64Temp = ((SINT64)s32In2) * ((SINT64)s32In1) >> 31; \
-        s32OutLow = (SINT32)s64Temp;                         \
-    }
-#endif
-#else
-#define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1, s32OutLow)           \
-    {                                                                  \
-        s32In1Temp = s32In1;                                           \
-        s32In2Temp = (SINT32)s16In2;                                   \
-                                                                       \
-        /* Multiply one +ve and the other -ve number */                \
-        if (s32In1Temp < 0) {                                          \
-            s32In1Temp ^= 0xFFFFFFFF;                                  \
-            s32In1Temp++;                                              \
-            s32OutLow = (s32In2Temp * (s32In1Temp >> 16));             \
-            s32OutLow += ((s32In2Temp * (s32In1Temp & 0xFFFF)) >> 16); \
-            s32OutLow ^= 0xFFFFFFFF;                                   \
-            s32OutLow++;                                               \
-        } else {                                                       \
-            s32OutLow = (s32In2Temp * (s32In1Temp >> 16));             \
-            s32OutLow += ((s32In2Temp * (s32In1Temp & 0xFFFF)) >> 16); \
-        }                                                              \
-        s32OutLow <<= 1;                                               \
-    }
-#if (SBC_IS_64_MULT_IN_IDCT == TRUE)
-#define SBC_MULT_64(s32In1, s32In2, s32OutLow, s32OutHi)                              \
-    {                                                                                 \
-        s32OutLow = (SINT32)(((SINT64)s32In1 * (SINT64)s32In2) & 0x00000000FFFFFFFF); \
-        s32OutHi = (SINT32)(((SINT64)s32In1 * (SINT64)s32In2) >> 32);                 \
-    }
-#define SBC_MULT_32_32(s32In2, s32In1, s32OutLow)                        \
-    {                                                                    \
-        s32HiTemp = 0;                                                   \
-        SBC_MULT_64(s32In2, s32In1, s32OutLow, s32HiTemp);               \
-        s32OutLow = (((s32OutLow >> 15) & 0x1FFFF) | (s32HiTemp << 17)); \
-    }
-#endif
-
-#endif
-#endif
-#endif
-
-#endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c
deleted file mode 100644
index 800a722a9..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_dct_coeffs.c
+++ /dev/null
@@ -1,203 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains the coefficient table used for DCT computation in
- *  analysis.
- *
- ******************************************************************************/
-
-#include "sbc_encoder.h"
-
-#if defined(SBC_ENC_INCLUDED)
-
-/*DCT coeff for 4 sub-band case.*/
-#if (SBC_FAST_DCT == FALSE)
-const SINT16 gas16AnalDCTcoeff4[] = {
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(0.0000 * 32768),
-    (SINT16)(-0.3827 * 32768),
-
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.9239 * 32768),
-
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.0000 * 32768),
-    (SINT16)(-0.9239 * 32768),
-
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.3827 * 32768)
-};
-
-/*DCT coeff for 8 sub-band case.*/
-const SINT16 gas16AnalDCTcoeff8[] = {
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(0.0000 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(0.0000 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(0.0000 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.8315 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(-0.7071 * 32768),
-    (SINT16)(0.9808 * 32768),
-    (SINT16)(-0.9239 * 32768),
-    (SINT16)(0.5556 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(1.0000 * 32767),
-    (SINT16)(-0.9808 * 32768),
-    (SINT16)(0.9239 * 32768),
-    (SINT16)(-0.8315 * 32768),
-    (SINT16)(0.7071 * 32768),
-    (SINT16)(-0.5556 * 32768),
-    (SINT16)(0.3827 * 32768),
-    (SINT16)(-0.1951 * 32768),
-    (SINT16)(-0.0000 * 32768),
-    (SINT16)(0.1951 * 32768),
-    (SINT16)(-0.3827 * 32768),
-    (SINT16)(0.5556 * 32768)
-};
-#endif
-
-#endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c
deleted file mode 100644
index 06af17a40..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_mono.c
+++ /dev/null
@@ -1,183 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains the code for bit allocation algorithm. It calculates
- *  the number of bits required for the encoded stream of data.
- *
- ******************************************************************************/
-
-/*Includes*/
-#include "sbc_encoder.h"
-#include "sbc_enc_func_declare.h"
-
-#if defined(SBC_ENC_INCLUDED)
-
-/*global arrays*/
-const SINT16 sbc_enc_as16Offset4[4][4] = { { -1, 0, 0, 0 }, { -2, 0, 0, 1 }, { -2, 0, 0, 1 }, { -2, 0, 0, 1 } };
-const SINT16 sbc_enc_as16Offset8[4][8] = { { -2, 0, 0, 0, 0, 0, 0, 1 },
-                                           { -3, 0, 0, 0, 0, 0, 1, 2 },
-                                           { -4, 0, 0, 0, 0, 0, 1, 2 },
-                                           { -4, 0, 0, 0, 0, 0, 1, 2 } };
-
-/****************************************************************************
-* BitAlloc - Calculates the required number of bits for the given scale factor
-* and the number of subbands.
-*
-* RETURNS : N/A
-*/
-
-void sbc_enc_bit_alloc_mono(SBC_ENC_PARAMS *pstrCodecParams)
-{
-    SINT32 s32MaxBitNeed; /*to store the max bits needed per sb*/
-    SINT32 s32BitCount;   /*the used number of bits*/
-    SINT32 s32SliceCount; /*to store hwo many slices can be put in bitpool*/
-    SINT32 s32BitSlice;   /*number of bitslices in bitpool*/
-    SINT32 s32Sb;         /*counter for sub-band*/
-    SINT32 s32Ch;         /*counter for channel*/
-    SINT16 *ps16BitNeed;  /*temp memory to store required number of bits*/
-    SINT32 s32Loudness;   /*used in Loudness calculation*/
-    SINT16 *ps16GenBufPtr;
-    SINT16 *ps16GenArrPtr;
-    SINT16 *ps16GenTabPtr;
-    SINT32 s32NumOfSubBands = pstrCodecParams->s16NumOfSubBands;
-
-    ps16BitNeed = pstrCodecParams->s16ScartchMemForBitAlloc;
-
-    for (s32Ch = 0; s32Ch < pstrCodecParams->s16NumOfChannels; s32Ch++) {
-        ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * SBC_MAX_NUM_OF_SUBBANDS;
-
-        /* bitneed values are derived from scale factor */
-        if (pstrCodecParams->s16AllocationMethod == SBC_SNR) {
-            ps16BitNeed = pstrCodecParams->as16ScaleFactor;
-            ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        } else {
-            ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-            if (s32NumOfSubBands == 4) {
-                ps16GenTabPtr = (SINT16 *)
-                    sbc_enc_as16Offset4[pstrCodecParams->s16SamplingFreq];
-            } else {
-                ps16GenTabPtr = (SINT16 *)
-                    sbc_enc_as16Offset8[pstrCodecParams->s16SamplingFreq];
-            }
-            for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-                if (pstrCodecParams->as16ScaleFactor[s32Ch * s32NumOfSubBands + s32Sb] == 0) {
-                    *(ps16GenBufPtr) = -5;
-                } else {
-                    s32Loudness =
-                        (SINT32)(pstrCodecParams->as16ScaleFactor[s32Ch * s32NumOfSubBands + s32Sb] - *ps16GenTabPtr);
-                    if (s32Loudness > 0) {
-                        *(ps16GenBufPtr) = (SINT16)(s32Loudness >> 1);
-                    } else {
-                        *(ps16GenBufPtr) = (SINT16)s32Loudness;
-                    }
-                }
-                ps16GenBufPtr++;
-                ps16GenTabPtr++;
-            }
-        }
-
-        /* max bitneed index is searched*/
-        s32MaxBitNeed = 0;
-        ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-            if (*(ps16GenBufPtr) > s32MaxBitNeed) {
-                s32MaxBitNeed = *(ps16GenBufPtr);
-            }
-
-            ps16GenBufPtr++;
-        }
-        ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        /*iterative process to find hwo many bitslices fit into the bitpool*/
-        s32BitSlice = s32MaxBitNeed + 1;
-        s32BitCount = pstrCodecParams->s16BitPool;
-        s32SliceCount = 0;
-        do {
-            s32BitSlice--;
-            s32BitCount -= s32SliceCount;
-            s32SliceCount = 0;
-
-            for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-                if ((((*ps16GenBufPtr - s32BitSlice) < 16) && (*ps16GenBufPtr - s32BitSlice) >= 1)) {
-                    if ((*ps16GenBufPtr - s32BitSlice) == 1) {
-                        s32SliceCount += 2;
-                    } else {
-                        s32SliceCount++;
-                    }
-                }
-                ps16GenBufPtr++;
-
-            } /*end of for*/
-            ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        } while (s32BitCount - s32SliceCount > 0);
-
-        if (s32BitCount == 0) {
-            s32BitCount -= s32SliceCount;
-            s32BitSlice--;
-        }
-
-        /*Bits are distributed until the last bitslice is reached*/
-        ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * s32NumOfSubBands;
-        ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-            if (*(ps16GenBufPtr) < s32BitSlice + 2) {
-                *(ps16GenArrPtr) = 0;
-            } else {
-                *(ps16GenArrPtr) = ((*(ps16GenBufPtr)-s32BitSlice) < 16) ?
-                                       (SINT16)(*(ps16GenBufPtr)-s32BitSlice) :
-                                       16;
-            }
-
-            ps16GenBufPtr++;
-            ps16GenArrPtr++;
-        }
-        ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * s32NumOfSubBands;
-        ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands;
-        /*the remaining bits are allocated starting at subband 0*/
-        s32Sb = 0;
-        while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
-            if ((*(ps16GenArrPtr) >= 2) && (*(ps16GenArrPtr) < 16)) {
-                (*(ps16GenArrPtr))++;
-                s32BitCount--;
-            } else if ((*(ps16GenBufPtr) == s32BitSlice + 1) &&
-                       (s32BitCount > 1)) {
-                *(ps16GenArrPtr) = 2;
-                s32BitCount -= 2;
-            }
-            s32Sb++;
-            ps16GenArrPtr++;
-            ps16GenBufPtr++;
-        }
-        ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * s32NumOfSubBands;
-
-        s32Sb = 0;
-        while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
-            if (*(ps16GenArrPtr) < 16) {
-                (*(ps16GenArrPtr))++;
-                s32BitCount--;
-            }
-            s32Sb++;
-            ps16GenArrPtr++;
-        }
-    }
-}
-/*End of BitAlloc() function*/
-
-#endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_ste.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_ste.c
deleted file mode 100644
index 598246133..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_bit_alloc_ste.c
+++ /dev/null
@@ -1,193 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains the code for bit allocation algorithm. It calculates
- *  the number of bits required for the encoded stream of data.
- *
- ******************************************************************************/
-
-/*Includes*/
-#include "sbc_encoder.h"
-#include "sbc_enc_func_declare.h"
-
-#if defined(SBC_ENC_INCLUDED)
-
-/*global arrays*/
-extern const SINT16 sbc_enc_as16Offset4[4][4];
-extern const SINT16 sbc_enc_as16Offset8[4][8];
-
-/****************************************************************************
-* BitAlloc - Calculates the required number of bits for the given scale factor
-* and the number of subbands.
-*
-* RETURNS : N/A
-*/
-
-void sbc_enc_bit_alloc_ste(SBC_ENC_PARAMS *pstrCodecParams)
-{
-    /* CAUTIOM -> mips optim for arm 32 require to use SINT32 instead of SINT16 */
-    /* Do not change variable type or name */
-    SINT32 s32MaxBitNeed; /*to store the max bits needed per sb*/
-    SINT32 s32BitCount;   /*the used number of bits*/
-    SINT32 s32SliceCount; /*to store hwo many slices can be put in bitpool*/
-    SINT32 s32BitSlice;   /*number of bitslices in bitpool*/
-    SINT32 s32Sb;         /*counter for sub-band*/
-    SINT32 s32Ch;         /*counter for channel*/
-    SINT16 *ps16BitNeed;  /*temp memory to store required number of bits*/
-    SINT32 s32Loudness;   /*used in Loudness calculation*/
-    SINT16 *ps16GenBufPtr, *pas16ScaleFactor;
-    SINT16 *ps16GenArrPtr;
-    SINT16 *ps16GenTabPtr;
-    SINT32 s32NumOfSubBands = pstrCodecParams->s16NumOfSubBands;
-    SINT32 s32BitPool = pstrCodecParams->s16BitPool;
-
-    /* bitneed values are derived from scale factor */
-    if (pstrCodecParams->s16AllocationMethod == SBC_SNR) {
-        ps16BitNeed = pstrCodecParams->as16ScaleFactor;
-        s32MaxBitNeed = pstrCodecParams->s16MaxBitNeed;
-    } else {
-        ps16BitNeed = pstrCodecParams->s16ScartchMemForBitAlloc;
-        pas16ScaleFactor = pstrCodecParams->as16ScaleFactor;
-        s32MaxBitNeed = 0;
-        ps16GenBufPtr = ps16BitNeed;
-        for (s32Ch = 0; s32Ch < 2; s32Ch++) {
-            if (s32NumOfSubBands == 4) {
-                ps16GenTabPtr = (SINT16 *)sbc_enc_as16Offset4[pstrCodecParams->s16SamplingFreq];
-            } else {
-                ps16GenTabPtr = (SINT16 *)sbc_enc_as16Offset8[pstrCodecParams->s16SamplingFreq];
-            }
-
-            for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-                if (*pas16ScaleFactor == 0) {
-                    *ps16GenBufPtr = -5;
-                } else {
-                    s32Loudness = (SINT32)(*pas16ScaleFactor - *ps16GenTabPtr);
-
-                    if (s32Loudness > 0) {
-                        *ps16GenBufPtr = (SINT16)(s32Loudness >> 1);
-                    } else {
-                        *ps16GenBufPtr = (SINT16)s32Loudness;
-                    }
-                }
-
-                if (*ps16GenBufPtr > s32MaxBitNeed) {
-                    s32MaxBitNeed = *ps16GenBufPtr;
-                }
-                pas16ScaleFactor++;
-                ps16GenBufPtr++;
-                ps16GenTabPtr++;
-            }
-        }
-    }
-
-    /* iterative process to find out hwo many bitslices fit into the bitpool */
-    s32BitSlice = s32MaxBitNeed + 1;
-    s32BitCount = s32BitPool;
-    s32SliceCount = 0;
-    do {
-        s32BitSlice--;
-        s32BitCount -= s32SliceCount;
-        s32SliceCount = 0;
-        ps16GenBufPtr = ps16BitNeed;
-
-        for (s32Sb = 0; s32Sb < 2 * s32NumOfSubBands; s32Sb++) {
-            if ((*ps16GenBufPtr >= s32BitSlice + 1) && (*ps16GenBufPtr < s32BitSlice + 16)) {
-                if (*(ps16GenBufPtr) == s32BitSlice + 1) {
-                    s32SliceCount += 2;
-                } else {
-                    s32SliceCount++;
-                }
-            }
-            ps16GenBufPtr++;
-        }
-    } while (s32BitCount - s32SliceCount > 0);
-
-    if (s32BitCount - s32SliceCount == 0) {
-        s32BitCount -= s32SliceCount;
-        s32BitSlice--;
-    }
-
-    /* Bits are distributed until the last bitslice is reached */
-    ps16GenBufPtr = ps16BitNeed;
-    ps16GenArrPtr = pstrCodecParams->as16Bits;
-    for (s32Ch = 0; s32Ch < 2; s32Ch++) {
-        for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-            if (*ps16GenBufPtr < s32BitSlice + 2) {
-                *ps16GenArrPtr = 0;
-            } else {
-                *ps16GenArrPtr = ((*(ps16GenBufPtr)-s32BitSlice) < 16) ?
-                                     (SINT16)(*(ps16GenBufPtr)-s32BitSlice) :
-                                     16;
-            }
-            ps16GenBufPtr++;
-            ps16GenArrPtr++;
-        }
-    }
-
-    /* the remaining bits are allocated starting at subband 0 */
-    s32Ch = 0;
-    s32Sb = 0;
-    ps16GenBufPtr = ps16BitNeed;
-    ps16GenArrPtr -= 2 * s32NumOfSubBands;
-
-    while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
-        if ((*(ps16GenArrPtr) >= 2) && (*(ps16GenArrPtr) < 16)) {
-            (*(ps16GenArrPtr))++;
-            s32BitCount--;
-        } else if ((*ps16GenBufPtr == s32BitSlice + 1) && (s32BitCount > 1)) {
-            *(ps16GenArrPtr) = 2;
-            s32BitCount -= 2;
-        }
-        if (s32Ch == 1) {
-            s32Ch = 0;
-            s32Sb++;
-            ps16GenBufPtr = ps16BitNeed + s32Sb;
-            ps16GenArrPtr = pstrCodecParams->as16Bits + s32Sb;
-
-        } else {
-            s32Ch = 1;
-            ps16GenBufPtr = ps16BitNeed + s32NumOfSubBands + s32Sb;
-            ps16GenArrPtr = pstrCodecParams->as16Bits + s32NumOfSubBands + s32Sb;
-        }
-    }
-
-    s32Ch = 0;
-    s32Sb = 0;
-    ps16GenArrPtr = pstrCodecParams->as16Bits;
-
-    while ((s32BitCount > 0) && (s32Sb < s32NumOfSubBands)) {
-        if (*(ps16GenArrPtr) < 16) {
-            (*(ps16GenArrPtr))++;
-            s32BitCount--;
-        }
-        if (s32Ch == 1) {
-            s32Ch = 0;
-            s32Sb++;
-            ps16GenArrPtr = pstrCodecParams->as16Bits + s32Sb;
-        } else {
-            s32Ch = 1;
-            ps16GenArrPtr = pstrCodecParams->as16Bits + s32NumOfSubBands + s32Sb;
-        }
-    }
-}
-
-/*End of BitAlloc() function*/
-
-#endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c
deleted file mode 100644
index 29dee9790..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_coeffs.c
+++ /dev/null
@@ -1,318 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains the Windowing coeffs for synthesis filter
- *
- ******************************************************************************/
-
-#include "sbc_encoder.h"
-
-#if defined(SBC_ENC_INCLUDED)
-
-#if (SBC_ARM_ASM_OPT == FALSE && SBC_IPAQ_OPT == FALSE)
-#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE)
-/*Window coeff for 4 sub band case*/
-const SINT16 gas32CoeffFor4SBs[] = {
-    (SINT16)((SINT32)0x00000000 >> 16), (SINT16)0x00000000,
-    (SINT16)((SINT32)0x001194E6 >> 16), (SINT16)0x001194E6,
-    (SINT16)((SINT32)0x0030E2D3 >> 16), (SINT16)0x0030E2D3,
-    (SINT16)((SINT32)0x00599403 >> 16), (SINT16)0x00599403,
-    (SINT16)((SINT32)0x007DBCC8 >> 16), (SINT16)0x007DBCC8,
-    (SINT16)((SINT32)0x007F88E4 >> 16), (SINT16)0x007F88E4,
-    (SINT16)((SINT32)0x003D239B >> 16), (SINT16)0x003D239B,
-    (SINT16)((SINT32)0xFF9BB9D5 >> 16), (SINT16)0xFF9BB9D5,
-
-    (SINT16)((SINT32)0x01659F45 >> 16), (SINT16)0x01659F45,
-    (SINT16)((SINT32)0x029DBAA3 >> 16), (SINT16)0x029DBAA3,
-    (SINT16)((SINT32)0x03B23341 >> 16), (SINT16)0x03B23341,
-    (SINT16)((SINT32)0x041EEE40 >> 16), (SINT16)0x041EEE40,
-    (SINT16)((SINT32)0x034FEE2C >> 16), (SINT16)0x034FEE2C,
-    (SINT16)((SINT32)0x00C8F2BC >> 16), (SINT16)0x00C8F2BC,
-    (SINT16)((SINT32)0xFC4F91D4 >> 16), (SINT16)0xFC4F91D4,
-    (SINT16)((SINT32)0xF60FAF37 >> 16), (SINT16)0xF60FAF37,
-
-    (SINT16)((SINT32)0x115B1ED2 >> 16), (SINT16)0x115B1ED2,
-    (SINT16)((SINT32)0x18F55C90 >> 16), (SINT16)0x18F55C90,
-    (SINT16)((SINT32)0x1F91CA46 >> 16), (SINT16)0x1F91CA46,
-    (SINT16)((SINT32)0x2412F251 >> 16), (SINT16)0x2412F251,
-    (SINT16)((SINT32)0x25AC1FF2 >> 16), (SINT16)0x25AC1FF2,
-    (SINT16)((SINT32)0x2412F251 >> 16), (SINT16)0x2412F251,
-    (SINT16)((SINT32)0x1F91CA46 >> 16), (SINT16)0x1F91CA46,
-    (SINT16)((SINT32)0x18F55C90 >> 16), (SINT16)0x18F55C90,
-
-    (SINT16)((SINT32)0xEEA4E12E >> 16), (SINT16)0xEEA4E12E,
-    (SINT16)((SINT32)0xF60FAF37 >> 16), (SINT16)0xF60FAF37,
-    (SINT16)((SINT32)0xFC4F91D4 >> 16), (SINT16)0xFC4F91D4,
-    (SINT16)((SINT32)0x00C8F2BC >> 16), (SINT16)0x00C8F2BC,
-    (SINT16)((SINT32)0x034FEE2C >> 16), (SINT16)0x034FEE2C,
-    (SINT16)((SINT32)0x041EEE40 >> 16), (SINT16)0x041EEE40,
-    (SINT16)((SINT32)0x03B23341 >> 16), (SINT16)0x03B23341,
-    (SINT16)((SINT32)0x029DBAA3 >> 16), (SINT16)0x029DBAA3,
-
-    (SINT16)((SINT32)0xFE9A60BB >> 16), (SINT16)0xFE9A60BB,
-    (SINT16)((SINT32)0xFF9BB9D5 >> 16), (SINT16)0xFF9BB9D5,
-    (SINT16)((SINT32)0x003D239B >> 16), (SINT16)0x003D239B,
-    (SINT16)((SINT32)0x007F88E4 >> 16), (SINT16)0x007F88E4,
-    (SINT16)((SINT32)0x007DBCC8 >> 16), (SINT16)0x007DBCC8,
-    (SINT16)((SINT32)0x00599403 >> 16), (SINT16)0x00599403,
-    (SINT16)((SINT32)0x0030E2D3 >> 16), (SINT16)0x0030E2D3,
-    (SINT16)((SINT32)0x001194E6 >> 16), (SINT16)0x001194E6
-};
-
-/*Window coeff for 8 sub band case*/
-const SINT16 gas32CoeffFor8SBs[] = {
-    (SINT16)((SINT32)0x00000000 >> 16), (SINT16)0x00000000,
-    (SINT16)((SINT32)0x00052173 >> 16), (SINT16)0x00052173,
-    (SINT16)((SINT32)0x000B3F71 >> 16), (SINT16)0x000B3F71,
-    (SINT16)((SINT32)0x00122C7D >> 16), (SINT16)0x00122C7D,
-    (SINT16)((SINT32)0x001AFF89 >> 16), (SINT16)0x001AFF89,
-    (SINT16)((SINT32)0x00255A62 >> 16), (SINT16)0x00255A62,
-    (SINT16)((SINT32)0x003060F4 >> 16), (SINT16)0x003060F4,
-    (SINT16)((SINT32)0x003A72E7 >> 16), (SINT16)0x003A72E7,
-
-    (SINT16)((SINT32)0x0041EC6A >> 16), (SINT16)0x0041EC6A, /* 8 */
-    (SINT16)((SINT32)0x0044EF48 >> 16), (SINT16)0x0044EF48,
-    (SINT16)((SINT32)0x00415B75 >> 16), (SINT16)0x00415B75,
-    (SINT16)((SINT32)0x0034F8B6 >> 16), (SINT16)0x0034F8B6,
-    (SINT16)((SINT32)0x001D8FD2 >> 16), (SINT16)0x001D8FD2,
-    (SINT16)((SINT32)0xFFFA2413 >> 16), (SINT16)0xFFFA2413,
-    (SINT16)((SINT32)0xFFC9F10E >> 16), (SINT16)0xFFC9F10E,
-    (SINT16)((SINT32)0xFF8D6793 >> 16), (SINT16)0xFF8D6793,
-
-    (SINT16)((SINT32)0x00B97348 >> 16), (SINT16)0x00B97348, /* 16 */
-    (SINT16)((SINT32)0x01071B96 >> 16), (SINT16)0x01071B96,
-    (SINT16)((SINT32)0x0156B3CA >> 16), (SINT16)0x0156B3CA,
-    (SINT16)((SINT32)0x01A1B38B >> 16), (SINT16)0x01A1B38B,
-    (SINT16)((SINT32)0x01E0224C >> 16), (SINT16)0x01E0224C,
-    (SINT16)((SINT32)0x0209291F >> 16), (SINT16)0x0209291F,
-    (SINT16)((SINT32)0x02138653 >> 16), (SINT16)0x02138653,
-    (SINT16)((SINT32)0x01F5F424 >> 16), (SINT16)0x01F5F424,
-
-    (SINT16)((SINT32)0x01A7ECEF >> 16), (SINT16)0x01A7ECEF, /* 24 */
-    (SINT16)((SINT32)0x01223EBA >> 16), (SINT16)0x01223EBA,
-    (SINT16)((SINT32)0x005FD0FF >> 16), (SINT16)0x005FD0FF,
-    (SINT16)((SINT32)0xFF5EEB73 >> 16), (SINT16)0xFF5EEB73,
-    (SINT16)((SINT32)0xFE20435D >> 16), (SINT16)0xFE20435D,
-    (SINT16)((SINT32)0xFCA86E7E >> 16), (SINT16)0xFCA86E7E,
-    (SINT16)((SINT32)0xFAFF95FC >> 16), (SINT16)0xFAFF95FC,
-    (SINT16)((SINT32)0xF9312891 >> 16), (SINT16)0xF9312891,
-
-    (SINT16)((SINT32)0x08B4307A >> 16), (SINT16)0x08B4307A, /* 32 */
-    (SINT16)((SINT32)0x0A9F3E9A >> 16), (SINT16)0x0A9F3E9A,
-    (SINT16)((SINT32)0x0C7D59B6 >> 16), (SINT16)0x0C7D59B6,
-    (SINT16)((SINT32)0x0E3BB16F >> 16), (SINT16)0x0E3BB16F,
-    (SINT16)((SINT32)0x0FC721F9 >> 16), (SINT16)0x0FC721F9,
-    (SINT16)((SINT32)0x110ECEF0 >> 16), (SINT16)0x110ECEF0,
-    (SINT16)((SINT32)0x120435FA >> 16), (SINT16)0x120435FA,
-    (SINT16)((SINT32)0x129C226F >> 16), (SINT16)0x129C226F,
-
-    (SINT16)((SINT32)0x12CF6C75 >> 16), (SINT16)0x12CF6C75, /* 40 */
-    (SINT16)((SINT32)0x129C226F >> 16), (SINT16)0x129C226F,
-    (SINT16)((SINT32)0x120435FA >> 16), (SINT16)0x120435FA,
-    (SINT16)((SINT32)0x110ECEF0 >> 16), (SINT16)0x110ECEF0,
-    (SINT16)((SINT32)0x0FC721F9 >> 16), (SINT16)0x0FC721F9,
-    (SINT16)((SINT32)0x0E3BB16F >> 16), (SINT16)0x0E3BB16F,
-    (SINT16)((SINT32)0x0C7D59B6 >> 16), (SINT16)0x0C7D59B6,
-    (SINT16)((SINT32)0x0A9F3E9A >> 16), (SINT16)0x0A9F3E9A,
-
-    (SINT16)((SINT32)0xF74BCF86 >> 16), (SINT16)0xF74BCF86, /* 48 */
-    (SINT16)((SINT32)0xF9312891 >> 16), (SINT16)0xF9312891,
-    (SINT16)((SINT32)0xFAFF95FC >> 16), (SINT16)0xFAFF95FC,
-    (SINT16)((SINT32)0xFCA86E7E >> 16), (SINT16)0xFCA86E7E,
-    (SINT16)((SINT32)0xFE20435D >> 16), (SINT16)0xFE20435D,
-    (SINT16)((SINT32)0xFF5EEB73 >> 16), (SINT16)0xFF5EEB73,
-    (SINT16)((SINT32)0x005FD0FF >> 16), (SINT16)0x005FD0FF,
-    (SINT16)((SINT32)0x01223EBA >> 16), (SINT16)0x01223EBA,
-
-    (SINT16)((SINT32)0x01A7ECEF >> 16), (SINT16)0x01A7ECEF, /* 56 */
-    (SINT16)((SINT32)0x01F5F424 >> 16), (SINT16)0x01F5F424,
-    (SINT16)((SINT32)0x02138653 >> 16), (SINT16)0x02138653,
-    (SINT16)((SINT32)0x0209291F >> 16), (SINT16)0x0209291F,
-    (SINT16)((SINT32)0x01E0224C >> 16), (SINT16)0x01E0224C,
-    (SINT16)((SINT32)0x01A1B38B >> 16), (SINT16)0x01A1B38B,
-    (SINT16)((SINT32)0x0156B3CA >> 16), (SINT16)0x0156B3CA,
-    (SINT16)((SINT32)0x01071B96 >> 16), (SINT16)0x01071B96,
-
-    (SINT16)((SINT32)0xFF468CB8 >> 16), (SINT16)0xFF468CB8, /* 64 */
-    (SINT16)((SINT32)0xFF8D6793 >> 16), (SINT16)0xFF8D6793,
-    (SINT16)((SINT32)0xFFC9F10E >> 16), (SINT16)0xFFC9F10E,
-    (SINT16)((SINT32)0xFFFA2413 >> 16), (SINT16)0xFFFA2413,
-    (SINT16)((SINT32)0x001D8FD2 >> 16), (SINT16)0x001D8FD2,
-    (SINT16)((SINT32)0x0034F8B6 >> 16), (SINT16)0x0034F8B6,
-    (SINT16)((SINT32)0x00415B75 >> 16), (SINT16)0x00415B75,
-    (SINT16)((SINT32)0x0044EF48 >> 16), (SINT16)0x0044EF48,
-
-    (SINT16)((SINT32)0x0041EC6A >> 16), (SINT16)0x0041EC6A, /* 72 */
-    (SINT16)((SINT32)0x003A72E7 >> 16), (SINT16)0x003A72E7,
-    (SINT16)((SINT32)0x003060F4 >> 16), (SINT16)0x003060F4,
-    (SINT16)((SINT32)0x00255A62 >> 16), (SINT16)0x00255A62,
-    (SINT16)((SINT32)0x001AFF89 >> 16), (SINT16)0x001AFF89,
-    (SINT16)((SINT32)0x00122C7D >> 16), (SINT16)0x00122C7D,
-    (SINT16)((SINT32)0x000B3F71 >> 16), (SINT16)0x000B3F71,
-    (SINT16)((SINT32)0x00052173 >> 16), (SINT16)0x00052173
-};
-
-#else
-
-/*Window coeff for 4 sub band case*/
-const SINT32 gas32CoeffFor4SBs[] = {
-    (SINT32)0x00000000,
-    (SINT32)0x001194E6,
-    (SINT32)0x0030E2D3,
-    (SINT32)0x00599403,
-    (SINT32)0x007DBCC8,
-    (SINT32)0x007F88E4,
-    (SINT32)0x003D239B,
-    (SINT32)0xFF9BB9D5,
-
-    (SINT32)0x01659F45,
-    (SINT32)0x029DBAA3,
-    (SINT32)0x03B23341,
-    (SINT32)0x041EEE40,
-    (SINT32)0x034FEE2C,
-    (SINT32)0x00C8F2BC,
-    (SINT32)0xFC4F91D4,
-    (SINT32)0xF60FAF37,
-
-    (SINT32)0x115B1ED2,
-    (SINT32)0x18F55C90,
-    (SINT32)0x1F91CA46,
-    (SINT32)0x2412F251,
-    (SINT32)0x25AC1FF2,
-    (SINT32)0x2412F251,
-    (SINT32)0x1F91CA46,
-    (SINT32)0x18F55C90,
-
-    (SINT32)0xEEA4E12E,
-    (SINT32)0xF60FAF37,
-    (SINT32)0xFC4F91D4,
-    (SINT32)0x00C8F2BC,
-    (SINT32)0x034FEE2C,
-    (SINT32)0x041EEE40,
-    (SINT32)0x03B23341,
-    (SINT32)0x029DBAA3,
-
-    (SINT32)0xFE9A60BB,
-    (SINT32)0xFF9BB9D5,
-    (SINT32)0x003D239B,
-    (SINT32)0x007F88E4,
-    (SINT32)0x007DBCC8,
-    (SINT32)0x00599403,
-    (SINT32)0x0030E2D3,
-    (SINT32)0x001194E6
-};
-
-/*Window coeff for 8 sub band case*/
-const SINT32 gas32CoeffFor8SBs[] = {
-    (SINT32)0x00000000,
-    (SINT32)0x00052173,
-    (SINT32)0x000B3F71,
-    (SINT32)0x00122C7D,
-    (SINT32)0x001AFF89,
-    (SINT32)0x00255A62,
-    (SINT32)0x003060F4,
-    (SINT32)0x003A72E7,
-
-    (SINT32)0x0041EC6A, /* 8 */
-    (SINT32)0x0044EF48,
-    (SINT32)0x00415B75,
-    (SINT32)0x0034F8B6,
-    (SINT32)0x001D8FD2,
-    (SINT32)0xFFFA2413,
-    (SINT32)0xFFC9F10E,
-    (SINT32)0xFF8D6793,
-
-    (SINT32)0x00B97348, /* 16 */
-    (SINT32)0x01071B96,
-    (SINT32)0x0156B3CA,
-    (SINT32)0x01A1B38B,
-    (SINT32)0x01E0224C,
-    (SINT32)0x0209291F,
-    (SINT32)0x02138653,
-    (SINT32)0x01F5F424,
-
-    (SINT32)0x01A7ECEF, /* 24 */
-    (SINT32)0x01223EBA,
-    (SINT32)0x005FD0FF,
-    (SINT32)0xFF5EEB73,
-    (SINT32)0xFE20435D,
-    (SINT32)0xFCA86E7E,
-    (SINT32)0xFAFF95FC,
-    (SINT32)0xF9312891,
-
-    (SINT32)0x08B4307A, /* 32 */
-    (SINT32)0x0A9F3E9A,
-    (SINT32)0x0C7D59B6,
-    (SINT32)0x0E3BB16F,
-    (SINT32)0x0FC721F9,
-    (SINT32)0x110ECEF0,
-    (SINT32)0x120435FA,
-    (SINT32)0x129C226F,
-
-    (SINT32)0x12CF6C75, /* 40 */
-    (SINT32)0x129C226F,
-    (SINT32)0x120435FA,
-    (SINT32)0x110ECEF0,
-    (SINT32)0x0FC721F9,
-    (SINT32)0x0E3BB16F,
-    (SINT32)0x0C7D59B6,
-    (SINT32)0x0A9F3E9A,
-
-    (SINT32)0xF74BCF86, /* 48 */
-    (SINT32)0xF9312891,
-    (SINT32)0xFAFF95FC,
-    (SINT32)0xFCA86E7E,
-    (SINT32)0xFE20435D,
-    (SINT32)0xFF5EEB73,
-    (SINT32)0x005FD0FF,
-    (SINT32)0x01223EBA,
-
-    (SINT32)0x01A7ECEF, /* 56 */
-    (SINT32)0x01F5F424,
-    (SINT32)0x02138653,
-    (SINT32)0x0209291F,
-    (SINT32)0x01E0224C,
-    (SINT32)0x01A1B38B,
-    (SINT32)0x0156B3CA,
-    (SINT32)0x01071B96,
-
-    (SINT32)0xFF468CB8, /* 64 */
-    (SINT32)0xFF8D6793,
-    (SINT32)0xFFC9F10E,
-    (SINT32)0xFFFA2413,
-    (SINT32)0x001D8FD2,
-    (SINT32)0x0034F8B6,
-    (SINT32)0x00415B75,
-    (SINT32)0x0044EF48,
-
-    (SINT32)0x0041EC6A, /* 72 */
-    (SINT32)0x003A72E7,
-    (SINT32)0x003060F4,
-    (SINT32)0x00255A62,
-    (SINT32)0x001AFF89,
-    (SINT32)0x00122C7D,
-    (SINT32)0x000B3F71,
-    (SINT32)0x00052173
-};
-
-#endif
-#endif
-
-#endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_func_declare.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_func_declare.h
deleted file mode 100644
index 1635b81a3..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_enc_func_declare.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Function declarations.
- *
- ******************************************************************************/
-
-#ifndef SBC_FUNCDECLARE_H
-#define SBC_FUNCDECLARE_H
-
-/*#include "sbc_encoder.h"*/
-/* Global data */
-#if (SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE)
-extern const SINT16 gas32CoeffFor4SBs[];
-extern const SINT16 gas32CoeffFor8SBs[];
-#else
-extern const SINT32 gas32CoeffFor4SBs[];
-extern const SINT32 gas32CoeffFor8SBs[];
-#endif
-
-/* Global functions*/
-
-extern void sbc_enc_bit_alloc_mono(SBC_ENC_PARAMS *CodecParams);
-extern void sbc_enc_bit_alloc_ste(SBC_ENC_PARAMS *CodecParams);
-
-extern void SbcAnalysisInit(void);
-
-extern void SbcAnalysisFilter4(SBC_ENC_PARAMS *strEncParams);
-extern void SbcAnalysisFilter8(SBC_ENC_PARAMS *strEncParams);
-
-extern void SBC_FastIDCT8(SINT32 *pInVect, SINT32 *pOutVect);
-extern void SBC_FastIDCT4(SINT32 *x0, SINT32 *pOutVect);
-
-extern void EncPacking(SBC_ENC_PARAMS *strEncParams);
-extern void EncQuantizer(SBC_ENC_PARAMS *);
-#if (SBC_DSP_OPT == TRUE)
-SINT32 SBC_Multiply_32_16_Simplified(SINT32 s32In2Temp, SINT32 s32In1Temp);
-#endif
-#endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c
deleted file mode 100644
index bcfdfa456..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.c
+++ /dev/null
@@ -1,321 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  contains code for encoder flow and initalization of encoder
- *
- ******************************************************************************/
-
-#include 
-#include 
-#include "sbc_encoder.h"
-#include "sbc_enc_func_declare.h"
-
-#if defined(SBC_ENC_INCLUDED)
-
-SINT16 EncMaxShiftCounter;
-
-#if (SBC_JOINT_STE_INCLUDED == TRUE)
-SINT32 s32LRDiff[SBC_MAX_NUM_OF_BLOCKS] = { 0 };
-SINT32 s32LRSum[SBC_MAX_NUM_OF_BLOCKS] = { 0 };
-#endif
-
-void SBC_Encoder(SBC_ENC_PARAMS *pstrEncParams)
-{
-    SINT32 s32Ch;                /* counter for ch*/
-    SINT32 s32Sb;                /* counter for sub-band*/
-    UINT32 u32Count, maxBit = 0; /* loop count*/
-    SINT32 s32MaxValue;          /* temp variable to store max value */
-
-    SINT16 *ps16ScfL;
-    SINT32 *SbBuffer;
-    SINT32 s32Blk; /* counter for block*/
-    SINT32 s32NumOfBlocks = pstrEncParams->s16NumOfBlocks;
-#if (SBC_JOINT_STE_INCLUDED == TRUE)
-    SINT32 s32MaxValue2;
-    UINT32 u32CountSum, u32CountDiff;
-    SINT32 *pSum, *pDiff;
-#endif
-    register SINT32 s32NumOfSubBands = pstrEncParams->s16NumOfSubBands;
-
-    pstrEncParams->pu8NextPacket = pstrEncParams->pu8Packet;
-
-#if (SBC_NO_PCM_CPY_OPTION == TRUE)
-    pstrEncParams->ps16NextPcmBuffer = pstrEncParams->ps16PcmBuffer;
-#else
-    pstrEncParams->ps16NextPcmBuffer = pstrEncParams->as16PcmBuffer;
-#endif
-    do {
-        /* SBC ananlysis filter*/
-        if (s32NumOfSubBands == 4) {
-            SbcAnalysisFilter4(pstrEncParams);
-        } else {
-            SbcAnalysisFilter8(pstrEncParams);
-        }
-
-        /* compute the scale factor, and save the max */
-        ps16ScfL = pstrEncParams->as16ScaleFactor;
-        s32Ch = pstrEncParams->s16NumOfChannels * s32NumOfSubBands;
-
-        pstrEncParams->ps16NextPcmBuffer += s32Ch * s32NumOfBlocks; /* in case of multible sbc frame to encode update the pcm pointer */
-
-        for (s32Sb = 0; s32Sb < s32Ch; s32Sb++) {
-            SbBuffer = pstrEncParams->s32SbBuffer + s32Sb;
-            s32MaxValue = 0;
-            for (s32Blk = s32NumOfBlocks; s32Blk > 0; s32Blk--) {
-                if (s32MaxValue < abs32(*SbBuffer)) {
-                    s32MaxValue = abs32(*SbBuffer);
-                }
-                SbBuffer += s32Ch;
-            }
-
-            u32Count = (s32MaxValue > 0x800000) ? 9 : 0;
-
-            for (; u32Count < 15; u32Count++) {
-                if (s32MaxValue <= (SINT32)(0x8000 << u32Count)) {
-                    break;
-                }
-            }
-            *ps16ScfL++ = (SINT16)u32Count;
-
-            if (u32Count > maxBit) {
-                maxBit = u32Count;
-            }
-        }
-        /* In case of JS processing,check whether to use JS */
-#if (SBC_JOINT_STE_INCLUDED == TRUE)
-        if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) {
-            /* Calculate sum and differance  scale factors for making JS decision   */
-            ps16ScfL = pstrEncParams->as16ScaleFactor;
-            /* calculate the scale factor of Joint stereo max sum and diff */
-            for (s32Sb = 0; s32Sb < s32NumOfSubBands - 1; s32Sb++) {
-                SbBuffer = pstrEncParams->s32SbBuffer + s32Sb;
-                s32MaxValue2 = 0;
-                s32MaxValue = 0;
-                pSum = s32LRSum;
-                pDiff = s32LRDiff;
-                for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
-                    *pSum = (*SbBuffer + *(SbBuffer + s32NumOfSubBands)) >> 1;
-                    if (abs32(*pSum) > s32MaxValue) {
-                        s32MaxValue = abs32(*pSum);
-                    }
-                    pSum++;
-                    *pDiff = (*SbBuffer - *(SbBuffer + s32NumOfSubBands)) >> 1;
-                    if (abs32(*pDiff) > s32MaxValue2) {
-                        s32MaxValue2 = abs32(*pDiff);
-                    }
-                    pDiff++;
-                    SbBuffer += s32Ch;
-                }
-                u32Count = (s32MaxValue > 0x800000) ? 9 : 0;
-                for (; u32Count < 15; u32Count++) {
-                    if (s32MaxValue <= (SINT32)(0x8000 << u32Count)) {
-                        break;
-                    }
-                }
-                u32CountSum = u32Count;
-                u32Count = (s32MaxValue2 > 0x800000) ? 9 : 0;
-                for (; u32Count < 15; u32Count++) {
-                    if (s32MaxValue2 <= (SINT32)(0x8000 << u32Count)) {
-                        break;
-                    }
-                }
-                u32CountDiff = u32Count;
-                if ((*ps16ScfL + *(ps16ScfL + s32NumOfSubBands)) > (SINT16)(u32CountSum + u32CountDiff)) {
-                    if (u32CountSum > maxBit) {
-                        maxBit = u32CountSum;
-                    }
-
-                    if (u32CountDiff > maxBit) {
-                        maxBit = u32CountDiff;
-                    }
-
-                    *ps16ScfL = (SINT16)u32CountSum;
-                    *(ps16ScfL + s32NumOfSubBands) = (SINT16)u32CountDiff;
-
-                    SbBuffer = pstrEncParams->s32SbBuffer + s32Sb;
-                    pSum = s32LRSum;
-                    pDiff = s32LRDiff;
-
-                    for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) {
-                        *SbBuffer = *pSum;
-                        *(SbBuffer + s32NumOfSubBands) = *pDiff;
-
-                        SbBuffer += s32NumOfSubBands << 1;
-                        pSum++;
-                        pDiff++;
-                    }
-
-                    pstrEncParams->as16Join[s32Sb] = 1;
-                } else {
-                    pstrEncParams->as16Join[s32Sb] = 0;
-                }
-                ps16ScfL++;
-            }
-            pstrEncParams->as16Join[s32Sb] = 0;
-        }
-#endif
-
-        pstrEncParams->s16MaxBitNeed = (SINT16)maxBit;
-
-        /* bit allocation */
-        if ((pstrEncParams->s16ChannelMode == SBC_STEREO) || (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO)) {
-            sbc_enc_bit_alloc_ste(pstrEncParams);
-        } else {
-            sbc_enc_bit_alloc_mono(pstrEncParams);
-        }
-
-        /* Quantize the encoded audio */
-        EncPacking(pstrEncParams);
-    } while (--(pstrEncParams->u8NumPacketToEncode));
-
-    pstrEncParams->u8NumPacketToEncode = 1; /* default is one for retrocompatibility purpose */
-}
-
-/****************************************************************************
-* InitSbcAnalysisFilt - Initalizes the input data to 0
-*
-* RETURNS : N/A
-*/
-void SBC_Encoder_Init(SBC_ENC_PARAMS *pstrEncParams)
-{
-    UINT16 s16SamplingFreq; /*temp variable to store smpling freq*/
-    SINT16 s16Bitpool;      /*to store bit pool value*/
-    SINT16 s16BitRate;      /*to store bitrate*/
-    SINT16 s16FrameLen;     /*to store frame length*/
-    UINT16 HeaderParams;
-
-    pstrEncParams->u8NumPacketToEncode = 1; /* default is one for retrocompatibility purpose */
-
-    if (pstrEncParams->sbc_mode != SBC_MODE_MSBC) {
-        /* Required number of channels */
-        if (pstrEncParams->s16ChannelMode == SBC_MONO) {
-            pstrEncParams->s16NumOfChannels = 1;
-        } else {
-            pstrEncParams->s16NumOfChannels = 2;
-        }
-
-        /* Bit pool calculation */
-        if (pstrEncParams->s16SamplingFreq == SBC_sf16000) {
-            s16SamplingFreq = 16000;
-        } else if (pstrEncParams->s16SamplingFreq == SBC_sf32000) {
-            s16SamplingFreq = 32000;
-        } else if (pstrEncParams->s16SamplingFreq == SBC_sf44100) {
-            s16SamplingFreq = 44100;
-        } else {
-            s16SamplingFreq = 48000;
-        }
-
-        if ((pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) || (pstrEncParams->s16ChannelMode == SBC_STEREO)) {
-            s16Bitpool = (SINT16)((pstrEncParams->u16BitRate *
-                                   pstrEncParams->s16NumOfSubBands * 1000 / s16SamplingFreq) -
-                                  ((32 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) + ((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands)) / pstrEncParams->s16NumOfBlocks));
-
-            s16FrameLen = 4 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) / 8 + (((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands) + (pstrEncParams->s16NumOfBlocks * s16Bitpool)) / 8;
-
-            s16BitRate = (8 * s16FrameLen * s16SamplingFreq) / (pstrEncParams->s16NumOfSubBands *
-                                                                pstrEncParams->s16NumOfBlocks * 1000);
-
-            if (s16BitRate > pstrEncParams->u16BitRate) {
-                s16Bitpool--;
-            }
-
-            if (pstrEncParams->s16NumOfSubBands == 8) {
-                pstrEncParams->s16BitPool = (s16Bitpool > 255) ? 255 : s16Bitpool;
-            } else {
-                pstrEncParams->s16BitPool = (s16Bitpool > 128) ? 128 : s16Bitpool;
-            }
-        } else {
-            s16Bitpool = (SINT16)(((pstrEncParams->s16NumOfSubBands *
-                                    pstrEncParams->u16BitRate * 1000) /
-                                   (s16SamplingFreq * pstrEncParams->s16NumOfChannels)) -
-                                  (((32 / pstrEncParams->s16NumOfChannels) +
-                                    (4 * pstrEncParams->s16NumOfSubBands)) /
-                                   pstrEncParams->s16NumOfBlocks));
-
-            pstrEncParams->s16BitPool = (s16Bitpool >
-                                         (16 * pstrEncParams->s16NumOfSubBands)) ?
-                                            (16 * pstrEncParams->s16NumOfSubBands) :
-                                            s16Bitpool;
-        }
-
-        if (pstrEncParams->s16BitPool < 0) {
-            pstrEncParams->s16BitPool = 0;
-        }
-        /* sampling freq */
-        HeaderParams = ((pstrEncParams->s16SamplingFreq & 3) << 6);
-
-        /* number of blocks*/
-        HeaderParams |= (((pstrEncParams->s16NumOfBlocks - 4) & 12) << 2);
-
-        /* channel mode: mono, dual...*/
-        HeaderParams |= ((pstrEncParams->s16ChannelMode & 3) << 2);
-
-        /* Loudness or SNR */
-        HeaderParams |= ((pstrEncParams->s16AllocationMethod & 1) << 1);
-        HeaderParams |= ((pstrEncParams->s16NumOfSubBands >> 3) & 1); /*4 or 8*/
-
-        pstrEncParams->FrameHeader = HeaderParams;
-    } else {
-        // mSBC
-
-        // Use mSBC encoding parameters to reset the control field
-        /* Required number of channels: 1 */
-        pstrEncParams->s16ChannelMode = SBC_MONO;
-        pstrEncParams->s16NumOfChannels = 1;
-
-        /* Required Sampling frequency : 16KHz */
-        pstrEncParams->s16SamplingFreq = SBC_sf16000;
-
-        /* Bit pool value: 26 */
-        pstrEncParams->s16BitPool = 26;
-
-        /* number of subbands: 8 */
-        pstrEncParams->s16NumOfSubBands = 8;
-
-        /* number of blocks: 15 */
-        pstrEncParams->s16NumOfBlocks = 15;
-
-        /* allocation method: loudness */
-        pstrEncParams->s16AllocationMethod = SBC_LOUDNESS;
-
-        /* set the header paramers, unused for mSBC */
-        pstrEncParams->FrameHeader = 0;
-    }
-
-    if (pstrEncParams->s16NumOfSubBands == 4) {
-        if (pstrEncParams->s16NumOfChannels == 1) {
-            EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 4 * 10) >> 2) << 2;
-        } else {
-            EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 4 * 10 * 2) >> 3) << 2;
-        }
-    } else {
-        if (pstrEncParams->s16NumOfChannels == 1) {
-            EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 8 * 10) >> 3) << 3;
-        } else {
-            EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 8 * 10 * 2) >> 4) << 3;
-        }
-    }
-
-    BT_WARN("SBC_Encoder_Init : bitrate %d, bitpool %d\n", pstrEncParams->u16BitRate, pstrEncParams->s16BitPool);
-
-    SbcAnalysisInit();
-}
-
-#endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.h
deleted file mode 100644
index d706c3495..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_encoder.h
+++ /dev/null
@@ -1,207 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains constants and structures used by Encoder.
- *
- ******************************************************************************/
-
-#ifndef SBC_ENCODER_H
-#define SBC_ENCODER_H
-
-#define ENCODER_VERSION "0025"
-
-#ifdef BUILDCFG
-#include "common/bt_target.h"
-#endif
-
-/*DEFINES*/
-#ifndef FALSE
-#define FALSE 0
-#endif
-
-#ifndef TRUE
-#define TRUE (!FALSE)
-#endif
-
-#define SBC_MAX_NUM_OF_SUBBANDS 8
-#define SBC_MAX_NUM_OF_CHANNELS 2
-#define SBC_MAX_NUM_OF_BLOCKS   16
-
-#define SBC_LOUDNESS 0
-#define SBC_SNR      1
-
-#define SUB_BANDS_8 8
-#define SUB_BANDS_4 4
-
-#define SBC_sf16000 0
-#define SBC_sf32000 1
-#define SBC_sf44100 2
-#define SBC_sf48000 3
-
-#define SBC_MONO         0
-#define SBC_DUAL         1
-#define SBC_STEREO       2
-#define SBC_JOINT_STEREO 3
-
-#define SBC_BLOCK_0 4
-#define SBC_BLOCK_1 8
-#define SBC_BLOCK_2 12
-#define SBC_BLOCK_3 16
-
-#define SBC_NULL 0
-
-#define SBC_MODE_STD  0
-#define SBC_MODE_MSBC 1
-
-#define SBC_SYNC_WORD_STD  (0x9C)
-#define SBC_SYNC_WORD_MSBC (0xAD)
-
-#ifndef SBC_MAX_NUM_FRAME
-#define SBC_MAX_NUM_FRAME 1
-#endif
-
-#ifndef SBC_DSP_OPT
-#define SBC_DSP_OPT FALSE
-#endif
-
-/* Set SBC_USE_ARM_PRAGMA to TRUE to use "#pragma arm section zidata" */
-#ifndef SBC_USE_ARM_PRAGMA
-#define SBC_USE_ARM_PRAGMA FALSE
-#endif
-
-/* Set SBC_ARM_ASM_OPT to TRUE in case the target is an ARM */
-/* this will replace all the 32 and 64 bit mult by in line assembly code */
-#ifndef SBC_ARM_ASM_OPT
-#define SBC_ARM_ASM_OPT FALSE
-#endif
-
-/* green hill compiler option -> Used to distinguish the syntax for inline assembly code*/
-#ifndef SBC_GHS_COMPILER
-#define SBC_GHS_COMPILER FALSE
-#endif
-
-/* ARM compiler option -> Used to distinguish the syntax for inline assembly code */
-#ifndef SBC_ARM_COMPILER
-#define SBC_ARM_COMPILER TRUE
-#endif
-
-/* Set SBC_IPAQ_OPT to TRUE in case the target is an ARM */
-/* 32 and 64 bit mult will be performed using SINT64 ( usualy __int64 ) cast that usualy give optimal performance if supported */
-#ifndef SBC_IPAQ_OPT
-#define SBC_IPAQ_OPT TRUE
-#endif
-
-/* Debug only: set SBC_IS_64_MULT_IN_WINDOW_ACCU to TRUE to use 64 bit multiplication in the windowing */
-/* -> not recomended, more MIPS for the same restitution.  */
-#ifndef SBC_IS_64_MULT_IN_WINDOW_ACCU
-#define SBC_IS_64_MULT_IN_WINDOW_ACCU FALSE
-#endif /*SBC_IS_64_MULT_IN_WINDOW_ACCU */
-
-/* Set SBC_IS_64_MULT_IN_IDCT to TRUE to use 64 bits multiplication in the DCT of Matrixing */
-/* -> more MIPS required for a better audio quality. comparasion with the SIG utilities shows a division by 10 of the RMS */
-/* CAUTION: It only apply in the if SBC_FAST_DCT is set to TRUE */
-#ifndef SBC_IS_64_MULT_IN_IDCT
-#define SBC_IS_64_MULT_IN_IDCT FALSE
-#endif /*SBC_IS_64_MULT_IN_IDCT */
-
-/* set SBC_IS_64_MULT_IN_QUANTIZER to TRUE to use 64 bits multiplication in the quantizer */
-/* setting this flag to FALSE add whistling noise at 5.5 and 11 KHz usualy not perceptible by human's hears. */
-#ifndef SBC_IS_64_MULT_IN_QUANTIZER
-#define SBC_IS_64_MULT_IN_QUANTIZER TRUE
-#endif /*SBC_IS_64_MULT_IN_IDCT */
-
-/* Debug only: set this flag to FALSE to disable fast DCT algorithm */
-#ifndef SBC_FAST_DCT
-#define SBC_FAST_DCT TRUE
-#endif /*SBC_FAST_DCT */
-
-/* In case we do not use joint stereo mode the flag save some RAM and ROM in case it is set to FALSE */
-#ifndef SBC_JOINT_STE_INCLUDED
-#define SBC_JOINT_STE_INCLUDED TRUE
-#endif
-
-/* TRUE -> application should provide PCM buffer, FALSE PCM buffer reside in SBC_ENC_PARAMS */
-#ifndef SBC_NO_PCM_CPY_OPTION
-#define SBC_NO_PCM_CPY_OPTION FALSE
-#endif
-
-#define MINIMUM_ENC_VX_BUFFER_SIZE (8 * 10 * 2)
-#ifndef ENC_VX_BUFFER_SIZE
-#define ENC_VX_BUFFER_SIZE (MINIMUM_ENC_VX_BUFFER_SIZE + 64)
-/*#define ENC_VX_BUFFER_SIZE MINIMUM_ENC_VX_BUFFER_SIZE + 1024*/
-#endif
-
-#ifndef SBC_FOR_EMBEDDED_LINUX
-#define SBC_FOR_EMBEDDED_LINUX FALSE
-#endif
-
-/*constants used for index calculation*/
-#define SBC_BLK (SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS)
-
-#include "sbc_types.h"
-
-typedef struct SBC_ENC_PARAMS_TAG {
-    SINT16 s16SamplingFreq;  /* 16k, 32k, 44.1k or 48k*/
-    SINT16 s16ChannelMode;   /* mono, dual, streo or joint streo*/
-    SINT16 s16NumOfSubBands; /* 4 or 8 */
-    SINT16 s16NumOfChannels;
-    SINT16 s16NumOfBlocks;      /* 4, 8, 12 or 16*/
-    SINT16 s16AllocationMethod; /* loudness or SNR*/
-    SINT16 s16BitPool;          /* 16*numOfSb for mono & dual;
-                                                       32*numOfSb for stereo & joint stereo */
-    UINT16 u16BitRate;
-    UINT8 sbc_mode;            /* SBC_MODE_STD or SBC_MODE_MSBC */
-    UINT8 u8NumPacketToEncode; /* number of sbc frame to encode. Default is 1 */
-#if (SBC_JOINT_STE_INCLUDED == TRUE)
-    SINT16 as16Join[SBC_MAX_NUM_OF_SUBBANDS]; /*1 if JS, 0 otherwise*/
-#endif
-
-    SINT16 s16MaxBitNeed;
-    SINT16 as16ScaleFactor[SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS];
-
-    SINT16 *ps16NextPcmBuffer;
-#if (SBC_NO_PCM_CPY_OPTION == TRUE)
-    SINT16 *ps16PcmBuffer;
-#else
-    SINT16 as16PcmBuffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS * SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS];
-#endif
-
-    SINT16 s16ScartchMemForBitAlloc[16];
-
-    SINT32 s32SbBuffer[SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS * SBC_MAX_NUM_OF_BLOCKS];
-
-    SINT16 as16Bits[SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS];
-
-    UINT8 *pu8Packet;
-    UINT8 *pu8NextPacket;
-    UINT16 FrameHeader;
-    UINT16 u16PacketLength;
-
-} SBC_ENC_PARAMS;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-extern void SBC_Encoder(SBC_ENC_PARAMS *strEncParams);
-extern void SBC_Encoder_Init(SBC_ENC_PARAMS *strEncParams);
-#ifdef __cplusplus
-}
-#endif
-#endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c
deleted file mode 100644
index 36adea762..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_packing.c
+++ /dev/null
@@ -1,262 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  This file contains code for packing the Encoded data into bit streams.
- *
- ******************************************************************************/
-
-#include "sbc_encoder.h"
-#include "sbc_enc_func_declare.h"
-
-#if defined(SBC_ENC_INCLUDED)
-
-#if (SBC_ARM_ASM_OPT == TRUE)
-#define Mult32(s32In1, s32In2, s32OutLow)                                                            \
-    {                                                                                                \
-        __asm {                                                                                    \
-        MUL s32OutLow,s32In1,s32In2; \
-        }                                                                                            \
-    }
-#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi)                                                 \
-    {                                                                                               \
-        __asm {                                                                                   \
-        SMULL s32OutLow,s32OutHi,s32In1,s32In2 \
-        }                                                                                           \
-    }
-#else
-#define Mult32(s32In1, s32In2, s32OutLow) s32OutLow = (SINT32)s32In1 * (SINT32)s32In2;
-#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi)              \
-    {                                                            \
-        s32OutLow = ((SINT32)(UINT16)s32In1 * (UINT16)s32In2);   \
-        s32TempVal2 = (SINT32)((s32In1 >> 16) * (UINT16)s32In2); \
-        s32Carry = ((((UINT32)(s32OutLow) >> 16) & 0xFFFF) +     \
-                    +(s32TempVal2 & 0xFFFF)) >>                  \
-                   16;                                           \
-        s32OutLow += (s32TempVal2 << 16);                        \
-        s32OutHi = (s32TempVal2 >> 16) + s32Carry;               \
-    }
-#endif
-
-void EncPacking(SBC_ENC_PARAMS *pstrEncParams)
-{
-    UINT8 *pu8PacketPtr; /* packet ptr*/
-    UINT8 Temp;
-    SINT32 s32Blk;        /* counter for block*/
-    SINT32 s32Ch;         /* counter for channel*/
-    SINT32 s32Sb;         /* counter for sub-band*/
-    SINT32 s32PresentBit; /* represents bit to be stored*/
-    /*SINT32 s32LoopCountI;                       loop counter*/
-    SINT32 s32LoopCountJ;                             /* loop counter*/
-    UINT32 u32QuantizedSbValue, u32QuantizedSbValue0; /* temp variable to store quantized sb val*/
-    SINT32 s32LoopCount;                              /* loop counter*/
-    UINT8 u8XoredVal;                                 /* to store XORed value in CRC calculation*/
-    UINT8 u8CRC;                                      /* to store CRC value*/
-    SINT16 *ps16GenPtr;
-    SINT32 s32NumOfBlocks;
-    SINT32 s32NumOfSubBands = pstrEncParams->s16NumOfSubBands;
-    SINT32 s32NumOfChannels = pstrEncParams->s16NumOfChannels;
-    UINT32 u32SfRaisedToPow2; /*scale factor raised to power 2*/
-    SINT16 *ps16ScfPtr;
-    SINT32 *ps32SbPtr;
-    UINT16 u16Levels; /*to store levels*/
-    SINT32 s32Temp1;  /*used in 64-bit multiplication*/
-    SINT32 s32Low;    /*used in 64-bit multiplication*/
-#if (SBC_IS_64_MULT_IN_QUANTIZER == TRUE)
-    SINT32 s32Hi1, s32Low1, s32Carry, s32TempVal2, s32Hi, s32Temp2;
-#endif
-
-    pu8PacketPtr = pstrEncParams->pu8NextPacket; /*Initialize the ptr*/
-    if (pstrEncParams->sbc_mode != SBC_MODE_MSBC) {
-        *pu8PacketPtr++ = (UINT8)SBC_SYNC_WORD_STD; /*Sync word*/
-        *pu8PacketPtr++ = (UINT8)(pstrEncParams->FrameHeader);
-
-        *pu8PacketPtr = (UINT8)(pstrEncParams->s16BitPool & 0x00FF);
-    } else {
-        *pu8PacketPtr++ = (UINT8)SBC_SYNC_WORD_MSBC; /*Sync word*/
-        // two reserved bytes
-        *pu8PacketPtr++ = 0;
-        *pu8PacketPtr = 0;
-    }
-    pu8PacketPtr += 2; /*skip for CRC*/
-
-    /*here it indicate if it is byte boundary or nibble boundary*/
-    s32PresentBit = 8;
-    Temp = 0;
-#if (SBC_JOINT_STE_INCLUDED == TRUE)
-    if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) {
-        /* pack join stero parameters */
-        for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) {
-            Temp <<= 1;
-            Temp |= pstrEncParams->as16Join[s32Sb];
-        }
-
-        /* pack RFA */
-        if (s32NumOfSubBands == SUB_BANDS_4) {
-            s32PresentBit = 4;
-        } else {
-            *(pu8PacketPtr++) = Temp;
-            Temp = 0;
-        }
-    }
-#endif
-
-    /* Pack Scale factor */
-    ps16GenPtr = pstrEncParams->as16ScaleFactor;
-    s32Sb = s32NumOfChannels * s32NumOfSubBands;
-    /*Temp=*pu8PacketPtr;*/
-    for (s32Ch = s32Sb; s32Ch > 0; s32Ch--) {
-        Temp <<= 4;
-        Temp |= *ps16GenPtr++;
-
-        if (s32PresentBit == 4) {
-            s32PresentBit = 8;
-            *(pu8PacketPtr++) = Temp;
-            Temp = 0;
-        } else {
-            s32PresentBit = 4;
-        }
-    }
-
-    /* Pack samples */
-    ps32SbPtr = pstrEncParams->s32SbBuffer;
-    /*Temp=*pu8PacketPtr;*/
-    s32NumOfBlocks = pstrEncParams->s16NumOfBlocks;
-    for (s32Blk = s32NumOfBlocks - 1; s32Blk >= 0; s32Blk--) {
-        ps16GenPtr = pstrEncParams->as16Bits;
-        ps16ScfPtr = pstrEncParams->as16ScaleFactor;
-        for (s32Ch = s32Sb - 1; s32Ch >= 0; s32Ch--) {
-            s32LoopCount = *ps16GenPtr++;
-            if (s32LoopCount != 0) {
-#if (SBC_IS_64_MULT_IN_QUANTIZER == TRUE)
-                /* finding level from reconstruction part of decoder */
-                u32SfRaisedToPow2 = ((UINT32)1 << ((*ps16ScfPtr) + 1));
-                u16Levels = (UINT16)(((UINT32)1 << s32LoopCount) - 1);
-
-                /* quantizer */
-                s32Temp1 = (*ps32SbPtr >> 2) + (u32SfRaisedToPow2 << 12);
-                s32Temp2 = u16Levels;
-
-                Mult64(s32Temp1, s32Temp2, s32Low, s32Hi);
-
-                s32Low1 = s32Low >> ((*ps16ScfPtr) + 2);
-                s32Low1 &= ((UINT32)1 << (32 - ((*ps16ScfPtr) + 2))) - 1;
-                s32Hi1 = s32Hi << (32 - ((*ps16ScfPtr) + 2));
-
-                u32QuantizedSbValue0 = (UINT16)((s32Low1 | s32Hi1) >> 12);
-#else
-                /* finding level from reconstruction part of decoder */
-                u32SfRaisedToPow2 = ((UINT32)1 << *ps16ScfPtr);
-                u16Levels = (UINT16)(((UINT32)1 << s32LoopCount) - 1);
-
-                /* quantizer */
-                s32Temp1 = (*ps32SbPtr >> 15) + u32SfRaisedToPow2;
-                Mult32(s32Temp1, u16Levels, s32Low);
-                s32Low >>= (*ps16ScfPtr + 1);
-                u32QuantizedSbValue0 = (UINT16)s32Low;
-#endif
-                /*store the number of bits required and the quantized s32Sb
-                sample to ease the coding*/
-                u32QuantizedSbValue = u32QuantizedSbValue0;
-
-                if (s32PresentBit >= s32LoopCount) {
-                    Temp <<= s32LoopCount;
-                    Temp |= u32QuantizedSbValue;
-                    s32PresentBit -= s32LoopCount;
-                } else {
-                    while (s32PresentBit < s32LoopCount) {
-                        s32LoopCount -= s32PresentBit;
-                        u32QuantizedSbValue >>= s32LoopCount;
-
-                        /*remove the unwanted msbs*/
-                        /*u32QuantizedSbValue <<= 16 - s32PresentBit;
-                        u32QuantizedSbValue >>= 16 - s32PresentBit;*/
-
-                        Temp <<= s32PresentBit;
-
-                        Temp |= u32QuantizedSbValue;
-                        /*restore the original*/
-                        u32QuantizedSbValue = u32QuantizedSbValue0;
-
-                        *(pu8PacketPtr++) = Temp;
-                        Temp = 0;
-                        s32PresentBit = 8;
-                    }
-                    Temp <<= s32LoopCount;
-
-                    /* remove the unwanted msbs */
-                    /*u32QuantizedSbValue <<= 16 - s32LoopCount;
-                    u32QuantizedSbValue >>= 16 - s32LoopCount;*/
-
-                    Temp |= u32QuantizedSbValue;
-
-                    s32PresentBit -= s32LoopCount;
-                }
-            }
-            ps16ScfPtr++;
-            ps32SbPtr++;
-        }
-    }
-
-    Temp <<= s32PresentBit;
-    *pu8PacketPtr = Temp;
-    pstrEncParams->u16PacketLength = pu8PacketPtr - pstrEncParams->pu8NextPacket + 1;
-    /*find CRC*/
-    pu8PacketPtr = pstrEncParams->pu8NextPacket + 1; /*Initialize the ptr*/
-    u8CRC = 0x0F;
-    s32LoopCount = s32Sb >> 1;
-
-    /*
-    The loops is run from the start of the packet till the scale factor
-    parameters. In case of JS, 'join' parameter is included in the packet
-    so that many more bytes are included in CRC calculation.
-    */
-    Temp = *pu8PacketPtr;
-    for (s32Ch = 1; s32Ch < (s32LoopCount + 4); s32Ch++) {
-        /* skip sync word and CRC bytes */
-        if (s32Ch != 3) {
-            for (s32LoopCountJ = 7; s32LoopCountJ >= 0; s32LoopCountJ--) {
-                u8XoredVal = ((u8CRC >> 7) & 0x01) ^ ((Temp >> s32LoopCountJ) & 0x01);
-                u8CRC <<= 1;
-                u8CRC ^= (u8XoredVal * 0x1D);
-                u8CRC &= 0xFF;
-            }
-        }
-        Temp = *(++pu8PacketPtr);
-    }
-
-    if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) {
-        for (s32LoopCountJ = 7; s32LoopCountJ >= (8 - s32NumOfSubBands); s32LoopCountJ--) {
-            u8XoredVal = ((u8CRC >> 7) & 0x01) ^ ((Temp >> s32LoopCountJ) & 0x01);
-            u8CRC <<= 1;
-            u8CRC ^= (u8XoredVal * 0x1D);
-            u8CRC &= 0xFF;
-        }
-    }
-
-    /* CRC calculation ends here */
-
-    /* store CRC in packet */
-    pu8PacketPtr = pstrEncParams->pu8NextPacket; /*Initialize the ptr*/
-    pu8PacketPtr += 3;
-    *pu8PacketPtr = u8CRC;
-    pstrEncParams->pu8NextPacket += pstrEncParams->u16PacketLength; /* move the pointer to the end in case there is more than one frame to encode */
-}
-
-#endif /* #if defined(SBC_ENC_INCLUDED) */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_types.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_types.h
deleted file mode 100644
index 82eed4368..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/sbc/enc/sbc_types.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/******************************************************************************
- *
- *  Copyright (C) 1999-2012 Broadcom Corporation
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at:
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- ******************************************************************************/
-
-/******************************************************************************
- *
- *  Data type declarations.
- *
- ******************************************************************************/
-
-#ifndef SBC_TYPES_H
-#define SBC_TYPES_H
-
-#include 
-
-typedef uint8_t UINT8;
-typedef uint16_t UINT16;
-typedef uint32_t UINT32;
-typedef uint64_t UINT64;
-typedef short SINT16;
-typedef long SINT32;
-
-#if (SBC_IPAQ_OPT == TRUE)
-
-#if (SBC_FOR_EMBEDDED_LINUX == TRUE)
-typedef long long SINT64;
-#else
-typedef int64_t SINT64;
-#endif
-
-#elif (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE) || (SBC_IS_64_MULT_IN_IDCT == TRUE)
-
-#if (SBC_FOR_EMBEDDED_LINUX == TRUE)
-typedef long long SINT64;
-#else
-typedef int64_t SINT64;
-#endif
-
-#endif
-
-#define abs32(x) ((x >= 0) ? x : (-x))
-
-#endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/bas.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/bas.c
index f4b34c022..851b40324 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/bas.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/bas.c
@@ -13,11 +13,11 @@
 #include 
 #include 
 
+#include "bas.h"
 #include "bluetooth.h"
 #include "conn.h"
 #include "gatt.h"
 #include "uuid.h"
-#include "bas.h"
 
 #if !defined(BFLB_BLE)
 #define LOG_LEVEL CONFIG_BT_GATT_BAS_LOG_LEVEL
@@ -27,64 +27,47 @@ LOG_MODULE_REGISTER(bas);
 
 static u8_t battery_level = 100U;
 
-static void blvl_ccc_cfg_changed(const struct bt_gatt_attr *attr,
-                                 u16_t value)
-{
-    ARG_UNUSED(attr);
+static void blvl_ccc_cfg_changed(const struct bt_gatt_attr *attr, u16_t value) {
+  ARG_UNUSED(attr);
 
-    bool notif_enabled = (value == BT_GATT_CCC_NOTIFY);
+  bool notif_enabled = (value == BT_GATT_CCC_NOTIFY);
 
 #if !defined(BFLB_BLE)
-    LOG_INF("BAS Notifications %s", notif_enabled ? "enabled" : "disabled");
+  LOG_INF("BAS Notifications %s", notif_enabled ? "enabled" : "disabled");
 #endif
 }
 
-static ssize_t read_blvl(struct bt_conn *conn,
-                         const struct bt_gatt_attr *attr, void *buf,
-                         u16_t len, u16_t offset)
-{
-    u8_t lvl8 = battery_level;
+static ssize_t read_blvl(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  u8_t lvl8 = battery_level;
 
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &lvl8,
-                             sizeof(lvl8));
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &lvl8, sizeof(lvl8));
 }
 
 static struct bt_gatt_attr attrs[] = {
     BT_GATT_PRIMARY_SERVICE(BT_UUID_BAS),
-    BT_GATT_CHARACTERISTIC(BT_UUID_BAS_BATTERY_LEVEL,
-                           BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,
-                           BT_GATT_PERM_READ, read_blvl, NULL,
-                           &battery_level),
+    BT_GATT_CHARACTERISTIC(BT_UUID_BAS_BATTERY_LEVEL, BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, BT_GATT_PERM_READ, read_blvl, NULL, &battery_level),
     BT_GATT_CCC(blvl_ccc_cfg_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
-    BT_GATT_DESCRIPTOR(BT_UUID_HIDS_REPORT_REF, BT_GATT_PERM_READ,
-                       NULL, NULL, NULL),
+    BT_GATT_DESCRIPTOR(BT_UUID_HIDS_REPORT_REF, BT_GATT_PERM_READ, NULL, NULL, NULL),
 };
 
 struct bt_gatt_service bas = BT_GATT_SERVICE(attrs);
 
-void bas_init(void)
-{
-    bt_gatt_service_register(&bas);
-}
+void bas_init(void) { bt_gatt_service_register(&bas); }
 
-u8_t bt_gatt_bas_get_battery_level(void)
-{
-    return battery_level;
-}
+u8_t bt_gatt_bas_get_battery_level(void) { return battery_level; }
 
-int bt_gatt_bas_set_battery_level(u8_t level)
-{
-    int rc;
+int bt_gatt_bas_set_battery_level(u8_t level) {
+  int rc;
 
-    if (level > 100U) {
-        return -EINVAL;
-    }
+  if (level > 100U) {
+    return -EINVAL;
+  }
 
-    battery_level = level;
+  battery_level = level;
 
-    rc = bt_gatt_notify(NULL, &bas.attrs[1], &level, sizeof(level));
+  rc = bt_gatt_notify(NULL, &bas.attrs[1], &level, sizeof(level));
 
-    return rc == -ENOTCONN ? 0 : rc;
+  return rc == -ENOTCONN ? 0 : rc;
 }
 
 #if !defined(BFLB_BLE)
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/dis.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/dis.c
index 3e6e99035..521249201 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/dis.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/dis.c
@@ -10,20 +10,20 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-#include 
+#include 
 #include 
 #include 
-#include 
 #include 
+#include 
 
 #include "settings.h"
 
 #include "bluetooth.h"
-#include "hci_host.h"
 #include "conn.h"
-#include "uuid.h"
-#include "gatt.h"
 #include "dis.h"
+#include "gatt.h"
+#include "hci_host.h"
+#include "uuid.h"
 
 #if !defined(BFLB_BLE)
 #define BT_DBG_ENABLED  IS_ENABLED(CONFIG_BT_DEBUG_SERVICE)
@@ -33,10 +33,10 @@
 
 #if CONFIG_BT_GATT_DIS_PNP
 struct dis_pnp {
-    u8_t pnp_vid_src;
-    u16_t pnp_vid;
-    u16_t pnp_pid;
-    u16_t pnp_ver;
+  u8_t  pnp_vid_src;
+  u16_t pnp_vid;
+  u16_t pnp_pid;
+  u16_t pnp_ver;
 } __packed;
 
 #if defined(BFLB_BLE)
@@ -61,9 +61,9 @@ struct dis_pnp {
 
 static struct dis_pnp dis_pnp_id = {
     .pnp_vid_src = DIS_PNP_VID_SRC,
-    .pnp_vid = CONFIG_BT_GATT_DIS_PNP_VID,
-    .pnp_pid = CONFIG_BT_GATT_DIS_PNP_PID,
-    .pnp_ver = CONFIG_BT_GATT_DIS_PNP_VER,
+    .pnp_vid     = CONFIG_BT_GATT_DIS_PNP_VID,
+    .pnp_pid     = CONFIG_BT_GATT_DIS_PNP_PID,
+    .pnp_ver     = CONFIG_BT_GATT_DIS_PNP_VER,
 };
 #endif
 
@@ -71,20 +71,16 @@ static struct dis_pnp dis_pnp_id = {
 static u8_t dis_model[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_MODEL;
 static u8_t dis_manuf[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_MANUF;
 #if defined(CONFIG_BT_GATT_DIS_SERIAL_NUMBER)
-static u8_t dis_serial_number[CONFIG_BT_GATT_DIS_STR_MAX] =
-    CONFIG_BT_GATT_DIS_SERIAL_NUMBER_STR;
+static u8_t dis_serial_number[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_SERIAL_NUMBER_STR;
 #endif
 #if defined(CONFIG_BT_GATT_DIS_FW_REV)
-static u8_t dis_fw_rev[CONFIG_BT_GATT_DIS_STR_MAX] =
-    CONFIG_BT_GATT_DIS_FW_REV_STR;
+static u8_t dis_fw_rev[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_FW_REV_STR;
 #endif
 #if defined(CONFIG_BT_GATT_DIS_HW_REV)
-static u8_t dis_hw_rev[CONFIG_BT_GATT_DIS_STR_MAX] =
-    CONFIG_BT_GATT_DIS_HW_REV_STR;
+static u8_t dis_hw_rev[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_HW_REV_STR;
 #endif
 #if defined(CONFIG_BT_GATT_DIS_SW_REV)
-static u8_t dis_sw_rev[CONFIG_BT_GATT_DIS_STR_MAX] =
-    CONFIG_BT_GATT_DIS_SW_REV_STR;
+static u8_t dis_sw_rev[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_SW_REV_STR;
 #endif
 
 #define BT_GATT_DIS_MODEL_REF             dis_model
@@ -105,21 +101,13 @@ static u8_t dis_sw_rev[CONFIG_BT_GATT_DIS_STR_MAX] =
 
 #endif /* CONFIG_BT_GATT_DIS_SETTINGS */
 
-static ssize_t read_str(struct bt_conn *conn,
-                        const struct bt_gatt_attr *attr, void *buf,
-                        u16_t len, u16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data,
-                             strlen(attr->user_data));
+static ssize_t read_str(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data, strlen(attr->user_data));
 }
 
 #if CONFIG_BT_GATT_DIS_PNP
-static ssize_t read_pnp_id(struct bt_conn *conn,
-                           const struct bt_gatt_attr *attr, void *buf,
-                           u16_t len, u16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, &dis_pnp_id,
-                             sizeof(dis_pnp_id));
+static ssize_t read_pnp_id(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) {
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, &dis_pnp_id, sizeof(dis_pnp_id));
 }
 #endif
 
@@ -128,149 +116,130 @@ static struct bt_gatt_attr attrs[] = {
 
     BT_GATT_PRIMARY_SERVICE(BT_UUID_DIS),
 
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MODEL_NUMBER,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL, BT_GATT_DIS_MODEL_REF),
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MANUFACTURER_NAME,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL, BT_GATT_DIS_MANUF_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MODEL_NUMBER, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_MODEL_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MANUFACTURER_NAME, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_MANUF_REF),
 #if CONFIG_BT_GATT_DIS_PNP
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_PNP_ID,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_pnp_id, NULL, &dis_pnp_id),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_PNP_ID, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_pnp_id, NULL, &dis_pnp_id),
 #endif
 
 #if defined(CONFIG_BT_GATT_DIS_SERIAL_NUMBER)
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SERIAL_NUMBER,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL,
-                           BT_GATT_DIS_SERIAL_NUMBER_STR_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SERIAL_NUMBER, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_SERIAL_NUMBER_STR_REF),
 #endif
 #if defined(CONFIG_BT_GATT_DIS_FW_REV)
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_FIRMWARE_REVISION,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL, BT_GATT_DIS_FW_REV_STR_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_FIRMWARE_REVISION, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_FW_REV_STR_REF),
 #endif
 #if defined(CONFIG_BT_GATT_DIS_HW_REV)
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_HARDWARE_REVISION,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL, BT_GATT_DIS_HW_REV_STR_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_HARDWARE_REVISION, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_HW_REV_STR_REF),
 #endif
 #if defined(CONFIG_BT_GATT_DIS_SW_REV)
-    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SOFTWARE_REVISION,
-                           BT_GATT_CHRC_READ, BT_GATT_PERM_READ,
-                           read_str, NULL, BT_GATT_DIS_SW_REV_STR_REF),
+    BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SOFTWARE_REVISION, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_str, NULL, BT_GATT_DIS_SW_REV_STR_REF),
 #endif
 
 };
 
 static struct bt_gatt_service dis_svc = BT_GATT_SERVICE(attrs);
 
-void dis_init(u8_t vid_src, u16_t vid, u16_t pid, u16_t pid_ver)
-{
-    dis_pnp_id.pnp_vid_src = vid_src;
-    dis_pnp_id.pnp_vid = vid;
-    dis_pnp_id.pnp_pid = pid;
-    dis_pnp_id.pnp_ver = pid_ver;
-    bt_gatt_service_register(&dis_svc);
+void dis_init(u8_t vid_src, u16_t vid, u16_t pid, u16_t pid_ver) {
+  dis_pnp_id.pnp_vid_src = vid_src;
+  dis_pnp_id.pnp_vid     = vid;
+  dis_pnp_id.pnp_pid     = pid;
+  dis_pnp_id.pnp_ver     = pid_ver;
+  bt_gatt_service_register(&dis_svc);
 }
 
 #if defined(CONFIG_BT_SETTINGS) && defined(CONFIG_BT_GATT_DIS_SETTINGS)
-static int dis_set(const char *name, size_t len_rd,
-                   settings_read_cb read_cb, void *store)
-{
-    int len, nlen;
-    const char *next;
-
-    nlen = settings_name_next(name, &next);
-    if (!strncmp(name, "manuf", nlen)) {
-        len = read_cb(store, &dis_manuf, sizeof(dis_manuf) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read manufacturer from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_manuf[len] = '\0';
-
-            BT_DBG("Manufacturer set to %s", dis_manuf);
-        }
-        return 0;
+static int dis_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *store) {
+  int         len, nlen;
+  const char *next;
+
+  nlen = settings_name_next(name, &next);
+  if (!strncmp(name, "manuf", nlen)) {
+    len = read_cb(store, &dis_manuf, sizeof(dis_manuf) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read manufacturer from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_manuf[len] = '\0';
+
+      BT_DBG("Manufacturer set to %s", dis_manuf);
     }
-    if (!strncmp(name, "model", nlen)) {
-        len = read_cb(store, &dis_model, sizeof(dis_model) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read model from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_model[len] = '\0';
-
-            BT_DBG("Model set to %s", dis_model);
-        }
-        return 0;
+    return 0;
+  }
+  if (!strncmp(name, "model", nlen)) {
+    len = read_cb(store, &dis_model, sizeof(dis_model) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read model from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_model[len] = '\0';
+
+      BT_DBG("Model set to %s", dis_model);
     }
+    return 0;
+  }
 #if defined(CONFIG_BT_GATT_DIS_SERIAL_NUMBER)
-    if (!strncmp(name, "serial", nlen)) {
-        len = read_cb(store, &dis_serial_number,
-                      sizeof(dis_serial_number) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read serial number from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_serial_number[len] = '\0';
-
-            BT_DBG("Serial number set to %s", dis_serial_number);
-        }
-        return 0;
+  if (!strncmp(name, "serial", nlen)) {
+    len = read_cb(store, &dis_serial_number, sizeof(dis_serial_number) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read serial number from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_serial_number[len] = '\0';
+
+      BT_DBG("Serial number set to %s", dis_serial_number);
     }
+    return 0;
+  }
 #endif
 #if defined(CONFIG_BT_GATT_DIS_FW_REV)
-    if (!strncmp(name, "fw", nlen)) {
-        len = read_cb(store, &dis_fw_rev, sizeof(dis_fw_rev) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read firmware revision from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_fw_rev[len] = '\0';
-
-            BT_DBG("Firmware revision set to %s", dis_fw_rev);
-        }
-        return 0;
+  if (!strncmp(name, "fw", nlen)) {
+    len = read_cb(store, &dis_fw_rev, sizeof(dis_fw_rev) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read firmware revision from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_fw_rev[len] = '\0';
+
+      BT_DBG("Firmware revision set to %s", dis_fw_rev);
     }
+    return 0;
+  }
 #endif
 #if defined(CONFIG_BT_GATT_DIS_HW_REV)
-    if (!strncmp(name, "hw", nlen)) {
-        len = read_cb(store, &dis_hw_rev, sizeof(dis_hw_rev) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read hardware revision from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_hw_rev[len] = '\0';
-
-            BT_DBG("Hardware revision set to %s", dis_hw_rev);
-        }
-        return 0;
+  if (!strncmp(name, "hw", nlen)) {
+    len = read_cb(store, &dis_hw_rev, sizeof(dis_hw_rev) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read hardware revision from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_hw_rev[len] = '\0';
+
+      BT_DBG("Hardware revision set to %s", dis_hw_rev);
     }
+    return 0;
+  }
 #endif
 #if defined(CONFIG_BT_GATT_DIS_SW_REV)
-    if (!strncmp(name, "sw", nlen)) {
-        len = read_cb(store, &dis_sw_rev, sizeof(dis_sw_rev) - 1);
-        if (len < 0) {
-            BT_ERR("Failed to read software revision from storage"
-                   " (err %d)",
-                   len);
-        } else {
-            dis_sw_rev[len] = '\0';
-
-            BT_DBG("Software revision set to %s", dis_sw_rev);
-        }
-        return 0;
+  if (!strncmp(name, "sw", nlen)) {
+    len = read_cb(store, &dis_sw_rev, sizeof(dis_sw_rev) - 1);
+    if (len < 0) {
+      BT_ERR("Failed to read software revision from storage"
+             " (err %d)",
+             len);
+    } else {
+      dis_sw_rev[len] = '\0';
+
+      BT_DBG("Software revision set to %s", dis_sw_rev);
     }
-#endif
     return 0;
+  }
+#endif
+  return 0;
 }
 
 SETTINGS_STATIC_HANDLER_DEFINE(bt_dis, "bt/dis", NULL, dis_set, NULL, NULL);
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c
index 14f3c9729..98e00f249 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/hog.c
@@ -9,49 +9,51 @@
  */
 
 #include 
+
+#include 
+#include 
 #include 
 #include 
-#include 
-#include 
 #include 
 
+#include "log.h"
 #include 
 #include 
-#include 
 #include 
+#include 
+
 #include "hog.h"
-#include "log.h"
 
 enum {
-    HIDS_REMOTE_WAKE = BIT(0),
-    HIDS_NORMALLY_CONNECTABLE = BIT(1),
+  HIDS_REMOTE_WAKE          = BIT(0),
+  HIDS_NORMALLY_CONNECTABLE = BIT(1),
 };
 
 struct hids_info {
-    uint16_t version; /* version number of base USB HID Specification */
-    uint8_t code;     /* country HID Device hardware is localized for. */
-    uint8_t flags;
+  uint16_t version; /* version number of base USB HID Specification */
+  uint8_t  code;    /* country HID Device hardware is localized for. */
+  uint8_t  flags;
 } __packed;
 
 struct hids_report {
-    uint8_t id;   /* report id */
-    uint8_t type; /* report type */
+  uint8_t id;   /* report id */
+  uint8_t type; /* report type */
 } __packed;
 
 static struct hids_info info = {
     .version = 0x0000,
-    .code = 0x00,
-    .flags = HIDS_NORMALLY_CONNECTABLE,
+    .code    = 0x00,
+    .flags   = HIDS_NORMALLY_CONNECTABLE,
 };
 
 enum {
-    HIDS_INPUT = 0x01,
-    HIDS_OUTPUT = 0x02,
-    HIDS_FEATURE = 0x03,
+  HIDS_INPUT   = 0x01,
+  HIDS_OUTPUT  = 0x02,
+  HIDS_FEATURE = 0x03,
 };
 
 static struct hids_report input = {
-    .id = 0x01,
+    .id   = 0x01,
     .type = HIDS_INPUT,
 };
 
@@ -86,127 +88,91 @@ static uint8_t report_map[] = {
     0xC0,       /* End Collection */
 };
 
-static ssize_t read_info(struct bt_conn *conn,
-                         const struct bt_gatt_attr *attr, void *buf,
-                         uint16_t len, uint16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data,
-                             sizeof(struct hids_info));
+static ssize_t read_info(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) {
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data, sizeof(struct hids_info));
 }
 
-static ssize_t read_report_map(struct bt_conn *conn,
-                               const struct bt_gatt_attr *attr, void *buf,
-                               uint16_t len, uint16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, report_map,
-                             sizeof(report_map));
+static ssize_t read_report_map(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) {
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, report_map, sizeof(report_map));
 }
 
-static ssize_t read_report(struct bt_conn *conn,
-                           const struct bt_gatt_attr *attr, void *buf,
-                           uint16_t len, uint16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data,
-                             sizeof(struct hids_report));
+static ssize_t read_report(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) {
+  return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data, sizeof(struct hids_report));
 }
 
-static void input_ccc_changed(const struct bt_gatt_attr *attr, uint16_t value)
-{
-    simulate_input = (value == BT_GATT_CCC_NOTIFY) ? 1 : 0;
-    BT_WARN("simulate_input = [%d]\r\n", simulate_input);
+static void input_ccc_changed(const struct bt_gatt_attr *attr, uint16_t value) {
+  simulate_input = (value == BT_GATT_CCC_NOTIFY) ? 1 : 0;
+  BT_WARN("simulate_input = [%d]\r\n", simulate_input);
 }
 
-static ssize_t read_input_report(struct bt_conn *conn,
-                                 const struct bt_gatt_attr *attr, void *buf,
-                                 uint16_t len, uint16_t offset)
-{
-    return bt_gatt_attr_read(conn, attr, buf, len, offset, NULL, 0);
-}
+static ssize_t read_input_report(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) { return bt_gatt_attr_read(conn, attr, buf, len, offset, NULL, 0); }
 
-static ssize_t write_ctrl_point(struct bt_conn *conn,
-                                const struct bt_gatt_attr *attr,
-                                const void *buf, uint16_t len, uint16_t offset,
-                                uint8_t flags)
-{
-    uint8_t *value = attr->user_data;
+static ssize_t write_ctrl_point(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, uint16_t len, uint16_t offset, uint8_t flags) {
+  uint8_t *value = attr->user_data;
 
-    if (offset + len > sizeof(ctrl_point)) {
-        return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
-    }
+  if (offset + len > sizeof(ctrl_point)) {
+    return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
+  }
 
-    memcpy(value + offset, buf, len);
+  memcpy(value + offset, buf, len);
 
-    return len;
+  return len;
 }
 
 /* HID Service Declaration */
 static struct bt_gatt_attr attrs[] = {
     BT_GATT_PRIMARY_SERVICE(BT_UUID_HIDS),
-    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_INFO, BT_GATT_CHRC_READ,
-                           BT_GATT_PERM_READ, read_info, NULL, &info),
-    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_REPORT_MAP, BT_GATT_CHRC_READ,
-                           BT_GATT_PERM_READ, read_report_map, NULL, NULL),
-    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_REPORT,
-                           BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,
-                           BT_GATT_PERM_READ_AUTHEN,
-                           read_input_report, NULL, NULL),
-    BT_GATT_CCC(input_ccc_changed,
-                BT_GATT_PERM_READ_AUTHEN | BT_GATT_PERM_WRITE_AUTHEN),
-    BT_GATT_DESCRIPTOR(BT_UUID_HIDS_REPORT_REF, BT_GATT_PERM_READ,
-                       read_report, NULL, &input),
-    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_CTRL_POINT,
-                           BT_GATT_CHRC_WRITE_WITHOUT_RESP,
-                           BT_GATT_PERM_WRITE,
-                           NULL, write_ctrl_point, &ctrl_point),
+    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_INFO, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_info, NULL, &info),
+    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_REPORT_MAP, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, read_report_map, NULL, NULL),
+    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_REPORT, BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, BT_GATT_PERM_READ_AUTHEN, read_input_report, NULL, NULL),
+    BT_GATT_CCC(input_ccc_changed, BT_GATT_PERM_READ_AUTHEN | BT_GATT_PERM_WRITE_AUTHEN),
+    BT_GATT_DESCRIPTOR(BT_UUID_HIDS_REPORT_REF, BT_GATT_PERM_READ, read_report, NULL, &input),
+    BT_GATT_CHARACTERISTIC(BT_UUID_HIDS_CTRL_POINT, BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_WRITE, NULL, write_ctrl_point, &ctrl_point),
 };
 
 struct hids_remote_key {
-    u8_t hid_page;
-    u16_t hid_usage;
+  u8_t  hid_page;
+  u16_t hid_usage;
 } __packed;
 
 static struct hids_remote_key remote_kbd_map_tab[] = {
-    { HID_PAGE_KBD, Key_a_or_A2 },
-    { HID_PAGE_KBD, Key_b_or_B },
-    { HID_PAGE_KBD, Key_c_or_C },
+    {HID_PAGE_KBD, Key_a_or_A2},
+    {HID_PAGE_KBD,  Key_b_or_B},
+    {HID_PAGE_KBD,  Key_c_or_C},
 };
 
-int hog_notify(struct bt_conn *conn, uint16_t hid_usage, uint8_t press)
-{
-    struct bt_gatt_attr *attr;
-    struct hids_remote_key *remote_key = NULL;
-    u8_t len = 4, data[4];
-
-    for (int i = 0; i < (sizeof(remote_kbd_map_tab) / sizeof(remote_kbd_map_tab[0])); i++) {
-        if (remote_kbd_map_tab[i].hid_usage == hid_usage) {
-            remote_key = &remote_kbd_map_tab[i];
-            break;
-        }
+int hog_notify(struct bt_conn *conn, uint16_t hid_usage, uint8_t press) {
+  struct bt_gatt_attr    *attr;
+  struct hids_remote_key *remote_key = NULL;
+  u8_t                    len        = 4, data[4];
+
+  for (int i = 0; i < (sizeof(remote_kbd_map_tab) / sizeof(remote_kbd_map_tab[0])); i++) {
+    if (remote_kbd_map_tab[i].hid_usage == hid_usage) {
+      remote_key = &remote_kbd_map_tab[i];
+      break;
     }
+  }
 
-    if (!remote_key)
-        return EINVAL;
+  if (!remote_key)
+    return EINVAL;
 
-    if (remote_key->hid_page == HID_PAGE_KBD) {
-        attr = &attrs[BT_CHAR_BLE_HID_REPORT_ATTR_VAL_INDEX];
-        len = 3;
-    } else
-        return EINVAL;
+  if (remote_key->hid_page == HID_PAGE_KBD) {
+    attr = &attrs[BT_CHAR_BLE_HID_REPORT_ATTR_VAL_INDEX];
+    len  = 3;
+  } else
+    return EINVAL;
 
-    sys_put_le16(hid_usage, data);
-    data[2] = 0;
-    data[3] = 0;
+  sys_put_le16(hid_usage, data);
+  data[2] = 0;
+  data[3] = 0;
 
-    if (!press) {
-        memset(data, 0, len);
-    }
+  if (!press) {
+    memset(data, 0, len);
+  }
 
-    return bt_gatt_notify(conn, attr, data, len);
+  return bt_gatt_notify(conn, attr, data, len);
 }
 
 struct bt_gatt_service hog_srv = BT_GATT_SERVICE(attrs);
 
-void hog_init(void)
-{
-    bt_gatt_service_register(&hog_srv);
-}
+void hog_init(void) { bt_gatt_service_register(&hog_srv); }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c
index 67d4db3bc..ee8ef026a 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.c
@@ -11,64 +11,55 @@
  *
  ****************************************************************************************
  */
+#include "scps.h"
 #include "bluetooth.h"
+#include "byteorder.h"
 #include "gatt.h"
 #include "uuid.h"
-#include "scps.h"
-#include "byteorder.h"
 
 struct scan_intvl_win {
-    u16_t scan_intvl;
-    u16_t scan_win;
+  u16_t scan_intvl;
+  u16_t scan_win;
 } __packed;
 
 static struct scan_intvl_win intvl_win = {
     .scan_intvl = BT_GAP_SCAN_FAST_INTERVAL,
-    .scan_win = BT_GAP_SCAN_FAST_WINDOW,
+    .scan_win   = BT_GAP_SCAN_FAST_WINDOW,
 };
 
-static ssize_t scan_intvl_win_write(struct bt_conn *conn,
-                                    const struct bt_gatt_attr *attr, const void *buf,
-                                    u16_t len, u16_t offset, u8_t flags)
-{
-    const u8_t *data = buf;
-    intvl_win.scan_intvl = sys_get_le16(data);
-    data += 2;
-    intvl_win.scan_win = sys_get_le16(data);
+static ssize_t scan_intvl_win_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len, u16_t offset, u8_t flags) {
+  const u8_t *data     = buf;
+  intvl_win.scan_intvl = sys_get_le16(data);
+  data += 2;
+  intvl_win.scan_win = sys_get_le16(data);
 
-    return len;
+  return len;
 }
 
-static struct bt_gatt_attr attrs[] = {
-    BT_GATT_PRIMARY_SERVICE(BT_UUID_SCPS),
-    BT_GATT_CHARACTERISTIC(BT_UUID_SCPS_SCAN_INTVL_WIN,
-                           BT_GATT_CHRC_WRITE_WITHOUT_RESP,
-                           BT_GATT_PERM_NONE, NULL, NULL,
-                           &intvl_win)
-};
+static struct bt_gatt_attr attrs[] = {BT_GATT_PRIMARY_SERVICE(BT_UUID_SCPS),
+                                      BT_GATT_CHARACTERISTIC(BT_UUID_SCPS_SCAN_INTVL_WIN, BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_NONE, NULL, NULL, &intvl_win)};
 
 static struct bt_gatt_service scps = BT_GATT_SERVICE(attrs);
 
-bool scps_init(u16_t scan_intvl, u16_t scan_win)
-{
-    int err;
+bool scps_init(u16_t scan_intvl, u16_t scan_win) {
+  int err;
 
-    if (scan_intvl < 0x0004 || scan_intvl > 0x4000) {
-        return false;
-    }
+  if (scan_intvl < 0x0004 || scan_intvl > 0x4000) {
+    return false;
+  }
 
-    if (scan_win < 0x0004 || scan_win > 0x4000) {
-        return false;
-    }
+  if (scan_win < 0x0004 || scan_win > 0x4000) {
+    return false;
+  }
 
-    if (scan_win > scan_intvl) {
-        return false;
-    }
+  if (scan_win > scan_intvl) {
+    return false;
+  }
 
-    intvl_win.scan_intvl = scan_intvl;
-    intvl_win.scan_win = scan_win;
+  intvl_win.scan_intvl = scan_intvl;
+  intvl_win.scan_win   = scan_win;
 
-    err = bt_gatt_service_register(&scps);
+  err = bt_gatt_service_register(&scps);
 
-    return err ? false : true;
+  return err ? false : true;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.h
index ede76ec22..274304d49 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/services/scps.h
@@ -15,8 +15,8 @@
 extern "C" {
 #endif
 
+#include 
 #include 
-
 bool scps_init(u16_t scan_itvl, u16_t scan_win);
 
 #ifdef __cplusplus
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/blecontroller/ble_inc/ble_lib_api.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/blecontroller/ble_inc/ble_lib_api.h
index 2cf94f98f..0135b36a3 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/blecontroller/ble_inc/ble_lib_api.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/blecontroller/ble_inc/ble_lib_api.h
@@ -6,6 +6,9 @@
 
 void ble_controller_init(uint8_t task_priority);
 void ble_controller_deinit(void);
+#if !defined(CFG_FREERTOS) && !defined(CFG_AOS)
+void blecontroller_main(void);
+#endif
 #if defined(CFG_BT_RESET)
 void ble_controller_reset(void);
 #endif
@@ -69,6 +72,7 @@ int     le_rx_test_cmd_handler(uint16_t src_id, void *param, bool from_hci);
 int     le_tx_test_cmd_handler(uint16_t src_id, void *param, bool from_hci);
 int     le_test_end_cmd_handler(bool from_hci);
 uint8_t le_get_direct_test_type(void);
+void    le_test_mode_custom_aa(uint32_t access_code);
 
 #if defined(CONFIG_BLE_MFG_HCI_CMD)
 int reset_cmd_handler(void);
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/blecontroller/lib/README.md b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/blecontroller/lib/README.md
new file mode 100644
index 000000000..8abbe6ad0
--- /dev/null
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/blecontroller/lib/README.md
@@ -0,0 +1,10 @@
+# blecontroller lib information
+
+## BL702
+
+1. `libblecontroller_702_m0s0sp` BL702 support BLE scan feature and BLE PDS(power down sleep) feature.
+1. `libblecontroller_702_m0s1` 1 BLE connection is supported, BL702 can only be slave in this connection.
+1. `libblecontroller_702_m0s1p` Based on libblecontroller_702_m0s1, add BLE PDS(power down sleep) feature.
+1. `libblecontroller_702_m0s1s` Based on libblecontroller_702_m0s1, add BLE scan feature.
+1. `libblecontroller_702_m1s1` 1 BLE connection is supported, BL702 can be master or slave in this connection.
+1. `libblecontroller_702_m16s1` 16 BLE connections are suppprted, BL702 can be master or slave in each connection.
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/blecontroller/lib/libblecontroller_702_std.a b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/blecontroller/lib/libblecontroller_702_std.a
new file mode 100644
index 000000000..3902fdcbc
Binary files /dev/null and b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/blecontroller/lib/libblecontroller_702_std.a differ
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c
index 36ec15144..365edb3cf 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/freertos/portable/gcc/risc-v/bl702/port.c
@@ -31,8 +31,8 @@
 
 /* Scheduler includes. */
 #include "FreeRTOS.h"
-#include "task.h"
 #include "portmacro.h"
+#include "task.h"
 
 #ifndef configCLINT_BASE_ADDRESS
 #warning configCLINT_BASE_ADDRESS must be defined in FreeRTOSConfig.h.  If the target chip includes a Core Local Interrupter (CLINT) then set configCLINT_BASE_ADDRESS to the CLINT base address.  Otherwise set configCLINT_BASE_ADDRESS to 0.
@@ -55,11 +55,11 @@ of the stack used by main.  Using the linker script method will repurpose the
 stack that was used by main before the scheduler was started for use as the
 interrupt stack after the scheduler has started. */
 #ifdef configISR_STACK_SIZE_WORDS
-static __attribute__((aligned(16))) StackType_t xISRStack[configISR_STACK_SIZE_WORDS] = { 0 };
-const StackType_t xISRStackTop = (StackType_t) & (xISRStack[configISR_STACK_SIZE_WORDS & ~portBYTE_ALIGNMENT_MASK]);
+static __attribute__((aligned(16))) StackType_t xISRStack[configISR_STACK_SIZE_WORDS] = {0};
+const StackType_t                               xISRStackTop                          = (StackType_t) & (xISRStack[configISR_STACK_SIZE_WORDS & ~portBYTE_ALIGNMENT_MASK]);
 #else
 extern const uint32_t __freertos_irq_stack_top[];
-const StackType_t xISRStackTop = (StackType_t)__freertos_irq_stack_top;
+const StackType_t     xISRStackTop = (StackType_t)__freertos_irq_stack_top;
 #endif
 
 /*
@@ -72,13 +72,13 @@ void vPortSetupTimerInterrupt(void) __attribute__((weak));
 /*-----------------------------------------------------------*/
 
 /* Used to program the machine timer compare register. */
-uint64_t ullNextTime = 0ULL;
-const uint64_t *pullNextTime = &ullNextTime;
-const size_t uxTimerIncrementsForOneTick = (size_t)(configCPU_CLOCK_HZ / configTICK_RATE_HZ); /* Assumes increment won't go over 32-bits. */
+uint64_t                 ullNextTime                         = 0ULL;
+const uint64_t          *pullNextTime                        = &ullNextTime;
+const size_t             uxTimerIncrementsForOneTick         = (size_t)(configCPU_CLOCK_HZ / configTICK_RATE_HZ); /* Assumes increment won't go over 32-bits. */
 volatile uint64_t *const pullMachineTimerCompareRegisterBase = (volatile uint64_t *const)(configCLINT_BASE_ADDRESS + 0x4000);
-volatile uint64_t *pullMachineTimerCompareRegister = 0;
-BaseType_t TrapNetCounter = 0;
-const BaseType_t *pTrapNetCounter = &TrapNetCounter;
+volatile uint64_t       *pullMachineTimerCompareRegister     = 0;
+BaseType_t               TrapNetCounter                      = 0;
+const BaseType_t        *pTrapNetCounter                     = &TrapNetCounter;
 
 /* Set configCHECK_FOR_STACK_OVERFLOW to 3 to add ISR stack checking to task
 stack checking.  A problem in the ISR stack will trigger an assert, not call the
@@ -91,13 +91,10 @@ the task stacks, and so will legitimately appear in many positions within
 the ISR stack. */
 #define portISR_STACK_FILL_BYTE 0xee
 
-static const uint8_t ucExpectedStackBytes[] = {
-    portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
-    portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
-    portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
-    portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
-    portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE
-};
+static const uint8_t ucExpectedStackBytes[] = {portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
+                                               portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
+                                               portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,
+                                               portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE};
 
 #define portCHECK_ISR_STACK() configASSERT((memcmp((void *)xISRStack, (void *)ucExpectedStackBytes, sizeof(ucExpectedStackBytes)) == 0))
 #else
@@ -109,87 +106,82 @@ static const uint8_t ucExpectedStackBytes[] = {
 
 #if (configCLINT_BASE_ADDRESS != 0)
 
-void vPortSetupTimerInterrupt(void)
-{
-    uint32_t ulCurrentTimeHigh, ulCurrentTimeLow;
-    volatile uint32_t *const pulTimeHigh = (volatile uint32_t *const)(configCLINT_BASE_ADDRESS + 0xBFFC);
-    volatile uint32_t *const pulTimeLow = (volatile uint32_t *const)(configCLINT_BASE_ADDRESS + 0xBFF8);
-    volatile uint32_t ulHartId = 0;
-
-    __asm volatile("csrr %0, mhartid"
-                   : "=r"(ulHartId));
-    pullMachineTimerCompareRegister = &(pullMachineTimerCompareRegisterBase[ulHartId]);
-
-    do {
-        ulCurrentTimeHigh = *pulTimeHigh;
-        ulCurrentTimeLow = *pulTimeLow;
-    } while (ulCurrentTimeHigh != *pulTimeHigh);
-
-    ullNextTime = (uint64_t)ulCurrentTimeHigh;
-    ullNextTime <<= 32ULL;
-    ullNextTime |= (uint64_t)ulCurrentTimeLow;
-    ullNextTime += (uint64_t)uxTimerIncrementsForOneTick;
-    *pullMachineTimerCompareRegister = ullNextTime;
-
-    /* Prepare the time to use after the next tick interrupt. */
-    ullNextTime += (uint64_t)uxTimerIncrementsForOneTick;
+void vPortSetupTimerInterrupt(void) {
+  uint32_t                 ulCurrentTimeHigh, ulCurrentTimeLow;
+  volatile uint32_t *const pulTimeHigh = (volatile uint32_t *const)(configCLINT_BASE_ADDRESS + 0xBFFC);
+  volatile uint32_t *const pulTimeLow  = (volatile uint32_t *const)(configCLINT_BASE_ADDRESS + 0xBFF8);
+  volatile uint32_t        ulHartId    = 0;
+
+  __asm volatile("csrr %0, mhartid" : "=r"(ulHartId));
+  pullMachineTimerCompareRegister = &(pullMachineTimerCompareRegisterBase[ulHartId]);
+
+  do {
+    ulCurrentTimeHigh = *pulTimeHigh;
+    ulCurrentTimeLow  = *pulTimeLow;
+  } while (ulCurrentTimeHigh != *pulTimeHigh);
+
+  ullNextTime = (uint64_t)ulCurrentTimeHigh;
+  ullNextTime <<= 32ULL;
+  ullNextTime |= (uint64_t)ulCurrentTimeLow;
+  ullNextTime += (uint64_t)uxTimerIncrementsForOneTick;
+  *pullMachineTimerCompareRegister = ullNextTime;
+
+  /* Prepare the time to use after the next tick interrupt. */
+  ullNextTime += (uint64_t)uxTimerIncrementsForOneTick;
 }
 
 #endif /* ( configCLINT_BASE_ADDRESS != 0 ) */
 /*-----------------------------------------------------------*/
 
-BaseType_t xPortStartScheduler(void)
-{
-    extern void xPortStartFirstTask(void);
+BaseType_t xPortStartScheduler(void) {
+  extern void xPortStartFirstTask(void);
 
 #if (configASSERT_DEFINED == 1)
-    {
-        volatile uint32_t mtvec = 0;
-
-        /* Check the least significant two bits of mtvec are 00 - indicating
-        single vector mode. */
-        __asm volatile("csrr %0, mtvec"
-                       : "=r"(mtvec));
-        //configASSERT( ( mtvec & 0x03UL ) == 0 );
-
-        /* Check alignment of the interrupt stack - which is the same as the
-        stack that was being used by main() prior to the scheduler being
-        started. */
-        configASSERT((xISRStackTop & portBYTE_ALIGNMENT_MASK) == 0);
-    }
+  {
+    volatile uint32_t mtvec = 0;
+
+    /* Check the least significant two bits of mtvec are 00 - indicating
+    single vector mode. */
+    __asm volatile("csrr %0, mtvec" : "=r"(mtvec));
+    // configASSERT( ( mtvec & 0x03UL ) == 0 );
+
+    /* Check alignment of the interrupt stack - which is the same as the
+    stack that was being used by main() prior to the scheduler being
+    started. */
+    configASSERT((xISRStackTop & portBYTE_ALIGNMENT_MASK) == 0);
+  }
 #endif /* configASSERT_DEFINED */
 
-    /* If there is a CLINT then it is ok to use the default implementation
-    in this file, otherwise vPortSetupTimerInterrupt() must be implemented to
-    configure whichever clock is to be used to generate the tick interrupt. */
-    vPortSetupTimerInterrupt();
+  /* If there is a CLINT then it is ok to use the default implementation
+  in this file, otherwise vPortSetupTimerInterrupt() must be implemented to
+  configure whichever clock is to be used to generate the tick interrupt. */
+  vPortSetupTimerInterrupt();
 
 #if (configCLINT_BASE_ADDRESS != 0)
-    {
-        /* Enable mtime and external interrupts.  1<<7 for timer interrupt, 1<<11
-        for external interrupt.  _RB_ What happens here when mtime is not present as
-        with pulpino? */
-        __asm volatile("csrs mie, %0" ::"r"(0x880));
-    }
+  {
+    /* Enable mtime and external interrupts.  1<<7 for timer interrupt, 1<<11
+    for external interrupt.  _RB_ What happens here when mtime is not present as
+    with pulpino? */
+    __asm volatile("csrs mie, %0" ::"r"(0x880));
+  }
 #else
-    {
-        /* Enable external interrupts. */
-        __asm volatile("csrs mie, %0" ::"r"(0x800));
-    }
+  {
+    /* Enable external interrupts. */
+    __asm volatile("csrs mie, %0" ::"r"(0x800));
+  }
 #endif /* configCLINT_BASE_ADDRESS */
 
-    *(uint8_t *)(0x02800400 + 7) = 1;
-    xPortStartFirstTask();
+  *(uint8_t *)(0x02800400 + 7) = 1;
+  xPortStartFirstTask();
 
-    /* Should not get here as after calling xPortStartFirstTask() only tasks
-    should be executing. */
-    return pdFAIL;
+  /* Should not get here as after calling xPortStartFirstTask() only tasks
+  should be executing. */
+  return pdFAIL;
 }
 /*-----------------------------------------------------------*/
 
-void vPortEndScheduler(void)
-{
-    /* Not implemented. */
-    for (;;)
-        ;
+void vPortEndScheduler(void) {
+  /* Not implemented. */
+  for (;;)
+    ;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/CMakeLists.txt b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/CMakeLists.txt
deleted file mode 100644
index b140a9273..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/CMakeLists.txt
+++ /dev/null
@@ -1,52 +0,0 @@
-################# Add global include #################
-list(APPEND ADD_INCLUDE
-"${CMAKE_CURRENT_SOURCE_DIR}/core"
-"${CMAKE_CURRENT_SOURCE_DIR}/common"
-"${CMAKE_CURRENT_SOURCE_DIR}/class/cdc"
-"${CMAKE_CURRENT_SOURCE_DIR}/class/hid"
-"${CMAKE_CURRENT_SOURCE_DIR}/class/msc"
-"${CMAKE_CURRENT_SOURCE_DIR}/class/video"
-"${CMAKE_CURRENT_SOURCE_DIR}/class/audio"
-"${CMAKE_CURRENT_SOURCE_DIR}/class/winusb"
-)
-#######################################################
-
-################# Add private include #################
-# list(APPEND ADD_PRIVATE_INCLUDE
-# )
-#######################################################
-
-############## Add current dir source files ###########
-file(GLOB_RECURSE sources "${CMAKE_CURRENT_SOURCE_DIR}/core/*.c"
-"${CMAKE_CURRENT_SOURCE_DIR}/class/*.c"
-)
-list(APPEND ADD_SRCS  ${sources})
-# aux_source_directory(src ADD_SRCS)
-#######################################################
-
-########### Add required/dependent components #########
-#list(APPEND ADD_REQUIREMENTS xxx)
-#######################################################
-
-############ Add static libs ##########################
-#list(APPEND ADD_STATIC_LIB "libxxx.a")
-#######################################################
-
-############ Add dynamic libs #########################
-# list(APPEND ADD_DYNAMIC_LIB "libxxx.so"
-# )
-#######################################################
-
-############ Add global compile option ################
-#add components denpend on this component
-if(CONFIG_USB_HS)
-list(APPEND ADD_DEFINITIONS -DCONFIG_USB_HS)
-endif()
-#######################################################
-
-############ Add private compile option ################
-#add compile option for this component that won't affect other modules
-# list(APPEND ADD_PRIVATE_DEFINITIONS -Dxxx)
-#######################################################
-
-generate_library()
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c
deleted file mode 100644
index 94d4311f9..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.c
+++ /dev/null
@@ -1,114 +0,0 @@
-#include "usbd_core.h"
-#include "usbd_audio.h"
-
-struct usbd_audio_control_info audio_control_info = { 0xdb00, 0x0000, 0x0100, 0xf600, 0 };
-
-int audio_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("AUDIO Class request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    switch (setup->bRequest) {
-        case AUDIO_REQUEST_SET_CUR:
-
-            if (setup->wValueL == 0x01) {
-                if (setup->wValueH == AUDIO_FU_CONTROL_MUTE) {
-                    memcpy(&audio_control_info.mute, *data, *len);
-                } else if (setup->wValueH == AUDIO_FU_CONTROL_VOLUME) {
-                    memcpy(&audio_control_info.vol_current, *data, *len);
-                    uint32_t vol;
-                    if (audio_control_info.vol_current == 0) {
-                        vol = 100;
-                    } else {
-                        vol = (audio_control_info.vol_current - 0xDB00 + 1) * 100 / (0xFFFF - 0xDB00);
-                    }
-                    usbd_audio_set_volume(vol);
-                    USBD_LOG_INFO("current audio volume:%d\r\n", vol);
-                }
-            }
-
-            break;
-
-        case AUDIO_REQUEST_GET_CUR:
-            if (setup->wValueH == AUDIO_FU_CONTROL_MUTE) {
-                *data = (uint8_t *)&audio_control_info.mute;
-                *len = 1;
-            } else if (setup->wValueH == AUDIO_FU_CONTROL_VOLUME) {
-                *data = (uint8_t *)&audio_control_info.vol_current;
-                *len = 2;
-            }
-
-            break;
-
-        case AUDIO_REQUEST_SET_RES:
-            break;
-
-        case AUDIO_REQUEST_SET_MEM:
-            break;
-
-        case AUDIO_REQUEST_GET_MIN:
-            *data = (uint8_t *)&audio_control_info.vol_min;
-            *len = 2;
-            break;
-
-        case AUDIO_REQUEST_GET_MAX:
-            *data = (uint8_t *)&audio_control_info.vol_max;
-            *len = 2;
-            break;
-
-        case AUDIO_REQUEST_GET_RES:
-            *data = (uint8_t *)&audio_control_info.vol_res;
-            *len = 2;
-            break;
-        case AUDIO_REQUEST_GET_MEM:
-            *data[0] = 0;
-            *len = 1;
-            break;
-
-        default:
-            USBD_LOG_WRN("Unhandled Audio Class bRequest 0x%02x\r\n", setup->bRequest);
-            return -1;
-    }
-
-    return 0;
-}
-
-void audio_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
-
-            break;
-
-        case USB_EVENT_SOF:
-            break;
-
-        case USB_EVENT_SET_INTERFACE:
-            usbd_audio_set_interface_callback(((uint8_t *)arg)[3]);
-            break;
-
-        default:
-            break;
-    }
-}
-
-__weak void usbd_audio_set_volume(uint8_t vol)
-{
-}
-
-void usbd_audio_add_interface(usbd_class_t *class, usbd_interface_t *intf)
-{
-    static usbd_class_t *last_class = NULL;
-
-    if (last_class != class) {
-        last_class = class;
-        usbd_class_register(class);
-    }
-
-    intf->class_handler = audio_class_request_handler;
-    intf->custom_handler = NULL;
-    intf->vendor_handler = NULL;
-    intf->notify_handler = audio_notify_handler;
-    usbd_class_add_interface(class, intf);
-}
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.h
deleted file mode 100644
index 35f3fe25f..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/audio/usbd_audio.h
+++ /dev/null
@@ -1,277 +0,0 @@
-/**
- * @file
- * @brief USB Audio Device Class public header
- *
- * Header follows below documentation:
- * - USB Device Class Definition for Audio Devices (audio10.pdf)
- *
- * Additional documentation considered a part of USB Audio v1.0:
- * - USB Device Class Definition for Audio Data Formats (frmts10.pdf)
- * - USB Device Class Definition for Terminal Types (termt10.pdf)
- */
-
-#ifndef _USBD_AUDIO_H_
-#define _USBD_AUDIO_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/** Audio Interface Subclass Codes
- * Refer to Table A-2 from audio10.pdf
- */
-#define AUDIO_SUBCLASS_UNDEFINED      0x00
-#define AUDIO_SUBCLASS_AUDIOCONTROL   0x01
-#define AUDIO_SUBCLASS_AUDIOSTREAMING 0x02
-#define AUDIO_SUBCLASS_MIDISTREAMING  0x03
-
-#define AUDIO_PROTOCOL_UNDEFINED 0x00U
-
-#define AUDIO_ENDPOINT_GENERAL 0x01U
-
-/** Audio Class-Specific Control Interface Descriptor Subtypes
- * Refer to Table A-5 from audio10.pdf
- */
-#define AUDIO_CONTROL_UNDEFINED       0x01U
-#define AUDIO_CONTROL_HEADER          0x01U
-#define AUDIO_CONTROL_INPUT_TERMINAL  0x02U
-#define AUDIO_CONTROL_OUTPUT_TERMINAL 0x03U
-#define AUDIO_CONTROL_MIXER_UNIT      0x04U
-#define AUDIO_CONTROL_SELECTOR_UNIT   0x05U
-#define AUDIO_CONTROL_FEATURE_UNIT    0x06U
-#define AUDIO_CONTROL_PROCESSING_UNIT 0x07U
-#define AUDIO_CONTROL_EXTENSION_UNIT  0x08U
-
-/** Audio Class-Specific AS Interface Descriptor Subtypes
- * Refer to Table A-6 from audio10.pdf
- */
-#define AUDIO_STREAMING_UNDEFINED       0x00U
-#define AUDIO_STREAMING_GENERAL         0x01U
-#define AUDIO_STREAMING_FORMAT_TYPE     0x02U
-#define AUDIO_STREAMING_FORMAT_SPECIFIC 0x03U
-
-/** Audio Class-Specific Request Codes
- * Refer to Table A-9 from audio10.pdf
- */
-#define AUDIO_REQUEST_UNDEFINED 0x00
-#define AUDIO_REQUEST_SET_CUR   0x01
-#define AUDIO_REQUEST_GET_CUR   0x81
-#define AUDIO_REQUEST_SET_MIN   0x02
-#define AUDIO_REQUEST_GET_MIN   0x82
-#define AUDIO_REQUEST_SET_MAX   0x03
-#define AUDIO_REQUEST_GET_MAX   0x83
-#define AUDIO_REQUEST_SET_RES   0x04
-#define AUDIO_REQUEST_GET_RES   0x84
-#define AUDIO_REQUEST_SET_MEM   0x05
-#define AUDIO_REQUEST_GET_MEM   0x85
-#define AUDIO_REQUEST_GET_STAT  0xFF
-
-/* Feature Unit Control Bits */
-#define AUDIO_CONTROL_MUTE              0x0001
-#define AUDIO_CONTROL_VOLUME            0x0002
-#define AUDIO_CONTROL_BASS              0x0004
-#define AUDIO_CONTROL_MID               0x0008
-#define AUDIO_CONTROL_TREBLE            0x0010
-#define AUDIO_CONTROL_GRAPHIC_EQUALIZER 0x0020
-#define AUDIO_CONTROL_AUTOMATIC_GAIN    0x0040
-#define AUDIO_CONTROL_DEALY             0x0080
-#define AUDIO_CONTROL_BASS_BOOST        0x0100
-#define AUDIO_CONTROL_LOUDNESS          0x0200
-
-/** Feature Unit Control Selectors
- * Refer to Table A-11 from audio10.pdf
- */
-#define AUDIO_FU_CONTROL_MUTE              0x01
-#define AUDIO_FU_CONTROL_VOLUME            0x02
-#define AUDIO_FU_CONTROL_BASS              0x03
-#define AUDIO_FU_CONTROL_MID               0x04
-#define AUDIO_FU_CONTROL_TREBLE            0x05
-#define AUDIO_FU_CONTROL_GRAPHIC_EQUALIZER 0x06
-#define AUDIO_FU_CONTROL_AUTOMATIC_GAIN    0x07
-#define AUDIO_FU_CONTROL_DELAY             0x08
-#define AUDIO_FU_CONTROL_BASS_BOOST        0x09
-#define AUDIO_FU_CONTROL_LOUDNESS          0x0A
-
-/* Audio Descriptor Types */
-#define AUDIO_UNDEFINED_DESCRIPTOR_TYPE     0x20
-#define AUDIO_DEVICE_DESCRIPTOR_TYPE        0x21
-#define AUDIO_CONFIGURATION_DESCRIPTOR_TYPE 0x22
-#define AUDIO_STRING_DESCRIPTOR_TYPE        0x23
-#define AUDIO_INTERFACE_DESCRIPTOR_TYPE     0x24
-#define AUDIO_ENDPOINT_DESCRIPTOR_TYPE      0x25
-
-/* Audio Data Format Type I Codes */
-#define AUDIO_FORMAT_TYPE_I_UNDEFINED 0x0000
-#define AUDIO_FORMAT_PCM              0x0001
-#define AUDIO_FORMAT_PCM8             0x0002
-#define AUDIO_FORMAT_IEEE_FLOAT       0x0003
-#define AUDIO_FORMAT_ALAW             0x0004
-#define AUDIO_FORMAT_MULAW            0x0005
-
-/* Predefined Audio Channel Configuration Bits */
-#define AUDIO_CHANNEL_M   0x0000 /* Mono */
-#define AUDIO_CHANNEL_L   0x0001 /* Left Front */
-#define AUDIO_CHANNEL_R   0x0002 /* Right Front */
-#define AUDIO_CHANNEL_C   0x0004 /* Center Front */
-#define AUDIO_CHANNEL_LFE 0x0008 /* Low Freq. Enhance. */
-#define AUDIO_CHANNEL_LS  0x0010 /* Left Surround */
-#define AUDIO_CHANNEL_RS  0x0020 /* Right Surround */
-#define AUDIO_CHANNEL_LC  0x0040 /* Left of Center */
-#define AUDIO_CHANNEL_RC  0x0080 /* Right of Center */
-#define AUDIO_CHANNEL_S   0x0100 /* Surround */
-#define AUDIO_CHANNEL_SL  0x0200 /* Side Left */
-#define AUDIO_CHANNEL_SR  0x0400 /* Side Right */
-#define AUDIO_CHANNEL_T   0x0800 /* Top */
-
-#define AUDIO_FORMAT_TYPE_I   0x01
-#define AUDIO_FORMAT_TYPE_II  0x02
-#define AUDIO_FORMAT_TYPE_III 0x03
-
-/** USB Terminal Types
- * Refer to Table 2-1 - Table 2-4 from termt10.pdf
- */
-enum usb_audio_terminal_types {
-    /* USB Terminal Types */
-    USB_AUDIO_USB_UNDEFINED = 0x0100,
-    USB_AUDIO_USB_STREAMING = 0x0101,
-    USB_AUDIO_USB_VENDOR_SPEC = 0x01FF,
-
-    /* Input Terminal Types */
-    USB_AUDIO_IN_UNDEFINED = 0x0200,
-    USB_AUDIO_IN_MICROPHONE = 0x0201,
-    USB_AUDIO_IN_DESKTOP_MIC = 0x0202,
-    USB_AUDIO_IN_PERSONAL_MIC = 0x0203,
-    USB_AUDIO_IN_OM_DIR_MIC = 0x0204,
-    USB_AUDIO_IN_MIC_ARRAY = 0x0205,
-    USB_AUDIO_IN_PROC_MIC_ARRAY = 0x0205,
-
-    /* Output Terminal Types */
-    USB_AUDIO_OUT_UNDEFINED = 0x0300,
-    USB_AUDIO_OUT_SPEAKER = 0x0301,
-    USB_AUDIO_OUT_HEADPHONES = 0x0302,
-    USB_AUDIO_OUT_HEAD_AUDIO = 0x0303,
-    USB_AUDIO_OUT_DESKTOP_SPEAKER = 0x0304,
-    USB_AUDIO_OUT_ROOM_SPEAKER = 0x0305,
-    USB_AUDIO_OUT_COMM_SPEAKER = 0x0306,
-    USB_AUDIO_OUT_LOW_FREQ_SPEAKER = 0x0307,
-
-    /* Bi-directional Terminal Types */
-    USB_AUDIO_IO_UNDEFINED = 0x0400,
-    USB_AUDIO_IO_HANDSET = 0x0401,
-    USB_AUDIO_IO_HEADSET = 0x0402,
-    USB_AUDIO_IO_SPEAKERPHONE_ECHO_NONE = 0x0403,
-    USB_AUDIO_IO_SPEAKERPHONE_ECHO_SUP = 0x0404,
-    USB_AUDIO_IO_SPEAKERPHONE_ECHO_CAN = 0x0405,
-};
-
-/**
- * @warning Size of baInterface is 2 just to make it useable
- * for all kind of devices: headphones, microphone and headset.
- * Actual size of the struct should be checked by reading
- * .bLength.
- */
-struct cs_ac_if_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bDescriptorSubtype;
-    uint16_t bcdADC;
-    uint16_t wTotalLength;
-    uint8_t bInCollection;
-    uint8_t baInterfaceNr[2];
-} __packed;
-
-struct input_terminal_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bDescriptorSubtype;
-    uint8_t bTerminalID;
-    uint16_t wTerminalType;
-    uint8_t bAssocTerminal;
-    uint8_t bNrChannels;
-    uint16_t wChannelConfig;
-    uint8_t iChannelNames;
-    uint8_t iTerminal;
-} __packed;
-
-/**
- * @note Size of Feature unit descriptor is not fixed.
- * This structure is just a helper not a common type.
- */
-struct feature_unit_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bDescriptorSubtype;
-    uint8_t bUnitID;
-    uint8_t bSourceID;
-    uint8_t bControlSize;
-    uint16_t bmaControls[1];
-} __packed;
-
-struct output_terminal_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bDescriptorSubtype;
-    uint8_t bTerminalID;
-    uint16_t wTerminalType;
-    uint8_t bAssocTerminal;
-    uint8_t bSourceID;
-    uint8_t iTerminal;
-} __packed;
-
-struct as_cs_interface_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bDescriptorSubtype;
-    uint8_t bTerminalLink;
-    uint8_t bDelay;
-    uint16_t wFormatTag;
-} __packed;
-
-struct format_type_i_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bDescriptorSubtype;
-    uint8_t bFormatType;
-    uint8_t bNrChannels;
-    uint8_t bSubframeSize;
-    uint8_t bBitResolution;
-    uint8_t bSamFreqType;
-    uint8_t tSamFreq[3];
-} __packed;
-
-struct std_as_ad_endpoint_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bEndpointAddress;
-    uint8_t bmAttributes;
-    uint16_t wMaxPacketSize;
-    uint8_t bInterval;
-    uint8_t bRefresh;
-    uint8_t bSynchAddress;
-} __packed;
-
-struct cs_as_ad_ep_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bDescriptorSubtype;
-    uint8_t bmAttributes;
-    uint8_t bLockDelayUnits;
-    uint16_t wLockDelay;
-} __packed;
-
-struct usbd_audio_control_info {
-    uint16_t vol_min;
-    uint16_t vol_max;
-    uint16_t vol_res;
-    uint16_t vol_current;
-    uint8_t mute;
-};
-
-void usbd_audio_add_interface(usbd_class_t *class, usbd_interface_t *intf);
-void usbd_audio_set_interface_callback(uint8_t value);
-void usbd_audio_set_volume(uint8_t vol);
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _USB_AUDIO_H_ */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c
deleted file mode 100644
index c48a74a8d..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.c
+++ /dev/null
@@ -1,171 +0,0 @@
-/**
- * @file usbd_cdc.c
- * @brief
- *
- * Copyright (c) 2021 Bouffalolab team
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.  The
- * ASF licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the
- * License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
- * License for the specific language governing permissions and limitations
- * under the License.
- *
- */
-#include "usbd_core.h"
-#include "usbd_cdc.h"
-
-const char *stop_name[] = { "1", "1.5", "2" };
-const char *parity_name[] = { "N", "O", "E", "M", "S" };
-
-/* Device data structure */
-struct cdc_acm_cfg_private {
-    /* CDC ACM line coding properties. LE order */
-    struct cdc_line_coding line_coding;
-    /* CDC ACM line state bitmap, DTE side */
-    uint8_t line_state;
-    /* CDC ACM serial state bitmap, DCE side */
-    uint8_t serial_state;
-    /* CDC ACM notification sent status */
-    uint8_t notification_sent;
-    /* CDC ACM configured flag */
-    bool configured;
-    /* CDC ACM suspended flag */
-    bool suspended;
-    uint32_t uart_first_init_flag;
-
-} usbd_cdc_acm_cfg;
-
-static void usbd_cdc_acm_reset(void)
-{
-    usbd_cdc_acm_cfg.line_coding.dwDTERate = 2000000;
-    usbd_cdc_acm_cfg.line_coding.bDataBits = 8;
-    usbd_cdc_acm_cfg.line_coding.bParityType = 0;
-    usbd_cdc_acm_cfg.line_coding.bCharFormat = 0;
-    usbd_cdc_acm_cfg.configured = false;
-    usbd_cdc_acm_cfg.uart_first_init_flag = 0;
-}
-
-/**
- * @brief Handler called for Class requests not handled by the USB stack.
- *
- * @param setup    Information about the request to execute.
- * @param len       Size of the buffer.
- * @param data      Buffer containing the request result.
- *
- * @return  0 on success, negative errno code on fail.
- */
-static int cdc_acm_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("CDC Class request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    switch (setup->bRequest) {
-        case CDC_REQUEST_SET_LINE_CODING:
-
-            /*******************************************************************************/
-            /* Line Coding Structure                                                       */
-            /*-----------------------------------------------------------------------------*/
-            /* Offset | Field       | Size | Value  | Description                          */
-            /* 0      | dwDTERate   |   4  | Number |Data terminal rate, in bits per second*/
-            /* 4      | bCharFormat |   1  | Number | Stop bits                            */
-            /*                                        0 - 1 Stop bit                       */
-            /*                                        1 - 1.5 Stop bits                    */
-            /*                                        2 - 2 Stop bits                      */
-            /* 5      | bParityType |  1   | Number | Parity                               */
-            /*                                        0 - None                             */
-            /*                                        1 - Odd                              */
-            /*                                        2 - Even                             */
-            /*                                        3 - Mark                             */
-            /*                                        4 - Space                            */
-            /* 6      | bDataBits  |   1   | Number Data bits (5, 6, 7, 8 or 16).          */
-            /*******************************************************************************/
-            if (usbd_cdc_acm_cfg.uart_first_init_flag == 0) {
-                usbd_cdc_acm_cfg.uart_first_init_flag = 1;
-                return 0;
-            }
-
-            memcpy(&usbd_cdc_acm_cfg.line_coding, *data, sizeof(usbd_cdc_acm_cfg.line_coding));
-            USBD_LOG_DBG("CDC_SET_LINE_CODING <%d %d %s %s>\r\n",
-                         usbd_cdc_acm_cfg.line_coding.dwDTERate,
-                         usbd_cdc_acm_cfg.line_coding.bDataBits,
-                         parity_name[usbd_cdc_acm_cfg.line_coding.bParityType],
-                         stop_name[usbd_cdc_acm_cfg.line_coding.bCharFormat]);
-            usbd_cdc_acm_set_line_coding(usbd_cdc_acm_cfg.line_coding.dwDTERate, usbd_cdc_acm_cfg.line_coding.bDataBits,
-                                         usbd_cdc_acm_cfg.line_coding.bParityType, usbd_cdc_acm_cfg.line_coding.bCharFormat);
-            break;
-
-        case CDC_REQUEST_SET_CONTROL_LINE_STATE:
-            usbd_cdc_acm_cfg.line_state = (uint8_t)setup->wValue;
-            bool dtr = (setup->wValue & 0x01);
-            bool rts = (setup->wValue & 0x02);
-            USBD_LOG_DBG("DTR 0x%x,RTS 0x%x\r\n",
-                         dtr, rts);
-            usbd_cdc_acm_set_dtr(dtr);
-            usbd_cdc_acm_set_rts(rts);
-            break;
-
-        case CDC_REQUEST_GET_LINE_CODING:
-            *data = (uint8_t *)(&usbd_cdc_acm_cfg.line_coding);
-            *len = sizeof(usbd_cdc_acm_cfg.line_coding);
-            USBD_LOG_DBG("CDC_GET_LINE_CODING %d %d %d %d\r\n",
-                         usbd_cdc_acm_cfg.line_coding.dwDTERate,
-                         usbd_cdc_acm_cfg.line_coding.bCharFormat,
-                         usbd_cdc_acm_cfg.line_coding.bParityType,
-                         usbd_cdc_acm_cfg.line_coding.bDataBits);
-            break;
-
-        default:
-            USBD_LOG_WRN("Unhandled CDC Class bRequest 0x%02x\r\n", setup->bRequest);
-            return -1;
-    }
-
-    return 0;
-}
-
-static void cdc_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
-            usbd_cdc_acm_reset();
-            break;
-
-        default:
-            break;
-    }
-}
-
-__weak void usbd_cdc_acm_set_line_coding(uint32_t baudrate, uint8_t databits, uint8_t parity, uint8_t stopbits)
-{
-}
-__weak void usbd_cdc_acm_set_dtr(bool dtr)
-{
-}
-__weak void usbd_cdc_acm_set_rts(bool rts)
-{
-}
-
-void usbd_cdc_add_acm_interface(usbd_class_t *class, usbd_interface_t *intf)
-{
-    static usbd_class_t *last_class = NULL;
-
-    if (last_class != class) {
-        last_class = class;
-        usbd_class_register(class);
-    }
-
-    intf->class_handler = cdc_acm_class_request_handler;
-    intf->custom_handler = NULL;
-    intf->vendor_handler = NULL;
-    intf->notify_handler = cdc_notify_handler;
-    usbd_class_add_interface(class, intf);
-}
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.h
deleted file mode 100644
index 33c2ac29c..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/cdc/usbd_cdc.h
+++ /dev/null
@@ -1,442 +0,0 @@
-/**
- * @file
- * @brief USB Communications Device Class (CDC) public header
- *
- * Header follows the Class Definitions for
- * Communications Devices Specification (CDC120-20101103-track.pdf),
- * PSTN Devices Specification (PSTN120.pdf) and
- * Ethernet Control Model Devices Specification (ECM120.pdf).
- * Header is limited to ACM and ECM Subclasses.
- */
-
-#ifndef _USBD_CDC_H
-#define _USBD_CDC_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*------------------------------------------------------------------------------
- *      Definitions  based on usbcdc11.pdf (www.usb.org)
- *----------------------------------------------------------------------------*/
-/* Communication device class specification version 1.10 */
-#define CDC_V1_10 0x0110U
-// Communication device class specification version 1.2
-#define CDC_V1_2_0 0x0120U
-
-/* Communication interface class code */
-/* (usbcdc11.pdf, 4.2, Table 15) */
-#define CDC_COMMUNICATION_INTERFACE_CLASS 0x02U
-
-/* Communication interface class subclass codes */
-/* (usbcdc11.pdf, 4.3, Table 16) */
-#define CDC_DIRECT_LINE_CONTROL_MODEL         0x01U
-#define CDC_ABSTRACT_CONTROL_MODEL            0x02U
-#define CDC_TELEPHONE_CONTROL_MODEL           0x03U
-#define CDC_MULTI_CHANNEL_CONTROL_MODEL       0x04U
-#define CDC_CAPI_CONTROL_MODEL                0x05U
-#define CDC_ETHERNET_NETWORKING_CONTROL_MODEL 0x06U
-#define CDC_ATM_NETWORKING_CONTROL_MODEL      0x07U
-#define CDC_WIRELESS_HANDSET_CONTROL_MODEL    0x08U
-#define CDC_DEVICE_MANAGEMENT                 0x09U
-#define CDC_MOBILE_DIRECT_LINE_MODEL          0x0AU
-#define CDC_OBEX                              0x0BU
-#define CDC_ETHERNET_EMULATION_MODEL          0x0CU
-#define CDC_NETWORK_CONTROL_MODEL             0x0DU
-
-/* Communication interface class control protocol codes */
-/* (usbcdc11.pdf, 4.4, Table 17) */
-#define CDC_COMMON_PROTOCOL_NONE                            0x00U
-#define CDC_COMMON_PROTOCOL_AT_COMMANDS                     0x01U
-#define CDC_COMMON_PROTOCOL_AT_COMMANDS_PCCA_101            0x02U
-#define CDC_COMMON_PROTOCOL_AT_COMMANDS_PCCA_101_AND_ANNEXO 0x03U
-#define CDC_COMMON_PROTOCOL_AT_COMMANDS_GSM_707             0x04U
-#define CDC_COMMON_PROTOCOL_AT_COMMANDS_3GPP_27007          0x05U
-#define CDC_COMMON_PROTOCOL_AT_COMMANDS_CDMA                0x06U
-#define CDC_COMMON_PROTOCOL_ETHERNET_EMULATION_MODEL        0x07U
-// NCM Communication Interface Protocol Codes
-// (usbncm10.pdf, 4.2, Table 4-2)
-#define CDC_NCM_PROTOCOL_NONE 0x00U
-#define CDC_NCM_PROTOCOL_OEM  0xFEU
-
-/* Data interface class code */
-/* (usbcdc11.pdf, 4.5, Table 18) */
-#define CDC_DATA_INTERFACE_CLASS 0x0A
-
-/* Data interface class protocol codes */
-/* (usbcdc11.pdf, 4.7, Table 19) */
-#define CDC_DATA_PROTOCOL_ISDN_BRI            0x30
-#define CDC_DATA_PROTOCOL_HDLC                0x31
-#define CDC_DATA_PROTOCOL_TRANSPARENT         0x32
-#define CDC_DATA_PROTOCOL_Q921_MANAGEMENT     0x50
-#define CDC_DATA_PROTOCOL_Q921_DATA_LINK      0x51
-#define CDC_DATA_PROTOCOL_Q921_MULTIPLEXOR    0x52
-#define CDC_DATA_PROTOCOL_V42                 0x90
-#define CDC_DATA_PROTOCOL_EURO_ISDN           0x91
-#define CDC_DATA_PROTOCOL_V24_RATE_ADAPTATION 0x92
-#define CDC_DATA_PROTOCOL_CAPI                0x93
-#define CDC_DATA_PROTOCOL_HOST_BASED_DRIVER   0xFD
-#define CDC_DATA_PROTOCOL_DESCRIBED_IN_PUFD   0xFE
-
-/* Type values for bDescriptorType field of functional descriptors */
-/* (usbcdc11.pdf, 5.2.3, Table 24) */
-#define CDC_CS_INTERFACE 0x24
-#define CDC_CS_ENDPOINT  0x25
-
-/* Type values for bDescriptorSubtype field of functional descriptors */
-/* (usbcdc11.pdf, 5.2.3, Table 25) */
-#define CDC_FUNC_DESC_HEADER                          0x00
-#define CDC_FUNC_DESC_CALL_MANAGEMENT                 0x01
-#define CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT     0x02
-#define CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT          0x03
-#define CDC_FUNC_DESC_TELEPHONE_RINGER                0x04
-#define CDC_FUNC_DESC_REPORTING_CAPABILITIES          0x05
-#define CDC_FUNC_DESC_UNION                           0x06
-#define CDC_FUNC_DESC_COUNTRY_SELECTION               0x07
-#define CDC_FUNC_DESC_TELEPHONE_OPERATIONAL_MODES     0x08
-#define CDC_FUNC_DESC_USB_TERMINAL                    0x09
-#define CDC_FUNC_DESC_NETWORK_CHANNEL                 0x0A
-#define CDC_FUNC_DESC_PROTOCOL_UNIT                   0x0B
-#define CDC_FUNC_DESC_EXTENSION_UNIT                  0x0C
-#define CDC_FUNC_DESC_MULTI_CHANNEL_MANAGEMENT        0x0D
-#define CDC_FUNC_DESC_CAPI_CONTROL_MANAGEMENT         0x0E
-#define CDC_FUNC_DESC_ETHERNET_NETWORKING             0x0F
-#define CDC_FUNC_DESC_ATM_NETWORKING                  0x10
-#define CDC_FUNC_DESC_WIRELESS_HANDSET_CONTROL_MODEL  0x11
-#define CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL        0x12
-#define CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL_DETAIL 0x13
-#define CDC_FUNC_DESC_DEVICE_MANAGEMENT_MODEL         0x14
-#define CDC_FUNC_DESC_OBEX                            0x15
-#define CDC_FUNC_DESC_COMMAND_SET                     0x16
-#define CDC_FUNC_DESC_COMMAND_SET_DETAIL              0x17
-#define CDC_FUNC_DESC_TELEPHONE_CONTROL_MODEL         0x18
-#define CDC_FUNC_DESC_OBEX_SERVICE_IDENTIFIER         0x19
-
-/* CDC class-specific request codes */
-/* (usbcdc11.pdf, 6.2, Table 46) */
-/* see Table 45 for info about the specific requests. */
-#define CDC_REQUEST_SEND_ENCAPSULATED_COMMAND      0x00
-#define CDC_REQUEST_GET_ENCAPSULATED_RESPONSE      0x01
-#define CDC_REQUEST_SET_COMM_FEATURE               0x02
-#define CDC_REQUEST_GET_COMM_FEATURE               0x03
-#define CDC_REQUEST_CLEAR_COMM_FEATURE             0x04
-#define CDC_REQUEST_SET_AUX_LINE_STATE             0x10
-#define CDC_REQUEST_SET_HOOK_STATE                 0x11
-#define CDC_REQUEST_PULSE_SETUP                    0x12
-#define CDC_REQUEST_SEND_PULSE                     0x13
-#define CDC_REQUEST_SET_PULSE_TIME                 0x14
-#define CDC_REQUEST_RING_AUX_JACK                  0x15
-#define CDC_REQUEST_SET_LINE_CODING                0x20
-#define CDC_REQUEST_GET_LINE_CODING                0x21
-#define CDC_REQUEST_SET_CONTROL_LINE_STATE         0x22
-#define CDC_REQUEST_SEND_BREAK                     0x23
-#define CDC_REQUEST_SET_RINGER_PARMS               0x30
-#define CDC_REQUEST_GET_RINGER_PARMS               0x31
-#define CDC_REQUEST_SET_OPERATION_PARMS            0x32
-#define CDC_REQUEST_GET_OPERATION_PARMS            0x33
-#define CDC_REQUEST_SET_LINE_PARMS                 0x34
-#define CDC_REQUEST_GET_LINE_PARMS                 0x35
-#define CDC_REQUEST_DIAL_DIGITS                    0x36
-#define CDC_REQUEST_SET_UNIT_PARAMETER             0x37
-#define CDC_REQUEST_GET_UNIT_PARAMETER             0x38
-#define CDC_REQUEST_CLEAR_UNIT_PARAMETER           0x39
-#define CDC_REQUEST_GET_PROFILE                    0x3A
-#define CDC_REQUEST_SET_ETHERNET_MULTICAST_FILTERS 0x40
-#define CDC_REQUEST_SET_ETHERNET_PMP_FILTER        0x41
-#define CDC_REQUEST_GET_ETHERNET_PMP_FILTER        0x42
-#define CDC_REQUEST_SET_ETHERNET_PACKET_FILTER     0x43
-#define CDC_REQUEST_GET_ETHERNET_STATISTIC         0x44
-#define CDC_REQUEST_SET_ATM_DATA_FORMAT            0x50
-#define CDC_REQUEST_GET_ATM_DEVICE_STATISTICS      0x51
-#define CDC_REQUEST_SET_ATM_DEFAULT_VC             0x52
-#define CDC_REQUEST_GET_ATM_VC_STATISTICS          0x53
-
-/* Communication feature selector codes */
-/* (usbcdc11.pdf, 6.2.2..6.2.4, Table 47) */
-#define CDC_ABSTRACT_STATE  0x01
-#define CDC_COUNTRY_SETTING 0x02
-
-/** Control Signal Bitmap Values for SetControlLineState */
-#define SET_CONTROL_LINE_STATE_RTS 0x02
-#define SET_CONTROL_LINE_STATE_DTR 0x01
-
-/* Feature Status returned for ABSTRACT_STATE Selector */
-/* (usbcdc11.pdf, 6.2.3, Table 48) */
-#define CDC_IDLE_SETTING          (1 << 0)
-#define CDC_DATA_MULTPLEXED_STATE (1 << 1)
-
-/* Control signal bitmap values for the SetControlLineState request */
-/* (usbcdc11.pdf, 6.2.14, Table 51) */
-#define CDC_DTE_PRESENT      (1 << 0)
-#define CDC_ACTIVATE_CARRIER (1 << 1)
-
-/* CDC class-specific notification codes */
-/* (usbcdc11.pdf, 6.3, Table 68) */
-/* see Table 67 for Info about class-specific notifications */
-#define CDC_NOTIFICATION_NETWORK_CONNECTION 0x00
-#define CDC_RESPONSE_AVAILABLE              0x01
-#define CDC_AUX_JACK_HOOK_STATE             0x08
-#define CDC_RING_DETECT                     0x09
-#define CDC_NOTIFICATION_SERIAL_STATE       0x20
-#define CDC_CALL_STATE_CHANGE               0x28
-#define CDC_LINE_STATE_CHANGE               0x29
-#define CDC_CONNECTION_SPEED_CHANGE         0x2A
-
-/* UART state bitmap values (Serial state notification). */
-/* (usbcdc11.pdf, 6.3.5, Table 69) */
-#define CDC_SERIAL_STATE_OVERRUN        (1 << 6) /* receive data overrun error has occurred */
-#define CDC_SERIAL_STATE_OVERRUN_Pos    (6)
-#define CDC_SERIAL_STATE_OVERRUN_Msk    (1 << CDC_SERIAL_STATE_OVERRUN_Pos)
-#define CDC_SERIAL_STATE_PARITY         (1 << 5) /* parity error has occurred */
-#define CDC_SERIAL_STATE_PARITY_Pos     (5)
-#define CDC_SERIAL_STATE_PARITY_Msk     (1 << CDC_SERIAL_STATE_PARITY_Pos)
-#define CDC_SERIAL_STATE_FRAMING        (1 << 4) /* framing error has occurred */
-#define CDC_SERIAL_STATE_FRAMING_Pos    (4)
-#define CDC_SERIAL_STATE_FRAMING_Msk    (1 << CDC_SERIAL_STATE_FRAMING_Pos)
-#define CDC_SERIAL_STATE_RING           (1 << 3) /* state of ring signal detection */
-#define CDC_SERIAL_STATE_RING_Pos       (3)
-#define CDC_SERIAL_STATE_RING_Msk       (1 << CDC_SERIAL_STATE_RING_Pos)
-#define CDC_SERIAL_STATE_BREAK          (1 << 2) /* state of break detection */
-#define CDC_SERIAL_STATE_BREAK_Pos      (2)
-#define CDC_SERIAL_STATE_BREAK_Msk      (1 << CDC_SERIAL_STATE_BREAK_Pos)
-#define CDC_SERIAL_STATE_TX_CARRIER     (1 << 1) /* state of transmission carrier */
-#define CDC_SERIAL_STATE_TX_CARRIER_Pos (1)
-#define CDC_SERIAL_STATE_TX_CARRIER_Msk (1 << CDC_SERIAL_STATE_TX_CARRIER_Pos)
-#define CDC_SERIAL_STATE_RX_CARRIER     (1 << 0) /* state of receiver carrier */
-#define CDC_SERIAL_STATE_RX_CARRIER_Pos (0)
-#define CDC_SERIAL_STATE_RX_CARRIER_Msk (1 << CDC_SERIAL_STATE_RX_CARRIER_Pos)
-
-/*------------------------------------------------------------------------------
- *      Structures  based on usbcdc11.pdf (www.usb.org)
- *----------------------------------------------------------------------------*/
-
-/* Header functional descriptor */
-/* (usbcdc11.pdf, 5.2.3.1) */
-/* This header must precede any list of class-specific descriptors. */
-struct cdc_header_descriptor {
-    uint8_t bFunctionLength;    /* size of this descriptor in bytes */
-    uint8_t bDescriptorType;    /* CS_INTERFACE descriptor type */
-    uint8_t bDescriptorSubtype; /* Header functional descriptor subtype */
-    uint16_t bcdCDC;            /* USB CDC specification release version */
-} __packed;
-
-/* Call management functional descriptor */
-/* (usbcdc11.pdf, 5.2.3.2) */
-/* Describes the processing of calls for the communication class interface. */
-struct cdc_call_management_descriptor {
-    uint8_t bFunctionLength;    /* size of this descriptor in bytes */
-    uint8_t bDescriptorType;    /* CS_INTERFACE descriptor type */
-    uint8_t bDescriptorSubtype; /* call management functional descriptor subtype */
-    uint8_t bmCapabilities;     /* capabilities that this configuration supports */
-    uint8_t bDataInterface;     /* interface number of the data class interface used for call management (optional) */
-} __packed;
-
-/* Abstract control management functional descriptor */
-/* (usbcdc11.pdf, 5.2.3.3) */
-/* Describes the command supported by the communication interface class with the Abstract Control Model subclass code. */
-struct cdc_abstract_control_management_descriptor {
-    uint8_t bFunctionLength;    /* size of this descriptor in bytes */
-    uint8_t bDescriptorType;    /* CS_INTERFACE descriptor type */
-    uint8_t bDescriptorSubtype; /* abstract control management functional descriptor subtype */
-    uint8_t bmCapabilities;     /* capabilities supported by this configuration */
-} __packed;
-
-/* Union functional descriptors */
-/* (usbcdc11.pdf, 5.2.3.8) */
-/* Describes the relationship between a group of interfaces that can be considered to form a functional unit. */
-struct cdc_union_descriptor {
-    uint8_t bFunctionLength;    /* size of this descriptor in bytes */
-    uint8_t bDescriptorType;    /* CS_INTERFACE descriptor type */
-    uint8_t bDescriptorSubtype; /* union functional descriptor subtype */
-    uint8_t bMasterInterface;   /* interface number designated as master */
-} __packed;
-
-/* Union functional descriptors with one slave interface */
-/* (usbcdc11.pdf, 5.2.3.8) */
-struct cdc_union_1slave_descriptor {
-    uint8_t bFunctionLength;
-    uint8_t bDescriptorType;
-    uint8_t bDescriptorSubtype;
-    uint8_t bControlInterface;
-    uint8_t bSubordinateInterface0;
-} __packed;
-
-/* Line coding structure for GET_LINE_CODING / SET_LINE_CODING class requests*/
-/* Format of the data returned when a GetLineCoding request is received */
-/* (usbcdc11.pdf, 6.2.13) */
-struct cdc_line_coding {
-    uint32_t dwDTERate;  /* Data terminal rate in bits per second */
-    uint8_t bCharFormat; /* Number of stop bits */
-    uint8_t bParityType; /* Parity bit type */
-    uint8_t bDataBits;   /* Number of data bits */
-} __packed;
-
-/** Data structure for the notification about SerialState */
-struct cdc_acm_notification {
-    uint8_t bmRequestType;
-    uint8_t bNotificationType;
-    uint16_t wValue;
-    uint16_t wIndex;
-    uint16_t wLength;
-    uint16_t data;
-} __packed;
-
-/** Ethernet Networking Functional Descriptor */
-struct cdc_ecm_descriptor {
-    uint8_t bFunctionLength;
-    uint8_t bDescriptorType;
-    uint8_t bDescriptorSubtype;
-    uint8_t iMACAddress;
-    uint32_t bmEthernetStatistics;
-    uint16_t wMaxSegmentSize;
-    uint16_t wNumberMCFilters;
-    uint8_t bNumberPowerFilters;
-} __packed;
-
-/*Length of template descriptor: 66 bytes*/
-#define CDC_ACM_DESCRIPTOR_LEN (8 + 9 + 5 + 5 + 4 + 5 + 7 + 9 + 7 + 7)
-// clang-format off
-#ifndef CONFIG_USB_HS
-#define CDC_ACM_DESCRIPTOR_INIT(bFirstInterface, int_ep, out_ep, in_ep, str_idx)               \
-    /* Interface Associate */                                                                  \
-    0x08,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION,             /* bDescriptorType */               \
-    bFirstInterface,                                       /* bFirstInterface */               \
-    0x02,                                                  /* bInterfaceCount */               \
-    USB_DEVICE_CLASS_CDC,                                  /* bFunctionClass */                \
-    CDC_ABSTRACT_CONTROL_MODEL,                            /* bFunctionSubClass */             \
-    CDC_COMMON_PROTOCOL_AT_COMMANDS,                       /* bFunctionProtocol */             \
-    0x00,                                                  /* iFunction */                     \
-    0x09,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_INTERFACE,                         /* bDescriptorType */               \
-    bFirstInterface,                                       /* bInterfaceNumber */              \
-    0x00,                                                  /* bAlternateSetting */             \
-    0x01,                                                  /* bNumEndpoints */                 \
-    USB_DEVICE_CLASS_CDC,                                  /* bInterfaceClass */               \
-    CDC_ABSTRACT_CONTROL_MODEL,                            /* bInterfaceSubClass */            \
-    CDC_COMMON_PROTOCOL_AT_COMMANDS,                       /* bInterfaceProtocol */            \
-    str_idx,                                               /* iInterface */                    \
-    0x05,                                                  /* bLength */                       \
-    CDC_CS_INTERFACE,                                      /* bDescriptorType */               \
-    CDC_FUNC_DESC_HEADER,                                  /* bDescriptorSubtype */            \
-    WBVAL(CDC_V1_10),                                      /* bcdCDC */                        \
-    0x05,                                                  /* bLength */                       \
-    CDC_CS_INTERFACE,                                      /* bDescriptorType */               \
-    CDC_FUNC_DESC_CALL_MANAGEMENT,                         /* bDescriptorSubtype */            \
-    bFirstInterface,                                       /* bmCapabilities */                \
-    (uint8_t)(bFirstInterface + 1),                        /* bDataInterface */                \
-    0x04,                                                  /* bLength */                       \
-    CDC_CS_INTERFACE,                                      /* bDescriptorType */               \
-    CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT,             /* bDescriptorSubtype */            \
-    0x02,                                                  /* bmCapabilities */                \
-    0x05,                                                  /* bLength */                       \
-    CDC_CS_INTERFACE,                                      /* bDescriptorType */               \
-    CDC_FUNC_DESC_UNION,                                   /* bDescriptorSubtype */            \
-    bFirstInterface,                                       /* bMasterInterface */              \
-    (uint8_t)(bFirstInterface + 1),                        /* bSlaveInterface0 */              \
-    0x07,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_ENDPOINT,                          /* bDescriptorType */               \
-    int_ep,                                                /* bEndpointAddress */              \
-    0x03,                                                  /* bmAttributes */                  \
-    0x40, 0x00,                                            /* wMaxPacketSize */                \
-    0x00,                                                  /* bInterval */                     \
-    0x09,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_INTERFACE,                         /* bDescriptorType */               \
-    (uint8_t)(bFirstInterface + 1),                        /* bInterfaceNumber */              \
-    0x00,                                                  /* bAlternateSetting */             \
-    0x02,                                                  /* bNumEndpoints */                 \
-    CDC_DATA_INTERFACE_CLASS,                              /* bInterfaceClass */               \
-    0x00,                                                  /* bInterfaceSubClass */            \
-    0x00,                                                  /* bInterfaceProtocol */            \
-    0x00,                                                  /* iInterface */                    \
-    0x07,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_ENDPOINT,                          /* bDescriptorType */               \
-    out_ep,                                                /* bEndpointAddress */              \
-    0x02,                                                  /* bmAttributes */                  \
-    0x40, 0x00,                                            /* wMaxPacketSize */                \
-    0x00,                                                  /* bInterval */                     \
-    0x07,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_ENDPOINT,                          /* bDescriptorType */               \
-    in_ep,                                                 /* bEndpointAddress */              \
-    0x02,                                                  /* bmAttributes */                  \
-    0x40, 0x00,                                            /* wMaxPacketSize */                \
-    0x00                                                   /* bInterval */
-#else
-#define CDC_ACM_DESCRIPTOR_INIT(bFirstInterface, int_ep, out_ep, in_ep, str_idx)               \
-    /* Interface Associate */                                                                  \
-    0x08,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION,             /* bDescriptorType */               \
-    bFirstInterface,                                       /* bFirstInterface */               \
-    0x02,                                                  /* bInterfaceCount */               \
-    USB_DEVICE_CLASS_CDC,                                  /* bFunctionClass */                \
-    CDC_ABSTRACT_CONTROL_MODEL,                            /* bFunctionSubClass */             \
-    CDC_COMMON_PROTOCOL_AT_COMMANDS,                       /* bFunctionProtocol */             \
-    0x00,                                                  /* iFunction */                     \
-    0x09,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_INTERFACE,                         /* bDescriptorType */               \
-    bFirstInterface,                                       /* bInterfaceNumber */              \
-    0x00,                                                  /* bAlternateSetting */             \
-    0x01,                                                  /* bNumEndpoints */                 \
-    USB_DEVICE_CLASS_CDC,                                  /* bInterfaceClass */               \
-    CDC_ABSTRACT_CONTROL_MODEL,                            /* bInterfaceSubClass */            \
-    CDC_COMMON_PROTOCOL_AT_COMMANDS,                       /* bInterfaceProtocol */            \
-    str_idx,                                               /* iInterface */                    \
-    0x05,                                                  /* bLength */                       \
-    CDC_CS_INTERFACE,                                      /* bDescriptorType */               \
-    CDC_FUNC_DESC_HEADER,                                  /* bDescriptorSubtype */            \
-    WBVAL(CDC_V1_10),                                      /* bcdCDC */                        \
-    0x05,                                                  /* bLength */                       \
-    CDC_CS_INTERFACE,                                      /* bDescriptorType */               \
-    CDC_FUNC_DESC_CALL_MANAGEMENT,                         /* bDescriptorSubtype */            \
-    bFirstInterface,                                       /* bmCapabilities */                \
-    (uint8_t)(bFirstInterface + 1),                        /* bDataInterface */                \
-    0x04,                                                  /* bLength */                       \
-    CDC_CS_INTERFACE,                                      /* bDescriptorType */               \
-    CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT,             /* bDescriptorSubtype */            \
-    0x02,                                                  /* bmCapabilities */                \
-    0x05,                                                  /* bLength */                       \
-    CDC_CS_INTERFACE,                                      /* bDescriptorType */               \
-    CDC_FUNC_DESC_UNION,                                   /* bDescriptorSubtype */            \
-    bFirstInterface,                                       /* bMasterInterface */              \
-    (uint8_t)(bFirstInterface + 1),                        /* bSlaveInterface0 */              \
-    0x07,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_ENDPOINT,                          /* bDescriptorType */               \
-    int_ep,                                                /* bEndpointAddress */              \
-    0x03,                                                  /* bmAttributes */                  \
-    0x00, 0x02,                                            /* wMaxPacketSize */                \
-    0x00,                                                  /* bInterval */                     \
-    0x09,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_INTERFACE,                         /* bDescriptorType */               \
-    (uint8_t)(bFirstInterface + 1),                        /* bInterfaceNumber */              \
-    0x00,                                                  /* bAlternateSetting */             \
-    0x02,                                                  /* bNumEndpoints */                 \
-    CDC_DATA_INTERFACE_CLASS,                              /* bInterfaceClass */               \
-    0x00,                                                  /* bInterfaceSubClass */            \
-    0x00,                                                  /* bInterfaceProtocol */            \
-    0x00,                                                  /* iInterface */                    \
-    0x07,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_ENDPOINT,                          /* bDescriptorType */               \
-    out_ep,                                                /* bEndpointAddress */              \
-    0x02,                                                  /* bmAttributes */                  \
-    0x00, 0x02,                                            /* wMaxPacketSize */                \
-    0x00,                                                  /* bInterval */                     \
-    0x07,                                                  /* bLength */                       \
-    USB_DESCRIPTOR_TYPE_ENDPOINT,                          /* bDescriptorType */               \
-    in_ep,                                                 /* bEndpointAddress */              \
-    0x02,                                                  /* bmAttributes */                  \
-    0x00, 0x02,                                            /* wMaxPacketSize */                \
-    0x00                                                   /* bInterval */
-#endif
-// clang-format on
-
-void usbd_cdc_add_acm_interface(usbd_class_t *class, usbd_interface_t *intf);
-
-void usbd_cdc_acm_set_line_coding(uint32_t baudrate, uint8_t databits, uint8_t parity, uint8_t stopbits);
-void usbd_cdc_acm_set_dtr(bool dtr);
-void usbd_cdc_acm_set_rts(bool rts);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* USB_CDC_H_ */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c
deleted file mode 100644
index 5e66d18b0..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.c
+++ /dev/null
@@ -1,286 +0,0 @@
-/**
- * @file usbd_hid.c
- * @brief
- *
- * Copyright (c) 2021 Bouffalolab team
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.  The
- * ASF licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the
- * License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
- * License for the specific language governing permissions and limitations
- * under the License.
- *
- */
-#include "usbd_core.h"
-#include "usbd_hid.h"
-
-#define HID_STATE_IDLE 0
-#define HID_STATE_BUSY 1
-
-struct usbd_hid_cfg_private {
-    const uint8_t *hid_descriptor;
-    const uint8_t *hid_report_descriptor;
-    uint32_t hid_report_descriptor_len;
-    uint8_t current_intf_num;
-    uint8_t hid_state;
-    uint8_t report;
-    uint8_t idle_state;
-    uint8_t protocol;
-
-    uint8_t (*get_report_callback)(uint8_t report_id, uint8_t report_type);
-    void (*set_report_callback)(uint8_t report_id, uint8_t report_type, uint8_t *report, uint8_t report_len);
-    uint8_t (*get_idle_callback)(uint8_t report_id);
-    void (*set_idle_callback)(uint8_t report_id, uint8_t duration);
-    void (*set_protocol_callback)(uint8_t protocol);
-    uint8_t (*get_protocol_callback)(void);
-
-    usb_slist_t list;
-} usbd_hid_cfg[4];
-
-static usb_slist_t usbd_hid_class_head = USB_SLIST_OBJECT_INIT(usbd_hid_class_head);
-
-static void usbd_hid_reset(void)
-{
-    usb_slist_t *i;
-    usb_slist_for_each(i, &usbd_hid_class_head)
-    {
-        struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
-        hid_intf->hid_state = HID_STATE_IDLE;
-        hid_intf->report = 0;
-        hid_intf->idle_state = 0;
-        hid_intf->protocol = 0;
-    }
-}
-
-int hid_custom_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("HID Custom request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    if (REQTYPE_GET_DIR(setup->bmRequestType) == USB_REQUEST_DEVICE_TO_HOST &&
-        setup->bRequest == USB_REQUEST_GET_DESCRIPTOR) {
-        uint8_t value = (uint8_t)(setup->wValue >> 8);
-        uint8_t intf_num = (uint8_t)setup->wIndex;
-
-        struct usbd_hid_cfg_private *current_hid_intf = NULL;
-        usb_slist_t *i;
-        usb_slist_for_each(i, &usbd_hid_class_head)
-        {
-            struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
-
-            if (hid_intf->current_intf_num == intf_num) {
-                current_hid_intf = hid_intf;
-                break;
-            }
-        }
-
-        if (current_hid_intf == NULL) {
-            return -2;
-        }
-
-        switch (value) {
-            case HID_DESCRIPTOR_TYPE_HID:
-                USBD_LOG_INFO("get HID Descriptor\r\n");
-                *data = (uint8_t *)current_hid_intf->hid_descriptor;
-                *len = current_hid_intf->hid_descriptor[0];
-                break;
-
-            case HID_DESCRIPTOR_TYPE_HID_REPORT:
-                USBD_LOG_INFO("get Report Descriptor\r\n");
-                *data = (uint8_t *)current_hid_intf->hid_report_descriptor;
-                *len = current_hid_intf->hid_report_descriptor_len;
-                break;
-
-            case HID_DESCRIPTOR_TYPE_HID_PHYSICAL:
-                USBD_LOG_INFO("get PHYSICAL Descriptor\r\n");
-
-                break;
-
-            default:
-                return -2;
-        }
-
-        return 0;
-    }
-
-    return -1;
-}
-
-int hid_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("HID Class request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    struct usbd_hid_cfg_private *current_hid_intf = NULL;
-    usb_slist_t *i;
-    usb_slist_for_each(i, &usbd_hid_class_head)
-    {
-        struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
-        uint8_t intf_num = (uint8_t)setup->wIndex;
-        if (hid_intf->current_intf_num == intf_num) {
-            current_hid_intf = hid_intf;
-            break;
-        }
-    }
-
-    if (current_hid_intf == NULL) {
-        return -2;
-    }
-
-    switch (setup->bRequest) {
-        case HID_REQUEST_GET_REPORT:
-            if (current_hid_intf->get_report_callback)
-                current_hid_intf->report = current_hid_intf->get_report_callback(setup->wValueL, setup->wValueH); /*report id ,report type*/
-
-            *data = (uint8_t *)¤t_hid_intf->report;
-            *len = 1;
-            break;
-        case HID_REQUEST_GET_IDLE:
-            if (current_hid_intf->get_idle_callback)
-                current_hid_intf->idle_state = current_hid_intf->get_idle_callback(setup->wValueL);
-
-            *data = (uint8_t *)¤t_hid_intf->idle_state;
-            *len = 1;
-            break;
-        case HID_REQUEST_GET_PROTOCOL:
-            if (current_hid_intf->get_protocol_callback)
-                current_hid_intf->protocol = current_hid_intf->get_protocol_callback();
-
-            *data = (uint8_t *)¤t_hid_intf->protocol;
-            *len = 1;
-            break;
-        case HID_REQUEST_SET_REPORT:
-            if (current_hid_intf->set_report_callback)
-                current_hid_intf->set_report_callback(setup->wValueL, setup->wValueH, *data, *len); /*report id ,report type,report,report len*/
-
-            current_hid_intf->report = **data;
-            break;
-        case HID_REQUEST_SET_IDLE:
-            if (current_hid_intf->set_idle_callback)
-                current_hid_intf->set_idle_callback(setup->wValueL, setup->wIndexH); /*report id ,duration*/
-
-            current_hid_intf->idle_state = setup->wIndexH;
-            break;
-        case HID_REQUEST_SET_PROTOCOL:
-            if (current_hid_intf->set_protocol_callback)
-                current_hid_intf->set_protocol_callback(setup->wValueL); /*protocol*/
-
-            current_hid_intf->protocol = setup->wValueL;
-            break;
-
-        default:
-            USBD_LOG_WRN("Unhandled HID Class bRequest 0x%02x\r\n", setup->bRequest);
-            return -1;
-    }
-
-    return 0;
-}
-
-static void hid_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
-            usbd_hid_reset();
-            break;
-
-        default:
-            break;
-    }
-}
-
-void usbd_hid_reset_state(void)
-{
-    // usbd_hid_cfg.hid_state = HID_STATE_IDLE;
-}
-
-void usbd_hid_send_report(uint8_t ep, uint8_t *data, uint8_t len)
-{
-    // if(usbd_hid_cfg.hid_state == HID_STATE_IDLE)
-    // {
-    //     usbd_hid_cfg.hid_state = HID_STATE_BUSY;
-    //     usbd_ep_write(ep, data, len, NULL);
-    // }
-}
-
-void usbd_hid_descriptor_register(uint8_t intf_num, const uint8_t *desc)
-{
-    // usbd_hid_cfg.hid_descriptor = desc;
-}
-
-void usbd_hid_report_descriptor_register(uint8_t intf_num, const uint8_t *desc, uint32_t desc_len)
-{
-    usb_slist_t *i;
-    usb_slist_for_each(i, &usbd_hid_class_head)
-    {
-        struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
-
-        if (hid_intf->current_intf_num == intf_num) {
-            hid_intf->hid_report_descriptor = desc;
-            hid_intf->hid_report_descriptor_len = desc_len;
-            return;
-        }
-    }
-}
-// clang-format off
-void usbd_hid_set_request_callback( uint8_t intf_num,
-                                    uint8_t (*get_report_callback)(uint8_t report_id, uint8_t report_type),
-                                    void (*set_report_callback)(uint8_t report_id, uint8_t report_type, uint8_t *report, uint8_t report_len),
-                                    uint8_t (*get_idle_callback)(uint8_t report_id),
-                                    void (*set_idle_callback)(uint8_t report_id, uint8_t duration),
-                                    void (*set_protocol_callback)(uint8_t protocol),
-                                    uint8_t (*get_protocol_callback)(void))
-// clang-format on
-{
-    usb_slist_t *i;
-    usb_slist_for_each(i, &usbd_hid_class_head)
-    {
-        struct usbd_hid_cfg_private *hid_intf = usb_slist_entry(i, struct usbd_hid_cfg_private, list);
-
-        if (hid_intf->current_intf_num == intf_num) {
-            if (get_report_callback)
-                hid_intf->get_report_callback = get_report_callback;
-            if (set_report_callback)
-                hid_intf->set_report_callback = set_report_callback;
-            if (get_idle_callback)
-                hid_intf->get_idle_callback = get_idle_callback;
-            if (set_idle_callback)
-                hid_intf->set_idle_callback = set_idle_callback;
-            if (set_protocol_callback)
-                hid_intf->set_protocol_callback = set_protocol_callback;
-            if (get_protocol_callback)
-                hid_intf->get_protocol_callback = get_protocol_callback;
-            return;
-        }
-    }
-}
-
-void usbd_hid_add_interface(usbd_class_t *class, usbd_interface_t *intf)
-{
-    static usbd_class_t *last_class = NULL;
-    static uint8_t hid_num = 0;
-    if (last_class != class) {
-        last_class = class;
-        usbd_class_register(class);
-    }
-
-    intf->class_handler = hid_class_request_handler;
-    intf->custom_handler = hid_custom_request_handler;
-    intf->vendor_handler = NULL;
-    intf->notify_handler = hid_notify_handler;
-    usbd_class_add_interface(class, intf);
-
-    usbd_hid_cfg[hid_num].current_intf_num = intf->intf_num;
-    usb_slist_add_tail(&usbd_hid_class_head, &usbd_hid_cfg[hid_num].list);
-    hid_num++;
-}
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.h
deleted file mode 100644
index 9319e7f2c..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/hid/usbd_hid.h
+++ /dev/null
@@ -1,360 +0,0 @@
-/**
- * @file
- * @brief USB Human Interface Device (HID) Class public header
- *
- * Header follows Device Class Definition for Human Interface Devices (HID)
- * Version 1.11 document (HID1_11-1.pdf).
- */
-#ifndef _USBD_HID_H_
-#define _USBD_HID_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* HID Protocol Codes */
-#define HID_PROTOCOL_NONE     0x00
-#define HID_PROTOCOL_BOOT     0x00
-#define HID_PROTOCOL_KEYBOARD 0x01
-#define HID_PROTOCOL_REPORT   0x01
-#define HID_PROTOCOL_MOUSE    0x02
-
-/* HID Class Descriptor Types */
-#define HID_DESCRIPTOR_TYPE_HID          0x21
-#define HID_DESCRIPTOR_TYPE_HID_REPORT   0x22
-#define HID_DESCRIPTOR_TYPE_HID_PHYSICAL 0x23
-
-/* HID Class Specific Requests */
-#define HID_REQUEST_GET_REPORT   0x01
-#define HID_REQUEST_GET_IDLE     0x02
-#define HID_REQUEST_GET_PROTOCOL 0x03
-#define HID_REQUEST_SET_REPORT   0x09
-#define HID_REQUEST_SET_IDLE     0x0A
-#define HID_REQUEST_SET_PROTOCOL 0x0B
-
-/* HID Report Types */
-#define HID_REPORT_INPUT   0x01
-#define HID_REPORT_OUTPUT  0x02
-#define HID_REPORT_FEATURE 0x03
-
-/* HID Report Definitions */
-struct usb_hid_class_subdescriptor {
-    uint8_t bDescriptorType;
-    uint16_t wDescriptorLength;
-} __packed;
-
-struct usb_hid_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint16_t bcdHID;
-    uint8_t bCountryCode;
-    uint8_t bNumDescriptors;
-
-    /*
-     * Specification says at least one Class Descriptor needs to
-     * be present (Report Descriptor).
-     */
-    struct usb_hid_class_subdescriptor subdesc[1];
-} __packed;
-
-/* HID Items types */
-#define ITEM_MAIN   0x0
-#define ITEM_GLOBAL 0x1
-#define ITEM_LOCAL  0x2
-
-/* HID Main Items tags */
-#define ITEM_TAG_INPUT          0x8
-#define ITEM_TAG_OUTPUT         0x9
-#define ITEM_TAG_COLLECTION     0xA
-#define ITEM_TAG_COLLECTION_END 0xC
-
-/* HID Global Items tags */
-#define ITEM_TAG_USAGE_PAGE   0x0
-#define ITEM_TAG_LOGICAL_MIN  0x1
-#define ITEM_TAG_LOGICAL_MAX  0x2
-#define ITEM_TAG_REPORT_SIZE  0x7
-#define ITEM_TAG_REPORT_ID    0x8
-#define ITEM_TAG_REPORT_COUNT 0x9
-
-/* HID Local Items tags */
-#define ITEM_TAG_USAGE     0x0
-#define ITEM_TAG_USAGE_MIN 0x1
-#define ITEM_TAG_USAGE_MAX 0x2
-
-#define HID_ITEM(bTag, bType, bSize) (((bTag & 0xF) << 4) | \
-                                      ((bType & 0x3) << 2) | (bSize & 0x3))
-
-#define HID_MAIN_ITEM(bTag, bSize)   HID_ITEM(bTag, ITEM_MAIN, bSize)
-#define HID_GLOBAL_ITEM(bTag, bSize) HID_ITEM(bTag, ITEM_GLOBAL, bSize)
-#define HID_LOCAL_ITEM(bTag, bSize)  HID_ITEM(bTag, ITEM_LOCAL, bSize)
-
-#define HID_MI_COLLECTION     HID_MAIN_ITEM(ITEM_TAG_COLLECTION, 1)
-#define HID_MI_COLLECTION_END HID_MAIN_ITEM(ITEM_TAG_COLLECTION_END, \
-                                            0)
-#define HID_MI_INPUT  HID_MAIN_ITEM(ITEM_TAG_INPUT, 1)
-#define HID_MI_OUTPUT HID_MAIN_ITEM(ITEM_TAG_OUTPUT, 1)
-
-#define HID_GI_USAGE_PAGE        HID_GLOBAL_ITEM(ITEM_TAG_USAGE_PAGE, 1)
-#define HID_GI_LOGICAL_MIN(size) HID_GLOBAL_ITEM(ITEM_TAG_LOGICAL_MIN, \
-                                                 size)
-#define HID_GI_LOGICAL_MAX(size) HID_GLOBAL_ITEM(ITEM_TAG_LOGICAL_MAX, \
-                                                 size)
-#define HID_GI_REPORT_SIZE HID_GLOBAL_ITEM(ITEM_TAG_REPORT_SIZE, \
-                                           1)
-#define HID_GI_REPORT_ID HID_GLOBAL_ITEM(ITEM_TAG_REPORT_ID, \
-                                         1)
-#define HID_GI_REPORT_COUNT HID_GLOBAL_ITEM(ITEM_TAG_REPORT_COUNT, \
-                                            1)
-
-#define HID_LI_USAGE           HID_LOCAL_ITEM(ITEM_TAG_USAGE, 1)
-#define HID_LI_USAGE_MIN(size) HID_LOCAL_ITEM(ITEM_TAG_USAGE_MIN, \
-                                              size)
-#define HID_LI_USAGE_MAX(size) HID_LOCAL_ITEM(ITEM_TAG_USAGE_MAX, \
-                                              size)
-
-/* Defined in Universal Serial Bus HID Usage Tables version 1.11 */
-#define USAGE_GEN_DESKTOP  0x01
-#define USAGE_GEN_KEYBOARD 0x07
-#define USAGE_GEN_LEDS     0x08
-#define USAGE_GEN_BUTTON   0x09
-
-/* Generic Desktop Page usages */
-#define USAGE_GEN_DESKTOP_UNDEFINED 0x00
-#define USAGE_GEN_DESKTOP_POINTER   0x01
-#define USAGE_GEN_DESKTOP_MOUSE     0x02
-#define USAGE_GEN_DESKTOP_JOYSTICK  0x04
-#define USAGE_GEN_DESKTOP_GAMEPAD   0x05
-#define USAGE_GEN_DESKTOP_KEYBOARD  0x06
-#define USAGE_GEN_DESKTOP_KEYPAD    0x07
-#define USAGE_GEN_DESKTOP_X         0x30
-#define USAGE_GEN_DESKTOP_Y         0x31
-#define USAGE_GEN_DESKTOP_WHEEL     0x38
-
-/* Collection types */
-#define COLLECTION_PHYSICAL    0x00
-#define COLLECTION_APPLICATION 0x01
-
-/* Example HID report descriptors */
-/**
- * @brief Simple HID mouse report descriptor for n button mouse.
- *
- * @param bcnt  Button count. Allowed values from 1 to 8.
- */
-#define HID_MOUSE_REPORT_DESC(bcnt)                                                                                          \
-    {                                                                                                                        \
-        /* USAGE_PAGE (Generic Desktop) */                                                                                   \
-        HID_GI_USAGE_PAGE, USAGE_GEN_DESKTOP,                                             /* USAGE (Mouse) */                \
-            HID_LI_USAGE, USAGE_GEN_DESKTOP_MOUSE,                                        /* COLLECTION (Application) */     \
-            HID_MI_COLLECTION, COLLECTION_APPLICATION,                                    /* USAGE (Pointer) */              \
-            HID_LI_USAGE, USAGE_GEN_DESKTOP_POINTER,                                      /* COLLECTION (Physical) */        \
-            HID_MI_COLLECTION, COLLECTION_PHYSICAL, /* Bits used for button signalling */ /* USAGE_PAGE (Button) */          \
-            HID_GI_USAGE_PAGE, USAGE_GEN_BUTTON,                                          /* USAGE_MINIMUM (Button 1) */     \
-            HID_LI_USAGE_MIN(1), 0x01,                                                    /* USAGE_MAXIMUM (Button bcnt) */  \
-            HID_LI_USAGE_MAX(1), bcnt,                                                    /* LOGICAL_MINIMUM (0) */          \
-            HID_GI_LOGICAL_MIN(1), 0x00,                                                  /* LOGICAL_MAXIMUM (1) */          \
-            HID_GI_LOGICAL_MAX(1), 0x01,                                                  /* REPORT_SIZE (1) */              \
-            HID_GI_REPORT_SIZE, 0x01,                                                     /* REPORT_COUNT (bcnt) */          \
-            HID_GI_REPORT_COUNT, bcnt,                                                    /* INPUT (Data,Var,Abs) */         \
-            HID_MI_INPUT, 0x02, /* Unused bits */                                         /* REPORT_SIZE (8 - bcnt) */       \
-            HID_GI_REPORT_SIZE, (8 - bcnt),                                               /* REPORT_COUNT (1) */             \
-            HID_GI_REPORT_COUNT, 0x01,                                                    /* INPUT (Cnst,Ary,Abs) */         \
-            HID_MI_INPUT, 0x01, /* X and Y axis, scroll */                                /* USAGE_PAGE (Generic Desktop) */ \
-            HID_GI_USAGE_PAGE, USAGE_GEN_DESKTOP,                                         /* USAGE (X) */                    \
-            HID_LI_USAGE, USAGE_GEN_DESKTOP_X,                                            /* USAGE (Y) */                    \
-            HID_LI_USAGE, USAGE_GEN_DESKTOP_Y,                                            /* USAGE (WHEEL) */                \
-            HID_LI_USAGE, USAGE_GEN_DESKTOP_WHEEL,                                        /* LOGICAL_MINIMUM (-127) */       \
-            HID_GI_LOGICAL_MIN(1), -127,                                                  /* LOGICAL_MAXIMUM (127) */        \
-            HID_GI_LOGICAL_MAX(1), 127,                                                   /* REPORT_SIZE (8) */              \
-            HID_GI_REPORT_SIZE, 0x08,                                                     /* REPORT_COUNT (3) */             \
-            HID_GI_REPORT_COUNT, 0x03,                                                    /* INPUT (Data,Var,Rel) */         \
-            HID_MI_INPUT, 0x06,                                                           /* END_COLLECTION */               \
-            HID_MI_COLLECTION_END,                                                        /* END_COLLECTION */               \
-            HID_MI_COLLECTION_END,                                                                                           \
-    }
-
-/**
- * @brief Simple HID keyboard report descriptor.
- */
-#define HID_KEYBOARD_REPORT_DESC()                                                                  \
-    {                                                                                               \
-        /* USAGE_PAGE (Generic Desktop) */                                                          \
-        HID_GI_USAGE_PAGE, USAGE_GEN_DESKTOP,            /* USAGE (Keyboard) */                     \
-            HID_LI_USAGE, USAGE_GEN_DESKTOP_KEYBOARD,    /* COLLECTION (Application) */             \
-            HID_MI_COLLECTION, COLLECTION_APPLICATION,   /* USAGE_PAGE (Keypad) */                  \
-            HID_GI_USAGE_PAGE, USAGE_GEN_DESKTOP_KEYPAD, /* USAGE_MINIMUM (Keyboard LeftControl) */ \
-            HID_LI_USAGE_MIN(1), 0xE0,                   /* USAGE_MAXIMUM (Keyboard Right GUI) */   \
-            HID_LI_USAGE_MAX(1), 0xE7,                   /* LOGICAL_MINIMUM (0) */                  \
-            HID_GI_LOGICAL_MIN(1), 0x00,                 /* LOGICAL_MAXIMUM (1) */                  \
-            HID_GI_LOGICAL_MAX(1), 0x01,                 /* REPORT_SIZE (1) */                      \
-            HID_GI_REPORT_SIZE, 0x01,                    /* REPORT_COUNT (8) */                     \
-            HID_GI_REPORT_COUNT, 0x08,                   /* INPUT (Data,Var,Abs) */                 \
-            HID_MI_INPUT, 0x02,                          /* REPORT_SIZE (8) */                      \
-            HID_GI_REPORT_SIZE, 0x08,                    /* REPORT_COUNT (1) */                     \
-            HID_GI_REPORT_COUNT, 0x01,                   /* INPUT (Cnst,Var,Abs) */                 \
-            HID_MI_INPUT, 0x03,                          /* REPORT_SIZE (1) */                      \
-            HID_GI_REPORT_SIZE, 0x01,                    /* REPORT_COUNT (5) */                     \
-            HID_GI_REPORT_COUNT, 0x05,                   /* USAGE_PAGE (LEDs) */                    \
-            HID_GI_USAGE_PAGE, USAGE_GEN_LEDS,           /* USAGE_MINIMUM (Num Lock) */             \
-            HID_LI_USAGE_MIN(1), 0x01,                   /* USAGE_MAXIMUM (Kana) */                 \
-            HID_LI_USAGE_MAX(1), 0x05,                   /* OUTPUT (Data,Var,Abs) */                \
-            HID_MI_OUTPUT, 0x02,                         /* REPORT_SIZE (3) */                      \
-            HID_GI_REPORT_SIZE, 0x03,                    /* REPORT_COUNT (1) */                     \
-            HID_GI_REPORT_COUNT, 0x01,                   /* OUTPUT (Cnst,Var,Abs) */                \
-            HID_MI_OUTPUT, 0x03,                         /* REPORT_SIZE (8) */                      \
-            HID_GI_REPORT_SIZE, 0x08,                    /* REPORT_COUNT (6) */                     \
-            HID_GI_REPORT_COUNT, 0x06,                   /* LOGICAL_MINIMUM (0) */                  \
-            HID_GI_LOGICAL_MIN(1), 0x00,                 /* LOGICAL_MAXIMUM (101) */                \
-            HID_GI_LOGICAL_MAX(1), 0x65,                 /* USAGE_PAGE (Keypad) */                  \
-            HID_GI_USAGE_PAGE, USAGE_GEN_DESKTOP_KEYPAD, /* USAGE_MINIMUM (Reserved) */             \
-            HID_LI_USAGE_MIN(1), 0x00,                   /* USAGE_MAXIMUM (Keyboard Application) */ \
-            HID_LI_USAGE_MAX(1), 0x65,                   /* INPUT (Data,Ary,Abs) */                 \
-            HID_MI_INPUT, 0x00,                          /* END_COLLECTION */                       \
-            HID_MI_COLLECTION_END,                                                                  \
-    }
-
-/**
- * @brief HID keyboard button codes.
- */
-enum hid_kbd_code {
-    HID_KEY_A = 4,
-    HID_KEY_B = 5,
-    HID_KEY_C = 6,
-    HID_KEY_D = 7,
-    HID_KEY_E = 8,
-    HID_KEY_F = 9,
-    HID_KEY_G = 10,
-    HID_KEY_H = 11,
-    HID_KEY_I = 12,
-    HID_KEY_J = 13,
-    HID_KEY_K = 14,
-    HID_KEY_L = 15,
-    HID_KEY_M = 16,
-    HID_KEY_N = 17,
-    HID_KEY_O = 18,
-    HID_KEY_P = 19,
-    HID_KEY_Q = 20,
-    HID_KEY_R = 21,
-    HID_KEY_S = 22,
-    HID_KEY_T = 23,
-    HID_KEY_U = 24,
-    HID_KEY_V = 25,
-    HID_KEY_W = 26,
-    HID_KEY_X = 27,
-    HID_KEY_Y = 28,
-    HID_KEY_Z = 29,
-    HID_KEY_1 = 30,
-    HID_KEY_2 = 31,
-    HID_KEY_3 = 32,
-    HID_KEY_4 = 33,
-    HID_KEY_5 = 34,
-    HID_KEY_6 = 35,
-    HID_KEY_7 = 36,
-    HID_KEY_8 = 37,
-    HID_KEY_9 = 38,
-    HID_KEY_0 = 39,
-    HID_KEY_ENTER = 40,
-    HID_KEY_ESC = 41,
-    HID_KEY_BACKSPACE = 42,
-    HID_KEY_TAB = 43,
-    HID_KEY_SPACE = 44,
-    HID_KEY_MINUS = 45,
-    HID_KEY_EQUAL = 46,
-    HID_KEY_LEFTBRACE = 47,
-    HID_KEY_RIGHTBRACE = 48,
-    HID_KEY_BACKSLASH = 49,
-    HID_KEY_HASH = 50, /* Non-US # and ~ */
-    HID_KEY_SEMICOLON = 51,
-    HID_KEY_APOSTROPHE = 52,
-    HID_KEY_GRAVE = 53,
-    HID_KEY_COMMA = 54,
-    HID_KEY_DOT = 55,
-    HID_KEY_SLASH = 56,
-    HID_KEY_CAPSLOCK = 57,
-    HID_KEY_F1 = 58,
-    HID_KEY_F2 = 59,
-    HID_KEY_F3 = 60,
-    HID_KEY_F4 = 61,
-    HID_KEY_F5 = 62,
-    HID_KEY_F6 = 63,
-    HID_KEY_F7 = 64,
-    HID_KEY_F8 = 65,
-    HID_KEY_F9 = 66,
-    HID_KEY_F10 = 67,
-    HID_KEY_F11 = 68,
-    HID_KEY_F12 = 69,
-    HID_KEY_SYSRQ = 70, /* PRINTSCREEN */
-    HID_KEY_SCROLLLOCK = 71,
-    HID_KEY_PAUSE = 72,
-    HID_KEY_INSERT = 73,
-    HID_KEY_HOME = 74,
-    HID_KEY_PAGEUP = 75,
-    HID_KEY_DELETE = 76,
-    HID_KEY_END = 77,
-    HID_KEY_PAGEDOWN = 78,
-    HID_KEY_RIGHT = 79,
-    HID_KEY_LEFT = 80,
-    HID_KEY_DOWN = 81,
-    HID_KEY_UP = 82,
-    HID_KEY_NUMLOCK = 83,
-    HID_KEY_KPSLASH = 84,    /* NUMPAD DIVIDE */
-    HID_KEY_KPASTERISK = 85, /* NUMPAD MULTIPLY */
-    HID_KEY_KPMINUS = 86,
-    HID_KEY_KPPLUS = 87,
-    HID_KEY_KPENTER = 88,
-    HID_KEY_KP_1 = 89,
-    HID_KEY_KP_2 = 90,
-    HID_KEY_KP_3 = 91,
-    HID_KEY_KP_4 = 92,
-    HID_KEY_KP_5 = 93,
-    HID_KEY_KP_6 = 94,
-    HID_KEY_KP_7 = 95,
-    HID_KEY_KP_8 = 96,
-    HID_KEY_KP_9 = 97,
-    HID_KEY_KP_0 = 98,
-};
-
-/**
- * @brief HID keyboard modifiers.
- */
-enum hid_kbd_modifier {
-    HID_KBD_MODIFIER_NONE = 0x00,
-    HID_KBD_MODIFIER_LEFT_CTRL = 0x01,
-    HID_KBD_MODIFIER_LEFT_SHIFT = 0x02,
-    HID_KBD_MODIFIER_LEFT_ALT = 0x04,
-    HID_KBD_MODIFIER_LEFT_UI = 0x08,
-    HID_KBD_MODIFIER_RIGHT_CTRL = 0x10,
-    HID_KBD_MODIFIER_RIGHT_SHIFT = 0x20,
-    HID_KBD_MODIFIER_RIGHT_ALT = 0x40,
-    HID_KBD_MODIFIER_RIGHT_UI = 0x80,
-};
-
-/**
- * @brief HID keyboard LEDs.
- */
-enum hid_kbd_led {
-    HID_KBD_LED_NUM_LOCK = 0x01,
-    HID_KBD_LED_CAPS_LOCK = 0x02,
-    HID_KBD_LED_SCROLL_LOCK = 0x04,
-    HID_KBD_LED_COMPOSE = 0x08,
-    HID_KBD_LED_KANA = 0x10,
-};
-
-void usbd_hid_descriptor_register(uint8_t intf_num, const uint8_t *desc);
-void usbd_hid_report_descriptor_register(uint8_t intf_num, const uint8_t *desc, uint32_t desc_len);
-void usbd_hid_add_interface(usbd_class_t *class, usbd_interface_t *intf);
-void usbd_hid_reset_state(void);
-void usbd_hid_send_report(uint8_t ep, uint8_t *data, uint8_t len);
-// clang-format off
-void usbd_hid_set_request_callback( uint8_t intf_num,
-                                    uint8_t (*get_report_callback)(uint8_t report_id, uint8_t report_type),
-                                    void (*set_report_callback)(uint8_t report_id, uint8_t report_type, uint8_t *report, uint8_t report_len),
-                                    uint8_t (*get_idle_callback)(uint8_t report_id),
-                                    void (*set_idle_callback)(uint8_t report_id, uint8_t duration),
-                                    void (*set_protocol_callback)(uint8_t protocol),
-                                    uint8_t (*get_protocol_callback)(void));
-// clang-format on
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _USB_HID_H_ */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c
deleted file mode 100644
index 262adbb11..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.c
+++ /dev/null
@@ -1,1004 +0,0 @@
-/**
- * @file usbd_msc.c
- * @brief
- *
- * Copyright (c) 2021 Bouffalolab team
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.  The
- * ASF licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the
- * License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
- * License for the specific language governing permissions and limitations
- * under the License.
- *
- */
-#include "usbd_core.h"
-#include "usbd_scsi.h"
-#include "usbd_msc.h"
-
-/* max USB packet size */
-#ifndef CONFIG_USB_HS
-#define MASS_STORAGE_BULK_EP_MPS 64
-#else
-#define MASS_STORAGE_BULK_EP_MPS 512
-#endif
-
-#define MSD_OUT_EP_IDX 0
-#define MSD_IN_EP_IDX  1
-
-/* Describe EndPoints configuration */
-static usbd_endpoint_t mass_ep_data[2];
-
-/* MSC Bulk-only Stage */
-enum Stage {
-    MSC_READ_CBW = 0, /* Command Block Wrapper */
-    MSC_DATA_OUT = 1, /* Data Out Phase */
-    MSC_DATA_IN = 2,  /* Data In Phase */
-    MSC_SEND_CSW = 3, /* Command Status Wrapper */
-    MSC_WAIT_CSW = 4, /* Command Status Wrapper */
-};
-
-/** MSC Bulk-Only Command Block Wrapper (CBW) */
-struct CBW {
-    uint32_t dSignature;
-    uint32_t dTag;
-    uint32_t dDataLength;
-    uint8_t bmFlags;
-    uint8_t bLUN;
-    uint8_t bCBLength;
-    uint8_t CB[16];
-} __packed;
-
-/** MSC Bulk-Only Command Status Wrapper (CSW) */
-struct CSW {
-    uint32_t dSignature;
-    uint32_t dTag;
-    uint32_t dDataResidue;
-    uint8_t bStatus;
-} __packed;
-
-/* Device data structure */
-struct usbd_msc_cfg_private {
-    /* state of the bulk-only state machine */
-    enum Stage stage;
-    struct CBW cbw;
-    struct CSW csw;
-
-    uint8_t sKey; /* Sense key */
-    uint8_t ASC;  /* Additional Sense Code */
-    uint8_t ASQ;  /* Additional Sense Qualifier */
-    uint8_t max_lun;
-    uint16_t scsi_blk_size;
-    uint32_t scsi_blk_nbr;
-
-    uint32_t scsi_blk_addr;
-    uint32_t scsi_blk_len;
-    uint8_t *block_buffer;
-
-} usbd_msc_cfg;
-
-/*memory OK (after a usbd_msc_memory_verify)*/
-static bool memOK;
-
-static void usbd_msc_reset(void)
-{
-    usbd_msc_cfg.stage = MSC_READ_CBW;
-    usbd_msc_cfg.scsi_blk_addr = 0U;
-    usbd_msc_cfg.scsi_blk_len = 0U;
-    usbd_msc_cfg.max_lun = 0;
-    usbd_msc_cfg.sKey = 0;
-    usbd_msc_cfg.ASC = 0;
-    usbd_msc_cfg.ASQ = 0;
-
-    (void)memset((void *)&usbd_msc_cfg.cbw, 0, sizeof(struct CBW));
-    (void)memset((void *)&usbd_msc_cfg.csw, 0, sizeof(struct CSW));
-
-    usbd_msc_get_cap(0, &usbd_msc_cfg.scsi_blk_nbr, &usbd_msc_cfg.scsi_blk_size);
-
-    if (usbd_msc_cfg.block_buffer) {
-        free(usbd_msc_cfg.block_buffer);
-    }
-    usbd_msc_cfg.block_buffer = malloc(usbd_msc_cfg.scsi_blk_size * sizeof(uint8_t));
-    memset(usbd_msc_cfg.block_buffer, 0, usbd_msc_cfg.scsi_blk_size * sizeof(uint8_t));
-}
-
-/**
- * @brief Handler called for Class requests not handled by the USB stack.
- *
- * @param setup    Information about the request to execute.
- * @param len       Size of the buffer.
- * @param data      Buffer containing the request result.
- *
- * @return  0 on success, negative errno code on fail.
- */
-static int msc_storage_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("MSC Class request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    switch (setup->bRequest) {
-        case MSC_REQUEST_RESET:
-            USBD_LOG_DBG("MSC_REQUEST_RESET\r\n");
-
-            if (setup->wLength) {
-                USBD_LOG_WRN("Invalid length\r\n");
-                return -1;
-            }
-
-            usbd_msc_reset();
-            break;
-
-        case MSC_REQUEST_GET_MAX_LUN:
-            USBD_LOG_DBG("MSC_REQUEST_GET_MAX_LUN\r\n");
-
-            if (setup->wLength != 1) {
-                USBD_LOG_WRN("Invalid length\r\n");
-                return -1;
-            }
-
-            *data = (uint8_t *)(&usbd_msc_cfg.max_lun);
-            *len = 1;
-            break;
-
-        default:
-            USBD_LOG_WRN("Unhandled MSC Class bRequest 0x%02x\r\n", setup->bRequest);
-            return -1;
-    }
-
-    return 0;
-}
-
-static void usbd_msc_bot_abort(void)
-{
-    if ((usbd_msc_cfg.cbw.bmFlags == 0) && (usbd_msc_cfg.cbw.dDataLength != 0)) {
-        usbd_ep_set_stall(mass_ep_data[MSD_OUT_EP_IDX].ep_addr);
-    }
-    usbd_ep_set_stall(mass_ep_data[MSD_IN_EP_IDX].ep_addr);
-}
-
-static void sendCSW(uint8_t CSW_Status)
-{
-    usbd_msc_cfg.csw.dSignature = MSC_CSW_Signature;
-    usbd_msc_cfg.csw.bStatus = CSW_Status;
-
-    /* updating the State Machine , so that we wait CSW when this
-	 * transfer is complete, ie when we get a bulk in callback
-	 */
-    usbd_msc_cfg.stage = MSC_WAIT_CSW;
-
-    if (usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr, (uint8_t *)&usbd_msc_cfg.csw,
-                      sizeof(struct CSW), NULL) != 0) {
-        USBD_LOG_ERR("usb write failure\r\n");
-    }
-}
-
-static void sendLastData(uint8_t *buffer, uint8_t size)
-{
-    size = MIN(size, usbd_msc_cfg.cbw.dDataLength);
-
-    /* updating the State Machine , so that we send CSW when this
-	 * transfer is complete, ie when we get a bulk in callback
-	 */
-    usbd_msc_cfg.stage = MSC_SEND_CSW;
-
-    if (usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr, buffer, size, NULL) != 0) {
-        USBD_LOG_ERR("USB write failed\r\n");
-    }
-
-    usbd_msc_cfg.csw.dDataResidue -= size;
-    usbd_msc_cfg.csw.bStatus = CSW_STATUS_CMD_PASSED;
-}
-
-/**
- * @brief SCSI COMMAND
- */
-static bool SCSI_testUnitReady(uint8_t **data, uint32_t *len);
-static bool SCSI_requestSense(uint8_t **data, uint32_t *len);
-static bool SCSI_inquiry(uint8_t **data, uint32_t *len);
-static bool SCSI_startStopUnit(uint8_t **data, uint32_t *len);
-static bool SCSI_preventAllowMediaRemoval(uint8_t **data, uint32_t *len);
-static bool SCSI_modeSense6(uint8_t **data, uint32_t *len);
-static bool SCSI_modeSense10(uint8_t **data, uint32_t *len);
-static bool SCSI_readFormatCapacity(uint8_t **data, uint32_t *len);
-static bool SCSI_readCapacity10(uint8_t **data, uint32_t *len);
-static bool SCSI_read10(uint8_t **data, uint32_t *len);
-static bool SCSI_read12(uint8_t **data, uint32_t *len);
-static bool SCSI_write10(uint8_t **data, uint32_t *len);
-static bool SCSI_write12(uint8_t **data, uint32_t *len);
-static bool SCSI_verify10(uint8_t **data, uint32_t *len);
-
-/**
-* @brief  SCSI_SenseCode
-*         Load the last error code in the error list
-* @param  sKey: Sense Key
-* @param  ASC: Additional Sense Code
-* @retval none
-
-*/
-static void SCSI_SenseCode(uint8_t sKey, uint8_t ASC)
-{
-    usbd_msc_cfg.sKey = sKey;
-    usbd_msc_cfg.ASC = ASC;
-}
-
-static bool SCSI_processRead(void)
-{
-    uint32_t transfer_len;
-
-    USBD_LOG_DBG("read addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr);
-
-    transfer_len = MIN(usbd_msc_cfg.scsi_blk_len, MASS_STORAGE_BULK_EP_MPS);
-
-    /* we read an entire block */
-    if (!(usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size)) {
-        if (usbd_msc_sector_read((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) {
-            SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_UNRECOVERED_READ_ERROR);
-            return false;
-        }
-    }
-
-    usbd_ep_write(mass_ep_data[MSD_IN_EP_IDX].ep_addr,
-                  &usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size], transfer_len, NULL);
-
-    usbd_msc_cfg.scsi_blk_addr += transfer_len;
-    usbd_msc_cfg.scsi_blk_len -= transfer_len;
-    usbd_msc_cfg.csw.dDataResidue -= transfer_len;
-
-    if (usbd_msc_cfg.scsi_blk_len == 0) {
-        usbd_msc_cfg.stage = MSC_SEND_CSW;
-    }
-
-    return true;
-}
-
-static bool SCSI_processWrite(uint8_t *buf, uint16_t len)
-{
-    USBD_LOG_DBG("write addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr);
-
-    /* we fill an array in RAM of 1 block before writing it in memory */
-    for (int i = 0; i < len; i++) {
-        usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size + i] = buf[i];
-    }
-
-    /* if the array is filled, write it in memory */
-    if ((usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size) + len >= usbd_msc_cfg.scsi_blk_size) {
-        if (usbd_msc_sector_write((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) {
-            SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_WRITE_FAULT);
-            return false;
-        }
-    }
-
-    usbd_msc_cfg.scsi_blk_addr += len;
-    usbd_msc_cfg.scsi_blk_len -= len;
-    usbd_msc_cfg.csw.dDataResidue -= len;
-
-    if (usbd_msc_cfg.scsi_blk_len == 0) {
-        sendCSW(CSW_STATUS_CMD_PASSED);
-    }
-
-    return true;
-}
-
-static bool SCSI_processVerify(uint8_t *buf, uint16_t len)
-{
-    USBD_LOG_DBG("verify addr:%d\r\n", usbd_msc_cfg.scsi_blk_addr);
-
-    /* we read an entire block */
-    if (!(usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size)) {
-        if (usbd_msc_sector_read((usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size), usbd_msc_cfg.block_buffer, usbd_msc_cfg.scsi_blk_size) != 0) {
-            SCSI_SenseCode(SCSI_SENSE_HARDWARE_ERROR, SCSI_ASC_UNRECOVERED_READ_ERROR);
-            return false;
-        }
-    }
-
-    /* info are in RAM -> no need to re-read memory */
-    for (uint16_t i = 0U; i < len; i++) {
-        if (usbd_msc_cfg.block_buffer[usbd_msc_cfg.scsi_blk_addr % usbd_msc_cfg.scsi_blk_size + i] != buf[i]) {
-            USBD_LOG_DBG("Mismatch sector %d offset %d",
-                         usbd_msc_cfg.scsi_blk_addr / usbd_msc_cfg.scsi_blk_size, i);
-            memOK = false;
-            break;
-        }
-    }
-
-    usbd_msc_cfg.scsi_blk_addr += len;
-    usbd_msc_cfg.scsi_blk_len -= len;
-    usbd_msc_cfg.csw.dDataResidue -= len;
-
-    if (usbd_msc_cfg.scsi_blk_len == 0) {
-        sendCSW(CSW_STATUS_CMD_PASSED);
-    }
-
-    return true;
-}
-
-static bool SCSI_CBWDecode(uint8_t *buf, uint16_t size)
-{
-    uint8_t send_buffer[64];
-    uint8_t *buf2send = send_buffer;
-    uint32_t len2send = 0;
-    bool ret = false;
-
-    if (size != sizeof(struct CBW)) {
-        USBD_LOG_ERR("size != sizeof(cbw)\r\n");
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    memcpy((uint8_t *)&usbd_msc_cfg.cbw, buf, size);
-
-    usbd_msc_cfg.csw.dTag = usbd_msc_cfg.cbw.dTag;
-    usbd_msc_cfg.csw.dDataResidue = usbd_msc_cfg.cbw.dDataLength;
-
-    if ((usbd_msc_cfg.cbw.bLUN > 1) || (usbd_msc_cfg.cbw.dSignature != MSC_CBW_Signature) || (usbd_msc_cfg.cbw.bCBLength < 1) || (usbd_msc_cfg.cbw.bCBLength > 16)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    } else {
-        switch (usbd_msc_cfg.cbw.CB[0]) {
-            case SCSI_TEST_UNIT_READY:
-                ret = SCSI_testUnitReady(&buf2send, &len2send);
-                break;
-            case SCSI_REQUEST_SENSE:
-                ret = SCSI_requestSense(&buf2send, &len2send);
-                break;
-            case SCSI_INQUIRY:
-                ret = SCSI_inquiry(&buf2send, &len2send);
-                break;
-            case SCSI_START_STOP_UNIT:
-                ret = SCSI_startStopUnit(&buf2send, &len2send);
-                break;
-            case SCSI_PREVENT_ALLOW_MEDIA_REMOVAL:
-                ret = SCSI_preventAllowMediaRemoval(&buf2send, &len2send);
-                break;
-            case SCSI_MODE_SENSE6:
-                ret = SCSI_modeSense6(&buf2send, &len2send);
-                break;
-            case SCSI_MODE_SENSE10:
-                ret = SCSI_modeSense10(&buf2send, &len2send);
-                break;
-            case SCSI_READ_FORMAT_CAPACITIES:
-                ret = SCSI_readFormatCapacity(&buf2send, &len2send);
-                break;
-            case SCSI_READ_CAPACITY10:
-                ret = SCSI_readCapacity10(&buf2send, &len2send);
-                break;
-            case SCSI_READ10:
-                ret = SCSI_read10(NULL, 0);
-                break;
-            case SCSI_READ12:
-                ret = SCSI_read12(NULL, 0);
-                break;
-            case SCSI_WRITE10:
-                ret = SCSI_write10(NULL, 0);
-                break;
-            case SCSI_WRITE12:
-                ret = SCSI_write12(NULL, 0);
-                break;
-            case SCSI_VERIFY10:
-                ret = SCSI_verify10(NULL, 0);
-                break;
-
-            default:
-                SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-                USBD_LOG_WRN("unsupported cmd:0x%02x\r\n", usbd_msc_cfg.cbw.CB[0]);
-                ret = false;
-                break;
-        }
-    }
-    if (ret) {
-        if (usbd_msc_cfg.stage == MSC_READ_CBW) {
-            if (len2send) {
-                sendLastData(buf2send, len2send);
-            } else {
-                sendCSW(CSW_STATUS_CMD_PASSED);
-            }
-        }
-    }
-    return ret;
-}
-
-static bool SCSI_testUnitReady(uint8_t **data, uint32_t *len)
-{
-    if (usbd_msc_cfg.cbw.dDataLength != 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-    *data = NULL;
-    *len = 0;
-    return true;
-}
-
-static bool SCSI_requestSense(uint8_t **data, uint32_t *len)
-{
-    uint8_t data_len = REQUEST_SENSE_DATA_LEN;
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    if (usbd_msc_cfg.cbw.CB[4] < REQUEST_SENSE_DATA_LEN) {
-        data_len = usbd_msc_cfg.cbw.CB[4];
-    }
-
-    uint8_t request_sense[REQUEST_SENSE_DATA_LEN] = {
-        0x70,
-        0x00,
-        0x00, /* Sense Key */
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        REQUEST_SENSE_DATA_LEN - 8,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00, /* Additional Sense Code */
-        0x00, /* Additional Sense Request */
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-    };
-
-    request_sense[2] = usbd_msc_cfg.sKey;
-    request_sense[12] = usbd_msc_cfg.ASC;
-    request_sense[13] = usbd_msc_cfg.ASQ;
-#if 0
-    request_sense[ 2] = 0x06;           /* UNIT ATTENTION */
-    request_sense[12] = 0x28;           /* Additional Sense Code: Not ready to ready transition */
-    request_sense[13] = 0x00;           /* Additional Sense Code Qualifier */
-#endif
-#if 0
-    request_sense[ 2] = 0x02;           /* NOT READY */
-    request_sense[12] = 0x3A;           /* Additional Sense Code: Medium not present */
-    request_sense[13] = 0x00;           /* Additional Sense Code Qualifier */
-#endif
-#if 0
-    request_sense[ 2] = 0x05;         /* ILLEGAL REQUEST */
-    request_sense[12] = 0x20;         /* Additional Sense Code: Invalid command */
-    request_sense[13] = 0x00;         /* Additional Sense Code Qualifier */
-#endif
-#if 0
-    request_sense[ 2] = 0x00;         /* NO SENSE */
-    request_sense[12] = 0x00;         /* Additional Sense Code: No additional code */
-    request_sense[13] = 0x00;         /* Additional Sense Code Qualifier */
-#endif
-
-    memcpy(*data, (uint8_t *)&request_sense, data_len);
-    *len = data_len;
-    return true;
-}
-
-static bool SCSI_inquiry(uint8_t **data, uint32_t *len)
-{
-    uint8_t data_len = STANDARD_INQUIRY_DATA_LEN;
-
-    uint8_t inquiry00[6] = {
-        0x00,
-        0x00,
-        0x00,
-        (0x06 - 4U),
-        0x00,
-        0x80
-    };
-
-    /* USB Mass storage VPD Page 0x80 Inquiry Data for Unit Serial Number */
-    uint8_t inquiry80[8] = {
-        0x00,
-        0x80,
-        0x00,
-        0x08,
-        0x20, /* Put Product Serial number */
-        0x20,
-        0x20,
-        0x20
-    };
-
-    uint8_t inquiry[STANDARD_INQUIRY_DATA_LEN] = {
-        /* 36 */
-
-        /* LUN 0 */
-        0x00,
-        0x80,
-        0x02,
-        0x02,
-        (STANDARD_INQUIRY_DATA_LEN - 5),
-        0x00,
-        0x00,
-        0x00,
-        'B', 'o', 'u', 'f', 'f', 'a', 'l', 'o', /* Manufacturer : 8 bytes */
-        'P', 'r', 'o', 'd', 'u', 'c', 't', ' ', /* Product      : 16 Bytes */
-        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
-        '0', '.', '0', '1' /* Version      : 4 Bytes */
-    };
-
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    if ((usbd_msc_cfg.cbw.CB[1] & 0x01U) != 0U) { /* Evpd is set */
-        if (usbd_msc_cfg.cbw.CB[2] == 0U) {       /* Request for Supported Vital Product Data Pages*/
-            data_len = 0x06;
-            memcpy(*data, (uint8_t *)&inquiry00, data_len);
-        } else if (usbd_msc_cfg.cbw.CB[2] == 0x80U) { /* Request for VPD page 0x80 Unit Serial Number */
-            data_len = 0x08;
-            memcpy(*data, (uint8_t *)&inquiry80, data_len);
-        } else { /* Request Not supported */
-            SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_FIELED_IN_COMMAND);
-            return false;
-        }
-    } else {
-        if (usbd_msc_cfg.cbw.CB[4] < STANDARD_INQUIRY_DATA_LEN) {
-            data_len = usbd_msc_cfg.cbw.CB[4];
-        }
-        memcpy(*data, (uint8_t *)&inquiry, data_len);
-    }
-
-    *len = data_len;
-    return true;
-}
-
-static bool SCSI_startStopUnit(uint8_t **data, uint32_t *len)
-{
-    if (usbd_msc_cfg.cbw.dDataLength != 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x1U) /* START=1 */
-    {
-        //SCSI_MEDIUM_UNLOCKED;
-    } else if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x2U) /* START=0 and LOEJ Load Eject=1 */
-    {
-        //SCSI_MEDIUM_EJECTED;
-    } else if ((usbd_msc_cfg.cbw.CB[4] & 0x3U) == 0x3U) /* START=1 and LOEJ Load Eject=1 */
-    {
-        //SCSI_MEDIUM_UNLOCKED;
-    } else {
-    }
-
-    *data = NULL;
-    *len = 0;
-    return true;
-}
-
-static bool SCSI_preventAllowMediaRemoval(uint8_t **data, uint32_t *len)
-{
-    if (usbd_msc_cfg.cbw.dDataLength != 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-    if (usbd_msc_cfg.cbw.CB[4] == 0U) {
-        //SCSI_MEDIUM_UNLOCKED;
-    } else {
-        //SCSI_MEDIUM_LOCKED;
-    }
-    *data = NULL;
-    *len = 0;
-    return true;
-}
-
-static bool SCSI_modeSense6(uint8_t **data, uint32_t *len)
-{
-    uint8_t data_len = 4;
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-    if (usbd_msc_cfg.cbw.CB[4] < MODE_SENSE6_DATA_LEN) {
-        data_len = usbd_msc_cfg.cbw.CB[4];
-    }
-
-    uint8_t sense6[] = { 0x03, 0x00, 0x00, 0x00 };
-
-    memcpy(*data, (uint8_t *)&sense6, data_len);
-    *len = data_len;
-    return true;
-}
-
-static bool SCSI_modeSense10(uint8_t **data, uint32_t *len)
-{
-    uint8_t data_len = MODE_SENSE10_DATA_LEN;
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-    if (usbd_msc_cfg.cbw.CB[8] < MODE_SENSE10_DATA_LEN) {
-        data_len = usbd_msc_cfg.cbw.CB[8];
-    }
-
-    uint8_t sense10[MODE_SENSE10_DATA_LEN] = {
-        0x00,
-        0x26,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x08,
-        0x12,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00,
-        0x00
-    };
-    memcpy(*data, (uint8_t *)&sense10, data_len);
-    *len = data_len;
-    return true;
-}
-
-static bool SCSI_readFormatCapacity(uint8_t **data, uint32_t *len)
-{
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-    uint8_t capacity[READ_FORMAT_CAPACITY_DATA_LEN] = {
-        0x00,
-        0x00,
-        0x00,
-        0x08, /* Capacity List Length */
-        (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 24) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 16) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 8) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_nbr >> 0) & 0xff),
-
-        0x02, /* Descriptor Code: Formatted Media */
-        0x00,
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 8) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 0) & 0xff),
-    };
-
-    memcpy(*data, (uint8_t *)&capacity, READ_FORMAT_CAPACITY_DATA_LEN);
-    *len = READ_FORMAT_CAPACITY_DATA_LEN;
-    return true;
-}
-
-static bool SCSI_readCapacity10(uint8_t **data, uint32_t *len)
-{
-    if (usbd_msc_cfg.cbw.dDataLength == 0U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    uint8_t capacity[READ_CAPACITY10_DATA_LEN] = {
-        (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 24) & 0xff),
-        (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 16) & 0xff),
-        (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 8) & 0xff),
-        (uint8_t)(((usbd_msc_cfg.scsi_blk_nbr - 1) >> 0) & 0xff),
-
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 24) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 16) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 8) & 0xff),
-        (uint8_t)((usbd_msc_cfg.scsi_blk_size >> 0) & 0xff),
-    };
-
-    memcpy(*data, (uint8_t *)&capacity, READ_CAPACITY10_DATA_LEN);
-    *len = READ_CAPACITY10_DATA_LEN;
-    return true;
-}
-
-static bool SCSI_read10(uint8_t **data, uint32_t *len)
-{
-    /* Logical Block Address of First Block */
-    uint32_t lba = 0;
-    uint32_t blk_num = 0;
-    if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x80U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
-    USBD_LOG_DBG("lba: 0x%x\r\n", lba);
-
-    usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
-
-    /* Number of Blocks to transfer */
-    blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]);
-
-    USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
-    usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
-
-    if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
-        USBD_LOG_ERR("LBA out of range\r\n");
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ADDRESS_OUT_OF_RANGE);
-        return false;
-    }
-
-    if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
-        return false;
-    }
-    usbd_msc_cfg.stage = MSC_DATA_IN;
-    return SCSI_processRead();
-}
-
-static bool SCSI_read12(uint8_t **data, uint32_t *len)
-{
-    /* Logical Block Address of First Block */
-    uint32_t lba = 0;
-    uint32_t blk_num = 0;
-    if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x80U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
-    USBD_LOG_DBG("lba: 0x%x\r\n", lba);
-
-    usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
-
-    /* Number of Blocks to transfer */
-    blk_num = GET_BE32(&usbd_msc_cfg.cbw.CB[6]);
-
-    USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
-    usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
-
-    if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
-        USBD_LOG_ERR("LBA out of range\r\n");
-        return false;
-    }
-
-    if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
-        return false;
-    }
-    usbd_msc_cfg.stage = MSC_DATA_IN;
-    return SCSI_processRead();
-}
-
-static bool SCSI_write10(uint8_t **data, uint32_t *len)
-{
-    /* Logical Block Address of First Block */
-    uint32_t lba = 0;
-    uint32_t blk_num = 0;
-    if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
-    USBD_LOG_DBG("lba: 0x%x\r\n", lba);
-
-    usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
-
-    /* Number of Blocks to transfer */
-    blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]);
-
-    USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
-    usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
-
-    if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
-        USBD_LOG_ERR("LBA out of range\r\n");
-        return false;
-    }
-
-    if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
-        return false;
-    }
-    usbd_msc_cfg.stage = MSC_DATA_OUT;
-    return true;
-}
-
-static bool SCSI_write12(uint8_t **data, uint32_t *len)
-{
-    /* Logical Block Address of First Block */
-    uint32_t lba = 0;
-    uint32_t blk_num = 0;
-    if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
-    USBD_LOG_DBG("lba: 0x%x\r\n", lba);
-
-    usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
-
-    /* Number of Blocks to transfer */
-    blk_num = GET_BE32(&usbd_msc_cfg.cbw.CB[6]);
-
-    USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
-    usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
-
-    if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
-        USBD_LOG_ERR("LBA out of range\r\n");
-        return false;
-    }
-
-    if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
-        return false;
-    }
-    usbd_msc_cfg.stage = MSC_DATA_OUT;
-    return true;
-}
-
-static bool SCSI_verify10(uint8_t **data, uint32_t *len)
-{
-    /* Logical Block Address of First Block */
-    uint32_t lba = 0;
-    uint32_t blk_num = 0;
-
-    if ((usbd_msc_cfg.cbw.CB[1] & 0x02U) == 0x00U) {
-        return true;
-    }
-
-    if (((usbd_msc_cfg.cbw.bmFlags & 0x80U) != 0x00U) || (usbd_msc_cfg.cbw.dDataLength == 0U)) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_CDB);
-        return false;
-    }
-
-    if ((usbd_msc_cfg.cbw.CB[1] & 0x02U) == 0x02U) {
-        SCSI_SenseCode(SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INVALID_FIELED_IN_COMMAND);
-        return false; /* Error, Verify Mode Not supported*/
-    }
-
-    lba = GET_BE32(&usbd_msc_cfg.cbw.CB[2]);
-    USBD_LOG_DBG("lba: 0x%x\r\n", lba);
-
-    usbd_msc_cfg.scsi_blk_addr = lba * usbd_msc_cfg.scsi_blk_size;
-
-    /* Number of Blocks to transfer */
-    blk_num = GET_BE16(&usbd_msc_cfg.cbw.CB[7]);
-
-    USBD_LOG_DBG("num (block) : 0x%x\r\n", blk_num);
-    usbd_msc_cfg.scsi_blk_len = blk_num * usbd_msc_cfg.scsi_blk_size;
-
-    if ((lba + blk_num) > usbd_msc_cfg.scsi_blk_nbr) {
-        USBD_LOG_ERR("LBA out of range\r\n");
-        return false;
-    }
-
-    if (usbd_msc_cfg.cbw.dDataLength != usbd_msc_cfg.scsi_blk_len) {
-        return false;
-    }
-
-    memOK = true;
-    usbd_msc_cfg.stage = MSC_DATA_OUT;
-    return true;
-}
-
-static void mass_storage_bulk_out(uint8_t ep)
-{
-    uint8_t out_buf[MASS_STORAGE_BULK_EP_MPS];
-    uint32_t bytes_read;
-
-    usbd_ep_read(ep, out_buf, MASS_STORAGE_BULK_EP_MPS,
-                 &bytes_read);
-
-    switch (usbd_msc_cfg.stage) {
-        case MSC_READ_CBW:
-            if (SCSI_CBWDecode(out_buf, bytes_read) == false) {
-                USBD_LOG_ERR("Command:0x%02x decode err\r\n", usbd_msc_cfg.cbw.CB[0]);
-                usbd_msc_bot_abort();
-                return;
-            }
-            break;
-        /* last command is write10 or write12,and has caculated blk_addr and blk_len,so the device start reading data from host*/
-        case MSC_DATA_OUT:
-            switch (usbd_msc_cfg.cbw.CB[0]) {
-                case SCSI_WRITE10:
-                case SCSI_WRITE12:
-                    if (SCSI_processWrite(out_buf, bytes_read) == false) {
-                        sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/
-                        //return;
-                    }
-                    break;
-                case SCSI_VERIFY10:
-                    if (SCSI_processVerify(out_buf, bytes_read) == false) {
-                        sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/
-                        //return;
-                    }
-                    break;
-                default:
-                    break;
-            }
-            break;
-        default:
-            break;
-    }
-
-    /*set ep ack to recv next data*/
-    usbd_ep_read(ep, NULL, 0, NULL);
-}
-
-/**
- * @brief EP Bulk IN handler, used to send data to the Host
- *
- * @param ep        Endpoint address.
- * @param ep_status Endpoint status code.
- *
- * @return  N/A.
- */
-static void mass_storage_bulk_in(uint8_t ep)
-{
-    switch (usbd_msc_cfg.stage) {
-        /* last command is read10 or read12,and has caculated blk_addr and blk_len,so the device has to send remain data to host*/
-        case MSC_DATA_IN:
-            switch (usbd_msc_cfg.cbw.CB[0]) {
-                case SCSI_READ10:
-                case SCSI_READ12:
-                    if (SCSI_processRead() == false) {
-                        sendCSW(CSW_STATUS_CMD_FAILED); /* send fail status to host,and the host will retry*/
-                        return;
-                    }
-                    break;
-                default:
-                    break;
-            }
-
-            break;
-
-        /*the device has to send a CSW*/
-        case MSC_SEND_CSW:
-            sendCSW(CSW_STATUS_CMD_PASSED);
-            break;
-
-        /*the host has received the CSW*/
-        case MSC_WAIT_CSW:
-            usbd_msc_cfg.stage = MSC_READ_CBW;
-            break;
-
-        default:
-            break;
-    }
-}
-
-void msc_storage_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
-            usbd_msc_reset();
-            break;
-
-        default:
-            break;
-    }
-}
-
-static usbd_class_t msc_class;
-
-static usbd_interface_t msc_intf = {
-    .class_handler = msc_storage_class_request_handler,
-    .vendor_handler = NULL,
-    .notify_handler = msc_storage_notify_handler,
-};
-
-void usbd_msc_class_init(uint8_t out_ep, uint8_t in_ep)
-{
-    msc_class.name = "usbd_msc";
-
-    usbd_class_register(&msc_class);
-    usbd_class_add_interface(&msc_class, &msc_intf);
-
-    mass_ep_data[0].ep_addr = out_ep;
-    mass_ep_data[0].ep_cb = mass_storage_bulk_out;
-    mass_ep_data[1].ep_addr = in_ep;
-    mass_ep_data[1].ep_cb = mass_storage_bulk_in;
-
-    usbd_interface_add_endpoint(&msc_intf, &mass_ep_data[0]);
-    usbd_interface_add_endpoint(&msc_intf, &mass_ep_data[1]);
-}
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.h
deleted file mode 100644
index 3b5fe3e5c..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_msc.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * @file
- * @brief USB Mass Storage Class public header
- *
- * Header follows the Mass Storage Class Specification
- * (Mass_Storage_Specification_Overview_v1.4_2-19-2010.pdf) and
- * Mass Storage Class Bulk-Only Transport Specification
- * (usbmassbulk_10.pdf).
- * Header is limited to Bulk-Only Transfer protocol.
- */
-
-#ifndef _USBD_MSC_H__
-#define _USBD_MSC_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* MSC Subclass Codes */
-#define MSC_SUBCLASS_RBC           0x01
-#define MSC_SUBCLASS_SFF8020I_MMC2 0x02
-#define MSC_SUBCLASS_QIC157        0x03
-#define MSC_SUBCLASS_UFI           0x04
-#define MSC_SUBCLASS_SFF8070I      0x05
-#define MSC_SUBCLASS_SCSI          0x06
-
-/* MSC Protocol Codes */
-#define MSC_PROTOCOL_CBI_INT   0x00
-#define MSC_PROTOCOL_CBI_NOINT 0x01
-#define MSC_PROTOCOL_BULK_ONLY 0x50
-
-/* MSC Request Codes */
-#define MSC_REQUEST_RESET       0xFF
-#define MSC_REQUEST_GET_MAX_LUN 0xFE
-
-/** MSC Command Block Wrapper (CBW) Signature */
-#define MSC_CBW_Signature 0x43425355
-/** Bulk-only Command Status Wrapper (CSW) Signature */
-#define MSC_CSW_Signature 0x53425355
-
-/** MSC Command Block Status Values */
-#define CSW_STATUS_CMD_PASSED  0x00
-#define CSW_STATUS_CMD_FAILED  0x01
-#define CSW_STATUS_PHASE_ERROR 0x02
-
-/*Length of template descriptor: 23 bytes*/
-#define MSC_DESCRIPTOR_LEN (9 + 7 + 7)
-// clang-format off
-#ifndef SUPPORT_USB_HS
-#define MSC_DESCRIPTOR_INIT(bFirstInterface, out_ep, in_ep,str_idx) \
-    /* Interface */                                              \
-    0x09,                          /* bLength */                 \
-    USB_DESCRIPTOR_TYPE_INTERFACE, /* bDescriptorType */         \
-    bFirstInterface,               /* bInterfaceNumber */        \
-    0x00,                          /* bAlternateSetting */       \
-    0x02,                          /* bNumEndpoints */           \
-    USB_DEVICE_CLASS_MASS_STORAGE, /* bInterfaceClass */         \
-    MSC_SUBCLASS_SCSI,             /* bInterfaceSubClass */      \
-    MSC_PROTOCOL_BULK_ONLY,        /* bInterfaceProtocol */      \
-    str_idx,                       /* iInterface */              \
-    0x07,                          /* bLength */                 \
-    USB_DESCRIPTOR_TYPE_ENDPOINT,  /* bDescriptorType */         \
-    out_ep,                        /* bEndpointAddress */        \
-    0x02,                          /* bmAttributes */            \
-    0x40, 0x00,                    /* wMaxPacketSize */          \
-    0x00,                          /* bInterval */               \
-    0x07,                          /* bLength */                 \
-    USB_DESCRIPTOR_TYPE_ENDPOINT,  /* bDescriptorType */         \
-    in_ep,                         /* bEndpointAddress */        \
-    0x02,                          /* bmAttributes */            \
-    0x40, 0x00,                    /* wMaxPacketSize */          \
-    0x00                           /* bInterval */
-#else
-#define MSC_DESCRIPTOR_INIT(bFirstInterface, out_ep, in_ep,str_idx) \
-    /* Interface */                                              \
-    0x09,                          /* bLength */                 \
-    USB_DESCRIPTOR_TYPE_INTERFACE, /* bDescriptorType */         \
-    bFirstInterface,               /* bInterfaceNumber */        \
-    0x00,                          /* bAlternateSetting */       \
-    0x02,                          /* bNumEndpoints */           \
-    USB_DEVICE_CLASS_MASS_STORAGE, /* bInterfaceClass */         \
-    MSC_SUBCLASS_SCSI,             /* bInterfaceSubClass */      \
-    MSC_PROTOCOL_BULK_ONLY,        /* bInterfaceProtocol */      \
-    str_idx,                       /* iInterface */              \
-    0x07,                          /* bLength */                 \
-    USB_DESCRIPTOR_TYPE_ENDPOINT,  /* bDescriptorType */         \
-    out_ep,                        /* bEndpointAddress */        \
-    0x02,                          /* bmAttributes */            \
-    0x00, 0x02,                    /* wMaxPacketSize */          \
-    0x00,                          /* bInterval */               \
-    0x07,                          /* bLength */                 \
-    USB_DESCRIPTOR_TYPE_ENDPOINT,  /* bDescriptorType */         \
-    in_ep,                         /* bEndpointAddress */        \
-    0x02,                          /* bmAttributes */            \
-    0x00, 0x02,                    /* wMaxPacketSize */          \
-    0x00                           /* bInterval */
-#endif
-// clang-format on
-
-void usbd_msc_class_init(uint8_t out_ep, uint8_t in_ep);
-void usbd_msc_get_cap(uint8_t lun, uint32_t *block_num, uint16_t *block_size);
-int usbd_msc_sector_read(uint32_t sector, uint8_t *buffer, uint32_t length);
-int usbd_msc_sector_write(uint32_t sector, uint8_t *buffer, uint32_t length);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* USB_MSC_H_ */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_scsi.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_scsi.h
deleted file mode 100644
index 618d8f7ad..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/msc/usbd_scsi.h
+++ /dev/null
@@ -1,325 +0,0 @@
-/**
- * @file
- * @brief USB Mass Storage Class SCSI public header
- *
- * Header follows the Mass Storage Class Specification
- * (Mass_Storage_Specification_Overview_v1.4_2-19-2010.pdf) and
- * Mass Storage Class Bulk-Only Transport Specification
- * (usbmassbulk_10.pdf).
- * Header is limited to Bulk-Only Transfer protocol.
- */
-
-#ifndef _USBD_SCSI_H_
-#define _USBD_SCSI_H_
-
-/* SCSI Commands */
-#define SCSI_TEST_UNIT_READY             0x00
-#define SCSI_REQUEST_SENSE               0x03
-#define SCSI_FORMAT_UNIT                 0x04
-#define SCSI_INQUIRY                     0x12
-#define SCSI_MODE_SELECT6                0x15
-#define SCSI_MODE_SENSE6                 0x1A
-#define SCSI_START_STOP_UNIT             0x1B
-#define SCSI_SEND_DIAGNOSTIC             0x1D
-#define SCSI_PREVENT_ALLOW_MEDIA_REMOVAL 0x1E
-#define SCSI_READ_FORMAT_CAPACITIES      0x23
-#define SCSI_READ_CAPACITY10             0x25
-#define SCSI_READ10                      0x28
-#define SCSI_WRITE10                     0x2A
-#define SCSI_VERIFY10                    0x2F
-#define SCSI_SYNC_CACHE10                0x35
-#define SCSI_READ12                      0xA8
-#define SCSI_WRITE12                     0xAA
-#define SCSI_MODE_SELECT10               0x55
-#define SCSI_MODE_SENSE10                0x5A
-#define SCSI_ATA_COMMAND_PASS_THROUGH16  0x85
-#define SCSI_READ16                      0x88
-#define SCSI_WRITE16                     0x8A
-#define SCSI_VERIFY16                    0x8F
-#define SCSI_SYNC_CACHE16                0x91
-#define SCSI_SERVICE_ACTION_IN16         0x9E
-#define SCSI_READ_CAPACITY16             0x9E
-#define SCSI_SERVICE_ACTION_OUT16        0x9F
-#define SCSI_ATA_COMMAND_PASS_THROUGH12  0xA1
-#define SCSI_REPORT_ID_INFO              0xA3
-#define SCSI_READ12                      0xA8
-#define SCSI_SERVICE_ACTION_OUT12        0xA9
-#define SCSI_SERVICE_ACTION_IN12         0xAB
-#define SCSI_VERIFY12                    0xAF
-
-/* SCSI Sense Key */
-#define SCSI_SENSE_NONE            0x00
-#define SCSI_SENSE_RECOVERED_ERROR 0x01
-#define SCSI_SENSE_NOT_READY       0x02
-#define SCSI_SENSE_MEDIUM_ERROR    0x03
-#define SCSI_SENSE_HARDWARE_ERROR  0x04
-#define SCSI_SENSE_ILLEGAL_REQUEST 0x05
-#define SCSI_SENSE_UNIT_ATTENTION  0x06
-#define SCSI_SENSE_DATA_PROTECT    0x07
-#define SCSI_SENSE_FIRMWARE_ERROR  0x08
-#define SCSI_SENSE_ABORTED_COMMAND 0x0b
-#define SCSI_SENSE_EQUAL           0x0c
-#define SCSI_SENSE_VOLUME_OVERFLOW 0x0d
-#define SCSI_SENSE_MISCOMPARE      0x0e
-
-/* Additional Sense Code */
-#define SCSI_ASC_INVALID_CDB                     0x20U
-#define SCSI_ASC_INVALID_FIELED_IN_COMMAND       0x24U
-#define SCSI_ASC_PARAMETER_LIST_LENGTH_ERROR     0x1AU
-#define SCSI_ASC_INVALID_FIELD_IN_PARAMETER_LIST 0x26U
-#define SCSI_ASC_ADDRESS_OUT_OF_RANGE            0x21U
-#define SCSI_ASC_MEDIUM_NOT_PRESENT              0x3AU
-#define SCSI_ASC_MEDIUM_HAVE_CHANGED             0x28U
-#define SCSI_ASC_WRITE_PROTECTED                 0x27U
-#define SCSI_ASC_UNRECOVERED_READ_ERROR          0x11U
-#define SCSI_ASC_WRITE_FAULT                     0x03U
-
-#define READ_FORMAT_CAPACITY_DATA_LEN 0x0CU
-#define READ_CAPACITY10_DATA_LEN      0x08U
-#define REQUEST_SENSE_DATA_LEN        0x12U
-#define STANDARD_INQUIRY_DATA_LEN     0x24U
-#define MODE_SENSE6_DATA_LEN          0x17U
-#define MODE_SENSE10_DATA_LEN         0x1BU
-
-#define SCSI_MEDIUM_STATUS_UNLOCKED 0x00U
-#define SCSI_MEDIUM_STATUS_LOCKED   0x01U
-#define SCSI_MEDIUM_STATUS_EJECTED  0x02U
-
-//--------------------------------------------------------------------+
-// SCSI Primary Command (SPC-4)
-//--------------------------------------------------------------------+
-
-/// SCSI Test Unit Ready Command
-typedef struct __packed {
-    uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_TEST_UNIT_READY
-    uint8_t lun;      ///< Logical Unit
-    uint8_t reserved[3];
-    uint8_t control;
-} scsi_test_unit_ready_cmd_t;
-
-/// SCSI Inquiry Command
-typedef struct __packed {
-    uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_INQUIRY
-    uint8_t reserved1;
-    uint8_t page_code;
-    uint8_t reserved2;
-    uint8_t alloc_length; ///< specifies the maximum number of bytes that USB host has allocated in the Data-In Buffer. An allocation length of zero specifies that no data shall be transferred.
-    uint8_t control;
-} scsi_inquiry_cmd_t, scsi_request_sense_cmd_t;
-
-/// SCSI Inquiry Response Data
-typedef struct __packed {
-    uint8_t peripheral_device_type : 5;
-    uint8_t peripheral_qualifier   : 3;
-
-    uint8_t              : 7;
-    uint8_t is_removable : 1;
-
-    uint8_t version;
-
-    uint8_t response_data_format : 4;
-    uint8_t hierarchical_support : 1;
-    uint8_t normal_aca           : 1;
-    uint8_t                      : 2;
-
-    uint8_t additional_length;
-
-    uint8_t protect                    : 1;
-    uint8_t                            : 2;
-    uint8_t third_party_copy           : 1;
-    uint8_t target_port_group_support  : 2;
-    uint8_t access_control_coordinator : 1;
-    uint8_t scc_support                : 1;
-
-    uint8_t addr16            : 1;
-    uint8_t                   : 3;
-    uint8_t multi_port        : 1;
-    uint8_t                   : 1; // vendor specific
-    uint8_t enclosure_service : 1;
-    uint8_t                   : 1;
-
-    uint8_t         : 1; // vendor specific
-    uint8_t cmd_que : 1;
-    uint8_t         : 2;
-    uint8_t sync    : 1;
-    uint8_t wbus16  : 1;
-    uint8_t         : 2;
-
-    uint8_t vendor_id[8];   ///< 8 bytes of ASCII data identifying the vendor of the product.
-    uint8_t product_id[16]; ///< 16 bytes of ASCII data defined by the vendor.
-    uint8_t product_rev[4]; ///< 4 bytes of ASCII data defined by the vendor.
-} scsi_inquiry_resp_t;
-
-typedef struct __packed {
-    uint8_t response_code : 7; ///< 70h - current errors, Fixed Format 71h - deferred errors, Fixed Format
-    uint8_t valid         : 1;
-
-    uint8_t reserved;
-
-    uint8_t sense_key     : 4;
-    uint8_t               : 1;
-    uint8_t ili           : 1; ///< Incorrect length indicator
-    uint8_t end_of_medium : 1;
-    uint8_t filemark      : 1;
-
-    uint32_t information;
-    uint8_t add_sense_len;
-    uint32_t command_specific_info;
-    uint8_t add_sense_code;
-    uint8_t add_sense_qualifier;
-    uint8_t field_replaceable_unit_code;
-
-    uint8_t sense_key_specific[3]; ///< sense key specific valid bit is bit 7 of key[0], aka MSB in Big Endian layout
-
-} scsi_sense_fixed_resp_t;
-
-typedef struct __packed {
-    uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_MODE_SENSE_6
-
-    uint8_t                          : 3;
-    uint8_t disable_block_descriptor : 1;
-    uint8_t                          : 4;
-
-    uint8_t page_code    : 6;
-    uint8_t page_control : 2;
-
-    uint8_t subpage_code;
-    uint8_t alloc_length;
-    uint8_t control;
-} scsi_mode_sense6_cmd_t;
-
-// This is only a Mode parameter header(6).
-typedef struct __packed {
-    uint8_t data_len;
-    uint8_t medium_type;
-
-    uint8_t reserved     : 7;
-    bool write_protected : 1;
-
-    uint8_t block_descriptor_len;
-} scsi_mode_sense6_resp_t;
-
-typedef struct
-{
-    uint8_t cmd_code;
-
-    uint8_t reserved1                : 3;
-    uint8_t disable_block_descriptor : 1;
-    uint8_t long_LBA                 : 1;
-    uint8_t reserved2                : 3;
-
-    uint8_t page_code    : 6;
-    uint8_t page_control : 2;
-
-    uint8_t subpage_code;
-
-    uint8_t reserved3;
-    uint8_t reserved4;
-    uint8_t reserved5;
-
-    uint8_t length[2];
-
-    uint8_t control;
-} scsi_mode_sense_10_cmd_t;
-
-typedef struct
-{
-    uint8_t mode_data_length_high;
-    uint8_t mode_data_length_low;
-    uint8_t medium_type;
-
-    uint8_t reserved1     : 4;
-    uint8_t DPO_FUA       : 1; /**< [Disable Page Out] and [Force Unit Access] in the SCSI_READ10 command is valid or not */
-    uint8_t reserved2     : 2;
-    uint8_t write_protect : 1;
-
-    uint8_t long_LBA  : 1;
-    uint8_t reserved3 : 7;
-
-    uint8_t reserved4;
-    uint8_t block_desc_length[2];
-} scsi_mode_10_resp_t;
-
-typedef struct __packed {
-    uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL
-    uint8_t reserved[3];
-    uint8_t prohibit_removal;
-    uint8_t control;
-} scsi_prevent_allow_medium_removal_t;
-
-typedef struct __packed {
-    uint8_t cmd_code;
-
-    uint8_t immded : 1;
-    uint8_t        : 7;
-
-    uint8_t TU_RESERVED;
-
-    uint8_t power_condition_mod : 4;
-    uint8_t                     : 4;
-
-    uint8_t start           : 1;
-    uint8_t load_eject      : 1;
-    uint8_t no_flush        : 1;
-    uint8_t                 : 1;
-    uint8_t power_condition : 4;
-
-    uint8_t control;
-} scsi_start_stop_unit_cmd_t;
-
-//--------------------------------------------------------------------+
-// SCSI MMC
-//--------------------------------------------------------------------+
-/// SCSI Read Format Capacity: Write Capacity
-typedef struct __packed {
-    uint8_t cmd_code;
-    uint8_t reserved[6];
-    uint16_t alloc_length;
-    uint8_t control;
-} scsi_read_format_capacity_cmd_t;
-
-typedef struct __packed {
-    uint8_t reserved[3];
-    uint8_t list_length; /// must be 8*n, length in bytes of formattable capacity descriptor followed it.
-
-    uint32_t block_num;      /// Number of Logical Blocks
-    uint8_t descriptor_type; // 00: reserved, 01 unformatted media , 10 Formatted media, 11 No media present
-
-    uint8_t reserved2;
-    uint16_t block_size_u16;
-
-} scsi_read_format_capacity_resp_t;
-
-//--------------------------------------------------------------------+
-// SCSI Block Command (SBC-3)
-// NOTE: All data in SCSI command are in Big Endian
-//--------------------------------------------------------------------+
-
-/// SCSI Read Capacity 10 Command: Read Capacity
-typedef struct __packed {
-    uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_READ_CAPACITY_10
-    uint8_t reserved1;
-    uint32_t lba; ///< The first Logical Block Address (LBA) accessed by this command
-    uint16_t reserved2;
-    uint8_t partial_medium_indicator;
-    uint8_t control;
-} scsi_read_capacity10_cmd_t;
-
-/// SCSI Read Capacity 10 Response Data
-typedef struct
-{
-    uint32_t last_lba;   ///< The last Logical Block Address of the device
-    uint32_t block_size; ///< Block size in bytes
-} scsi_read_capacity10_resp_t;
-
-/// SCSI Read 10 Command
-typedef struct __packed {
-    uint8_t cmd_code; ///< SCSI OpCode
-    uint8_t reserved; // has LUN according to wiki
-    uint32_t lba;     ///< The first Logical Block Address (LBA) accessed by this command
-    uint8_t reserved2;
-    uint16_t block_count; ///< Number of Blocks used by this command
-    uint8_t control;
-} scsi_read10_t, scsi_write10_t, scsi_read_write_10_t;
-
-#endif /* ZEPHYR_INCLUDE_USB_CLASS_USB_CDC_H_ */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c
deleted file mode 100644
index 6eb2554ba..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.c
+++ /dev/null
@@ -1,134 +0,0 @@
-/**
- * @file usbd_video.c
- *
- * Copyright (c) 2021 Bouffalolab team
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.  The
- * ASF licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the
- * License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
- * License for the specific language governing permissions and limitations
- * under the License.
- *
- */
-#include "usbd_core.h"
-#include "usbd_video.h"
-
-extern struct video_probe_and_commit_controls probe;
-extern struct video_probe_and_commit_controls commit;
-
-int video_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("Video Class request: "
-                 "bRequest 0x%02x\r\n",
-                 setup->bRequest);
-
-    switch (setup->bRequest) {
-        case VIDEO_REQUEST_SET_CUR:
-            if (setup->wValue == 256) {
-                memcpy((uint8_t *)&probe, *data, setup->wLength);
-            } else if (setup->wValue == 512) {
-                memcpy((uint8_t *)&commit, *data, setup->wLength);
-            }
-
-            break;
-
-        case VIDEO_REQUEST_GET_CUR:
-            if (setup->wValue == 256) {
-                *data = (uint8_t *)&probe;
-            } else if (setup->wValue == 512) {
-                *data = (uint8_t *)&commit;
-            }
-
-            break;
-
-        case VIDEO_REQUEST_GET_MIN:
-            if (setup->wValue == 256) {
-                *data = (uint8_t *)&probe;
-            } else if (setup->wValue == 512) {
-                *data = (uint8_t *)&commit;
-            }
-
-            break;
-
-        case VIDEO_REQUEST_GET_MAX:
-            if (setup->wValue == 256) {
-                *data = (uint8_t *)&probe;
-            } else if (setup->wValue == 512) {
-                *data = (uint8_t *)&commit;
-            }
-
-            break;
-
-        case VIDEO_REQUEST_GET_RES:
-
-            break;
-
-        case VIDEO_REQUEST_GET_LEN:
-
-            break;
-
-        case VIDEO_REQUEST_GET_INFO:
-
-            break;
-
-        case VIDEO_REQUEST_GET_DEF:
-            if (setup->wLength == 256) {
-                *data = (uint8_t *)&probe;
-            } else if (setup->wLength == 512) {
-                *data = (uint8_t *)&commit;
-            }
-
-            break;
-
-        default:
-            USBD_LOG_WRN("Unhandled Video Class bRequest 0x%02x\r\n", setup->bRequest);
-            return -1;
-    }
-
-    return 0;
-}
-
-void video_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
-
-            break;
-
-        case USB_EVENT_SOF:
-            usbd_video_sof_callback();
-            break;
-
-        case USB_EVENT_SET_INTERFACE:
-            usbd_video_set_interface_callback(((uint8_t *)arg)[3]);
-            break;
-
-        default:
-            break;
-    }
-}
-
-void usbd_video_add_interface(usbd_class_t *class, usbd_interface_t *intf)
-{
-    static usbd_class_t *last_class = NULL;
-
-    if (last_class != class) {
-        last_class = class;
-        usbd_class_register(class);
-    }
-
-    intf->class_handler = video_class_request_handler;
-    intf->custom_handler = NULL;
-    intf->vendor_handler = NULL;
-    intf->notify_handler = video_notify_handler;
-    usbd_class_add_interface(class, intf);
-}
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.h
deleted file mode 100644
index 09c452f5f..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/video/usbd_video.h
+++ /dev/null
@@ -1,821 +0,0 @@
-/**
- * @file
- * @brief USB Video Device Class public header
- *
- * Header follows below documentation:
- * - USB Device Class Definition for Video Devices UVC 1.5 Class specification.pdf
- */
-
-#ifndef _USBD_VIDEO_H_
-#define _USBD_VIDEO_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define USB_DEVICE_VIDEO_CLASS_VERSION_1_5 0
-
-/*! @brief Video device subclass code */
-#define VIDEO_SC_UNDEFINED                  0x00U
-#define VIDEO_SC_VIDEOCONTROL               0x01U
-#define VIDEO_SC_VIDEOSTREAMING             0x02U
-#define VIDEO_SC_VIDEO_INTERFACE_COLLECTION 0x03U
-
-/*! @brief Video device protocol code */
-#define VIDEO_PC_PROTOCOL_UNDEFINED 0x00U
-#define VIDEO_PC_PROTOCOL_15        0x01U
-
-/*! @brief Video device class-specific descriptor type */
-#define VIDEO_CS_UNDEFINED_DESCRIPTOR_TYPE     0x20U
-#define VIDEO_CS_DEVICE_DESCRIPTOR_TYPE        0x21U
-#define VIDEO_CS_CONFIGURATION_DESCRIPTOR_TYPE 0x22U
-#define VIDEO_CS_STRING_DESCRIPTOR_TYPE        0x23U
-#define VIDEO_CS_INTERFACE_DESCRIPTOR_TYPE     0x24U
-#define VIDEO_CS_ENDPOINT_DESCRIPTOR_TYPE      0x25U
-
-/*! @brief Video device class-specific VC interface descriptor subtype */
-#define VIDEO_VC_DESCRIPTOR_UNDEFINED_DESCRIPTOR_SUBTYPE 0x00U
-#define VIDEO_VC_HEADER_DESCRIPTOR_SUBTYPE               0x01U
-#define VIDEO_VC_INPUT_TERMINAL_DESCRIPTOR_SUBTYPE       0x02U
-#define VIDEO_VC_OUTPUT_TERMINAL_DESCRIPTOR_SUBTYPE      0x03U
-#define VIDEO_VC_SELECTOR_UNIT_DESCRIPTOR_SUBTYPE        0x04U
-#define VIDEO_VC_PROCESSING_UNIT_DESCRIPTOR_SUBTYPE      0x05U
-#define VIDEO_VC_EXTENSION_UNIT_DESCRIPTOR_SUBTYPE       0x06U
-#define VIDEO_VC_ENCODING_UNIT_DESCRIPTOR_SUBTYPE        0x07U
-
-/*! @brief Video device class-specific VS interface descriptor subtype */
-#define VIDEO_VS_UNDEFINED_DESCRIPTOR_SUBTYPE             0x00U
-#define VIDEO_VS_INPUT_HEADER_DESCRIPTOR_SUBTYPE          0x01U
-#define VIDEO_VS_OUTPUT_HEADER_DESCRIPTOR_SUBTYPE         0x02U
-#define VIDEO_VS_STILL_IMAGE_FRAME_DESCRIPTOR_SUBTYPE     0x03U
-#define VIDEO_VS_FORMAT_UNCOMPRESSED_DESCRIPTOR_SUBTYPE   0x04U
-#define VIDEO_VS_FRAME_UNCOMPRESSED_DESCRIPTOR_SUBTYPE    0x05U
-#define VIDEO_VS_FORMAT_MJPEG_DESCRIPTOR_SUBTYPE          0x06U
-#define VIDEO_VS_FRAME_MJPEG_DESCRIPTOR_SUBTYPE           0x07U
-#define VIDEO_VS_FORMAT_MPEG2TS_DESCRIPTOR_SUBTYPE        0x0AU
-#define VIDEO_VS_FORMAT_DV_DESCRIPTOR_SUBTYPE             0x0CU
-#define VIDEO_VS_COLORFORMAT_DESCRIPTOR_SUBTYPE           0x0DU
-#define VIDEO_VS_FORMAT_FRAME_BASED_DESCRIPTOR_SUBTYPE    0x10U
-#define VIDEO_VS_FRAME_FRAME_BASED_DESCRIPTOR_SUBTYPE     0x11U
-#define VIDEO_VS_FORMAT_STREAM_BASED_DESCRIPTOR_SUBTYPE   0x12U
-#define VIDEO_VS_FORMAT_H264_DESCRIPTOR_SUBTYPE           0x13U
-#define VIDEO_VS_FRAME_H264_DESCRIPTOR_SUBTYPE            0x14U
-#define VIDEO_VS_FORMAT_H264_SIMULCAST_DESCRIPTOR_SUBTYPE 0x15U
-#define VIDEO_VS_FORMAT_VP8_DESCRIPTOR_SUBTYPE            0x16U
-#define VIDEO_VS_FRAME_VP8_DESCRIPTOR_SUBTYPE             0x17U
-#define VIDEO_VS_FORMAT_VP8_SIMULCAST_DESCRIPTOR_SUBTYPE  0x18U
-
-/*! @brief Video device class-specific VC endpoint descriptor subtype */
-#define VIDEO_EP_UNDEFINED_DESCRIPTOR_SUBTYPE 0x00U
-#define VIDEO_EP_GENERAL_DESCRIPTOR_SUBTYPE   0x01U
-#define VIDEO_EP_ENDPOINT_DESCRIPTOR_SUBTYPE  0x02U
-#define VIDEO_EP_INTERRUPT_DESCRIPTOR_SUBTYPE 0x03U
-
-/*! @brief Video device class-specific request code */
-#define VIDEO_REQUEST_UNDEFINED   0x00U
-#define VIDEO_REQUEST_SET_CUR     0x01U
-#define VIDEO_REQUEST_SET_CUR_ALL 0x11U
-#define VIDEO_REQUEST_GET_CUR     0x81U
-#define VIDEO_REQUEST_GET_MIN     0x82U
-#define VIDEO_REQUEST_GET_MAX     0x83U
-#define VIDEO_REQUEST_GET_RES     0x84U
-#define VIDEO_REQUEST_GET_LEN     0x85U
-#define VIDEO_REQUEST_GET_INFO    0x86U
-#define VIDEO_REQUEST_GET_DEF     0x87U
-#define VIDEO_REQUEST_GET_CUR_ALL 0x91U
-#define VIDEO_REQUEST_GET_MIN_ALL 0x92U
-#define VIDEO_REQUEST_GET_MAX_ALL 0x93U
-#define VIDEO_REQUEST_GET_RES_ALL 0x94U
-#define VIDEO_REQUEST_GET_DEF_ALL 0x97U
-
-/*! @brief Video device class-specific VideoControl interface control selector */
-#define VIDEO_VC_CONTROL_UNDEFINED          0x00U
-#define VIDEO_VC_VIDEO_POWER_MODE_CONTROL   0x01U
-#define VIDEO_VC_REQUEST_ERROR_CODE_CONTROL 0x02U
-
-/*! @brief Video device class-specific Terminal control selector */
-#define VIDEO_TE_CONTROL_UNDEFINED 0x00U
-
-/*! @brief Video device class-specific Selector Unit control selector */
-#define VIDEO_SU_CONTROL_UNDEFINED    0x00U
-#define VIDEO_SU_INPUT_SELECT_CONTROL 0x01U
-
-/*! @brief Video device class-specific Camera Terminal control selector */
-#define VIDEO_CT_CONTROL_UNDEFINED              0x00U
-#define VIDEO_CT_SCANNING_MODE_CONTROL          0x01U
-#define VIDEO_CT_AE_MODE_CONTROL                0x02U
-#define VIDEO_CT_AE_PRIORITY_CONTROL            0x03U
-#define VIDEO_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x04U
-#define VIDEO_CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x05U
-#define VIDEO_CT_FOCUS_ABSOLUTE_CONTROL         0x06U
-#define VIDEO_CT_FOCUS_RELATIVE_CONTROL         0x07U
-#define VIDEO_CT_FOCUS_AUTO_CONTROL             0x08U
-#define VIDEO_CT_IRIS_ABSOLUTE_CONTROL          0x09U
-#define VIDEO_CT_IRIS_RELATIVE_CONTROL          0x0AU
-#define VIDEO_CT_ZOOM_ABSOLUTE_CONTROL          0x0BU
-#define VIDEO_CT_ZOOM_RELATIVE_CONTROL          0x0CU
-#define VIDEO_CT_PANTILT_ABSOLUTE_CONTROL       0x0DU
-#define VIDEO_CT_PANTILT_RELATIVE_CONTROL       0x0EU
-#define VIDEO_CT_ROLL_ABSOLUTE_CONTROL          0x0FU
-#define VIDEO_CT_ROLL_RELATIVE_CONTROL          0x10U
-#define VIDEO_CT_PRIVACY_CONTROL                0x11U
-#define VIDEO_CT_FOCUS_SIMPLE_CONTROL           0x12U
-#define VIDEO_CT_WINDOW_CONTROL                 0x13U
-#define VIDEO_CT_REGION_OF_INTEREST_CONTROL     0x14U
-
-/*! @brief Video device class-specific Processing Unit control selector */
-#define VIDEO_PU_CONTROL_UNDEFINED                      0x00U
-#define VIDEO_PU_BACKLIGHT_COMPENSATION_CONTROL         0x01U
-#define VIDEO_PU_BRIGHTNESS_CONTROL                     0x02U
-#define VIDEO_PU_CONTRAST_CONTROL                       0x03U
-#define VIDEO_PU_GAIN_CONTROL                           0x04U
-#define VIDEO_PU_POWER_LINE_FREQUENCY_CONTROL           0x05U
-#define VIDEO_PU_HUE_CONTROL                            0x06U
-#define VIDEO_PU_SATURATION_CONTROL                     0x07U
-#define VIDEO_PU_SHARPNESS_CONTROL                      0x08U
-#define VIDEO_PU_GAMMA_CONTROL                          0x09U
-#define VIDEO_PU_WHITE_BALANCE_TEMPERATURE_CONTROL      0x0AU
-#define VIDEO_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x0BU
-#define VIDEO_PU_WHITE_BALANCE_COMPONENT_CONTROL        0x0CU
-#define VIDEO_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL   0x0DU
-#define VIDEO_PU_DIGITAL_MULTIPLIER_CONTROL             0x0EU
-#define VIDEO_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL       0x0FU
-#define VIDEO_PU_HUE_AUTO_CONTROL                       0x10U
-#define VIDEO_PU_ANALOG_VIDEO_STANDARD_CONTROL          0x11U
-#define VIDEO_PU_ANALOG_LOCK_STATUS_CONTROL             0x12U
-#define VIDEO_PU_CONTRAST_AUTO_CONTROL                  0x13U
-
-/*! @brief Video device class-specific Encoding Unit control selector */
-#define VIDEO_EU_CONTROL_UNDEFINED           0x00U
-#define VIDEO_EU_SELECT_LAYER_CONTROL        0x01U
-#define VIDEO_EU_PROFILE_TOOLSET_CONTROL     0x02U
-#define VIDEO_EU_VIDEO_RESOLUTION_CONTROL    0x03U
-#define VIDEO_EU_MIN_FRAME_INTERVAL_CONTROL  0x04U
-#define VIDEO_EU_SLICE_MODE_CONTROL          0x05U
-#define VIDEO_EU_RATE_CONTROL_MODE_CONTROL   0x06U
-#define VIDEO_EU_AVERAGE_BITRATE_CONTROL     0x07U
-#define VIDEO_EU_CPB_SIZE_CONTROL            0x08U
-#define VIDEO_EU_PEAK_BIT_RATE_CONTROL       0x09U
-#define VIDEO_EU_QUANTIZATION_PARAMS_CONTROL 0x0AU
-#define VIDEO_EU_SYNC_REF_FRAME_CONTROL      0x0BU
-#define VIDEO_EU_LTR_BUFFER_                 CONTROL0x0CU
-#define VIDEO_EU_LTR_PICTURE_CONTROL         0x0DU
-#define VIDEO_EU_LTR_VALIDATION_CONTROL      0x0EU
-#define VIDEO_EU_LEVEL_IDC_LIMIT_CONTROL     0x0FU
-#define VIDEO_EU_SEI_PAYLOADTYPE_CONTROL     0x10U
-#define VIDEO_EU_QP_RANGE_CONTROL            0x11U
-#define VIDEO_EU_PRIORITY_CONTROL            0x12U
-#define VIDEO_EU_START_OR_STOP_LAYER_CONTROL 0x13U
-#define VIDEO_EU_ERROR_RESILIENCY_CONTROL    0x14U
-
-/*! @brief Video device class-specific Extension Unit control selector */
-#define VIDEO_XU_CONTROL_UNDEFINED 0x00U
-
-/*! @brief Video device class-specific VideoStreaming Interface control selector */
-#define VIDEO_VS_CONTROL_UNDEFINED            0x00U
-#define VIDEO_VS_PROBE_CONTROL                0x01U
-#define VIDEO_VS_COMMIT_CONTROL               0x02U
-#define VIDEO_VS_STILL_PROBE_CONTROL          0x03U
-#define VIDEO_VS_STILL_COMMIT_CONTROL         0x04U
-#define VIDEO_VS_STILL_IMAGE_TRIGGER_CONTROL  0x05U
-#define VIDEO_VS_STREAM_ERROR_CODE_CONTROL    0x06U
-#define VIDEO_VS_GENERATE_KEY_FRAME_CONTROL   0x07U
-#define VIDEO_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x08U
-#define VIDEO_VS_SYNCH_DELAY_CONTROL          0x09U
-
-/*! @}*/
-
-/*!
- * @name USB Video class terminal types
- * @{
- */
-
-/*! @brief Video device USB terminal type */
-#define VIDEO_TT_VENDOR_SPECIFIC 0x0100U
-#define VIDEO_TT_STREAMING       0x0101U
-
-/*! @brief Video device input terminal type */
-#define VIDEO_ITT_VENDOR_SPECIFIC       0x0200U
-#define VIDEO_ITT_CAMERA                0x0201U
-#define VIDEO_ITT_MEDIA_TRANSPORT_INPUT 0x0202U
-
-/*! @brief Video device output terminal type */
-#define VIDEO_OTT_VENDOR_SPECIFIC        0x0300U
-#define VIDEO_OTT_DISPLAY                0x0301U
-#define VIDEO_OTT_MEDIA_TRANSPORT_OUTPUT 0x0302U
-
-/*! @brief Video device external terminal type */
-#define VIDEO_ET_VENDOR_SPECIFIC     0x0400U
-#define VIDEO_ET_COMPOSITE_CONNECTOR 0x0401U
-#define VIDEO_ET_SVIDEO_CONNECTOR    0x0402U
-#define VIDEO_ET_COMPONENT_CONNECTOR 0x0403U
-
-/*! @}*/
-
-/*!
- * @name USB Video class setup request types
- * @{
- */
-
-/*! @brief Video device class setup request set type */
-#define VIDEO_SET_REQUEST_INTERFACE 0x21U
-#define VIDEO_SET_REQUEST_ENDPOINT  0x22U
-
-/*! @brief Video device class setup request get type */
-#define VIDEO_GET_REQUEST_INTERFACE 0xA1U
-#define VIDEO_GET_REQUEST_ENDPOINT  0xA2U
-
-/*! @}*/
-
-/*! @brief Video device still image trigger control */
-#define VIDEO_STILL_IMAGE_TRIGGER_NORMAL_OPERATION                            0x00U
-#define VIDEO_STILL_IMAGE_TRIGGER_TRANSMIT_STILL_IMAGE                        0x01U
-#define VIDEO_STILL_IMAGE_TRIGGER_TRANSMIT_STILL_IMAGE_VS_DEDICATED_BULK_PIPE 0x02U
-#define VIDEO_STILL_IMAGE_TRIGGER_ABORT_STILL_IMAGE_TRANSMISSION              0x03U
-
-/*!
- * @name USB Video device class-specific request commands
- * @{
- */
-
-/*! @brief Video device class-specific request GET CUR COMMAND */
-#define VIDEO_GET_CUR_VC_POWER_MODE_CONTROL 0x8101U
-#define VIDEO_GET_CUR_VC_ERROR_CODE_CONTROL 0x8102U
-
-#define VIDEO_GET_CUR_PU_BACKLIGHT_COMPENSATION_CONTROL         0x8121U
-#define VIDEO_GET_CUR_PU_BRIGHTNESS_CONTROL                     0x8122U
-#define VIDEO_GET_CUR_PU_CONTRACT_CONTROL                       0x8123U
-#define VIDEO_GET_CUR_PU_GAIN_CONTROL                           0x8124U
-#define VIDEO_GET_CUR_PU_POWER_LINE_FREQUENCY_CONTROL           0x8125U
-#define VIDEO_GET_CUR_PU_HUE_CONTROL                            0x8126U
-#define VIDEO_GET_CUR_PU_SATURATION_CONTROL                     0x8127U
-#define VIDEO_GET_CUR_PU_SHARRNESS_CONTROL                      0x8128U
-#define VIDEO_GET_CUR_PU_GAMMA_CONTROL                          0x8129U
-#define VIDEO_GET_CUR_PU_WHITE_BALANCE_TEMPERATURE_CONTROL      0x812AU
-#define VIDEO_GET_CUR_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x812BU
-#define VIDEO_GET_CUR_PU_WHITE_BALANCE_COMPONENT_CONTROL        0x812CU
-#define VIDEO_GET_CUR_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL   0x812DU
-#define VIDEO_GET_CUR_PU_DIGITAL_MULTIPLIER_CONTROL             0x812EU
-#define VIDEO_GET_CUR_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL       0x812FU
-#define VIDEO_GET_CUR_PU_HUE_AUTO_CONTROL                       0x8130U
-#define VIDEO_GET_CUR_PU_ANALOG_VIDEO_STANDARD_CONTROL          0x8131U
-#define VIDEO_GET_CUR_PU_ANALOG_LOCK_STATUS_CONTROL             0x8132U
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_CUR_PU_CONTRAST_AUTO_CONTROL 0x8133U
-#endif
-
-#define VIDEO_GET_CUR_CT_SCANNING_MODE_CONTROL          0x8141U
-#define VIDEO_GET_CUR_CT_AE_MODE_CONTROL                0x8142U
-#define VIDEO_GET_CUR_CT_AE_PRIORITY_CONTROL            0x8143U
-#define VIDEO_GET_CUR_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8144U
-#define VIDEO_GET_CUR_CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x8145U
-#define VIDEO_GET_CUR_CT_FOCUS_ABSOLUTE_CONTROL         0x8146U
-#define VIDEO_GET_CUR_CT_FOCUS_RELATIVE_CONTROL         0x8147U
-#define VIDEO_GET_CUR_CT_FOCUS_AUTO_CONTROL             0x8148U
-#define VIDEO_GET_CUR_CT_IRIS_ABSOLUTE_CONTROL          0x8149U
-#define VIDEO_GET_CUR_CT_IRIS_RELATIVE_CONTROL          0x814AU
-#define VIDEO_GET_CUR_CT_ZOOM_ABSOLUTE_CONTROL          0x814BU
-#define VIDEO_GET_CUR_CT_ZOOM_RELATIVE_CONTROL          0x814CU
-#define VIDEO_GET_CUR_CT_PANTILT_ABSOLUTE_CONTROL       0x814DU
-#define VIDEO_GET_CUR_CT_PANTILT_RELATIVE_CONTROL       0x814EU
-#define VIDEO_GET_CUR_CT_ROLL_ABSOLUTE_CONTROL          0x814FU
-#define VIDEO_GET_CUR_CT_ROLL_RELATIVE_CONTROL          0x8150U
-#define VIDEO_GET_CUR_CT_PRIVACY_CONTROL                0x8151U
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_CUR_CT_FOCUS_SIMPLE_CONTROL       0x8152U
-#define VIDEO_GET_CUR_CT_DIGITAL_WINDOW_CONTROL     0x8153U
-#define VIDEO_GET_CUR_CT_REGION_OF_INTEREST_CONTROL 0x8154U
-#endif
-
-#define VIDEO_GET_CUR_VS_PROBE_CONTROL                0x8161U
-#define VIDEO_GET_CUR_VS_COMMIT_CONTROL               0x8162U
-#define VIDEO_GET_CUR_VS_STILL_PROBE_CONTROL          0x8163U
-#define VIDEO_GET_CUR_VS_STILL_COMMIT_CONTROL         0x8164U
-#define VIDEO_GET_CUR_VS_STILL_IMAGE_TRIGGER_CONTROL  0x8165U
-#define VIDEO_GET_CUR_VS_STREAM_ERROR_CODE_CONTROL    0x8166U
-#define VIDEO_GET_CUR_VS_GENERATE_KEY_FRAME_CONTROL   0x8167U
-#define VIDEO_GET_CUR_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8168U
-#define VIDEO_GET_CUR_VS_SYNCH_DELAY_CONTROL          0x8169U
-
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_CUR_EU_SELECT_LAYER_CONTROL        0x8181U
-#define VIDEO_GET_CUR_EU_PROFILE_TOOLSET_CONTROL     0x8182U
-#define VIDEO_GET_CUR_EU_VIDEO_RESOLUTION_CONTROL    0x8183U
-#define VIDEO_GET_CUR_EU_MIN_FRAME_INTERVAL_CONTROL  0x8184U
-#define VIDEO_GET_CUR_EU_SLICE_MODE_CONTROL          0x8185U
-#define VIDEO_GET_CUR_EU_RATE_CONTROL_MODE_CONTROL   0x8186U
-#define VIDEO_GET_CUR_EU_AVERAGE_BITRATE_CONTROL     0x8187U
-#define VIDEO_GET_CUR_EU_CPB_SIZE_CONTROL            0x8188U
-#define VIDEO_GET_CUR_EU_PEAK_BIT_RATE_CONTROL       0x8189U
-#define VIDEO_GET_CUR_EU_QUANTIZATION_PARAMS_CONTROL 0x818AU
-#define VIDEO_GET_CUR_EU_SYNC_REF_FRAME_CONTROL      0x818BU
-#define VIDEO_GET_CUR_EU_LTR_BUFFER_CONTROL          0x818CU
-#define VIDEO_GET_CUR_EU_LTR_PICTURE_CONTROL         0x818DU
-#define VIDEO_GET_CUR_EU_LTR_VALIDATION_CONTROL      0x818EU
-#define VIDEO_GET_CUR_EU_LEVEL_IDC_LIMIT_CONTROL     0x818FU
-#define VIDEO_GET_CUR_EU_SEI_PAYLOADTYPE_CONTROL     0x8190U
-#define VIDEO_GET_CUR_EU_QP_RANGE_CONTROL            0x8191U
-#define VIDEO_GET_CUR_EU_PRIORITY_CONTROL            0x8192U
-#define VIDEO_GET_CUR_EU_START_OR_STOP_LAYER_CONTROL 0x8193U
-#define VIDEO_GET_CUR_EU_ERROR_RESILIENCY_CONTROL    0x8194U
-#endif
-
-/*! @brief Video device class-specific request GET MIN COMMAND */
-#define VIDEO_GET_MIN_PU_BACKLIGHT_COMPENSATION_CONTROL    0x8221U
-#define VIDEO_GET_MIN_PU_BRIGHTNESS_CONTROL                0x8222U
-#define VIDEO_GET_MIN_PU_CONTRACT_CONTROL                  0x8223U
-#define VIDEO_GET_MIN_PU_GAIN_CONTROL                      0x8224U
-#define VIDEO_GET_MIN_PU_HUE_CONTROL                       0x8226U
-#define VIDEO_GET_MIN_PU_SATURATION_CONTROL                0x8227U
-#define VIDEO_GET_MIN_PU_SHARRNESS_CONTROL                 0x8228U
-#define VIDEO_GET_MIN_PU_GAMMA_CONTROL                     0x8229U
-#define VIDEO_GET_MIN_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x822AU
-#define VIDEO_GET_MIN_PU_WHITE_BALANCE_COMPONENT_CONTROL   0x822CU
-#define VIDEO_GET_MIN_PU_DIGITAL_MULTIPLIER_CONTROL        0x822EU
-#define VIDEO_GET_MIN_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL  0x822FU
-
-#define VIDEO_GET_MIN_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8244U
-#define VIDEO_GET_MIN_CT_FOCUS_ABSOLUTE_CONTROL         0x8246U
-#define VIDEO_GET_MIN_CT_FOCUS_RELATIVE_CONTROL         0x8247U
-#define VIDEO_GET_MIN_CT_IRIS_ABSOLUTE_CONTROL          0x8249U
-#define VIDEO_GET_MIN_CT_ZOOM_ABSOLUTE_CONTROL          0x824BU
-#define VIDEO_GET_MIN_CT_ZOOM_RELATIVE_CONTROL          0x824CU
-#define VIDEO_GET_MIN_CT_PANTILT_ABSOLUTE_CONTROL       0x824DU
-#define VIDEO_GET_MIN_CT_PANTILT_RELATIVE_CONTROL       0x824EU
-#define VIDEO_GET_MIN_CT_ROLL_ABSOLUTE_CONTROL          0x824FU
-#define VIDEO_GET_MIN_CT_ROLL_RELATIVE_CONTROL          0x8250U
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_MIN_CT_DIGITAL_WINDOW_CONTROL     0x8251U
-#define VIDEO_GET_MIN_CT_REGION_OF_INTEREST_CONTROL 0x8252U
-#endif
-
-#define VIDEO_GET_MIN_VS_PROBE_CONTROL                0x8261U
-#define VIDEO_GET_MIN_VS_STILL_PROBE_CONTROL          0x8263U
-#define VIDEO_GET_MIN_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8268U
-#define VIDEO_GET_MIN_VS_SYNCH_DELAY_CONTROL          0x8269U
-
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_MIN_EU_VIDEO_RESOLUTION_CONTROL    0x8283U
-#define VIDEO_GET_MIN_EU_MIN_FRAME_INTERVAL_CONTROL  0x8284U
-#define VIDEO_GET_MIN_EU_SLICE_MODE_CONTROL          0x8285U
-#define VIDEO_GET_MIN_EU_AVERAGE_BITRATE_CONTROL     0x8287U
-#define VIDEO_GET_MIN_EU_CPB_SIZE_CONTROL            0x8288U
-#define VIDEO_GET_MIN_EU_PEAK_BIT_RATE_CONTROL       0x8289U
-#define VIDEO_GET_MIN_EU_QUANTIZATION_PARAMS_CONTROL 0x828AU
-#define VIDEO_GET_MIN_EU_SYNC_REF_FRAME_CONTROL      0x828BU
-#define VIDEO_GET_MIN_EU_LEVEL_IDC_LIMIT_CONTROL     0x828FU
-#define VIDEO_GET_MIN_EU_SEI_PAYLOADTYPE_CONTROL     0x8290U
-#define VIDEO_GET_MIN_EU_QP_RANGE_CONTROL            0x8291U
-#endif
-
-/*! @brief Video device class-specific request GET MAX COMMAND */
-#define VIDEO_GET_MAX_PU_BACKLIGHT_COMPENSATION_CONTROL    0x8321U
-#define VIDEO_GET_MAX_PU_BRIGHTNESS_CONTROL                0x8322U
-#define VIDEO_GET_MAX_PU_CONTRACT_CONTROL                  0x8323U
-#define VIDEO_GET_MAX_PU_GAIN_CONTROL                      0x8324U
-#define VIDEO_GET_MAX_PU_HUE_CONTROL                       0x8326U
-#define VIDEO_GET_MAX_PU_SATURATION_CONTROL                0x8327U
-#define VIDEO_GET_MAX_PU_SHARRNESS_CONTROL                 0x8328U
-#define VIDEO_GET_MAX_PU_GAMMA_CONTROL                     0x8329U
-#define VIDEO_GET_MAX_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x832AU
-#define VIDEO_GET_MAX_PU_WHITE_BALANCE_COMPONENT_CONTROL   0x832CU
-#define VIDEO_GET_MAX_PU_DIGITAL_MULTIPLIER_CONTROL        0x832EU
-#define VIDEO_GET_MAX_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL  0x832FU
-
-#define VIDEO_GET_MAX_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8344U
-#define VIDEO_GET_MAX_CT_FOCUS_ABSOLUTE_CONTROL         0x8346U
-#define VIDEO_GET_MAX_CT_FOCUS_RELATIVE_CONTROL         0x8347U
-#define VIDEO_GET_MAX_CT_IRIS_ABSOLUTE_CONTROL          0x8349U
-#define VIDEO_GET_MAX_CT_ZOOM_ABSOLUTE_CONTROL          0x834BU
-#define VIDEO_GET_MAX_CT_ZOOM_RELATIVE_CONTROL          0x834CU
-#define VIDEO_GET_MAX_CT_PANTILT_ABSOLUTE_CONTROL       0x834DU
-#define VIDEO_GET_MAX_CT_PANTILT_RELATIVE_CONTROL       0x834EU
-#define VIDEO_GET_MAX_CT_ROLL_ABSOLUTE_CONTROL          0x834FU
-#define VIDEO_GET_MAX_CT_ROLL_RELATIVE_CONTROL          0x8350U
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_MAX_CT_DIGITAL_WINDOW_CONTROL     0x8351U
-#define VIDEO_GET_MAX_CT_REGION_OF_INTEREST_CONTROL 0x8352U
-#endif
-
-#define VIDEO_GET_MAX_VS_PROBE_CONTROL                0x8361U
-#define VIDEO_GET_MAX_VS_STILL_PROBE_CONTROL          0x8363U
-#define VIDEO_GET_MAX_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8368U
-#define VIDEO_GET_MAX_VS_SYNCH_DELAY_CONTROL          0x8369U
-
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_MAX_EU_VIDEO_RESOLUTION_CONTROL    0x8383U
-#define VIDEO_GET_MAX_EU_MIN_FRAME_INTERVAL_CONTROL  0x8384U
-#define VIDEO_GET_MAX_EU_SLICE_MODE_CONTROL          0x8385U
-#define VIDEO_GET_MAX_EU_AVERAGE_BITRATE_CONTROL     0x8387U
-#define VIDEO_GET_MAX_EU_CPB_SIZE_CONTROL            0x8388U
-#define VIDEO_GET_MAX_EU_PEAK_BIT_RATE_CONTROL       0x8389U
-#define VIDEO_GET_MAX_EU_QUANTIZATION_PARAMS_CONTROL 0x838AU
-#define VIDEO_GET_MAX_EU_SYNC_REF_FRAME_CONTROL      0x838BU
-#define VIDEO_GET_MAX_EU_LTR_BUFFER_CONTROL          0x838CU
-#define VIDEO_GET_MAX_EU_LEVEL_IDC_LIMIT_CONTROL     0x838FU
-#define VIDEO_GET_MAX_EU_SEI_PAYLOADTYPE_CONTROL     0x8390U
-#define VIDEO_GET_MAX_EU_QP_RANGE_CONTROL            0x8391U
-#endif
-
-/*! @brief Video device class-specific request GET RES COMMAND */
-#define VIDEO_GET_RES_PU_BACKLIGHT_COMPENSATION_CONTROL    0x8421U
-#define VIDEO_GET_RES_PU_BRIGHTNESS_CONTROL                0x8422U
-#define VIDEO_GET_RES_PU_CONTRACT_CONTROL                  0x8423U
-#define VIDEO_GET_RES_PU_GAIN_CONTROL                      0x8424U
-#define VIDEO_GET_RES_PU_HUE_CONTROL                       0x8426U
-#define VIDEO_GET_RES_PU_SATURATION_CONTROL                0x8427U
-#define VIDEO_GET_RES_PU_SHARRNESS_CONTROL                 0x8428U
-#define VIDEO_GET_RES_PU_GAMMA_CONTROL                     0x8429U
-#define VIDEO_GET_RES_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x842AU
-#define VIDEO_GET_RES_PU_WHITE_BALANCE_COMPONENT_CONTROL   0x842CU
-#define VIDEO_GET_RES_PU_DIGITAL_MULTIPLIER_CONTROL        0x842EU
-#define VIDEO_GET_RES_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL  0x842FU
-
-#define VIDEO_GET_RES_CT_AE_MODE_CONTROL                0x8442U
-#define VIDEO_GET_RES_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8444U
-#define VIDEO_GET_RES_CT_FOCUS_ABSOLUTE_CONTROL         0x8446U
-#define VIDEO_GET_RES_CT_FOCUS_RELATIVE_CONTROL         0x8447U
-#define VIDEO_GET_RES_CT_IRIS_ABSOLUTE_CONTROL          0x8449U
-#define VIDEO_GET_RES_CT_ZOOM_ABSOLUTE_CONTROL          0x844BU
-#define VIDEO_GET_RES_CT_ZOOM_RELATIVE_CONTROL          0x844CU
-#define VIDEO_GET_RES_CT_PANTILT_ABSOLUTE_CONTROL       0x844DU
-#define VIDEO_GET_RES_CT_PANTILT_RELATIVE_CONTROL       0x844EU
-#define VIDEO_GET_RES_CT_ROLL_ABSOLUTE_CONTROL          0x844FU
-#define VIDEO_GET_RES_CT_ROLL_RELATIVE_CONTROL          0x8450U
-
-#define VIDEO_GET_RES_VS_PROBE_CONTROL                0x8461U
-#define VIDEO_GET_RES_VS_STILL_PROBE_CONTROL          0x8463U
-#define VIDEO_GET_RES_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8468U
-#define VIDEO_GET_RES_VS_SYNCH_DELAY_CONTROL          0x8469U
-
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_RES_EU_AVERAGE_BITRATE_CONTROL     0x8487U
-#define VIDEO_GET_RES_EU_CPB_SIZE_CONTROL            0x8488U
-#define VIDEO_GET_RES_EU_PEAK_BIT_RATE_CONTROL       0x8489U
-#define VIDEO_GET_RES_EU_QUANTIZATION_PARAMS_CONTROL 0x848AU
-#define VIDEO_GET_RES_EU_ERROR_RESILIENCY_CONTROL    0x8494U
-#endif
-
-/*! @brief Video device class-specific request GET LEN COMMAND */
-
-#define VIDEO_GET_LEN_VS_PROBE_CONTROL        0x8561U
-#define VIDEO_GET_LEN_VS_COMMIT_CONTROL       0x8562U
-#define VIDEO_GET_LEN_VS_STILL_PROBE_CONTROL  0x8563U
-#define VIDEO_GET_LEN_VS_STILL_COMMIT_CONTROL 0x8564U
-
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_LEN_EU_SELECT_LAYER_CONTROL        0x8581U
-#define VIDEO_GET_LEN_EU_PROFILE_TOOLSET_CONTROL     0x8582U
-#define VIDEO_GET_LEN_EU_VIDEO_RESOLUTION_CONTROL    0x8583U
-#define VIDEO_GET_LEN_EU_MIN_FRAME_INTERVAL_CONTROL  0x8584U
-#define VIDEO_GET_LEN_EU_SLICE_MODE_CONTROL          0x8585U
-#define VIDEO_GET_LEN_EU_RATE_CONTROL_MODE_CONTROL   0x8586U
-#define VIDEO_GET_LEN_EU_AVERAGE_BITRATE_CONTROL     0x8587U
-#define VIDEO_GET_LEN_EU_CPB_SIZE_CONTROL            0x8588U
-#define VIDEO_GET_LEN_EU_PEAK_BIT_RATE_CONTROL       0x8589U
-#define VIDEO_GET_LEN_EU_QUANTIZATION_PARAMS_CONTROL 0x858AU
-#define VIDEO_GET_LEN_EU_SYNC_REF_FRAME_CONTROL      0x858BU
-#define VIDEO_GET_LEN_EU_LTR_BUFFER_CONTROL          0x858CU
-#define VIDEO_GET_LEN_EU_LTR_PICTURE_CONTROL         0x858DU
-#define VIDEO_GET_LEN_EU_LTR_VALIDATION_CONTROL      0x858EU
-#define VIDEO_GET_LEN_EU_QP_RANGE_CONTROL            0x8591U
-#define VIDEO_GET_LEN_EU_PRIORITY_CONTROL            0x8592U
-#define VIDEO_GET_LEN_EU_START_OR_STOP_LAYER_CONTROL 0x8593U
-#endif
-
-/*! @brief Video device class-specific request GET INFO COMMAND */
-#define VIDEO_GET_INFO_VC_POWER_MODE_CONTROL 0x8601U
-#define VIDEO_GET_INFO_VC_ERROR_CODE_CONTROL 0x8602U
-
-#define VIDEO_GET_INFO_PU_BACKLIGHT_COMPENSATION_CONTROL         0x8621U
-#define VIDEO_GET_INFO_PU_BRIGHTNESS_CONTROL                     0x8622U
-#define VIDEO_GET_INFO_PU_CONTRACT_CONTROL                       0x8623U
-#define VIDEO_GET_INFO_PU_GAIN_CONTROL                           0x8624U
-#define VIDEO_GET_INFO_PU_POWER_LINE_FREQUENCY_CONTROL           0x8625U
-#define VIDEO_GET_INFO_PU_HUE_CONTROL                            0x8626U
-#define VIDEO_GET_INFO_PU_SATURATION_CONTROL                     0x8627U
-#define VIDEO_GET_INFO_PU_SHARRNESS_CONTROL                      0x8628U
-#define VIDEO_GET_INFO_PU_GAMMA_CONTROL                          0x8629U
-#define VIDEO_GET_INFO_PU_WHITE_BALANCE_TEMPERATURE_CONTROL      0x862AU
-#define VIDEO_GET_INFO_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x862BU
-#define VIDEO_GET_INFO_PU_WHITE_BALANCE_COMPONENT_CONTROL        0x862CU
-#define VIDEO_GET_INFO_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL   0x862DU
-#define VIDEO_GET_INFO_PU_DIGITAL_MULTIPLIER_CONTROL             0x862EU
-#define VIDEO_GET_INFO_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL       0x862FU
-#define VIDEO_GET_INFO_PU_HUE_AUTO_CONTROL                       0x8630U
-#define VIDEO_GET_INFO_PU_ANALOG_VIDEO_STANDARD_CONTROL          0x8631U
-#define VIDEO_GET_INFO_PU_ANALOG_LOCK_STATUS_CONTROL             0x8632U
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_INFO_PU_CONTRAST_AUTO_CONTROL 0x8633U
-#endif
-
-#define VIDEO_GET_INFO_CT_SCANNING_MODE_CONTROL          0x8641U
-#define VIDEO_GET_INFO_CT_AE_MODE_CONTROL                0x8642U
-#define VIDEO_GET_INFO_CT_AE_PRIORITY_CONTROL            0x8643U
-#define VIDEO_GET_INFO_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8644U
-#define VIDEO_GET_INFO_CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x8645U
-#define VIDEO_GET_INFO_CT_FOCUS_ABSOLUTE_CONTROL         0x8646U
-#define VIDEO_GET_INFO_CT_FOCUS_RELATIVE_CONTROL         0x8647U
-#define VIDEO_GET_INFO_CT_FOCUS_AUTO_CONTROL             0x8648U
-#define VIDEO_GET_INFO_CT_IRIS_ABSOLUTE_CONTROL          0x8649U
-#define VIDEO_GET_INFO_CT_IRIS_RELATIVE_CONTROL          0x864AU
-#define VIDEO_GET_INFO_CT_ZOOM_ABSOLUTE_CONTROL          0x864BU
-#define VIDEO_GET_INFO_CT_ZOOM_RELATIVE_CONTROL          0x864CU
-#define VIDEO_GET_INFO_CT_PANTILT_ABSOLUTE_CONTROL       0x864DU
-#define VIDEO_GET_INFO_CT_PANTILT_RELATIVE_CONTROL       0x864EU
-#define VIDEO_GET_INFO_CT_ROLL_ABSOLUTE_CONTROL          0x864FU
-#define VIDEO_GET_INFO_CT_ROLL_RELATIVE_CONTROL          0x8650U
-#define VIDEO_GET_INFO_CT_PRIVACY_CONTROL                0x8651U
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_INFO_CT_FOCUS_SIMPLE_CONTROL 0x8652U
-#endif
-
-#define VIDEO_GET_INFO_VS_PROBE_CONTROL                0x8661U
-#define VIDEO_GET_INFO_VS_COMMIT_CONTROL               0x8662U
-#define VIDEO_GET_INFO_VS_STILL_PROBE_CONTROL          0x8663U
-#define VIDEO_GET_INFO_VS_STILL_COMMIT_CONTROL         0x8664U
-#define VIDEO_GET_INFO_VS_STILL_IMAGE_TRIGGER_CONTROL  0x8665U
-#define VIDEO_GET_INFO_VS_STREAM_ERROR_CODE_CONTROL    0x8666U
-#define VIDEO_GET_INFO_VS_GENERATE_KEY_FRAME_CONTROL   0x8667U
-#define VIDEO_GET_INFO_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8668U
-#define VIDEO_GET_INFO_VS_SYNCH_DELAY_CONTROL          0x8669U
-
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_INFO_EU_SELECT_LAYER_CONTROL        0x8681U
-#define VIDEO_GET_INFO_EU_PROFILE_TOOLSET_CONTROL     0x8682U
-#define VIDEO_GET_INFO_EU_VIDEO_RESOLUTION_CONTROL    0x8683U
-#define VIDEO_GET_INFO_EU_MIN_FRAME_INTERVAL_CONTROL  0x8684U
-#define VIDEO_GET_INFO_EU_SLICE_MODE_CONTROL          0x8685U
-#define VIDEO_GET_INFO_EU_RATE_CONTROL_MODE_CONTROL   0x8686U
-#define VIDEO_GET_INFO_EU_AVERAGE_BITRATE_CONTROL     0x8687U
-#define VIDEO_GET_INFO_EU_CPB_SIZE_CONTROL            0x8688U
-#define VIDEO_GET_INFO_EU_PEAK_BIT_RATE_CONTROL       0x8689U
-#define VIDEO_GET_INFO_EU_QUANTIZATION_PARAMS_CONTROL 0x868AU
-#define VIDEO_GET_INFO_EU_SYNC_REF_FRAME_CONTROL      0x868BU
-#define VIDEO_GET_INFO_EU_LTR_BUFFER_CONTROL          0x868CU
-#define VIDEO_GET_INFO_EU_LTR_PICTURE_CONTROL         0x868DU
-#define VIDEO_GET_INFO_EU_LTR_VALIDATION_CONTROL      0x868EU
-#define VIDEO_GET_INFO_EU_SEI_PAYLOADTYPE_CONTROL     0x8690U
-#define VIDEO_GET_INFO_EU_QP_RANGE_CONTROL            0x8691U
-#define VIDEO_GET_INFO_EU_PRIORITY_CONTROL            0x8692U
-#define VIDEO_GET_INFO_EU_START_OR_STOP_LAYER_CONTROL 0x8693U
-#endif
-
-/*! @brief Video device class-specific request GET DEF COMMAND */
-#define VIDEO_GET_DEF_PU_BACKLIGHT_COMPENSATION_CONTROL         0x8721U
-#define VIDEO_GET_DEF_PU_BRIGHTNESS_CONTROL                     0x8722U
-#define VIDEO_GET_DEF_PU_CONTRACT_CONTROL                       0x8723U
-#define VIDEO_GET_DEF_PU_GAIN_CONTROL                           0x8724U
-#define VIDEO_GET_DEF_PU_POWER_LINE_FREQUENCY_CONTROL           0x8725U
-#define VIDEO_GET_DEF_PU_HUE_CONTROL                            0x8726U
-#define VIDEO_GET_DEF_PU_SATURATION_CONTROL                     0x8727U
-#define VIDEO_GET_DEF_PU_SHARRNESS_CONTROL                      0x8728U
-#define VIDEO_GET_DEF_PU_GAMMA_CONTROL                          0x8729U
-#define VIDEO_GET_DEF_PU_WHITE_BALANCE_TEMPERATURE_CONTROL      0x872AU
-#define VIDEO_GET_DEF_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x872BU
-#define VIDEO_GET_DEF_PU_WHITE_BALANCE_COMPONENT_CONTROL        0x872CU
-#define VIDEO_GET_DEF_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL   0x872DU
-#define VIDEO_GET_DEF_PU_DIGITAL_MULTIPLIER_CONTROL             0x872EU
-#define VIDEO_GET_DEF_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL       0x872FU
-#define VIDEO_GET_DEF_PU_HUE_AUTO_CONTROL                       0x8730U
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_DEF_PU_CONTRAST_AUTO_CONTROL 0x8731U
-#endif
-
-#define VIDEO_GET_DEF_CT_AE_MODE_CONTROL                0x8742U
-#define VIDEO_GET_DEF_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x8744U
-#define VIDEO_GET_DEF_CT_FOCUS_ABSOLUTE_CONTROL         0x8746U
-#define VIDEO_GET_DEF_CT_FOCUS_RELATIVE_CONTROL         0x8747U
-#define VIDEO_GET_DEF_CT_FOCUS_AUTO_CONTROL             0x8748U
-#define VIDEO_GET_DEF_CT_IRIS_ABSOLUTE_CONTROL          0x8749U
-#define VIDEO_GET_DEF_CT_ZOOM_ABSOLUTE_CONTROL          0x874BU
-#define VIDEO_GET_DEF_CT_ZOOM_RELATIVE_CONTROL          0x874CU
-#define VIDEO_GET_DEF_CT_PANTILT_ABSOLUTE_CONTROL       0x874DU
-#define VIDEO_GET_DEF_CT_PANTILT_RELATIVE_CONTROL       0x874EU
-#define VIDEO_GET_DEF_CT_ROLL_ABSOLUTE_CONTROL          0x874FU
-#define VIDEO_GET_DEF_CT_ROLL_RELATIVE_CONTROL          0x8750U
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_DEF_CT_FOCUS_SIMPLE_CONTROL       0x8751U
-#define VIDEO_GET_DEF_CT_DIGITAL_WINDOW_CONTROL     0x8752U
-#define VIDEO_GET_DEF_CT_REGION_OF_INTEREST_CONTROL 0x8753U
-#endif
-
-#define VIDEO_GET_DEF_VS_PROBE_CONTROL                0x8761U
-#define VIDEO_GET_DEF_VS_STILL_PROBE_CONTROL          0x8763U
-#define VIDEO_GET_DEF_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x8768U
-#define VIDEO_GET_DEF_VS_SYNCH_DELAY_CONTROL          0x8769U
-
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_GET_DEF_EU_PROFILE_TOOLSET_CONTROL     0x8782U
-#define VIDEO_GET_DEF_EU_VIDEO_RESOLUTION_CONTROL    0x8783U
-#define VIDEO_GET_DEF_EU_MIN_FRAME_INTERVAL_CONTROL  0x8784U
-#define VIDEO_GET_DEF_EU_SLICE_MODE_CONTROL          0x8785U
-#define VIDEO_GET_DEF_EU_RATE_CONTROL_MODE_CONTROL   0x8786U
-#define VIDEO_GET_DEF_EU_AVERAGE_BITRATE_CONTROL     0x8787U
-#define VIDEO_GET_DEF_EU_CPB_SIZE_CONTROL            0x8788U
-#define VIDEO_GET_DEF_EU_PEAK_BIT_RATE_CONTROL       0x8789U
-#define VIDEO_GET_DEF_EU_QUANTIZATION_PARAMS_CONTROL 0x878AU
-#define VIDEO_GET_DEF_EU_LTR_BUFFER_CONTROL          0x878CU
-#define VIDEO_GET_DEF_EU_LTR_PICTURE_CONTROL         0x878DU
-#define VIDEO_GET_DEF_EU_LTR_VALIDATION_CONTROL      0x878EU
-#define VIDEO_GET_DEF_EU_LEVEL_IDC_LIMIT_CONTROL     0x878FU
-#define VIDEO_GET_DEF_EU_SEI_PAYLOADTYPE_CONTROL     0x8790U
-#define VIDEO_GET_DEF_EU_QP_RANGE_CONTROL            0x8791U
-#define VIDEO_GET_DEF_EU_ERROR_RESILIENCY_CONTROL    0x8794U
-#endif
-
-/*! @brief Video device class-specific request SET CUR COMMAND */
-#define VIDEO_SET_CUR_VC_POWER_MODE_CONTROL 0x0101U
-
-#define VIDEO_SET_CUR_PU_BACKLIGHT_COMPENSATION_CONTROL         0x0121U
-#define VIDEO_SET_CUR_PU_BRIGHTNESS_CONTROL                     0x0122U
-#define VIDEO_SET_CUR_PU_CONTRACT_CONTROL                       0x0123U
-#define VIDEO_SET_CUR_PU_GAIN_CONTROL                           0x0124U
-#define VIDEO_SET_CUR_PU_POWER_LINE_FREQUENCY_CONTROL           0x0125U
-#define VIDEO_SET_CUR_PU_HUE_CONTROL                            0x0126U
-#define VIDEO_SET_CUR_PU_SATURATION_CONTROL                     0x0127U
-#define VIDEO_SET_CUR_PU_SHARRNESS_CONTROL                      0x0128U
-#define VIDEO_SET_CUR_PU_GAMMA_CONTROL                          0x0129U
-#define VIDEO_SET_CUR_PU_WHITE_BALANCE_TEMPERATURE_CONTROL      0x012AU
-#define VIDEO_SET_CUR_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x012BU
-#define VIDEO_SET_CUR_PU_WHITE_BALANCE_COMPONENT_CONTROL        0x012CU
-#define VIDEO_SET_CUR_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL   0x012DU
-#define VIDEO_SET_CUR_PU_DIGITAL_MULTIPLIER_CONTROL             0x012EU
-#define VIDEO_SET_CUR_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL       0x012FU
-#define VIDEO_SET_CUR_PU_HUE_AUTO_CONTROL                       0x0130U
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_SET_CUR_PU_CONTRAST_AUTO_CONTROL 0x0131U
-#endif
-
-#define VIDEO_SET_CUR_CT_SCANNING_MODE_CONTROL          0x0141U
-#define VIDEO_SET_CUR_CT_AE_MODE_CONTROL                0x0142U
-#define VIDEO_SET_CUR_CT_AE_PRIORITY_CONTROL            0x0143U
-#define VIDEO_SET_CUR_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x0144U
-#define VIDEO_SET_CUR_CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x0145U
-#define VIDEO_SET_CUR_CT_FOCUS_ABSOLUTE_CONTROL         0x0146U
-#define VIDEO_SET_CUR_CT_FOCUS_RELATIVE_CONTROL         0x0147U
-#define VIDEO_SET_CUR_CT_FOCUS_AUTO_CONTROL             0x0148U
-#define VIDEO_SET_CUR_CT_IRIS_ABSOLUTE_CONTROL          0x0149U
-#define VIDEO_SET_CUR_CT_IRIS_RELATIVE_CONTROL          0x014AU
-#define VIDEO_SET_CUR_CT_ZOOM_ABSOLUTE_CONTROL          0x014BU
-#define VIDEO_SET_CUR_CT_ZOOM_RELATIVE_CONTROL          0x014CU
-#define VIDEO_SET_CUR_CT_PANTILT_ABSOLUTE_CONTROL       0x014DU
-#define VIDEO_SET_CUR_CT_PANTILT_RELATIVE_CONTROL       0x014EU
-#define VIDEO_SET_CUR_CT_ROLL_ABSOLUTE_CONTROL          0x014FU
-#define VIDEO_SET_CUR_CT_ROLL_RELATIVE_CONTROL          0x0150U
-#define VIDEO_SET_CUR_CT_PRIVACY_CONTROL                0x0151U
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_SET_CUR_CT_FOCUS_SIMPLE_CONTROL       0x0152U
-#define VIDEO_SET_CUR_CT_DIGITAL_WINDOW_CONTROL     0x0153U
-#define VIDEO_SET_CUR_CT_REGION_OF_INTEREST_CONTROL 0x0154U
-#endif
-
-#define VIDEO_SET_CUR_VS_PROBE_CONTROL                0x0161U
-#define VIDEO_SET_CUR_VS_COMMIT_CONTROL               0x0162U
-#define VIDEO_SET_CUR_VS_STILL_PROBE_CONTROL          0x0163U
-#define VIDEO_SET_CUR_VS_STILL_COMMIT_CONTROL         0x0164U
-#define VIDEO_SET_CUR_VS_STILL_IMAGE_TRIGGER_CONTROL  0x0165U
-#define VIDEO_SET_CUR_VS_STREAM_ERROR_CODE_CONTROL    0x0166U
-#define VIDEO_SET_CUR_VS_GENERATE_KEY_FRAME_CONTROL   0x0167U
-#define VIDEO_SET_CUR_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x0168U
-#define VIDEO_SET_CUR_VS_SYNCH_DELAY_CONTROL          0x0169U
-
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-#define VIDEO_SET_CUR_EU_SELECT_LAYER_CONTROL        0x0181U
-#define VIDEO_SET_CUR_EU_PROFILE_TOOLSET_CONTROL     0x0182U
-#define VIDEO_SET_CUR_EU_VIDEO_RESOLUTION_CONTROL    0x0183U
-#define VIDEO_SET_CUR_EU_MIN_FRAME_INTERVAL_CONTROL  0x0184U
-#define VIDEO_SET_CUR_EU_SLICE_MODE_CONTROL          0x0185U
-#define VIDEO_SET_CUR_EU_RATE_CONTROL_MODE_CONTROL   0x0186U
-#define VIDEO_SET_CUR_EU_AVERAGE_BITRATE_CONTROL     0x0187U
-#define VIDEO_SET_CUR_EU_CPB_SIZE_CONTROL            0x0188U
-#define VIDEO_SET_CUR_EU_PEAK_BIT_RATE_CONTROL       0x0189U
-#define VIDEO_SET_CUR_EU_QUANTIZATION_PARAMS_CONTROL 0x018AU
-#define VIDEO_SET_CUR_EU_SYNC_REF_FRAME_CONTROL      0x018BU
-#define VIDEO_SET_CUR_EU_LTR_BUFFER_CONTROL          0x018CU
-#define VIDEO_SET_CUR_EU_LTR_PICTURE_CONTROL         0x018DU
-#define VIDEO_SET_CUR_EU_LTR_VALIDATION_CONTROL      0x018EU
-#define VIDEO_SET_CUR_EU_LEVEL_IDC_LIMIT_CONTROL     0x018FU
-#define VIDEO_SET_CUR_EU_SEI_PAYLOADTYPE_CONTROL     0x0190U
-#define VIDEO_SET_CUR_EU_QP_RANGE_CONTROL            0x0191U
-#define VIDEO_SET_CUR_EU_PRIORITY_CONTROL            0x0192U
-#define VIDEO_SET_CUR_EU_START_OR_STOP_LAYER_CONTROL 0x0193U
-#define VIDEO_SET_CUR_EU_ERROR_RESILIENCY_CONTROL    0x0194U
-#endif
-
-/*! @brief The payload header structure for MJPEG payload format. */
-struct video_mjpeg_payload_header {
-    uint8_t bHeaderLength; /*!< The payload header length. */
-    union {
-        uint8_t bmheaderInfo; /*!< The payload header bitmap field. */
-        struct
-        {
-            uint8_t frameIdentifier : 1U; /*!< Frame Identifier. This bit toggles at each frame start boundary and stays
-                                             constant for the rest of the frame.*/
-            uint8_t endOfFrame      : 1U; /*!< End of Frame. This bit indicates the end of a video frame and is set in the
-                                        last video sample that belongs to a frame.*/
-            uint8_t
-                presentationTimeStamp    : 1U; /*!< Presentation Time Stamp. This bit, when set, indicates the presence of
-                                               a PTS field.*/
-            uint8_t sourceClockReference : 1U; /*!< Source Clock Reference. This bit, when set, indicates the presence
-                                                  of a SCR field.*/
-            uint8_t reserved             : 1U; /*!< Reserved. Set to 0. */
-            uint8_t stillImage           : 1U; /*!< Still Image. This bit, when set, identifies a video sample that belongs to a
-                                         still image.*/
-            uint8_t errorBit             : 1U; /*!< Error Bit. This bit, when set, indicates an error in the device streaming.*/
-            uint8_t endOfHeader          : 1U; /*!< End of Header. This bit, when set, indicates the end of the BFH fields.*/
-        } headerInfoBits;
-        struct
-        {
-            uint8_t FID : 1U; /*!< Frame Identifier. This bit toggles at each frame start boundary and stays constant
-                                 for the rest of the frame.*/
-            uint8_t EOI : 1U; /*!< End of Frame. This bit indicates the end of a video frame and is set in the last
-                                 video sample that belongs to a frame.*/
-            uint8_t PTS : 1U; /*!< Presentation Time Stamp. This bit, when set, indicates the presence of a PTS field.*/
-            uint8_t SCR : 1U; /*!< Source Clock Reference. This bit, when set, indicates the presence of a SCR field.*/
-            uint8_t RES : 1U; /*!< Reserved. Set to 0. */
-            uint8_t STI : 1U; /*!< Still Image. This bit, when set, identifies a video sample that belongs to a still
-                                 image.*/
-            uint8_t ERR : 1U; /*!< Error Bit. This bit, when set, indicates an error in the device streaming.*/
-            uint8_t EOH : 1U; /*!< End of Header. This bit, when set, indicates the end of the BFH fields.*/
-        } headerInfoBitmap;
-    } headerInfoUnion;
-    uint32_t dwPresentationTime;      /*!< Presentation time stamp (PTS) field.*/
-    uint8_t bSourceClockReference[6]; /*!< Source clock reference (SCR) field.*/
-} __packed;
-
-/*! @brief The Video probe and commit controls structure.*/
-struct video_probe_and_commit_controls {
-    union {
-        uint8_t bmHint; /*!< Bit-field control indicating to the function what fields shall be kept fixed. */
-        struct
-        {
-            uint8_t dwFrameInterval : 1U; /*!< dwFrameInterval field.*/
-            uint8_t wKeyFrameRate   : 1U; /*!< wKeyFrameRate field.*/
-            uint8_t wPFrameRate     : 1U; /*!< wPFrameRate field.*/
-            uint8_t wCompQuality    : 1U; /*!< wCompQuality field.*/
-            uint8_t wCompWindowSize : 1U; /*!< wCompWindowSize field.*/
-            uint8_t reserved        : 3U; /*!< Reserved field.*/
-        } hintBitmap;
-    } hintUnion;
-    union {
-        uint8_t bmHint; /*!< Bit-field control indicating to the function what fields shall be kept fixed. */
-        struct
-        {
-            uint8_t reserved : 8U; /*!< Reserved field.*/
-        } hintBitmap;
-    } hintUnion1;
-    uint8_t bFormatIndex;              /*!< Video format index from a format descriptor.*/
-    uint8_t bFrameIndex;               /*!< Video frame index from a frame descriptor.*/
-    uint32_t dwFrameInterval;          /*!< Frame interval in 100ns units.*/
-    uint16_t wKeyFrameRate;            /*!< Key frame rate in key-frame per video-frame units.*/
-    uint16_t wPFrameRate;              /*!< PFrame rate in PFrame/key frame units.*/
-    uint16_t wCompQuality;             /*!< Compression quality control in abstract units 0U (lowest) to 10000U (highest).*/
-    uint16_t wCompWindowSize;          /*!< Window size for average bit rate control.*/
-    uint16_t wDelay;                   /*!< Internal video streaming interface latency in ms from video data capture to presentation on
-                        the USB.*/
-    uint32_t dwMaxVideoFrameSize;      /*!< Maximum video frame or codec-specific segment size in bytes.*/
-    uint32_t dwMaxPayloadTransferSize; /*!< Specifies the maximum number of bytes that the device can transmit or
-                                          receive in a single payload transfer.*/
-    uint32_t dwClockFrequency;         /*!< The device clock frequency in Hz for the specified format. This specifies the
-                                  units used for the time information fields in the Video Payload Headers in the data
-                                  stream.*/
-    uint8_t bmFramingInfo;             /*!< Bit-field control supporting the following values: D0 Frame ID, D1 EOF.*/
-    uint8_t bPreferedVersion;          /*!< The preferred payload format version supported by the host or device for the
-                                  specified bFormatIndex value.*/
-    uint8_t bMinVersion;               /*!< The minimum payload format version supported by the device for the specified bFormatIndex
-                            value.*/
-    uint8_t bMaxVersion;               /*!< The maximum payload format version supported by the device for the specified bFormatIndex
-                            value.*/
-#if defined(USB_DEVICE_VIDEO_CLASS_VERSION_1_5) && USB_DEVICE_VIDEO_CLASS_VERSION_1_5
-    uint8_t bUsage; /*!< This bitmap enables features reported by the bmUsages field of the Video Frame Descriptor.*/
-    uint8_t
-        bBitDepthLuma;                  /*!< Represents bit_depth_luma_minus8 + 8U, which must be the same as bit_depth_chroma_minus8 +
-                           8.*/
-    uint8_t bmSettings;                 /*!< A bitmap of flags that is used to discover and control specific features of a temporally
-                           encoded video stream.*/
-    uint8_t bMaxNumberOfRefFramesPlus1; /*!< Host indicates the maximum number of frames stored for use as references.*/
-    uint16_t bmRateControlModes;        /*!< This field contains 4U sub-fields, each of which is a 4U bit number.*/
-    uint64_t bmLayoutPerStream;         /*!< This field contains 4U sub-fields, each of which is a 2U byte number.*/
-#endif
-} __packed;
-
-/*! @brief The Video still probe and still commit controls structure.*/
-struct video_still_probe_and_commit_controls {
-    uint8_t bFormatIndex;              /*!< Video format index from a format descriptor.*/
-    uint8_t bFrameIndex;               /*!< Video frame index from a frame descriptor.*/
-    uint8_t bCompressionIndex;         /*!< Compression index from a frame descriptor.*/
-    uint32_t dwMaxVideoFrameSize;      /*!< Maximum still image size in bytes.*/
-    uint32_t dwMaxPayloadTransferSize; /*!< Specifies the maximum number of bytes that the device can transmit or
-                                          receive in a single payload transfer.*/
-} __packed;
-
-void usbd_video_sof_callback(void);
-void usbd_video_set_interface_callback(uint8_t value);
-void usbd_video_add_interface(usbd_class_t *class, usbd_interface_t *intf);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* USB_VIDEO_H_ */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/webusb/usbd_webusb.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/webusb/usbd_webusb.h
deleted file mode 100644
index d94d17021..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/webusb/usbd_webusb.h
+++ /dev/null
@@ -1,22 +0,0 @@
-#ifndef _USBD_WEBUSB_H
-#define _USBD_WEBUSB_H
-
-/* WebUSB Descriptor Types */
-#define WEBUSB_DESCRIPTOR_SET_HEADER_TYPE       0x00
-#define WEBUSB_CONFIGURATION_SUBSET_HEADER_TYPE 0x01
-#define WEBUSB_FUNCTION_SUBSET_HEADER_TYPE      0x02
-#define WEBUSB_URL_TYPE                         0x03
-
-/* WebUSB Request Codes */
-#define WEBUSB_REQUEST_GET_URL 0x02
-
-/* bScheme in URL descriptor */
-#define WEBUSB_URL_SCHEME_HTTP  0x00
-#define WEBUSB_URL_SCHEME_HTTPS 0x01
-
-/* WebUSB Descriptor sizes */
-#define WEBUSB_DESCRIPTOR_SET_HEADER_SIZE       5
-#define WEBUSB_CONFIGURATION_SUBSET_HEADER_SIZE 4
-#define WEBUSB_FUNCTION_SUBSET_HEADER_SIZE      3
-
-#endif
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/winusb/usbd_winusb.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/winusb/usbd_winusb.h
deleted file mode 100644
index dc4a51dd6..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/class/winusb/usbd_winusb.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#ifndef _USBD_WINUSB_H
-#define _USBD_WINUSB_H
-
-/* WinUSB Microsoft OS 2.0 descriptor request codes */
-#define WINUSB_REQUEST_GET_DESCRIPTOR_SET 0x07
-#define WINUSB_REQUEST_SET_ALT_ENUM       0x08
-
-/* WinUSB Microsoft OS 2.0 descriptor sizes */
-#define WINUSB_DESCRIPTOR_SET_HEADER_SIZE  10
-#define WINUSB_FUNCTION_SUBSET_HEADER_SIZE 8
-#define WINUSB_FEATURE_COMPATIBLE_ID_SIZE  20
-
-/* WinUSB Microsoft OS 2.0 Descriptor Types */
-#define WINUSB_SET_HEADER_DESCRIPTOR_TYPE       0x00
-#define WINUSB_SUBSET_HEADER_CONFIGURATION_TYPE 0x01
-#define WINUSB_SUBSET_HEADER_FUNCTION_TYPE      0x02
-#define WINUSB_FEATURE_COMPATIBLE_ID_TYPE       0x03
-#define WINUSB_FEATURE_REG_PROPERTY_TYPE        0x04
-#define WINUSB_FEATURE_MIN_RESUME_TIME_TYPE     0x05
-#define WINUSB_FEATURE_MODEL_ID_TYPE            0x06
-#define WINUSB_FEATURE_CCGP_DEVICE_TYPE         0x07
-
-#define WINUSB_PROP_DATA_TYPE_REG_SZ       0x01
-#define WINUSB_PROP_DATA_TYPE_REG_MULTI_SZ 0x07
-
-#endif
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_dc.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_dc.h
deleted file mode 100644
index bb8383826..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_dc.h
+++ /dev/null
@@ -1,197 +0,0 @@
-#ifndef _USB_DC_H
-#define _USB_DC_H
-
-#include "stdint.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * USB endpoint direction and number.
- */
-#define USB_EP_DIR_MASK 0x80U
-#define USB_EP_DIR_IN   0x80U
-#define USB_EP_DIR_OUT  0x00U
-
-/** Get endpoint index (number) from endpoint address */
-#define USB_EP_GET_IDX(ep) ((ep) & ~USB_EP_DIR_MASK)
-/** Get direction from endpoint address */
-#define USB_EP_GET_DIR(ep) ((ep)&USB_EP_DIR_MASK)
-/** Get endpoint address from endpoint index and direction */
-#define USB_EP_GET_ADDR(idx, dir) ((idx) | ((dir)&USB_EP_DIR_MASK))
-/** True if the endpoint is an IN endpoint */
-#define USB_EP_DIR_IS_IN(ep) (USB_EP_GET_DIR(ep) == USB_EP_DIR_IN)
-/** True if the endpoint is an OUT endpoint */
-#define USB_EP_DIR_IS_OUT(ep) (USB_EP_GET_DIR(ep) == USB_EP_DIR_OUT)
-
-/**
- * USB endpoint Transfer Type mask.
- */
-#define USBD_EP_TYPE_CTRL 0
-#define USBD_EP_TYPE_ISOC 1
-#define USBD_EP_TYPE_BULK 2
-#define USBD_EP_TYPE_INTR 3
-#define USBD_EP_TYPE_MASK 3
-
-/* Default USB control EP, always 0 and 0x80 */
-#define USB_CONTROL_OUT_EP0 0
-#define USB_CONTROL_IN_EP0  0x80
-
-/**
- * @brief USB Device Controller API
- * @defgroup _usb_device_controller_api USB Device Controller API
- * @{
- */
-/**< maximum packet size (MPS) for EP 0 */
-#define USB_CTRL_EP_MPS 64
-
-/**
- * @brief USB Endpoint Transfer Type
- */
-enum usb_dc_ep_transfer_type {
-    /** Control type endpoint */
-    USB_DC_EP_CONTROL = 0,
-    /** Isochronous type endpoint */
-    USB_DC_EP_ISOCHRONOUS,
-    /** Bulk type endpoint */
-    USB_DC_EP_BULK,
-    /** Interrupt type endpoint  */
-    USB_DC_EP_INTERRUPT
-};
-
-/**
- * @brief USB Endpoint Configuration.
- *
- * Structure containing the USB endpoint configuration.
- */
-struct usbd_endpoint_cfg {
-    /** The number associated with the EP in the device
-     *  configuration structure
-     *       IN  EP = 0x80 | \
-     *       OUT EP = 0x00 | \
-     */
-    uint8_t ep_addr;
-    /** Endpoint max packet size */
-    uint16_t ep_mps;
-    /** Endpoint Transfer Type.
-     * May be Bulk, Interrupt, Control or Isochronous
-     */
-    enum usb_dc_ep_transfer_type ep_type;
-};
-
-/**
- * @brief USB Device Core Layer API
- * @defgroup _usb_device_core_api USB Device Core API
- * @{
- */
-
-/**
- * @brief Set USB device address
- *
- * @param[in] addr Device address
- *
- * @return 0 on success, negative errno code on fail.
- */
-int usbd_set_address(const uint8_t addr);
-
-/*
- * @brief configure and enable endpoint
- *
- * This function sets endpoint configuration according to one specified in USB
- * endpoint descriptor and then enables it for data transfers.
- *
- * @param [in]  ep_desc Endpoint descriptor byte array
- *
- * @return true if successfully configured and enabled
- */
-int usbd_ep_open(const struct usbd_endpoint_cfg *ep_cfg);
-/**
- * @brief Disable the selected endpoint
- *
- * Function to disable the selected endpoint. Upon success interrupts are
- * disabled for the corresponding endpoint and the endpoint is no longer able
- * for transmitting/receiving data.
- *
- * @param[in] ep Endpoint address corresponding to the one
- *               listed in the device configuration table
- *
- * @return 0 on success, negative errno code on fail.
- */
-int usbd_ep_close(const uint8_t ep);
-/**
- * @brief Set stall condition for the selected endpoint
- *
- * @param[in] ep Endpoint address corresponding to the one
- *               listed in the device configuration table
- *
- * @return 0 on success, negative errno code on fail.
- */
-int usbd_ep_set_stall(const uint8_t ep);
-/**
- * @brief Clear stall condition for the selected endpoint
- *
- * @param[in] ep Endpoint address corresponding to the one
- *               listed in the device configuration table
- *
- * @return 0 on success, negative errno code on fail.
- */
-int usbd_ep_clear_stall(const uint8_t ep);
-/**
- * @brief Check if the selected endpoint is stalled
- *
- * @param[in]  ep       Endpoint address corresponding to the one
- *                      listed in the device configuration table
- * @param[out] stalled  Endpoint stall status
- *
- * @return 0 on success, negative errno code on fail.
- */
-int usbd_ep_is_stalled(const uint8_t ep, uint8_t *stalled);
-/**
- * @brief Write data to the specified endpoint
- *
- * This function is called to write data to the specified endpoint. The
- * supplied usbd_endpoint_callback function will be called when data is transmitted
- * out.
- *
- * @param[in]  ep        Endpoint address corresponding to the one
- *                       listed in the device configuration table
- * @param[in]  data      Pointer to data to write
- * @param[in]  data_len  Length of the data requested to write. This may
- *                       be zero for a zero length status packet.
- * @param[out] ret_bytes Bytes scheduled for transmission. This value
- *                       may be NULL if the application expects all
- *                       bytes to be written
- *
- * @return 0 on success, negative errno code on fail.
- */
-int usbd_ep_write(const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes);
-/**
- * @brief Read data from the specified endpoint
- *
- * This is similar to usb_dc_ep_read, the difference being that, it doesn't
- * clear the endpoint NAKs so that the consumer is not bogged down by further
- * upcalls till he is done with the processing of the data. The caller should
- * reactivate ep by setting max_data_len 0 do so.
- *
- * @param[in]  ep           Endpoint address corresponding to the one
- *                          listed in the device configuration table
- * @param[in]  data         Pointer to data buffer to write to
- * @param[in]  max_data_len Max length of data to read
- * @param[out] read_bytes   Number of bytes read. If data is NULL and
- *                          max_data_len is 0 the number of bytes
- *                          available for read should be returned.
- *
- * @return 0 on success, negative errno code on fail.
- */
-int usbd_ep_read(const uint8_t ep, uint8_t *data, uint32_t max_data_len, uint32_t *read_bytes);
-
-/**
- * @}
- */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_def.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_def.h
deleted file mode 100644
index 57903f6b7..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_def.h
+++ /dev/null
@@ -1,566 +0,0 @@
-#ifndef USB_REQUEST_H
-#define USB_REQUEST_H
-
-/* Useful define */
-#define USB_1_1 0x0110
-#define USB_2_0 0x0200
-/* Set USB version to 2.1 so that the host will request the BOS descriptor */
-#define USB_2_1 0x0210
-
-// USB Speed
-#define USB_SPEED_LOW  0U
-#define USB_SPEED_FULL 1U
-#define USB_SPEED_HIGH 2U
-
-// USB PID Types
-#define USB_PID_RESERVED 0U
-#define USB_PID_OUT      1U
-#define USB_PID_ACK      2U
-#define USB_PID_DATA0    3U
-#define USB_PID_PING     4U
-#define USB_PID_SOF      5U
-#define USB_PID_DATA2    7U
-#define USB_PID_NYET     6U
-#define USB_PID_SPLIT    8U
-#define USB_PID_IN       9U
-#define USB_PID_NAK      10U
-#define USB_PID_DATA1    11U
-#define USB_PID_PRE      12U
-#define USB_PID_ERR      12U
-#define USB_PID_SETUP    13U
-#define USB_PID_STALL    14U
-#define USB_PID_MDATA    15U
-
-// bmRequestType.Dir
-#define USB_REQUEST_HOST_TO_DEVICE 0U
-#define USB_REQUEST_DEVICE_TO_HOST 1U
-
-// bmRequestType.Type
-#define USB_REQUEST_STANDARD 0U
-#define USB_REQUEST_CLASS    1U
-#define USB_REQUEST_VENDOR   2U
-#define USB_REQUEST_RESERVED 3U
-
-// bmRequestType.Recipient
-#define USB_REQUEST_TO_DEVICE    0U
-#define USB_REQUEST_TO_INTERFACE 1U
-#define USB_REQUEST_TO_ENDPOINT  2U
-#define USB_REQUEST_TO_OTHER     3U
-
-/* USB Standard Request Codes */
-#define USB_REQUEST_GET_STATUS          0x00
-#define USB_REQUEST_CLEAR_FEATURE       0x01
-#define USB_REQUEST_SET_FEATURE         0x03
-#define USB_REQUEST_SET_ADDRESS         0x05
-#define USB_REQUEST_GET_DESCRIPTOR      0x06
-#define USB_REQUEST_SET_DESCRIPTOR      0x07
-#define USB_REQUEST_GET_CONFIGURATION   0x08
-#define USB_REQUEST_SET_CONFIGURATION   0x09
-#define USB_REQUEST_GET_INTERFACE       0x0A
-#define USB_REQUEST_SET_INTERFACE       0x0B
-#define USB_REQUEST_SYNCH_FRAME         0x0C
-#define USB_REQUEST_SET_ENCRYPTION      0x0D
-#define USB_REQUEST_GET_ENCRYPTION      0x0E
-#define USB_REQUEST_RPIPE_ABORT         0x0E
-#define USB_REQUEST_SET_HANDSHAKE       0x0F
-#define USB_REQUEST_RPIPE_RESET         0x0F
-#define USB_REQUEST_GET_HANDSHAKE       0x10
-#define USB_REQUEST_SET_CONNECTION      0x11
-#define USB_REQUEST_SET_SECURITY_DATA   0x12
-#define USB_REQUEST_GET_SECURITY_DATA   0x13
-#define USB_REQUEST_SET_WUSB_DATA       0x14
-#define USB_REQUEST_LOOPBACK_DATA_WRITE 0x15
-#define USB_REQUEST_LOOPBACK_DATA_READ  0x16
-#define USB_REQUEST_SET_INTERFACE_DS    0x17
-
-/* USB GET_STATUS Bit Values */
-#define USB_GETSTATUS_SELF_POWERED   0x01
-#define USB_GETSTATUS_REMOTE_WAKEUP  0x02
-#define USB_GETSTATUS_ENDPOINT_STALL 0x01
-
-/* USB Standard Feature selectors */
-#define USB_FEATURE_ENDPOINT_STALL 0
-#define USB_FEATURE_REMOTE_WAKEUP  1
-#define USB_FEATURE_TEST_MODE      2
-
-/* Descriptor size in bytes */
-#define USB_DEVICE_DESC_SIZE          0x12
-#define USB_CONFIGURATION_DESC_SIZE   0x09
-#define USB_INTERFACE_DESC_SIZE       0x09
-#define USB_ENDPOINT_DESC_SIZE        0x07
-#define USB_LANGID_STRING_DESC_SIZE   0x04
-#define USB_OTHER_SPEED_DESC_SIZE     0x09
-#define USB_DEVICE_QUAL_DESC_SIZE     0x0A
-#define USB_INTERFACE_ASSOC_DESC_SIZE 0x08
-#define USB_FUNCTION_DESC_SIZE        0x03
-#define USB_OTG_DESC_SIZE             0x03
-
-/* USB Descriptor Types */
-#define USB_DESCRIPTOR_TYPE_DEVICE                0x01U
-#define USB_DESCRIPTOR_TYPE_CONFIGURATION         0x02U
-#define USB_DESCRIPTOR_TYPE_STRING                0x03U
-#define USB_DESCRIPTOR_TYPE_INTERFACE             0x04U
-#define USB_DESCRIPTOR_TYPE_ENDPOINT              0x05U
-#define USB_DESCRIPTOR_TYPE_DEVICE_QUALIFIER      0x06U
-#define USB_DESCRIPTOR_TYPE_OTHER_SPEED           0x07U
-#define USB_DESCRIPTOR_TYPE_INTERFACE_POWER       0x08U
-#define USB_DESCRIPTOR_TYPE_OTG                   0x09U
-#define USB_DESCRIPTOR_TYPE_DEBUG                 0x0AU
-#define USB_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION 0x0BU
-#define USB_DESCRIPTOR_TYPE_BINARY_OBJECT_STORE   0x0FU
-#define USB_DESCRIPTOR_TYPE_DEVICE_CAPABILITY     0x10U
-
-#define USB_DESCRIPTOR_TYPE_FUNCTIONAL 0x21U
-
-// Class Specific Descriptor
-#define USB_CS_DESCRIPTOR_TYPE_DEVICE        0x21U
-#define USB_CS_DESCRIPTOR_TYPE_CONFIGURATION 0x22U
-#define USB_CS_DESCRIPTOR_TYPE_STRING        0x23U
-#define USB_CS_DESCRIPTOR_TYPE_INTERFACE     0x24U
-#define USB_CS_DESCRIPTOR_TYPE_ENDPOINT      0x25U
-
-#define USB_DESCRIPTOR_TYPE_SUPERSPEED_ENDPOINT_COMPANION     0x30U
-#define USB_DESCRIPTOR_TYPE_SUPERSPEED_ISO_ENDPOINT_COMPANION 0x31U
-
-/* USB Device Classes */
-#define USB_DEVICE_CLASS_RESERVED      0x00
-#define USB_DEVICE_CLASS_AUDIO         0x01
-#define USB_DEVICE_CLASS_CDC           0x02
-#define USB_DEVICE_CLASS_HID           0x03
-#define USB_DEVICE_CLASS_MONITOR       0x04
-#define USB_DEVICE_CLASS_PHYSICAL      0x05
-#define USB_DEVICE_CLASS_IMAGE         0x06
-#define USB_DEVICE_CLASS_PRINTER       0x07
-#define USB_DEVICE_CLASS_MASS_STORAGE  0x08
-#define USB_DEVICE_CLASS_HUB           0x09
-#define USB_DEVICE_CLASS_CDC_DATA      0x0a
-#define USB_DEVICE_CLASS_SMART_CARD    0x0b
-#define USB_DEVICE_CLASS_SECURITY      0x0d
-#define USB_DEVICE_CLASS_VIDEO         0x0e
-#define USB_DEVICE_CLASS_HEALTHCARE    0x0f
-#define USB_DEVICE_CLASS_DIAG_DEVICE   0xdc
-#define USB_DEVICE_CLASS_WIRELESS      0xe0
-#define USB_DEVICE_CLASS_MISC          0xef
-#define USB_DEVICE_CLASS_APP_SPECIFIC  0xfe
-#define USB_DEVICE_CLASS_VEND_SPECIFIC 0xff
-
-/* usb string index define */
-#define USB_STRING_LANGID_INDEX    0x00
-#define USB_STRING_MFC_INDEX       0x01
-#define USB_STRING_PRODUCT_INDEX   0x02
-#define USB_STRING_SERIAL_INDEX    0x03
-#define USB_STRING_CONFIG_INDEX    0x04
-#define USB_STRING_INTERFACE_INDEX 0x05
-#define USB_STRING_OS_INDEX        0x06
-#define USB_STRING_MAX             USB_STRING_OS_INDEX
-/*
- * Devices supporting Microsoft OS Descriptors store special string
- * descriptor at fixed index (0xEE). It is read when a new device is
- * attached to a computer for the first time.
- */
-#define USB_OSDESC_STRING_DESC_INDEX 0xEE
-
-/* bmAttributes in Configuration Descriptor */
-#define USB_CONFIG_POWERED_MASK  0x40
-#define USB_CONFIG_BUS_POWERED   0x80
-#define USB_CONFIG_SELF_POWERED  0xC0
-#define USB_CONFIG_REMOTE_WAKEUP 0x20
-
-/* bMaxPower in Configuration Descriptor */
-#define USB_CONFIG_POWER_MA(mA) ((mA) / 2)
-
-/* bEndpointAddress in Endpoint Descriptor */
-#define USB_ENDPOINT_DIRECTION_MASK 0x80
-#define USB_ENDPOINT_OUT(addr)      ((addr) | 0x00)
-#define USB_ENDPOINT_IN(addr)       ((addr) | 0x80)
-
-/* bmAttributes in Endpoint Descriptor */
-#define USB_ENDPOINT_TYPE_MASK               0x03
-#define USB_ENDPOINT_TYPE_CONTROL            0x00
-#define USB_ENDPOINT_TYPE_ISOCHRONOUS        0x01
-#define USB_ENDPOINT_TYPE_BULK               0x02
-#define USB_ENDPOINT_TYPE_INTERRUPT          0x03
-#define USB_ENDPOINT_SYNC_MASK               0x0C
-#define USB_ENDPOINT_SYNC_NO_SYNCHRONIZATION 0x00
-#define USB_ENDPOINT_SYNC_ASYNCHRONOUS       0x04
-#define USB_ENDPOINT_SYNC_ADAPTIVE           0x08
-#define USB_ENDPOINT_SYNC_SYNCHRONOUS        0x0C
-#define USB_ENDPOINT_USAGE_MASK              0x30
-#define USB_ENDPOINT_USAGE_DATA              0x00
-#define USB_ENDPOINT_USAGE_FEEDBACK          0x10
-#define USB_ENDPOINT_USAGE_IMPLICIT_FEEDBACK 0x20
-#define USB_ENDPOINT_USAGE_RESERVED          0x30
-
-/* bDevCapabilityType in Device Capability Descriptor */
-#define USB_DEVICE_CAPABILITY_WIRELESS_USB                1
-#define USB_DEVICE_CAPABILITY_USB_2_0_EXTENSION           2
-#define USB_DEVICE_CAPABILITY_SUPERSPEED_USB              3
-#define USB_DEVICE_CAPABILITY_CONTAINER_ID                4
-#define USB_DEVICE_CAPABILITY_PLATFORM                    5
-#define USB_DEVICE_CAPABILITY_POWER_DELIVERY_CAPABILITY   6
-#define USB_DEVICE_CAPABILITY_BATTERY_INFO_CAPABILITY     7
-#define USB_DEVICE_CAPABILITY_PD_CONSUMER_PORT_CAPABILITY 8
-#define USB_DEVICE_CAPABILITY_PD_PROVIDER_PORT_CAPABILITY 9
-#define USB_DEVICE_CAPABILITY_SUPERSPEED_PLUS             10
-#define USB_DEVICE_CAPABILITY_PRECISION_TIME_MEASUREMENT  11
-#define USB_DEVICE_CAPABILITY_WIRELESS_USB_EXT            12
-
-#define USB_BOS_CAPABILITY_EXTENSION 0x02
-#define USB_BOS_CAPABILITY_PLATFORM  0x05
-
-/* Setup packet definition used to read raw data from USB line */
-struct usb_setup_packet {
-    __packed union {
-        uint8_t bmRequestType; /* bmRequestType */
-        struct
-        {
-            uint8_t Recipient : 5; /* D4..0: Recipient */
-            uint8_t Type      : 2; /* D6..5: Type */
-            uint8_t Dir       : 1; /* D7:    Data Phase Txsfer Direction */
-        } bmRequestType_b;
-    };
-    uint8_t bRequest;
-    __packed union {
-        uint16_t wValue; /* wValue */
-        struct
-        {
-            uint8_t wValueL;
-            uint8_t wValueH;
-        };
-    };
-    __packed union {
-        uint16_t wIndex; /* wIndex */
-        struct
-        {
-            uint8_t wIndexL;
-            uint8_t wIndexH;
-        };
-    };
-    uint16_t wLength;
-} __packed;
-
-/** Standard Device Descriptor */
-struct usb_device_descriptor {
-    uint8_t bLength;            /* Descriptor size in bytes = 18 */
-    uint8_t bDescriptorType;    /* DEVICE descriptor type = 1 */
-    uint16_t bcdUSB;            /* USB spec in BCD, e.g. 0x0200 */
-    uint8_t bDeviceClass;       /* Class code, if 0 see interface */
-    uint8_t bDeviceSubClass;    /* Sub-Class code, 0 if class = 0 */
-    uint8_t bDeviceProtocol;    /* Protocol, if 0 see interface */
-    uint8_t bMaxPacketSize0;    /* Endpoint 0 max. size */
-    uint16_t idVendor;          /* Vendor ID per USB-IF */
-    uint16_t idProduct;         /* Product ID per manufacturer */
-    uint16_t bcdDevice;         /* Device release # in BCD */
-    uint8_t iManufacturer;      /* Index to manufacturer string */
-    uint8_t iProduct;           /* Index to product string */
-    uint8_t iSerialNumber;      /* Index to serial number string */
-    uint8_t bNumConfigurations; /* Number of possible configurations */
-} __packed;
-
-/** USB device_qualifier descriptor */
-struct usb_device_qualifier_descriptor {
-    uint8_t bLength;            /* Descriptor size in bytes = 10 */
-    uint8_t bDescriptorType;    /* DEVICE QUALIFIER type = 6 */
-    uint16_t bcdUSB;            /* USB spec in BCD, e.g. 0x0200 */
-    uint8_t bDeviceClass;       /* Class code, if 0 see interface */
-    uint8_t bDeviceSubClass;    /* Sub-Class code, 0 if class = 0 */
-    uint8_t bDeviceProtocol;    /* Protocol, if 0 see interface */
-    uint8_t bMaxPacketSize;     /* Endpoint 0 max. size */
-    uint8_t bNumConfigurations; /* Number of possible configurations */
-    uint8_t bReserved;          /* Reserved = 0 */
-} __packed;
-
-/** Standard Configuration Descriptor */
-struct usb_configuration_descriptor {
-    uint8_t bLength;             /* Descriptor size in bytes = 9 */
-    uint8_t bDescriptorType;     /* CONFIGURATION type = 2 or 7 */
-    uint16_t wTotalLength;       /* Length of concatenated descriptors */
-    uint8_t bNumInterfaces;      /* Number of interfaces, this config. */
-    uint8_t bConfigurationValue; /* Value to set this config. */
-    uint8_t iConfiguration;      /* Index to configuration string */
-    uint8_t bmAttributes;        /* Config. characteristics */
-    uint8_t bMaxPower;           /* Max.power from bus, 2mA units */
-} __packed;
-
-/** Standard Interface Descriptor */
-struct usb_interface_descriptor {
-    uint8_t bLength;            /* Descriptor size in bytes = 9 */
-    uint8_t bDescriptorType;    /* INTERFACE descriptor type = 4 */
-    uint8_t bInterfaceNumber;   /* Interface no.*/
-    uint8_t bAlternateSetting;  /* Value to select this IF */
-    uint8_t bNumEndpoints;      /* Number of endpoints excluding 0 */
-    uint8_t bInterfaceClass;    /* Class code, 0xFF = vendor */
-    uint8_t bInterfaceSubClass; /* Sub-Class code, 0 if class = 0 */
-    uint8_t bInterfaceProtocol; /* Protocol, 0xFF = vendor */
-    uint8_t iInterface;         /* Index to interface string */
-} __packed;
-
-/** Standard Endpoint Descriptor */
-struct usb_endpoint_descriptor {
-    uint8_t bLength;          /* Descriptor size in bytes = 7 */
-    uint8_t bDescriptorType;  /* ENDPOINT descriptor type = 5 */
-    uint8_t bEndpointAddress; /* Endpoint # 0 - 15 | IN/OUT */
-    uint8_t bmAttributes;     /* Transfer type */
-    uint16_t wMaxPacketSize;  /* Bits 10:0 = max. packet size */
-    uint8_t bInterval;        /* Polling interval in (micro) frames */
-} __packed;
-
-/** Unicode (UTF16LE) String Descriptor */
-struct usb_string_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint16_t bString;
-} __packed;
-
-/* USB Interface Association Descriptor */
-struct usb_interface_association_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bFirstInterface;
-    uint8_t bInterfaceCount;
-    uint8_t bFunctionClass;
-    uint8_t bFunctionSubClass;
-    uint8_t bFunctionProtocol;
-    uint8_t iFunction;
-} __packed;
-
-/* MS OS 1.0 string descriptor */
-struct usb_msosv1_string_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bString[14];
-    uint8_t bMS_VendorCode; /* Vendor Code, used for a control request */
-    uint8_t bPad;           /* Padding byte for VendorCode look as UTF16 */
-} __packed;
-
-/* MS OS 1.0 Header descriptor */
-struct usb_msosv1_compat_id_header_descriptor {
-    uint32_t dwLength;
-    uint16_t bcdVersion;
-    uint16_t wIndex;
-    uint8_t bCount;
-    uint8_t reserved[7];
-} __packed;
-
-/* MS OS 1.0 Function descriptor */
-struct usb_msosv1_comp_id_function_descriptor {
-    uint8_t bFirstInterfaceNumber;
-    uint8_t reserved1;
-    uint8_t compatibleID[8];
-    uint8_t subCompatibleID[8];
-    uint8_t reserved2[6];
-} __packed;
-
-#define usb_msosv1_comp_id_create(x)                                         \
-    struct usb_msosv1_comp_id {                                              \
-        struct usb_msosv1_compat_id_header_descriptor compat_id_header;      \
-        struct usb_msosv1_comp_id_function_descriptor compat_id_function[x]; \
-    };
-
-struct usb_msosv1_descriptor {
-    uint8_t *string;
-    uint8_t string_len;
-    uint8_t vendor_code;
-    uint8_t *compat_id;
-    uint16_t compat_id_len;
-    uint8_t *comp_id_property;
-    uint16_t comp_id_property_len;
-};
-
-/* MS OS 2.0 Header descriptor */
-struct usb_msosv2_header_descriptor {
-    uint32_t dwLength;
-    uint16_t bcdVersion;
-    uint16_t wIndex;
-    uint8_t bCount;
-} __packed;
-
-/*Microsoft OS 2.0 set header descriptor*/
-struct usb_msosv2_set_header_descriptor {
-    uint16_t wLength;
-    uint16_t wDescriptorType;
-    uint32_t dwWindowsVersion;
-    uint16_t wDescriptorSetTotalLength;
-} __packed;
-
-/* Microsoft OS 2.0 compatibleID descriptor*/
-struct usb_msosv2_comp_id_descriptor {
-    uint16_t wLength;
-    uint16_t wDescriptorType;
-    uint8_t compatibleID[8];
-    uint8_t subCompatibleID[8];
-} __packed;
-
-/* MS OS 2.0 property descriptor */
-struct usb_msosv2_property_descriptor {
-    uint16_t wLength;
-    uint16_t wDescriptorType;
-    uint32_t dwPropertyDataType;
-    uint16_t wPropertyNameLength;
-    const char *bPropertyName;
-    uint32_t dwPropertyDataLength;
-    const char *bPropertyData;
-};
-
-/* Microsoft OS 2.0 subset function descriptor  */
-struct usb_msosv2_subset_function_descriptor {
-    uint16_t wLength;
-    uint16_t wDescriptorType;
-    uint8_t bFirstInterface;
-    uint8_t bReserved;
-    uint16_t wSubsetLength;
-} __packed;
-
-struct usb_msosv2_descriptor {
-    uint8_t *compat_id;
-    uint16_t compat_id_len;
-    uint8_t vendor_code;
-};
-
-/* BOS header Descriptor */
-struct usb_bos_header_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint16_t wTotalLength;
-    uint8_t bNumDeviceCaps;
-} __packed;
-
-/* BOS Capability platform Descriptor */
-struct usb_bos_capability_platform_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bDevCapabilityType;
-    uint8_t bReserved;
-    uint8_t PlatformCapabilityUUID[16];
-} __packed;
-
-/* BOS Capability MS OS Descriptors version 2 */
-struct usb_bos_capability_msosv2_descriptor {
-    uint32_t dwWindowsVersion;
-    uint16_t wMSOSDescriptorSetTotalLength;
-    uint8_t bVendorCode;
-    uint8_t bAltEnumCode;
-} __packed;
-
-/* BOS Capability webusb */
-struct usb_bos_capability_webusb_descriptor {
-    uint16_t bcdVersion;
-    uint8_t bVendorCode;
-    uint8_t iLandingPage;
-} __packed;
-
-/* BOS Capability extension Descriptor*/
-struct usb_bos_capability_extension_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bDevCapabilityType;
-    uint32_t bmAttributes;
-} __packed;
-
-/* Microsoft OS 2.0 Platform Capability Descriptor
-* See https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/
-* microsoft-defined-usb-descriptors
-* Adapted from the source:
-* https://github.com/sowbug/weblight/blob/master/firmware/webusb.c
-* (BSD-2) Thanks http://janaxelson.com/files/ms_os_20_descriptors.c
-*/
-struct usb_bos_capability_platform_msosv2_descriptor {
-    struct usb_bos_capability_platform_descriptor platform_msos;
-    struct usb_bos_capability_msosv2_descriptor data_msosv2;
-} __packed;
-
-/* WebUSB Platform Capability Descriptor:
-* https://wicg.github.io/webusb/#webusb-platform-capability-descriptor
-*/
-struct usb_bos_capability_platform_webusb_descriptor {
-    struct usb_bos_capability_platform_descriptor platform_webusb;
-    struct usb_bos_capability_webusb_descriptor data_webusb;
-} __packed;
-
-struct usb_webusb_url_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bScheme;
-    char URL[];
-} __packed;
-
-struct usb_bos_descriptor {
-    uint8_t *string;
-    uint32_t string_len;
-};
-
-/* USB Device Capability Descriptor */
-struct usb_device_capability_descriptor {
-    uint8_t bLength;
-    uint8_t bDescriptorType;
-    uint8_t bDevCapabilityType;
-} __packed;
-
-/** USB descriptor header */
-struct usb_desc_header {
-    uint8_t bLength;         /**< descriptor length */
-    uint8_t bDescriptorType; /**< descriptor type */
-};
-// clang-format off
-#define USB_DEVICE_DESCRIPTOR_INIT(bcdUSB, bDeviceClass, bDeviceSubClass, bDeviceProtocol, idVendor, idProduct, bcdDevice, bNumConfigurations) \
-    0x12,                       /* bLength */                                                                                              \
-    USB_DESCRIPTOR_TYPE_DEVICE, /* bDescriptorType */                                                                                      \
-    WBVAL(bcdUSB),              /* bcdUSB */                                                                                               \
-    bDeviceClass,               /* bDeviceClass */                                                                                         \
-    bDeviceSubClass,            /* bDeviceSubClass */                                                                                      \
-    bDeviceProtocol,            /* bDeviceProtocol */                                                                                      \
-    0x40,                       /* bMaxPacketSize */                                                                                       \
-    WBVAL(idVendor),            /* idVendor */                                                                                             \
-    WBVAL(idProduct),           /* idProduct */                                                                                            \
-    WBVAL(bcdDevice),           /* bcdDevice */                                                                                            \
-    USB_STRING_MFC_INDEX,       /* iManufacturer */                                                                                        \
-    USB_STRING_PRODUCT_INDEX,   /* iProduct */                                                                                             \
-    USB_STRING_SERIAL_INDEX,    /* iSerial */                                                                                              \
-    bNumConfigurations          /* bNumConfigurations */
-
-#define USB_CONFIG_DESCRIPTOR_INIT(wTotalLength, bNumInterfaces, bConfigurationValue, bmAttributes, bMaxPower) \
-    0x09,                              /* bLength */                                                       \
-    USB_DESCRIPTOR_TYPE_CONFIGURATION, /* bDescriptorType */                                               \
-    WBVAL(wTotalLength),               /* wTotalLength */                                                  \
-    bNumInterfaces,                    /* bNumInterfaces */                                                \
-    bConfigurationValue,               /* bConfigurationValue */                                           \
-    0x00,                              /* iConfiguration */                                                \
-    bmAttributes,                      /* bmAttributes */                                                  \
-    USB_CONFIG_POWER_MA(bMaxPower)     /* bMaxPower */
-
-#define USB_INTERFACE_DESCRIPTOR_INIT(bInterfaceNumber, bAlternateSetting, bNumEndpoints,                  \
-                                      bInterfaceClass, bInterfaceSubClass, bInterfaceProtocol, iInterface) \
-    0x09,                          /* bLength */                                                       \
-    USB_DESCRIPTOR_TYPE_INTERFACE, /* bDescriptorType */                                               \
-    bInterfaceNumber,              /* bInterfaceNumber */                                              \
-    bAlternateSetting,             /* bAlternateSetting */                                             \
-    bNumEndpoints,                 /* bNumEndpoints */                                                 \
-    bInterfaceClass,               /* bInterfaceClass */                                               \
-    bInterfaceSubClass,            /* bInterfaceSubClass */                                            \
-    bInterfaceProtocol,            /* bInterfaceProtocol */                                            \
-    iInterface                     /* iInterface */
-
-#define USB_ENDPOINT_DESCRIPTOR_INIT(bEndpointAddress, bmAttributes, wMaxPacketSize, bInterval) \
-    0x07,                         /* bLength */                                             \
-    USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */                                     \
-    bEndpointAddress,             /* bEndpointAddress */                                    \
-    bmAttributes,                 /* bmAttributes */                                        \
-    WBVAL(wMaxPacketSize),        /* wMaxPacketSize */                                      \
-    bInterval                     /* bInterval */
-
-#define USB_IAD_INIT(bFirstInterface, bInterfaceCount, bFunctionClass, bFunctionSubClass, bFunctionProtocol) \
-    0x08,                                      /* bLength */                                             \
-    USB_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION, /* bDescriptorType */                                     \
-    bFirstInterface,                           /* bFirstInterface */                                     \
-    bInterfaceCount,                           /* bInterfaceCount */                                     \
-    bFunctionClass,                            /* bFunctionClass */                                      \
-    bFunctionSubClass,                         /* bFunctionSubClass */                                   \
-    bFunctionProtocol,                         /* bFunctionProtocol */                                   \
-    0x00                                       /* iFunction */
-
-#define USB_LANGID_INIT(id)                           \
-    0x04,                           /* bLength */     \
-    USB_DESCRIPTOR_TYPE_STRING, /* bDescriptorType */ \
-    WBVAL(id)                   /* wLangID0 */
-// clang-format on
-#endif
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_slist.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_slist.h
deleted file mode 100644
index 357df1bed..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_slist.h
+++ /dev/null
@@ -1,224 +0,0 @@
-#ifndef __USB_SLIST_H__
-#define __USB_SLIST_H__
-
-#include "string.h"
-#include "stdint.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * usb_container_of - return the member address of ptr, if the type of ptr is the
- * struct type.
- */
-#define usb_container_of(ptr, type, member) \
-    ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))
-
-/**
- * Single List structure
- */
-struct usb_slist_node {
-    struct usb_slist_node *next; /**< point to next node. */
-};
-typedef struct usb_slist_node usb_slist_t; /**< Type for single list. */
-
-/**
- * @brief initialize a single list
- *
- * @param l the single list to be initialized
- */
-static inline void usb_slist_init(usb_slist_t *l)
-{
-    l->next = NULL;
-}
-
-static inline void usb_slist_add_head(usb_slist_t *l, usb_slist_t *n)
-{
-    n->next = l->next;
-    l->next = n;
-}
-
-static inline void usb_slist_add_tail(usb_slist_t *l, usb_slist_t *n)
-{
-    while (l->next) {
-        l = l->next;
-    }
-
-    /* append the node to the tail */
-    l->next = n;
-    n->next = NULL;
-}
-
-static inline void usb_slist_insert(usb_slist_t *l, usb_slist_t *next, usb_slist_t *n)
-{
-    if (!next) {
-        usb_slist_add_tail(next, l);
-        return;
-    }
-
-    while (l->next) {
-        if (l->next == next) {
-            l->next = n;
-            n->next = next;
-        }
-
-        l = l->next;
-    }
-}
-
-static inline usb_slist_t *usb_slist_remove(usb_slist_t *l, usb_slist_t *n)
-{
-    /* remove slist head */
-    while (l->next && l->next != n) {
-        l = l->next;
-    }
-
-    /* remove node */
-    if (l->next != (usb_slist_t *)0) {
-        l->next = l->next->next;
-    }
-
-    return l;
-}
-
-static inline unsigned int usb_slist_len(const usb_slist_t *l)
-{
-    unsigned int len = 0;
-    const usb_slist_t *list = l->next;
-
-    while (list != NULL) {
-        list = list->next;
-        len++;
-    }
-
-    return len;
-}
-
-static inline unsigned int usb_slist_contains(usb_slist_t *l, usb_slist_t *n)
-{
-    while (l->next) {
-        if (l->next == n) {
-            return 0;
-        }
-
-        l = l->next;
-    }
-
-    return 1;
-}
-
-static inline usb_slist_t *usb_slist_head(usb_slist_t *l)
-{
-    return l->next;
-}
-
-static inline usb_slist_t *usb_slist_tail(usb_slist_t *l)
-{
-    while (l->next) {
-        l = l->next;
-    }
-
-    return l;
-}
-
-static inline usb_slist_t *usb_slist_next(usb_slist_t *n)
-{
-    return n->next;
-}
-
-static inline int usb_slist_isempty(usb_slist_t *l)
-{
-    return l->next == NULL;
-}
-
-/**
- * @brief initialize a slist object
- */
-#define USB_SLIST_OBJECT_INIT(object) \
-    {                                 \
-        NULL                          \
-    }
-
-/**
- * @brief initialize a slist object
- */
-#define USB_SLIST_DEFINE(slist) \
-    usb_slist_t slist = { NULL }
-
-/**
- * @brief get the struct for this single list node
- * @param node the entry point
- * @param type the type of structure
- * @param member the name of list in structure
- */
-#define usb_slist_entry(node, type, member) \
-    usb_container_of(node, type, member)
-
-/**
- * usb_slist_first_entry - get the first element from a slist
- * @ptr:    the slist head to take the element from.
- * @type:   the type of the struct this is embedded in.
- * @member: the name of the slist_struct within the struct.
- *
- * Note, that slist is expected to be not empty.
- */
-#define usb_slist_first_entry(ptr, type, member) \
-    usb_slist_entry((ptr)->next, type, member)
-
-/**
- * usb_slist_tail_entry - get the tail element from a slist
- * @ptr:    the slist head to take the element from.
- * @type:   the type of the struct this is embedded in.
- * @member: the name of the slist_struct within the struct.
- *
- * Note, that slist is expected to be not empty.
- */
-#define usb_slist_tail_entry(ptr, type, member) \
-    usb_slist_entry(usb_slist_tail(ptr), type, member)
-
-/**
- * usb_slist_first_entry_or_null - get the first element from a slist
- * @ptr:    the slist head to take the element from.
- * @type:   the type of the struct this is embedded in.
- * @member: the name of the slist_struct within the struct.
- *
- * Note, that slist is expected to be not empty.
- */
-#define usb_slist_first_entry_or_null(ptr, type, member) \
-    (usb_slist_isempty(ptr) ? NULL : usb_slist_first_entry(ptr, type, member))
-
-/**
- * usb_slist_for_each - iterate over a single list
- * @pos:    the usb_slist_t * to use as a loop cursor.
- * @head:   the head for your single list.
- */
-#define usb_slist_for_each(pos, head) \
-    for (pos = (head)->next; pos != NULL; pos = pos->next)
-
-#define usb_slist_for_each_safe(pos, next, head)    \
-    for (pos = (head)->next, next = pos->next; pos; \
-         pos = next, next = pos->next)
-
-/**
- * usb_slist_for_each_entry  -   iterate over single list of given type
- * @pos:    the type * to use as a loop cursor.
- * @head:   the head for your single list.
- * @member: the name of the list_struct within the struct.
- */
-#define usb_slist_for_each_entry(pos, head, member)                 \
-    for (pos = usb_slist_entry((head)->next, typeof(*pos), member); \
-         &pos->member != (NULL);                                    \
-         pos = usb_slist_entry(pos->member.next, typeof(*pos), member))
-
-#define usb_slist_for_each_entry_safe(pos, n, head, member)          \
-    for (pos = usb_slist_entry((head)->next, typeof(*pos), member),  \
-        n = usb_slist_entry(pos->member.next, typeof(*pos), member); \
-         &pos->member != (NULL);                                     \
-         pos = n, n = usb_slist_entry(pos->member.next, typeof(*pos), member))
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_util.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_util.h
deleted file mode 100644
index 95e75cbac..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/common/usb_util.h
+++ /dev/null
@@ -1,150 +0,0 @@
-#ifndef _USB_UTIL_H
-#define _USB_UTIL_H
-
-#include "stdbool.h"
-#include "string.h"
-#include "stdint.h"
-#include "stdio.h"
-#include "stdlib.h"
-#include "usb_slist.h"
-#include "bflb_platform.h"
-
-#ifndef __packed
-#define __packed __attribute__((__packed__))
-#endif
-#ifndef __aligned
-#define __aligned(x) __attribute__((__aligned__(x)))
-#endif
-#define __may_alias __attribute__((__may_alias__))
-#ifndef __printf_like
-#define __printf_like(f, a) __attribute__((format(printf, f, a)))
-#endif
-#define __used __attribute__((__used__))
-#ifndef __deprecated
-#define __deprecated __attribute__((deprecated))
-#endif
-#define ARG_UNUSED(x) (void)(x)
-
-// #define likely(x)   __builtin_expect((bool)!!(x), true)
-// #define unlikely(x) __builtin_expect((bool)!!(x), false)
-
-#define popcount(x) __builtin_popcount(x)
-
-#ifndef __no_optimization
-#define __no_optimization __attribute__((optimize("-O0")))
-#endif
-
-#ifndef __weak
-#define __weak __attribute__((__weak__))
-#endif
-#define __unused __attribute__((__unused__))
-
-#ifndef __ALIGN_BEGIN
-#define __ALIGN_BEGIN
-#endif
-#ifndef __ALIGN_END
-#define __ALIGN_END __attribute__((aligned(4)))
-#endif
-
-#ifndef LO_BYTE
-#define LO_BYTE(x) ((uint8_t)(x & 0x00FF))
-#endif
-
-#ifndef HI_BYTE
-#define HI_BYTE(x) ((uint8_t)((x & 0xFF00) >> 8))
-#endif
-
-/**
- * @def MAX
- * @brief The larger value between @p a and @p b.
- * @note Arguments are evaluated twice.
- */
-#ifndef MAX
-/* Use Z_MAX for a GCC-only, single evaluation version */
-#define MAX(a, b) (((a) > (b)) ? (a) : (b))
-#endif
-
-/**
- * @def MIN
- * @brief The smaller value between @p a and @p b.
- * @note Arguments are evaluated twice.
- */
-#ifndef MIN
-/* Use Z_MIN for a GCC-only, single evaluation version */
-#define MIN(a, b) (((a) < (b)) ? (a) : (b))
-#endif
-
-#ifndef BCD
-#define BCD(x) ((((x) / 10) << 4) | ((x) % 10))
-#endif
-
-#ifdef BIT
-#undef BIT
-#define BIT(n) (1UL << (n))
-#else
-#define BIT(n) (1UL << (n))
-#endif
-
-#ifndef ARRAY_SIZE
-#define ARRAY_SIZE(array) \
-    ((int)((sizeof(array) / sizeof((array)[0]))))
-#endif
-
-#ifndef BSWAP16
-#define BSWAP16(u16) (__builtin_bswap16(u16))
-#endif
-#ifndef BSWAP32
-#define BSWAP32(u32) (__builtin_bswap32(u32))
-#endif
-
-#define GET_BE16(field) \
-    (((uint16_t)(field)[0] << 8) | ((uint16_t)(field)[1]))
-
-#define GET_BE32(field) \
-    (((uint32_t)(field)[0] << 24) | ((uint32_t)(field)[1] << 16) | ((uint32_t)(field)[2] << 8) | ((uint32_t)(field)[3] << 0))
-
-#define SET_BE16(field, value)                \
-    do {                                      \
-        (field)[0] = (uint8_t)((value) >> 8); \
-        (field)[1] = (uint8_t)((value) >> 0); \
-    } while (0)
-
-#define SET_BE24(field, value)                 \
-    do {                                       \
-        (field)[0] = (uint8_t)((value) >> 16); \
-        (field)[1] = (uint8_t)((value) >> 8);  \
-        (field)[2] = (uint8_t)((value) >> 0);  \
-    } while (0)
-
-#define SET_BE32(field, value)                 \
-    do {                                       \
-        (field)[0] = (uint8_t)((value) >> 24); \
-        (field)[1] = (uint8_t)((value) >> 16); \
-        (field)[2] = (uint8_t)((value) >> 8);  \
-        (field)[3] = (uint8_t)((value) >> 0);  \
-    } while (0)
-
-#define REQTYPE_GET_DIR(x)   (((x) >> 7) & 0x01)
-#define REQTYPE_GET_TYPE(x)  (((x) >> 5) & 0x03U)
-#define REQTYPE_GET_RECIP(x) ((x)&0x1F)
-
-#define GET_DESC_TYPE(x)  (((x) >> 8) & 0xFFU)
-#define GET_DESC_INDEX(x) ((x)&0xFFU)
-
-#define WBVAL(x) (x & 0xFF), ((x >> 8) & 0xFF)
-#define DBVAL(x) (x & 0xFF), ((x >> 8) & 0xFF), ((x >> 16) & 0xFF), ((x >> 24) & 0xFF)
-
-#define USB_DESC_SECTION __attribute__((section("usb_desc"))) __used __aligned(1)
-
-#if 0
-#define USBD_LOG_WRN(a, ...) bflb_platform_printf(a, ##__VA_ARGS__)
-#define USBD_LOG_DBG(a, ...) bflb_platform_printf(a, ##__VA_ARGS__)
-#define USBD_LOG_ERR(a, ...) bflb_platform_printf(a, ##__VA_ARGS__)
-#else
-#define USBD_LOG_INFO(a, ...) bflb_platform_printf(a, ##__VA_ARGS__)
-#define USBD_LOG_DBG(a, ...)
-#define USBD_LOG_WRN(a, ...) bflb_platform_printf(a, ##__VA_ARGS__)
-#define USBD_LOG_ERR(a, ...)  bflb_platform_printf(a, ##__VA_ARGS__)
-#endif
-
-#endif
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c
deleted file mode 100644
index 47929088f..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.c
+++ /dev/null
@@ -1,1269 +0,0 @@
-/**
- * @file usbd_core.c
- * @brief
- *
- * Copyright (c) 2021 Bouffalolab team
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.  The
- * ASF licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the
- * License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
- * License for the specific language governing permissions and limitations
- * under the License.
- *
- */
-#include "usbd_core.h"
-#include "usbd_winusb.h"
-
-#define USBD_EP_CALLBACK_LIST_SEARCH   0
-#define USBD_EP_CALLBACK_ARR_SEARCH    1
-#define USBD_EP_CALLBACK_SEARCH_METHOD USBD_EP_CALLBACK_ARR_SEARCH
-
-/* general descriptor field offsets */
-#define DESC_bLength         0 /** Length offset */
-#define DESC_bDescriptorType 1 /** Descriptor type offset */
-
-/* config descriptor field offsets */
-#define CONF_DESC_wTotalLength        2 /** Total length offset */
-#define CONF_DESC_bConfigurationValue 5 /** Configuration value offset */
-#define CONF_DESC_bmAttributes        7 /** configuration characteristics */
-
-/* interface descriptor field offsets */
-#define INTF_DESC_bInterfaceNumber  2 /** Interface number offset */
-#define INTF_DESC_bAlternateSetting 3 /** Alternate setting offset */
-
-#define USB_REQUEST_BUFFER_SIZE 256
-#define USB_EP_OUT_NUM          8
-#define USB_EP_IN_NUM           8
-
-static struct usbd_core_cfg_priv {
-    /** Setup packet */
-    struct usb_setup_packet setup;
-    /** Pointer to data buffer */
-    uint8_t *ep0_data_buf;
-    /** Remaining bytes in buffer */
-    uint32_t ep0_data_buf_residue;
-    /** Total length of control transfer */
-    uint32_t ep0_data_buf_len;
-    /** Zero length packet flag of control transfer */
-    bool zlp_flag;
-    /** Pointer to registered descriptors */
-    const uint8_t *descriptors;
-    /* Buffer used for storing standard, class and vendor request data */
-    uint8_t req_data[USB_REQUEST_BUFFER_SIZE];
-
-#if USBD_EP_CALLBACK_SEARCH_METHOD == 1
-    usbd_endpoint_callback in_ep_cb[USB_EP_IN_NUM];
-    usbd_endpoint_callback out_ep_cb[USB_EP_OUT_NUM];
-#endif
-    /** Variable to check whether the usb has been enabled */
-    bool enabled;
-    /** Variable to check whether the usb has been configured */
-    bool configured;
-    /** Currently selected configuration */
-    uint8_t configuration;
-    /** Remote wakeup feature status */
-    uint16_t remote_wakeup;
-    uint8_t reserved;
-} usbd_core_cfg;
-
-static usb_slist_t usbd_class_head = USB_SLIST_OBJECT_INIT(usbd_class_head);
-static struct usb_msosv1_descriptor *msosv1_desc;
-static struct usb_msosv2_descriptor *msosv2_desc;
-static struct usb_bos_descriptor *bos_desc;
-
-/**
- * @brief print the contents of a setup packet
- *
- * @param [in] setup The setup packet
- *
- */
-static void usbd_print_setup(struct usb_setup_packet *setup)
-{
-    USBD_LOG_INFO("Setup: "
-                  "bmRequestType 0x%02x, bRequest 0x%02x, wValue 0x%04x, wIndex 0x%04x, wLength 0x%04x\r\n",
-                  setup->bmRequestType,
-                  setup->bRequest,
-                  setup->wValue,
-                  setup->wIndex,
-                  setup->wLength);
-}
-
-/**
- * @brief Check if the device is in Configured state
- *
- * @return true if Configured, false otherwise.
- */
-static bool is_device_configured(void)
-{
-    return (usbd_core_cfg.configuration != 0);
-}
-/**
- * @brief Check if the interface of given number is valid
- *
- * @param [in] interface Number of the addressed interface
- *
- * This function searches through descriptor and checks
- * is the Host has addressed valid interface.
- *
- * @return true if interface exists - valid
- */
-static bool is_interface_valid(uint8_t interface)
-{
-    const uint8_t *p = (uint8_t *)usbd_core_cfg.descriptors;
-    const struct usb_configuration_descriptor *cfg_descr;
-
-    /* Search through descriptor for matching interface */
-    while (p[DESC_bLength] != 0U) {
-        if (p[DESC_bDescriptorType] == USB_DESCRIPTOR_TYPE_CONFIGURATION) {
-            cfg_descr = (const struct usb_configuration_descriptor *)p;
-
-            if (interface < cfg_descr->bNumInterfaces) {
-                return true;
-            }
-        }
-
-        p += p[DESC_bLength];
-    }
-
-    return false;
-}
-/**
- * @brief Check if the endpoint of given address is valid
- *
- * @param [in] ep Address of the Endpoint
- *
- * This function checks if the Endpoint of given address
- * is valid for the configured device. Valid Endpoint is
- * either Control Endpoint or one used by the device.
- *
- * @return true if endpoint exists - valid
- */
-static bool is_ep_valid(uint8_t ep)
-{
-    /* Check if its Endpoint 0 */
-    if ((ep & 0x7f) == 0) {
-        return true;
-    }
-
-    return true;
-}
-#if USBD_EP_CALLBACK_SEARCH_METHOD == 1
-static void usbd_ep_callback_register(void)
-{
-    usb_slist_t *i, *j, *k;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
-
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
-
-            usb_slist_for_each(k, &intf->ep_list)
-            {
-                usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list);
-
-                if (ept->ep_cb) {
-                    if (ept->ep_addr & 0x80) {
-                        usbd_core_cfg.in_ep_cb[ept->ep_addr & 0x7f] = ept->ep_cb;
-                    } else {
-                        usbd_core_cfg.out_ep_cb[ept->ep_addr & 0x7f] = ept->ep_cb;
-                    }
-                }
-            }
-        }
-    }
-}
-#endif
-/**
- * @brief configure and enable endpoint
- *
- * This function sets endpoint configuration according to one specified in USB
- * endpoint descriptor and then enables it for data transfers.
- *
- * @param [in]  ep_desc Endpoint descriptor byte array
- *
- * @return true if successfully configured and enabled
- */
-static bool usbd_set_endpoint(const struct usb_endpoint_descriptor *ep_desc)
-{
-    struct usbd_endpoint_cfg ep_cfg;
-
-    ep_cfg.ep_addr = ep_desc->bEndpointAddress;
-    ep_cfg.ep_mps = ep_desc->wMaxPacketSize;
-    ep_cfg.ep_type = ep_desc->bmAttributes & USBD_EP_TYPE_MASK;
-
-    USBD_LOG_INFO("Open endpoint:0x%x type:%u mps:%u\r\n",
-                  ep_cfg.ep_addr, ep_cfg.ep_type, ep_cfg.ep_mps);
-
-    usbd_ep_open(&ep_cfg);
-    usbd_core_cfg.configured = true;
-
-    return true;
-}
-/**
- * @brief Disable endpoint for transferring data
- *
- * This function cancels transfers that are associated with endpoint and
- * disabled endpoint itself.
- *
- * @param [in]  ep_desc Endpoint descriptor byte array
- *
- * @return true if successfully deconfigured and disabled
- */
-static bool usbd_reset_endpoint(const struct usb_endpoint_descriptor *ep_desc)
-{
-    struct usbd_endpoint_cfg ep_cfg;
-
-    ep_cfg.ep_addr = ep_desc->bEndpointAddress;
-    ep_cfg.ep_mps = ep_desc->wMaxPacketSize;
-    ep_cfg.ep_type = ep_desc->bmAttributes & USBD_EP_TYPE_MASK;
-
-    USBD_LOG_INFO("Close endpoint:0x%x type:%u\r\n",
-                  ep_cfg.ep_addr, ep_cfg.ep_type);
-
-    usbd_ep_close(ep_cfg.ep_addr);
-
-    return true;
-}
-
-/**
- * @brief get specified USB descriptor
- *
- * This function parses the list of installed USB descriptors and attempts
- * to find the specified USB descriptor.
- *
- * @param [in]  type_index Type and index of the descriptor
- * @param [in]  lang_id    Language ID of the descriptor (currently unused)
- * @param [out] len        Descriptor length
- * @param [out] data       Descriptor data
- *
- * @return true if the descriptor was found, false otherwise
- */
-static bool usbd_get_descriptor(uint16_t type_index, uint8_t **data, uint32_t *len)
-{
-    uint8_t type = 0U;
-    uint8_t index = 0U;
-    uint8_t *p = NULL;
-    uint32_t cur_index = 0U;
-    bool found = false;
-
-    type = GET_DESC_TYPE(type_index);
-    index = GET_DESC_INDEX(type_index);
-
-    if ((type == USB_DESCRIPTOR_TYPE_STRING) && (index == USB_OSDESC_STRING_DESC_INDEX)) {
-        USBD_LOG_INFO("read MS OS 2.0 descriptor string\r\n");
-
-        if (!msosv1_desc) {
-            return false;
-        }
-
-        *data = (uint8_t *)msosv1_desc->string;
-        *len = msosv1_desc->string_len;
-
-        return true;
-    } else if (type == USB_DESCRIPTOR_TYPE_BINARY_OBJECT_STORE) {
-        USBD_LOG_INFO("read BOS descriptor string\r\n");
-
-        if (!bos_desc) {
-            return false;
-        }
-
-        *data = bos_desc->string;
-        *len = bos_desc->string_len;
-        return true;
-    }
-    /*
-     * Invalid types of descriptors,
-     * see USB Spec. Revision 2.0, 9.4.3 Get Descriptor
-     */
-    else if ((type == USB_DESCRIPTOR_TYPE_INTERFACE) || (type == USB_DESCRIPTOR_TYPE_ENDPOINT) ||
-#ifndef CONFIG_USB_HS
-             (type > USB_DESCRIPTOR_TYPE_ENDPOINT)) {
-#else
-             (type > USB_DESCRIPTOR_TYPE_OTHER_SPEED)) {
-#endif
-        return false;
-    }
-
-    p = (uint8_t *)usbd_core_cfg.descriptors;
-
-    cur_index = 0U;
-
-    while (p[DESC_bLength] != 0U) {
-        if (p[DESC_bDescriptorType] == type) {
-            if (cur_index == index) {
-                found = true;
-                break;
-            }
-
-            cur_index++;
-        }
-
-        /* skip to next descriptor */
-        p += p[DESC_bLength];
-    }
-
-    if (found) {
-        /* set data pointer */
-        *data = p;
-
-        /* get length from structure */
-        if (type == USB_DESCRIPTOR_TYPE_CONFIGURATION) {
-            /* configuration descriptor is an
-             * exception, length is at offset
-             * 2 and 3
-             */
-            *len = (p[CONF_DESC_wTotalLength]) |
-                   (p[CONF_DESC_wTotalLength + 1] << 8);
-        } else {
-            /* normally length is at offset 0 */
-            *len = p[DESC_bLength];
-        }
-    } else {
-        /* nothing found */
-        USBD_LOG_ERR("descriptor  not found!\r\n", type, index);
-    }
-
-    return found;
-}
-
-/**
- * @brief set USB configuration
- *
- * This function configures the device according to the specified configuration
- * index and alternate setting by parsing the installed USB descriptor list.
- * A configuration index of 0 unconfigures the device.
- *
- * @param [in] config_index Configuration index
- * @param [in] alt_setting  Alternate setting number
- *
- * @return true if successfully configured false if error or unconfigured
- */
-static bool usbd_set_configuration(uint8_t config_index, uint8_t alt_setting)
-{
-    uint8_t *p = (uint8_t *)usbd_core_cfg.descriptors;
-    uint8_t cur_alt_setting = 0xFF;
-    uint8_t cur_config = 0xFF;
-    bool found = false;
-
-    if (config_index == 0U) {
-        /* TODO: unconfigure device */
-        USBD_LOG_ERR("Device not configured - invalid configuration\r\n");
-        return true;
-    }
-
-    /* configure endpoints for this configuration/altsetting */
-    while (p[DESC_bLength] != 0U) {
-        switch (p[DESC_bDescriptorType]) {
-            case USB_DESCRIPTOR_TYPE_CONFIGURATION:
-                /* remember current configuration index */
-                cur_config = p[CONF_DESC_bConfigurationValue];
-
-                if (cur_config == config_index) {
-                    found = true;
-                }
-
-                break;
-
-            case USB_DESCRIPTOR_TYPE_INTERFACE:
-                /* remember current alternate setting */
-                cur_alt_setting =
-                    p[INTF_DESC_bAlternateSetting];
-                break;
-
-            case USB_DESCRIPTOR_TYPE_ENDPOINT:
-                if ((cur_config != config_index) ||
-                    (cur_alt_setting != alt_setting)) {
-                    break;
-                }
-
-                found = usbd_set_endpoint((struct usb_endpoint_descriptor *)p);
-                break;
-
-            default:
-                break;
-        }
-
-        /* skip to next descriptor */
-        p += p[DESC_bLength];
-    }
-
-    return found;
-}
-
-/**
- * @brief set USB interface
- *
- * @param [in] iface Interface index
- * @param [in] alt_setting  Alternate setting number
- *
- * @return true if successfully configured false if error or unconfigured
- */
-static bool usbd_set_interface(uint8_t iface, uint8_t alt_setting)
-{
-    const uint8_t *p = usbd_core_cfg.descriptors;
-    const uint8_t *if_desc = NULL;
-    struct usb_endpoint_descriptor *ep_desc;
-    uint8_t cur_alt_setting = 0xFF;
-    uint8_t cur_iface = 0xFF;
-    bool ret = false;
-
-    USBD_LOG_DBG("iface %u alt_setting %u\r\n", iface, alt_setting);
-
-    while (p[DESC_bLength] != 0U) {
-        switch (p[DESC_bDescriptorType]) {
-            case USB_DESCRIPTOR_TYPE_INTERFACE:
-                /* remember current alternate setting */
-                cur_alt_setting = p[INTF_DESC_bAlternateSetting];
-                cur_iface = p[INTF_DESC_bInterfaceNumber];
-
-                if (cur_iface == iface &&
-                    cur_alt_setting == alt_setting) {
-                    if_desc = (void *)p;
-                }
-
-                USBD_LOG_DBG("Current iface %u alt setting %u",
-                             cur_iface, cur_alt_setting);
-                break;
-
-            case USB_DESCRIPTOR_TYPE_ENDPOINT:
-                if (cur_iface == iface) {
-                    ep_desc = (struct usb_endpoint_descriptor *)p;
-
-                    if (cur_alt_setting != alt_setting) {
-                        ret = usbd_reset_endpoint(ep_desc);
-                    } else {
-                        ret = usbd_set_endpoint(ep_desc);
-                    }
-                }
-
-                break;
-
-            default:
-                break;
-        }
-
-        /* skip to next descriptor */
-        p += p[DESC_bLength];
-    }
-
-    usbd_event_notify_handler(USB_EVENT_SET_INTERFACE, (void *)if_desc);
-
-    return ret;
-}
-
-/**
- * @brief handle a standard device request
- *
- * @param [in]     setup    The setup packet
- * @param [in,out] len      Pointer to data length
- * @param [in,out] ep0_data_buf Data buffer
- *
- * @return true if the request was handled successfully
- */
-static bool usbd_std_device_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    uint16_t value = setup->wValue;
-    // uint16_t index = setup->wIndex;
-    bool ret = true;
-
-    switch (setup->bRequest) {
-        case USB_REQUEST_GET_STATUS:
-            USBD_LOG_DBG("REQ_GET_STATUS\r\n");
-            /* bit 0: self-powered */
-            /* bit 1: remote wakeup */
-            *data = (uint8_t *)&usbd_core_cfg.remote_wakeup;
-
-            *len = 2;
-            break;
-
-        case USB_REQUEST_CLEAR_FEATURE:
-            USBD_LOG_DBG("REQ_CLEAR_FEATURE\r\n");
-            ret = false;
-
-            if (value == USB_FEATURE_REMOTE_WAKEUP) {
-                usbd_core_cfg.remote_wakeup = 0;
-                usbd_event_notify_handler(USB_EVENT_CLEAR_REMOTE_WAKEUP, NULL);
-                ret = true;
-            }
-
-            break;
-
-        case USB_REQUEST_SET_FEATURE:
-            USBD_LOG_DBG("REQ_SET_FEATURE\r\n");
-            ret = false;
-
-            if (value == USB_FEATURE_REMOTE_WAKEUP) {
-                usbd_core_cfg.remote_wakeup = 1;
-                usbd_event_notify_handler(USB_EVENT_SET_REMOTE_WAKEUP, NULL);
-                ret = true;
-            }
-
-            if (value == USB_FEATURE_TEST_MODE) {
-                /* put TEST_MODE code here */
-            }
-
-            break;
-
-        case USB_REQUEST_SET_ADDRESS:
-            USBD_LOG_DBG("REQ_SET_ADDRESS, addr 0x%x\r\n", value);
-            usbd_set_address(value);
-            break;
-
-        case USB_REQUEST_GET_DESCRIPTOR:
-            USBD_LOG_DBG("REQ_GET_DESCRIPTOR\r\n");
-            ret = usbd_get_descriptor(value, data, len);
-            break;
-
-        case USB_REQUEST_SET_DESCRIPTOR:
-            USBD_LOG_DBG("Device req 0x%02x not implemented\r\n", setup->bRequest);
-            ret = false;
-            break;
-
-        case USB_REQUEST_GET_CONFIGURATION:
-            USBD_LOG_DBG("REQ_GET_CONFIGURATION\r\n");
-            /* indicate if we are configured */
-            *data = (uint8_t *)&usbd_core_cfg.configuration;
-            *len = 1;
-            break;
-
-        case USB_REQUEST_SET_CONFIGURATION:
-            value &= 0xFF;
-            USBD_LOG_DBG("REQ_SET_CONFIGURATION, conf 0x%x\r\n", value);
-
-            if (!usbd_set_configuration(value, 0)) {
-                USBD_LOG_DBG("USB Set Configuration failed\r\n");
-                ret = false;
-            } else {
-                /* configuration successful,
-                 * update current configuration
-                 */
-                usbd_core_cfg.configuration = value;
-                usbd_event_notify_handler(USB_EVENT_CONFIGURED, NULL);
-            }
-
-            break;
-
-        case USB_REQUEST_GET_INTERFACE:
-            break;
-
-        case USB_REQUEST_SET_INTERFACE:
-            break;
-
-        default:
-            USBD_LOG_ERR("Illegal device req 0x%02x\r\n", setup->bRequest);
-            ret = false;
-            break;
-    }
-
-    return ret;
-}
-
-/**
- * @brief handle a standard interface request
- *
- * @param [in]     setup    The setup packet
- * @param [in,out] len      Pointer to data length
- * @param [in]     ep0_data_buf Data buffer
- *
- * @return true if the request was handled successfully
- */
-static bool usbd_std_interface_req_handler(struct usb_setup_packet *setup,
-                                           uint8_t **data, uint32_t *len)
-{
-    /** The device must be configured to accept standard interface
-     * requests and the addressed Interface must be valid.
-     */
-    if (!is_device_configured() ||
-        (!is_interface_valid((uint8_t)setup->wIndex))) {
-        return false;
-    }
-
-    switch (setup->bRequest) {
-        case USB_REQUEST_GET_STATUS:
-            /* no bits specified */
-            *data = (uint8_t *)&usbd_core_cfg.remote_wakeup;
-
-            *len = 2;
-            break;
-
-        case USB_REQUEST_CLEAR_FEATURE:
-        case USB_REQUEST_SET_FEATURE:
-            /* not defined for interface */
-            return false;
-
-        case USB_REQUEST_GET_INTERFACE:
-            /** This handler is called for classes that does not support
-             * alternate Interfaces so always return 0. Classes that
-             * support alternative interfaces handles GET_INTERFACE
-             * in custom_handler.
-             */
-            *data = (uint8_t *)&usbd_core_cfg.reserved;
-
-            *len = 1;
-            break;
-
-        case USB_REQUEST_SET_INTERFACE:
-            USBD_LOG_DBG("REQ_SET_INTERFACE\r\n");
-            usbd_set_interface(setup->wIndex, setup->wValue);
-            break;
-
-        default:
-            USBD_LOG_ERR("Illegal interface req 0x%02x\r\n", setup->bRequest);
-            return false;
-    }
-
-    return true;
-}
-
-/**
- * @brief handle a standard endpoint request
- *
- * @param [in]     setup    The setup packet
- * @param [in,out] len      Pointer to data length
- * @param [in]     ep0_data_buf Data buffer
- *
- * @return true if the request was handled successfully
- */
-static bool usbd_std_endpoint_req_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    uint8_t ep = (uint8_t)setup->wIndex;
-
-    /* Check if request addresses valid Endpoint */
-    if (!is_ep_valid(ep)) {
-        return false;
-    }
-
-    switch (setup->bRequest) {
-        case USB_REQUEST_GET_STATUS:
-
-            /** This request is valid for Control Endpoints when
-             * the device is not yet configured. For other
-             * Endpoints the device must be configured.
-             * Firstly check if addressed ep is Control Endpoint.
-             * If no then the device must be in Configured state
-             * to accept the request.
-             */
-            if (((ep & 0x7f) == 0) || is_device_configured()) {
-                /* bit 0 - Endpoint halted or not */
-                usbd_ep_is_stalled(ep, (uint8_t *)&usbd_core_cfg.remote_wakeup);
-                *data = (uint8_t *)&usbd_core_cfg.remote_wakeup;
-
-                *len = 2;
-                break;
-            }
-
-            return false;
-
-        case USB_REQUEST_CLEAR_FEATURE:
-            if (setup->wValue == USB_FEATURE_ENDPOINT_STALL) {
-                /** This request is valid for Control Endpoints when
-                 * the device is not yet configured. For other
-                 * Endpoints the device must be configured.
-                 * Firstly check if addressed ep is Control Endpoint.
-                 * If no then the device must be in Configured state
-                 * to accept the request.
-                 */
-                if (((ep & 0x7f) == 0) || is_device_configured()) {
-                    USBD_LOG_ERR("ep:%x clear halt\r\n", ep);
-                    usbd_ep_clear_stall(ep);
-                    usbd_event_notify_handler(USB_EVENT_CLEAR_HALT, NULL);
-                    break;
-                }
-            }
-
-            /* only ENDPOINT_HALT defined for endpoints */
-            return false;
-
-        case USB_REQUEST_SET_FEATURE:
-            if (setup->wValue == USB_FEATURE_ENDPOINT_STALL) {
-                /** This request is valid for Control Endpoints when
-                 * the device is not yet configured. For other
-                 * Endpoints the device must be configured.
-                 * Firstly check if addressed ep is Control Endpoint.
-                 * If no then the device must be in Configured state
-                 * to accept the request.
-                 */
-                if (((ep & 0x7f) == 0) || is_device_configured()) {
-                    /* set HALT by stalling */
-                    USBD_LOG_ERR("ep:%x set halt\r\n", ep);
-                    usbd_ep_set_stall(ep);
-                    usbd_event_notify_handler(USB_EVENT_SET_HALT, NULL);
-                    break;
-                }
-            }
-
-            /* only ENDPOINT_HALT defined for endpoints */
-            return false;
-
-        case USB_REQUEST_SYNCH_FRAME:
-
-            /* For Synch Frame request the device must be configured */
-            if (is_device_configured()) {
-                /* Not supported, return false anyway */
-                USBD_LOG_DBG("ep req 0x%02x not implemented\r\n", setup->bRequest);
-            }
-
-            return false;
-
-        default:
-            USBD_LOG_ERR("Illegal ep req 0x%02x\r\n", setup->bRequest);
-            return false;
-    }
-
-    return true;
-}
-
-/**
- * @brief default handler for standard ('chapter 9') requests
- *
- * If a custom request handler was installed, this handler is called first.
- *
- * @param [in]     setup    The setup packet
- * @param [in]     ep0_data_buf Data buffer
- * @param [in,out] len      Pointer to data length
- *
- * @return true if the request was handled successfully
- */
-static int usbd_standard_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    int rc = 0;
-
-    switch (setup->bmRequestType_b.Recipient) {
-        case USB_REQUEST_TO_DEVICE:
-            if (usbd_std_device_req_handler(setup, data, len) == false) {
-                rc = -1;
-            }
-
-            break;
-
-        case USB_REQUEST_TO_INTERFACE:
-            if (usbd_std_interface_req_handler(setup, data, len) == false) {
-                rc = -1;
-            }
-
-            break;
-
-        case USB_REQUEST_TO_ENDPOINT:
-            if (usbd_std_endpoint_req_handler(setup, data, len) == false) {
-                rc = -1;
-            }
-
-            break;
-
-        default:
-            rc = -1;
-    }
-
-    return rc;
-}
-
-/*
- * The functions usbd_class_request_handler(), usbd_custom_request_handler() and usbd_vendor_request_handler()
- * go through the interfaces one after the other and compare the
- * bInterfaceNumber with the wIndex and and then call the appropriate
- * callback of the USB function.
- * Note, a USB function can have more than one interface and the
- * request does not have to be directed to the first interface (unlikely).
- * These functions can be simplified and moved to usb_handle_request()
- * when legacy initialization throgh the usb_set_config() and
- * usb_enable() is no longer needed.
- */
-static int usbd_class_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("bRequest 0x%02x, wIndex 0x%04x\r\n", setup->bRequest, setup->wIndex);
-
-    if (setup->bmRequestType_b.Recipient != USB_REQUEST_TO_INTERFACE) {
-        return -1;
-    }
-
-    usb_slist_t *i, *j;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
-
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
-
-            if (intf->class_handler && (intf->intf_num == (setup->wIndex & 0xFF))) {
-                return intf->class_handler(setup, data, len);
-            }
-        }
-    }
-    return -1;
-}
-
-static int usbd_vendor_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("bRequest 0x%02x, wValue0x%04x, wIndex 0x%04x\r\n", setup->bRequest, setup->wValue, setup->wIndex);
-
-    // if(setup->bmRequestType_b.Recipient != USB_REQUEST_TO_DEVICE)
-    // {
-    //     return -1;
-    // }
-
-    if (msosv1_desc) {
-        if (setup->bRequest == msosv1_desc->vendor_code) {
-            switch (setup->wIndex) {
-                case 0x04:
-                    USBD_LOG_INFO("get Compat ID\r\n");
-                    *data = (uint8_t *)msosv1_desc->compat_id;
-                    *len = msosv1_desc->compat_id_len;
-
-                    return 0;
-                case 0x05:
-                    USBD_LOG_INFO("get Compat id properties\r\n");
-                    *data = (uint8_t *)msosv1_desc->comp_id_property;
-                    *len = msosv1_desc->comp_id_property_len;
-
-                    return 0;
-                default:
-                    USBD_LOG_ERR("unknown vendor code\r\n");
-                    return -1;
-            }
-        }
-    } else if (msosv2_desc) {
-        if (setup->bRequest == msosv2_desc->vendor_code) {
-            switch (setup->wIndex) {
-                case WINUSB_REQUEST_GET_DESCRIPTOR_SET:
-                    USBD_LOG_INFO("GET MS OS 2.0 Descriptor\r\n");
-                    *data = (uint8_t *)msosv2_desc->compat_id;
-                    *len = msosv2_desc->compat_id_len;
-                    return 0;
-                default:
-                    USBD_LOG_ERR("unknown vendor code\r\n");
-                    return -1;
-            }
-        }
-    }
-
-    usb_slist_t *i, *j;
-
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
-
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
-
-            if (intf->vendor_handler && !intf->vendor_handler(setup, data, len)) {
-                return 0;
-            }
-        }
-    }
-
-    return -1;
-}
-
-static int usbd_custom_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    USBD_LOG_DBG("bRequest 0x%02x, wIndex 0x%04x\r\n", setup->bRequest, setup->wIndex);
-
-    if (setup->bmRequestType_b.Recipient != USB_REQUEST_TO_INTERFACE) {
-        return -1;
-    }
-
-    usb_slist_t *i, *j;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
-
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
-
-            if (intf->custom_handler && (intf->intf_num == (setup->wIndex & 0xFF))) {
-                return intf->custom_handler(setup, data, len);
-            }
-        }
-    }
-
-    return -1;
-}
-
-/**
- * @brief handle a request by calling one of the installed request handlers
- *
- * Local function to handle a request by calling one of the installed request
- * handlers. In case of data going from host to device, the data is at *ppbData.
- * In case of data going from device to host, the handler can either choose to
- * write its data at *ppbData or update the data pointer.
- *
- * @param [in]     setup The setup packet
- * @param [in,out] data  Data buffer
- * @param [in,out] len   Pointer to data length
- *
- * @return true if the request was handles successfully
- */
-static bool usbd_setup_request_handler(struct usb_setup_packet *setup, uint8_t **data, uint32_t *len)
-{
-    uint8_t type = setup->bmRequestType_b.Type;
-
-    if (type == USB_REQUEST_STANDARD) {
-        if (!usbd_custom_request_handler(setup, data, len)) {
-            return true;
-        }
-
-        if (usbd_standard_request_handler(setup, data, len) < 0) {
-            USBD_LOG_ERR("Handler Error %d\r\n", type);
-            usbd_print_setup(setup);
-            return false;
-        }
-    } else if (type == USB_REQUEST_CLASS) {
-        if (usbd_class_request_handler(setup, data, len) < 0) {
-            USBD_LOG_ERR("Handler Error %d\r\n", type);
-            usbd_print_setup(setup);
-            return false;
-        }
-    } else if (type == USB_REQUEST_VENDOR) {
-        if (usbd_vendor_request_handler(setup, data, len) < 0) {
-            USBD_LOG_ERR("Handler Error %d\r\n", type);
-            usbd_print_setup(setup);
-            return false;
-        }
-    } else {
-        return false;
-    }
-
-    return true;
-}
-/**
- * @brief send data or status to host
- *
- * @return N/A
- */
-static void usbd_send_to_host(uint16_t len)
-{
-    uint32_t chunk = 0U;
-
-    if (usbd_core_cfg.zlp_flag == false) {
-        chunk = usbd_core_cfg.ep0_data_buf_residue;
-
-        if (usbd_ep_write(USB_CONTROL_IN_EP0, usbd_core_cfg.ep0_data_buf, usbd_core_cfg.ep0_data_buf_residue, &chunk) < 0) {
-            USBD_LOG_ERR("USB write data failed\r\n");
-            return;
-        }
-
-        usbd_core_cfg.ep0_data_buf += chunk;
-        usbd_core_cfg.ep0_data_buf_residue -= chunk;
-
-        /*
-         * Set ZLP flag when host asks for a bigger length and the
-         * last chunk is wMaxPacketSize long, to indicate the last
-         * packet.
-         */
-        if ((!usbd_core_cfg.ep0_data_buf_residue) && (usbd_core_cfg.ep0_data_buf_len >= USB_CTRL_EP_MPS) && !(usbd_core_cfg.ep0_data_buf_len % USB_CTRL_EP_MPS)) {
-            /* Transfers a zero-length packet next*/
-            usbd_core_cfg.zlp_flag = true;
-        }
-    } else {
-        usbd_core_cfg.zlp_flag = false;
-        USBD_LOG_DBG("send zlp\r\n");
-        if (usbd_ep_write(USB_CONTROL_IN_EP0, NULL, 0, NULL) < 0) {
-            USBD_LOG_ERR("USB write zlp failed\r\n");
-            return;
-        }
-    }
-}
-
-static void usbd_ep0_setup_handler(void)
-{
-    struct usb_setup_packet *setup = &usbd_core_cfg.setup;
-
-    /*
-    * OUT transfer, Setup packet,
-    * reset request message state machine
-    */
-    if (usbd_ep_read(USB_CONTROL_OUT_EP0, (uint8_t *)setup,
-                     sizeof(struct usb_setup_packet), NULL) < 0) {
-        USBD_LOG_ERR("Read Setup Packet failed\r\n");
-        usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-        return;
-    }
-
-    //usbd_print_setup(setup);
-
-    if (setup->wLength > USB_REQUEST_BUFFER_SIZE) {
-        if (setup->bmRequestType_b.Dir != USB_REQUEST_DEVICE_TO_HOST) {
-            USBD_LOG_ERR("Request buffer too small\r\n");
-            usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-            return;
-        }
-    }
-
-    // usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
-    usbd_core_cfg.ep0_data_buf_residue = setup->wLength;
-    usbd_core_cfg.ep0_data_buf_len = setup->wLength;
-    usbd_core_cfg.zlp_flag = false;
-
-    /* this maybe set code in class request code  */
-    if (setup->wLength &&
-        setup->bmRequestType_b.Dir == USB_REQUEST_HOST_TO_DEVICE) {
-        USBD_LOG_DBG("prepare to out data\r\n");
-        return;
-    }
-
-    /* Ask installed handler to process request */
-    if (!usbd_setup_request_handler(setup, &usbd_core_cfg.ep0_data_buf, &usbd_core_cfg.ep0_data_buf_len)) {
-        USBD_LOG_ERR("usbd_setup_request_handler failed\r\n");
-        usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-        return;
-    }
-
-    /* Send smallest of requested and offered length */
-    usbd_core_cfg.ep0_data_buf_residue = MIN(usbd_core_cfg.ep0_data_buf_len,
-                                             setup->wLength);
-    /*Send data or status to host*/
-    usbd_send_to_host(setup->wLength);
-}
-
-static void usbd_ep0_out_handler(void)
-{
-    uint32_t chunk = 0U;
-    struct usb_setup_packet *setup = &usbd_core_cfg.setup;
-
-    /* OUT transfer, status packets */
-    if (usbd_core_cfg.ep0_data_buf_residue == 0) {
-        /* absorb zero-length status message */
-        USBD_LOG_DBG("recv status\r\n");
-
-        if (usbd_ep_read(USB_CONTROL_OUT_EP0,
-                         NULL,
-                         0, NULL) < 0) {
-            USBD_LOG_ERR("Read DATA Packet failed\r\n");
-            usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-        }
-
-        return;
-    }
-
-    usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
-
-    /* OUT transfer, data packets */
-    if (usbd_ep_read(USB_CONTROL_OUT_EP0,
-                     usbd_core_cfg.ep0_data_buf,
-                     usbd_core_cfg.ep0_data_buf_residue, &chunk) < 0) {
-        USBD_LOG_ERR("Read DATA Packet failed\r\n");
-        usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-        return;
-    }
-
-    usbd_core_cfg.ep0_data_buf += chunk;
-    usbd_core_cfg.ep0_data_buf_residue -= chunk;
-
-    if (usbd_core_cfg.ep0_data_buf_residue == 0) {
-        /* Received all, send data to handler */
-        usbd_core_cfg.ep0_data_buf = usbd_core_cfg.req_data;
-
-        if (!usbd_setup_request_handler(setup, &usbd_core_cfg.ep0_data_buf, &usbd_core_cfg.ep0_data_buf_len)) {
-            USBD_LOG_ERR("usbd_setup_request_handler1 failed\r\n");
-            usbd_ep_set_stall(USB_CONTROL_IN_EP0);
-            return;
-        }
-
-        /*Send status to host*/
-        usbd_send_to_host(setup->wLength);
-    } else {
-        USBD_LOG_ERR("ep0_data_buf_residue is not zero\r\n");
-    }
-}
-
-static void usbd_ep0_in_handler(void)
-{
-    struct usb_setup_packet *setup = &usbd_core_cfg.setup;
-
-    /* Send more data if available */
-    if (usbd_core_cfg.ep0_data_buf_residue != 0 || usbd_core_cfg.zlp_flag == true) {
-        usbd_send_to_host(setup->wLength);
-    } else {
-        /*ep0 tx has completed,and no data to send,so do nothing*/
-    }
-}
-
-static void usbd_ep_out_handler(uint8_t ep)
-{
-#if USBD_EP_CALLBACK_SEARCH_METHOD == 0
-    usb_slist_t *i, *j, *k;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
-
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
-
-            usb_slist_for_each(k, &intf->ep_list)
-            {
-                usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list);
-
-                if ((ept->ep_addr == ep) && ept->ep_cb) {
-                    ept->ep_cb(ep);
-                }
-            }
-        }
-    }
-#else
-
-    if (usbd_core_cfg.out_ep_cb[ep & 0x7f]) {
-        usbd_core_cfg.out_ep_cb[ep & 0x7f](ep);
-    }
-
-#endif
-}
-
-static void usbd_ep_in_handler(uint8_t ep)
-{
-#if USBD_EP_CALLBACK_SEARCH_METHOD == 0
-    usb_slist_t *i, *j, *k;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
-
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
-
-            usb_slist_for_each(k, &intf->ep_list)
-            {
-                usbd_endpoint_t *ept = usb_slist_entry(k, struct usbd_endpoint, list);
-
-                if ((ept->ep_addr == ep) && ept->ep_cb) {
-                    ept->ep_cb(ep);
-                }
-            }
-        }
-    }
-#else
-
-    if (usbd_core_cfg.in_ep_cb[ep & 0x7f]) {
-        usbd_core_cfg.in_ep_cb[ep & 0x7f](ep);
-    }
-
-#endif
-}
-
-static void usbd_class_event_notify_handler(uint8_t event, void *arg)
-{
-    usb_slist_t *i, *j;
-    usb_slist_for_each(i, &usbd_class_head)
-    {
-        usbd_class_t *class = usb_slist_entry(i, struct usbd_class, list);
-
-        usb_slist_for_each(j, &class->intf_list)
-        {
-            usbd_interface_t *intf = usb_slist_entry(j, struct usbd_interface, list);
-
-            if (intf->notify_handler) {
-                intf->notify_handler(event, arg);
-            }
-        }
-    }
-}
-
-void usbd_event_notify_handler(uint8_t event, void *arg)
-{
-    switch (event) {
-        case USB_EVENT_RESET:
-            usbd_set_address(0);
-#if USBD_EP_CALLBACK_SEARCH_METHOD == 1
-            usbd_ep_callback_register();
-#endif
-
-        case USB_EVENT_ERROR:
-        case USB_EVENT_SOF:
-        case USB_EVENT_CONNECTED:
-        case USB_EVENT_CONFIGURED:
-        case USB_EVENT_SUSPEND:
-        case USB_EVENT_DISCONNECTED:
-        case USB_EVENT_RESUME:
-        case USB_EVENT_SET_INTERFACE:
-        case USB_EVENT_SET_REMOTE_WAKEUP:
-        case USB_EVENT_CLEAR_REMOTE_WAKEUP:
-        case USB_EVENT_SET_HALT:
-        case USB_EVENT_CLEAR_HALT:
-            usbd_class_event_notify_handler(event, arg);
-            break;
-
-        case USB_EVENT_SETUP_NOTIFY:
-            usbd_ep0_setup_handler();
-            break;
-
-        case USB_EVENT_EP0_IN_NOTIFY:
-            usbd_ep0_in_handler();
-            break;
-
-        case USB_EVENT_EP0_OUT_NOTIFY:
-            usbd_ep0_out_handler();
-            break;
-
-        case USB_EVENT_EP_IN_NOTIFY:
-            usbd_ep_in_handler((uint32_t)arg);
-            break;
-
-        case USB_EVENT_EP_OUT_NOTIFY:
-            usbd_ep_out_handler((uint32_t)arg);
-            break;
-
-        default:
-            USBD_LOG_ERR("USB unknown event: %d\r\n", event);
-            break;
-    }
-}
-
-void usbd_desc_register(const uint8_t *desc)
-{
-    usbd_core_cfg.descriptors = desc;
-}
-/* Register MS OS Descriptors version 1 */
-void usbd_msosv1_desc_register(struct usb_msosv1_descriptor *desc)
-{
-    msosv1_desc = desc;
-}
-
-/* Register MS OS Descriptors version 2 */
-void usbd_msosv2_desc_register(struct usb_msosv2_descriptor *desc)
-{
-    msosv2_desc = desc;
-}
-
-void usbd_bos_desc_register(struct usb_bos_descriptor *desc)
-{
-    bos_desc = desc;
-}
-
-void usbd_class_register(usbd_class_t *class)
-{
-    usb_slist_add_tail(&usbd_class_head, &class->list);
-    usb_slist_init(&class->intf_list);
-}
-
-void usbd_class_add_interface(usbd_class_t *class, usbd_interface_t *intf)
-{
-    static uint8_t intf_offset = 0;
-    intf->intf_num = intf_offset;
-    usb_slist_add_tail(&class->intf_list, &intf->list);
-    usb_slist_init(&intf->ep_list);
-    intf_offset++;
-}
-
-void usbd_interface_add_endpoint(usbd_interface_t *intf, usbd_endpoint_t *ep)
-{
-    usb_slist_add_tail(&intf->ep_list, &ep->list);
-}
-
-bool usb_device_is_configured(void)
-{
-    return usbd_core_cfg.configured;
-}
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.h
deleted file mode 100644
index 6884a76ef..000000000
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/usb_stack/core/usbd_core.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/**
- * @file usbd_core.h
- *
- * Copyright (c) 2021 Bouffalolab team
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.  The
- * ASF licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the
- * License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
- * License for the specific language governing permissions and limitations
- * under the License.
- *
- */
-#ifndef _USBD_CORE_H
-#define _USBD_CORE_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "usb_util.h"
-#include "usb_def.h"
-#include "usb_dc.h"
-
-enum usb_event_type {
-    /** USB error reported by the controller */
-    USB_EVENT_ERROR,
-    /** USB reset */
-    USB_EVENT_RESET,
-    /** Start of Frame received */
-    USB_EVENT_SOF,
-    /** USB connection established, hardware enumeration is completed */
-    USB_EVENT_CONNECTED,
-    /** USB configuration done */
-    USB_EVENT_CONFIGURED,
-    /** USB connection suspended by the HOST */
-    USB_EVENT_SUSPEND,
-    /** USB connection lost */
-    USB_EVENT_DISCONNECTED,
-    /** USB connection resumed by the HOST */
-    USB_EVENT_RESUME,
-
-    /** USB interface selected */
-    USB_EVENT_SET_INTERFACE,
-    /** USB interface selected */
-    USB_EVENT_SET_REMOTE_WAKEUP,
-    /** USB interface selected */
-    USB_EVENT_CLEAR_REMOTE_WAKEUP,
-    /** Set Feature ENDPOINT_HALT received */
-    USB_EVENT_SET_HALT,
-    /** Clear Feature ENDPOINT_HALT received */
-    USB_EVENT_CLEAR_HALT,
-    /** setup packet received */
-    USB_EVENT_SETUP_NOTIFY,
-    /** ep0 in packet received */
-    USB_EVENT_EP0_IN_NOTIFY,
-    /** ep0 out packet received */
-    USB_EVENT_EP0_OUT_NOTIFY,
-    /** ep in packet except ep0 received */
-    USB_EVENT_EP_IN_NOTIFY,
-    /** ep out packet except ep0 received */
-    USB_EVENT_EP_OUT_NOTIFY,
-    /** Initial USB connection status */
-    USB_EVENT_UNKNOWN
-};
-
-/**
- * @brief Callback function signature for the USB Endpoint status
- */
-typedef void (*usbd_endpoint_callback)(uint8_t ep);
-
-/**
- * @brief Callback function signature for class specific requests
- *
- * Function which handles Class specific requests corresponding to an
- * interface number specified in the device descriptor table. For host
- * to device direction the 'len' and 'payload_data' contain the length
- * of the received data and the pointer to the received data respectively.
- * For device to host class requests, 'len' and 'payload_data' should be
- * set by the callback function with the length and the address of the
- * data to be transmitted buffer respectively.
- */
-typedef int (*usbd_request_handler)(struct usb_setup_packet *setup,
-                                    uint8_t **data, uint32_t *transfer_len);
-
-/* callback function pointer structure for Application to handle events */
-typedef void (*usbd_notify_handler)(uint8_t event, void *arg);
-
-typedef struct usbd_endpoint {
-    usb_slist_t list;
-    uint8_t ep_addr;
-    usbd_endpoint_callback ep_cb;
-} usbd_endpoint_t;
-
-typedef struct usbd_interface {
-    usb_slist_t list;
-    /** Handler for USB Class specific Control (EP 0) communications */
-    usbd_request_handler class_handler;
-    /** Handler for USB Vendor specific commands */
-    usbd_request_handler vendor_handler;
-    /** Handler for USB custom specific commands */
-    usbd_request_handler custom_handler;
-    /** Handler for USB event notify commands */
-    usbd_notify_handler notify_handler;
-    uint8_t intf_num;
-    usb_slist_t ep_list;
-} usbd_interface_t;
-
-typedef struct usbd_class {
-    usb_slist_t list;
-    const char *name;
-    usb_slist_t intf_list;
-} usbd_class_t;
-
-void usbd_event_notify_handler(uint8_t event, void *arg);
-
-void usbd_desc_register(const uint8_t *desc);
-void usbd_class_register(usbd_class_t *class);
-void usbd_msosv1_desc_register(struct usb_msosv1_descriptor *desc);
-void usbd_msosv2_desc_register(struct usb_msosv2_descriptor *desc);
-void usbd_bos_desc_register(struct usb_bos_descriptor *desc);
-void usbd_class_add_interface(usbd_class_t *class, usbd_interface_t *intf);
-void usbd_interface_add_endpoint(usbd_interface_t *intf, usbd_endpoint_t *ep);
-bool usb_device_is_configured(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/bl702_flash.ld b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/bl702_flash.ld
index 2ae61c596..3349c5441 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/bl702_flash.ld
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/bl702_flash.ld
@@ -175,7 +175,7 @@ SECTIONS
 
         . = ALIGN(4);
         __tcm_code_end__ = .;
-    } > itcm_memory
+    } > dtcm_memory
 
     __hbn_load_addr = __itcm_load_addr + SIZEOF(.itcm_region);
 
@@ -203,25 +203,7 @@ SECTIONS
         . = ALIGN(4);
         __tcm_data_end__ = .;
     } > dtcm_memory
-    /*************************************************************************/
-    /* .stack_dummy section doesn't contains any symbols. It is only
-     * used for linker to calculate size of stack sections, and assign
-     * values to stack symbols later */
-    .stack_dummy (NOLOAD):
-    {
-        . = ALIGN(0x4);
-        . = . + StackSize;
-        . = ALIGN(0x4);
-    } > dtcm_memory
-
-    /* Set stack top to end of RAM, and stack limit move down by
-     * size of stack_dummy section */
-    __StackTop = ORIGIN(dtcm_memory) + LENGTH(dtcm_memory);
-    PROVIDE( __freertos_irq_stack_top = __StackTop);
-    __StackLimit = __StackTop - SIZEOF(.stack_dummy);
-    /* Check if data + heap + stack exceeds RAM limit */
-    ASSERT(__StackLimit >= __tcm_data_end__, "region RAM overflowed with stack")
-    /*************************************************************************/
+   
 
     /*************************************************************************/
     /* .stack_dummy section doesn't contains any symbols. It is only
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/inc/hal_dma.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/inc/hal_dma.h
index dda00291a..9d51c162e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/inc/hal_dma.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/inc/hal_dma.h
@@ -81,10 +81,10 @@ enum dma_index_type {
 #define DMA_TRANSFER_WIDTH_16BIT 1
 #define DMA_TRANSFER_WIDTH_32BIT 2
 
-#define DMA_BURST_1BYTE  0
-#define DMA_BURST_4BYTE  1
-#define DMA_BURST_8BYTE  2
-#define DMA_BURST_16BYTE 3
+#define DMA_BURST_INCR1  0
+#define DMA_BURST_INCR4  1
+#define DMA_BURST_INCR8  2
+#define DMA_BURST_INCR16 3
 
 #define DMA_ADDR_UART0_TDR (0x4000A000 + 0x88)
 #define DMA_ADDR_UART0_RDR (0x4000A000 + 0x8C)
@@ -174,13 +174,13 @@ typedef struct dma_device {
     uint8_t dst_burst_size;
     uint8_t src_width;
     uint8_t dst_width;
-    dma_lli_ctrl_t *lli_cfg;
+    uint8_t intr; /* private param */
+    dma_lli_ctrl_t *lli_cfg;/* private param*/
 } dma_device_t;
 
 #define DMA_DEV(dev) ((dma_device_t *)dev)
 
 int dma_register(enum dma_index_type index, const char *name);
-int dma_allocate_register(const char *name);
 int dma_reload(struct device *dev, uint32_t src_addr, uint32_t dst_addr, uint32_t transfer_size);
 
 #ifdef __cplusplus
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_boot2.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_boot2.c
index 0767d5215..c906b6249 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_boot2.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_boot2.c
@@ -1,13 +1,13 @@
 #include "hal_boot2.h"
-#include "hal_flash.h"
 #include "bl702_ef_ctrl.h"
-#include "bl702_hbn.h"
 #include "bl702_glb.h"
+#include "bl702_hbn.h"
 #include "bl702_xip_sflash.h"
-#include "tzc_sec_reg.h"
+#include "hal_flash.h"
 #include "hal_gpio.h"
-#include "softcrc.h"
 #include "hal_sec_hash.h"
+#include "softcrc.h"
+#include "tzc_sec_reg.h"
 
 /**
  * @brief boot2 custom
@@ -15,10 +15,7 @@
  * @param None
  * @return uint32
  */
-uint32_t hal_boot2_custom(void)
-{
-    return 0;
-}
+uint32_t hal_boot2_custom(void) { return 0; }
 
 /**
  * @brief get efuse Boot2 config
@@ -28,56 +25,49 @@ uint32_t hal_boot2_custom(void)
  * @param
  * @return None
  */
-void hal_boot2_get_efuse_cfg(boot2_efuse_hw_config *efuse_cfg)
-{
-    uint32_t tmp;
-    uint32_t rootClk;
-    uint8_t hdiv = 0, bdiv = 0;
-
-    /* save bclk fclk div and root clock sel */
-    bdiv = GLB_Get_BCLK_Div();
-    hdiv = GLB_Get_HCLK_Div();
-    rootClk = BL_RD_REG(HBN_BASE, HBN_GLB);
-
-    /* change root clock to rc32m for efuse operation */
-    HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_RC32M);
-
-    /* Get sign and aes type*/
-    EF_Ctrl_Read_Secure_Boot((EF_Ctrl_Sign_Type *)efuse_cfg->sign, (EF_Ctrl_SF_AES_Type *)efuse_cfg->encrypted);
-    /* Get hash:aes key slot 0 and slot1*/
-    EF_Ctrl_Read_AES_Key(0, (uint32_t *)efuse_cfg->pk_hash_cpu0, 8);
-    EF_Ctrl_Read_Chip_ID(efuse_cfg->chip_id);
-    /* Get HBN check sign config */
-    EF_Ctrl_Read_Sw_Usage(0, &tmp);
-    efuse_cfg->hbn_check_sign = (tmp >> 22) & 0x01;
-
-    /* restore bclk fclk div and root clock sel */
-    GLB_Set_System_CLK_Div(hdiv, bdiv);
-    BL_WR_REG(HBN_BASE, HBN_GLB, rootClk);
-    __NOP();
-    __NOP();
-    __NOP();
-    __NOP();
+void hal_boot2_get_efuse_cfg(boot2_efuse_hw_config *efuse_cfg) {
+  uint32_t tmp;
+  uint32_t rootClk;
+  uint8_t  hdiv = 0, bdiv = 0;
+
+  /* save bclk fclk div and root clock sel */
+  bdiv    = GLB_Get_BCLK_Div();
+  hdiv    = GLB_Get_HCLK_Div();
+  rootClk = BL_RD_REG(HBN_BASE, HBN_GLB);
+
+  /* change root clock to rc32m for efuse operation */
+  HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_RC32M);
+
+  /* Get sign and aes type*/
+  EF_Ctrl_Read_Secure_Boot((EF_Ctrl_Sign_Type *)efuse_cfg->sign, (EF_Ctrl_SF_AES_Type *)efuse_cfg->encrypted);
+  /* Get hash:aes key slot 0 and slot1*/
+  EF_Ctrl_Read_AES_Key(0, (uint32_t *)efuse_cfg->pk_hash_cpu0, 8);
+  EF_Ctrl_Read_Chip_ID(efuse_cfg->chip_id);
+  /* Get HBN check sign config */
+  EF_Ctrl_Read_Sw_Usage(0, &tmp);
+  efuse_cfg->hbn_check_sign = (tmp >> 22) & 0x01;
+
+  /* restore bclk fclk div and root clock sel */
+  GLB_Set_System_CLK_Div(hdiv, bdiv);
+  BL_WR_REG(HBN_BASE, HBN_GLB, rootClk);
+  __NOP();
+  __NOP();
+  __NOP();
+  __NOP();
 }
 /**
  * @brief reset sec eng clock
  *
  * @return
  */
-void hal_boot2_reset_sec_eng(void)
-{
-    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_SEC);
-}
+void hal_boot2_reset_sec_eng(void) { GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_SEC); }
 
 /**
  * @brief system soft reset
  *
  * @return
  */
-void hal_boot2_sw_system_reset(void)
-{
-    GLB_SW_System_Reset();
-}
+void hal_boot2_sw_system_reset(void) { GLB_SW_System_Reset(); }
 
 /**
  * @brief
@@ -87,10 +77,7 @@ void hal_boot2_sw_system_reset(void)
  * @param
  * @return
  */
-void hal_boot2_set_psmode_status(uint32_t flag)
-{
-    HBN_Set_Status_Flag(flag);
-}
+void hal_boot2_set_psmode_status(uint32_t flag) { HBN_Set_Status_Flag(flag); }
 
 /**
  * @brief
@@ -100,10 +87,7 @@ void hal_boot2_set_psmode_status(uint32_t flag)
  * @param
  * @return flag
  */
-uint32_t hal_boot2_get_psmode_status(void)
-{
-    return HBN_Get_Status_Flag();
-}
+uint32_t hal_boot2_get_psmode_status(void) { return HBN_Get_Status_Flag(); }
 
 /**
  * @brief
@@ -113,10 +97,7 @@ uint32_t hal_boot2_get_psmode_status(void)
  * @param
  * @return user define flag
  */
-uint32_t hal_boot2_get_user_fw(void)
-{
-    return BL_RD_WORD(HBN_BASE + HBN_RSV0_OFFSET);
-}
+uint32_t hal_boot2_get_user_fw(void) { return BL_RD_WORD(HBN_BASE + HBN_RSV0_OFFSET); }
 
 /**
  * @brief clr user define flag
@@ -126,10 +107,9 @@ uint32_t hal_boot2_get_user_fw(void)
  * @param
  * @return
  */
-void hal_boot2_clr_user_fw(void)
-{
-    uint32_t *p = (uint32_t *)(HBN_BASE + HBN_RSV0_OFFSET);
-    *p = 0;
+void hal_boot2_clr_user_fw(void) {
+  uint32_t *p = (uint32_t *)(HBN_BASE + HBN_RSV0_OFFSET);
+  *p          = 0;
 }
 
 /**
@@ -137,15 +117,14 @@ void hal_boot2_clr_user_fw(void)
  *
  * @return
  */
-void ATTR_TCM_SECTION hal_boot2_sboot_finish(void)
-{
-    uint32_t tmp_val;
+void ATTR_TCM_SECTION hal_boot2_sboot_finish(void) {
+  uint32_t tmp_val;
 
-    tmp_val = BL_RD_REG(TZC_SEC_BASE, TZC_SEC_TZC_ROM_CTRL);
+  tmp_val = BL_RD_REG(TZC_SEC_BASE, TZC_SEC_TZC_ROM_CTRL);
 
-    tmp_val = BL_SET_REG_BITS_VAL(tmp_val, TZC_SEC_TZC_SBOOT_DONE, 0xf);
+  tmp_val = BL_SET_REG_BITS_VAL(tmp_val, TZC_SEC_TZC_SBOOT_DONE, 0xf);
 
-    BL_WR_REG(TZC_SEC_BASE, TZC_SEC_TZC_ROM_CTRL, tmp_val);
+  BL_WR_REG(TZC_SEC_BASE, TZC_SEC_TZC_ROM_CTRL, tmp_val);
 }
 
 /**
@@ -153,14 +132,13 @@ void ATTR_TCM_SECTION hal_boot2_sboot_finish(void)
  *
  * @return
  */
-void hal_boot2_uart_gpio_init(void)
-{
-    GLB_GPIO_Type gpios[] = { GPIO_PIN_14, GPIO_PIN_15 };
+void hal_boot2_uart_gpio_init(void) {
+  GLB_GPIO_Type gpios[] = {GPIO_PIN_14, GPIO_PIN_15};
 
-    GLB_GPIO_Func_Init(GPIO_FUN_UART, gpios, 2);
+  GLB_GPIO_Func_Init(GPIO_FUN_UART, gpios, 2);
 
-    GLB_UART_Fun_Sel((GPIO_PIN_14 % 8), GLB_UART_SIG_FUN_UART0_TXD); //  GPIO_FUN_UART1_TX
-    GLB_UART_Fun_Sel((GPIO_PIN_15 % 8), GLB_UART_SIG_FUN_UART0_RXD);
+  GLB_UART_Fun_Sel((GPIO_PIN_14 % 8), GLB_UART_SIG_FUN_UART0_TXD); //  GPIO_FUN_UART1_TX
+  GLB_UART_Fun_Sel((GPIO_PIN_15 % 8), GLB_UART_SIG_FUN_UART0_RXD);
 }
 
 /**
@@ -168,13 +146,12 @@ void hal_boot2_uart_gpio_init(void)
  *
  * @return
  */
-void hal_boot2_debug_uart_gpio_init(void)
-{
-    GLB_GPIO_Type gpios[] = { GPIO_PIN_17 };
+void hal_boot2_debug_uart_gpio_init(void) {
+  GLB_GPIO_Type gpios[] = {GPIO_PIN_17};
 
-    GLB_GPIO_Func_Init(GPIO_FUN_UART, gpios, 1);
+  GLB_GPIO_Func_Init(GPIO_FUN_UART, gpios, 1);
 
-    GLB_UART_Fun_Sel((GPIO_PIN_17 % 8), GLB_UART_SIG_FUN_UART1_TXD);
+  GLB_UART_Fun_Sel((GPIO_PIN_17 % 8), GLB_UART_SIG_FUN_UART1_TXD);
 }
 
 /**
@@ -183,14 +160,13 @@ void hal_boot2_debug_uart_gpio_init(void)
  * @return
  */
 #if HAL_BOOT2_SUPPORT_USB_IAP
-void hal_boot2_debug_usb_port_init(void)
-{
-    /* must do this , or usb can not be recognized */
-    cpu_global_irq_disable();
-    cpu_global_irq_enable();
-
-    GLB_GPIO_Type gpios[] = { GPIO_PIN_7, GPIO_PIN_8 };
-    GLB_GPIO_Func_Init(GPIO_FUN_ANALOG, gpios, 2);
+void hal_boot2_debug_usb_port_init(void) {
+  /* must do this , or usb can not be recognized */
+  cpu_global_irq_disable();
+  cpu_global_irq_enable();
+
+  GLB_GPIO_Type gpios[] = {GPIO_PIN_7, GPIO_PIN_8};
+  GLB_GPIO_Func_Init(GPIO_FUN_ANALOG, gpios, 2);
 }
 #endif
 
@@ -199,279 +175,244 @@ void hal_boot2_debug_usb_port_init(void)
  *
  * @return
  */
-void hal_boot2_debug_uart_gpio_deinit(void)
-{
-    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0);
-    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1);
-    GLB_UART_Sig_Swap_Set(UART_SIG_SWAP_NONE);
+void hal_boot2_debug_uart_gpio_deinit(void) {
+  GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0);
+  GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1);
+  GLB_UART_Sig_Swap_Set(UART_SIG_SWAP_NONE);
 }
 
-
 /****************************************************************************/ /**
- * @brief  Check bootheader crc
- *
- * @param  data: bootheader data pointer
- *
- * @return boot_error_code type
- *
-*******************************************************************************/
-static uint32_t hal_boot_check_bootheader(struct hal_bootheader_t *header)
-{
-    uint32_t crc_pass = 0;
-    uint32_t crc;
-
-    if (header->bootCfg.bval.crcIgnore == 1 && header->crc32 == HAL_BOOT2_DEADBEEF_VAL) {
-        //MSG("Crc ignored\r\n");
-        crc_pass = 1;
-    } else {
-        crc = BFLB_Soft_CRC32((uint8_t *)header, sizeof(struct hal_bootheader_t) - sizeof(header->crc32));
-
-        if (header->crc32 == crc) {
-            crc_pass = 1;
-        }
+                                                                                * @brief  Check bootheader crc
+                                                                                *
+                                                                                * @param  data: bootheader data pointer
+                                                                                *
+                                                                                * @return boot_error_code type
+                                                                                *
+                                                                                *******************************************************************************/
+static uint32_t hal_boot_check_bootheader(struct hal_bootheader_t *header) {
+  uint32_t crc_pass = 0;
+  uint32_t crc;
+
+  if (header->bootCfg.bval.crcIgnore == 1 && header->crc32 == HAL_BOOT2_DEADBEEF_VAL) {
+    // MSG("Crc ignored\r\n");
+    crc_pass = 1;
+  } else {
+    crc = BFLB_Soft_CRC32((uint8_t *)header, sizeof(struct hal_bootheader_t) - sizeof(header->crc32));
+
+    if (header->crc32 == crc) {
+      crc_pass = 1;
     }
-    return crc_pass;
+  }
+  return crc_pass;
 }
 
 /****************************************************************************/ /**
- * @brief  Check if the input public key is the same as  burned in the efuse
- *
- * @param  g_boot_img_cfg: Boot image config pointer
- * @param  data: Image data pointer
- *
- * @return boot_error_code type
- *
-*******************************************************************************/
-int32_t hal_boot_parse_bootheader(boot2_image_config *boot_img_cfg, uint8_t *data)
-{
-    struct  hal_bootheader_t *header = (struct  hal_bootheader_t *)data;
-    uint32_t crc_pass = 0;
-    uint32_t i = 0;
-    uint32_t *phash = (uint32_t *)header->hash;
-
-    crc_pass=hal_boot_check_bootheader(header);
-
-    if (!crc_pass) {
-        //MSG_ERR("bootheader crc error\r\n");
-        //blsp_dump_data((uint8_t *)&crc, 4);
-        return 0x0204;
-    }
-
-    if (header->bootCfg.bval.notLoadInBoot) {
-        return 0x0202;
+                                                                                * @brief  Check if the input public key is the same as  burned in the efuse
+                                                                                *
+                                                                                * @param  g_boot_img_cfg: Boot image config pointer
+                                                                                * @param  data: Image data pointer
+                                                                                *
+                                                                                * @return boot_error_code type
+                                                                                *
+                                                                                *******************************************************************************/
+int32_t hal_boot_parse_bootheader(boot2_image_config *boot_img_cfg, uint8_t *data) {
+  struct hal_bootheader_t *header   = (struct hal_bootheader_t *)data;
+  uint32_t                 crc_pass = 0;
+  uint32_t                 i        = 0;
+  uint32_t                *phash    = (uint32_t *)header->hash;
+
+  crc_pass = hal_boot_check_bootheader(header);
+
+  if (!crc_pass) {
+    // MSG_ERR("bootheader crc error\r\n");
+    // blsp_dump_data((uint8_t *)&crc, 4);
+    return 0x0204;
+  }
+
+  if (header->bootCfg.bval.notLoadInBoot) {
+    return 0x0202;
+  }
+
+  /* Get which CPU's img it is*/
+  for (i = 0; i < HAL_BOOT2_CPU_MAX; i++) {
+    if (0 == memcmp((void *)&header->magicCode, HAL_BOOT2_CPU0_MAGIC, sizeof(header->magicCode))) {
+      break;
+    } else if (0 == memcmp((void *)&header->magicCode, HAL_BOOT2_CPU1_MAGIC, sizeof(header->magicCode))) {
+      break;
     }
+  }
 
-    /* Get which CPU's img it is*/
-    for (i = 0; i < HAL_BOOT2_CPU_MAX; i++) {
-        if (0 == memcmp((void *)&header->magicCode, HAL_BOOT2_CPU0_MAGIC,
-                        sizeof(header->magicCode))) {
-            break;
-        } else if (0 == memcmp((void *)&header->magicCode, HAL_BOOT2_CPU1_MAGIC,
-                               sizeof(header->magicCode))) {
-            break;
-        }
-    }
+  if (i == HAL_BOOT2_CPU_MAX) {
+    /* No cpu img magic match */
+    // MSG_ERR("Magic code error\r\n");
+    return 0x0203;
+  }
 
-    if (i == HAL_BOOT2_CPU_MAX) {
-        /* No cpu img magic match */
-        //MSG_ERR("Magic code error\r\n");
-        return 0x0203;
-    }
-
-    if(boot_img_cfg==NULL){
-        return 0;
-    }
-    
-    boot_img_cfg->pk_src=i;    
-    boot_img_cfg->img_valid=0;
-
-    /* Deal with pll config */
-
-    /* Encrypt and sign */
-    boot_img_cfg->basic_cfg.encrypt_type = header->bootCfg.bval.encrypt_type;
-    boot_img_cfg->basic_cfg.sign_type = header->bootCfg.bval.sign;
-    boot_img_cfg->basic_cfg.key_sel = header->bootCfg.bval.key_sel;
-
-    /* Xip relative */
-    boot_img_cfg->basic_cfg.no_segment = header->bootCfg.bval.no_segment;
-    boot_img_cfg->cpu_cfg[0].cache_enable = header->bootCfg.bval.cache_enable;
-    boot_img_cfg->basic_cfg.aes_region_lock = header->bootCfg.bval.aes_region_lock;
-    //boot_img_cfg->cpu_cfg[1].halt_cpu = header->bootCfg.bval.halt_cpu1;
-    boot_img_cfg->cpu_cfg[0].cache_way_dis = header->bootCfg.bval.cache_way_disable;
-    boot_img_cfg->basic_cfg.hash_ignore = header->bootCfg.bval.hash_ignore;
-    /* Firmware len*/
-    boot_img_cfg->basic_cfg.img_len_cnt= header->img_segment_info.img_len;
-
-    /* Boot entry and flash offset */
-    boot_img_cfg->cpu_cfg[0].boot_entry = header->bootEntry;
-    boot_img_cfg->basic_cfg.group_image_offset = header->img_start.flash_offset;
-
-    boot_img_cfg->cpu_cfg[0].config_enable=1;
-    boot_img_cfg->cpu_cfg[0].halt_cpu =0;
-
-    //MSG("sign %d,encrypt:%d\r\n", boot_img_cfg->sign_type,boot_img_cfg->encrypt_type);
-
-    /* Check encrypt and sign match*/
-    if (g_efuse_cfg.encrypted[i] != 0) {
-        if (boot_img_cfg->basic_cfg.encrypt_type == 0) {
-            //MSG_ERR("Encrypt not fit\r\n");
-            return 0x0205;
-        }
+  if (boot_img_cfg == NULL) {
+    return 0;
+  }
+
+  boot_img_cfg->pk_src    = i;
+  boot_img_cfg->img_valid = 0;
+
+  /* Deal with pll config */
+
+  /* Encrypt and sign */
+  boot_img_cfg->basic_cfg.encrypt_type = header->bootCfg.bval.encrypt_type;
+  boot_img_cfg->basic_cfg.sign_type    = header->bootCfg.bval.sign;
+  boot_img_cfg->basic_cfg.key_sel      = header->bootCfg.bval.key_sel;
+
+  /* Xip relative */
+  boot_img_cfg->basic_cfg.no_segment      = header->bootCfg.bval.no_segment;
+  boot_img_cfg->cpu_cfg[0].cache_enable   = header->bootCfg.bval.cache_enable;
+  boot_img_cfg->basic_cfg.aes_region_lock = header->bootCfg.bval.aes_region_lock;
+  // boot_img_cfg->cpu_cfg[1].halt_cpu = header->bootCfg.bval.halt_cpu1;
+  boot_img_cfg->cpu_cfg[0].cache_way_dis = header->bootCfg.bval.cache_way_disable;
+  boot_img_cfg->basic_cfg.hash_ignore    = header->bootCfg.bval.hash_ignore;
+  /* Firmware len*/
+  boot_img_cfg->basic_cfg.img_len_cnt = header->img_segment_info.img_len;
+
+  /* Boot entry and flash offset */
+  boot_img_cfg->cpu_cfg[0].boot_entry        = header->bootEntry;
+  boot_img_cfg->basic_cfg.group_image_offset = header->img_start.flash_offset;
+
+  boot_img_cfg->cpu_cfg[0].config_enable = 1;
+  boot_img_cfg->cpu_cfg[0].halt_cpu      = 0;
+
+  // MSG("sign %d,encrypt:%d\r\n", boot_img_cfg->sign_type,boot_img_cfg->encrypt_type);
+
+  /* Check encrypt and sign match*/
+  if (g_efuse_cfg.encrypted[i] != 0) {
+    if (boot_img_cfg->basic_cfg.encrypt_type == 0) {
+      // MSG_ERR("Encrypt not fit\r\n");
+      return 0x0205;
     }
+  }
 
-    if (g_efuse_cfg.sign[i] !=boot_img_cfg->basic_cfg.sign_type) {
-        //MSG_ERR("sign not fit\r\n");
-        boot_img_cfg->basic_cfg.sign_type = g_efuse_cfg.sign[i];
-        return 0x0206;
-    }
+  if (g_efuse_cfg.sign[i] != boot_img_cfg->basic_cfg.sign_type) {
+    // MSG_ERR("sign not fit\r\n");
+    boot_img_cfg->basic_cfg.sign_type = g_efuse_cfg.sign[i];
+    return 0x0206;
+  }
 
-    if (g_ps_mode == 1 && (!g_efuse_cfg.hbn_check_sign)) {
-        /* In HBN Mode, if user select to ignore hash and sign*/
-        boot_img_cfg->basic_cfg.hash_ignore = 1;
-    } else if ((boot_img_cfg->basic_cfg.hash_ignore == 1 && *phash != HAL_BOOT2_DEADBEEF_VAL) ||
-                g_efuse_cfg.sign[i] != 0) {
-        /* If signed or user not really want to ignore, hash can't be ignored*/
-        boot_img_cfg->basic_cfg.hash_ignore = 0;
-    }
+  if (g_ps_mode == 1 && (!g_efuse_cfg.hbn_check_sign)) {
+    /* In HBN Mode, if user select to ignore hash and sign*/
+    boot_img_cfg->basic_cfg.hash_ignore = 1;
+  } else if ((boot_img_cfg->basic_cfg.hash_ignore == 1 && *phash != HAL_BOOT2_DEADBEEF_VAL) || g_efuse_cfg.sign[i] != 0) {
+    /* If signed or user not really want to ignore, hash can't be ignored*/
+    boot_img_cfg->basic_cfg.hash_ignore = 0;
+  }
 
-    if (g_user_hash_ignored) {
-        boot_img_cfg->basic_cfg.hash_ignore = 1;
-    }
+  if (g_user_hash_ignored) {
+    boot_img_cfg->basic_cfg.hash_ignore = 1;
+  }
 
-    ARCH_MemCpy_Fast(boot_img_cfg->basic_cfg.hash, header->hash, sizeof(header->hash));
+  ARCH_MemCpy_Fast(boot_img_cfg->basic_cfg.hash, header->hash, sizeof(header->hash));
 
-    if (boot_img_cfg->basic_cfg.img_len_cnt == 0) {
-        return 0x0207;
-    }
+  if (boot_img_cfg->basic_cfg.img_len_cnt == 0) {
+    return 0x0207;
+  }
 
-    return 0;
+  return 0;
 }
 
-void ATTR_TCM_SECTION hal_boot2_clean_cache(void)
-{
-    /* no need clean again since hal_boot2_set_cache will also clean
-      unused way,and bl702 no data cache except psram */
+void ATTR_TCM_SECTION hal_boot2_clean_cache(void) {
+  /* no need clean again since hal_boot2_set_cache will also clean
+    unused way,and bl702 no data cache except psram */
 }
 
-
-BL_Err_Type ATTR_TCM_SECTION hal_boot2_set_cache(uint8_t cont_read, boot2_image_config *boot_img_cfg)
-{
-    return flash_set_cache(cont_read, boot_img_cfg->cpu_cfg[0].cache_enable, 
-                    boot_img_cfg->cpu_cfg[0].cache_way_dis,
-                    boot_img_cfg->basic_cfg.group_image_offset);
-}
- 
-/****************************************************************************/ /**
- * @brief  get the ram image name and count
- *
- * @param  img_name: ram image name in partition
- * @param  ram_img_cnt: ram image count that support boot from flash
- *
- * @return None
- *
-*******************************************************************************/
-void hal_boot2_get_ram_img_cnt(char* img_name[],uint32_t *ram_img_cnt )
-{
-    *ram_img_cnt=0;
+BL_Err_Type ATTR_TCM_SECTION hal_boot2_set_cache(uint8_t cont_read, boot2_image_config *boot_img_cfg) {
+  return flash_set_cache(cont_read, boot_img_cfg->cpu_cfg[0].cache_enable, boot_img_cfg->cpu_cfg[0].cache_way_dis, boot_img_cfg->basic_cfg.group_image_offset);
 }
 
 /****************************************************************************/ /**
- * @brief  get the ram image info
- *
- * @param  data: bootheader information
- * @param  image_offset: ram image offset in flash(from of bootheader)
- * @param  img_len: ram image length
- * @param  hash: pointer to hash pointer
- *
- * @return None
- *
-*******************************************************************************/
-void hal_boot2_get_img_info(uint8_t *data, uint32_t *image_offset, uint32_t *img_len,uint8_t **hash)
-{
-    *img_len=0;
-}
+                                                                                * @brief  get the ram image name and count
+                                                                                *
+                                                                                * @param  img_name: ram image name in partition
+                                                                                * @param  ram_img_cnt: ram image count that support boot from flash
+                                                                                *
+                                                                                * @return None
+                                                                                *
+                                                                                *******************************************************************************/
+void hal_boot2_get_ram_img_cnt(char *img_name[], uint32_t *ram_img_cnt) { *ram_img_cnt = 0; }
 
 /****************************************************************************/ /**
- * @brief  release other cpu to boot up
- *
- * @param  core: core number
- * @param  boot_addr: boot address
- *
- * @return None
- *
-*******************************************************************************/
-void ATTR_TCM_SECTION hal_boot2_release_cpu(uint32_t core, uint32_t boot_addr)
-{
-
-}
+                                                                                * @brief  get the ram image info
+                                                                                *
+                                                                                * @param  data: bootheader information
+                                                                                * @param  image_offset: ram image offset in flash(from of bootheader)
+                                                                                * @param  img_len: ram image length
+                                                                                * @param  hash: pointer to hash pointer
+                                                                                *
+                                                                                * @return None
+                                                                                *
+                                                                                *******************************************************************************/
+void hal_boot2_get_img_info(uint8_t *data, uint32_t *image_offset, uint32_t *img_len, uint8_t **hash) { *img_len = 0; }
 
 /****************************************************************************/ /**
- * @brief  get xip address according to flash addr
- *
- * @param  flash_addr: flash address
- *
- * @return XIP Address
- *
-*******************************************************************************/
-uint32_t hal_boot2_get_xip_addr(uint32_t flash_addr)
-{
-    uint32_t img_offset= SF_Ctrl_Get_Flash_Image_Offset();
-    if(flash_addr>=img_offset){
-        return BL702_FLASH_XIP_BASE+(flash_addr-img_offset);
-    }else{
-        return 0;
-    }
-}
+                                                                                * @brief  release other cpu to boot up
+                                                                                *
+                                                                                * @param  core: core number
+                                                                                * @param  boot_addr: boot address
+                                                                                *
+                                                                                * @return None
+                                                                                *
+                                                                                *******************************************************************************/
+void ATTR_TCM_SECTION hal_boot2_release_cpu(uint32_t core, uint32_t boot_addr) {}
 
 /****************************************************************************/ /**
- * @brief  get multi-group count
- *
- * @param  None
- *
- * @return 1 for multi-group 0 for not
- *
-*******************************************************************************/
-uint32_t hal_boot2_get_grp_count(void)
-{
-    return 1;
+                                                                                * @brief  get xip address according to flash addr
+                                                                                *
+                                                                                * @param  flash_addr: flash address
+                                                                                *
+                                                                                * @return XIP Address
+                                                                                *
+                                                                                *******************************************************************************/
+uint32_t hal_boot2_get_xip_addr(uint32_t flash_addr) {
+  uint32_t img_offset = SF_Ctrl_Get_Flash_Image_Offset();
+  if (flash_addr >= img_offset) {
+    return BL702_FLASH_XIP_BASE + (flash_addr - img_offset);
+  } else {
+    return 0;
+  }
 }
 
 /****************************************************************************/ /**
- * @brief  get cpu count
- *
- * @param  None
- *
- * @return 1 for multi-group 0 for not
- *
-*******************************************************************************/
-uint32_t hal_boot2_get_cpu_count(void)
-{
-    return 1;
-}
+                                                                                * @brief  get multi-group count
+                                                                                *
+                                                                                * @param  None
+                                                                                *
+                                                                                * @return 1 for multi-group 0 for not
+                                                                                *
+                                                                                *******************************************************************************/
+uint32_t hal_boot2_get_grp_count(void) { return 1; }
 
 /****************************************************************************/ /**
- * @brief  get cpu count
- *
- * @param  None
- *
- * @return 1 for multi-group 0 for not
- *
-*******************************************************************************/
-uint32_t ATTR_TCM_SECTION hal_boot2_get_feature_flag(void)
-{
-    return HAL_BOOT2_SP_FLAG;
-}
+                                                                                * @brief  get cpu count
+                                                                                *
+                                                                                * @param  None
+                                                                                *
+                                                                                * @return 1 for multi-group 0 for not
+                                                                                *
+                                                                                *******************************************************************************/
+uint32_t hal_boot2_get_cpu_count(void) { return 1; }
 
 /****************************************************************************/ /**
- * @brief  get boot header offset
- *
- * @param  None
- *
- * @return bootheader offset
- *
-*******************************************************************************/
-uint32_t hal_boot2_get_bootheader_offset(void)
-{
-    return 0x00;
-}
+                                                                                * @brief  get cpu count
+                                                                                *
+                                                                                * @param  None
+                                                                                *
+                                                                                * @return 1 for multi-group 0 for not
+                                                                                *
+                                                                                *******************************************************************************/
+uint32_t ATTR_TCM_SECTION hal_boot2_get_feature_flag(void) { return HAL_BOOT2_SP_FLAG; }
 
+/****************************************************************************/ /**
+                                                                                * @brief  get boot header offset
+                                                                                *
+                                                                                * @param  None
+                                                                                *
+                                                                                * @return bootheader offset
+                                                                                *
+                                                                                *******************************************************************************/
+uint32_t hal_boot2_get_bootheader_offset(void) { return 0x00; }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c
index 56a003739..f2581e018 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_clock.c
@@ -323,7 +323,7 @@ void peripheral_clock_init(void) {
 #if BSP_PWM_CLOCK_SOURCE == ROOT_CLOCK_SOURCE_32K_CLK
 
   for (int i = 0; i < 5; i++) {
-    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i)*0x20;
+    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i) * 0x20;
     tmp_pwm = BL_RD_REG(PWMx, PWM_CONFIG);
     BL_WR_REG(PWMx, PWM_CONFIG, BL_SET_REG_BIT(tmp_pwm, PWM_STOP_EN));
 
@@ -343,7 +343,7 @@ void peripheral_clock_init(void) {
 #elif BSP_PWM_CLOCK_SOURCE == ROOT_CLOCK_SOURCE_BCLK
 
   for (int i = 0; i < 5; i++) {
-    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i)*0x20;
+    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i) * 0x20;
     tmp_pwm = BL_RD_REG(PWMx, PWM_CONFIG);
     BL_WR_REG(PWMx, PWM_CONFIG, BL_SET_REG_BIT(tmp_pwm, PWM_STOP_EN));
 
@@ -363,7 +363,7 @@ void peripheral_clock_init(void) {
 #elif BSP_PWM_CLOCK_SOURCE == ROOT_CLOCK_SOURCE_XCLK
 
   for (int i = 0; i < 5; i++) {
-    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i)*0x20;
+    PWMx    = PWM_BASE + PWM_CHANNEL_OFFSET + (i) * 0x20;
     tmp_pwm = BL_RD_REG(PWMx, PWM_CONFIG);
     BL_WR_REG(PWMx, PWM_CONFIG, BL_SET_REG_BIT(tmp_pwm, PWM_STOP_EN));
 
@@ -456,6 +456,11 @@ void peripheral_clock_init(void) {
   tmpVal |= (1 << BL_AHB_SLAVE1_USB);
   GLB_Set_USB_CLK(1);
 #endif
+
+#if defined(BSP_USING_DMA)
+  tmpVal |= (1 << BL_AHB_SLAVE1_DMA);
+#endif
+
   BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal);
 }
 
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c
index 34fc9f01b..13f671c82 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_common.c
@@ -22,83 +22,66 @@
  */
 #include "hal_common.h"
 #include "bl702_ef_ctrl.h"
+#include "bl702_l1c.h"
 #include "bl702_romdriver.h"
 #include "bl702_sec_eng.h"
-#include "bl702_l1c.h"
 #include "hbn_reg.h"
 
 volatile uint32_t nesting = 0;
 
-void ATTR_TCM_SECTION cpu_global_irq_enable(void)
-{
-    nesting--;
-    if (nesting == 0) {
-        __enable_irq();
-    }
+void ATTR_TCM_SECTION cpu_global_irq_enable(void) {
+  nesting--;
+  if (nesting == 0) {
+    __enable_irq();
+  }
 }
 
-void ATTR_TCM_SECTION cpu_global_irq_disable(void)
-{
-    __disable_irq();
-    nesting++;
+void ATTR_TCM_SECTION cpu_global_irq_disable(void) {
+  __disable_irq();
+  nesting++;
 }
 
-void hal_por_reset(void)
-{
-    RomDriver_GLB_SW_POR_Reset();
-}
+void hal_por_reset(void) { RomDriver_GLB_SW_POR_Reset(); }
 
-void hal_system_reset(void)
-{
-    RomDriver_GLB_SW_System_Reset();
-}
+void hal_system_reset(void) { RomDriver_GLB_SW_System_Reset(); }
 
-void hal_cpu_reset(void)
-{
-    RomDriver_GLB_SW_CPU_Reset();
-}
+void hal_cpu_reset(void) { RomDriver_GLB_SW_CPU_Reset(); }
 
-void hal_get_chip_id(uint8_t chip_id[8])
-{
-    EF_Ctrl_Read_MAC_Address(chip_id);
-}
+void hal_get_chip_id(uint8_t chip_id[8]) { EF_Ctrl_Read_MAC_Address(chip_id); }
 
-void hal_enter_usb_iap(void)
-{
-    BL_WR_WORD(HBN_BASE + HBN_RSV0_OFFSET, 0x00425355); //"\0BSU"
+void hal_enter_usb_iap(void) {
+  BL_WR_WORD(HBN_BASE + HBN_RSV0_OFFSET, 0x00425355); //"\0BSU"
 
-    arch_delay_ms(1000);
-    RomDriver_GLB_SW_POR_Reset();
+  arch_delay_ms(1000);
+  RomDriver_GLB_SW_POR_Reset();
 }
 
-void ATTR_TCM_SECTION hal_jump2app(uint32_t flash_offset)
-{
-    /*flash_offset from 48K to 3.98M*/
-    if ((flash_offset >= 0xc000) && (flash_offset < (0x400000 - 20 * 1024))) {
-        void (*app_main)(void) = (void (*)(void))0x23000000;
-        BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, flash_offset);
-        L1C_Cache_Flush_Ext();
-        app_main();
-    } else {
-        while(1)
-        {}
+void ATTR_TCM_SECTION hal_jump2app(uint32_t flash_offset) {
+  /*flash_offset from 48K to 3.98M*/
+  if ((flash_offset >= 0xc000) && (flash_offset < (0x400000 - 20 * 1024))) {
+    void (*app_main)(void) = (void (*)(void))0x23000000;
+    BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, flash_offset);
+    L1C_Cache_Flush_Ext();
+    app_main();
+  } else {
+    while (1) {
     }
+  }
 }
 
-int hal_get_trng_seed(void)
-{
-    uint32_t seed[8];
-    uint32_t tmpVal;
-    tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1);
-    tmpVal |= (1 << BL_AHB_SLAVE1_SEC);
-    BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal);
+int hal_get_trng_seed(void) {
+  uint32_t seed[8];
+  uint32_t tmpVal;
+  tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1);
+  tmpVal |= (1 << BL_AHB_SLAVE1_SEC);
+  BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal);
 
-    Sec_Eng_Trng_Enable();
-    Sec_Eng_Trng_Read((uint8_t *)seed);
-    Sec_Eng_Trng_Disable();
-    tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1);
-    tmpVal &= (~(1 << BL_AHB_SLAVE1_SEC));
-    BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal);
+  Sec_Eng_Trng_Enable();
+  Sec_Eng_Trng_Read((uint8_t *)seed);
+  Sec_Eng_Trng_Disable();
+  tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1);
+  tmpVal &= (~(1 << BL_AHB_SLAVE1_SEC));
+  BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal);
 
-    return seed[0];
+  return seed[0];
 }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c
index 0fbe57f8d..240469af0 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_dma.c
@@ -23,20 +23,19 @@
 #include "hal_dma.h"
 #include "bl702_dma.h"
 
-#define DMA_CHANNEL_BASE(id_base, ch) ((id_base) + DMA_CHANNEL_OFFSET + (ch)*0x100)
+#define DMA_CHANNEL_BASE(id_base, ch) ((id_base) + DMA_CHANNEL_OFFSET + (ch) * 0x100)
 
 static const uint32_t dma_channel_base[][8] = {
     {
-        DMA_CHANNEL_BASE(DMA_BASE, 0),
-        DMA_CHANNEL_BASE(DMA_BASE, 1),
-        DMA_CHANNEL_BASE(DMA_BASE, 2),
-        DMA_CHANNEL_BASE(DMA_BASE, 3),
-        DMA_CHANNEL_BASE(DMA_BASE, 4),
-        DMA_CHANNEL_BASE(DMA_BASE, 5),
-        DMA_CHANNEL_BASE(DMA_BASE, 6),
-        DMA_CHANNEL_BASE(DMA_BASE, 7),
-    }
-
+     DMA_CHANNEL_BASE(DMA_BASE, 0),
+     DMA_CHANNEL_BASE(DMA_BASE, 1),
+     DMA_CHANNEL_BASE(DMA_BASE, 2),
+     DMA_CHANNEL_BASE(DMA_BASE, 3),
+     DMA_CHANNEL_BASE(DMA_BASE, 4),
+     DMA_CHANNEL_BASE(DMA_BASE, 5),
+     DMA_CHANNEL_BASE(DMA_BASE, 6),
+     DMA_CHANNEL_BASE(DMA_BASE, 7),
+     }
 };
 
 static void DMA0_IRQ(void);
@@ -74,38 +73,37 @@ static dma_device_t dmax_device[DMA_MAX_INDEX] = {
  * @param oflag
  * @return int
  */
-int dma_open(struct device *dev, uint16_t oflag)
-{
-    dma_device_t *dma_device = (dma_device_t *)dev;
-    DMA_Channel_Cfg_Type chCfg = { 0 };
-
-    /* Disable all interrupt */
-    DMA_IntMask(dma_device->ch, DMA_INT_ALL, MASK);
-    /* Enable uart interrupt*/
-    CPU_Interrupt_Disable(DMA_ALL_IRQn);
-
-    DMA_Disable();
-
-    DMA_Channel_Disable(dma_device->ch);
-
-    chCfg.ch = dma_device->ch;
-    chCfg.dir = dma_device->direction;
-    chCfg.srcPeriph = dma_device->src_req;
-    chCfg.dstPeriph = dma_device->dst_req;
-    chCfg.srcAddrInc = dma_device->src_addr_inc;
-    chCfg.destAddrInc = dma_device->dst_addr_inc;
-    chCfg.srcBurstSzie = dma_device->src_burst_size;
-    chCfg.dstBurstSzie = dma_device->dst_burst_size;
-    chCfg.srcTransfWidth = dma_device->src_width;
-    chCfg.dstTransfWidth = dma_device->dst_width;
-    DMA_Channel_Init(&chCfg);
-
-    DMA_Enable();
-
-    Interrupt_Handler_Register(DMA_ALL_IRQn, DMA0_IRQ);
-    /* Enable uart interrupt*/
-    CPU_Interrupt_Enable(DMA_ALL_IRQn);
-    return 0;
+int dma_open(struct device *dev, uint16_t oflag) {
+  dma_device_t        *dma_device = (dma_device_t *)dev;
+  DMA_Channel_Cfg_Type chCfg      = {0};
+
+  /* Disable all interrupt */
+  DMA_IntMask(dma_device->ch, DMA_INT_ALL, MASK);
+  CPU_Interrupt_Disable(DMA_ALL_IRQn);
+
+  DMA_Disable();
+
+  DMA_Channel_Disable(dma_device->ch);
+
+  dma_device->intr     = 0;
+  chCfg.ch             = dma_device->ch;
+  chCfg.dir            = dma_device->direction;
+  chCfg.srcPeriph      = dma_device->src_req;
+  chCfg.dstPeriph      = dma_device->dst_req;
+  chCfg.srcAddrInc     = dma_device->src_addr_inc;
+  chCfg.destAddrInc    = dma_device->dst_addr_inc;
+  chCfg.srcBurstSize   = dma_device->src_burst_size;
+  chCfg.dstBurstSize   = dma_device->dst_burst_size;
+  chCfg.srcTransfWidth = dma_device->src_width;
+  chCfg.dstTransfWidth = dma_device->dst_width;
+  DMA_Channel_Init(&chCfg);
+
+  DMA_Enable();
+
+  Interrupt_Handler_Register(DMA_ALL_IRQn, DMA0_IRQ);
+  /* Enable dma interrupt*/
+  CPU_Interrupt_Enable(DMA_ALL_IRQn);
+  return 0;
 }
 /**
  * @brief
@@ -115,62 +113,61 @@ int dma_open(struct device *dev, uint16_t oflag)
  * @param args
  * @return int
  */
-int dma_control(struct device *dev, int cmd, void *args)
-{
-    dma_device_t *dma_device = (dma_device_t *)dev;
-
-    switch (cmd) {
-        case DEVICE_CTRL_SET_INT:
-            /* Dma interrupt configuration */
-            DMA_IntMask(dma_device->ch, DMA_INT_TCOMPLETED, UNMASK);
-            DMA_IntMask(dma_device->ch, DMA_INT_ERR, UNMASK);
-
-            break;
-
-        case DEVICE_CTRL_CLR_INT:
-            /* Dma interrupt configuration */
-            DMA_IntMask(dma_device->ch, DMA_INT_TCOMPLETED, MASK);
-            DMA_IntMask(dma_device->ch, DMA_INT_ERR, MASK);
-
-            break;
-
-        case DEVICE_CTRL_GET_INT:
-            break;
-
-        case DEVICE_CTRL_CONFIG:
-            break;
-
-        case DEVICE_CTRL_DMA_CHANNEL_UPDATE:
-            DMA_LLI_Update(dma_device->ch, (uint32_t)args);
-            break;
-
-        case DEVICE_CTRL_DMA_CHANNEL_GET_STATUS:
-            return DMA_Channel_Is_Busy(dma_device->ch);
-
-        case DEVICE_CTRL_DMA_CHANNEL_START:
-            DMA_Channel_Enable(dma_device->ch);
-            break;
-
-        case DEVICE_CTRL_DMA_CHANNEL_STOP:
-            DMA_Channel_Disable(dma_device->ch);
-            break;
-        case DEVICE_CTRL_DMA_CONFIG_SI: {
-            uint32_t tmpVal = BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL);
-            tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SI, ((uint32_t)args) & 0x01);
-            BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, tmpVal);
-
-        } break;
-        case DEVICE_CTRL_DMA_CONFIG_DI: {
-            uint32_t tmpVal = BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL);
-            tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DI, ((uint32_t)args) & 0x01);
-            BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, tmpVal);
-
-        } break;
-        default:
-            break;
-    }
-
-    return 0;
+int dma_control(struct device *dev, int cmd, void *args) {
+  dma_device_t *dma_device = (dma_device_t *)dev;
+
+  switch (cmd) {
+  case DEVICE_CTRL_SET_INT:
+    /* Dma interrupt configuration */
+    DMA_IntMask(dma_device->ch, DMA_INT_TCOMPLETED, UNMASK);
+    DMA_IntMask(dma_device->ch, DMA_INT_ERR, UNMASK);
+    dma_device->intr = 1;
+    break;
+
+  case DEVICE_CTRL_CLR_INT:
+    /* Dma interrupt configuration */
+    DMA_IntMask(dma_device->ch, DMA_INT_TCOMPLETED, MASK);
+    DMA_IntMask(dma_device->ch, DMA_INT_ERR, MASK);
+    dma_device->intr = 0;
+    break;
+
+  case DEVICE_CTRL_GET_INT:
+    break;
+
+  case DEVICE_CTRL_CONFIG:
+    break;
+
+  case DEVICE_CTRL_DMA_CHANNEL_UPDATE:
+    DMA_LLI_Update(dma_device->ch, (uint32_t)args);
+    break;
+
+  case DEVICE_CTRL_DMA_CHANNEL_GET_STATUS:
+    return DMA_Channel_Is_Busy(dma_device->ch);
+
+  case DEVICE_CTRL_DMA_CHANNEL_START:
+    DMA_Channel_Enable(dma_device->ch);
+    break;
+
+  case DEVICE_CTRL_DMA_CHANNEL_STOP:
+    DMA_Channel_Disable(dma_device->ch);
+    break;
+  case DEVICE_CTRL_DMA_CONFIG_SI: {
+    uint32_t tmpVal = BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL);
+    tmpVal          = BL_SET_REG_BITS_VAL(tmpVal, DMA_SI, ((uint32_t)args) & 0x01);
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, tmpVal);
+
+  } break;
+  case DEVICE_CTRL_DMA_CONFIG_DI: {
+    uint32_t tmpVal = BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL);
+    tmpVal          = BL_SET_REG_BITS_VAL(tmpVal, DMA_DI, ((uint32_t)args) & 0x01);
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, tmpVal);
+
+  } break;
+  default:
+    break;
+  }
+
+  return 0;
 }
 /**
  * @brief
@@ -178,95 +175,35 @@ int dma_control(struct device *dev, int cmd, void *args)
  * @param dev
  * @return int
  */
-int dma_close(struct device *dev)
-{
-    dma_device_t *dma_device = (dma_device_t *)dev;
-    DMA_Channel_Cfg_Type chCfg = { 0 };
-
-    DMA_Channel_Disable(dma_device->ch);
-    DMA_Channel_Init(&chCfg);
-    return 0;
+int dma_close(struct device *dev) {
+  dma_device_t        *dma_device = (dma_device_t *)dev;
+  DMA_Channel_Cfg_Type chCfg      = {0};
+
+  DMA_Channel_Disable(dma_device->ch);
+  DMA_Channel_Init(&chCfg);
+  dma_device->intr = 0;
+  return 0;
 }
 
-int dma_register(enum dma_index_type index, const char *name)
-{
-    struct device *dev;
+int dma_register(enum dma_index_type index, const char *name) {
+  struct device *dev;
 
-    if (DMA_MAX_INDEX == 0) {
-        return -DEVICE_EINVAL;
-    }
-
-    dev = &(dmax_device[index].parent);
-
-    dev->open = dma_open;
-    dev->close = dma_close;
-    dev->control = dma_control;
-    // dev->write = dma_write;
-    // dev->read = dma_read;
-
-    dev->type = DEVICE_CLASS_DMA;
-    dev->handle = NULL;
-
-    return device_register(dev, name);
-}
-
-static BL_Err_Type dma_scan_unregister_device(uint8_t *allocate_index)
-{
-    struct device *dev;
-    dlist_t *node;
-    uint8_t dma_index = 0;
-    uint32_t dma_handle[DMA_MAX_INDEX];
+  if (DMA_MAX_INDEX == 0) {
+    return -DEVICE_EINVAL;
+  }
 
-    for (dma_index = 0; dma_index < DMA_MAX_INDEX; dma_index++) {
-        dma_handle[dma_index] = 0xff;
-    }
+  dev = &(dmax_device[index].parent);
 
-    /* get registered dma handle list*/
-    dlist_for_each(node, device_get_list_header())
-    {
-        dev = dlist_entry(node, struct device, list);
+  dev->open    = dma_open;
+  dev->close   = dma_close;
+  dev->control = dma_control;
+  // dev->write = dma_write;
+  // dev->read = dma_read;
 
-        if (dev->type == DEVICE_CLASS_DMA) {
-            dma_handle[(((uint32_t)dev - (uint32_t)dmax_device) / sizeof(dma_device_t)) % DMA_MAX_INDEX] = SET;
-        }
-    }
-
-    for (dma_index = 0; dma_index < DMA_MAX_INDEX; dma_index++) {
-        if (dma_handle[dma_index] == 0xff) {
-            *allocate_index = dma_index;
-            return SUCCESS;
-        }
-    }
+  dev->type   = DEVICE_CLASS_DMA;
+  dev->handle = NULL;
 
-    return ERROR;
-}
-
-int dma_allocate_register(const char *name)
-{
-    struct device *dev;
-    uint8_t index;
-
-    if (DMA_MAX_INDEX == 0) {
-        return -DEVICE_EINVAL;
-    }
-
-    if (dma_scan_unregister_device(&index) == ERROR) {
-        return -DEVICE_ENOSPACE;
-    }
-
-    dev = &(dmax_device[index].parent);
-
-    dev->open = dma_open;
-    dev->close = dma_close;
-    dev->control = dma_control;
-    // dev->write = dma_write;
-    // dev->read = dma_read;
-
-    dev->status = DEVICE_UNREGISTER;
-    dev->type = DEVICE_CLASS_DMA;
-    dev->handle = NULL;
-
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 
 /**
@@ -278,106 +215,104 @@ int dma_allocate_register(const char *name)
  * @param transfer_size
  * @return int
  */
-int dma_reload(struct device *dev, uint32_t src_addr, uint32_t dst_addr, uint32_t transfer_size)
-{
-#if defined(BSP_USING_DMA0_CH0) || defined(BSP_USING_DMA0_CH1) || defined(BSP_USING_DMA0_CH2) || defined(BSP_USING_DMA0_CH3) || \
-    defined(BSP_USING_DMA0_CH4) || defined(BSP_USING_DMA0_CH5) || defined(BSP_USING_DMA0_CH6) || defined(BSP_USING_DMA0_CH7)
+int dma_reload(struct device *dev, uint32_t src_addr, uint32_t dst_addr, uint32_t transfer_size) {
+#ifdef BSP_USING_DMA
+  uint32_t           malloc_count;
+  uint32_t           remain_len;
+  uint32_t           actual_transfer_len    = 0;
+  uint32_t           actual_transfer_offset = 0;
+  dma_control_data_t dma_ctrl_cfg;
+  bool               intr = false;
 
-    uint32_t malloc_count;
-    uint32_t remain_len;
-    uint32_t actual_transfer_len = 0;
-    uint32_t actual_transfer_offset = 0;
-    dma_control_data_t dma_ctrl_cfg;
+  dma_device_t *dma_device = (dma_device_t *)dev;
 
-    dma_device_t *dma_device = (dma_device_t *)dev;
+  DMA_Channel_Disable(dma_device->ch);
 
-    DMA_Channel_Disable(dma_device->ch);
-
-    if (transfer_size == 0) {
-        return 0;
+  if (transfer_size == 0) {
+    return 0;
+  }
+
+  switch (dma_device->src_width) {
+  case DMA_TRANSFER_WIDTH_8BIT:
+    actual_transfer_offset = 4095;
+    actual_transfer_len    = transfer_size;
+    break;
+  case DMA_TRANSFER_WIDTH_16BIT:
+    if (transfer_size % 2) {
+      return -1;
     }
-
-    switch (dma_device->src_width) {
-        case DMA_TRANSFER_WIDTH_8BIT:
-            actual_transfer_offset = 4095;
-            actual_transfer_len = transfer_size;
-            break;
-        case DMA_TRANSFER_WIDTH_16BIT:
-            if (transfer_size % 2) {
-                return -1;
-            }
-            actual_transfer_offset = 4095 << 1;
-            actual_transfer_len = transfer_size >> 1;
-            break;
-        case DMA_TRANSFER_WIDTH_32BIT:
-            if (transfer_size % 4) {
-                return -1;
-            }
-
-            actual_transfer_offset = 4095 << 2;
-            actual_transfer_len = transfer_size >> 2;
-            break;
-
-        default:
-            return -3;
-            break;
+    actual_transfer_offset = 4095 << 1;
+    actual_transfer_len    = transfer_size >> 1;
+    break;
+  case DMA_TRANSFER_WIDTH_32BIT:
+    if (transfer_size % 4) {
+      return -1;
     }
 
-    dma_ctrl_cfg = (dma_control_data_t)(BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL));
+    actual_transfer_offset = 4095 << 2;
+    actual_transfer_len    = transfer_size >> 2;
+    break;
 
-    malloc_count = actual_transfer_len / 4095;
-    remain_len = actual_transfer_len % 4095;
+  default:
+    return -3;
+    break;
+  }
 
-    if (remain_len) {
-        malloc_count++;
-    }
-
-    dma_device->lli_cfg = (dma_lli_ctrl_t *)realloc(dma_device->lli_cfg, sizeof(dma_lli_ctrl_t) * malloc_count);
+  dma_ctrl_cfg = (dma_control_data_t)(BL_RD_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL));
+  intr         = dma_device->intr;
 
-    if (dma_device->lli_cfg) {
-        /*transfer_size will be integer multiple of 4095*n or 4095*2*n or 4095*4*n,(n>0) */
-        for (uint32_t i = 0; i < malloc_count; i++) {
-            dma_device->lli_cfg[i].src_addr = src_addr;
-            dma_device->lli_cfg[i].dst_addr = dst_addr;
-            dma_device->lli_cfg[i].nextlli = 0;
+  malloc_count = actual_transfer_len / 4095;
+  remain_len   = actual_transfer_len % 4095;
 
-            dma_ctrl_cfg.bits.TransferSize = 4095;
-            dma_ctrl_cfg.bits.I = 0;
+  if (remain_len) {
+    malloc_count++;
+  }
 
-            if (dma_ctrl_cfg.bits.SI) {
-                src_addr += actual_transfer_offset;
-            }
+  dma_device->lli_cfg = (dma_lli_ctrl_t *)realloc(dma_device->lli_cfg, sizeof(dma_lli_ctrl_t) * malloc_count);
 
-            if (dma_ctrl_cfg.bits.DI) {
-                dst_addr += actual_transfer_offset;
-            }
+  if (dma_device->lli_cfg) {
+    dma_ctrl_cfg.bits.TransferSize = 4095;
+    dma_ctrl_cfg.bits.I            = 0;
+    /*transfer_size will be integer multiple of 4095*n or 4095*2*n or 4095*4*n,(n>0) */
+    for (uint32_t i = 0; i < malloc_count; i++) {
+      dma_device->lli_cfg[i].src_addr = src_addr;
+      dma_device->lli_cfg[i].dst_addr = dst_addr;
+      dma_device->lli_cfg[i].nextlli  = 0;
 
-            if (i == malloc_count - 1) {
-                if (remain_len) {
-                    dma_ctrl_cfg.bits.TransferSize = remain_len;
-                }
-                dma_ctrl_cfg.bits.I = 1;
+      if (dma_ctrl_cfg.bits.SI) {
+        src_addr += actual_transfer_offset;
+      }
 
-                if (dma_device->transfer_mode == DMA_LLI_CYCLE_MODE) {
-                    dma_device->lli_cfg[i].nextlli = (uint32_t)&dma_device->lli_cfg[0];
-                }
-            }
+      if (dma_ctrl_cfg.bits.DI) {
+        dst_addr += actual_transfer_offset;
+      }
 
-            if (i) {
-                dma_device->lli_cfg[i - 1].nextlli = (uint32_t)&dma_device->lli_cfg[i];
-            }
+      if (i == malloc_count - 1) {
+        if (remain_len) {
+          dma_ctrl_cfg.bits.TransferSize = remain_len;
+        }
+        dma_ctrl_cfg.bits.I = intr;
 
-            dma_device->lli_cfg[i].cfg = dma_ctrl_cfg;
+        if (dma_device->transfer_mode == DMA_LLI_CYCLE_MODE) {
+          dma_device->lli_cfg[i].nextlli = (uint32_t)&dma_device->lli_cfg[0];
         }
-        BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_SRCADDR, dma_device->lli_cfg[0].src_addr);
-        BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_DSTADDR, dma_device->lli_cfg[0].dst_addr);
-        BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_LLI, dma_device->lli_cfg[0].nextlli);
-        BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, dma_device->lli_cfg[0].cfg.WORD);
-    } else {
-        return -2;
+      }
+
+      if (i) {
+        dma_device->lli_cfg[i - 1].nextlli = (uint32_t)&dma_device->lli_cfg[i];
+      }
+
+      dma_device->lli_cfg[i].cfg = dma_ctrl_cfg;
     }
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_SRCADDR, dma_device->lli_cfg[0].src_addr);
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_DSTADDR, dma_device->lli_cfg[0].dst_addr);
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_LLI, dma_device->lli_cfg[0].nextlli);
+    BL_WR_REG(dma_channel_base[dma_device->id][dma_device->ch], DMA_CONTROL, dma_device->lli_cfg[0].cfg.WORD);
+  } else {
+    return -2;
+  }
 #endif
-    return 0;
+  return 0;
 }
 
 /**
@@ -385,47 +320,45 @@ int dma_reload(struct device *dev, uint32_t src_addr, uint32_t dst_addr, uint32_
  *
  * @param handle
  */
-void dma_channel_isr(dma_device_t *handle)
-{
-    uint32_t tmpVal;
-    uint32_t intClr;
-
-    /* Get DMA register */
-    uint32_t DMAChs = DMA_BASE;
-
-    if (!handle->parent.callback) {
-        return;
-    }
-
-    tmpVal = BL_RD_REG(DMAChs, DMA_INTTCSTATUS);
-    if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCSTATUS) & (1 << handle->ch)) != 0) {
-        /* Clear interrupt */
-        tmpVal = BL_RD_REG(DMAChs, DMA_INTTCCLEAR);
-        intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR);
-        intClr |= (1 << handle->ch);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR, intClr);
-        BL_WR_REG(DMAChs, DMA_INTTCCLEAR, tmpVal);
-        handle->parent.callback(&handle->parent, NULL, 0, DMA_INT_TCOMPLETED);
-    }
-
-    tmpVal = BL_RD_REG(DMAChs, DMA_INTERRORSTATUS);
-    if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRORSTATUS) & (1 << handle->ch)) != 0) {
-        /*Clear interrupt */
-        tmpVal = BL_RD_REG(DMAChs, DMA_INTERRCLR);
-        intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR);
-        intClr |= (1 << handle->ch);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR, intClr);
-        BL_WR_REG(DMAChs, DMA_INTERRCLR, tmpVal);
-        handle->parent.callback(&handle->parent, NULL, 0, DMA_INT_ERR);
-    }
+void dma_channel_isr(dma_device_t *handle) {
+  uint32_t tmpVal;
+  uint32_t intClr;
+
+  /* Get DMA register */
+  uint32_t DMAChs = DMA_BASE;
+
+  if (!handle->parent.callback) {
+    return;
+  }
+
+  tmpVal = BL_RD_REG(DMAChs, DMA_INTTCSTATUS);
+  if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCSTATUS) & (1 << handle->ch)) != 0) {
+    /* Clear interrupt */
+    tmpVal = BL_RD_REG(DMAChs, DMA_INTTCCLEAR);
+    intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR);
+    intClr |= (1 << handle->ch);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR, intClr);
+    BL_WR_REG(DMAChs, DMA_INTTCCLEAR, tmpVal);
+    handle->parent.callback(&handle->parent, NULL, 0, DMA_INT_TCOMPLETED);
+  }
+
+  tmpVal = BL_RD_REG(DMAChs, DMA_INTERRORSTATUS);
+  if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRORSTATUS) & (1 << handle->ch)) != 0) {
+    /*Clear interrupt */
+    tmpVal = BL_RD_REG(DMAChs, DMA_INTERRCLR);
+    intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR);
+    intClr |= (1 << handle->ch);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR, intClr);
+    BL_WR_REG(DMAChs, DMA_INTERRCLR, tmpVal);
+    handle->parent.callback(&handle->parent, NULL, 0, DMA_INT_ERR);
+  }
 }
 /**
  * @brief
  *
  */
-void DMA0_IRQ(void)
-{
-    for (uint8_t i = 0; i < DMA_MAX_INDEX; i++) {
-        dma_channel_isr(&dmax_device[i]);
-    }
+void DMA0_IRQ(void) {
+  for (uint8_t i = 0; i < DMA_MAX_INDEX; i++) {
+    dma_channel_isr(&dmax_device[i]);
+  }
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_flash.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_flash.c
index dad0210ce..a0d7f874d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_flash.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_flash.c
@@ -20,14 +20,14 @@
  * under the License.
  *
  */
+#include "hal_flash.h"
 #include "bl702_glb.h"
-#include "bl702_xip_sflash.h"
-#include "bl702_xip_sflash_ext.h"
 #include "bl702_sf_cfg.h"
 #include "bl702_sf_cfg_ext.h"
-#include "hal_flash.h"
+#include "bl702_xip_sflash.h"
+#include "bl702_xip_sflash_ext.h"
 
-static uint32_t g_jedec_id = 0;
+static uint32_t           g_jedec_id = 0;
 static SPI_Flash_Cfg_Type g_flash_cfg;
 
 /**
@@ -35,12 +35,11 @@ static SPI_Flash_Cfg_Type g_flash_cfg;
  *
  * @return BL_Err_Type
  */
-uint32_t flash_get_jedecid(void)
-{
-    uint32_t jid = 0;
+uint32_t flash_get_jedecid(void) {
+  uint32_t jid = 0;
 
-    jid = ((g_jedec_id&0xff)<<16) + (g_jedec_id&0xff00) + ((g_jedec_id&0xff0000)>>16);
-    return jid;
+  jid = ((g_jedec_id & 0xff) << 16) + (g_jedec_id & 0xff00) + ((g_jedec_id & 0xff0000) >> 16);
+  return jid;
 }
 
 /**
@@ -48,12 +47,11 @@ uint32_t flash_get_jedecid(void)
  *
  * @return BL_Err_Type
  */
-BL_Err_Type flash_get_cfg(uint8_t **cfg_addr, uint32_t *len)
-{
-    *cfg_addr = (uint8_t *)&g_flash_cfg;
-    *len = sizeof(SPI_Flash_Cfg_Type);
+BL_Err_Type flash_get_cfg(uint8_t **cfg_addr, uint32_t *len) {
+  *cfg_addr = (uint8_t *)&g_flash_cfg;
+  *len      = sizeof(SPI_Flash_Cfg_Type);
 
-    return SUCCESS;
+  return SUCCESS;
 }
 
 /**
@@ -61,13 +59,12 @@ BL_Err_Type flash_get_cfg(uint8_t **cfg_addr, uint32_t *len)
  *
  * @return BL_Err_Type
  */
-static BL_Err_Type ATTR_TCM_SECTION flash_set_qspi_enable(SPI_Flash_Cfg_Type *p_flash_cfg)
-{
-    if ((p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
-        SFlash_Qspi_Enable(p_flash_cfg);
-    }
+static BL_Err_Type ATTR_TCM_SECTION flash_set_qspi_enable(SPI_Flash_Cfg_Type *p_flash_cfg) {
+  if ((p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
+    SFlash_Qspi_Enable(p_flash_cfg);
+  }
 
-    return SUCCESS;
+  return SUCCESS;
 }
 
 /**
@@ -75,18 +72,17 @@ static BL_Err_Type ATTR_TCM_SECTION flash_set_qspi_enable(SPI_Flash_Cfg_Type *p_
  *
  * @return BL_Err_Type
  */
-static BL_Err_Type ATTR_TCM_SECTION flash_set_l1c_wrap(SPI_Flash_Cfg_Type *p_flash_cfg)
-{
-    if (((p_flash_cfg->ioMode >> 4) & 0x01) == 1) {
-        L1C_Set_Wrap(DISABLE);
-    } else {
-        L1C_Set_Wrap(ENABLE);
-        if ((p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
-            SFlash_SetBurstWrap(p_flash_cfg);
-        }
+static BL_Err_Type ATTR_TCM_SECTION flash_set_l1c_wrap(SPI_Flash_Cfg_Type *p_flash_cfg) {
+  if (((p_flash_cfg->ioMode >> 4) & 0x01) == 1) {
+    L1C_Set_Wrap(DISABLE);
+  } else {
+    L1C_Set_Wrap(ENABLE);
+    if ((p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (p_flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
+      SFlash_SetBurstWrap(p_flash_cfg);
     }
+  }
 
-    return SUCCESS;
+  return SUCCESS;
 }
 
 /**
@@ -94,32 +90,31 @@ static BL_Err_Type ATTR_TCM_SECTION flash_set_l1c_wrap(SPI_Flash_Cfg_Type *p_fla
  *
  * @return BL_Err_Type
  */
-static BL_Err_Type ATTR_TCM_SECTION flash_config_init(SPI_Flash_Cfg_Type *p_flash_cfg, uint8_t *jedec_id)
-{
-    BL_Err_Type ret = ERROR;
-    uint32_t jid = 0;
-    uint32_t offset = 0;
-
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    XIP_SFlash_State_Save(p_flash_cfg, &offset);
-    SFlash_GetJedecId(p_flash_cfg, (uint8_t *)&jid);
-    arch_memcpy(jedec_id, (uint8_t *)&jid, 3);
-    jid &= 0xFFFFFF;
-    g_jedec_id = jid;
-    ret = SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(jid, p_flash_cfg);
-    if (ret == SUCCESS) {
-        p_flash_cfg->mid = (jid & 0xff);
-    }
-
-    /* Set flash controler from p_flash_cfg */
-    flash_set_qspi_enable(p_flash_cfg);
-    flash_set_l1c_wrap(p_flash_cfg);
-    XIP_SFlash_State_Restore(p_flash_cfg, p_flash_cfg->ioMode & 0x0f, offset);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
-
-    return ret;
+static BL_Err_Type ATTR_TCM_SECTION flash_config_init(SPI_Flash_Cfg_Type *p_flash_cfg, uint8_t *jedec_id) {
+  BL_Err_Type ret    = ERROR;
+  uint32_t    jid    = 0;
+  uint32_t    offset = 0;
+
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  XIP_SFlash_State_Save(p_flash_cfg, &offset);
+  SFlash_GetJedecId(p_flash_cfg, (uint8_t *)&jid);
+  arch_memcpy(jedec_id, (uint8_t *)&jid, 3);
+  jid &= 0xFFFFFF;
+  g_jedec_id = jid;
+  ret        = SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(jid, p_flash_cfg);
+  if (ret == SUCCESS) {
+    p_flash_cfg->mid = (jid & 0xff);
+  }
+
+  /* Set flash controler from p_flash_cfg */
+  flash_set_qspi_enable(p_flash_cfg);
+  flash_set_l1c_wrap(p_flash_cfg);
+  XIP_SFlash_State_Restore(p_flash_cfg, p_flash_cfg->ioMode & 0x0f, offset);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
+
+  return ret;
 }
 
 /**
@@ -127,26 +122,25 @@ static BL_Err_Type ATTR_TCM_SECTION flash_config_init(SPI_Flash_Cfg_Type *p_flas
  *
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_init(void)
-{
-    BL_Err_Type ret = ERROR;
-    uint8_t clkDelay = 1;
-    uint8_t clkInvert = 1;
-    uint32_t jedec_id = 0;
-
-    cpu_global_irq_disable();
-    L1C_Cache_Flush_Ext();
-    SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(0, &g_flash_cfg);
-    L1C_Cache_Flush_Ext();
-    cpu_global_irq_enable();
-    if (g_flash_cfg.mid != 0xff) {
-        return SUCCESS;
-    }
-    clkDelay = g_flash_cfg.clkDelay;
-    clkInvert = g_flash_cfg.clkInvert;
-    g_flash_cfg.ioMode = g_flash_cfg.ioMode & 0x0f;
+BL_Err_Type ATTR_TCM_SECTION flash_init(void) {
+  BL_Err_Type ret       = ERROR;
+  uint8_t     clkDelay  = 1;
+  uint8_t     clkInvert = 1;
+  uint32_t    jedec_id  = 0;
+
+  cpu_global_irq_disable();
+  L1C_Cache_Flush_Ext();
+  SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(0, &g_flash_cfg);
+  L1C_Cache_Flush_Ext();
+  cpu_global_irq_enable();
+  if (g_flash_cfg.mid != 0xff) {
+    return SUCCESS;
+  }
+  clkDelay           = g_flash_cfg.clkDelay;
+  clkInvert          = g_flash_cfg.clkInvert;
+  g_flash_cfg.ioMode = g_flash_cfg.ioMode & 0x0f;
 
-    ret = flash_config_init(&g_flash_cfg, (uint8_t *)&jedec_id);
+  ret = flash_config_init(&g_flash_cfg, (uint8_t *)&jedec_id);
 #if 0
     MSG("flash ID = %08x\r\n", jedec_id);
     bflb_platform_dump((uint8_t *)&g_flash_cfg, sizeof(g_flash_cfg));
@@ -154,10 +148,10 @@ BL_Err_Type ATTR_TCM_SECTION flash_init(void)
         MSG("flash config init fail!\r\n");
     }
 #endif
-    g_flash_cfg.clkDelay = clkDelay;
-    g_flash_cfg.clkInvert = clkInvert;
+  g_flash_cfg.clkDelay  = clkDelay;
+  g_flash_cfg.clkInvert = clkInvert;
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -166,19 +160,18 @@ BL_Err_Type ATTR_TCM_SECTION flash_init(void)
  * @param data
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_read_jedec_id(uint8_t *data)
-{
-    uint32_t jid = 0;
-
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    XIP_SFlash_GetJedecId_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, (uint8_t *)&jid);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
-    jid &= 0xFFFFFF;
-    arch_memcpy(data, (void *)&jid, 4);
-
-    return SUCCESS;
+BL_Err_Type ATTR_TCM_SECTION flash_read_jedec_id(uint8_t *data) {
+  uint32_t jid = 0;
+
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  XIP_SFlash_GetJedecId_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, (uint8_t *)&jid);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
+  jid &= 0xFFFFFF;
+  arch_memcpy(data, (void *)&jid, 4);
+
+  return SUCCESS;
 }
 
 /**
@@ -189,15 +182,14 @@ BL_Err_Type ATTR_TCM_SECTION flash_read_jedec_id(uint8_t *data)
  * @param len
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_read_via_xip(uint32_t addr, uint8_t *data, uint32_t len)
-{
-    cpu_global_irq_disable();
-    L1C_Cache_Flush_Ext();
-    XIP_SFlash_Read_Via_Cache_Need_Lock(addr, data, len);
-    L1C_Cache_Flush_Ext();
-    cpu_global_irq_enable();
-
-    return SUCCESS;
+BL_Err_Type ATTR_TCM_SECTION flash_read_via_xip(uint32_t addr, uint8_t *data, uint32_t len) {
+  cpu_global_irq_disable();
+  L1C_Cache_Flush_Ext();
+  XIP_SFlash_Read_Via_Cache_Need_Lock(addr, data, len);
+  L1C_Cache_Flush_Ext();
+  cpu_global_irq_enable();
+
+  return SUCCESS;
 }
 
 /**
@@ -208,17 +200,16 @@ BL_Err_Type ATTR_TCM_SECTION flash_read_via_xip(uint32_t addr, uint8_t *data, ui
  * @param len
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_read(uint32_t addr, uint8_t *data, uint32_t len)
-{
-    BL_Err_Type ret = ERROR;
+BL_Err_Type ATTR_TCM_SECTION flash_read(uint32_t addr, uint8_t *data, uint32_t len) {
+  BL_Err_Type ret = ERROR;
 
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    ret = XIP_SFlash_Read_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, addr, data, len);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  ret = XIP_SFlash_Read_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, addr, data, len);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -229,17 +220,16 @@ BL_Err_Type ATTR_TCM_SECTION flash_read(uint32_t addr, uint8_t *data, uint32_t l
  * @param len
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_write(uint32_t addr, uint8_t *data, uint32_t len)
-{
-    BL_Err_Type ret = ERROR;
+BL_Err_Type ATTR_TCM_SECTION flash_write(uint32_t addr, uint8_t *data, uint32_t len) {
+  BL_Err_Type ret = ERROR;
 
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    ret = XIP_SFlash_Write_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, addr, data, len);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  ret = XIP_SFlash_Write_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, addr, data, len);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -249,17 +239,16 @@ BL_Err_Type ATTR_TCM_SECTION flash_write(uint32_t addr, uint8_t *data, uint32_t
  * @param endaddr
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_erase(uint32_t startaddr, uint32_t len)
-{
-    BL_Err_Type ret = ERROR;
+BL_Err_Type ATTR_TCM_SECTION flash_erase(uint32_t startaddr, uint32_t len) {
+  BL_Err_Type ret = ERROR;
 
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    ret = XIP_SFlash_Erase_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, startaddr, startaddr + len - 1);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  ret = XIP_SFlash_Erase_Need_Lock(&g_flash_cfg, g_flash_cfg.ioMode & 0x0f, startaddr, startaddr + len - 1);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -268,17 +257,16 @@ BL_Err_Type ATTR_TCM_SECTION flash_erase(uint32_t startaddr, uint32_t len)
  * @param protect
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_write_protect_set(SFlash_Protect_Kh25v40_Type protect)
-{
-    BL_Err_Type ret = ERROR;
+BL_Err_Type ATTR_TCM_SECTION flash_write_protect_set(SFlash_Protect_Kh25v40_Type protect) {
+  BL_Err_Type ret = ERROR;
 
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    ret = XIP_SFlash_KH25V40_Write_Protect_Need_Lock(&g_flash_cfg, protect);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  ret = XIP_SFlash_KH25V40_Write_Protect_Need_Lock(&g_flash_cfg, protect);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -287,17 +275,16 @@ BL_Err_Type ATTR_TCM_SECTION flash_write_protect_set(SFlash_Protect_Kh25v40_Type
  * @param None
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_clear_status_register(void)
-{
-    BL_Err_Type ret = ERROR;
+BL_Err_Type ATTR_TCM_SECTION flash_clear_status_register(void) {
+  BL_Err_Type ret = ERROR;
 
-    cpu_global_irq_disable();
-    XIP_SFlash_Opt_Enter();
-    ret = XIP_SFlash_Clear_Status_Register_Need_Lock(&g_flash_cfg);
-    XIP_SFlash_Opt_Exit();
-    cpu_global_irq_enable();
+  cpu_global_irq_disable();
+  XIP_SFlash_Opt_Enter();
+  ret = XIP_SFlash_Clear_Status_Register_Need_Lock(&g_flash_cfg);
+  XIP_SFlash_Opt_Exit();
+  cpu_global_irq_enable();
 
-    return ret;
+  return ret;
 }
 
 /**
@@ -309,38 +296,37 @@ BL_Err_Type ATTR_TCM_SECTION flash_clear_status_register(void)
  * @param flash_offset
  * @return BL_Err_Type
  */
-BL_Err_Type ATTR_TCM_SECTION flash_set_cache(uint8_t cont_read, uint8_t cache_enable, uint8_t cache_way_disable, uint32_t flash_offset)
-{
-    uint32_t tmp[1];
-    BL_Err_Type stat;
+BL_Err_Type ATTR_TCM_SECTION flash_set_cache(uint8_t cont_read, uint8_t cache_enable, uint8_t cache_way_disable, uint32_t flash_offset) {
+  uint32_t    tmp[1];
+  BL_Err_Type stat;
 
-    SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB);
+  SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB);
 
-    XIP_SFlash_Opt_Enter();
-    /* To make it simple, exit cont read anyway */
-    SFlash_Reset_Continue_Read(&g_flash_cfg);
+  XIP_SFlash_Opt_Enter();
+  /* To make it simple, exit cont read anyway */
+  SFlash_Reset_Continue_Read(&g_flash_cfg);
 
-    if (g_flash_cfg.cReadSupport == 0) {
-        cont_read = 0;
-    }
+  if (g_flash_cfg.cReadSupport == 0) {
+    cont_read = 0;
+  }
 
-    if (cont_read == 1) {
-        stat = SFlash_Read(&g_flash_cfg, g_flash_cfg.ioMode & 0xf, 1, 0x00000000, (uint8_t *)tmp, sizeof(tmp));
+  if (cont_read == 1) {
+    stat = SFlash_Read(&g_flash_cfg, g_flash_cfg.ioMode & 0xf, 1, 0x00000000, (uint8_t *)tmp, sizeof(tmp));
 
-        if (SUCCESS != stat) {
-            XIP_SFlash_Opt_Exit();
-            return ERROR;
-        }
+    if (SUCCESS != stat) {
+      XIP_SFlash_Opt_Exit();
+      return ERROR;
     }
+  }
 
-    /* Set default value */
-    L1C_Cache_Enable_Set(0xf);
+  /* Set default value */
+  L1C_Cache_Enable_Set(0xf);
 
-    if (cache_enable) {
-        SF_Ctrl_Set_Flash_Image_Offset(flash_offset);
-        SFlash_Cache_Read_Enable(&g_flash_cfg, g_flash_cfg.ioMode & 0xf, cont_read, cache_way_disable);
-    }
-    XIP_SFlash_Opt_Exit();
+  if (cache_enable) {
+    SF_Ctrl_Set_Flash_Image_Offset(flash_offset);
+    SFlash_Cache_Read_Enable(&g_flash_cfg, g_flash_cfg.ioMode & 0xf, cont_read, cache_way_disable);
+  }
+  XIP_SFlash_Opt_Exit();
 
-    return SUCCESS;
+  return SUCCESS;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_gpio.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_gpio.c
index 20778c906..251c2e92e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_gpio.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_gpio.c
@@ -144,10 +144,11 @@ void gpio_set_mode(uint32_t pin, uint32_t mode) {
 void gpio_write(uint32_t pin, uint32_t value) {
   uint32_t tmp = BL_RD_REG(GLB_BASE, GLB_GPIO_OUTPUT);
 
-  if (value)
+  if (value) {
     tmp |= (1 << pin);
-  else
+  } else {
     tmp &= ~(1 << pin);
+  }
 
   BL_WR_REG(GLB_BASE, GLB_GPIO_OUTPUT, tmp);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_mtimer.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_mtimer.c
index 2305305ef..4821f514d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_mtimer.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_mtimer.c
@@ -28,11 +28,10 @@ static void (*systick_callback)(void);
 static uint64_t next_compare_tick = 0;
 static uint64_t current_set_ticks = 0;
 
-static void Systick_Handler(void)
-{
-    *(volatile uint64_t *)(CLIC_CTRL_ADDR + CLIC_MTIMECMP) = next_compare_tick;
-    systick_callback();
-    next_compare_tick += current_set_ticks;
+static void Systick_Handler(void) {
+  *(volatile uint64_t *)(CLIC_CTRL_ADDR + CLIC_MTIMECMP) = next_compare_tick;
+  systick_callback();
+  next_compare_tick += current_set_ticks;
 }
 
 /**
@@ -41,38 +40,36 @@ static void Systick_Handler(void)
  * @param time
  * @param interruptFun
  */
-void mtimer_set_alarm_time(uint64_t ticks, void (*interruptfun)(void))
-{
-    CPU_Interrupt_Disable(MTIME_IRQn);
+void mtimer_set_alarm_time(uint64_t ticks, void (*interruptfun)(void)) {
+  CPU_Interrupt_Disable(MTIME_IRQn);
 
-    uint32_t ulCurrentTimeHigh, ulCurrentTimeLow;
-    volatile uint32_t *const pulTimeHigh = (volatile uint32_t *const)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
-    volatile uint32_t *const pulTimeLow = (volatile uint32_t *const)(CLIC_CTRL_ADDR + CLIC_MTIME);
-    volatile uint32_t ulHartId = 0;
+  uint32_t                 ulCurrentTimeHigh, ulCurrentTimeLow;
+  volatile uint32_t *const pulTimeHigh = (volatile uint32_t *const)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
+  volatile uint32_t *const pulTimeLow  = (volatile uint32_t *const)(CLIC_CTRL_ADDR + CLIC_MTIME);
+  volatile uint32_t        ulHartId    = 0;
 
-    current_set_ticks = ticks;
-    systick_callback = interruptfun;
+  current_set_ticks = ticks;
+  systick_callback  = interruptfun;
 
-    __asm volatile("csrr %0, mhartid"
-                   : "=r"(ulHartId));
+  __asm volatile("csrr %0, mhartid" : "=r"(ulHartId));
 
-    do {
-        ulCurrentTimeHigh = *pulTimeHigh;
-        ulCurrentTimeLow = *pulTimeLow;
-    } while (ulCurrentTimeHigh != *pulTimeHigh);
+  do {
+    ulCurrentTimeHigh = *pulTimeHigh;
+    ulCurrentTimeLow  = *pulTimeLow;
+  } while (ulCurrentTimeHigh != *pulTimeHigh);
 
-    next_compare_tick = (uint64_t)ulCurrentTimeHigh;
-    next_compare_tick <<= 32ULL;
-    next_compare_tick |= (uint64_t)ulCurrentTimeLow;
-    next_compare_tick += (uint64_t)current_set_ticks;
+  next_compare_tick = (uint64_t)ulCurrentTimeHigh;
+  next_compare_tick <<= 32ULL;
+  next_compare_tick |= (uint64_t)ulCurrentTimeLow;
+  next_compare_tick += (uint64_t)current_set_ticks;
 
-    *(volatile uint64_t *)(CLIC_CTRL_ADDR + CLIC_MTIMECMP) = next_compare_tick;
+  *(volatile uint64_t *)(CLIC_CTRL_ADDR + CLIC_MTIMECMP) = next_compare_tick;
 
-    /* Prepare the time to use after the next tick interrupt. */
-    next_compare_tick += (uint64_t)current_set_ticks;
+  /* Prepare the time to use after the next tick interrupt. */
+  next_compare_tick += (uint64_t)current_set_ticks;
 
-    Interrupt_Handler_Register(MTIME_IRQn, Systick_Handler);
-    CPU_Interrupt_Enable(MTIME_IRQn);
+  Interrupt_Handler_Register(MTIME_IRQn, Systick_Handler);
+  CPU_Interrupt_Enable(MTIME_IRQn);
 }
 
 /**
@@ -80,64 +77,58 @@ void mtimer_set_alarm_time(uint64_t ticks, void (*interruptfun)(void))
  *
  * @return uint64_t
  */
-uint64_t mtimer_get_time_ms()
-{
-    return mtimer_get_time_us() / 1000;
-}
+uint64_t mtimer_get_time_ms() { return mtimer_get_time_us() / 1000; }
 /**
  * @brief
  *
  * @return uint64_t
  */
-uint64_t mtimer_get_time_us()
-{
-    uint32_t tmpValLow, tmpValHigh, tmpValHigh1;
+uint64_t mtimer_get_time_us() {
+  uint32_t tmpValLow, tmpValHigh, tmpValHigh1;
 
-    do {
-        tmpValLow = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME);
-        tmpValHigh = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
-        tmpValHigh1 = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
-    } while (tmpValHigh != tmpValHigh1);
+  do {
+    tmpValLow   = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME);
+    tmpValHigh  = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
+    tmpValHigh1 = *(volatile uint32_t *)(CLIC_CTRL_ADDR + CLIC_MTIME + 4);
+  } while (tmpValHigh != tmpValHigh1);
 
-    return (((uint64_t)tmpValHigh << 32) + tmpValLow);
+  return (((uint64_t)tmpValHigh << 32) + tmpValLow);
 }
 /**
  * @brief
  *
  * @param time
  */
-void mtimer_delay_ms(uint32_t time)
-{
-    uint64_t cnt = 0;
-    uint32_t clock = SystemCoreClockGet();
-    uint64_t startTime = mtimer_get_time_ms();
-
-    while (mtimer_get_time_ms() - startTime < time) {
-        cnt++;
-
-        /* assume BFLB_BSP_Get_Time_Ms take 32 cycles*/
-        if (cnt > (time * (clock >> (10 + 5))) * 2) {
-            break;
-        }
+void mtimer_delay_ms(uint32_t time) {
+  uint64_t cnt       = 0;
+  uint32_t clock     = SystemCoreClockGet();
+  uint64_t startTime = mtimer_get_time_ms();
+
+  while (mtimer_get_time_ms() - startTime < time) {
+    cnt++;
+
+    /* assume BFLB_BSP_Get_Time_Ms take 32 cycles*/
+    if (cnt > (time * (clock >> (10 + 5))) * 2) {
+      break;
     }
+  }
 }
 /**
  * @brief
  *
  * @param time
  */
-void mtimer_delay_us(uint32_t time)
-{
-    uint64_t cnt = 0;
-    uint32_t clock = SystemCoreClockGet();
-    uint64_t startTime = mtimer_get_time_us();
-
-    while (mtimer_get_time_us() - startTime < time) {
-        cnt++;
-
-        /* assume BFLB_BSP_Get_Time_Ms take 32 cycles*/
-        if (cnt > (time * (clock >> (10 + 5))) * 2) {
-            break;
-        }
+void mtimer_delay_us(uint32_t time) {
+  uint64_t cnt       = 0;
+  uint32_t clock     = SystemCoreClockGet();
+  uint64_t startTime = mtimer_get_time_us();
+
+  while (mtimer_get_time_us() - startTime < time) {
+    cnt++;
+
+    /* assume BFLB_BSP_Get_Time_Ms take 32 cycles*/
+    if (cnt > (time * (clock >> (10 + 5))) * 2) {
+      break;
     }
+  }
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c
index e7efc2ef5..8130246cb 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm.c
@@ -55,352 +55,364 @@ void HBN_OUT1_IRQ(void);
  *  @{
  */
 static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel0 = {
-    .pdsCtl = {
-        .pdsStart = 1,
-        .sleepForever = 0,
-        .xtalForceOff = 0,
-        .saveWifiState = 0,
-        .dcdc18Off = 1,
-        .bgSysOff = 1,
-        .gpioIePuPd = 1,
-        .puFlash = 0,
-        .clkOff = 1,
-        .memStby = 1,
-        .swPuFlash = 1,
-        .isolation = 1,
-        .waitXtalRdy = 0,
-        .pdsPwrOff = 1,
-        .xtalOff = 0,
-        .socEnbForceOn = 1,
-        .pdsRstSocEn = 0,
-        .pdsRC32mOn = 0,
-        .pdsLdoVselEn = 0,
-        .pdsRamLowPowerWithClkEn = 1,
-        .cpu0WfiMask = 0,
-        .ldo11Off = 1,
-        .pdsForceRamClkEn = 0,
-        .pdsLdoVol = 0xA,
-        .pdsCtlRfSel = 3,
-        .pdsCtlPllSel = 0,
-    },
-    .pdsCtl2 = {
-        .forceCpuPwrOff = 0,
-        .forceBzPwrOff = 0,
-        .forceUsbPwrOff = 0,
-        .forceCpuIsoEn = 0,
-        .forceBzIsoEn = 0,
-        .forceUsbIsoEn = 0,
-        .forceCpuPdsRst = 0,
-        .forceBzPdsRst = 0,
-        .forceUsbPdsRst = 0,
-        .forceCpuMemStby = 0,
-        .forceBzMemStby = 0,
-        .forceUsbMemStby = 0,
-        .forceCpuGateClk = 0,
-        .forceBzGateClk = 0,
-        .forceUsbGateClk = 0,
-    },
-    .pdsCtl3 = {
-        .forceMiscPwrOff = 0,
-        .forceBlePwrOff = 0,
-        .forceBleIsoEn = 0,
-        .forceMiscPdsRst = 0,
-        .forceBlePdsRst = 0,
-        .forceMiscMemStby = 0,
-        .forceBleMemStby = 0,
-        .forceMiscGateClk = 0,
-        .forceBleGateClk = 0,
-        .CpuIsoEn = 0,
-        .BzIsoEn = 0,
-        .BleIsoEn = 1,
-        .UsbIsoEn = 0,
-        .MiscIsoEn = 0,
-    },
+    .pdsCtl =
+        {
+                 .pdsStart                = 1,
+                 .sleepForever            = 0,
+                 .xtalForceOff            = 0,
+                 .saveWifiState           = 0,
+                 .dcdc18Off               = 1,
+                 .bgSysOff                = 1,
+                 .gpioIePuPd              = 1,
+                 .puFlash                 = 0,
+                 .clkOff                  = 1,
+                 .memStby                 = 1,
+                 .swPuFlash               = 1,
+                 .isolation               = 1,
+                 .waitXtalRdy             = 0,
+                 .pdsPwrOff               = 1,
+                 .xtalOff                 = 0,
+                 .socEnbForceOn           = 1,
+                 .pdsRstSocEn             = 0,
+                 .pdsRC32mOn              = 0,
+                 .pdsLdoVselEn            = 0,
+                 .pdsRamLowPowerWithClkEn = 1,
+                 .cpu0WfiMask             = 0,
+                 .ldo11Off                = 1,
+                 .pdsForceRamClkEn        = 0,
+                 .pdsLdoVol               = 0xA,
+                 .pdsCtlRfSel             = 3,
+                 .pdsCtlPllSel            = 0,
+                 },
+    .pdsCtl2 =
+        {
+                 .forceCpuPwrOff  = 0,
+                 .forceBzPwrOff   = 0,
+                 .forceUsbPwrOff  = 0,
+                 .forceCpuIsoEn   = 0,
+                 .forceBzIsoEn    = 0,
+                 .forceUsbIsoEn   = 0,
+                 .forceCpuPdsRst  = 0,
+                 .forceBzPdsRst   = 0,
+                 .forceUsbPdsRst  = 0,
+                 .forceCpuMemStby = 0,
+                 .forceBzMemStby  = 0,
+                 .forceUsbMemStby = 0,
+                 .forceCpuGateClk = 0,
+                 .forceBzGateClk  = 0,
+                 .forceUsbGateClk = 0,
+                 },
+    .pdsCtl3 =
+        {
+                 .forceMiscPwrOff  = 0,
+                 .forceBlePwrOff   = 0,
+                 .forceBleIsoEn    = 0,
+                 .forceMiscPdsRst  = 0,
+                 .forceBlePdsRst   = 0,
+                 .forceMiscMemStby = 0,
+                 .forceBleMemStby  = 0,
+                 .forceMiscGateClk = 0,
+                 .forceBleGateClk  = 0,
+                 .CpuIsoEn         = 0,
+                 .BzIsoEn          = 0,
+                 .BleIsoEn         = 1,
+                 .UsbIsoEn         = 0,
+                 .MiscIsoEn        = 0,
+                 },
     .pdsCtl4 = {
-        .cpuPwrOff = 0,
-        .cpuRst = 0,
-        .cpuMemStby = 1,
-        .cpuGateClk = 1,
-        .BzPwrOff = 0,
-        .BzRst = 0,
-        .BzMemStby = 1,
-        .BzGateClk = 1,
-        .BlePwrOff = 1,
-        .BleRst = 1,
-        .BleMemStby = 1,
-        .BleGateClk = 1,
-        .UsbPwrOff = 0,
-        .UsbRst = 0,
-        .UsbMemStby = 1,
-        .UsbGateClk = 1,
-        .MiscPwrOff = 0,
-        .MiscRst = 0,
-        .MiscMemStby = 1,
-        .MiscGateClk = 1,
-        .MiscAnaPwrOff = 1,
-        .MiscDigPwrOff = 1,
-    }
+                 .cpuPwrOff     = 0,
+                 .cpuRst        = 0,
+                 .cpuMemStby    = 1,
+                 .cpuGateClk    = 1,
+                 .BzPwrOff      = 0,
+                 .BzRst         = 0,
+                 .BzMemStby     = 1,
+                 .BzGateClk     = 1,
+                 .BlePwrOff     = 1,
+                 .BleRst        = 1,
+                 .BleMemStby    = 1,
+                 .BleGateClk    = 1,
+                 .UsbPwrOff     = 0,
+                 .UsbRst        = 0,
+                 .UsbMemStby    = 1,
+                 .UsbGateClk    = 1,
+                 .MiscPwrOff    = 0,
+                 .MiscRst       = 0,
+                 .MiscMemStby   = 1,
+                 .MiscGateClk   = 1,
+                 .MiscAnaPwrOff = 1,
+                 .MiscDigPwrOff = 1,
+                 }
 };
 static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel1 = {
-    .pdsCtl = {
-        .pdsStart = 1,
-        .sleepForever = 0,
-        .xtalForceOff = 0,
-        .saveWifiState = 0,
-        .dcdc18Off = 1,
-        .bgSysOff = 1,
-        .gpioIePuPd = 1,
-        .puFlash = 0,
-        .clkOff = 1,
-        .memStby = 1,
-        .swPuFlash = 1,
-        .isolation = 1,
-        .waitXtalRdy = 0,
-        .pdsPwrOff = 1,
-        .xtalOff = 0,
-        .socEnbForceOn = 1,
-        .pdsRstSocEn = 0,
-        .pdsRC32mOn = 0,
-        .pdsLdoVselEn = 0,
-        .pdsRamLowPowerWithClkEn = 1,
-        .cpu0WfiMask = 0,
-        .ldo11Off = 1,
-        .pdsForceRamClkEn = 0,
-        .pdsLdoVol = 0xA,
-        .pdsCtlRfSel = 3,
-        .pdsCtlPllSel = 0,
-    },
-    .pdsCtl2 = {
-        .forceCpuPwrOff = 0,
-        .forceBzPwrOff = 0,
-        .forceUsbPwrOff = 0,
-        .forceCpuIsoEn = 0,
-        .forceBzIsoEn = 0,
-        .forceUsbIsoEn = 0,
-        .forceCpuPdsRst = 0,
-        .forceBzPdsRst = 0,
-        .forceUsbPdsRst = 0,
-        .forceCpuMemStby = 0,
-        .forceBzMemStby = 0,
-        .forceUsbMemStby = 0,
-        .forceCpuGateClk = 0,
-        .forceBzGateClk = 0,
-        .forceUsbGateClk = 0,
-    },
-    .pdsCtl3 = {
-        .forceMiscPwrOff = 0,
-        .forceBlePwrOff = 0,
-        .forceBleIsoEn = 0,
-        .forceMiscPdsRst = 0,
-        .forceBlePdsRst = 0,
-        .forceMiscMemStby = 0,
-        .forceBleMemStby = 0,
-        .forceMiscGateClk = 0,
-        .forceBleGateClk = 0,
-        .CpuIsoEn = 0,
-        .BzIsoEn = 0,
-        .BleIsoEn = 1,
-        .UsbIsoEn = 1,
-        .MiscIsoEn = 0,
-    },
+    .pdsCtl =
+        {
+                 .pdsStart                = 1,
+                 .sleepForever            = 0,
+                 .xtalForceOff            = 0,
+                 .saveWifiState           = 0,
+                 .dcdc18Off               = 1,
+                 .bgSysOff                = 1,
+                 .gpioIePuPd              = 1,
+                 .puFlash                 = 0,
+                 .clkOff                  = 1,
+                 .memStby                 = 1,
+                 .swPuFlash               = 1,
+                 .isolation               = 1,
+                 .waitXtalRdy             = 0,
+                 .pdsPwrOff               = 1,
+                 .xtalOff                 = 0,
+                 .socEnbForceOn           = 1,
+                 .pdsRstSocEn             = 0,
+                 .pdsRC32mOn              = 0,
+                 .pdsLdoVselEn            = 0,
+                 .pdsRamLowPowerWithClkEn = 1,
+                 .cpu0WfiMask             = 0,
+                 .ldo11Off                = 1,
+                 .pdsForceRamClkEn        = 0,
+                 .pdsLdoVol               = 0xA,
+                 .pdsCtlRfSel             = 3,
+                 .pdsCtlPllSel            = 0,
+                 },
+    .pdsCtl2 =
+        {
+                 .forceCpuPwrOff  = 0,
+                 .forceBzPwrOff   = 0,
+                 .forceUsbPwrOff  = 0,
+                 .forceCpuIsoEn   = 0,
+                 .forceBzIsoEn    = 0,
+                 .forceUsbIsoEn   = 0,
+                 .forceCpuPdsRst  = 0,
+                 .forceBzPdsRst   = 0,
+                 .forceUsbPdsRst  = 0,
+                 .forceCpuMemStby = 0,
+                 .forceBzMemStby  = 0,
+                 .forceUsbMemStby = 0,
+                 .forceCpuGateClk = 0,
+                 .forceBzGateClk  = 0,
+                 .forceUsbGateClk = 0,
+                 },
+    .pdsCtl3 =
+        {
+                 .forceMiscPwrOff  = 0,
+                 .forceBlePwrOff   = 0,
+                 .forceBleIsoEn    = 0,
+                 .forceMiscPdsRst  = 0,
+                 .forceBlePdsRst   = 0,
+                 .forceMiscMemStby = 0,
+                 .forceBleMemStby  = 0,
+                 .forceMiscGateClk = 0,
+                 .forceBleGateClk  = 0,
+                 .CpuIsoEn         = 0,
+                 .BzIsoEn          = 0,
+                 .BleIsoEn         = 1,
+                 .UsbIsoEn         = 1,
+                 .MiscIsoEn        = 0,
+                 },
     .pdsCtl4 = {
-        .cpuPwrOff = 0,
-        .cpuRst = 0,
-        .cpuMemStby = 1,
-        .cpuGateClk = 1,
-        .BzPwrOff = 0,
-        .BzRst = 0,
-        .BzMemStby = 1,
-        .BzGateClk = 1,
-        .BlePwrOff = 1,
-        .BleRst = 1,
-        .BleMemStby = 1,
-        .BleGateClk = 1,
-        .UsbPwrOff = 1,
-        .UsbRst = 1,
-        .UsbMemStby = 1,
-        .UsbGateClk = 1,
-        .MiscPwrOff = 0,
-        .MiscRst = 0,
-        .MiscMemStby = 1,
-        .MiscGateClk = 1,
-        .MiscAnaPwrOff = 1,
-        .MiscDigPwrOff = 1,
-    }
+                 .cpuPwrOff     = 0,
+                 .cpuRst        = 0,
+                 .cpuMemStby    = 1,
+                 .cpuGateClk    = 1,
+                 .BzPwrOff      = 0,
+                 .BzRst         = 0,
+                 .BzMemStby     = 1,
+                 .BzGateClk     = 1,
+                 .BlePwrOff     = 1,
+                 .BleRst        = 1,
+                 .BleMemStby    = 1,
+                 .BleGateClk    = 1,
+                 .UsbPwrOff     = 1,
+                 .UsbRst        = 1,
+                 .UsbMemStby    = 1,
+                 .UsbGateClk    = 1,
+                 .MiscPwrOff    = 0,
+                 .MiscRst       = 0,
+                 .MiscMemStby   = 1,
+                 .MiscGateClk   = 1,
+                 .MiscAnaPwrOff = 1,
+                 .MiscDigPwrOff = 1,
+                 }
 };
 static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel2 = {
-    .pdsCtl = {
-        .pdsStart = 1,
-        .sleepForever = 0,
-        .xtalForceOff = 0,
-        .saveWifiState = 0,
-        .dcdc18Off = 1,
-        .bgSysOff = 1,
-        .gpioIePuPd = 1,
-        .puFlash = 0,
-        .clkOff = 1,
-        .memStby = 1,
-        .swPuFlash = 1,
-        .isolation = 1,
-        .waitXtalRdy = 0,
-        .pdsPwrOff = 1,
-        .xtalOff = 0,
-        .socEnbForceOn = 1,
-        .pdsRstSocEn = 0,
-        .pdsRC32mOn = 0,
-        .pdsLdoVselEn = 0,
-        .pdsRamLowPowerWithClkEn = 1,
-        .cpu0WfiMask = 0,
-        .ldo11Off = 1,
-        .pdsForceRamClkEn = 0,
-        .pdsLdoVol = 0xA,
-        .pdsCtlRfSel = 2,
-        .pdsCtlPllSel = 0,
-    },
-    .pdsCtl2 = {
-        .forceCpuPwrOff = 0,
-        .forceBzPwrOff = 0,
-        .forceUsbPwrOff = 0,
-        .forceCpuIsoEn = 0,
-        .forceBzIsoEn = 0,
-        .forceUsbIsoEn = 0,
-        .forceCpuPdsRst = 0,
-        .forceBzPdsRst = 0,
-        .forceUsbPdsRst = 0,
-        .forceCpuMemStby = 0,
-        .forceBzMemStby = 0,
-        .forceUsbMemStby = 0,
-        .forceCpuGateClk = 0,
-        .forceBzGateClk = 0,
-        .forceUsbGateClk = 0,
-    },
-    .pdsCtl3 = {
-        .forceMiscPwrOff = 0,
-        .forceBlePwrOff = 0,
-        .forceBleIsoEn = 0,
-        .forceMiscPdsRst = 0,
-        .forceBlePdsRst = 0,
-        .forceMiscMemStby = 0,
-        .forceBleMemStby = 0,
-        .forceMiscGateClk = 0,
-        .forceBleGateClk = 0,
-        .CpuIsoEn = 0,
-        .BzIsoEn = 1,
-        .BleIsoEn = 1,
-        .UsbIsoEn = 0,
-        .MiscIsoEn = 0,
-    },
+    .pdsCtl =
+        {
+                 .pdsStart                = 1,
+                 .sleepForever            = 0,
+                 .xtalForceOff            = 0,
+                 .saveWifiState           = 0,
+                 .dcdc18Off               = 1,
+                 .bgSysOff                = 1,
+                 .gpioIePuPd              = 1,
+                 .puFlash                 = 0,
+                 .clkOff                  = 1,
+                 .memStby                 = 1,
+                 .swPuFlash               = 1,
+                 .isolation               = 1,
+                 .waitXtalRdy             = 0,
+                 .pdsPwrOff               = 1,
+                 .xtalOff                 = 0,
+                 .socEnbForceOn           = 1,
+                 .pdsRstSocEn             = 0,
+                 .pdsRC32mOn              = 0,
+                 .pdsLdoVselEn            = 0,
+                 .pdsRamLowPowerWithClkEn = 1,
+                 .cpu0WfiMask             = 0,
+                 .ldo11Off                = 1,
+                 .pdsForceRamClkEn        = 0,
+                 .pdsLdoVol               = 0xA,
+                 .pdsCtlRfSel             = 2,
+                 .pdsCtlPllSel            = 0,
+                 },
+    .pdsCtl2 =
+        {
+                 .forceCpuPwrOff  = 0,
+                 .forceBzPwrOff   = 0,
+                 .forceUsbPwrOff  = 0,
+                 .forceCpuIsoEn   = 0,
+                 .forceBzIsoEn    = 0,
+                 .forceUsbIsoEn   = 0,
+                 .forceCpuPdsRst  = 0,
+                 .forceBzPdsRst   = 0,
+                 .forceUsbPdsRst  = 0,
+                 .forceCpuMemStby = 0,
+                 .forceBzMemStby  = 0,
+                 .forceUsbMemStby = 0,
+                 .forceCpuGateClk = 0,
+                 .forceBzGateClk  = 0,
+                 .forceUsbGateClk = 0,
+                 },
+    .pdsCtl3 =
+        {
+                 .forceMiscPwrOff  = 0,
+                 .forceBlePwrOff   = 0,
+                 .forceBleIsoEn    = 0,
+                 .forceMiscPdsRst  = 0,
+                 .forceBlePdsRst   = 0,
+                 .forceMiscMemStby = 0,
+                 .forceBleMemStby  = 0,
+                 .forceMiscGateClk = 0,
+                 .forceBleGateClk  = 0,
+                 .CpuIsoEn         = 0,
+                 .BzIsoEn          = 1,
+                 .BleIsoEn         = 1,
+                 .UsbIsoEn         = 0,
+                 .MiscIsoEn        = 0,
+                 },
     .pdsCtl4 = {
-        .cpuPwrOff = 0,
-        .cpuRst = 0,
-        .cpuMemStby = 1,
-        .cpuGateClk = 1,
-        .BzPwrOff = 1,
-        .BzRst = 1,
-        .BzMemStby = 1,
-        .BzGateClk = 1,
-        .BlePwrOff = 1,
-        .BleRst = 1,
-        .BleMemStby = 1,
-        .BleGateClk = 1,
-        .UsbPwrOff = 0,
-        .UsbRst = 0,
-        .UsbMemStby = 1,
-        .UsbGateClk = 1,
-        .MiscPwrOff = 0,
-        .MiscRst = 0,
-        .MiscMemStby = 1,
-        .MiscGateClk = 1,
-        .MiscAnaPwrOff = 1,
-        .MiscDigPwrOff = 1,
-    }
+                 .cpuPwrOff     = 0,
+                 .cpuRst        = 0,
+                 .cpuMemStby    = 1,
+                 .cpuGateClk    = 1,
+                 .BzPwrOff      = 1,
+                 .BzRst         = 1,
+                 .BzMemStby     = 1,
+                 .BzGateClk     = 1,
+                 .BlePwrOff     = 1,
+                 .BleRst        = 1,
+                 .BleMemStby    = 1,
+                 .BleGateClk    = 1,
+                 .UsbPwrOff     = 0,
+                 .UsbRst        = 0,
+                 .UsbMemStby    = 1,
+                 .UsbGateClk    = 1,
+                 .MiscPwrOff    = 0,
+                 .MiscRst       = 0,
+                 .MiscMemStby   = 1,
+                 .MiscGateClk   = 1,
+                 .MiscAnaPwrOff = 1,
+                 .MiscDigPwrOff = 1,
+                 }
 };
 static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel3 = {
-    .pdsCtl = {
-        .pdsStart = 1,
-        .sleepForever = 0,
-        .xtalForceOff = 0,
-        .saveWifiState = 0,
-        .dcdc18Off = 1,
-        .bgSysOff = 1,
-        .gpioIePuPd = 1,
-        .puFlash = 0,
-        .clkOff = 1,
-        .memStby = 1,
-        .swPuFlash = 1,
-        .isolation = 1,
-        .waitXtalRdy = 0,
-        .pdsPwrOff = 1,
-        .xtalOff = 0,
-        .socEnbForceOn = 1,
-        .pdsRstSocEn = 0,
-        .pdsRC32mOn = 0,
-        .pdsLdoVselEn = 0,
-        .pdsRamLowPowerWithClkEn = 1,
-        .cpu0WfiMask = 0,
-        .ldo11Off = 1,
-        .pdsForceRamClkEn = 0,
-        .pdsLdoVol = 0xA,
-        .pdsCtlRfSel = 2,
-        .pdsCtlPllSel = 0,
-    },
-    .pdsCtl2 = {
-        .forceCpuPwrOff = 0,
-        .forceBzPwrOff = 0,
-        .forceUsbPwrOff = 0,
-        .forceCpuIsoEn = 0,
-        .forceBzIsoEn = 0,
-        .forceUsbIsoEn = 0,
-        .forceCpuPdsRst = 0,
-        .forceBzPdsRst = 0,
-        .forceUsbPdsRst = 0,
-        .forceCpuMemStby = 0,
-        .forceBzMemStby = 0,
-        .forceUsbMemStby = 0,
-        .forceCpuGateClk = 0,
-        .forceBzGateClk = 0,
-        .forceUsbGateClk = 0,
-    },
-    .pdsCtl3 = {
-        .forceMiscPwrOff = 0,
-        .forceBlePwrOff = 0,
-        .forceBleIsoEn = 0,
-        .forceMiscPdsRst = 0,
-        .forceBlePdsRst = 0,
-        .forceMiscMemStby = 0,
-        .forceBleMemStby = 0,
-        .forceMiscGateClk = 0,
-        .forceBleGateClk = 0,
-        .CpuIsoEn = 0,
-        .BzIsoEn = 1,
-        .BleIsoEn = 1,
-        .UsbIsoEn = 1,
-        .MiscIsoEn = 0,
-    },
+    .pdsCtl =
+        {
+                 .pdsStart                = 1,
+                 .sleepForever            = 0,
+                 .xtalForceOff            = 0,
+                 .saveWifiState           = 0,
+                 .dcdc18Off               = 1,
+                 .bgSysOff                = 1,
+                 .gpioIePuPd              = 1,
+                 .puFlash                 = 0,
+                 .clkOff                  = 1,
+                 .memStby                 = 1,
+                 .swPuFlash               = 1,
+                 .isolation               = 1,
+                 .waitXtalRdy             = 0,
+                 .pdsPwrOff               = 1,
+                 .xtalOff                 = 0,
+                 .socEnbForceOn           = 1,
+                 .pdsRstSocEn             = 0,
+                 .pdsRC32mOn              = 0,
+                 .pdsLdoVselEn            = 0,
+                 .pdsRamLowPowerWithClkEn = 1,
+                 .cpu0WfiMask             = 0,
+                 .ldo11Off                = 1,
+                 .pdsForceRamClkEn        = 0,
+                 .pdsLdoVol               = 0xA,
+                 .pdsCtlRfSel             = 2,
+                 .pdsCtlPllSel            = 0,
+                 },
+    .pdsCtl2 =
+        {
+                 .forceCpuPwrOff  = 0,
+                 .forceBzPwrOff   = 0,
+                 .forceUsbPwrOff  = 0,
+                 .forceCpuIsoEn   = 0,
+                 .forceBzIsoEn    = 0,
+                 .forceUsbIsoEn   = 0,
+                 .forceCpuPdsRst  = 0,
+                 .forceBzPdsRst   = 0,
+                 .forceUsbPdsRst  = 0,
+                 .forceCpuMemStby = 0,
+                 .forceBzMemStby  = 0,
+                 .forceUsbMemStby = 0,
+                 .forceCpuGateClk = 0,
+                 .forceBzGateClk  = 0,
+                 .forceUsbGateClk = 0,
+                 },
+    .pdsCtl3 =
+        {
+                 .forceMiscPwrOff  = 0,
+                 .forceBlePwrOff   = 0,
+                 .forceBleIsoEn    = 0,
+                 .forceMiscPdsRst  = 0,
+                 .forceBlePdsRst   = 0,
+                 .forceMiscMemStby = 0,
+                 .forceBleMemStby  = 0,
+                 .forceMiscGateClk = 0,
+                 .forceBleGateClk  = 0,
+                 .CpuIsoEn         = 0,
+                 .BzIsoEn          = 1,
+                 .BleIsoEn         = 1,
+                 .UsbIsoEn         = 1,
+                 .MiscIsoEn        = 0,
+                 },
     .pdsCtl4 = {
-        .cpuPwrOff = 0,
-        .cpuRst = 0,
-        .cpuMemStby = 1,
-        .cpuGateClk = 1,
-        .BzPwrOff = 1,
-        .BzRst = 1,
-        .BzMemStby = 1,
-        .BzGateClk = 1,
-        .BlePwrOff = 1,
-        .BleRst = 1,
-        .BleMemStby = 1,
-        .BleGateClk = 1,
-        .UsbPwrOff = 1,
-        .UsbRst = 1,
-        .UsbMemStby = 1,
-        .UsbGateClk = 1,
-        .MiscPwrOff = 0,
-        .MiscRst = 0,
-        .MiscMemStby = 1,
-        .MiscGateClk = 1,
-        .MiscAnaPwrOff = 1,
-        .MiscDigPwrOff = 1,
-    }
+                 .cpuPwrOff     = 0,
+                 .cpuRst        = 0,
+                 .cpuMemStby    = 1,
+                 .cpuGateClk    = 1,
+                 .BzPwrOff      = 1,
+                 .BzRst         = 1,
+                 .BzMemStby     = 1,
+                 .BzGateClk     = 1,
+                 .BlePwrOff     = 1,
+                 .BleRst        = 1,
+                 .BleMemStby    = 1,
+                 .BleGateClk    = 1,
+                 .UsbPwrOff     = 1,
+                 .UsbRst        = 1,
+                 .UsbMemStby    = 1,
+                 .UsbGateClk    = 1,
+                 .MiscPwrOff    = 0,
+                 .MiscRst       = 0,
+                 .MiscMemStby   = 1,
+                 .MiscGateClk   = 1,
+                 .MiscAnaPwrOff = 1,
+                 .MiscDigPwrOff = 1,
+                 }
 };
 #if 0
 static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel4 = {
@@ -753,91 +765,94 @@ static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel7 = {
 };
 #endif
 static PDS_DEFAULT_LV_CFG_Type ATTR_TCM_CONST_SECTION pdsCfgLevel31 = {
-    .pdsCtl = {
-        .pdsStart = 1,
-        .sleepForever = 0,
-        .xtalForceOff = 0,
-        .saveWifiState = 0,
-        .dcdc18Off = 1,
-        .bgSysOff = 1,
-        .gpioIePuPd = 1,
-        .puFlash = 0,
-        .clkOff = 1,
-        .memStby = 1,
-        .swPuFlash = 1,
-        .isolation = 1,
-        .waitXtalRdy = 0,
-        .pdsPwrOff = 1,
-        .xtalOff = 0,
-        .socEnbForceOn = 0,
-        .pdsRstSocEn = 0,
-        .pdsRC32mOn = 0,
-        .pdsLdoVselEn = 0,
-        .pdsRamLowPowerWithClkEn = 1,
-        .cpu0WfiMask = 0,
-        .ldo11Off = 1,
-        .pdsForceRamClkEn = 0,
-        .pdsLdoVol = 0xA,
-        .pdsCtlRfSel = 2,
-        .pdsCtlPllSel = 0,
-    },
-    .pdsCtl2 = {
-        .forceCpuPwrOff = 0,
-        .forceBzPwrOff = 0,
-        .forceUsbPwrOff = 0,
-        .forceCpuIsoEn = 0,
-        .forceBzIsoEn = 0,
-        .forceUsbIsoEn = 0,
-        .forceCpuPdsRst = 0,
-        .forceBzPdsRst = 0,
-        .forceUsbPdsRst = 0,
-        .forceCpuMemStby = 0,
-        .forceBzMemStby = 0,
-        .forceUsbMemStby = 0,
-        .forceCpuGateClk = 0,
-        .forceBzGateClk = 0,
-        .forceUsbGateClk = 0,
-    },
-    .pdsCtl3 = {
-        .forceMiscPwrOff = 0,
-        .forceBlePwrOff = 0,
-        .forceBleIsoEn = 0,
-        .forceMiscPdsRst = 0,
-        .forceBlePdsRst = 0,
-        .forceMiscMemStby = 0,
-        .forceBleMemStby = 0,
-        .forceMiscGateClk = 0,
-        .forceBleGateClk = 0,
-        .CpuIsoEn = 1,
-        .BzIsoEn = 1,
-        .BleIsoEn = 1,
-        .UsbIsoEn = 1,
-        .MiscIsoEn = 1,
-    },
+    .pdsCtl =
+        {
+                 .pdsStart                = 1,
+                 .sleepForever            = 0,
+                 .xtalForceOff            = 0,
+                 .saveWifiState           = 0,
+                 .dcdc18Off               = 1,
+                 .bgSysOff                = 1,
+                 .gpioIePuPd              = 1,
+                 .puFlash                 = 0,
+                 .clkOff                  = 1,
+                 .memStby                 = 1,
+                 .swPuFlash               = 1,
+                 .isolation               = 1,
+                 .waitXtalRdy             = 0,
+                 .pdsPwrOff               = 1,
+                 .xtalOff                 = 0,
+                 .socEnbForceOn           = 0,
+                 .pdsRstSocEn             = 0,
+                 .pdsRC32mOn              = 0,
+                 .pdsLdoVselEn            = 0,
+                 .pdsRamLowPowerWithClkEn = 1,
+                 .cpu0WfiMask             = 0,
+                 .ldo11Off                = 1,
+                 .pdsForceRamClkEn        = 0,
+                 .pdsLdoVol               = 0xA,
+                 .pdsCtlRfSel             = 2,
+                 .pdsCtlPllSel            = 0,
+                 },
+    .pdsCtl2 =
+        {
+                 .forceCpuPwrOff  = 0,
+                 .forceBzPwrOff   = 0,
+                 .forceUsbPwrOff  = 0,
+                 .forceCpuIsoEn   = 0,
+                 .forceBzIsoEn    = 0,
+                 .forceUsbIsoEn   = 0,
+                 .forceCpuPdsRst  = 0,
+                 .forceBzPdsRst   = 0,
+                 .forceUsbPdsRst  = 0,
+                 .forceCpuMemStby = 0,
+                 .forceBzMemStby  = 0,
+                 .forceUsbMemStby = 0,
+                 .forceCpuGateClk = 0,
+                 .forceBzGateClk  = 0,
+                 .forceUsbGateClk = 0,
+                 },
+    .pdsCtl3 =
+        {
+                 .forceMiscPwrOff  = 0,
+                 .forceBlePwrOff   = 0,
+                 .forceBleIsoEn    = 0,
+                 .forceMiscPdsRst  = 0,
+                 .forceBlePdsRst   = 0,
+                 .forceMiscMemStby = 0,
+                 .forceBleMemStby  = 0,
+                 .forceMiscGateClk = 0,
+                 .forceBleGateClk  = 0,
+                 .CpuIsoEn         = 1,
+                 .BzIsoEn          = 1,
+                 .BleIsoEn         = 1,
+                 .UsbIsoEn         = 1,
+                 .MiscIsoEn        = 1,
+                 },
     .pdsCtl4 = {
-        .cpuPwrOff = 1,
-        .cpuRst = 1,
-        .cpuMemStby = 1,
-        .cpuGateClk = 1,
-        .BzPwrOff = 1,
-        .BzRst = 1,
-        .BzMemStby = 1,
-        .BzGateClk = 1,
-        .BlePwrOff = 1,
-        .BleRst = 1,
-        .BleMemStby = 1,
-        .BleGateClk = 1,
-        .UsbPwrOff = 1,
-        .UsbRst = 1,
-        .UsbMemStby = 1,
-        .UsbGateClk = 1,
-        .MiscPwrOff = 1,
-        .MiscRst = 1,
-        .MiscMemStby = 1,
-        .MiscGateClk = 1,
-        .MiscAnaPwrOff = 1,
-        .MiscDigPwrOff = 1,
-    }
+                 .cpuPwrOff     = 1,
+                 .cpuRst        = 1,
+                 .cpuMemStby    = 1,
+                 .cpuGateClk    = 1,
+                 .BzPwrOff      = 1,
+                 .BzRst         = 1,
+                 .BzMemStby     = 1,
+                 .BzGateClk     = 1,
+                 .BlePwrOff     = 1,
+                 .BleRst        = 1,
+                 .BleMemStby    = 1,
+                 .BleGateClk    = 1,
+                 .UsbPwrOff     = 1,
+                 .UsbRst        = 1,
+                 .UsbMemStby    = 1,
+                 .UsbGateClk    = 1,
+                 .MiscPwrOff    = 1,
+                 .MiscRst       = 1,
+                 .MiscMemStby   = 1,
+                 .MiscGateClk   = 1,
+                 .MiscAnaPwrOff = 1,
+                 .MiscDigPwrOff = 1,
+                 }
 };
 
 /****************************************************************************/ /**
@@ -1159,13 +1174,15 @@ ATTR_TCM_SECTION void pm_hbn_mode_enter(enum pm_hbn_sleep_level hbn_level, uint8
   /* To make it simple and safe*/
   cpu_global_irq_disable();
 
-  if (sleep_time && (hbn_level < PM_HBN_LEVEL_2))
+  if (sleep_time && (hbn_level < PM_HBN_LEVEL_2)) {
     rtc_init(sleep_time); // sleep time,unit is second
+  }
 
-  if (hbn_level >= PM_HBN_LEVEL_2)
+  if (hbn_level >= PM_HBN_LEVEL_2) {
     HBN_Power_Off_RC32K();
-  else
+  } else {
     HBN_Power_On_RC32K();
+  }
 
   HBN_Power_Down_Flash(NULL);
   /* SF io select from efuse value */
@@ -1237,9 +1254,10 @@ ATTR_HBN_RAM_SECTION void pm_hbn_enter_again(bool reset) {
   BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, 0xffffffff);
   BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, 0);
 
-  if (!reset)
+  if (!reset) {
     /* Enable HBN mode */
     BL_WR_REG(HBN_BASE, HBN_RSV0, HBN_STATUS_ENTER_FLAG);
+  }
 
   tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
   tmpVal = BL_SET_REG_BIT(tmpVal, HBN_MODE);
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm_util.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm_util.c
index 4636c9d1b..0a20b7195 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm_util.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_pm_util.c
@@ -21,12 +21,12 @@
  *
  */
 
+#include "hal_pm_util.h"
+#include "bl702_glb.h"
 #include "bl702_romdriver.h"
 #include "bl702_sf_ctrl.h"
-#include "bl702_glb.h"
 #include "hal_clock.h"
 #include "hal_pm.h"
-#include "hal_pm_util.h"
 
 /* Cache Way Disable, will get from l1c register */
 extern uint8_t cacheWayDisable;
@@ -54,30 +54,29 @@ void (*hardware_recovery)(void) = NULL;
  *
  * @note If necessary,please application layer call vTaskStepTick,
  */
-uint32_t hal_pds_enter_with_time_compensation(uint32_t pdsLevel, uint32_t pdsSleepCycles)
-{
-    uint32_t rtcLowBeforeSleep = 0, rtcHighBeforeSleep = 0;
-    uint32_t rtcLowAfterSleep = 0, rtcHighAfterSleep = 0;
-    uint32_t actualSleepDuration_32768cycles = 0;
-    uint32_t actualSleepDuration_ms = 0;
+uint32_t hal_pds_enter_with_time_compensation(uint32_t pdsLevel, uint32_t pdsSleepCycles) {
+  uint32_t rtcLowBeforeSleep = 0, rtcHighBeforeSleep = 0;
+  uint32_t rtcLowAfterSleep = 0, rtcHighAfterSleep = 0;
+  uint32_t actualSleepDuration_32768cycles = 0;
+  uint32_t actualSleepDuration_ms          = 0;
 
-    pm_set_wakeup_callback(pm_pds_fastboot_entry);
+  pm_set_wakeup_callback(pm_pds_fastboot_entry);
 
-    HBN_Get_RTC_Timer_Val(&rtcLowBeforeSleep, &rtcHighBeforeSleep);
+  HBN_Get_RTC_Timer_Val(&rtcLowBeforeSleep, &rtcHighBeforeSleep);
 
-    pm_pds31_fast_mode_enter(pdsLevel, pdsSleepCycles);
+  pm_pds31_fast_mode_enter(pdsLevel, pdsSleepCycles);
 
-    HBN_Get_RTC_Timer_Val(&rtcLowAfterSleep, &rtcHighAfterSleep);
+  HBN_Get_RTC_Timer_Val(&rtcLowAfterSleep, &rtcHighAfterSleep);
 
-    CHECK_PARAM((rtcHighAfterSleep - rtcHighBeforeSleep) <= 1); // make sure sleep less than 1 hour (2^32 us > 1 hour)
+  CHECK_PARAM((rtcHighAfterSleep - rtcHighBeforeSleep) <= 1); // make sure sleep less than 1 hour (2^32 us > 1 hour)
 
-    actualSleepDuration_32768cycles = (rtcLowAfterSleep - rtcLowBeforeSleep);
+  actualSleepDuration_32768cycles = (rtcLowAfterSleep - rtcLowBeforeSleep);
 
-    actualSleepDuration_ms = (actualSleepDuration_32768cycles >> 5) - (actualSleepDuration_32768cycles >> 11) - (actualSleepDuration_32768cycles >> 12);
+  actualSleepDuration_ms = (actualSleepDuration_32768cycles >> 5) - (actualSleepDuration_32768cycles >> 11) - (actualSleepDuration_32768cycles >> 12);
 
-    // vTaskStepTick(actualSleepDuration_ms);
+  // vTaskStepTick(actualSleepDuration_ms);
 
-    return actualSleepDuration_ms;
+  return actualSleepDuration_ms;
 }
 /**
  * @brief get delay value of spi flash init
@@ -85,58 +84,56 @@ uint32_t hal_pds_enter_with_time_compensation(uint32_t pdsLevel, uint32_t pdsSle
  * @param delay_index
  * @return uint8_t
  */
-static uint8_t ATTR_PDS_RAM_SECTION bflb_spi_flash_get_delay_val(uint8_t delay_index)
-{
-    switch (delay_index) {
-        case 0:
-            return 0x00;
-        case 1:
-            return 0x80;
-        case 2:
-            return 0xc0;
-        case 3:
-            return 0xe0;
-        case 4:
-            return 0xf0;
-        case 5:
-            return 0xf8;
-        case 6:
-            return 0xfc;
-        case 7:
-            return 0xfe;
-        default:
-            return 0x00;
-    }
+static uint8_t ATTR_PDS_RAM_SECTION bflb_spi_flash_get_delay_val(uint8_t delay_index) {
+  switch (delay_index) {
+  case 0:
+    return 0x00;
+  case 1:
+    return 0x80;
+  case 2:
+    return 0xc0;
+  case 3:
+    return 0xe0;
+  case 4:
+    return 0xf0;
+  case 5:
+    return 0xf8;
+  case 6:
+    return 0xfc;
+  case 7:
+    return 0xfe;
+  default:
+    return 0x00;
+  }
 }
 /**
  * @brief config spi flash
  *
  * @param pFlashCfg flash parameter
  */
-static void ATTR_PDS_RAM_SECTION bflb_spi_flash_set_sf_ctrl(SPI_Flash_Cfg_Type *pFlashCfg)
-{
-    SF_Ctrl_Cfg_Type sfCtrlCfg;
-    uint8_t delay_index;
-
-    sfCtrlCfg.owner = SF_CTRL_OWNER_SAHB;
-
-    /* bit0-3 for clk delay */
-    sfCtrlCfg.clkDelay = (pFlashCfg->clkDelay & 0x0f);
-    /* bit0 for clk invert */
-    sfCtrlCfg.clkInvert = pFlashCfg->clkInvert & 0x01;
-    /* bit1 for rx clk invert */
-    sfCtrlCfg.rxClkInvert = (pFlashCfg->clkInvert >> 1) & 0x01;
-    /* bit4-6 for do delay */
-    delay_index = (pFlashCfg->clkDelay >> 4) & 0x07;
-    sfCtrlCfg.doDelay = bflb_spi_flash_get_delay_val(delay_index);
-    /* bit2-4 for di delay */
-    delay_index = (pFlashCfg->clkInvert >> 2) & 0x07;
-    sfCtrlCfg.diDelay = bflb_spi_flash_get_delay_val(delay_index);
-    /* bit5-7 for oe delay */
-    delay_index = (pFlashCfg->clkInvert >> 5) & 0x07;
-    sfCtrlCfg.oeDelay = bflb_spi_flash_get_delay_val(delay_index);
-
-    RomDriver_SFlash_Init(&sfCtrlCfg);
+static void ATTR_PDS_RAM_SECTION bflb_spi_flash_set_sf_ctrl(SPI_Flash_Cfg_Type *pFlashCfg) {
+  SF_Ctrl_Cfg_Type sfCtrlCfg;
+  uint8_t          delay_index;
+
+  sfCtrlCfg.owner = SF_CTRL_OWNER_SAHB;
+
+  /* bit0-3 for clk delay */
+  sfCtrlCfg.clkDelay = (pFlashCfg->clkDelay & 0x0f);
+  /* bit0 for clk invert */
+  sfCtrlCfg.clkInvert = pFlashCfg->clkInvert & 0x01;
+  /* bit1 for rx clk invert */
+  sfCtrlCfg.rxClkInvert = (pFlashCfg->clkInvert >> 1) & 0x01;
+  /* bit4-6 for do delay */
+  delay_index       = (pFlashCfg->clkDelay >> 4) & 0x07;
+  sfCtrlCfg.doDelay = bflb_spi_flash_get_delay_val(delay_index);
+  /* bit2-4 for di delay */
+  delay_index       = (pFlashCfg->clkInvert >> 2) & 0x07;
+  sfCtrlCfg.diDelay = bflb_spi_flash_get_delay_val(delay_index);
+  /* bit5-7 for oe delay */
+  delay_index       = (pFlashCfg->clkInvert >> 5) & 0x07;
+  sfCtrlCfg.oeDelay = bflb_spi_flash_get_delay_val(delay_index);
+
+  RomDriver_SFlash_Init(&sfCtrlCfg);
 }
 
 /**
@@ -145,177 +142,168 @@ static void ATTR_PDS_RAM_SECTION bflb_spi_flash_set_sf_ctrl(SPI_Flash_Cfg_Type *
  * @param media_boot
  * @return int32_t
  */
-int32_t ATTR_PDS_RAM_SECTION pm_spi_flash_init(uint8_t media_boot)
-{
-    uint32_t stat;
-    uint32_t jdecId = 0;
-    uint32_t flash_read_try = 0;
-
-    /*use fclk as flash clok */
-    RomDriver_GLB_Set_SF_CLK(1, GLB_SFLASH_CLK_XCLK, 0); // 32M
-    RomDriver_SF_Ctrl_Set_Clock_Delay(0);
-
-    bflb_spi_flash_set_sf_ctrl(flash_cfg);
-
-    /* Wake flash up from power down */
-    RomDriver_SFlash_Releae_Powerdown(flash_cfg);
-    //ARCH_Delay_US(15*((pFlashCfg->pdDelay&0x7)+1));
-    RomDriver_BL702_Delay_US(120);
-
-    do {
-        if (flash_read_try > 4) {
-            // bflb_bootrom_printd("Flash read id TO\r\n");
-            break;
-        } else if (flash_read_try > 0) {
-            RomDriver_BL702_Delay_US(500);
-        }
-
-        // bflb_bootrom_printd("reset flash\r\n");
-        /* Exit form continous read for accepting command */
-        RomDriver_SFlash_Reset_Continue_Read(flash_cfg);
-        /* Send software reset command(80bv has no this command)to deburst wrap for ISSI like */
-        RomDriver_SFlash_Software_Reset(flash_cfg);
-        /* Disable burst may be removed(except for 80BV) and only work with winbond,but just for make sure */
-        RomDriver_SFlash_Write_Enable(flash_cfg);
-        /* For disable command that is setting register instaed of send command, we need write enable */
-        RomDriver_SFlash_DisableBurstWrap(flash_cfg);
-
-        stat = RomDriver_SFlash_SetSPIMode(SF_CTRL_SPI_MODE);
-        if (SUCCESS != stat) {
-            // bflb_bootrom_printe("enter spi mode fail %d\r\n", stat);
-            // return BFLB_BOOTROM_FLASH_INIT_ERROR;
-            return -1;
-        }
-
-        RomDriver_SFlash_GetJedecId(flash_cfg, (uint8_t *)&jdecId);
-
-        /* Dummy disable burstwrap for make sure */
-        RomDriver_SFlash_Write_Enable(flash_cfg);
-        /* For disable command that is setting register instead of send command, we need write enable */
-        RomDriver_SFlash_DisableBurstWrap(flash_cfg);
-
-        jdecId = jdecId & 0xffffff;
-        // bflb_bootrom_printd("ID =%08x\r\n", jdecId);
-        flash_read_try++;
-    } while ((jdecId & 0x00ffff) == 0 || (jdecId & 0xffff00) == 0 || (jdecId & 0x00ffff) == 0xffff || (jdecId & 0xffff00) == 0xffff00);
-
-    /*clear offset setting*/
-
-    // reset image offset
-    BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, flash_offset);
-
-    /* set read mode */
-    if ((flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
-        stat = RomDriver_SFlash_Qspi_Enable(flash_cfg);
+int32_t ATTR_PDS_RAM_SECTION pm_spi_flash_init(uint8_t media_boot) {
+  uint32_t stat;
+  uint32_t jdecId         = 0;
+  uint32_t flash_read_try = 0;
+
+  /*use fclk as flash clok */
+  RomDriver_GLB_Set_SF_CLK(1, GLB_SFLASH_CLK_XCLK, 0); // 32M
+  RomDriver_SF_Ctrl_Set_Clock_Delay(0);
+
+  bflb_spi_flash_set_sf_ctrl(flash_cfg);
+
+  /* Wake flash up from power down */
+  RomDriver_SFlash_Releae_Powerdown(flash_cfg);
+  // ARCH_Delay_US(15*((pFlashCfg->pdDelay&0x7)+1));
+  RomDriver_BL702_Delay_US(120);
+
+  do {
+    if (flash_read_try > 4) {
+      // bflb_bootrom_printd("Flash read id TO\r\n");
+      break;
+    } else if (flash_read_try > 0) {
+      RomDriver_BL702_Delay_US(500);
     }
 
-    if (media_boot) {
-        RomDriver_L1C_Set_Wrap(DISABLE);
-
-        RomDriver_SFlash_Cache_Read_Enable(flash_cfg, flash_cfg->ioMode & 0xf, 0, 0x00);
+    // bflb_bootrom_printd("reset flash\r\n");
+    /* Exit form continous read for accepting command */
+    RomDriver_SFlash_Reset_Continue_Read(flash_cfg);
+    /* Send software reset command(80bv has no this command)to deburst wrap for ISSI like */
+    RomDriver_SFlash_Software_Reset(flash_cfg);
+    /* Disable burst may be removed(except for 80BV) and only work with winbond,but just for make sure */
+    RomDriver_SFlash_Write_Enable(flash_cfg);
+    /* For disable command that is setting register instaed of send command, we need write enable */
+    RomDriver_SFlash_DisableBurstWrap(flash_cfg);
+
+    stat = RomDriver_SFlash_SetSPIMode(SF_CTRL_SPI_MODE);
+    if (SUCCESS != stat) {
+      // bflb_bootrom_printe("enter spi mode fail %d\r\n", stat);
+      // return BFLB_BOOTROM_FLASH_INIT_ERROR;
+      return -1;
     }
 
-    return jdecId;
+    RomDriver_SFlash_GetJedecId(flash_cfg, (uint8_t *)&jdecId);
+
+    /* Dummy disable burstwrap for make sure */
+    RomDriver_SFlash_Write_Enable(flash_cfg);
+    /* For disable command that is setting register instead of send command, we need write enable */
+    RomDriver_SFlash_DisableBurstWrap(flash_cfg);
+
+    jdecId = jdecId & 0xffffff;
+    // bflb_bootrom_printd("ID =%08x\r\n", jdecId);
+    flash_read_try++;
+  } while ((jdecId & 0x00ffff) == 0 || (jdecId & 0xffff00) == 0 || (jdecId & 0x00ffff) == 0xffff || (jdecId & 0xffff00) == 0xffff00);
+
+  /*clear offset setting*/
+
+  // reset image offset
+  BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, flash_offset);
+
+  /* set read mode */
+  if ((flash_cfg->ioMode & 0x0f) == SF_CTRL_QO_MODE || (flash_cfg->ioMode & 0x0f) == SF_CTRL_QIO_MODE) {
+    stat = RomDriver_SFlash_Qspi_Enable(flash_cfg);
+  }
+
+  if (media_boot) {
+    RomDriver_L1C_Set_Wrap(DISABLE);
+
+    RomDriver_SFlash_Cache_Read_Enable(flash_cfg, flash_cfg->ioMode & 0xf, 0, 0x00);
+  }
+
+  return jdecId;
 }
 
 // can be placed in flash, here placed in pds section to reduce fast boot time
-static void ATTR_PDS_RAM_SECTION pm_pds_restore_cpu_reg(void)
-{
-    __asm__ __volatile__(
-        "la     a2,     __ld_pds_bak_addr\n\t"
-        "lw     ra,     0(a2)\n\t"
-        "lw     sp,     1*4(a2)\n\t"
-        "lw     tp,     2*4(a2)\n\t"
-        "lw     t0,     3*4(a2)\n\t"
-        "lw     t1,     4*4(a2)\n\t"
-        "lw     t2,     5*4(a2)\n\t"
-        "lw     fp,     6*4(a2)\n\t"
-        "lw     s1,     7*4(a2)\n\t"
-        "lw     a0,     8*4(a2)\n\t"
-        "lw     a1,     9*4(a2)\n\t"
-        "lw     a3,     10*4(a2)\n\t"
-        "lw     a4,     11*4(a2)\n\t"
-        "lw     a5,     12*4(a2)\n\t"
-        "lw     a6,     13*4(a2)\n\t"
-        "lw     a7,     14*4(a2)\n\t"
-        "lw     s2,     15*4(a2)\n\t"
-        "lw     s3,     16*4(a2)\n\t"
-        "lw     s4,     17*4(a2)\n\t"
-        "lw     s5,     18*4(a2)\n\t"
-        "lw     s6,     19*4(a2)\n\t"
-        "lw     s7,     20*4(a2)\n\t"
-        "lw     s8,     21*4(a2)\n\t"
-        "lw     s9,     22*4(a2)\n\t"
-        "lw     s10,    23*4(a2)\n\t"
-        "lw     s11,    24*4(a2)\n\t"
-        "lw     t3,     25*4(a2)\n\t"
-        "lw     t4,     26*4(a2)\n\t"
-        "lw     t5,     27*4(a2)\n\t"
-        "lw     t6,     28*4(a2)\n\t"
-        "csrw   mtvec,  a0\n\t"
-        "csrw   mstatus,a1\n\t"
-        "ret\n\t");
+static void ATTR_PDS_RAM_SECTION pm_pds_restore_cpu_reg(void) {
+  __asm__ __volatile__("la     a2,     __ld_pds_bak_addr\n\t"
+                       "lw     ra,     0(a2)\n\t"
+                       "lw     sp,     1*4(a2)\n\t"
+                       "lw     tp,     2*4(a2)\n\t"
+                       "lw     t0,     3*4(a2)\n\t"
+                       "lw     t1,     4*4(a2)\n\t"
+                       "lw     t2,     5*4(a2)\n\t"
+                       "lw     fp,     6*4(a2)\n\t"
+                       "lw     s1,     7*4(a2)\n\t"
+                       "lw     a0,     8*4(a2)\n\t"
+                       "lw     a1,     9*4(a2)\n\t"
+                       "lw     a3,     10*4(a2)\n\t"
+                       "lw     a4,     11*4(a2)\n\t"
+                       "lw     a5,     12*4(a2)\n\t"
+                       "lw     a6,     13*4(a2)\n\t"
+                       "lw     a7,     14*4(a2)\n\t"
+                       "lw     s2,     15*4(a2)\n\t"
+                       "lw     s3,     16*4(a2)\n\t"
+                       "lw     s4,     17*4(a2)\n\t"
+                       "lw     s5,     18*4(a2)\n\t"
+                       "lw     s6,     19*4(a2)\n\t"
+                       "lw     s7,     20*4(a2)\n\t"
+                       "lw     s8,     21*4(a2)\n\t"
+                       "lw     s9,     22*4(a2)\n\t"
+                       "lw     s10,    23*4(a2)\n\t"
+                       "lw     s11,    24*4(a2)\n\t"
+                       "lw     t3,     25*4(a2)\n\t"
+                       "lw     t4,     26*4(a2)\n\t"
+                       "lw     t5,     27*4(a2)\n\t"
+                       "lw     t6,     28*4(a2)\n\t"
+                       "csrw   mtvec,  a0\n\t"
+                       "csrw   mstatus,a1\n\t"
+                       "ret\n\t");
 }
-void ATTR_PDS_RAM_SECTION sf_io_select(void)
-{
-    uint32_t tmpVal = 0;
-    uint8_t flashCfg = 0;
-    uint8_t psramCfg = 0;
-    uint8_t isInternalFlash = 0;
-    uint8_t isInternalPsram = 0;
-
-    /* SF io select from efuse value */
-    tmpVal = BL_RD_WORD(0x40007074);
-    flashCfg = ((tmpVal >> 26) & 7);
-    psramCfg = ((tmpVal >> 24) & 3);
-    if (flashCfg == 1 || flashCfg == 2) {
-        isInternalFlash = 1;
-    } else {
-        isInternalFlash = 0;
-    }
-    if (psramCfg == 1) {
-        isInternalPsram = 1;
-    } else {
-        isInternalPsram = 0;
-    }
-    tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO);
-    if (isInternalFlash == 1 && isInternalPsram == 0) {
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x3f);
-    } else {
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00);
-    }
-    BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal);
+void ATTR_PDS_RAM_SECTION sf_io_select(void) {
+  uint32_t tmpVal          = 0;
+  uint8_t  flashCfg        = 0;
+  uint8_t  psramCfg        = 0;
+  uint8_t  isInternalFlash = 0;
+  uint8_t  isInternalPsram = 0;
+
+  /* SF io select from efuse value */
+  tmpVal   = BL_RD_WORD(0x40007074);
+  flashCfg = ((tmpVal >> 26) & 7);
+  psramCfg = ((tmpVal >> 24) & 3);
+  if (flashCfg == 1 || flashCfg == 2) {
+    isInternalFlash = 1;
+  } else {
+    isInternalFlash = 0;
+  }
+  if (psramCfg == 1) {
+    isInternalPsram = 1;
+  } else {
+    isInternalPsram = 0;
+  }
+  tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO);
+  if (isInternalFlash == 1 && isInternalPsram == 0) {
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x3f);
+  } else {
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00);
+  }
+  BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal);
 }
 // must be placed in pds section
-void ATTR_PDS_RAM_SECTION pm_pds_fastboot_entry(void)
-{
-    // reload gp register
-    __asm__ __volatile__(
-        ".option push\n\t"
-        ".option norelax\n\t"
-        "la gp, __global_pointer$\n\t"
-        ".option pop\n\t");
+void ATTR_PDS_RAM_SECTION pm_pds_fastboot_entry(void) {
+  // reload gp register
+  __asm__ __volatile__(".option push\n\t"
+                       ".option norelax\n\t"
+                       "la gp, __global_pointer$\n\t"
+                       ".option pop\n\t");
 
 #if XTAL_TYPE != INTERNAL_RC_32M
-    /* power on Xtal_32M*/
-    (*(volatile uint32_t *)(AON_BASE + AON_RF_TOP_AON_OFFSET)) |= (3 << 4);
+  /* power on Xtal_32M*/
+  (*(volatile uint32_t *)(AON_BASE + AON_RF_TOP_AON_OFFSET)) |= (3 << 4);
 #endif
 
-    // recovery flash pad and param
-    RomDriver_SF_Cfg_Init_Flash_Gpio(0, 1);
-    pm_spi_flash_init(1);
-    sf_io_select();
+  // recovery flash pad and param
+  RomDriver_SF_Cfg_Init_Flash_Gpio(0, 1);
+  pm_spi_flash_init(1);
+  sf_io_select();
 
-    /* Recovery hardware , include tcm , gpio and clock */
-    if (hardware_recovery) {
-        hardware_recovery();
-    }
+  /* Recovery hardware , include tcm , gpio and clock */
+  if (hardware_recovery) {
+    hardware_recovery();
+  }
 
-    // Restore cpu registers
-    pm_pds_restore_cpu_reg();
+  // Restore cpu registers
+  pm_pds_restore_cpu_reg();
 }
 
-void pm_set_hardware_recovery_callback(void (*hardware_recovery_cb)(void))
-{
-    hardware_recovery = hardware_recovery_cb;
-}
\ No newline at end of file
+void pm_set_hardware_recovery_callback(void (*hardware_recovery_cb)(void)) { hardware_recovery = hardware_recovery_cb; }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_rtc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_rtc.c
index 9b4a4368d..d177b9760 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_rtc.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_rtc.c
@@ -29,73 +29,68 @@ static uint64_t current_timestamp = 0;
  *
  * @param sleep_time
  */
-void rtc_init(uint64_t sleep_time)
-{
-    uint32_t tmpVal;
-    uint32_t comp_l, comp_h;
+void rtc_init(uint64_t sleep_time) {
+  uint32_t tmpVal;
+  uint32_t comp_l, comp_h;
 
-    /* Clear & Disable RTC counter */
-    tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
-    /* Clear RTC control bit0 */
-    BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffff0);
+  /* Clear & Disable RTC counter */
+  tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
+  /* Clear RTC control bit0 */
+  BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffff0);
 
-    /* Get current RTC timer */
-    /* Tigger RTC val read */
-    tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H);
-    tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
-    BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
-    tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
-    BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
+  /* Get current RTC timer */
+  /* Tigger RTC val read */
+  tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H);
+  tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
+  BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
+  tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
+  BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
 
-    /* Read RTC val */
-    comp_l = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L);
-    comp_h = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff);
+  /* Read RTC val */
+  comp_l = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L);
+  comp_h = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff);
 
-    /* calculate RTC Comp time */
-    comp_l += (uint32_t)((sleep_time * 32768) & 0xFFFFFFFF);
-    comp_h += (uint32_t)(((sleep_time * 32768) >> 32) & 0xFFFFFFFF);
+  /* calculate RTC Comp time */
+  comp_l += (uint32_t)((sleep_time * 32768) & 0xFFFFFFFF);
+  comp_h += (uint32_t)(((sleep_time * 32768) >> 32) & 0xFFFFFFFF);
 
-    /* Set RTC Comp time  */
-    BL_WR_REG(HBN_BASE, HBN_TIME_L, comp_l);
-    BL_WR_REG(HBN_BASE, HBN_TIME_H, comp_h & 0xff);
+  /* Set RTC Comp time  */
+  BL_WR_REG(HBN_BASE, HBN_TIME_L, comp_l);
+  BL_WR_REG(HBN_BASE, HBN_TIME_H, comp_h & 0xff);
 
-    tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
-    /* Set interrupt delay option */
-    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RTC_DLY_OPTION, HBN_RTC_INT_DELAY_0T);
-    /* Set RTC compare mode */
-    tmpVal |= (HBN_RTC_COMP_BIT0_39 << 1);
-    BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal);
+  tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
+  /* Set interrupt delay option */
+  tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RTC_DLY_OPTION, HBN_RTC_INT_DELAY_0T);
+  /* Set RTC compare mode */
+  tmpVal |= (HBN_RTC_COMP_BIT0_39 << 1);
+  BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal);
 
-    /* Enable RTC Counter */
-    tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
-    /* Set RTC control bit0 */
-    BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal | 0x01);
+  /* Enable RTC Counter */
+  tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL);
+  /* Set RTC control bit0 */
+  BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal | 0x01);
 }
 
-void rtc_set_timestamp(uint64_t time_stamp)
-{
-    current_timestamp = time_stamp;
-}
+void rtc_set_timestamp(uint64_t time_stamp) { current_timestamp = time_stamp; }
 /**
-* @bref Get rtc value
-*
-*/
-uint64_t rtc_get_timestamp(void)
-{
-    uint32_t tmpVal;
-    uint64_t time_l;
-    uint64_t time_h;
+ * @bref Get rtc value
+ *
+ */
+uint64_t rtc_get_timestamp(void) {
+  uint32_t tmpVal;
+  uint64_t time_l;
+  uint64_t time_h;
 
-    /* Tigger RTC val read */
-    tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H);
-    tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
-    BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
-    tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
-    BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
+  /* Tigger RTC val read */
+  tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H);
+  tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
+  BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
+  tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH);
+  BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal);
 
-    /* Read RTC val */
-    time_l = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L);
-    time_h = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff);
+  /* Read RTC val */
+  time_l = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L);
+  time_h = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff);
 
-    return (((time_h << 32 | time_l) >> 15) + current_timestamp);
+  return (((time_h << 32 | time_l) >> 15) + current_timestamp);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_aes.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_aes.c
index 7cc6410a9..833164c5e 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_aes.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_aes.c
@@ -25,95 +25,87 @@
 
 static SEC_Eng_AES_Ctx aesCtx;
 
-int sec_aes_init(sec_aes_handle_t *handle, sec_aes_type aes_tye, sec_aes_key_type key_type)
-{
-    handle->aes_type = aes_tye;
-    handle->key_type = key_type;
+int sec_aes_init(sec_aes_handle_t *handle, sec_aes_type aes_tye, sec_aes_key_type key_type) {
+  handle->aes_type = aes_tye;
+  handle->key_type = key_type;
 
-    return 0;
+  return 0;
 }
 
-static SEC_ENG_AES_Key_Type sec_aes_get_key_type(sec_aes_handle_t *handle)
-{
-    SEC_ENG_AES_Key_Type type = 0;
+static SEC_ENG_AES_Key_Type sec_aes_get_key_type(sec_aes_handle_t *handle) {
+  SEC_ENG_AES_Key_Type type = 0;
 
-    switch (handle->key_type) {
-        case SEC_AES_KEY_128:
-            type = SEC_ENG_AES_KEY_128BITS;
-            break;
+  switch (handle->key_type) {
+  case SEC_AES_KEY_128:
+    type = SEC_ENG_AES_KEY_128BITS;
+    break;
 
-        case SEC_AES_KEY_256:
-            type = SEC_ENG_AES_KEY_256BITS;
-            break;
+  case SEC_AES_KEY_256:
+    type = SEC_ENG_AES_KEY_256BITS;
+    break;
 
-        case SEC_AES_KEY_192:
-            type = SEC_ENG_AES_KEY_192BITS;
-            break;
+  case SEC_AES_KEY_192:
+    type = SEC_ENG_AES_KEY_192BITS;
+    break;
 
-        default:
-            return SEC_ENG_AES_KEY_128BITS;
-    }
+  default:
+    return SEC_ENG_AES_KEY_128BITS;
+  }
 
-    return type;
+  return type;
 }
 
-int sec_aes_setkey(sec_aes_handle_t *handle, const uint8_t *key, uint8_t key_len, const uint8_t *nonce, uint8_t dir)
-{
-    SEC_ENG_AES_Key_Type type = sec_aes_get_key_type(handle);
-
-    switch (handle->aes_type) {
-        case SEC_AES_CBC:
-            Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0);
-            Sec_Eng_AES_Init(&aesCtx, SEC_ENG_AES_ID0, SEC_ENG_AES_CBC, type,
-                             SEC_AES_DIR_ENCRYPT == dir ? SEC_ENG_AES_ENCRYPTION : SEC_ENG_AES_DECRYPTION);
-            break;
-
-        case SEC_AES_CTR:
-            Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0);
-            Sec_Eng_AES_Init(&aesCtx, SEC_ENG_AES_ID0, SEC_ENG_AES_CTR, type,
-                             SEC_AES_DIR_ENCRYPT == dir ? SEC_ENG_AES_ENCRYPTION : SEC_ENG_AES_DECRYPTION);
-            break;
-
-        case SEC_AES_ECB:
-            break;
-
-        default:
-            return -1;
-    }
-
-    /* if key len is 0, means key is from efuse and *key value is key_sel value */
-    if (key_len == 0) {
-        Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0, SEC_ENG_AES_KEY_HW, key, nonce);
-    } else {
-        Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0, SEC_ENG_AES_KEY_SW, key, nonce);
-    }
-
-    return 0;
+int sec_aes_setkey(sec_aes_handle_t *handle, const uint8_t *key, uint8_t key_len, const uint8_t *nonce, uint8_t dir) {
+  SEC_ENG_AES_Key_Type type = sec_aes_get_key_type(handle);
+
+  switch (handle->aes_type) {
+  case SEC_AES_CBC:
+    Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0);
+    Sec_Eng_AES_Init(&aesCtx, SEC_ENG_AES_ID0, SEC_ENG_AES_CBC, type, SEC_AES_DIR_ENCRYPT == dir ? SEC_ENG_AES_ENCRYPTION : SEC_ENG_AES_DECRYPTION);
+    break;
+
+  case SEC_AES_CTR:
+    Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0);
+    Sec_Eng_AES_Init(&aesCtx, SEC_ENG_AES_ID0, SEC_ENG_AES_CTR, type, SEC_AES_DIR_ENCRYPT == dir ? SEC_ENG_AES_ENCRYPTION : SEC_ENG_AES_DECRYPTION);
+    break;
+
+  case SEC_AES_ECB:
+    break;
+
+  default:
+    return -1;
+  }
+
+  /* if key len is 0, means key is from efuse and *key value is key_sel value */
+  if (key_len == 0) {
+    Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0, SEC_ENG_AES_KEY_HW, key, nonce);
+  } else {
+    Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0, SEC_ENG_AES_KEY_SW, key, nonce);
+  }
+
+  return 0;
 }
 
-int sec_aes_encrypt(sec_aes_handle_t *handle, const uint8_t *in, uint32_t len, size_t offset, uint8_t *out)
-{
-    if (SUCCESS != Sec_Eng_AES_Crypt(&aesCtx, SEC_ENG_AES_ID0, in, len, out)) {
-        return -1;
-    }
+int sec_aes_encrypt(sec_aes_handle_t *handle, const uint8_t *in, uint32_t len, size_t offset, uint8_t *out) {
+  if (SUCCESS != Sec_Eng_AES_Crypt(&aesCtx, SEC_ENG_AES_ID0, in, len, out)) {
+    return -1;
+  }
 
-    return 0;
+  return 0;
 }
 
-int sec_aes_decrypt(sec_aes_handle_t *handle, const uint8_t *in, uint32_t len, size_t offset, uint8_t *out)
-{
-    if (SUCCESS != Sec_Eng_AES_Crypt(&aesCtx, SEC_ENG_AES_ID0, in, len, out)) {
-        return -1;
-    }
+int sec_aes_decrypt(sec_aes_handle_t *handle, const uint8_t *in, uint32_t len, size_t offset, uint8_t *out) {
+  if (SUCCESS != Sec_Eng_AES_Crypt(&aesCtx, SEC_ENG_AES_ID0, in, len, out)) {
+    return -1;
+  }
 
-    return 0;
+  return 0;
 }
 
-int sec_aes_deinit(sec_aes_handle_t *handle)
-{
-    Sec_Eng_AES_Finish(SEC_ENG_AES_ID0);
+int sec_aes_deinit(sec_aes_handle_t *handle) {
+  Sec_Eng_AES_Finish(SEC_ENG_AES_ID0);
 
-    memset(handle, 0, sizeof(sec_aes_handle_t));
+  memset(handle, 0, sizeof(sec_aes_handle_t));
 
-    return 0;
+  return 0;
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_dsa.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_dsa.c
index 3929b90d6..c9e6f0713 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_dsa.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_dsa.c
@@ -23,12 +23,12 @@
 #include "hal_sec_dsa.h"
 #include "bl702_sec_eng.h"
 
-//#define DSA_DBG                                   1
-//#define DSA_DBG_DETAIL                            1
+// #define DSA_DBG                                   1
+// #define DSA_DBG_DETAIL                            1
 void bflb_platform_dump(uint8_t *data, uint32_t len);
 
 #if (defined(DSA_DBG) || defined(DSA_DBG_DETAIL))
-uint32_t pka_tmp[64] = { 0 };
+uint32_t pka_tmp[64] = {0};
 #endif
 
 /*
@@ -43,44 +43,43 @@ h=qInv*(m1-m2)%p
 m=m2+h*q
 m=c^d
 */
-static SEC_ENG_PKA_REG_SIZE_Type sec_dsa_get_reg_size(uint32_t size)
-{
-    switch (size) {
-        case 64:
-            return SEC_ENG_PKA_REG_SIZE_8;
+static SEC_ENG_PKA_REG_SIZE_Type sec_dsa_get_reg_size(uint32_t size) {
+  switch (size) {
+  case 64:
+    return SEC_ENG_PKA_REG_SIZE_8;
 
-        case 128:
-            return SEC_ENG_PKA_REG_SIZE_16;
+  case 128:
+    return SEC_ENG_PKA_REG_SIZE_16;
 
-        case 256:
-            return SEC_ENG_PKA_REG_SIZE_32;
-
-        case 512:
-            return SEC_ENG_PKA_REG_SIZE_64;
+  case 256:
+    return SEC_ENG_PKA_REG_SIZE_32;
 
-        case 768:
-            return SEC_ENG_PKA_REG_SIZE_96;
+  case 512:
+    return SEC_ENG_PKA_REG_SIZE_64;
 
-        case 1024:
-            return SEC_ENG_PKA_REG_SIZE_128;
+  case 768:
+    return SEC_ENG_PKA_REG_SIZE_96;
 
-        case 1536:
-            return SEC_ENG_PKA_REG_SIZE_192;
+  case 1024:
+    return SEC_ENG_PKA_REG_SIZE_128;
 
-        case 2048:
-            return SEC_ENG_PKA_REG_SIZE_256;
+  case 1536:
+    return SEC_ENG_PKA_REG_SIZE_192;
 
-        case 3072:
-            return SEC_ENG_PKA_REG_SIZE_384;
+  case 2048:
+    return SEC_ENG_PKA_REG_SIZE_256;
 
-        case 4096:
-            return SEC_ENG_PKA_REG_SIZE_512;
+  case 3072:
+    return SEC_ENG_PKA_REG_SIZE_384;
 
-        default:
-            return SEC_ENG_PKA_REG_SIZE_32;
-    }
+  case 4096:
+    return SEC_ENG_PKA_REG_SIZE_512;
 
+  default:
     return SEC_ENG_PKA_REG_SIZE_32;
+  }
+
+  return SEC_ENG_PKA_REG_SIZE_32;
 }
 
 /* c code:
@@ -93,151 +92,138 @@ while b:
     base = base * base % c
 return number
 */
-int sec_dsa_mexp_binary(uint32_t size, const uint32_t *a, const uint32_t *b, const uint32_t *c, uint32_t *r)
-{
-    uint32_t i, j, k;
-    uint32_t tmp;
-    uint32_t isOne = 0;
-    uint8_t *p = (uint8_t *)b;
-    SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
-    SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
-    uint32_t dataSize = (size >> 3) >> 2;
+int sec_dsa_mexp_binary(uint32_t size, const uint32_t *a, const uint32_t *b, const uint32_t *c, uint32_t *r) {
+  uint32_t                  i, j, k;
+  uint32_t                  tmp;
+  uint32_t                  isOne    = 0;
+  uint8_t                  *p        = (uint8_t *)b;
+  SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
+  SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
+  uint32_t                  dataSize = (size >> 3) >> 2;
 #if 1
-    uint8_t oneBuf[128] ALIGN4 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-                                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
+  uint8_t oneBuf[128] ALIGN4 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
 #endif
-    /* 0:c
-     * 4:a
-     * 5:number
-     * 6&7:temp
-     */
-
-    /* base = a */
-    Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)a, dataSize, 0);
-
-    /* number = 1 */
-    Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)oneBuf, sizeof(oneBuf) / 4, 0);
-    //Sec_Eng_PKA_Write_Immediate(nregType,5,0x01,1);
+  /* 0:c
+   * 4:a
+   * 5:number
+   * 6&7:temp
+   */
+
+  /* base = a */
+  Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)a, dataSize, 0);
+
+  /* number = 1 */
+  Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)oneBuf, sizeof(oneBuf) / 4, 0);
+  // Sec_Eng_PKA_Write_Immediate(nregType,5,0x01,1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)pka_tmp, dataSize);
-    MSG("number:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize * 4);
+  Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)pka_tmp, dataSize);
+  MSG("number:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize * 4);
 #endif
 
-    Sec_Eng_PKA_Write_Data(nregType, 0, (uint32_t *)c, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 0, (uint32_t *)c, dataSize, 0);
 
-    Sec_Eng_PKA_CREG(nregType, 6, dataSize, 1);
-    Sec_Eng_PKA_CREG(nregType, 7, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 6, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 7, dataSize, 1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
-    MSG("base:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize * 4);
+  Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
+  MSG("base:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize * 4);
 #endif
-    /* Remove zeros bytes*/
-    k = 0;
+  /* Remove zeros bytes*/
+  k = 0;
 
-    while (p[k] == 0 && k < (size >> 3)) {
-        k++;
-    }
+  while (p[k] == 0 && k < (size >> 3)) {
+    k++;
+  }
 
-    i = (size >> 3) - 1;
+  i = (size >> 3) - 1;
 
-    for (; i >= k; i--) {
-        tmp = p[i];
-        j = 0;
+  for (; i >= k; i--) {
+    tmp = p[i];
+    j   = 0;
 
-        for (j = 0; j < 8; j++) {
-            isOne = tmp & (1 << j);
+    for (j = 0; j < 8; j++) {
+      isOne = tmp & (1 << j);
 
-            if (isOne) {
-                /* number = number * base % c */
-                Sec_Eng_PKA_LMUL(lregType, 3, nregType, 5, nregType, 4, 0);
-                Sec_Eng_PKA_MREM(nregType, 5, lregType, 3, nregType, 0, 1);
+      if (isOne) {
+        /* number = number * base % c */
+        Sec_Eng_PKA_LMUL(lregType, 3, nregType, 5, nregType, 4, 0);
+        Sec_Eng_PKA_MREM(nregType, 5, lregType, 3, nregType, 0, 1);
 #ifdef DSA_DBG
-                Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)pka_tmp, dataSize);
-                MSG("number:\r\n");
-                bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
+        Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)pka_tmp, dataSize);
+        MSG("number:\r\n");
+        bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
 #endif
-            }
+      }
 
-            /* base = base * base % c */
-            Sec_Eng_PKA_LSQR(lregType, 3, nregType, 4, 0);
-            Sec_Eng_PKA_MREM(nregType, 4, lregType, 3, nregType, 0, 1);
+      /* base = base * base % c */
+      Sec_Eng_PKA_LSQR(lregType, 3, nregType, 4, 0);
+      Sec_Eng_PKA_MREM(nregType, 4, lregType, 3, nregType, 0, 1);
 #ifdef DSA_DBG
-            Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
-            MSG("base:\r\n");
-            bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
+      Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
+      MSG("base:\r\n");
+      bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
 #endif
-        }
     }
+  }
 
-    Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)r, dataSize);
+  Sec_Eng_PKA_Read_Data(nregType, 5, (uint32_t *)r, dataSize);
 #ifdef DSA_DBG
-    MSG("r:\r\n");
-    bflb_platform_dump(r, dataSize * 4);
+  MSG("r:\r\n");
+  bflb_platform_dump(r, dataSize * 4);
 #endif
-    return 0;
+  return 0;
 }
 
 /*r=a^b%c*/
-int sec_dsa_mexp_mont(uint32_t size, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *invR_c, uint32_t *primeN_c, uint32_t *r)
-{
-    SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
-    SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
-    uint32_t dataSize = (size >> 3) >> 2;
-
-    /* 0:c
-     * 1:NPrime_c
-     * 2:invR_c
-     * 4:a(mont domain)
-     * 5:b
-     * 6:a^b%c(mont domain)
-     * 7:a^b%c(gf domain)
-     * 10&11:2^size for GF2Mont*/
-    Sec_Eng_PKA_Write_Data(nregType, 0, (uint32_t *)c, dataSize, 0);
-    Sec_Eng_PKA_Write_Data(nregType, 1, (uint32_t *)primeN_c, dataSize, 1);
-    Sec_Eng_PKA_Write_Data(nregType, 2, (uint32_t *)invR_c, dataSize, 1);
-
-    /* change a into mont domain*/
-    Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)a, dataSize, 0);
-    Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
-    Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
-    Sec_Eng_PKA_GF2Mont(nregType, 4, nregType, 4, size, lregType, 5, nregType, 0);
+int sec_dsa_mexp_mont(uint32_t size, uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *invR_c, uint32_t *primeN_c, uint32_t *r) {
+  SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
+  SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
+  uint32_t                  dataSize = (size >> 3) >> 2;
+
+  /* 0:c
+   * 1:NPrime_c
+   * 2:invR_c
+   * 4:a(mont domain)
+   * 5:b
+   * 6:a^b%c(mont domain)
+   * 7:a^b%c(gf domain)
+   * 10&11:2^size for GF2Mont*/
+  Sec_Eng_PKA_Write_Data(nregType, 0, (uint32_t *)c, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 1, (uint32_t *)primeN_c, dataSize, 1);
+  Sec_Eng_PKA_Write_Data(nregType, 2, (uint32_t *)invR_c, dataSize, 1);
+
+  /* change a into mont domain*/
+  Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)a, dataSize, 0);
+  Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
+  Sec_Eng_PKA_GF2Mont(nregType, 4, nregType, 4, size, lregType, 5, nregType, 0);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
-    MSG("GF2Mont Result of a:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
+  Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
+  MSG("GF2Mont Result of a:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
 #endif
 
-    Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)b, dataSize, 0);
-    /* a^b%c*/
-    Sec_Eng_PKA_MEXP(nregType, 6, nregType, 4, nregType, 5, nregType, 0, 1);
+  Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)b, dataSize, 0);
+  /* a^b%c*/
+  Sec_Eng_PKA_MEXP(nregType, 6, nregType, 4, nregType, 5, nregType, 0, 1);
 
-    /* change result into gf domain*/
-    Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
-    Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
-    /*index 2 is invertR*/
-    Sec_Eng_PKA_Mont2GF(nregType, 7, nregType, 6, nregType, 2, lregType, 5, nregType, 0);
-    Sec_Eng_PKA_Read_Data(nregType, 7, (uint32_t *)r, dataSize);
+  /* change result into gf domain*/
+  Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
+  /*index 2 is invertR*/
+  Sec_Eng_PKA_Mont2GF(nregType, 7, nregType, 6, nregType, 2, lregType, 5, nregType, 0);
+  Sec_Eng_PKA_Read_Data(nregType, 7, (uint32_t *)r, dataSize);
 #ifdef DSA_DBG
-    MSG("r:\r\n");
-    bflb_platform_dump(r, dataSize /*dataSize*4*/);
+  MSG("r:\r\n");
+  bflb_platform_dump(r, dataSize /*dataSize*4*/);
 #endif
-    return 0;
+  return 0;
 }
 
 /**
@@ -247,17 +233,16 @@ int sec_dsa_mexp_mont(uint32_t size, uint32_t *a, uint32_t *b, uint32_t *c, uint
  * invR_p*r%p=1(r is 1024/2048/256)
  * invR_q*r%q=1(r is 1024/2048/256)
  */
-int sec_dsa_decrypt_crt(uint32_t size, uint32_t *c, sec_dsa_crt_cfg_t *crtCfg, uint32_t *d, uint32_t *r)
-{
-    /*
-     * m1 = pow(c, dP, p)
-     * m2 = pow(c, dQ, q)
-     * h = (qInv * (m1 - m2)) % p
-     * m = m2 + h * q
-     * */
-    SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
-    SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
-    uint32_t dataSize = (size >> 3) >> 2;
+int sec_dsa_decrypt_crt(uint32_t size, uint32_t *c, sec_dsa_crt_cfg_t *crtCfg, uint32_t *d, uint32_t *r) {
+  /*
+   * m1 = pow(c, dP, p)
+   * m2 = pow(c, dQ, q)
+   * h = (qInv * (m1 - m2)) % p
+   * m = m2 + h * q
+   * */
+  SEC_ENG_PKA_REG_SIZE_Type nregType = sec_dsa_get_reg_size(size);
+  SEC_ENG_PKA_REG_SIZE_Type lregType = sec_dsa_get_reg_size(size * 2);
+  uint32_t                  dataSize = (size >> 3) >> 2;
 #if 0
     uint8_t  m1[64] = {0x11, 0xdd, 0x19, 0x7e, 0x69, 0x1a, 0x40, 0x0a, 0x28, 0xfc, 0x3b, 0x31, 0x47, 0xa2, 0x6c, 0x14,
                        0x4e, 0xf6, 0xb0, 0xe6, 0xcd, 0x89, 0x0b, 0x4f, 0x02, 0xe4, 0x86, 0xe2, 0xe5, 0xbe, 0xe1, 0xaf,
@@ -270,120 +255,117 @@ int sec_dsa_decrypt_crt(uint32_t size, uint32_t *c, sec_dsa_crt_cfg_t *crtCfg, u
                        0x68, 0x90, 0x57, 0x97, 0xfc, 0x78, 0xd5, 0xdb, 0x07, 0x5b, 0xfe, 0x21, 0x0a, 0x2d, 0x7f, 0xc1
                       };
 #else
-    uint32_t m1[32];
-    uint32_t m2[32];
+  uint32_t m1[32];
+  uint32_t m2[32];
 #endif
-    /*
-     * 4:m1
-     * 5:m2
-     * 6:qInv
-     * 7:p
-     * 8:q
-     * 9:h
-     * 10&11:qInv*(m1-m2)
-     */
-    sec_dsa_mexp_mont(size, c, crtCfg->dP, crtCfg->p, crtCfg->invR_p, crtCfg->primeN_p, m1);
-    sec_dsa_mexp_mont(size, c, crtCfg->dQ, crtCfg->q, crtCfg->invR_q, crtCfg->primeN_q, m2);
-
-    Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)m1, dataSize, 0);
-    Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)m2, dataSize, 0);
-    Sec_Eng_PKA_Write_Data(nregType, 6, (uint32_t *)crtCfg->qInv, dataSize, 0);
-    Sec_Eng_PKA_Write_Data(nregType, 7, (uint32_t *)crtCfg->p, dataSize, 0);
-    Sec_Eng_PKA_Write_Data(nregType, 8, (uint32_t *)crtCfg->q, dataSize, 0);
-
-    /*(m1 - m2)%p*/
-    Sec_Eng_PKA_MSUB(nregType, 4, nregType, 4, nregType, 5, nregType, 7, 1);
+  /*
+   * 4:m1
+   * 5:m2
+   * 6:qInv
+   * 7:p
+   * 8:q
+   * 9:h
+   * 10&11:qInv*(m1-m2)
+   */
+  sec_dsa_mexp_mont(size, c, crtCfg->dP, crtCfg->p, crtCfg->invR_p, crtCfg->primeN_p, m1);
+  sec_dsa_mexp_mont(size, c, crtCfg->dQ, crtCfg->q, crtCfg->invR_q, crtCfg->primeN_q, m2);
+
+  Sec_Eng_PKA_Write_Data(nregType, 4, (uint32_t *)m1, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 5, (uint32_t *)m2, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 6, (uint32_t *)crtCfg->qInv, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 7, (uint32_t *)crtCfg->p, dataSize, 0);
+  Sec_Eng_PKA_Write_Data(nregType, 8, (uint32_t *)crtCfg->q, dataSize, 0);
+
+  /*(m1 - m2)%p*/
+  Sec_Eng_PKA_MSUB(nregType, 4, nregType, 4, nregType, 5, nregType, 7, 1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
-    MSG("m1 - m2:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
+  Sec_Eng_PKA_Read_Data(nregType, 4, (uint32_t *)pka_tmp, dataSize);
+  MSG("m1 - m2:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*/);
 #endif
-    /* (qInv * (m1 - m2)) % p*/
-    Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
-    Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
-    Sec_Eng_PKA_LMUL(lregType, 5, nregType, 6, nregType, 4, 1);
+  /* (qInv * (m1 - m2)) % p*/
+  Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
+  Sec_Eng_PKA_LMUL(lregType, 5, nregType, 6, nregType, 4, 1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)pka_tmp, dataSize * 2);
-    MSG("qInv * (m1 - m2):\r\n");
-    bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*2*/);
+  Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)pka_tmp, dataSize * 2);
+  MSG("qInv * (m1 - m2):\r\n");
+  bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*2*/);
 #endif
-    Sec_Eng_PKA_MREM(nregType, 9, lregType, 5, nregType, 7, 1);
+  Sec_Eng_PKA_MREM(nregType, 9, lregType, 5, nregType, 7, 1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(nregType, 9, (uint32_t *)pka_tmp, dataSize);
-    MSG("h:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize * 4);
+  Sec_Eng_PKA_Read_Data(nregType, 9, (uint32_t *)pka_tmp, dataSize);
+  MSG("h:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize * 4);
 #endif
 
-    /* h*q */
-    Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
-    Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
-    Sec_Eng_PKA_LMUL(lregType, 5, nregType, 9, nregType, 8, 1);
+  /* h*q */
+  Sec_Eng_PKA_CREG(nregType, 10, dataSize, 1);
+  Sec_Eng_PKA_CREG(nregType, 11, dataSize, 1);
+  Sec_Eng_PKA_LMUL(lregType, 5, nregType, 9, nregType, 8, 1);
 #ifdef DSA_DBG
-    Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)pka_tmp, dataSize * 2);
-    MSG("h*q:\r\n");
-    bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*2*/);
+  Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)pka_tmp, dataSize * 2);
+  MSG("h*q:\r\n");
+  bflb_platform_dump(pka_tmp, dataSize /*dataSize*4*2*/);
 #endif
-    /* m2 + h*q*/
-    Sec_Eng_PKA_LADD(lregType, 5, lregType, 5, nregType, 5, 1);
+  /* m2 + h*q*/
+  Sec_Eng_PKA_LADD(lregType, 5, lregType, 5, nregType, 5, 1);
 
-    Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)r, dataSize * 2);
+  Sec_Eng_PKA_Read_Data(lregType, 5, (uint32_t *)r, dataSize * 2);
 #ifdef DSA_DBG
-    MSG("r:\r\n");
-    bflb_platform_dump(r, dataSize * 4 * 2);
+  MSG("r:\r\n");
+  bflb_platform_dump(r, dataSize * 4 * 2);
 #endif
-    return 0;
+  return 0;
 }
 
-int sec_dsa_init(sec_dsa_handle_t *handle, uint32_t size)
-{
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
+int sec_dsa_init(sec_dsa_handle_t *handle, uint32_t size) {
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
 
-    memset(handle, 0, sizeof(sec_dsa_handle_t));
-    handle->size = size;
-    handle->crtSize = (size >> 1);
+  memset(handle, 0, sizeof(sec_dsa_handle_t));
+  handle->size    = size;
+  handle->crtSize = (size >> 1);
 
-    return 0;
+  return 0;
 }
 
-int sec_dsa_sign(sec_dsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, uint32_t *s)
-{
-    uint32_t dsa_tmp[64] = { 0 };
+int sec_dsa_sign(sec_dsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, uint32_t *s) {
+  uint32_t dsa_tmp[64] = {0};
 
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
 
-    memcpy(dsa_tmp + ((handle->crtSize >> 3) >> 2) - hashLenInWord, hash, hashLenInWord * 4);
+  memcpy(dsa_tmp + ((handle->crtSize >> 3) >> 2) - hashLenInWord, hash, hashLenInWord * 4);
 
-    if (0 == sec_dsa_decrypt_crt(handle->crtSize, dsa_tmp, &handle->crtCfg, handle->d, s)) {
-        return 0;
-    } else {
-        return -1;
-    }
+  if (0 == sec_dsa_decrypt_crt(handle->crtSize, dsa_tmp, &handle->crtCfg, handle->d, s)) {
+    return 0;
+  } else {
+    return -1;
+  }
 }
 
 /**
  */
-int sec_dsa_verify(sec_dsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, const uint32_t *s)
-{
-    uint32_t dsa_tmp[64];
-    uint8_t i = 0;
-    uint8_t resultOffset = 0;
-
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
-
-    if (0 == sec_dsa_mexp_binary(handle->size, s, handle->e, handle->n, dsa_tmp)) {
-        resultOffset = (handle->size >> 5) - hashLenInWord;
-
-        for (i = 0; i < hashLenInWord; i++) {
-            if (dsa_tmp[resultOffset + i] != hash[i]) {
-                return -1;
-            }
-        }
-
-        return 0;
-    } else {
+int sec_dsa_verify(sec_dsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, const uint32_t *s) {
+  uint32_t dsa_tmp[64];
+  uint8_t  i            = 0;
+  uint8_t  resultOffset = 0;
+
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
+
+  if (0 == sec_dsa_mexp_binary(handle->size, s, handle->e, handle->n, dsa_tmp)) {
+    resultOffset = (handle->size >> 5) - hashLenInWord;
+
+    for (i = 0; i < hashLenInWord; i++) {
+      if (dsa_tmp[resultOffset + i] != hash[i]) {
         return -1;
+      }
     }
+
+    return 0;
+  } else {
+    return -1;
+  }
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c
index 8ba150f50..c41b03f8d 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_ecdsa.c
@@ -11,431 +11,332 @@
 /* Used in verify */
 #define ECP_SECP256R1_S_REG_INDEX     5
 #define ECP_SECP256R1_BAR_S_REG_INDEX 6
-#define ECP_SECP256R1_HASH_REG_INDEX  6 //use ECP_SECP256R1_BAR_S_REG_INDEX since it's temp
+#define ECP_SECP256R1_HASH_REG_INDEX  6 // use ECP_SECP256R1_BAR_S_REG_INDEX since it's temp
 #define ECP_SECP256R1_U1_REG_INDEX    7
 #define ECP_SECP256R1_LT_REG_TYPE     SEC_ENG_PKA_REG_SIZE_64
 #define ECP_SECP256R1_LT_REG_INDEX    7
 #define ECP_SECP256R1_SLT_REG_TYPE    SEC_ENG_PKA_REG_SIZE_128
 #define ECP_SECP256R1_SLT_REG_INDEX   3
 
-//#define ECDSA_DBG                                   1
-//#define ECDSA_DBG_DETAIL                            1
+// #define ECDSA_DBG                                   1
+// #define ECDSA_DBG_DETAIL                            1
 
 #define secp256r1
 #define secp256k1
-#define SEC_ECC_POINT_MUL_PARAM_CFG(G) sec_ecc_point_mul_cfg( \
-    (uint32_t *)G##P,                                         \
-    (uint32_t *)G##PrimeN_P,                                  \
-    (uint32_t *)G##_1,                                        \
-    (uint32_t *)G##_BAR2,                                     \
-    (uint32_t *)G##_BAR3,                                     \
-    (uint32_t *)G##_BAR4,                                     \
-    (uint32_t *)G##_BAR8,                                     \
-    (uint32_t *)G##_1P1,                                      \
-    (uint32_t *)G##_1M1)
-
-#define SEC_ECC_BASIC_PARAM_CFG(G) sec_ecc_basic_parameter_cfg( \
-    (uint32_t *)G##N,                                           \
-    (uint32_t *)G##PrimeN_N,                                    \
-    (uint32_t *)G##InvR_N)
+#define SEC_ECC_POINT_MUL_PARAM_CFG(G)                                                                                                                                                                 \
+  sec_ecc_point_mul_cfg((uint32_t *)G##P, (uint32_t *)G##PrimeN_P, (uint32_t *)G##_1, (uint32_t *)G##_BAR2, (uint32_t *)G##_BAR3, (uint32_t *)G##_BAR4, (uint32_t *)G##_BAR8, (uint32_t *)G##_1P1,     \
+                        (uint32_t *)G##_1M1)
+
+#define SEC_ECC_BASIC_PARAM_CFG(G) sec_ecc_basic_parameter_cfg((uint32_t *)G##N, (uint32_t *)G##PrimeN_N, (uint32_t *)G##InvR_N)
 
 void bflb_platform_dump(uint8_t *data, uint32_t len);
 
 #if (defined(ECDSA_DBG) || defined(ECDSA_DBG_DETAIL))
-uint32_t pka_tmp[32] = { 0 };
+uint32_t pka_tmp[32] = {0};
 #endif
 /********************************************** secp256r1 *******************************************/
-const uint8_t secp256r1P[32] ALIGN4 = {
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
-};
-const uint8_t secp256r1B[32] ALIGN4 = {
-    0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc,
-    0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b
-};
-const uint8_t secp256r1Gx[32] ALIGN4 = {
-    0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2,
-    0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96
-};
-const uint8_t secp256r1Gy[32] ALIGN4 = {
-    0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16,
-    0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5
-};
-const uint8_t secp256r1N[32] ALIGN4 = {
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51
-};
-const uint8_t secp256r1PrimeN_N[32] ALIGN4 = {
-    0x60, 0xd0, 0x66, 0x33, 0xa9, 0xd6, 0x28, 0x1c, 0x50, 0xfe, 0x77, 0xec, 0xc5, 0x88, 0xc6, 0xf6,
-    0x48, 0xc9, 0x44, 0x08, 0x7d, 0x74, 0xd2, 0xe4, 0xcc, 0xd1, 0xc8, 0xaa, 0xee, 0x00, 0xbc, 0x4f
-};
-const uint8_t secp256r1InvR_N[32] ALIGN4 = {
-    0x60, 0xd0, 0x66, 0x33, 0x49, 0x05, 0xc1, 0xe9, 0x07, 0xf8, 0xb6, 0x04, 0x1e, 0x60, 0x77, 0x25,
-    0xba, 0xde, 0xf3, 0xe2, 0x43, 0x56, 0x6f, 0xaf, 0xce, 0x1b, 0xc8, 0xf7, 0x9c, 0x19, 0x7c, 0x79
-};
-const uint8_t secp256r1PrimeN_P[32] ALIGN4 = {
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
-};
-const uint8_t secp256r1InvR_P[32] ALIGN4 = {
-    0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x02,
-    0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00
-};
-const uint8_t secp256r1_1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
-};
-const uint8_t secp256r1_BAR2[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02
-};
-const uint8_t secp256r1_BAR3[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x02, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03
-};
-const uint8_t secp256r1_BAR4[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04
-};
-const uint8_t secp256r1_BAR8[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08
-};
-const uint8_t secp256r1_1P1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02
-};
-const uint8_t secp256r1_1M1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
-};
-const uint8_t secp256r1_Zerox[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
-};
-const uint8_t secp256r1_Zeroy[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
-    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
-};
-const uint8_t secp256r1_Gx[32] ALIGN4 = {
-    0x18, 0x90, 0x5f, 0x76, 0xa5, 0x37, 0x55, 0xc6, 0x79, 0xfb, 0x73, 0x2b, 0x77, 0x62, 0x25, 0x10,
-    0x75, 0xba, 0x95, 0xfc, 0x5f, 0xed, 0xb6, 0x01, 0x79, 0xe7, 0x30, 0xd4, 0x18, 0xa9, 0x14, 0x3c
-};
-const uint8_t secp256r1_Gy[32] ALIGN4 = {
-    0x85, 0x71, 0xff, 0x18, 0x25, 0x88, 0x5d, 0x85, 0xd2, 0xe8, 0x86, 0x88, 0xdd, 0x21, 0xf3, 0x25,
-    0x8b, 0x4a, 0xb8, 0xe4, 0xba, 0x19, 0xe4, 0x5c, 0xdd, 0xf2, 0x53, 0x57, 0xce, 0x95, 0x56, 0x0a
-};
+const uint8_t secp256r1P[32] ALIGN4        = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
+const uint8_t secp256r1B[32] ALIGN4        = {0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc,
+                                              0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b};
+const uint8_t secp256r1Gx[32] ALIGN4       = {0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2,
+                                              0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96};
+const uint8_t secp256r1Gy[32] ALIGN4       = {0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16,
+                                              0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5};
+const uint8_t secp256r1N[32] ALIGN4        = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+                                              0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51};
+const uint8_t secp256r1PrimeN_N[32] ALIGN4 = {0x60, 0xd0, 0x66, 0x33, 0xa9, 0xd6, 0x28, 0x1c, 0x50, 0xfe, 0x77, 0xec, 0xc5, 0x88, 0xc6, 0xf6,
+                                              0x48, 0xc9, 0x44, 0x08, 0x7d, 0x74, 0xd2, 0xe4, 0xcc, 0xd1, 0xc8, 0xaa, 0xee, 0x00, 0xbc, 0x4f};
+const uint8_t secp256r1InvR_N[32] ALIGN4   = {0x60, 0xd0, 0x66, 0x33, 0x49, 0x05, 0xc1, 0xe9, 0x07, 0xf8, 0xb6, 0x04, 0x1e, 0x60, 0x77, 0x25,
+                                              0xba, 0xde, 0xf3, 0xe2, 0x43, 0x56, 0x6f, 0xaf, 0xce, 0x1b, 0xc8, 0xf7, 0x9c, 0x19, 0x7c, 0x79};
+const uint8_t secp256r1PrimeN_P[32] ALIGN4 = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+const uint8_t secp256r1InvR_P[32] ALIGN4   = {0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x02,
+                                              0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00};
+const uint8_t secp256r1_1[32] ALIGN4       = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+const uint8_t secp256r1_BAR2[32] ALIGN4    = {0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+                                              0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02};
+const uint8_t secp256r1_BAR3[32] ALIGN4    = {0x00, 0x00, 0x00, 0x02, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+                                              0xff, 0xff, 0xff, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03};
+const uint8_t secp256r1_BAR4[32] ALIGN4    = {0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+                                              0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04};
+const uint8_t secp256r1_BAR8[32] ALIGN4    = {0x00, 0x00, 0x00, 0x07, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+                                              0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08};
+const uint8_t secp256r1_1P1[32] ALIGN4     = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+                                              0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02};
+const uint8_t secp256r1_1M1[32] ALIGN4     = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+                                              0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+const uint8_t secp256r1_Zerox[32] ALIGN4   = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+const uint8_t secp256r1_Zeroy[32] ALIGN4   = {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+                                              0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+const uint8_t secp256r1_Gx[32] ALIGN4      = {0x18, 0x90, 0x5f, 0x76, 0xa5, 0x37, 0x55, 0xc6, 0x79, 0xfb, 0x73, 0x2b, 0x77, 0x62, 0x25, 0x10,
+                                              0x75, 0xba, 0x95, 0xfc, 0x5f, 0xed, 0xb6, 0x01, 0x79, 0xe7, 0x30, 0xd4, 0x18, 0xa9, 0x14, 0x3c};
+const uint8_t secp256r1_Gy[32] ALIGN4      = {0x85, 0x71, 0xff, 0x18, 0x25, 0x88, 0x5d, 0x85, 0xd2, 0xe8, 0x86, 0x88, 0xdd, 0x21, 0xf3, 0x25,
+                                              0x8b, 0x4a, 0xb8, 0xe4, 0xba, 0x19, 0xe4, 0x5c, 0xdd, 0xf2, 0x53, 0x57, 0xce, 0x95, 0x56, 0x0a};
 
 /********************************************** secp256k1 *******************************************/
-const uint8_t secp256k1P[32] ALIGN4 = {
-    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
-    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F
-};
-const uint8_t secp256k1B[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07
-};
-const uint8_t secp256k1Gx[32] ALIGN4 = {
-    0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, 0x07,
-    0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, 0x98
-};
-const uint8_t secp256k1Gy[32] ALIGN4 = {
-    0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16,
-    0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5
-};
-const uint8_t secp256k1N[32] ALIGN4 = {
-    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
-    0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41
-};
-const uint8_t secp256k1PrimeN_N[32] ALIGN4 = {
-    0xd9, 0xe8, 0x89, 0xd, 0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5e,
-    0x50, 0xa5, 0x1a, 0xc8, 0x34, 0xb9, 0xec, 0x24, 0x4b, 0xd, 0xff, 0x66, 0x55, 0x88, 0xb1, 0x3f
-};
-const uint8_t secp256k1InvR_N[32] ALIGN4 = {
-    0xd9, 0xe8, 0x89, 0xd, 0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5d,
-    0x3b, 0xbb, 0xd4, 0x56, 0x7f, 0xa5, 0xc, 0x3c, 0x80, 0xfd, 0x22, 0x93, 0x80, 0x97, 0xc0, 0x16
-};
-const uint8_t secp256k1PrimeN_P[32] ALIGN4 = {
-    0xc9, 0xbd, 0x19, 0x5, 0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61,
-    0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9, 0x1d, 0xd2, 0x25, 0x35, 0x31
-};
-const uint8_t secp256k1InvR_P[32] ALIGN4 = {
-    0xc9, 0xbd, 0x19, 0x5, 0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61,
-    0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9, 0x1d, 0x8, 0x68, 0x19, 0x2a
-};
-const uint8_t secp256k1_1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
-};
-const uint8_t secp256k1_BAR2[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x07, 0xa2
-};
-const uint8_t secp256k1_BAR3[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x0b, 0x73
-};
-const uint8_t secp256k1_BAR4[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x0f, 0x44
-};
-const uint8_t secp256k1_BAR8[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x1e, 0x88
-};
-const uint8_t secp256k1_1P1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd2
-};
-const uint8_t secp256k1_1M1[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd0
-};
-const uint8_t secp256k1_Zerox[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
-};
-const uint8_t secp256k1_Zeroy[32] ALIGN4 = {
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd1
-};
-const uint8_t secp256k1_Gx[32] ALIGN4 = {
-    0x99, 0x81, 0xe6, 0x43, 0xe9, 0x08, 0x9f, 0x48, 0x97, 0x9f, 0x48, 0xc0, 0x33, 0xfd, 0x12, 0x9c,
-    0x23, 0x1e, 0x29, 0x53, 0x29, 0xbc, 0x66, 0xdb, 0xd7, 0x36, 0x2e, 0x5a, 0x48, 0x7e, 0x20, 0x97
-};
-const uint8_t secp256k1_Gy[32] ALIGN4 = {
-    0xcf, 0x3f, 0x85, 0x1f, 0xd4, 0xa5, 0x82, 0xd6, 0x70, 0xb6, 0xb5, 0x9a, 0xac, 0x19, 0xc1, 0x36,
-    0x8d, 0xfc, 0x5d, 0x5d, 0x1f, 0x1d, 0xc6, 0x4d, 0xb1, 0x5e, 0xa6, 0xd2, 0xd3, 0xdb, 0xab, 0xe2
-};
-
-static BL_Err_Type sec_ecc_basic_parameter_cfg(uint32_t *n, uint32_t *prime_n, uint32_t *invr_n)
-{
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)n, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_NPRIME_N_REG_INDEX, (uint32_t *)prime_n, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX, (uint32_t *)invr_n, ECP_SECP256R1_SIZE / 4, 0);
-    return SUCCESS;
+const uint8_t secp256k1P[32] ALIGN4        = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+                                              0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F};
+const uint8_t secp256k1B[32] ALIGN4        = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07};
+const uint8_t secp256k1Gx[32] ALIGN4       = {0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, 0x07,
+                                              0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, 0x98};
+const uint8_t secp256k1Gy[32] ALIGN4       = {0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16,
+                                              0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5};
+const uint8_t secp256k1N[32] ALIGN4        = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
+                                              0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41};
+const uint8_t secp256k1PrimeN_N[32] ALIGN4 = {0xd9, 0xe8, 0x89, 0xd,  0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5e,
+                                              0x50, 0xa5, 0x1a, 0xc8, 0x34, 0xb9, 0xec, 0x24, 0x4b, 0xd,  0xff, 0x66, 0x55, 0x88, 0xb1, 0x3f};
+const uint8_t secp256k1InvR_N[32] ALIGN4   = {0xd9, 0xe8, 0x89, 0xd,  0x64, 0x94, 0xef, 0x93, 0x89, 0x7f, 0x30, 0xc1, 0x27, 0xcf, 0xab, 0x5d,
+                                              0x3b, 0xbb, 0xd4, 0x56, 0x7f, 0xa5, 0xc,  0x3c, 0x80, 0xfd, 0x22, 0x93, 0x80, 0x97, 0xc0, 0x16};
+const uint8_t secp256k1PrimeN_P[32] ALIGN4 = {0xc9, 0xbd, 0x19, 0x5,  0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61,
+                                              0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9,  0x1d, 0xd2, 0x25, 0x35, 0x31};
+const uint8_t secp256k1InvR_P[32] ALIGN4   = {0xc9, 0xbd, 0x19, 0x5,  0x15, 0x53, 0x83, 0x99, 0x9c, 0x46, 0xc2, 0xc2, 0x95, 0xf2, 0xb7, 0x61,
+                                              0xbc, 0xb2, 0x23, 0xfe, 0xdc, 0x24, 0xa0, 0x59, 0xd8, 0x38, 0x9,  0x1d, 0x8,  0x68, 0x19, 0x2a};
+const uint8_t secp256k1_1[32] ALIGN4       = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+const uint8_t secp256k1_BAR2[32] ALIGN4    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x07, 0xa2};
+const uint8_t secp256k1_BAR3[32] ALIGN4    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x0b, 0x73};
+const uint8_t secp256k1_BAR4[32] ALIGN4    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x0f, 0x44};
+const uint8_t secp256k1_BAR8[32] ALIGN4    = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x1e, 0x88};
+const uint8_t secp256k1_1P1[32] ALIGN4     = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd2};
+const uint8_t secp256k1_1M1[32] ALIGN4     = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd0};
+const uint8_t secp256k1_Zerox[32] ALIGN4   = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+const uint8_t secp256k1_Zeroy[32] ALIGN4   = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xd1};
+const uint8_t secp256k1_Gx[32] ALIGN4      = {0x99, 0x81, 0xe6, 0x43, 0xe9, 0x08, 0x9f, 0x48, 0x97, 0x9f, 0x48, 0xc0, 0x33, 0xfd, 0x12, 0x9c,
+                                              0x23, 0x1e, 0x29, 0x53, 0x29, 0xbc, 0x66, 0xdb, 0xd7, 0x36, 0x2e, 0x5a, 0x48, 0x7e, 0x20, 0x97};
+const uint8_t secp256k1_Gy[32] ALIGN4      = {0xcf, 0x3f, 0x85, 0x1f, 0xd4, 0xa5, 0x82, 0xd6, 0x70, 0xb6, 0xb5, 0x9a, 0xac, 0x19, 0xc1, 0x36,
+                                              0x8d, 0xfc, 0x5d, 0x5d, 0x1f, 0x1d, 0xc6, 0x4d, 0xb1, 0x5e, 0xa6, 0xd2, 0xd3, 0xdb, 0xab, 0xe2};
+
+static BL_Err_Type sec_ecc_basic_parameter_cfg(uint32_t *n, uint32_t *prime_n, uint32_t *invr_n) {
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)n, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_NPRIME_N_REG_INDEX, (uint32_t *)prime_n, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX, (uint32_t *)invr_n, ECP_SECP256R1_SIZE / 4, 0);
+  return SUCCESS;
 }
-static BL_Err_Type sec_ecc_basic_parameter_init(uint8_t id)
-{
-    if (id >= ECP_TYPE_MAX) {
-        return ERROR;
-    }
-
-    if (id == ECP_SECP256R1) {
-        SEC_ECC_BASIC_PARAM_CFG(secp256r1);
-    } else if (id == ECP_SECP256K1) {
-        SEC_ECC_BASIC_PARAM_CFG(secp256k1);
-    }
-
-    return SUCCESS;
+static BL_Err_Type sec_ecc_basic_parameter_init(uint8_t id) {
+  if (id >= ECP_TYPE_MAX) {
+    return ERROR;
+  }
+
+  if (id == ECP_SECP256R1) {
+    SEC_ECC_BASIC_PARAM_CFG(secp256r1);
+  } else if (id == ECP_SECP256K1) {
+    SEC_ECC_BASIC_PARAM_CFG(secp256k1);
+  }
+
+  return SUCCESS;
 }
 
-static BL_Err_Type sec_ecc_point_mul_cfg(uint32_t *p, uint32_t *primeN_p, uint32_t *ori_1, uint32_t *bar2,
-                                         uint32_t *bar3, uint32_t *bar4, uint32_t *bar8, uint32_t *bar1p1, uint32_t *bar1m1)
-{
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)p, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 1, (uint32_t *)primeN_p, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 8, (uint32_t *)ori_1, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 9, (uint32_t *)bar2, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 10, (uint32_t *)bar3, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 11, (uint32_t *)bar4, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 12, (uint32_t *)bar8, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 19, (uint32_t *)bar1p1, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 20, (uint32_t *)bar1m1, ECP_SECP256R1_SIZE / 4, 0);
-
-    return SUCCESS;
+static BL_Err_Type sec_ecc_point_mul_cfg(uint32_t *p, uint32_t *primeN_p, uint32_t *ori_1, uint32_t *bar2, uint32_t *bar3, uint32_t *bar4, uint32_t *bar8, uint32_t *bar1p1, uint32_t *bar1m1) {
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)p, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 1, (uint32_t *)primeN_p, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 8, (uint32_t *)ori_1, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 9, (uint32_t *)bar2, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 10, (uint32_t *)bar3, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 11, (uint32_t *)bar4, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 12, (uint32_t *)bar8, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 19, (uint32_t *)bar1p1, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 20, (uint32_t *)bar1m1, ECP_SECP256R1_SIZE / 4, 0);
+
+  return SUCCESS;
 }
 
-static int sec_ecc_point_mul_init(uint8_t id)
-{
-    if (id >= ECP_TYPE_MAX) {
-        return ERROR;
-    }
+static int sec_ecc_point_mul_init(uint8_t id) {
+  if (id >= ECP_TYPE_MAX) {
+    return ERROR;
+  }
 
-    if (id == ECP_SECP256R1) {
-        SEC_ECC_POINT_MUL_PARAM_CFG(secp256r1);
-    } else if (id == ECP_SECP256K1) {
-        SEC_ECC_POINT_MUL_PARAM_CFG(secp256k1);
-    }
+  if (id == ECP_SECP256R1) {
+    SEC_ECC_POINT_MUL_PARAM_CFG(secp256r1);
+  } else if (id == ECP_SECP256K1) {
+    SEC_ECC_POINT_MUL_PARAM_CFG(secp256k1);
+  }
 
-    return SUCCESS;
+  return SUCCESS;
 }
 
-static void sec_ecdsa_point_add_inf_check(uint8_t *pka_p1_eq_inf, uint8_t *pka_p2_eq_inf)
-{
-    uint8_t res[4];
-
-    /* index 2:BAR_Zero_x
-     * index 3:BAR_Zero_y
-     * index 4:BAR_Zero_z
-     * index 5:BAR_G_x
-     * index 6:BAR_G_y
-     * index 7:BAR_G_z
-     * index 8:1
-     * index 9:2
-     * index 10:3
-     * index 11:4
-     * index 12:8
-     * index 19:1P1
-     * index 20:1m1*/
-
-    //cout = 1 if X1 = 0
-    Sec_Eng_PKA_LCMP(res, 3, 2, 3, 8); //s0 < s1 => cout = 1
-    //cout = 1 if Y1 < Bar_1p1
-    Sec_Eng_PKA_LCMP(res + 1, 3, 3, 3, 19);
-    //cout=1 if Y1 > Bar_1m1
-    Sec_Eng_PKA_LCMP(res + 2, 3, 20, 3, 3);
-    //cout =1 if Z1 = 0
-    Sec_Eng_PKA_LCMP(res + 3, 3, 4, 3, 8);
-    *pka_p1_eq_inf = res[0] & res[1] & res[2] & res[3];
-
-    //cout = 1 if X2 = 0
-    Sec_Eng_PKA_LCMP(res, 3, 5, 3, 8);
-    // cout = 1 if Y2 < Bar_1p1
-    Sec_Eng_PKA_LCMP(res + 1, 3, 6, 3, 19);
-    //cout = 1 if Y2 > Bar_1m1
-    Sec_Eng_PKA_LCMP(res + 2, 3, 20, 3, 6);
-    //cout = 1 if Z2 = 0
-    Sec_Eng_PKA_LCMP(res + 3, 3, 7, 3, 8);
-    *pka_p2_eq_inf = res[0] & res[1] & res[2] & res[3];
+static void sec_ecdsa_point_add_inf_check(uint8_t *pka_p1_eq_inf, uint8_t *pka_p2_eq_inf) {
+  uint8_t res[4];
+
+  /* index 2:BAR_Zero_x
+   * index 3:BAR_Zero_y
+   * index 4:BAR_Zero_z
+   * index 5:BAR_G_x
+   * index 6:BAR_G_y
+   * index 7:BAR_G_z
+   * index 8:1
+   * index 9:2
+   * index 10:3
+   * index 11:4
+   * index 12:8
+   * index 19:1P1
+   * index 20:1m1*/
+
+  // cout = 1 if X1 = 0
+  Sec_Eng_PKA_LCMP(res, 3, 2, 3, 8); // s0 < s1 => cout = 1
+  // cout = 1 if Y1 < Bar_1p1
+  Sec_Eng_PKA_LCMP(res + 1, 3, 3, 3, 19);
+  // cout=1 if Y1 > Bar_1m1
+  Sec_Eng_PKA_LCMP(res + 2, 3, 20, 3, 3);
+  // cout =1 if Z1 = 0
+  Sec_Eng_PKA_LCMP(res + 3, 3, 4, 3, 8);
+  *pka_p1_eq_inf = res[0] & res[1] & res[2] & res[3];
+
+  // cout = 1 if X2 = 0
+  Sec_Eng_PKA_LCMP(res, 3, 5, 3, 8);
+  // cout = 1 if Y2 < Bar_1p1
+  Sec_Eng_PKA_LCMP(res + 1, 3, 6, 3, 19);
+  // cout = 1 if Y2 > Bar_1m1
+  Sec_Eng_PKA_LCMP(res + 2, 3, 20, 3, 6);
+  // cout = 1 if Z2 = 0
+  Sec_Eng_PKA_LCMP(res + 3, 3, 7, 3, 8);
+  *pka_p2_eq_inf = res[0] & res[1] & res[2] & res[3];
 }
 
-static void sec_ecdsa_copy_x2_to_x1(uint8_t id)
-{
-    //X2->X1
-    Sec_Eng_PKA_Move_Data(3, 2, 3, 5, 0);
-    //Y2->Y1
-    Sec_Eng_PKA_Move_Data(3, 3, 3, 6, 0);
-    //Z2->Z1
-    Sec_Eng_PKA_Move_Data(3, 4, 3, 7, 1); //Caution!!! wait movdat ready to execute next command
+static void sec_ecdsa_copy_x2_to_x1(uint8_t id) {
+  // X2->X1
+  Sec_Eng_PKA_Move_Data(3, 2, 3, 5, 0);
+  // Y2->Y1
+  Sec_Eng_PKA_Move_Data(3, 3, 3, 6, 0);
+  // Z2->Z1
+  Sec_Eng_PKA_Move_Data(3, 4, 3, 7, 1); // Caution!!! wait movdat ready to execute next command
 }
 
-static void sec_ecdsa_point_add(uint8_t id)
-{
-    /* index 2:BAR_Zero_x
-     * index 3:BAR_Zero_y
-     * index 4:BAR_Zero_z
-     * index 5:BAR_G_x
-     * index 6:BAR_G_y
-     * index 7:BAR_G_z
-     * index 8:1
-     * index 9:2
-     * index 10:3
-     * index 11:4
-     * index 12:8
-     * index 19:1P1
-     * index 20:1m1*/
-
-    //U1 = Y2*Z1
-    //PKA_MMUL(0,3,13,3, 6,3, 4,3,0);//d_reg_type,d_reg_idx,s0_reg_type,s0_reg_idx,s1_reg_type,s1_reg_idx,s2_reg_type,s2_reg_idx
-    Sec_Eng_PKA_MMUL(3, 13, 3, 6, 3, 4, 3, 0, 0);
-
-    //U2 = Y1*Z2
-    //PKA_MMUL(0,3,14,3, 3,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 14, 3, 3, 3, 7, 3, 0, 0);
-
-    //V1 = X2*Z1
-    //PKA_MMUL(0,3,15,3, 5,3, 4,3,0);
-    Sec_Eng_PKA_MMUL(3, 15, 3, 5, 3, 4, 3, 0, 0);
-
-    //V2 = X1*Z2
-    //PKA_MMUL(0,3,16,3, 2,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 16, 3, 2, 3, 7, 3, 0, 0);
-
-    //U = U1-U2
-    //PKA_MSUB(0,3,13,3,13,3,14,3,0);
-    Sec_Eng_PKA_MSUB(3, 13, 3, 13, 3, 14, 3, 0, 0);
-
-    //V = V1-V2
-    //PKA_MSUB(0,3,15,3,15,3,16,3,0);
-    Sec_Eng_PKA_MSUB(3, 15, 3, 15, 3, 16, 3, 0, 0);
-
-    //W = Z1*Z2
-    //PKA_MMUL(0,3, 2,3, 4,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 2, 3, 4, 3, 7, 3, 0, 0);
-
-    //V^2
-    //PKA_MMUL(0,3, 3,3,15,3,15,3,0);
-    Sec_Eng_PKA_MMUL(3, 3, 3, 15, 3, 15, 3, 0, 0);
-
-    //V^3
-    //PKA_MMUL(0,3, 4,3, 3,3,15,3,0);
-    Sec_Eng_PKA_MMUL(3, 4, 3, 3, 3, 15, 3, 0, 0);
-
-    //U^2
-    //PKA_MMUL(0,3,17,3,13,3,13,3,0);
-    Sec_Eng_PKA_MMUL(3, 17, 3, 13, 3, 13, 3, 0, 0);
-
-    //U^2*W
-    //PKA_MMUL(0,3,17,3,17,3, 2,3,0);
-    Sec_Eng_PKA_MMUL(3, 17, 3, 17, 3, 2, 3, 0, 0);
-
-    //U^2*W-V^3
-    //PKA_MSUB(0,3,17,3,17,3, 4,3,0);
-    Sec_Eng_PKA_MSUB(3, 17, 3, 17, 3, 4, 3, 0, 0);
-
-    //2*V^2
-    //PKA_MMUL(0,3,18,3, 9,3, 3,3,0);
-    Sec_Eng_PKA_MMUL(3, 18, 3, 9, 3, 3, 3, 0, 0);
-
-    //2*V^2*V2
-    //PKA_MMUL(0,3,18,3,18,3,16,3,0);
-    Sec_Eng_PKA_MMUL(3, 18, 3, 18, 3, 16, 3, 0, 0);
-
-    //A = U^2*W-V^3-2*V^2*V2
-    //PKA_MSUB(0,3,18,3,17,3,18,3,0);
-    Sec_Eng_PKA_MSUB(3, 18, 3, 17, 3, 18, 3, 0, 0);
-
-    //V^2*V2
-    //PKA_MMUL(0,3, 3,3, 3,3,16,3,0);
-    Sec_Eng_PKA_MMUL(3, 3, 3, 3, 3, 16, 3, 0, 0);
-
-    //V^3*U2
-    //PKA_MMUL(0,3,14,3, 4,3,14,3,0);
-    Sec_Eng_PKA_MMUL(3, 14, 3, 4, 3, 14, 3, 0, 0);
-
-    //Z3 = V^3*W
-    //PKA_MMUL(0,3, 4,3, 4,3, 2,3,0);
-    Sec_Eng_PKA_MMUL(3, 4, 3, 4, 3, 2, 3, 0, 0);
-
-    //X3 = V*A
-    //PKA_MMUL(0,3, 2,3,15,3,18,3,0);
-    Sec_Eng_PKA_MMUL(3, 2, 3, 15, 3, 18, 3, 0, 0);
-
-    //V^2*V2-A
-    //PKA_MSUB(0,3, 3,3, 3,3,18,3,0);
-    Sec_Eng_PKA_MSUB(3, 3, 3, 3, 3, 18, 3, 0, 0);
-
-    //U*(V^2*V2-A)
-    //PKA_MMUL(0,3, 3,3,13,3, 3,3,0);
-    Sec_Eng_PKA_MMUL(3, 3, 3, 13, 3, 3, 3, 0, 0);
-
-    //Y3 = U*(V^2*V2-A)-V^3*U2
-    //PKA_MSUB(1,3, 3,3, 3,3,14,3,0);
-    Sec_Eng_PKA_MSUB(3, 3, 3, 3, 3, 14, 3, 0, 1);
+static void sec_ecdsa_point_add(uint8_t id) {
+  /* index 2:BAR_Zero_x
+   * index 3:BAR_Zero_y
+   * index 4:BAR_Zero_z
+   * index 5:BAR_G_x
+   * index 6:BAR_G_y
+   * index 7:BAR_G_z
+   * index 8:1
+   * index 9:2
+   * index 10:3
+   * index 11:4
+   * index 12:8
+   * index 19:1P1
+   * index 20:1m1*/
+
+  // U1 = Y2*Z1
+  // PKA_MMUL(0,3,13,3, 6,3, 4,3,0);//d_reg_type,d_reg_idx,s0_reg_type,s0_reg_idx,s1_reg_type,s1_reg_idx,s2_reg_type,s2_reg_idx
+  Sec_Eng_PKA_MMUL(3, 13, 3, 6, 3, 4, 3, 0, 0);
+
+  // U2 = Y1*Z2
+  // PKA_MMUL(0,3,14,3, 3,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 14, 3, 3, 3, 7, 3, 0, 0);
+
+  // V1 = X2*Z1
+  // PKA_MMUL(0,3,15,3, 5,3, 4,3,0);
+  Sec_Eng_PKA_MMUL(3, 15, 3, 5, 3, 4, 3, 0, 0);
+
+  // V2 = X1*Z2
+  // PKA_MMUL(0,3,16,3, 2,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 16, 3, 2, 3, 7, 3, 0, 0);
+
+  // U = U1-U2
+  // PKA_MSUB(0,3,13,3,13,3,14,3,0);
+  Sec_Eng_PKA_MSUB(3, 13, 3, 13, 3, 14, 3, 0, 0);
+
+  // V = V1-V2
+  // PKA_MSUB(0,3,15,3,15,3,16,3,0);
+  Sec_Eng_PKA_MSUB(3, 15, 3, 15, 3, 16, 3, 0, 0);
+
+  // W = Z1*Z2
+  // PKA_MMUL(0,3, 2,3, 4,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 2, 3, 4, 3, 7, 3, 0, 0);
+
+  // V^2
+  // PKA_MMUL(0,3, 3,3,15,3,15,3,0);
+  Sec_Eng_PKA_MMUL(3, 3, 3, 15, 3, 15, 3, 0, 0);
+
+  // V^3
+  // PKA_MMUL(0,3, 4,3, 3,3,15,3,0);
+  Sec_Eng_PKA_MMUL(3, 4, 3, 3, 3, 15, 3, 0, 0);
+
+  // U^2
+  // PKA_MMUL(0,3,17,3,13,3,13,3,0);
+  Sec_Eng_PKA_MMUL(3, 17, 3, 13, 3, 13, 3, 0, 0);
+
+  // U^2*W
+  // PKA_MMUL(0,3,17,3,17,3, 2,3,0);
+  Sec_Eng_PKA_MMUL(3, 17, 3, 17, 3, 2, 3, 0, 0);
+
+  // U^2*W-V^3
+  // PKA_MSUB(0,3,17,3,17,3, 4,3,0);
+  Sec_Eng_PKA_MSUB(3, 17, 3, 17, 3, 4, 3, 0, 0);
+
+  // 2*V^2
+  // PKA_MMUL(0,3,18,3, 9,3, 3,3,0);
+  Sec_Eng_PKA_MMUL(3, 18, 3, 9, 3, 3, 3, 0, 0);
+
+  // 2*V^2*V2
+  // PKA_MMUL(0,3,18,3,18,3,16,3,0);
+  Sec_Eng_PKA_MMUL(3, 18, 3, 18, 3, 16, 3, 0, 0);
+
+  // A = U^2*W-V^3-2*V^2*V2
+  // PKA_MSUB(0,3,18,3,17,3,18,3,0);
+  Sec_Eng_PKA_MSUB(3, 18, 3, 17, 3, 18, 3, 0, 0);
+
+  // V^2*V2
+  // PKA_MMUL(0,3, 3,3, 3,3,16,3,0);
+  Sec_Eng_PKA_MMUL(3, 3, 3, 3, 3, 16, 3, 0, 0);
+
+  // V^3*U2
+  // PKA_MMUL(0,3,14,3, 4,3,14,3,0);
+  Sec_Eng_PKA_MMUL(3, 14, 3, 4, 3, 14, 3, 0, 0);
+
+  // Z3 = V^3*W
+  // PKA_MMUL(0,3, 4,3, 4,3, 2,3,0);
+  Sec_Eng_PKA_MMUL(3, 4, 3, 4, 3, 2, 3, 0, 0);
+
+  // X3 = V*A
+  // PKA_MMUL(0,3, 2,3,15,3,18,3,0);
+  Sec_Eng_PKA_MMUL(3, 2, 3, 15, 3, 18, 3, 0, 0);
+
+  // V^2*V2-A
+  // PKA_MSUB(0,3, 3,3, 3,3,18,3,0);
+  Sec_Eng_PKA_MSUB(3, 3, 3, 3, 3, 18, 3, 0, 0);
+
+  // U*(V^2*V2-A)
+  // PKA_MMUL(0,3, 3,3,13,3, 3,3,0);
+  Sec_Eng_PKA_MMUL(3, 3, 3, 13, 3, 3, 3, 0, 0);
+
+  // Y3 = U*(V^2*V2-A)-V^3*U2
+  // PKA_MSUB(1,3, 3,3, 3,3,14,3,0);
+  Sec_Eng_PKA_MSUB(3, 3, 3, 3, 3, 14, 3, 0, 1);
 }
 /**
  * @brief calculate secp256r1's W
  *
  * @note index 13:W = 3X^2-3Z^2
  */
-static void sec_ecdsa_cal_secp256r1_w(void)
-{
-    //X1^2
-    //PKA_MMUL(0,3,13,3, 5,3, 5,3,0);//d_reg_type,d_reg_idx,s0_reg_type,s0_reg_idx,s1_reg_type,s1_reg_idx,s2_reg_type,s2_reg_idx
-    Sec_Eng_PKA_MMUL(3, 13, 3, 5, 3, 5, 3, 0, 0);
-
-    //Z1^2
-    //PKA_MMUL(0,3,14,3, 7,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 14, 3, 7, 3, 7, 3, 0, 0);
-
-    //X1^2-Z1^2
-    //PKA_MSUB(0,3,13,3,13,3,14,3,0);
-    Sec_Eng_PKA_MSUB(3, 13, 3, 13, 3, 14, 3, 0, 0);
-
-    //W = 3*(X1^2-Z1^2)
-    //PKA_MMUL(0,3,13,3,10,3,13,3,0);
-    Sec_Eng_PKA_MMUL(3, 13, 3, 10, 3, 13, 3, 0, 0);
+static void sec_ecdsa_cal_secp256r1_w(void) {
+  // X1^2
+  // PKA_MMUL(0,3,13,3, 5,3, 5,3,0);//d_reg_type,d_reg_idx,s0_reg_type,s0_reg_idx,s1_reg_type,s1_reg_idx,s2_reg_type,s2_reg_idx
+  Sec_Eng_PKA_MMUL(3, 13, 3, 5, 3, 5, 3, 0, 0);
+
+  // Z1^2
+  // PKA_MMUL(0,3,14,3, 7,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 14, 3, 7, 3, 7, 3, 0, 0);
+
+  // X1^2-Z1^2
+  // PKA_MSUB(0,3,13,3,13,3,14,3,0);
+  Sec_Eng_PKA_MSUB(3, 13, 3, 13, 3, 14, 3, 0, 0);
+
+  // W = 3*(X1^2-Z1^2)
+  // PKA_MMUL(0,3,13,3,10,3,13,3,0);
+  Sec_Eng_PKA_MMUL(3, 13, 3, 10, 3, 13, 3, 0, 0);
 }
 
 /**
@@ -443,1008 +344,955 @@ static void sec_ecdsa_cal_secp256r1_w(void)
  *
  * @note index 13:W = 3X^2
  */
-static void sec_ecdsa_cal_secp256k1_w(void)
-{
-    //X1^2
-    Sec_Eng_PKA_MMUL(3, 13, 3, 5, 3, 5, 3, 0, 0);
+static void sec_ecdsa_cal_secp256k1_w(void) {
+  // X1^2
+  Sec_Eng_PKA_MMUL(3, 13, 3, 5, 3, 5, 3, 0, 0);
 
-    //W = 3* (X1^2)
-    Sec_Eng_PKA_MMUL(3, 13, 3, 10, 3, 13, 3, 0, 0);
+  // W = 3* (X1^2)
+  Sec_Eng_PKA_MMUL(3, 13, 3, 10, 3, 13, 3, 0, 0);
 }
 
-static BL_Err_Type sec_ecdsa_point_double(sec_ecp_type id)
-{
-    /* index 2:BAR_Zero_x
-     * index 3:BAR_Zero_y
-     * index 4:BAR_Zero_z
-     * index 5:BAR_G_x
-     * index 6:BAR_G_y
-     * index 7:BAR_G_z
-     * index 8:1
-     * index 9:2
-     * index 10:3
-     * index 11:4
-     * index 12:8
-     * index 19:1P1
-     * index 20:1m1*/
-
-    if (id >= ECP_TYPE_MAX) {
-        return ERROR;
-    }
-
-    if (id == ECP_SECP256R1) {
-        sec_ecdsa_cal_secp256r1_w();
-    } else if (id == ECP_SECP256K1) {
-        sec_ecdsa_cal_secp256k1_w();
-    }
-
-    //S = Y1*Z1
-    //PKA_MMUL(0,3,14,3, 6,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 14, 3, 6, 3, 7, 3, 0, 0);
-
-    //X1*Y1
-    //PKA_MMUL(0,3,15,3, 5,3, 6,3,0);
-    Sec_Eng_PKA_MMUL(3, 15, 3, 5, 3, 6, 3, 0, 0);
-
-    //W^2
-    //PKA_MMUL(0,3, 7,3,13,3,13,3,0);
-    Sec_Eng_PKA_MMUL(3, 7, 3, 13, 3, 13, 3, 0, 0);
-
-    //B = X1*Y1*S
-    //PKA_MMUL(0,3,15,3,15,3,14,3,0);
-    Sec_Eng_PKA_MMUL(3, 15, 3, 15, 3, 14, 3, 0, 0);
-
-    //8*B
-    //PKA_MMUL(0,3, 5,3,12,3,15,3,0);
-    Sec_Eng_PKA_MMUL(3, 5, 3, 12, 3, 15, 3, 0, 0);
-
-    //H = W^2-8*B
-    //PKA_MSUB(0,3, 7,3, 7,3, 5,3,0);
-    Sec_Eng_PKA_MSUB(3, 7, 3, 7, 3, 5, 3, 0, 0);
-
-    //2*H
-    //PKA_MMUL(0,3, 5,3, 9,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 5, 3, 9, 3, 7, 3, 0, 0);
-
-    //X2 = 2*H*S
-    //PKA_MMUL(0,3, 5,3, 5,3,14,3,0);
-    Sec_Eng_PKA_MMUL(3, 5, 3, 5, 3, 14, 3, 0, 0);
-
-    //4*B
-    //PKA_MMUL(0,3,15,3,11,3,15,3,0);
-    Sec_Eng_PKA_MMUL(3, 15, 3, 11, 3, 15, 3, 0, 0);
-
-    //S^2
-    //PKA_MMUL(0,3,16,3,14,3,14,3,0);
-    Sec_Eng_PKA_MMUL(3, 16, 3, 14, 3, 14, 3, 0, 0);
-
-    //4*B-H
-    //PKA_MSUB(0,3,15,3,15,3, 7,3,0);
-    Sec_Eng_PKA_MSUB(3, 15, 3, 15, 3, 7, 3, 0, 0);
-
-    //Y1^2
-    //PKA_MMUL(0,3, 6,3, 6,3, 6,3,0);
-    Sec_Eng_PKA_MMUL(3, 6, 3, 6, 3, 6, 3, 0, 0);
-
-    //W*(4*B-H)
-    //PKA_MMUL(0,3,15,3,15,3,13,3,0);
-    Sec_Eng_PKA_MMUL(3, 15, 3, 15, 3, 13, 3, 0, 0);
-
-    //8*Y1^2
-    //PKA_MMUL(0,3, 6,3,12,3, 6,3,0);
-    Sec_Eng_PKA_MMUL(3, 6, 3, 12, 3, 6, 3, 0, 0);
-
-    //8*Y1^2*S^2
-    //PKA_MMUL(0,3, 6,3, 6,3,16,3,0);
-    Sec_Eng_PKA_MMUL(3, 6, 3, 6, 3, 16, 3, 0, 0);
-
-    //Y2 = W*(4*B-H)-8*Y1^2*S^2
-    //PKA_MSUB(0,3, 6,3,15,3, 6,3,0);
-    Sec_Eng_PKA_MSUB(3, 6, 3, 15, 3, 6, 3, 0, 0);
-
-    //S^3
-    //PKA_MMUL(0,3, 7,3,14,3,16,3,0);
-    Sec_Eng_PKA_MMUL(3, 7, 3, 14, 3, 16, 3, 0, 0);
-
-    //Z2 = 8*S^3
-    //PKA_MMUL(1,3, 7,3,12,3, 7,3,0);
-    Sec_Eng_PKA_MMUL(3, 7, 3, 12, 3, 7, 3, 0, 1);
-
-    return SUCCESS;
+static BL_Err_Type sec_ecdsa_point_double(sec_ecp_type id) {
+  /* index 2:BAR_Zero_x
+   * index 3:BAR_Zero_y
+   * index 4:BAR_Zero_z
+   * index 5:BAR_G_x
+   * index 6:BAR_G_y
+   * index 7:BAR_G_z
+   * index 8:1
+   * index 9:2
+   * index 10:3
+   * index 11:4
+   * index 12:8
+   * index 19:1P1
+   * index 20:1m1*/
+
+  if (id >= ECP_TYPE_MAX) {
+    return ERROR;
+  }
+
+  if (id == ECP_SECP256R1) {
+    sec_ecdsa_cal_secp256r1_w();
+  } else if (id == ECP_SECP256K1) {
+    sec_ecdsa_cal_secp256k1_w();
+  }
+
+  // S = Y1*Z1
+  // PKA_MMUL(0,3,14,3, 6,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 14, 3, 6, 3, 7, 3, 0, 0);
+
+  // X1*Y1
+  // PKA_MMUL(0,3,15,3, 5,3, 6,3,0);
+  Sec_Eng_PKA_MMUL(3, 15, 3, 5, 3, 6, 3, 0, 0);
+
+  // W^2
+  // PKA_MMUL(0,3, 7,3,13,3,13,3,0);
+  Sec_Eng_PKA_MMUL(3, 7, 3, 13, 3, 13, 3, 0, 0);
+
+  // B = X1*Y1*S
+  // PKA_MMUL(0,3,15,3,15,3,14,3,0);
+  Sec_Eng_PKA_MMUL(3, 15, 3, 15, 3, 14, 3, 0, 0);
+
+  // 8*B
+  // PKA_MMUL(0,3, 5,3,12,3,15,3,0);
+  Sec_Eng_PKA_MMUL(3, 5, 3, 12, 3, 15, 3, 0, 0);
+
+  // H = W^2-8*B
+  // PKA_MSUB(0,3, 7,3, 7,3, 5,3,0);
+  Sec_Eng_PKA_MSUB(3, 7, 3, 7, 3, 5, 3, 0, 0);
+
+  // 2*H
+  // PKA_MMUL(0,3, 5,3, 9,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 5, 3, 9, 3, 7, 3, 0, 0);
+
+  // X2 = 2*H*S
+  // PKA_MMUL(0,3, 5,3, 5,3,14,3,0);
+  Sec_Eng_PKA_MMUL(3, 5, 3, 5, 3, 14, 3, 0, 0);
+
+  // 4*B
+  // PKA_MMUL(0,3,15,3,11,3,15,3,0);
+  Sec_Eng_PKA_MMUL(3, 15, 3, 11, 3, 15, 3, 0, 0);
+
+  // S^2
+  // PKA_MMUL(0,3,16,3,14,3,14,3,0);
+  Sec_Eng_PKA_MMUL(3, 16, 3, 14, 3, 14, 3, 0, 0);
+
+  // 4*B-H
+  // PKA_MSUB(0,3,15,3,15,3, 7,3,0);
+  Sec_Eng_PKA_MSUB(3, 15, 3, 15, 3, 7, 3, 0, 0);
+
+  // Y1^2
+  // PKA_MMUL(0,3, 6,3, 6,3, 6,3,0);
+  Sec_Eng_PKA_MMUL(3, 6, 3, 6, 3, 6, 3, 0, 0);
+
+  // W*(4*B-H)
+  // PKA_MMUL(0,3,15,3,15,3,13,3,0);
+  Sec_Eng_PKA_MMUL(3, 15, 3, 15, 3, 13, 3, 0, 0);
+
+  // 8*Y1^2
+  // PKA_MMUL(0,3, 6,3,12,3, 6,3,0);
+  Sec_Eng_PKA_MMUL(3, 6, 3, 12, 3, 6, 3, 0, 0);
+
+  // 8*Y1^2*S^2
+  // PKA_MMUL(0,3, 6,3, 6,3,16,3,0);
+  Sec_Eng_PKA_MMUL(3, 6, 3, 6, 3, 16, 3, 0, 0);
+
+  // Y2 = W*(4*B-H)-8*Y1^2*S^2
+  // PKA_MSUB(0,3, 6,3,15,3, 6,3,0);
+  Sec_Eng_PKA_MSUB(3, 6, 3, 15, 3, 6, 3, 0, 0);
+
+  // S^3
+  // PKA_MMUL(0,3, 7,3,14,3,16,3,0);
+  Sec_Eng_PKA_MMUL(3, 7, 3, 14, 3, 16, 3, 0, 0);
+
+  // Z2 = 8*S^3
+  // PKA_MMUL(1,3, 7,3,12,3, 7,3,0);
+  Sec_Eng_PKA_MMUL(3, 7, 3, 12, 3, 7, 3, 0, 1);
+
+  return SUCCESS;
 }
 #ifdef ECDSA_DBG_DETAIL
-static void sec_ecdsa_dump_temp_result()
-{
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("2=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("3=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("4=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
-
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("5=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("6=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 7, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("7=\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+static void sec_ecdsa_dump_temp_result() {
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("2=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("3=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("4=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("5=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("6=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 7, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("7=\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 }
 #endif
-static int sec_ecdsa_verify_point_mul(uint8_t id, const uint32_t *m)
-{
-    uint32_t i, j, k;
-    uint32_t tmp;
-    uint32_t isOne = 0;
-    uint8_t *p = (uint8_t *)m;
-    uint8_t pka_p1_eq_inf, pka_p2_eq_inf;
-
-    /* Remove zeros bytes*/
-    k = 0;
-
-    while (p[k] == 0 && k < 31) {
-        k++;
-    }
+static int sec_ecdsa_verify_point_mul(uint8_t id, const uint32_t *m) {
+  uint32_t i, j, k;
+  uint32_t tmp;
+  uint32_t isOne = 0;
+  uint8_t *p     = (uint8_t *)m;
+  uint8_t  pka_p1_eq_inf, pka_p2_eq_inf;
 
-    i = 31;
+  /* Remove zeros bytes*/
+  k = 0;
 
-    for (; i >= k; i--) {
-        tmp = p[i];
-        j = 0;
+  while (p[k] == 0 && k < 31) {
+    k++;
+  }
 
-        for (j = 0; j < 8; j++) {
-            isOne = tmp & (1 << j);
+  i = 31;
 
-            if (isOne) {
-                sec_ecdsa_point_add_inf_check(&pka_p1_eq_inf, &pka_p2_eq_inf);
+  for (; i >= k; i--) {
+    tmp = p[i];
+    j   = 0;
 
-                if (pka_p1_eq_inf == 1 && pka_p2_eq_inf == 0) {
-                    //sum = X2
-                    sec_ecdsa_copy_x2_to_x1(id);
+    for (j = 0; j < 8; j++) {
+      isOne = tmp & (1 << j);
+
+      if (isOne) {
+        sec_ecdsa_point_add_inf_check(&pka_p1_eq_inf, &pka_p2_eq_inf);
+
+        if (pka_p1_eq_inf == 1 && pka_p2_eq_inf == 0) {
+          // sum = X2
+          sec_ecdsa_copy_x2_to_x1(id);
 #ifdef ECDSA_DBG_DETAIL
-                    MSG("sum = X2\r\n");
-                    sec_ecdsa_dump_temp_result();
+          MSG("sum = X2\r\n");
+          sec_ecdsa_dump_temp_result();
 #endif
-                } else if (pka_p1_eq_inf == 0 && pka_p2_eq_inf == 1) {
-                    //sum = X1
-                    //MSG("sum = X1\r\n");
-                } else if (pka_p1_eq_inf == 0 && pka_p2_eq_inf == 0) {
-                    //sum = X1 + X2
-                    sec_ecdsa_point_add(id);
+        } else if (pka_p1_eq_inf == 0 && pka_p2_eq_inf == 1) {
+          // sum = X1
+          // MSG("sum = X1\r\n");
+        } else if (pka_p1_eq_inf == 0 && pka_p2_eq_inf == 0) {
+          // sum = X1 + X2
+          sec_ecdsa_point_add(id);
 #ifdef ECDSA_DBG_DETAIL
-                    MSG("sum = X1+X2\r\n");
-                    sec_ecdsa_dump_temp_result();
+          MSG("sum = X1+X2\r\n");
+          sec_ecdsa_dump_temp_result();
 #endif
-                } else {
-                    //MSG("Error! infinite point + infinite point\r\n");
-                    return -1;
-                }
-            }
+        } else {
+          // MSG("Error! infinite point + infinite point\r\n");
+          return -1;
+        }
+      }
 
-            sec_ecdsa_point_double(id);
+      sec_ecdsa_point_double(id);
 #ifdef ECDSA_DBG_DETAIL
-            sec_ecdsa_dump_temp_result();
+      sec_ecdsa_dump_temp_result();
 #endif
-        }
+    }
 
-        if (i == 0) {
-            break;
-        }
+    if (i == 0) {
+      break;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
 /*cal d*G if pkX(pky)==NULL
  * cal d(bG) if pkX(pky)!=NULL */
-static int32_t sec_ecdh_get_scalar_point(uint8_t id, const uint32_t *pkX, const uint32_t *pkY, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy)
-{
+static int32_t sec_ecdh_get_scalar_point(uint8_t id, const uint32_t *pkX, const uint32_t *pkY, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy) {
 #ifdef ECDSA_DBG
-    uint32_t pk_z[8];
+  uint32_t pk_z[8];
 #endif
 
-    if (id >= ECP_TYPE_MAX) {
-        return ERROR;
-    }
+  if (id >= ECP_TYPE_MAX) {
+    return ERROR;
+  }
 
-    /* Pointer check */
-    if (private_key == NULL) {
-        return -1;
-    }
+  /* Pointer check */
+  if (private_key == NULL) {
+    return -1;
+  }
 
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
 
-    sec_ecc_basic_parameter_init(id);
+  sec_ecc_basic_parameter_init(id);
 
-    //Clear D[7]
-    //PKA_CREG(1,4, 7,0);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
+  // Clear D[7]
+  // PKA_CREG(1,4, 7,0);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
 
-    sec_ecc_point_mul_init(id);
+  sec_ecc_point_mul_init(id);
 
+  if (id == ECP_SECP256R1) {
+    // X1
+    // PKA_CTREG(3, 2,8,bar_Zero_x);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
+    // Y1
+    // PKA_CTREG(3, 3,8,bar_Zero_y);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    // X1
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256k1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
+    // Y1
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256k1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+  }
+  // Z1
+  // PKA_CTREG(3, 4,8,bar_Zero_z);
+  // PKA_MOVDAT(1,3, 4,3, 2);
+  Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
+
+  if (pkX == NULL) {
     if (id == ECP_SECP256R1) {
-        //X1
-        //PKA_CTREG(3, 2,8,bar_Zero_x);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
-        //Y1
-        //PKA_CTREG(3, 3,8,bar_Zero_y);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+      // X2
+      // PKA_CTREG(3, 5,8,bar_G_x);
+      Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256r1_Gx, ECP_SECP256R1_SIZE / 4, 0);
+      // Y2
+      // PKA_CTREG(3, 6,8,bar_G_y);
+      Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1_Gy, ECP_SECP256R1_SIZE / 4, 0);
     } else if (id == ECP_SECP256K1) {
-        //X1
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256k1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
-        //Y1
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256k1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+      // X2
+      Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256k1_Gx, ECP_SECP256R1_SIZE / 4, 0);
+      // Y2
+      Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1_Gy, ECP_SECP256R1_SIZE / 4, 0);
     }
-    //Z1
-    //PKA_CTREG(3, 4,8,bar_Zero_z);
-    //PKA_MOVDAT(1,3, 4,3, 2);
-    Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
-
-    if (pkX == NULL) {
-        if (id == ECP_SECP256R1) {
-            //X2
-            //PKA_CTREG(3, 5,8,bar_G_x);
-            Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256r1_Gx, ECP_SECP256R1_SIZE / 4, 0);
-            //Y2
-            //PKA_CTREG(3, 6,8,bar_G_y);
-            Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1_Gy, ECP_SECP256R1_SIZE / 4, 0);
-        } else if (id == ECP_SECP256K1) {
-            //X2
-            Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256k1_Gx, ECP_SECP256R1_SIZE / 4, 0);
-            //Y2
-            Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1_Gy, ECP_SECP256R1_SIZE / 4, 0);
-        }
-    } else {
-        /* chaneg peer's public key to mont domain*/
-        //PUB_x
-        //PKA_CTREG(3, 5,8,PUB_x);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pkX, ECP_SECP256R1_SIZE / 4, 0);
-        //bar_pub_x
-        //PKA_GF2MONT(3, 5,3, 5);
-        /* Change s to Mont domain,remember to clear temp register and index 0 is P256*/
-        /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256,
-                            ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  } else {
+    /* chaneg peer's public key to mont domain*/
+    // PUB_x
+    // PKA_CTREG(3, 5,8,PUB_x);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pkX, ECP_SECP256R1_SIZE / 4, 0);
+    // bar_pub_x
+    // PKA_GF2MONT(3, 5,3, 5);
+    /* Change s to Mont domain,remember to clear temp register and index 0 is P256*/
+    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-        MSG("PK.x in Mont:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+    MSG("PK.x in Mont:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-        //PUB_y
-        //PKA_CTREG(3, 6,8,PUB_y);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pkY, ECP_SECP256R1_SIZE / 4, 0);
-        //bar_pub_y
-        //PKA_GF2MONT(3, 6,3, 6);
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 6, 256,
-                            ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+    // PUB_y
+    // PKA_CTREG(3, 6,8,PUB_y);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pkY, ECP_SECP256R1_SIZE / 4, 0);
+    // bar_pub_y
+    // PKA_GF2MONT(3, 6,3, 6);
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 6, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-        MSG("PK.y in Mont:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+    MSG("PK.y in Mont:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
-    }
-
-    //Z2
-    //PKA_CTREG(3, 7,8,bar_G_z);
-    //PKA_MOVDAT(1,3, 7,3, 3);
-    Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
-    /* Clear temp register since it's used in point-mul*/
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
-
-    sec_ecdsa_verify_point_mul(id, private_key);
-    //get bar_u1_x
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
+  }
+
+  // Z2
+  // PKA_CTREG(3, 7,8,bar_G_z);
+  // PKA_MOVDAT(1,3, 7,3, 3);
+  Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
+  /* Clear temp register since it's used in point-mul*/
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
+
+  sec_ecdsa_verify_point_mul(id, private_key);
+  // get bar_u1_x
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u1_x\r\n");
-    bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
+  MSG("bar_u1_x\r\n");
+  bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
 #endif
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u1_y\r\n");
-    bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
+  MSG("bar_u1_y\r\n");
+  bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
 #endif
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)pk_z, ECP_SECP256R1_SIZE / 4);
-    MSG("bar_u1_z\r\n");
-    bflb_platform_dump(pk_z, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)pk_z, ECP_SECP256R1_SIZE / 4);
+  MSG("bar_u1_z\r\n");
+  bflb_platform_dump(pk_z, ECP_SECP256R1_SIZE);
 #endif
 
-    //get R.x
-    //R.z ^ -1
-    Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
-    if (id == ECP_SECP256R1) {
-        //inv_r
-        //PKA_CTREG(3, 6,8,inv_r);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
-    } else if (id == ECP_SECP256K1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
-    }
-    //R.z ^ -1
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    //PKA_MONT2GF(3, 5,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-
-    //R.x (Montgomery to GF)
-    //PKA_MONT2GF(3, 6,3, 2,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-
-    //R.x (GF to Affine domain)
-    //PKA_MONT2GF(3, 2,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
+  // get R.x
+  // R.z ^ -1
+  Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
+  if (id == ECP_SECP256R1) {
+    // inv_r
+    // PKA_CTREG(3, 6,8,inv_r);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
+  }
+  // R.z ^ -1
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  // PKA_MONT2GF(3, 5,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+
+  // R.x (Montgomery to GF)
+  // PKA_MONT2GF(3, 6,3, 2,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+
+  // R.x (GF to Affine domain)
+  // PKA_MONT2GF(3, 2,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("R.x=\r\n");
-    bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
+  MSG("R.x=\r\n");
+  bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
 #endif
-    if (id == ECP_SECP256R1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
-    } else if (id == ECP_SECP256K1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256k1N, ECP_SECP256R1_SIZE / 4, 0);
-    }
-
-    Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 2,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
+  if (id == ECP_SECP256R1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256k1N, ECP_SECP256R1_SIZE / 4, 0);
+  }
+
+  Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)pRx, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("R.x%n=\r\n");
-    bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
+  MSG("R.x%n=\r\n");
+  bflb_platform_dump(pRx, ECP_SECP256R1_SIZE);
 #endif
-    if (id == ECP_SECP256R1) {
-        /*after %n,re write p*/
-        Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)secp256r1P, ECP_SECP256R1_SIZE / 4, 0);
-    } else if (id == ECP_SECP256K1) {
-        Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)secp256k1P, ECP_SECP256R1_SIZE / 4, 0);
-    }
-
-    //get R.y
-    //R.z ^ -1
-    Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
-    //inv_r
-    //PKA_CTREG(3, 6,8,inv_r);
-    if (id == ECP_SECP256R1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
-    } else if (id == ECP_SECP256K1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
-    }
-    //R.z ^ -1
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    //PKA_MONT2GF(3, 5,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-    //R.x (Montgomery to GF)
-    //PKA_MONT2GF(3, 6,3, 2,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-
-    //R.x (GF to Affine domain)
-    //PKA_MONT2GF(3, 2,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
+  if (id == ECP_SECP256R1) {
+    /*after %n,re write p*/
+    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)secp256r1P, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_32, 0, (uint32_t *)secp256k1P, ECP_SECP256R1_SIZE / 4, 0);
+  }
+
+  // get R.y
+  // R.z ^ -1
+  Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
+  // inv_r
+  // PKA_CTREG(3, 6,8,inv_r);
+  if (id == ECP_SECP256R1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256k1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
+  }
+  // R.z ^ -1
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  // PKA_MONT2GF(3, 5,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  // R.x (Montgomery to GF)
+  // PKA_MONT2GF(3, 6,3, 2,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+
+  // R.x (GF to Affine domain)
+  // PKA_MONT2GF(3, 2,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("R.y=\r\n");
-    bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
+  MSG("R.y=\r\n");
+  bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
 #endif
-    if (id == ECP_SECP256R1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
-    } else if (id == ECP_SECP256K1) {
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256k1N, ECP_SECP256R1_SIZE / 4, 0);
-    }
-    Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 3,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
+  if (id == ECP_SECP256R1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
+  } else if (id == ECP_SECP256K1) {
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256k1N, ECP_SECP256R1_SIZE / 4, 0);
+  }
+  Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, 3, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)pRy, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("R.y%n=\r\n");
-    bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
+  MSG("R.y%n=\r\n");
+  bflb_platform_dump(pRy, ECP_SECP256R1_SIZE);
 #endif
-    return 0;
+  return 0;
 }
 
-static int32_t sec_ecc_is_zero(uint8_t *a, uint32_t len)
-{
-    uint32_t i = 0;
+static int32_t sec_ecc_is_zero(uint8_t *a, uint32_t len) {
+  uint32_t i = 0;
 
-    for (i = 0; i < len; i++) {
-        if (a[i] != 0) {
-            return 0;
-        }
+  for (i = 0; i < len; i++) {
+    if (a[i] != 0) {
+      return 0;
     }
+  }
 
-    return 1;
+  return 1;
 }
 
-static int32_t sec_ecc_cmp(uint8_t *a, uint8_t *b, uint32_t len)
-{
-    uint32_t i = 0, j = 0;
+static int32_t sec_ecc_cmp(uint8_t *a, uint8_t *b, uint32_t len) {
+  uint32_t i = 0, j = 0;
 
-    for (i = 0; i < len; i++) {
-        if (a[i] != 0) {
-            break;
-        }
+  for (i = 0; i < len; i++) {
+    if (a[i] != 0) {
+      break;
     }
+  }
 
-    for (j = 0; j < len; j++) {
-        if (b[j] != 0) {
-            break;
-        }
+  for (j = 0; j < len; j++) {
+    if (b[j] != 0) {
+      break;
     }
+  }
 
-    if (i == len && j == len) {
-        return (0);
-    }
+  if (i == len && j == len) {
+    return (0);
+  }
 
-    if (i > j) {
-        return (-1);
-    }
+  if (i > j) {
+    return (-1);
+  }
 
-    if (j > i) {
-        return (1);
-    }
+  if (j > i) {
+    return (1);
+  }
 
-    for (; i < len; i++) {
-        if (a[i] > b[i]) {
-            return (1);
-        }
+  for (; i < len; i++) {
+    if (a[i] > b[i]) {
+      return (1);
+    }
 
-        if (a[i] < b[i]) {
-            return (-1);
-        }
+    if (a[i] < b[i]) {
+      return (-1);
     }
+  }
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdsa_init(sec_ecdsa_handle_t *handle, sec_ecp_type id)
-{
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
-    Sec_Eng_Trng_Enable();
+int sec_ecdsa_init(sec_ecdsa_handle_t *handle, sec_ecp_type id) {
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
+  Sec_Eng_Trng_Enable();
 
-    handle->ecpId = id;
+  handle->ecpId = id;
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdsa_deinit(sec_ecdsa_handle_t *handle)
-{
-    Sec_Eng_PKA_Reset();
+int sec_ecdsa_deinit(sec_ecdsa_handle_t *handle) {
+  Sec_Eng_PKA_Reset();
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdsa_verify(sec_ecdsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, const uint32_t *r, const uint32_t *s)
-{
-    uint32_t bar_u1_x[8];
-    uint32_t bar_u1_y[8];
-    uint32_t bar_u1_z[8];
-    uint32_t bar_u2_x[8];
-    uint32_t bar_u2_y[8];
-    uint32_t bar_u2_z[8];
-    uint32_t pka_u1[8] = { 0 };
-    uint32_t pka_u2[8] = { 0 };
-    uint32_t i = 0;
-
-    /* Pointer check */
-    if (hash == NULL || handle->publicKeyx == NULL || handle->publicKeyy == NULL || r == NULL || s == NULL) {
-        return -1;
-    }
-
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
+int sec_ecdsa_verify(sec_ecdsa_handle_t *handle, const uint32_t *hash, uint32_t hashLenInWord, const uint32_t *r, const uint32_t *s) {
+  uint32_t bar_u1_x[8];
+  uint32_t bar_u1_y[8];
+  uint32_t bar_u1_z[8];
+  uint32_t bar_u2_x[8];
+  uint32_t bar_u2_y[8];
+  uint32_t bar_u2_z[8];
+  uint32_t pka_u1[8] = {0};
+  uint32_t pka_u2[8] = {0};
+  uint32_t i         = 0;
+
+  /* Pointer check */
+  if (hash == NULL || handle->publicKeyx == NULL || handle->publicKeyy == NULL || r == NULL || s == NULL) {
+    return -1;
+  }
 
-    /*Step 0: make sure r and s are in range 1..n-1*/
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
 
-    /* r and s should not be 0*/
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 8, (uint32_t *)secp256r1_1, ECP_SECP256R1_SIZE / 4, 0);
-    //cout = 1 if r = 0
-    Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, 8); //s0 < s1 => cout = 1
+  /*Step 0: make sure r and s are in range 1..n-1*/
 
-    if (i == 1) {
-        return -1;
-    }
+  /* r and s should not be 0*/
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 8, (uint32_t *)secp256r1_1, ECP_SECP256R1_SIZE / 4, 0);
+  // cout = 1 if r = 0
+  Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, 8); // s0 < s1 => cout = 1
 
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
-    //cout = 1 if r = 0
-    Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, 8); //s0 < s1 => cout = 1
-
-    if (i == 1) {
-        return -1;
-    }
+  if (i == 1) {
+    return -1;
+  }
 
-    sec_ecc_basic_parameter_init(handle->ecpId);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
+  // cout = 1 if r = 0
+  Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, 8); // s0 < s1 => cout = 1
 
-    /* r and s should not be 0*/
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
-    //cout = 1 if r < N
-    Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+  if (i == 1) {
+    return -1;
+  }
 
-    if (i != 1) {
-        return -1;
-    }
+  sec_ecc_basic_parameter_init(handle->ecpId);
 
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
-    //cout = 1 if r < N
-    Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+  /* r and s should not be 0*/
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
+  // cout = 1 if r < N
+  Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
 
-    if (i != 1) {
-        return -1;
-    }
+  if (i != 1) {
+    return -1;
+  }
 
-    /* u1 = e / s mod n, u2 = r / s mod n
-     * R = u1 G + u2 Q*/
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
+  // cout = 1 if r < N
+  Sec_Eng_PKA_LCMP((uint8_t *)&i, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
 
-    /* Step1: Get S^-1*/
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
-    /* Change s to Mont domain */
-    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 256,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+  if (i != 1) {
+    return -1;
+  }
+
+  /* u1 = e / s mod n, u2 = r / s mod n
+   * R = u1 G + u2 Q*/
+
+  /* Step1: Get S^-1*/
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)s, ECP_SECP256R1_SIZE / 4, 0);
+  /* Change s to Mont domain */
+  /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX,
+                      ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("GF2Mont Result of s:\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("GF2Mont Result of s:\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Get S^-1 in Mont domain */
-    Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+  /* Get S^-1 in Mont domain */
+  Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("s^-1 in Mont:\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("s^-1 in Mont:\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Change S^-1 into GF domain,now  ECP_SECP256R1_S_REG_INDEX store s^-1*/
-    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+  /* Change S^-1 into GF domain,now  ECP_SECP256R1_S_REG_INDEX store s^-1*/
+  /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_BAR_S_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX,
+                      ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("S^-1:\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("S^-1:\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step2: Get u1*/
-    //u1=hash(e)*s^-1;
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, (uint32_t *)hash, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_LMUL(ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 0);
-    Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, (uint32_t *)pka_u1, ECP_SECP256R1_SIZE / 4);
+  /* Step2: Get u1*/
+  // u1=hash(e)*s^-1;
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, (uint32_t *)hash, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_LMUL(ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 0);
+  Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, (uint32_t *)pka_u1, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("u1:\r\n");
-    bflb_platform_dump(pka_u1, ECP_SECP256R1_SIZE);
+  MSG("u1:\r\n");
+  bflb_platform_dump(pka_u1, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step3: Get u2*/
-    //u2=r*s^-1;
-    // use hash and u1 temp register
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
-    Sec_Eng_PKA_LMUL(ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 0);
-    Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX,
-                     ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, (uint32_t *)pka_u2, ECP_SECP256R1_SIZE / 4);
+  /* Step3: Get u2*/
+  // u2=r*s^-1;
+  //  use hash and u1 temp register
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
+  Sec_Eng_PKA_LMUL(ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_HASH_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_S_REG_INDEX, 0);
+  Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_U1_REG_INDEX, (uint32_t *)pka_u2, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("u2:\r\n");
-    bflb_platform_dump(pka_u2, ECP_SECP256R1_SIZE);
+  MSG("u2:\r\n");
+  bflb_platform_dump(pka_u2, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step4: Get u1*G*/
-
-    //Clear D[7]
-    //PKA_CREG(1,4, 7,0);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
-
-    sec_ecc_point_mul_init(handle->ecpId);
-
-    //X1
-    //PKA_CTREG(3, 2,8,bar_Zero_x);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
-    //Y1
-    //PKA_CTREG(3, 3,8,bar_Zero_y);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
-    //Z1
-    //PKA_CTREG(3, 4,8,bar_Zero_z);
-    //PKA_MOVDAT(1,3, 4,3, 2);
-    Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
-
-    //X2
-    //PKA_CTREG(3, 5,8,bar_G_x);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256r1_Gx, ECP_SECP256R1_SIZE / 4, 0);
-    //Y2
-    //PKA_CTREG(3, 6,8,bar_G_y);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1_Gy, ECP_SECP256R1_SIZE / 4, 0);
-    //Z2
-    //PKA_CTREG(3, 7,8,bar_G_z);
-    //PKA_MOVDAT(1,3, 7,3, 3);
-    Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
-
-    sec_ecdsa_verify_point_mul(handle->ecpId, pka_u1);
-    //get bar_u1_x
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u1_x, ECP_SECP256R1_SIZE / 4);
+  /* Step4: Get u1*G*/
+
+  // Clear D[7]
+  // PKA_CREG(1,4, 7,0);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
+
+  sec_ecc_point_mul_init(handle->ecpId);
+
+  // X1
+  // PKA_CTREG(3, 2,8,bar_Zero_x);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
+  // Y1
+  // PKA_CTREG(3, 3,8,bar_Zero_y);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+  // Z1
+  // PKA_CTREG(3, 4,8,bar_Zero_z);
+  // PKA_MOVDAT(1,3, 4,3, 2);
+  Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
+
+  // X2
+  // PKA_CTREG(3, 5,8,bar_G_x);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)secp256r1_Gx, ECP_SECP256R1_SIZE / 4, 0);
+  // Y2
+  // PKA_CTREG(3, 6,8,bar_G_y);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1_Gy, ECP_SECP256R1_SIZE / 4, 0);
+  // Z2
+  // PKA_CTREG(3, 7,8,bar_G_z);
+  // PKA_MOVDAT(1,3, 7,3, 3);
+  Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
+
+  sec_ecdsa_verify_point_mul(handle->ecpId, pka_u1);
+  // get bar_u1_x
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u1_x, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u1_x\r\n");
-    bflb_platform_dump(bar_u1_x, ECP_SECP256R1_SIZE);
+  MSG("bar_u1_x\r\n");
+  bflb_platform_dump(bar_u1_x, ECP_SECP256R1_SIZE);
 #endif
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u1_y, ECP_SECP256R1_SIZE / 4);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u1_y, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u1_y\r\n");
-    bflb_platform_dump(bar_u1_y, ECP_SECP256R1_SIZE);
+  MSG("bar_u1_y\r\n");
+  bflb_platform_dump(bar_u1_y, ECP_SECP256R1_SIZE);
 #endif
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u1_z, ECP_SECP256R1_SIZE / 4);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u1_z, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u1_z\r\n");
-    bflb_platform_dump(bar_u1_z, ECP_SECP256R1_SIZE);
+  MSG("bar_u1_z\r\n");
+  bflb_platform_dump(bar_u1_z, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step4: Get u2*Q*/
-    //X1
-    //PKA_CTREG(3, 2,8,bar_Zero_x);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
-    //Y1
-    //PKA_CTREG(3, 3,8,bar_Zero_y);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
-    //Z1
-    //PKA_CTREG(3, 4,8,bar_Zero_z);
-    //PKA_MOVDAT(1,3, 4,3, 2);
-    Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
-
-    //PUB_x
-    //PKA_CTREG(3, 5,8,PUB_x);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)handle->publicKeyx, ECP_SECP256R1_SIZE / 4, 0);
-    //bar_pub_x
-    //PKA_GF2MONT(3, 5,3, 5);
-    /* Change s to Mont domain,remember to clear temp register and index 0 is P256*/
-    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  /* Step4: Get u2*Q*/
+  // X1
+  // PKA_CTREG(3, 2,8,bar_Zero_x);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)secp256r1_Zerox, ECP_SECP256R1_SIZE / 4, 0);
+  // Y1
+  // PKA_CTREG(3, 3,8,bar_Zero_y);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)secp256r1_Zeroy, ECP_SECP256R1_SIZE / 4, 0);
+  // Z1
+  // PKA_CTREG(3, 4,8,bar_Zero_z);
+  // PKA_MOVDAT(1,3, 4,3, 2);
+  Sec_Eng_PKA_Move_Data(3, 4, 3, 2, 1);
+
+  // PUB_x
+  // PKA_CTREG(3, 5,8,PUB_x);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)handle->publicKeyx, ECP_SECP256R1_SIZE / 4, 0);
+  // bar_pub_x
+  // PKA_GF2MONT(3, 5,3, 5);
+  /* Change s to Mont domain,remember to clear temp register and index 0 is P256*/
+  /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("PK.x in Mont:\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("PK.x in Mont:\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-    //PUB_y
-    //PKA_CTREG(3, 6,8,PUB_y);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)handle->publicKeyy, ECP_SECP256R1_SIZE / 4, 0);
-    //bar_pub_y
-    //PKA_GF2MONT(3, 6,3, 6);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 6, 256,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  // PUB_y
+  // PKA_CTREG(3, 6,8,PUB_y);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)handle->publicKeyy, ECP_SECP256R1_SIZE / 4, 0);
+  // bar_pub_y
+  // PKA_GF2MONT(3, 6,3, 6);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 6, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
 #ifdef ECDSA_DBG
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-    MSG("PK.y in Mont:\r\n");
-    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+  MSG("PK.y in Mont:\r\n");
+  bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-    //bar_pub_z
-    //PKA_CTREG(3, 7,8,PUB_z);
-    //PKA_MOVDAT(1,3, 7,3, 3);
-    Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
+  // bar_pub_z
+  // PKA_CTREG(3, 7,8,PUB_z);
+  // PKA_MOVDAT(1,3, 7,3, 3);
+  Sec_Eng_PKA_Move_Data(3, 7, 3, 3, 1);
 
-    /* Clear temp register since it's used in point-mul*/
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
+  /* Clear temp register since it's used in point-mul*/
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_LT_REG_TYPE, 7, ECP_SECP256R1_SIZE / 4, 1);
 
-    sec_ecdsa_verify_point_mul(handle->ecpId, pka_u2);
-    //get bar_u1_x
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u2_x, ECP_SECP256R1_SIZE / 4);
+  sec_ecdsa_verify_point_mul(handle->ecpId, pka_u2);
+  // get bar_u1_x
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u2_x, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u2_x\r\n");
-    bflb_platform_dump(bar_u2_x, ECP_SECP256R1_SIZE);
+  MSG("bar_u2_x\r\n");
+  bflb_platform_dump(bar_u2_x, ECP_SECP256R1_SIZE);
 #endif
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u2_y, ECP_SECP256R1_SIZE / 4);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u2_y, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u2_y\r\n");
-    bflb_platform_dump(bar_u2_y, ECP_SECP256R1_SIZE);
+  MSG("bar_u2_y\r\n");
+  bflb_platform_dump(bar_u2_y, ECP_SECP256R1_SIZE);
 #endif
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u2_z, ECP_SECP256R1_SIZE / 4);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u2_z, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("bar_u2_z\r\n");
-    bflb_platform_dump(bar_u2_z, ECP_SECP256R1_SIZE);
+  MSG("bar_u2_z\r\n");
+  bflb_platform_dump(bar_u2_z, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step5: Get u1*G+u2*Q*/
-    //move bar_u2_x
-    //PKA_MOVDAT(0,3, 5,3, 2);
-    Sec_Eng_PKA_Move_Data(3, 5, 3, 2, 0);
-    //move bar_u2_y
-    //PKA_MOVDAT(0,3, 6,3, 3);
-    Sec_Eng_PKA_Move_Data(3, 6, 3, 3, 0);
-    //move bar_u2_z
-    //PKA_MOVDAT(1,3, 7,3, 4);
-    Sec_Eng_PKA_Move_Data(3, 7, 3, 4, 1);
-
-    //bar_u1_x
-    //PKA_CTREG(3, 2,8,bar_u1_x);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u1_x, ECP_SECP256R1_SIZE / 4, 0);
-    //bar_u1_y
-    //PKA_CTREG(3, 3,8,bar_u1_y);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u1_y, ECP_SECP256R1_SIZE / 4, 0);
-    //bar_u1_z
-    //PKA_CTREG(3, 4,8,bar_u1_z);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u1_z, ECP_SECP256R1_SIZE / 4, 0);
-
-    //R = u1 * G + u2 * PUB
-    //PKA_POINT_ADDITION();
-    sec_ecdsa_point_add(handle->ecpId);
-
-    /* Step6 Get R.x(R=u1G+u2P)*/
-    //R.z ^ -1
-    //PKA_MINV(0,3, 5,3, 4,3, 0);
-    Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
-    //inv_r
-    //PKA_CTREG(3, 6,8,inv_r);
-    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
-    //R.z ^ -1
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-    //PKA_MONT2GF(3, 5,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-
-    //R.x (Montgomery to GF)
-    //PKA_MONT2GF(3, 6,3, 2,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-
-    //R.x (GF to Affine domain)
-    //PKA_MONT2GF(3, 2,3, 5,3, 6);
-    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6,
-                        ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
-    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u2_x, ECP_SECP256R1_SIZE / 4);
+  /* Step5: Get u1*G+u2*Q*/
+  // move bar_u2_x
+  // PKA_MOVDAT(0,3, 5,3, 2);
+  Sec_Eng_PKA_Move_Data(3, 5, 3, 2, 0);
+  // move bar_u2_y
+  // PKA_MOVDAT(0,3, 6,3, 3);
+  Sec_Eng_PKA_Move_Data(3, 6, 3, 3, 0);
+  // move bar_u2_z
+  // PKA_MOVDAT(1,3, 7,3, 4);
+  Sec_Eng_PKA_Move_Data(3, 7, 3, 4, 1);
+
+  // bar_u1_x
+  // PKA_CTREG(3, 2,8,bar_u1_x);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u1_x, ECP_SECP256R1_SIZE / 4, 0);
+  // bar_u1_y
+  // PKA_CTREG(3, 3,8,bar_u1_y);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 3, (uint32_t *)bar_u1_y, ECP_SECP256R1_SIZE / 4, 0);
+  // bar_u1_z
+  // PKA_CTREG(3, 4,8,bar_u1_z);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)bar_u1_z, ECP_SECP256R1_SIZE / 4, 0);
+
+  // R = u1 * G + u2 * PUB
+  // PKA_POINT_ADDITION();
+  sec_ecdsa_point_add(handle->ecpId);
+
+  /* Step6 Get R.x(R=u1G+u2P)*/
+  // R.z ^ -1
+  // PKA_MINV(0,3, 5,3, 4,3, 0);
+  Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 0, 1);
+  // inv_r
+  // PKA_CTREG(3, 6,8,inv_r);
+  Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)secp256r1InvR_P, ECP_SECP256R1_SIZE / 4, 0);
+  // R.z ^ -1
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+  Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+  // PKA_MONT2GF(3, 5,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+
+  // R.x (Montgomery to GF)
+  // PKA_MONT2GF(3, 6,3, 2,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+
+  // R.x (GF to Affine domain)
+  // PKA_MONT2GF(3, 2,3, 5,3, 6);
+  Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 2, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 0);
+  Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 2, (uint32_t *)bar_u2_x, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-    MSG("R.x=\r\n");
-    bflb_platform_dump(bar_u2_x, ECP_SECP256R1_SIZE);
+  MSG("R.x=\r\n");
+  bflb_platform_dump(bar_u2_x, ECP_SECP256R1_SIZE);
 #endif
 
-    /* Step7 check R.x=r*/
-    /* Check Result */
-    for (i = 0; i < 8; i++) {
-        if (bar_u2_x[i] != r[i]) {
-            return -1;
-        }
+  /* Step7 check R.x=r*/
+  /* Check Result */
+  for (i = 0; i < 8; i++) {
+    if (bar_u2_x[i] != r[i]) {
+      return -1;
     }
+  }
 
 #ifdef ECDSA_DBG
-    MSG("Verify success\r\n");
+  MSG("Verify success\r\n");
 #endif
-    return 0;
+  return 0;
 }
 
-int sec_ecdsa_sign(sec_ecdsa_handle_t *handle, const uint32_t *random_k, const uint32_t *hash, uint32_t hashLenInWord, uint32_t *r, uint32_t *s)
-{
-    uint32_t k[8];
-    uint32_t Rx[8];
-    uint32_t Ry[8];
-    uint32_t KInvert[8];
-    uint32_t maxTry1 = 100;
+int sec_ecdsa_sign(sec_ecdsa_handle_t *handle, const uint32_t *random_k, const uint32_t *hash, uint32_t hashLenInWord, uint32_t *r, uint32_t *s) {
+  uint32_t k[8];
+  uint32_t Rx[8];
+  uint32_t Ry[8];
+  uint32_t KInvert[8];
+  uint32_t maxTry1 = 100;
 
-    /* Pointer check */
-    if (handle->privateKey == NULL || hash == NULL || r == NULL || s == NULL) {
-        return -1;
-    }
+  /* Pointer check */
+  if (handle->privateKey == NULL || hash == NULL || r == NULL || s == NULL) {
+    return -1;
+  }
 
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
-    Sec_Eng_Trng_Enable();
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
+  Sec_Eng_Trng_Enable();
 
-    while (maxTry1--) {
-        /* step 1 ,get random k*/
-        if (random_k == NULL) {
-            if (sec_ecc_get_random_value(k, (uint32_t *)secp256r1N, 32) < 0) {
-                return -1;
-            }
-        } else {
-            memcpy(k, random_k, 32);
-        }
+  while (maxTry1--) {
+    /* step 1 ,get random k*/
+    if (random_k == NULL) {
+      if (sec_ecc_get_random_value(k, (uint32_t *)secp256r1N, 32) < 0) {
+        return -1;
+      }
+    } else {
+      memcpy(k, random_k, 32);
+    }
 
 #ifdef ECDSA_DBG
-        MSG("Random k:\r\n");
-        bflb_platform_dump(k, ECP_SECP256R1_SIZE);
+    MSG("Random k:\r\n");
+    bflb_platform_dump(k, ECP_SECP256R1_SIZE);
 #endif
 
-        /*step 2, calc R=kG*/
-        if (sec_ecdsa_get_public_key(handle, k, Rx, Ry) < 0) {
-            return -1;
-        }
+    /*step 2, calc R=kG*/
+    if (sec_ecdsa_get_public_key(handle, k, Rx, Ry) < 0) {
+      return -1;
+    }
 
-        if (sec_ecc_is_zero((uint8_t *)Rx, 32)) {
-            continue;
-        }
+    if (sec_ecc_is_zero((uint8_t *)Rx, 32)) {
+      continue;
+    }
 
-        memcpy(r, Rx, 32);
+    memcpy(r, Rx, 32);
 #ifdef ECDSA_DBG
-        MSG("r:\r\n");
-        bflb_platform_dump(r, ECP_SECP256R1_SIZE);
+    MSG("r:\r\n");
+    bflb_platform_dump(r, ECP_SECP256R1_SIZE);
 #endif
-        sec_ecc_basic_parameter_init(handle->ecpId);
-        /* step 3,get k^-1*/
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)k, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
-        /* Change k to Mont domain */
-        /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
-        Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256,
-                            ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+    sec_ecc_basic_parameter_init(handle->ecpId);
+    /* step 3,get k^-1*/
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)k, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
+    /* Change k to Mont domain */
+    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX - 1, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_CREG(ECP_SECP256R1_REG_TYPE, 2 * ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_SIZE / 4, 1);
+    Sec_Eng_PKA_GF2Mont(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 5, 256, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
-        MSG("GF2Mont Result of k:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 4);
+    MSG("GF2Mont Result of k:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE);
 #endif
 
-        /* Get k^-1 in Mont domain */
-        Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 5,
-                         ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+    /* Get k^-1 in Mont domain */
+    Sec_Eng_PKA_MINV(ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4);
-        MSG("k^-1 in Mont:\r\n");
-        bflb_platform_dump(KInvert, ECP_SECP256R1_SIZE);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 6, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4);
+    MSG("k^-1 in Mont:\r\n");
+    bflb_platform_dump(KInvert, ECP_SECP256R1_SIZE);
 #endif
 
-        /* Change k^-1 into GF domain,now  ECP_SECP256R1_S_REG_INDEX store k^-1*/
-        /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
-        Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX,
-                            ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4);
+    /* Change k^-1 into GF domain,now  ECP_SECP256R1_S_REG_INDEX store k^-1*/
+    /* Clear register for ECP_SECP256R1_LT_REG_INDEX*/
+    Sec_Eng_PKA_Mont2GF(ECP_SECP256R1_REG_TYPE, 5, ECP_SECP256R1_REG_TYPE, 6, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_INVR_N_REG_INDEX, ECP_SECP256R1_LT_REG_TYPE, ECP_SECP256R1_LT_REG_INDEX,
+                        ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-        MSG("k^-1:\r\n");
-        bflb_platform_dump(KInvert, ECP_SECP256R1_SIZE);
+    MSG("k^-1:\r\n");
+    bflb_platform_dump(KInvert, ECP_SECP256R1_SIZE);
 #endif
 
-        /* Step 4,r*d     ((e + r * d) / k) */
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)handle->privateKey, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_LMUL(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 4,
-                         ECP_SECP256R1_REG_TYPE, 5, 1);
+    /* Step 4,r*d     ((e + r * d) / k) */
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)handle->privateKey, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)r, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_LMUL(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_REG_TYPE, 5, 1);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
-        MSG("r*d:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
+    MSG("r*d:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
 #endif
 
-        /* Step 5,e+r*d   ((e + r * d) / k) */
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)hash, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_LADD(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX,
-                         ECP_SECP256R1_REG_TYPE, 5, 1);
+    /* Step 5,e+r*d   ((e + r * d) / k) */
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)hash, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_LADD(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 5, 1);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
-        MSG("e+r*d:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
+    MSG("e+r*d:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
 #endif
 
-        /* Step 6,(e+r*d)*k^-1   ((e + r * d) / k) */
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_LMUL(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX,
-                         ECP_SECP256R1_REG_TYPE, 5, 1);
+    /* Step 6,(e+r*d)*k^-1   ((e + r * d) / k) */
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, 5, (uint32_t *)KInvert, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_LMUL(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_REG_TYPE, 5, 1);
 #ifdef ECDSA_DBG
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
-        MSG("(e+r*d)*k^-1:\r\n");
-        bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, (uint32_t *)pka_tmp, ECP_SECP256R1_SIZE / 2);
+    MSG("(e+r*d)*k^-1:\r\n");
+    bflb_platform_dump(pka_tmp, ECP_SECP256R1_SIZE * 2);
 #endif
-        /*N write only this time,add following operation will not change this register*/
-        Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
-        Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX,
-                         ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
-        Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)s, ECP_SECP256R1_SIZE / 4);
+    /*N write only this time,add following operation will not change this register*/
+    Sec_Eng_PKA_Write_Data(ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, (uint32_t *)secp256r1N, ECP_SECP256R1_SIZE / 4, 0);
+    Sec_Eng_PKA_MREM(ECP_SECP256R1_REG_TYPE, 4, ECP_SECP256R1_SLT_REG_TYPE, ECP_SECP256R1_SLT_REG_INDEX, ECP_SECP256R1_REG_TYPE, ECP_SECP256R1_N_REG_INDEX, 1);
+    Sec_Eng_PKA_Read_Data(ECP_SECP256R1_REG_TYPE, 4, (uint32_t *)s, ECP_SECP256R1_SIZE / 4);
 #ifdef ECDSA_DBG
-        MSG("s:\r\n");
-        bflb_platform_dump(s, ECP_SECP256R1_SIZE);
+    MSG("s:\r\n");
+    bflb_platform_dump(s, ECP_SECP256R1_SIZE);
 #endif
 
-        /* Check s zero*/
-        if (sec_ecc_is_zero((uint8_t *)s, 32)) {
-            continue;
-        }
-
-        return 0;
+    /* Check s zero*/
+    if (sec_ecc_is_zero((uint8_t *)s, 32)) {
+      continue;
     }
 
-    return -1;
+    return 0;
+  }
+
+  return -1;
 }
 
-int sec_ecdsa_get_private_key(sec_ecdsa_handle_t *handle, uint32_t *private_key)
-{
-    if (sec_ecc_get_random_value(private_key, (uint32_t *)secp256r1N, 32) < 0) {
-        return -1;
-    }
+int sec_ecdsa_get_private_key(sec_ecdsa_handle_t *handle, uint32_t *private_key) {
+  if (sec_ecc_get_random_value(private_key, (uint32_t *)secp256r1N, 32) < 0) {
+    return -1;
+  }
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdsa_get_public_key(sec_ecdsa_handle_t *handle, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy)
-{
-    return sec_ecdh_get_scalar_point(handle->ecpId, NULL, NULL, private_key, pRx, pRy);
+int sec_ecdsa_get_public_key(sec_ecdsa_handle_t *handle, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy) {
+  return sec_ecdh_get_scalar_point(handle->ecpId, NULL, NULL, private_key, pRx, pRy);
 }
 
-int sec_ecc_get_random_value(uint32_t *randomData, uint32_t *maxRef, uint32_t size)
-{
-    uint32_t maxTry = 100;
-    int32_t ret = 0;
+int sec_ecc_get_random_value(uint32_t *randomData, uint32_t *maxRef, uint32_t size) {
+  uint32_t maxTry = 100;
+  int32_t  ret    = 0;
 
-    while (maxTry--) {
-        ret = Sec_Eng_Trng_Get_Random((uint8_t *)randomData, size);
+  while (maxTry--) {
+    ret = Sec_Eng_Trng_Get_Random((uint8_t *)randomData, size);
 
-        if (ret < 0) {
-            return -1;
-        }
+    if (ret < 0) {
+      return -1;
+    }
 
-        if (maxRef != NULL) {
-            if (sec_ecc_cmp((uint8_t *)maxRef, (uint8_t *)randomData, size) > 0) {
-                return 0;
-            }
-        } else {
-            return 0;
-        }
+    if (maxRef != NULL) {
+      if (sec_ecc_cmp((uint8_t *)maxRef, (uint8_t *)randomData, size) > 0) {
+        return 0;
+      }
+    } else {
+      return 0;
     }
+  }
 
-    return -1;
+  return -1;
 }
 
-int sec_eng_trng_enable(void)
-{
-    return Sec_Eng_Trng_Enable();
-}
+int sec_eng_trng_enable(void) { return Sec_Eng_Trng_Enable(); }
 
-void sec_eng_trng_disable(void)
-{
-    Sec_Eng_Trng_Disable();
-}
+void sec_eng_trng_disable(void) { Sec_Eng_Trng_Disable(); }
 
-int sec_eng_trng_read(uint8_t data[32])
-{
-    return Sec_Eng_Trng_Read(data);
-}
+int sec_eng_trng_read(uint8_t data[32]) { return Sec_Eng_Trng_Read(data); }
 
-int sec_ecdh_init(sec_ecdh_handle_t *handle, sec_ecp_type id)
-{
-    Sec_Eng_PKA_Reset();
-    Sec_Eng_PKA_BigEndian_Enable();
-    Sec_Eng_Trng_Enable();
+int sec_ecdh_init(sec_ecdh_handle_t *handle, sec_ecp_type id) {
+  Sec_Eng_PKA_Reset();
+  Sec_Eng_PKA_BigEndian_Enable();
+  Sec_Eng_Trng_Enable();
 
-    handle->ecpId = id;
+  handle->ecpId = id;
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdh_deinit(sec_ecdh_handle_t *handle)
-{
-    Sec_Eng_PKA_Reset();
+int sec_ecdh_deinit(sec_ecdh_handle_t *handle) {
+  Sec_Eng_PKA_Reset();
 
-    return 0;
+  return 0;
 }
 
-int sec_ecdh_get_encrypt_key(sec_ecdh_handle_t *handle, const uint32_t *pkX, const uint32_t *pkY, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy)
-{
-    return sec_ecdh_get_scalar_point(handle->ecpId, pkX, pkY, private_key, pRx, pRy);
+int sec_ecdh_get_encrypt_key(sec_ecdh_handle_t *handle, const uint32_t *pkX, const uint32_t *pkY, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy) {
+  return sec_ecdh_get_scalar_point(handle->ecpId, pkX, pkY, private_key, pRx, pRy);
 }
 
-int sec_ecdh_get_public_key(sec_ecdh_handle_t *handle, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy)
-{
-    return sec_ecdh_get_scalar_point(handle->ecpId, NULL, NULL, private_key, pRx, pRy);
+int sec_ecdh_get_public_key(sec_ecdh_handle_t *handle, const uint32_t *private_key, const uint32_t *pRx, const uint32_t *pRy) {
+  return sec_ecdh_get_scalar_point(handle->ecpId, NULL, NULL, private_key, pRx, pRy);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_hash.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_hash.c
index 736c08119..45c5de92c 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_hash.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_sec_hash.c
@@ -25,9 +25,7 @@
 
 void SEC_SHA_IRQHandler(void);
 
-static sec_hash_device_t sec_hashx_device[SEC_HASH_MAX_INDEX] = {
-    0
-};
+static sec_hash_device_t sec_hashx_device[SEC_HASH_MAX_INDEX] = {0};
 
 static SEC_Eng_SHA256_Ctx shaCtx;
 
@@ -40,37 +38,36 @@ static SEC_Eng_SHA256_Ctx sha256Ctx;
  * @param oflag
  * @return int
  */
-int sec_hash_open(struct device *dev, uint16_t oflag)
-{
-    sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
-    int ret = 0;
-
-    switch (sec_hash_device->type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            Sec_Eng_SHA256_Init(&shaCtx, SEC_ENG_SHA_ID0, SEC_ENG_SHA224, sec_hash_device->shaBuf, sec_hash_device->shaPadding);
-            Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
-            break;
-
-        case SEC_HASH_SHA256:
-            Sec_Eng_SHA256_Init(&shaCtx, SEC_ENG_SHA_ID0, SEC_ENG_SHA256, sec_hash_device->shaBuf, sec_hash_device->shaPadding);
-            Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_open(struct device *dev, uint16_t oflag) {
+  sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
+  int                ret             = 0;
+
+  switch (sec_hash_device->type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    Sec_Eng_SHA256_Init(&shaCtx, SEC_ENG_SHA_ID0, SEC_ENG_SHA224, sec_hash_device->shaBuf, sec_hash_device->shaPadding);
+    Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
+    break;
+
+  case SEC_HASH_SHA256:
+    Sec_Eng_SHA256_Init(&shaCtx, SEC_ENG_SHA_ID0, SEC_ENG_SHA256, sec_hash_device->shaBuf, sec_hash_device->shaPadding);
+    Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 /**
  * @brief
@@ -78,11 +75,10 @@ int sec_hash_open(struct device *dev, uint16_t oflag)
  * @param dev
  * @return int
  */
-int sec_hash_close(struct device *dev)
-{
-    //sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
-    //memset(sec_hash_device, 0, sizeof(sec_hash_device_t)); //will cause crash
-    return 0;
+int sec_hash_close(struct device *dev) {
+  // sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
+  // memset(sec_hash_device, 0, sizeof(sec_hash_device_t)); //will cause crash
+  return 0;
 }
 /**
  * @brief
@@ -92,10 +88,7 @@ int sec_hash_close(struct device *dev)
  * @param args
  * @return int
  */
-int sec_hash_control(struct device *dev, int cmd, void *args)
-{
-    return 0;
-}
+int sec_hash_control(struct device *dev, int cmd, void *args) { return 0; }
 
 /**
  * @brief
@@ -106,35 +99,34 @@ int sec_hash_control(struct device *dev, int cmd, void *args)
  * @param size
  * @return int
  */
-int sec_hash_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size)
-{
-    sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
-    int ret = 0;
-
-    switch (sec_hash_device->type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            Sec_Eng_SHA256_Update(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
-            break;
-
-        case SEC_HASH_SHA256:
-            Sec_Eng_SHA256_Update(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) {
+  sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
+  int                ret             = 0;
+
+  switch (sec_hash_device->type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    Sec_Eng_SHA256_Update(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
+    break;
+
+  case SEC_HASH_SHA256:
+    Sec_Eng_SHA256_Update(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 
 /**
@@ -146,37 +138,36 @@ int sec_hash_write(struct device *dev, uint32_t pos, const void *buffer, uint32_
  * @param size
  * @return int
  */
-int sec_hash_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
-{
-    sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
-    int ret = 0;
-
-    switch (sec_hash_device->type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            Sec_Eng_SHA256_Finish(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
-            ret = 28;
-            break;
-
-        case SEC_HASH_SHA256:
-            Sec_Eng_SHA256_Finish(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
-            ret = 32;
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) {
+  sec_hash_device_t *sec_hash_device = (sec_hash_device_t *)dev;
+  int                ret             = 0;
+
+  switch (sec_hash_device->type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    Sec_Eng_SHA256_Finish(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
+    ret = 28;
+    break;
+
+  case SEC_HASH_SHA256:
+    Sec_Eng_SHA256_Finish(&shaCtx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
+    ret = 32;
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 
 /**
@@ -186,38 +177,37 @@ int sec_hash_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
  * @param type
  * @return int
  */
-int sec_hash_init(sec_hash_handle_t *handle, uint8_t type)
-{
-    int ret = 0;
-
-    switch (type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            handle->type = type;
-            Sec_Eng_SHA256_Init(&sha256Ctx, SEC_ENG_SHA_ID0, SEC_ENG_SHA224, handle->shaBuf, handle->shaPadding);
-            Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
-            break;
-
-        case SEC_HASH_SHA256:
-            handle->type = type;
-            Sec_Eng_SHA256_Init(&sha256Ctx, SEC_ENG_SHA_ID0, SEC_ENG_SHA256, handle->shaBuf, handle->shaPadding);
-            Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_init(sec_hash_handle_t *handle, uint8_t type) {
+  int ret = 0;
+
+  switch (type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    handle->type = type;
+    Sec_Eng_SHA256_Init(&sha256Ctx, SEC_ENG_SHA_ID0, SEC_ENG_SHA224, handle->shaBuf, handle->shaPadding);
+    Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
+    break;
+
+  case SEC_HASH_SHA256:
+    handle->type = type;
+    Sec_Eng_SHA256_Init(&sha256Ctx, SEC_ENG_SHA_ID0, SEC_ENG_SHA256, handle->shaBuf, handle->shaPadding);
+    Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0);
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 /**
  * @brief
@@ -225,12 +215,11 @@ int sec_hash_init(sec_hash_handle_t *handle, uint8_t type)
  * @param handle
  * @return int
  */
-int sec_hash_deinit(sec_hash_handle_t *handle)
-{
-    memset(handle->shaBuf, 0, sizeof(handle->shaBuf));
-    memset(handle->shaPadding, 0, sizeof(handle->shaPadding));
+int sec_hash_deinit(sec_hash_handle_t *handle) {
+  memset(handle->shaBuf, 0, sizeof(handle->shaBuf));
+  memset(handle->shaPadding, 0, sizeof(handle->shaPadding));
 
-    return 0;
+  return 0;
 }
 
 /**
@@ -241,34 +230,33 @@ int sec_hash_deinit(sec_hash_handle_t *handle)
  * @param size
  * @return int
  */
-int sec_hash_update(sec_hash_handle_t *handle, const void *buffer, uint32_t size)
-{
-    int ret = 0;
-
-    switch (handle->type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            Sec_Eng_SHA256_Update(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
-            break;
-
-        case SEC_HASH_SHA256:
-            Sec_Eng_SHA256_Update(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_update(sec_hash_handle_t *handle, const void *buffer, uint32_t size) {
+  int ret = 0;
+
+  switch (handle->type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    Sec_Eng_SHA256_Update(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
+    break;
+
+  case SEC_HASH_SHA256:
+    Sec_Eng_SHA256_Update(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer, size);
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 
 /**
@@ -278,36 +266,35 @@ int sec_hash_update(sec_hash_handle_t *handle, const void *buffer, uint32_t size
  * @param buffer
  * @return int
  */
-int sec_hash_finish(sec_hash_handle_t *handle, void *buffer)
-{
-    int ret = 0;
-
-    switch (handle->type) {
-        case SEC_HASH_SHA1:
-            ret = -1;
-            break;
-
-        case SEC_HASH_SHA224:
-            Sec_Eng_SHA256_Finish(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
-            ret = 28;
-            break;
-
-        case SEC_HASH_SHA256:
-            Sec_Eng_SHA256_Finish(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
-            ret = 32;
-            break;
-
-        case SEC_HASH_SHA384:
-        case SEC_HASH_SHA512:
-            ret = -1;
-            break;
-
-        default:
-            ret = -1;
-            break;
-    }
-
-    return ret;
+int sec_hash_finish(sec_hash_handle_t *handle, void *buffer) {
+  int ret = 0;
+
+  switch (handle->type) {
+  case SEC_HASH_SHA1:
+    ret = -1;
+    break;
+
+  case SEC_HASH_SHA224:
+    Sec_Eng_SHA256_Finish(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
+    ret = 28;
+    break;
+
+  case SEC_HASH_SHA256:
+    Sec_Eng_SHA256_Finish(&sha256Ctx, SEC_ENG_SHA_ID0, (uint8_t *)buffer);
+    ret = 32;
+    break;
+
+  case SEC_HASH_SHA384:
+  case SEC_HASH_SHA512:
+    ret = -1;
+    break;
+
+  default:
+    ret = -1;
+    break;
+  }
+
+  return ret;
 }
 
 /**
@@ -319,27 +306,26 @@ int sec_hash_finish(sec_hash_handle_t *handle, void *buffer)
  * @param flag
  * @return int
  */
-static int sec_hash_sha_register(enum sec_hash_index_type index, enum sec_hash_type type, const char *name)
-{
-    struct device *dev;
+static int sec_hash_sha_register(enum sec_hash_index_type index, enum sec_hash_type type, const char *name) {
+  struct device *dev;
 
-    if (SEC_HASH_MAX_INDEX == 0) {
-        return -DEVICE_EINVAL;
-    }
+  if (SEC_HASH_MAX_INDEX == 0) {
+    return -DEVICE_EINVAL;
+  }
 
-    dev = &(sec_hashx_device[index].parent);
-    sec_hashx_device[index].type = type;
+  dev                          = &(sec_hashx_device[index].parent);
+  sec_hashx_device[index].type = type;
 
-    dev->open = sec_hash_open;
-    dev->close = sec_hash_close;
-    dev->control = sec_hash_control;
-    dev->write = sec_hash_write;
-    dev->read = sec_hash_read;
+  dev->open    = sec_hash_open;
+  dev->close   = sec_hash_close;
+  dev->control = sec_hash_control;
+  dev->write   = sec_hash_write;
+  dev->read    = sec_hash_read;
 
-    dev->type = DEVICE_CLASS_SEC_HASH;
-    dev->handle = NULL;
+  dev->type   = DEVICE_CLASS_SEC_HASH;
+  dev->handle = NULL;
 
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 
 /**
@@ -350,10 +336,7 @@ static int sec_hash_sha_register(enum sec_hash_index_type index, enum sec_hash_t
  * @param flag
  * @return int
  */
-int sec_hash_sha256_register(enum sec_hash_index_type index, const char *name)
-{
-    return sec_hash_sha_register(index, SEC_HASH_SHA256, name);
-}
+int sec_hash_sha256_register(enum sec_hash_index_type index, const char *name) { return sec_hash_sha_register(index, SEC_HASH_SHA256, name); }
 
 /**
  * @brief
@@ -363,25 +346,17 @@ int sec_hash_sha256_register(enum sec_hash_index_type index, const char *name)
  * @param flag
  * @return int
  */
-int sec_hash_sha224_register(enum sec_hash_index_type index, const char *name)
-{
-    return sec_hash_sha_register(index, SEC_HASH_SHA224, name);
-}
+int sec_hash_sha224_register(enum sec_hash_index_type index, const char *name) { return sec_hash_sha_register(index, SEC_HASH_SHA224, name); }
 
 /**
  * @brief
  *
  * @param handle
  */
-void sec_hash_isr(void)
-{
-}
+void sec_hash_isr(void) {}
 
 /**
  * @brief
  *
  */
-void SEC_SHA_IRQ(void)
-{
-    sec_hash_isr();
-}
\ No newline at end of file
+void SEC_SHA_IRQ(void) { sec_hash_isr(); }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c
index 26dbe0bb8..5b7b37c05 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_uart.c
@@ -21,10 +21,10 @@
  *
  */
 #include "hal_uart.h"
-#include "hal_dma.h"
-#include "hal_clock.h"
-#include "bl702_uart.h"
 #include "bl702_glb.h"
+#include "bl702_uart.h"
+#include "hal_clock.h"
+#include "hal_dma.h"
 #include "uart_config.h"
 
 #ifdef BSP_USING_UART0
@@ -49,71 +49,72 @@ static uart_device_t uartx_device[UART_MAX_INDEX] = {
  * @param oflag
  * @return int
  */
-int uart_open(struct device *dev, uint16_t oflag)
-{
-    uart_device_t *uart_device = (uart_device_t *)dev;
-    UART_FifoCfg_Type fifoCfg = { 0 };
-    UART_CFG_Type uart_cfg = { 0 };
-
-    /* disable all interrupt */
-    UART_IntMask(uart_device->id, UART_INT_ALL, MASK);
-    /* disable uart before config */
-    UART_Disable(uart_device->id, UART_TXRX);
-
-    uint32_t uart_clk = peripheral_clock_get(PERIPHERAL_CLOCK_UART);
-    uart_cfg.baudRate = uart_device->baudrate;
-    uart_cfg.dataBits = uart_device->databits;
-    uart_cfg.stopBits = uart_device->stopbits;
-    uart_cfg.parity = uart_device->parity;
-    uart_cfg.uartClk = uart_clk;
-    uart_cfg.ctsFlowControl = UART_CTS_FLOWCONTROL_ENABLE;
-    uart_cfg.rtsSoftwareControl = UART_RTS_FLOWCONTROL_ENABLE;
-    uart_cfg.byteBitInverse = UART_MSB_FIRST_ENABLE;
-    uart_cfg.txSoftwareControl = UART_TX_SWCONTROL_ENABLE;
-    uart_cfg.txLinMode = UART_TX_LINMODE_ENABLE;
-    uart_cfg.rxLinMode = UART_RX_LINMODE_ENABLE;
-    uart_cfg.txBreakBitCnt = UART_TX_BREAKBIT_CNT;
-    uart_cfg.rxDeglitch = ENABLE;
-
-    /* uart init with default configuration */
-    UART_Init(uart_device->id, &uart_cfg);
-
-    /* Enable tx free run mode */
-    UART_TxFreeRun(uart_device->id, ENABLE);
-    /*set de-glitch function cycle count value*/
-    UART_SetDeglitchCount(uart_device->id, 2);
-
-    /* Set rx time-out value */
-    UART_SetRxTimeoutValue(uart_device->id, UART_DEFAULT_RTO_TIMEOUT);
-
-    fifoCfg.txFifoDmaThreshold = uart_device->fifo_threshold;
-    fifoCfg.txFifoDmaEnable = DISABLE;
-    fifoCfg.rxFifoDmaThreshold = uart_device->fifo_threshold;
-    fifoCfg.rxFifoDmaEnable = DISABLE;
-
-    if (oflag & DEVICE_OFLAG_STREAM_TX) {
-    }
-    if ((oflag & DEVICE_OFLAG_INT_TX) || (oflag & DEVICE_OFLAG_INT_RX)) {
+int uart_open(struct device *dev, uint16_t oflag) {
+  uart_device_t    *uart_device = (uart_device_t *)dev;
+  UART_FifoCfg_Type fifoCfg     = {0};
+  UART_CFG_Type     uart_cfg    = {0};
+
+  /* disable all interrupt */
+  UART_IntMask(uart_device->id, UART_INT_ALL, MASK);
+  /* disable uart before config */
+  UART_Disable(uart_device->id, UART_TXRX);
+
+  uint32_t uart_clk           = peripheral_clock_get(PERIPHERAL_CLOCK_UART);
+  uart_cfg.baudRate           = uart_device->baudrate;
+  uart_cfg.dataBits           = uart_device->databits;
+  uart_cfg.stopBits           = uart_device->stopbits;
+  uart_cfg.parity             = uart_device->parity;
+  uart_cfg.uartClk            = uart_clk;
+  uart_cfg.ctsFlowControl     = UART_CTS_FLOWCONTROL_ENABLE;
+  uart_cfg.rtsSoftwareControl = UART_RTS_FLOWCONTROL_ENABLE;
+  uart_cfg.byteBitInverse     = UART_MSB_FIRST_ENABLE;
+  uart_cfg.txSoftwareControl  = UART_TX_SWCONTROL_ENABLE;
+  uart_cfg.txLinMode          = UART_TX_LINMODE_ENABLE;
+  uart_cfg.rxLinMode          = UART_RX_LINMODE_ENABLE;
+  uart_cfg.txBreakBitCnt      = UART_TX_BREAKBIT_CNT;
+  uart_cfg.rxDeglitch         = ENABLE;
+
+  /* uart init with default configuration */
+  UART_Init(uart_device->id, &uart_cfg);
+
+  /* Enable tx free run mode */
+  UART_TxFreeRun(uart_device->id, ENABLE);
+  /*set de-glitch function cycle count value*/
+  UART_SetDeglitchCount(uart_device->id, 2);
+
+  /* Set rx time-out value */
+  UART_SetRxTimeoutValue(uart_device->id, UART_DEFAULT_RTO_TIMEOUT);
+
+  fifoCfg.txFifoDmaThreshold = uart_device->fifo_threshold;
+  fifoCfg.txFifoDmaEnable    = DISABLE;
+  fifoCfg.rxFifoDmaThreshold = uart_device->fifo_threshold;
+  fifoCfg.rxFifoDmaEnable    = DISABLE;
+
+  if (oflag & DEVICE_OFLAG_STREAM_TX) {
+  }
+  if ((oflag & DEVICE_OFLAG_INT_TX) || (oflag & DEVICE_OFLAG_INT_RX)) {
 #ifdef BSP_USING_UART0
-        if (uart_device->id == UART0_ID)
-            Interrupt_Handler_Register(UART0_IRQn, UART0_IRQ);
+    if (uart_device->id == UART0_ID) {
+      Interrupt_Handler_Register(UART0_IRQn, UART0_IRQ);
+    }
 #endif
 #ifdef BSP_USING_UART1
-        if (uart_device->id == UART1_ID)
-            Interrupt_Handler_Register(UART1_IRQn, UART1_IRQ);
-#endif
-    }
-    if (oflag & DEVICE_OFLAG_DMA_TX) {
-        fifoCfg.txFifoDmaEnable = ENABLE;
-    }
-    if (oflag & DEVICE_OFLAG_DMA_RX) {
-        fifoCfg.rxFifoDmaEnable = ENABLE;
+    if (uart_device->id == UART1_ID) {
+      Interrupt_Handler_Register(UART1_IRQn, UART1_IRQ);
     }
-
-    UART_FifoConfig(uart_device->id, &fifoCfg);
-    /* enable uart */
-    UART_Enable(uart_device->id, UART_TXRX);
-    return 0;
+#endif
+  }
+  if (oflag & DEVICE_OFLAG_DMA_TX) {
+    fifoCfg.txFifoDmaEnable = ENABLE;
+  }
+  if (oflag & DEVICE_OFLAG_DMA_RX) {
+    fifoCfg.rxFifoDmaEnable = ENABLE;
+  }
+
+  UART_FifoConfig(uart_device->id, &fifoCfg);
+  /* enable uart */
+  UART_Enable(uart_device->id, UART_TXRX);
+  return 0;
 }
 /**
  * @brief
@@ -121,17 +122,16 @@ int uart_open(struct device *dev, uint16_t oflag)
  * @param dev
  * @return int
  */
-int uart_close(struct device *dev)
-{
-    uart_device_t *uart_device = (uart_device_t *)dev;
-
-    UART_Disable(uart_device->id, UART_TXRX);
-    if (uart_device->id == 0) {
-        GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0);
-    } else if (uart_device->id == 1) {
-        GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1);
-    }
-    return 0;
+int uart_close(struct device *dev) {
+  uart_device_t *uart_device = (uart_device_t *)dev;
+
+  UART_Disable(uart_device->id, UART_TXRX);
+  if (uart_device->id == 0) {
+    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0);
+  } else if (uart_device->id == 1) {
+    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1);
+  }
+  return 0;
 }
 /**
  * @brief
@@ -141,123 +141,124 @@ int uart_close(struct device *dev)
  * @param args
  * @return int
  */
-int uart_control(struct device *dev, int cmd, void *args)
-{
-    uart_device_t *uart_device = (uart_device_t *)dev;
-
-    switch (cmd) {
-        case DEVICE_CTRL_SET_INT /* constant-expression */: {
-            uint32_t offset = __builtin_ctz((uint32_t)args);
-            while (offset < 9) {
-                if ((uint32_t)args & (1 << offset)) {
-                    UART_IntMask(uart_device->id, offset, UNMASK);
-                }
-                offset++;
-            }
-            if (uart_device->id == UART0_ID)
-                CPU_Interrupt_Enable(UART0_IRQn);
-            else if (uart_device->id == UART1_ID)
-                CPU_Interrupt_Enable(UART1_IRQn);
-
-            break;
-        }
-        case DEVICE_CTRL_CLR_INT /* constant-expression */: {
-            uint32_t offset = __builtin_ctz((uint32_t)args);
-            while (offset < 9) {
-                if ((uint32_t)args & (1 << offset)) {
-                    UART_IntMask(uart_device->id, offset, MASK);
-                }
-                offset++;
-            }
-            if (uart_device->id == UART0_ID)
-                CPU_Interrupt_Disable(UART0_IRQn);
-            else if (uart_device->id == UART1_ID)
-                CPU_Interrupt_Disable(UART1_IRQn);
-
-            break;
-        }
-        case DEVICE_CTRL_GET_INT /* constant-expression */:
-            /* code */
-            break;
-        case DEVICE_CTRL_RESUME /* constant-expression */:
-            UART_Enable(uart_device->id, UART_TXRX);
-            break;
-        case DEVICE_CTRL_SUSPEND /* constant-expression */:
-            UART_Disable(uart_device->id, UART_TXRX);
-            break;
-        case DEVICE_CTRL_CONFIG /* constant-expression */: {
-            uart_param_cfg_t *cfg = (uart_param_cfg_t *)args;
-            UART_CFG_Type uart_cfg;
-
-            uint32_t uart_clk = peripheral_clock_get(PERIPHERAL_CLOCK_UART);
-
-            uart_cfg.uartClk = uart_clk;
-            uart_cfg.baudRate = cfg->baudrate;
-            uart_cfg.stopBits = cfg->stopbits;
-            uart_cfg.parity = cfg->parity;
-            uart_cfg.dataBits = cfg->databits;
-            uart_cfg.ctsFlowControl = UART_CTS_FLOWCONTROL_ENABLE;
-            uart_cfg.rtsSoftwareControl = UART_RTS_FLOWCONTROL_ENABLE;
-            uart_cfg.byteBitInverse = UART_MSB_FIRST_ENABLE;
-            uart_cfg.txSoftwareControl = UART_TX_SWCONTROL_ENABLE;
-            uart_cfg.txLinMode = UART_TX_LINMODE_ENABLE;
-            uart_cfg.rxLinMode = UART_RX_LINMODE_ENABLE;
-            uart_cfg.txBreakBitCnt = UART_TX_BREAKBIT_CNT;
-            uart_cfg.rxDeglitch = ENABLE;
-            UART_Init(uart_device->id, &uart_cfg);
-            /*set de-glitch function cycle count value*/
-            UART_SetDeglitchCount(uart_device->id, 2);
-            break;
-        }
-        case DEVICE_CTRL_GET_CONFIG /* constant-expression */:
-            break;
-        case DEVICE_CTRL_ATTACH_TX_DMA /* constant-expression */:
-            uart_device->tx_dma = (struct device *)args;
-            break;
-        case DEVICE_CTRL_ATTACH_RX_DMA /* constant-expression */:
-            uart_device->rx_dma = (struct device *)args;
-            break;
-        case DEVICE_CTRL_TX_DMA_SUSPEND: {
-            uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_TX_EN);
-            BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
-            dev->oflag &= ~DEVICE_OFLAG_DMA_TX;
-            break;
-        }
-        case DEVICE_CTRL_RX_DMA_SUSPEND: {
-            uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_RX_EN);
-            BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
-            dev->oflag &= ~DEVICE_OFLAG_DMA_RX;
-            break;
-        }
-        case DEVICE_CTRL_TX_DMA_RESUME: {
-            uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
-            tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_TX_EN);
-            BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
-            dev->oflag |= DEVICE_OFLAG_DMA_TX;
-            break;
-        }
-        case DEVICE_CTRL_RX_DMA_RESUME: {
-            uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
-            tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_RX_EN);
-            BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
-            dev->oflag |= DEVICE_OFLAG_DMA_RX;
-            break;
-        }
-        case DEVICE_CTRL_UART_GET_TX_FIFO /* constant-expression */:
-            return UART_GetTxFifoCount(uart_device->id);
-        case DEVICE_CTRL_UART_GET_RX_FIFO /* constant-expression */:
-            return UART_GetRxFifoCount(uart_device->id);
-        case DEVICE_CTRL_UART_CLEAR_TX_FIFO /* constant-expression */:
-            return UART_TxFifoClear(uart_device->id);
-        case DEVICE_CTRL_UART_CLEAR_RX_FIFO /* constant-expression */:
-            return UART_RxFifoClear(uart_device->id);
-        default:
-            break;
+int uart_control(struct device *dev, int cmd, void *args) {
+  uart_device_t *uart_device = (uart_device_t *)dev;
+
+  switch (cmd) {
+  case DEVICE_CTRL_SET_INT /* constant-expression */: {
+    uint32_t offset = __builtin_ctz((uint32_t)args);
+    while (offset < 9) {
+      if ((uint32_t)args & (1 << offset)) {
+        UART_IntMask(uart_device->id, offset, UNMASK);
+      }
+      offset++;
+    }
+    if (uart_device->id == UART0_ID) {
+      CPU_Interrupt_Enable(UART0_IRQn);
+    } else if (uart_device->id == UART1_ID) {
+      CPU_Interrupt_Enable(UART1_IRQn);
+    }
+
+    break;
+  }
+  case DEVICE_CTRL_CLR_INT /* constant-expression */: {
+    uint32_t offset = __builtin_ctz((uint32_t)args);
+    while (offset < 9) {
+      if ((uint32_t)args & (1 << offset)) {
+        UART_IntMask(uart_device->id, offset, MASK);
+      }
+      offset++;
+    }
+    if (uart_device->id == UART0_ID) {
+      CPU_Interrupt_Disable(UART0_IRQn);
+    } else if (uart_device->id == UART1_ID) {
+      CPU_Interrupt_Disable(UART1_IRQn);
     }
 
-    return 0;
+    break;
+  }
+  case DEVICE_CTRL_GET_INT /* constant-expression */:
+    /* code */
+    break;
+  case DEVICE_CTRL_RESUME /* constant-expression */:
+    UART_Enable(uart_device->id, UART_TXRX);
+    break;
+  case DEVICE_CTRL_SUSPEND /* constant-expression */:
+    UART_Disable(uart_device->id, UART_TXRX);
+    break;
+  case DEVICE_CTRL_CONFIG /* constant-expression */: {
+    uart_param_cfg_t *cfg = (uart_param_cfg_t *)args;
+    UART_CFG_Type     uart_cfg;
+
+    uint32_t uart_clk = peripheral_clock_get(PERIPHERAL_CLOCK_UART);
+
+    uart_cfg.uartClk            = uart_clk;
+    uart_cfg.baudRate           = cfg->baudrate;
+    uart_cfg.stopBits           = cfg->stopbits;
+    uart_cfg.parity             = cfg->parity;
+    uart_cfg.dataBits           = cfg->databits;
+    uart_cfg.ctsFlowControl     = UART_CTS_FLOWCONTROL_ENABLE;
+    uart_cfg.rtsSoftwareControl = UART_RTS_FLOWCONTROL_ENABLE;
+    uart_cfg.byteBitInverse     = UART_MSB_FIRST_ENABLE;
+    uart_cfg.txSoftwareControl  = UART_TX_SWCONTROL_ENABLE;
+    uart_cfg.txLinMode          = UART_TX_LINMODE_ENABLE;
+    uart_cfg.rxLinMode          = UART_RX_LINMODE_ENABLE;
+    uart_cfg.txBreakBitCnt      = UART_TX_BREAKBIT_CNT;
+    uart_cfg.rxDeglitch         = ENABLE;
+    UART_Init(uart_device->id, &uart_cfg);
+    /*set de-glitch function cycle count value*/
+    UART_SetDeglitchCount(uart_device->id, 2);
+    break;
+  }
+  case DEVICE_CTRL_GET_CONFIG /* constant-expression */:
+    break;
+  case DEVICE_CTRL_ATTACH_TX_DMA /* constant-expression */:
+    uart_device->tx_dma = (struct device *)args;
+    break;
+  case DEVICE_CTRL_ATTACH_RX_DMA /* constant-expression */:
+    uart_device->rx_dma = (struct device *)args;
+    break;
+  case DEVICE_CTRL_TX_DMA_SUSPEND: {
+    uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
+    tmpVal          = BL_CLR_REG_BIT(tmpVal, UART_DMA_TX_EN);
+    BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
+    dev->oflag &= ~DEVICE_OFLAG_DMA_TX;
+    break;
+  }
+  case DEVICE_CTRL_RX_DMA_SUSPEND: {
+    uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
+    tmpVal          = BL_CLR_REG_BIT(tmpVal, UART_DMA_RX_EN);
+    BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
+    dev->oflag &= ~DEVICE_OFLAG_DMA_RX;
+    break;
+  }
+  case DEVICE_CTRL_TX_DMA_RESUME: {
+    uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
+    tmpVal          = BL_SET_REG_BIT(tmpVal, UART_DMA_TX_EN);
+    BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
+    dev->oflag |= DEVICE_OFLAG_DMA_TX;
+    break;
+  }
+  case DEVICE_CTRL_RX_DMA_RESUME: {
+    uint32_t tmpVal = BL_RD_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0);
+    tmpVal          = BL_SET_REG_BIT(tmpVal, UART_DMA_RX_EN);
+    BL_WR_REG(UART0_BASE + uart_device->id * 0x100, UART_FIFO_CONFIG_0, tmpVal);
+    dev->oflag |= DEVICE_OFLAG_DMA_RX;
+    break;
+  }
+  case DEVICE_CTRL_UART_GET_TX_FIFO /* constant-expression */:
+    return UART_GetTxFifoCount(uart_device->id);
+  case DEVICE_CTRL_UART_GET_RX_FIFO /* constant-expression */:
+    return UART_GetRxFifoCount(uart_device->id);
+  case DEVICE_CTRL_UART_CLEAR_TX_FIFO /* constant-expression */:
+    return UART_TxFifoClear(uart_device->id);
+  case DEVICE_CTRL_UART_CLEAR_RX_FIFO /* constant-expression */:
+    return UART_RxFifoClear(uart_device->id);
+  default:
+    break;
+  }
+
+  return 0;
 }
 /**
  * @brief
@@ -268,27 +269,28 @@ int uart_control(struct device *dev, int cmd, void *args)
  * @param size
  * @return int
  */
-int uart_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size)
-{
-    int ret = 0;
-    uart_device_t *uart_device = (uart_device_t *)dev;
-    if (dev->oflag & DEVICE_OFLAG_DMA_TX) {
-        struct device *dma_ch = (struct device *)uart_device->tx_dma;
-        if (!dma_ch)
-            return -1;
-
-        if (uart_device->id == 0) {
-            ret = dma_reload(dma_ch, (uint32_t)buffer, (uint32_t)DMA_ADDR_UART0_TDR, size);
-            dma_channel_start(dma_ch);
-        } else if (uart_device->id == 1) {
-            ret = dma_reload(dma_ch, (uint32_t)buffer, (uint32_t)DMA_ADDR_UART1_TDR, size);
-            dma_channel_start(dma_ch);
-        }
-        return ret;
-    } else if (dev->oflag & DEVICE_OFLAG_INT_TX) {
-        return -2;
-    } else
-        return UART_SendData(uart_device->id, (uint8_t *)buffer, size);
+int uart_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) {
+  int            ret         = 0;
+  uart_device_t *uart_device = (uart_device_t *)dev;
+  if (dev->oflag & DEVICE_OFLAG_DMA_TX) {
+    struct device *dma_ch = (struct device *)uart_device->tx_dma;
+    if (!dma_ch) {
+      return -1;
+    }
+
+    if (uart_device->id == 0) {
+      ret = dma_reload(dma_ch, (uint32_t)buffer, (uint32_t)DMA_ADDR_UART0_TDR, size);
+      dma_channel_start(dma_ch);
+    } else if (uart_device->id == 1) {
+      ret = dma_reload(dma_ch, (uint32_t)buffer, (uint32_t)DMA_ADDR_UART1_TDR, size);
+      dma_channel_start(dma_ch);
+    }
+    return ret;
+  } else if (dev->oflag & DEVICE_OFLAG_INT_TX) {
+    return -2;
+  } else {
+    return UART_SendData(uart_device->id, (uint8_t *)buffer, size);
+  }
 }
 /**
  * @brief
@@ -299,28 +301,28 @@ int uart_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t si
  * @param size
  * @return int
  */
-int uart_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
-{
-    int ret = -1;
-    uart_device_t *uart_device = (uart_device_t *)dev;
-    if (dev->oflag & DEVICE_OFLAG_DMA_RX) {
-        struct device *dma_ch = (struct device *)uart_device->rx_dma;
-        if (!dma_ch)
-            return -1;
-
-        if (uart_device->id == 0) {
-            ret = dma_reload(dma_ch, (uint32_t)DMA_ADDR_UART0_RDR, (uint32_t)buffer, size);
-            dma_channel_start(dma_ch);
-        } else if (uart_device->id == 1) {
-            ret = dma_reload(dma_ch, (uint32_t)DMA_ADDR_UART1_RDR, (uint32_t)buffer, size);
-            dma_channel_start(dma_ch);
-        }
-        return ret;
-    } else if (dev->oflag & DEVICE_OFLAG_INT_RX) {
-        return -2;
-    } else {
-        return UART_ReceiveData(uart_device->id, (uint8_t *)buffer, size);
+int uart_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) {
+  int            ret         = -1;
+  uart_device_t *uart_device = (uart_device_t *)dev;
+  if (dev->oflag & DEVICE_OFLAG_DMA_RX) {
+    struct device *dma_ch = (struct device *)uart_device->rx_dma;
+    if (!dma_ch) {
+      return -1;
     }
+
+    if (uart_device->id == 0) {
+      ret = dma_reload(dma_ch, (uint32_t)DMA_ADDR_UART0_RDR, (uint32_t)buffer, size);
+      dma_channel_start(dma_ch);
+    } else if (uart_device->id == 1) {
+      ret = dma_reload(dma_ch, (uint32_t)DMA_ADDR_UART1_RDR, (uint32_t)buffer, size);
+      dma_channel_start(dma_ch);
+    }
+    return ret;
+  } else if (dev->oflag & DEVICE_OFLAG_INT_RX) {
+    return -2;
+  } else {
+    return UART_ReceiveData(uart_device->id, (uint8_t *)buffer, size);
+  }
 }
 /**
  * @brief
@@ -330,94 +332,94 @@ int uart_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
  * @param flag
  * @return int
  */
-int uart_register(enum uart_index_type index, const char *name)
-{
-    struct device *dev;
+int uart_register(enum uart_index_type index, const char *name) {
+  struct device *dev;
 
-    if (UART_MAX_INDEX == 0)
-        return -DEVICE_EINVAL;
+  if (UART_MAX_INDEX == 0) {
+    return -DEVICE_EINVAL;
+  }
 
-    dev = &(uartx_device[index].parent);
+  dev = &(uartx_device[index].parent);
 
-    dev->open = uart_open;
-    dev->close = uart_close;
-    dev->control = uart_control;
-    dev->write = uart_write;
-    dev->read = uart_read;
+  dev->open    = uart_open;
+  dev->close   = uart_close;
+  dev->control = uart_control;
+  dev->write   = uart_write;
+  dev->read    = uart_read;
 
-    dev->type = DEVICE_CLASS_UART;
-    dev->handle = NULL;
+  dev->type   = DEVICE_CLASS_UART;
+  dev->handle = NULL;
 
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 /**
  * @brief
  *
  * @param handle
  */
-void uart_isr(uart_device_t *handle)
-{
-    uint32_t tmpVal = 0;
-    uint32_t maskVal = 0;
-    uint32_t UARTx = (UART0_BASE + handle->id * 0x100);
-
-    tmpVal = BL_RD_REG(UARTx, UART_INT_STS);
-    maskVal = BL_RD_REG(UARTx, UART_INT_MASK);
-
-    if (!handle->parent.callback)
-        return;
-
-    /* Length of uart tx data transfer arrived interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_END_MASK)) {
-        BL_WR_REG(UARTx, UART_INT_CLEAR, 0x1);
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_END);
-    }
-
-    /* Length of uart rx data transfer arrived interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_END_MASK)) {
-        BL_WR_REG(UARTx, UART_INT_CLEAR, 0x2);
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_RX_END);
-    }
-
-    /* Tx fifo ready interrupt,auto-cleared when data is pushed */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FIFO_MASK)) {
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_FIFO);
-    }
-
-    /* Rx fifo ready interrupt,auto-cleared when data is popped */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FIFO_MASK)) {
-        uint8_t buffer[UART_FIFO_MAX_LEN];
-        uint8_t len = UART_ReceiveData(handle->id, buffer, UART_FIFO_MAX_LEN);
-        if (len) {
-            handle->parent.callback(&handle->parent, &buffer[0], len, UART_EVENT_RX_FIFO);
-        }
-    }
-
-    /* Rx time-out interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_RTO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_RTO_MASK)) {
-        BL_WR_REG(UARTx, UART_INT_CLEAR, 0x10);
-        uint8_t buffer[UART_FIFO_MAX_LEN];
-        uint8_t len = UART_ReceiveData(handle->id, buffer, UART_FIFO_MAX_LEN);
-        if (len) {
-            handle->parent.callback(&handle->parent, &buffer[0], len, UART_EVENT_RTO);
-        }
-    }
-
-    /* Rx parity check error interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_PCE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_PCE_MASK)) {
-        BL_WR_REG(UARTx, UART_INT_CLEAR, 0x20);
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_PCE);
-    }
-
-    /* Tx fifo overflow/underflow error interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FER_MASK)) {
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_FER);
+void uart_isr(uart_device_t *handle) {
+  uint32_t tmpVal  = 0;
+  uint32_t maskVal = 0;
+  uint32_t UARTx   = (UART0_BASE + handle->id * 0x100);
+
+  tmpVal  = BL_RD_REG(UARTx, UART_INT_STS);
+  maskVal = BL_RD_REG(UARTx, UART_INT_MASK);
+
+  if (!handle->parent.callback) {
+    return;
+  }
+
+  /* Length of uart tx data transfer arrived interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_END_MASK)) {
+    BL_WR_REG(UARTx, UART_INT_CLEAR, 0x1);
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_END);
+  }
+
+  /* Length of uart rx data transfer arrived interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_END_MASK)) {
+    BL_WR_REG(UARTx, UART_INT_CLEAR, 0x2);
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_RX_END);
+  }
+
+  /* Tx fifo ready interrupt,auto-cleared when data is pushed */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FIFO_MASK)) {
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_FIFO);
+  }
+
+  /* Rx fifo ready interrupt,auto-cleared when data is popped */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FIFO_MASK)) {
+    uint8_t buffer[UART_FIFO_MAX_LEN];
+    uint8_t len = UART_ReceiveData(handle->id, buffer, UART_FIFO_MAX_LEN);
+    if (len) {
+      handle->parent.callback(&handle->parent, &buffer[0], len, UART_EVENT_RX_FIFO);
     }
-
-    /* Rx fifo overflow/underflow error interrupt */
-    if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FER_MASK)) {
-        handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_RX_FER);
+  }
+
+  /* Rx time-out interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_RTO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_RTO_MASK)) {
+    BL_WR_REG(UARTx, UART_INT_CLEAR, 0x10);
+    uint8_t buffer[UART_FIFO_MAX_LEN];
+    uint8_t len = UART_ReceiveData(handle->id, buffer, UART_FIFO_MAX_LEN);
+    if (len) {
+      handle->parent.callback(&handle->parent, &buffer[0], len, UART_EVENT_RTO);
     }
+  }
+
+  /* Rx parity check error interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_PCE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_PCE_MASK)) {
+    BL_WR_REG(UARTx, UART_INT_CLEAR, 0x20);
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_PCE);
+  }
+
+  /* Tx fifo overflow/underflow error interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FER_MASK)) {
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_TX_FER);
+  }
+
+  /* Rx fifo overflow/underflow error interrupt */
+  if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FER_MASK)) {
+    handle->parent.callback(&handle->parent, NULL, 0, UART_EVENT_RX_FER);
+  }
 }
 
 #ifdef BSP_USING_UART0
@@ -425,18 +427,12 @@ void uart_isr(uart_device_t *handle)
  * @brief
  *
  */
-void UART0_IRQ(void)
-{
-    uart_isr(&uartx_device[UART0_INDEX]);
-}
+void UART0_IRQ(void) { uart_isr(&uartx_device[UART0_INDEX]); }
 #endif
 #ifdef BSP_USING_UART1
 /**
  * @brief
  *
  */
-void UART1_IRQ(void)
-{
-    uart_isr(&uartx_device[UART1_INDEX]);
-}
+void UART1_IRQ(void) { uart_isr(&uartx_device[UART1_INDEX]); }
 #endif
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c
index 6e925f2a2..7c744b1a4 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_usb.c
@@ -21,182 +21,175 @@
  *
  */
 #include "hal_usb.h"
+#include "bl702_dma.h"
+#include "bl702_glb.h"
+#include "bl702_usb.h"
 #include "hal_dma.h"
 #include "hal_mtimer.h"
-#include "bl702_usb.h"
-#include "bl702_glb.h"
 
 #define USE_INTERNAL_TRANSCEIVER
-//#define ENABLE_LPM_INT
-//#define ENABLE_SOF3MS_INT
-//#define ENABLE_ERROR_INT
+// #define ENABLE_LPM_INT
+// #define ENABLE_SOF3MS_INT
+// #define ENABLE_ERROR_INT
 
 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
 
-#define USB_DC_LOG_WRN(a, ...) //bflb_platform_printf(a, ##__VA_ARGS__)
+#define USB_DC_LOG_WRN(a, ...) // bflb_platform_printf(a, ##__VA_ARGS__)
 #define USB_DC_LOG_DBG(a, ...)
-#define USB_DC_LOG_ERR(a, ...) //bflb_platform_printf(a, ##__VA_ARGS__)
+#define USB_DC_LOG_ERR(a, ...) // bflb_platform_printf(a, ##__VA_ARGS__)
 #define USB_DC_LOG(a, ...)
 
 static usb_dc_device_t usb_fs_device;
-static void USB_FS_IRQ(void);
-
-static dma_lli_ctrl_t usb_lli_list = {
-    .src_addr = 0,
-    .dst_addr = 0,
-    .nextlli = 0,
-    .cfg.bits.fix_cnt = 0,
-    .cfg.bits.dst_min_mode = 0,
-    .cfg.bits.dst_add_mode = 0,
-    .cfg.bits.SI = 0,
-    .cfg.bits.DI = 0,
-    .cfg.bits.SWidth = DMA_TRANSFER_WIDTH_8BIT,
-    .cfg.bits.DWidth = DMA_TRANSFER_WIDTH_8BIT,
-    .cfg.bits.SBSize = 0,
-    .cfg.bits.DBSize = 0,
-    .cfg.bits.I = 0,
-    .cfg.bits.TransferSize = 0
-};
-
-static void usb_set_power_up(void)
-{
-    uint32_t tmpVal = 0;
-
-    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-    tmpVal = BL_SET_REG_BIT(tmpVal, GLB_PU_USB);
-    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+static void            USB_FS_IRQ(void);
+
+static dma_lli_ctrl_t usb_lli_list = {.src_addr              = 0,
+                                      .dst_addr              = 0,
+                                      .nextlli               = 0,
+                                      .cfg.bits.fix_cnt      = 0,
+                                      .cfg.bits.dst_min_mode = 0,
+                                      .cfg.bits.dst_add_mode = 0,
+                                      .cfg.bits.SI           = 0,
+                                      .cfg.bits.DI           = 0,
+                                      .cfg.bits.SWidth       = DMA_TRANSFER_WIDTH_8BIT,
+                                      .cfg.bits.DWidth       = DMA_TRANSFER_WIDTH_8BIT,
+                                      .cfg.bits.SBSize       = 0,
+                                      .cfg.bits.DBSize       = 0,
+                                      .cfg.bits.I            = 0,
+                                      .cfg.bits.TransferSize = 0};
+
+static void usb_set_power_up(void) {
+  uint32_t tmpVal = 0;
+
+  tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+  tmpVal = BL_SET_REG_BIT(tmpVal, GLB_PU_USB);
+  BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
 }
 
-static void usb_set_power_off(void)
-{
-    uint32_t tmpVal = 0;
+static void usb_set_power_off(void) {
+  uint32_t tmpVal = 0;
 
-    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-    tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_PU_USB);
-    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+  tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+  tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_PU_USB);
+  BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
 }
 
-static uint8_t usb_ep_is_enabled(uint8_t ep)
-{
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
-
-    /* Check if ep enabled */
-    if ((USB_EP_DIR_IS_OUT(ep)) &&
-        usb_fs_device.out_ep[ep_idx].ep_ena) {
-        return 1;
-    } else if ((USB_EP_DIR_IS_IN(ep)) &&
-               usb_fs_device.in_ep[ep_idx].ep_ena) {
-        return 1;
-    }
+static uint8_t usb_ep_is_enabled(uint8_t ep) {
+  uint8_t ep_idx = USB_EP_GET_IDX(ep);
 
-    return 0;
+  /* Check if ep enabled */
+  if ((USB_EP_DIR_IS_OUT(ep)) && usb_fs_device.out_ep[ep_idx].ep_ena) {
+    return 1;
+  } else if ((USB_EP_DIR_IS_IN(ep)) && usb_fs_device.in_ep[ep_idx].ep_ena) {
+    return 1;
+  }
+
+  return 0;
 }
 
-static void usb_xcvr_config(BL_Fun_Type NewState)
-{
-    uint32_t tmpVal = 0;
+static void usb_xcvr_config(BL_Fun_Type NewState) {
+  uint32_t tmpVal = 0;
 
-    if (NewState != DISABLE) {
+  if (NewState != DISABLE) {
 #if defined(USE_EXTERNAL_TRANSCEIVER)
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 0); //use external tranceiver
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 0); // use external tranceiver
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
 #elif defined(USE_INTERNAL_TRANSCEIVER)
 #if 1
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SUS, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SPD, 1); //0 for 1.1 ls,1 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_DATA_CONVERT, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_OEB_SEL, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_PMOS, 3);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_NMOS, 3);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_RISE, 2); //1 for 1.1 ls
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_FALL, 2); //1 for 1.1 ls
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_RISE, 2); //1 for 1.1 ls
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_FALL, 2); //1 for 1.1 ls
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_RES_PULLUP_TUNE, 5);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 1);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_P, 2);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_M, 2);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
-
-        ///* force BD=1, not use */
-        //tmpVal=BL_RD_REG(GLB_BASE,GLB_USB_XCVR);
-        //tmpVal=BL_SET_REG_BIT(tmpVal,GLB_PU_USB_LDO);
-        //BL_WR_REG(GLB_BASE,GLB_USB_XCVR,tmpVal);
-
-        /* BD_voltage_thresdhold=2.8V */
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 7);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SUS, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SPD, 1); // 0 for 1.1 ls,1 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_DATA_CONVERT, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_OEB_SEL, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_PMOS, 3);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_NMOS, 3);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_RISE, 2); // 1 for 1.1 ls
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_FALL, 2); // 1 for 1.1 ls
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_RISE, 2); // 1 for 1.1 ls
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_FALL, 2); // 1 for 1.1 ls
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_RES_PULLUP_TUNE, 5);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 1);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_P, 2);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_M, 2);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+
+    ///* force BD=1, not use */
+    // tmpVal=BL_RD_REG(GLB_BASE,GLB_USB_XCVR);
+    // tmpVal=BL_SET_REG_BIT(tmpVal,GLB_PU_USB_LDO);
+    // BL_WR_REG(GLB_BASE,GLB_USB_XCVR,tmpVal);
+
+    /* BD_voltage_thresdhold=2.8V */
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 7);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
 
 #else
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SUS, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SPD, 0); //0 for 1.1 ls,1 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_DATA_CONVERT, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_OEB_SEL, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_PMOS, 3);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_NMOS, 3);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_RISE, 1); //4 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_FALL, 1); //3 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_RISE, 1); //4 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_FALL, 1); //3 for 1.1 fs
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_RES_PULLUP_TUNE, 5);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 1);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_P, 2);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_M, 2);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SUS, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SPD, 0); // 0 for 1.1 ls,1 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_DATA_CONVERT, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_OEB_SEL, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_PMOS, 3);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ROUT_NMOS, 3);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_RISE, 1); // 4 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_P_FALL, 1); // 3 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_RISE, 1); // 4 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_SLEWRATE_M_FALL, 1); // 3 for 1.1 fs
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_RES_PULLUP_TUNE, 5);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 1);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_P, 2);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_V_HYS_M, 2);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
 #endif
 
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 1);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 1);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
 #endif
-    } else {
+  } else {
 #ifdef USE_INTERNAL_TRANSCEIVER
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 0);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 0);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
 
-        ///* force BD=1, not use */
-        //tmpVal=BL_RD_REG(GLB_BASE,GLB_USB_XCVR);
-        //tmpVal=BL_SET_REG_BIT(tmpVal,GLB_PU_USB_LDO);
-        //BL_WR_REG(GLB_BASE,GLB_USB_XCVR,tmpVal);
+    ///* force BD=1, not use */
+    // tmpVal=BL_RD_REG(GLB_BASE,GLB_USB_XCVR);
+    // tmpVal=BL_SET_REG_BIT(tmpVal,GLB_PU_USB_LDO);
+    // BL_WR_REG(GLB_BASE,GLB_USB_XCVR,tmpVal);
 
-        /* BD_voltage_thresdhold=2.8V */
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 7);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+    /* BD_voltage_thresdhold=2.8V */
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_BD_VTH, 7);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
 
 #else
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1); //use internal tranceiver
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
-
-        tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
-        tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
-        BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR_CONFIG);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_USB_USE_XCVR, 1); // use internal tranceiver
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR_CONFIG, tmpVal);
+
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_USB, 1);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
 #endif
-    }
+  }
 }
 
 /**
@@ -206,85 +199,84 @@ static void usb_xcvr_config(BL_Fun_Type NewState)
  * @param oflag
  * @return int
  */
-int usb_open(struct device *dev, uint16_t oflag)
-{
-    USB_Config_Type usbCfg = { 0 };
-
-    usb_set_power_off();
-    mtimer_delay_ms(10);
-    usb_set_power_up();
-
-    usb_xcvr_config(DISABLE);
-    usb_xcvr_config(ENABLE);
-
-    CPU_Interrupt_Disable(USB_IRQn);
-
-    usbCfg.DeviceAddress = 0;
-    usbCfg.EnumInEn = ENABLE;
-    usbCfg.EnumOutEn = ENABLE;
-    usbCfg.RomBaseDescriptorUsed = 0;
-    usbCfg.SoftwareCtrl = 1;
-    usbCfg.EnumMaxPacketSize = USB_CTRL_EP_MPS;
-
-    /* Init Device */
-    USB_Set_Config(DISABLE, &usbCfg);
-
-    usb_fs_device.out_ep[0].ep_ena = 1U;
-    usb_fs_device.in_ep[0].ep_ena = 1U;
-    usb_fs_device.out_ep[0].ep_cfg.ep_mps = USB_CTRL_EP_MPS;
-    usb_fs_device.out_ep[0].ep_cfg.ep_type = USBD_EP_TYPE_CTRL;
-    usb_fs_device.in_ep[0].ep_cfg.ep_mps = USB_CTRL_EP_MPS;
-    usb_fs_device.in_ep[0].ep_cfg.ep_type = USBD_EP_TYPE_CTRL;
-
-    /* USB interrupt enable config */
-    BL_WR_REG(USB_BASE, USB_INT_EN, 0);
-    USB_IntEn(USB_INT_RESET, ENABLE);          //1
-    USB_IntEn(USB_INT_EP0_SETUP_DONE, ENABLE); //5
-    USB_IntEn(USB_INT_EP0_IN_DONE, ENABLE);    //7
-    USB_IntEn(USB_INT_EP0_OUT_DONE, ENABLE);   //9
-    USB_IntEn(USB_INT_RESET_END, ENABLE);      //27
-
-    /* USB interrupt mask config */
-    BL_WR_REG(USB_BASE, USB_INT_MASK, 0xffffffff);
-    USB_IntMask(USB_INT_RESET, UNMASK);          //1
-    USB_IntMask(USB_INT_EP0_SETUP_DONE, UNMASK); //5
-    USB_IntMask(USB_INT_EP0_IN_DONE, UNMASK);    //7
-    USB_IntMask(USB_INT_EP0_OUT_DONE, UNMASK);   //9
-    USB_IntMask(USB_INT_RESET_END, UNMASK);      //27
+int usb_open(struct device *dev, uint16_t oflag) {
+  USB_Config_Type usbCfg = {0};
+
+  usb_set_power_off();
+  mtimer_delay_ms(10);
+  usb_set_power_up();
+
+  usb_xcvr_config(DISABLE);
+  usb_xcvr_config(ENABLE);
+
+  CPU_Interrupt_Disable(USB_IRQn);
+
+  usbCfg.DeviceAddress         = 0;
+  usbCfg.EnumInEn              = ENABLE;
+  usbCfg.EnumOutEn             = ENABLE;
+  usbCfg.RomBaseDescriptorUsed = 0;
+  usbCfg.SoftwareCtrl          = 1;
+  usbCfg.EnumMaxPacketSize     = USB_CTRL_EP_MPS;
+
+  /* Init Device */
+  USB_Set_Config(DISABLE, &usbCfg);
+
+  usb_fs_device.out_ep[0].ep_ena         = 1U;
+  usb_fs_device.in_ep[0].ep_ena          = 1U;
+  usb_fs_device.out_ep[0].ep_cfg.ep_mps  = USB_CTRL_EP_MPS;
+  usb_fs_device.out_ep[0].ep_cfg.ep_type = USBD_EP_TYPE_CTRL;
+  usb_fs_device.in_ep[0].ep_cfg.ep_mps   = USB_CTRL_EP_MPS;
+  usb_fs_device.in_ep[0].ep_cfg.ep_type  = USBD_EP_TYPE_CTRL;
+
+  /* USB interrupt enable config */
+  BL_WR_REG(USB_BASE, USB_INT_EN, 0);
+  USB_IntEn(USB_INT_RESET, ENABLE);          // 1
+  USB_IntEn(USB_INT_EP0_SETUP_DONE, ENABLE); // 5
+  USB_IntEn(USB_INT_EP0_IN_DONE, ENABLE);    // 7
+  USB_IntEn(USB_INT_EP0_OUT_DONE, ENABLE);   // 9
+  USB_IntEn(USB_INT_RESET_END, ENABLE);      // 27
+
+  /* USB interrupt mask config */
+  BL_WR_REG(USB_BASE, USB_INT_MASK, 0xffffffff);
+  USB_IntMask(USB_INT_RESET, UNMASK);          // 1
+  USB_IntMask(USB_INT_EP0_SETUP_DONE, UNMASK); // 5
+  USB_IntMask(USB_INT_EP0_IN_DONE, UNMASK);    // 7
+  USB_IntMask(USB_INT_EP0_OUT_DONE, UNMASK);   // 9
+  USB_IntMask(USB_INT_RESET_END, UNMASK);      // 27
 
 #ifdef ENABLE_LPM_INT
-    USB_IntEn(USB_INT_LPM_PACKET, ENABLE);
-    USB_IntEn(USB_INT_LPM_WAKEUP, ENABLE);
-    USB_IntMask(USB_INT_LPM_PACKET, UNMASK);
-    USB_IntMask(USB_INT_LPM_WAKEUP, UNMASK);
+  USB_IntEn(USB_INT_LPM_PACKET, ENABLE);
+  USB_IntEn(USB_INT_LPM_WAKEUP, ENABLE);
+  USB_IntMask(USB_INT_LPM_PACKET, UNMASK);
+  USB_IntMask(USB_INT_LPM_WAKEUP, UNMASK);
 
-    USB_LPM_Enable();
-    USB_Set_LPM_Default_Response(USB_LPM_DEFAULT_RESP_ACK);
+  USB_LPM_Enable();
+  USB_Set_LPM_Default_Response(USB_LPM_DEFAULT_RESP_ACK);
 
 #endif
 
 #ifdef ENABLE_SOF3MS_INT
-    /* disable sof3ms until reset_end */
-    USB_IntEn(USB_INT_LOST_SOF_3_TIMES, DISABLE);
-    USB_IntMask(USB_INT_LOST_SOF_3_TIMES, MASK);
+  /* disable sof3ms until reset_end */
+  USB_IntEn(USB_INT_LOST_SOF_3_TIMES, DISABLE);
+  USB_IntMask(USB_INT_LOST_SOF_3_TIMES, MASK);
 
-    /* recommended enable sof3ms after reset_end */
-    USB_IntEn(USB_INT_LOST_SOF_3_TIMES, ENABLE);
-    USB_IntMask(USB_INT_LOST_SOF_3_TIMES, UNMASK);
+  /* recommended enable sof3ms after reset_end */
+  USB_IntEn(USB_INT_LOST_SOF_3_TIMES, ENABLE);
+  USB_IntMask(USB_INT_LOST_SOF_3_TIMES, UNMASK);
 #endif
 
 #ifdef ENABLE_ERROR_INT
-    USB_IntEn(USB_INT_ERROR, ENABLE);
-    USB_IntMask(USB_INT_ERROR, UNMASK);
+  USB_IntEn(USB_INT_ERROR, ENABLE);
+  USB_IntMask(USB_INT_ERROR, UNMASK);
 #endif
-    /*Clear pending interrupts*/
-    USB_Clr_IntStatus(USB_INT_ALL);
+  /*Clear pending interrupts*/
+  USB_Clr_IntStatus(USB_INT_ALL);
 
-    Interrupt_Handler_Register(USB_IRQn, USB_FS_IRQ);
-    CPU_Interrupt_Enable(USB_IRQn);
-    USB_Enable();
+  Interrupt_Handler_Register(USB_IRQn, USB_FS_IRQ);
+  CPU_Interrupt_Enable(USB_IRQn);
+  USB_Enable();
 
-    return 0;
+  return 0;
 }
 /**
  * @brief
@@ -292,23 +284,22 @@ int usb_open(struct device *dev, uint16_t oflag)
  * @param dev
  * @return int
  */
-int usb_close(struct device *dev)
-{
-    /* disable all interrupts and force USB reset */
-    CPU_Interrupt_Disable(USB_IRQn);
-    USB_IntMask(USB_INT_LPM_WAKEUP, MASK);
-    USB_IntMask(USB_INT_LPM_PACKET, MASK);
+int usb_close(struct device *dev) {
+  /* disable all interrupts and force USB reset */
+  CPU_Interrupt_Disable(USB_IRQn);
+  USB_IntMask(USB_INT_LPM_WAKEUP, MASK);
+  USB_IntMask(USB_INT_LPM_PACKET, MASK);
 
-    USB_Disable();
+  USB_Disable();
 
-    /* clear interrupt status register */
-    USB_Clr_IntStatus(USB_INT_ALL);
+  /* clear interrupt status register */
+  USB_Clr_IntStatus(USB_INT_ALL);
 
-    usb_set_power_off();
+  usb_set_power_off();
 
-    usb_xcvr_config(DISABLE);
-    GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_USB);
-    return 0;
+  usb_xcvr_config(DISABLE);
+  GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_USB);
+  return 0;
 }
 /**
  * @brief
@@ -318,130 +309,127 @@ int usb_close(struct device *dev)
  * @param args
  * @return int
  */
-int usb_control(struct device *dev, int cmd, void *args)
-{
-    struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
-
-    switch (cmd) {
-        case DEVICE_CTRL_SET_INT /* constant-expression */: {
-            uint32_t offset = __builtin_ctz((uint32_t)args);
-
-            while (offset < 24) {
-                if ((uint32_t)args & (1 << offset)) {
-                    USB_IntEn(offset, ENABLE);
-                    USB_IntMask(offset, UNMASK);
-                }
-
-                offset++;
-            }
-            break;
-        }
-        case DEVICE_CTRL_CLR_INT /* constant-expression */: {
-            uint32_t offset = __builtin_ctz((uint32_t)args);
-
-            while (offset < 24) {
-                if ((uint32_t)args & (1 << offset)) {
-                    USB_IntEn(offset, DISABLE);
-                    USB_IntMask(offset, MASK);
-                }
-
-                offset++;
-            }
-            break;
-        }
-        case DEVICE_CTRL_USB_DC_SET_ACK /* constant-expression */:
-            USB_Set_EPx_Status(USB_EP_GET_IDX(((uint32_t)args) & 0x7f), USB_EP_STATUS_ACK);
-            return 0;
-        case DEVICE_CTRL_USB_DC_ENUM_ON: {
-            uint32_t tmpVal;
-            tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-            tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 1);
-            BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-            return 0;
-        }
-        case DEVICE_CTRL_USB_DC_ENUM_OFF: {
-            uint32_t tmpVal;
-            tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
-            tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
-            BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
-            return 0;
-        }
-        case DEVICE_CTRL_USB_DC_GET_EP_TX_FIFO_CNT:
-            return USB_Get_EPx_TX_FIFO_CNT(((uint32_t)args) & 0x7f);
-
-        case DEVICE_CTRL_USB_DC_GET_EP_RX_FIFO_CNT:
-            return USB_Get_EPx_RX_FIFO_CNT(((uint32_t)args) & 0x7f);
-        case DEVICE_CTRL_ATTACH_TX_DMA /* constant-expression */:
-            usb_device->tx_dma = (struct device *)args;
-            break;
-
-        case DEVICE_CTRL_ATTACH_RX_DMA /* constant-expression */:
-            usb_device->rx_dma = (struct device *)args;
-            break;
-
-        case DEVICE_CTRL_USB_DC_SET_TX_DMA /* constant-expression */:
-            USB_Set_EPx_TX_DMA_Interface_Config(((uint32_t)args) & 0x7f, ENABLE);
-            break;
-
-        case DEVICE_CTRL_USB_DC_SET_RX_DMA /* constant-expression */:
-            USB_Set_EPx_RX_DMA_Interface_Config(((uint32_t)args) & 0x7f, ENABLE);
-            break;
-
-        default:
-            break;
-    }
+int usb_control(struct device *dev, int cmd, void *args) {
+  struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
+
+  switch (cmd) {
+  case DEVICE_CTRL_SET_INT /* constant-expression */: {
+    uint32_t offset = __builtin_ctz((uint32_t)args);
+
+    while (offset < 24) {
+      if ((uint32_t)args & (1 << offset)) {
+        USB_IntEn(offset, ENABLE);
+        USB_IntMask(offset, UNMASK);
+      }
 
+      offset++;
+    }
+    break;
+  }
+  case DEVICE_CTRL_CLR_INT /* constant-expression */: {
+    uint32_t offset = __builtin_ctz((uint32_t)args);
+
+    while (offset < 24) {
+      if ((uint32_t)args & (1 << offset)) {
+        USB_IntEn(offset, DISABLE);
+        USB_IntMask(offset, MASK);
+      }
+
+      offset++;
+    }
+    break;
+  }
+  case DEVICE_CTRL_USB_DC_SET_ACK /* constant-expression */:
+    USB_Set_EPx_Status(USB_EP_GET_IDX(((uint32_t)args) & 0x7f), USB_EP_STATUS_ACK);
+    return 0;
+  case DEVICE_CTRL_USB_DC_ENUM_ON: {
+    uint32_t tmpVal;
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 1);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
     return 0;
+  }
+  case DEVICE_CTRL_USB_DC_ENUM_OFF: {
+    uint32_t tmpVal;
+    tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR);
+    tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, 0);
+    BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal);
+    return 0;
+  }
+  case DEVICE_CTRL_USB_DC_GET_EP_TX_FIFO_CNT:
+    return USB_Get_EPx_TX_FIFO_CNT(((uint32_t)args) & 0x7f);
+
+  case DEVICE_CTRL_USB_DC_GET_EP_RX_FIFO_CNT:
+    return USB_Get_EPx_RX_FIFO_CNT(((uint32_t)args) & 0x7f);
+  case DEVICE_CTRL_ATTACH_TX_DMA /* constant-expression */:
+    usb_device->tx_dma = (struct device *)args;
+    break;
+
+  case DEVICE_CTRL_ATTACH_RX_DMA /* constant-expression */:
+    usb_device->rx_dma = (struct device *)args;
+    break;
+
+  case DEVICE_CTRL_USB_DC_SET_TX_DMA /* constant-expression */:
+    USB_Set_EPx_TX_DMA_Interface_Config(((uint32_t)args) & 0x7f, ENABLE);
+    break;
+
+  case DEVICE_CTRL_USB_DC_SET_RX_DMA /* constant-expression */:
+    USB_Set_EPx_RX_DMA_Interface_Config(((uint32_t)args) & 0x7f, ENABLE);
+    break;
+
+  default:
+    break;
+  }
+
+  return 0;
 }
 
-int usb_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size)
-{
-    struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
-    uint8_t ep_idx = USB_EP_GET_IDX(pos);
-
-    if (usb_device->in_ep[ep_idx].ep_cfg.ep_type == USBD_EP_TYPE_ISOC) {
-        uint32_t usb_ep_addr = USB_BASE + 0x308 + ep_idx * 0x10;
-
-        dma_channel_stop(usb_device->tx_dma);
-        usb_lli_list.src_addr = (uint32_t)buffer;
-        usb_lli_list.dst_addr = usb_ep_addr;
-        usb_lli_list.cfg.bits.TransferSize = size;
-        usb_lli_list.cfg.bits.DI = 0;
-        usb_lli_list.cfg.bits.SI = 1;
-        usb_lli_list.cfg.bits.SBSize = DMA_BURST_16BYTE;
-        usb_lli_list.cfg.bits.DBSize = DMA_BURST_1BYTE;
-        dma_channel_update(usb_device->tx_dma, (void *)((uint32_t)&usb_lli_list));
-        dma_channel_start(usb_device->tx_dma);
-        return 0;
-    } else {
-    }
+int usb_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) {
+  struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
+  uint8_t               ep_idx     = USB_EP_GET_IDX(pos);
+
+  if (usb_device->in_ep[ep_idx].ep_cfg.ep_type == USBD_EP_TYPE_ISOC) {
+    uint32_t usb_ep_addr = USB_BASE + 0x308 + ep_idx * 0x10;
+
+    dma_channel_stop(usb_device->tx_dma);
+    usb_lli_list.src_addr              = (uint32_t)buffer;
+    usb_lli_list.dst_addr              = usb_ep_addr;
+    usb_lli_list.cfg.bits.TransferSize = size;
+    usb_lli_list.cfg.bits.DI           = 0;
+    usb_lli_list.cfg.bits.SI           = 1;
+    usb_lli_list.cfg.bits.SBSize       = DMA_BURST_SIZE_16;
+    usb_lli_list.cfg.bits.DBSize       = DMA_BURST_SIZE_1;
+    dma_channel_update(usb_device->tx_dma, (void *)((uint32_t)&usb_lli_list));
+    dma_channel_start(usb_device->tx_dma);
+    return 0;
+  } else {
+  }
 
-    return -1;
+  return -1;
 }
 
-int usb_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
-{
-    struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
-    uint8_t ep_idx = USB_EP_GET_IDX(pos);
-
-    if (usb_device->out_ep[ep_idx].ep_cfg.ep_type == USBD_EP_TYPE_ISOC) {
-        uint32_t usb_ep_addr = USB_BASE + 0x308 + ep_idx * 0x1c;
-
-        dma_channel_stop(usb_device->tx_dma);
-        usb_lli_list.src_addr = usb_ep_addr;
-        usb_lli_list.dst_addr = (uint32_t)buffer;
-        usb_lli_list.cfg.bits.TransferSize = size;
-        usb_lli_list.cfg.bits.DI = 1;
-        usb_lli_list.cfg.bits.SI = 0;
-        usb_lli_list.cfg.bits.SBSize = DMA_BURST_1BYTE;
-        usb_lli_list.cfg.bits.DBSize = DMA_BURST_16BYTE;
-        dma_channel_update(usb_device->rx_dma, (void *)((uint32_t)&usb_lli_list));
-        dma_channel_start(usb_device->rx_dma);
-        return 0;
-    } else {
-    }
+int usb_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size) {
+  struct usb_dc_device *usb_device = (struct usb_dc_device *)dev;
+  uint8_t               ep_idx     = USB_EP_GET_IDX(pos);
+
+  if (usb_device->out_ep[ep_idx].ep_cfg.ep_type == USBD_EP_TYPE_ISOC) {
+    uint32_t usb_ep_addr = USB_BASE + 0x308 + ep_idx * 0x1c;
+
+    dma_channel_stop(usb_device->tx_dma);
+    usb_lli_list.src_addr              = usb_ep_addr;
+    usb_lli_list.dst_addr              = (uint32_t)buffer;
+    usb_lli_list.cfg.bits.TransferSize = size;
+    usb_lli_list.cfg.bits.DI           = 1;
+    usb_lli_list.cfg.bits.SI           = 0;
+    usb_lli_list.cfg.bits.SBSize       = DMA_BURST_SIZE_1;
+    usb_lli_list.cfg.bits.DBSize       = DMA_BURST_SIZE_16;
+    dma_channel_update(usb_device->rx_dma, (void *)((uint32_t)&usb_lli_list));
+    dma_channel_start(usb_device->rx_dma);
+    return 0;
+  } else {
+  }
 
-    return -1;
+  return -1;
 }
 
 /**
@@ -452,26 +440,25 @@ int usb_read(struct device *dev, uint32_t pos, void *buffer, uint32_t size)
  * @param flag
  * @return int
  */
-int usb_dc_register(enum usb_index_type index, const char *name)
-{
-    struct device *dev;
+int usb_dc_register(enum usb_index_type index, const char *name) {
+  struct device *dev;
 
-    if (USB_MAX_INDEX == 0) {
-        return -DEVICE_EINVAL;
-    }
+  if (USB_MAX_INDEX == 0) {
+    return -DEVICE_EINVAL;
+  }
 
-    dev = &(usb_fs_device.parent);
+  dev = &(usb_fs_device.parent);
 
-    dev->open = usb_open;
-    dev->close = usb_close;
-    dev->control = usb_control;
-    dev->write = usb_write;
-    dev->read = usb_read;
+  dev->open    = usb_open;
+  dev->close   = usb_close;
+  dev->control = usb_control;
+  dev->write   = usb_write;
+  dev->read    = usb_read;
 
-    dev->type = DEVICE_CLASS_USB;
-    dev->handle = NULL;
+  dev->type   = DEVICE_CLASS_USB;
+  dev->handle = NULL;
 
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 
 /**
@@ -481,10 +468,9 @@ int usb_dc_register(enum usb_index_type index, const char *name)
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_set_dev_address(const uint8_t addr)
-{
-    USB_Set_Device_Addr(addr);
-    return 0;
+int usb_dc_set_dev_address(const uint8_t addr) {
+  USB_Set_Device_Addr(addr);
+  return 0;
 }
 
 /**
@@ -496,77 +482,73 @@ int usb_dc_set_dev_address(const uint8_t addr)
  * @param ep_cfg  ep_cfg Endpoint
  * @return int
  */
-int usb_dc_ep_open(struct device *dev, const struct usb_dc_ep_cfg *ep_cfg)
-{
-    uint8_t ep;
-    EP_Config_Type epCfg;
-
-    if (!ep_cfg) {
-        return -1;
-    }
-
-    ep = ep_cfg->ep_addr;
-
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
+int usb_dc_ep_open(struct device *dev, const struct usb_dc_ep_cfg *ep_cfg) {
+  uint8_t        ep;
+  EP_Config_Type epCfg;
 
-    USB_DC_LOG_DBG("%s ep %x, mps %d, type %d\r\n", __func__, ep, ep_cfg->ep_mps, ep_cfg->ep_type);
-
-    if (ep_idx == 0) {
-        return 0;
-    }
-
-    if (USB_EP_DIR_IS_OUT(ep)) {
-        epCfg.dir = EP_OUT;
-        epCfg.EPMaxPacketSize = ep_cfg->ep_mps;
-        usb_fs_device.out_ep[ep_idx].ep_cfg.ep_mps = ep_cfg->ep_mps;
-        usb_fs_device.out_ep[ep_idx].ep_cfg.ep_type = ep_cfg->ep_type;
-    } else {
-        epCfg.dir = EP_IN;
-        epCfg.EPMaxPacketSize = ep_cfg->ep_mps;
-        usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps = ep_cfg->ep_mps;
-        usb_fs_device.in_ep[ep_idx].ep_cfg.ep_type = ep_cfg->ep_type;
-    }
-
-    switch (ep_cfg->ep_type) {
-        case USBD_EP_TYPE_CTRL:
-            epCfg.type = USB_DC_EP_TYPE_CTRL;
-            break;
-
-        case USBD_EP_TYPE_ISOC:
-            epCfg.type = USB_DC_EP_TYPE_ISOC;
-            break;
+  if (!ep_cfg) {
+    return -1;
+  }
 
-        case USBD_EP_TYPE_BULK:
-            epCfg.type = USB_DC_EP_TYPE_BULK;
-            break;
+  ep = ep_cfg->ep_addr;
 
-        case USBD_EP_TYPE_INTR:
-            epCfg.type = USB_DC_EP_TYPE_INTR;
-            break;
+  uint8_t ep_idx = USB_EP_GET_IDX(ep);
 
-        default:
-            return -1;
-    }
+  USB_DC_LOG_DBG("%s ep %x, mps %d, type %d\r\n", __func__, ep, ep_cfg->ep_mps, ep_cfg->ep_type);
 
-    USB_Set_EPx_Config(ep_idx, &epCfg);
+  if (ep_idx == 0) {
+    return 0;
+  }
+
+  if (USB_EP_DIR_IS_OUT(ep)) {
+    epCfg.dir                                   = EP_OUT;
+    epCfg.EPMaxPacketSize                       = ep_cfg->ep_mps;
+    usb_fs_device.out_ep[ep_idx].ep_cfg.ep_mps  = ep_cfg->ep_mps;
+    usb_fs_device.out_ep[ep_idx].ep_cfg.ep_type = ep_cfg->ep_type;
+  } else {
+    epCfg.dir                                  = EP_IN;
+    epCfg.EPMaxPacketSize                      = ep_cfg->ep_mps;
+    usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps  = ep_cfg->ep_mps;
+    usb_fs_device.in_ep[ep_idx].ep_cfg.ep_type = ep_cfg->ep_type;
+  }
+
+  switch (ep_cfg->ep_type) {
+  case USBD_EP_TYPE_CTRL:
+    epCfg.type = USB_DC_EP_TYPE_CTRL;
+    break;
+
+  case USBD_EP_TYPE_ISOC:
+    epCfg.type = USB_DC_EP_TYPE_ISOC;
+    break;
+
+  case USBD_EP_TYPE_BULK:
+    epCfg.type = USB_DC_EP_TYPE_BULK;
+    break;
+
+  case USBD_EP_TYPE_INTR:
+    epCfg.type = USB_DC_EP_TYPE_INTR;
+    break;
+
+  default:
+    return -1;
+  }
 
-    if (USB_EP_DIR_IS_OUT(ep)) {
-        /* Clear NAK and enable ep */
-        USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_ACK);
-        usb_fs_device.out_ep[ep_idx].ep_ena = 1U;
-    } else {
-        //USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_ACK);
-        USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_NACK);
-        usb_fs_device.in_ep[ep_idx].ep_ena = 1U;
-    }
+  USB_Set_EPx_Config(ep_idx, &epCfg);
 
-    return 0;
+  if (USB_EP_DIR_IS_OUT(ep)) {
+    /* Clear NAK and enable ep */
+    USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_ACK);
+    usb_fs_device.out_ep[ep_idx].ep_ena = 1U;
+  } else {
+    // USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_ACK);
+    USB_Set_EPx_Status(USB_EP_GET_IDX(ep), USB_EP_STATUS_NACK);
+    usb_fs_device.in_ep[ep_idx].ep_ena = 1U;
+  }
+
+  return 0;
 }
 
-int usb_dc_ep_close(const uint8_t ep)
-{
-    return 0;
-}
+int usb_dc_ep_close(const uint8_t ep) { return 0; }
 
 /**
  * @brief Set stall condition for the selected endpoint
@@ -576,63 +558,62 @@ int usb_dc_ep_close(const uint8_t ep)
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_ep_set_stall(const uint8_t ep)
-{
-    uint32_t tmpVal = 0;
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
-
-    if (USB_EP_DIR_IS_OUT(ep)) {
-        usb_fs_device.out_ep[ep_idx].is_stalled = 1U;
-    } else {
-        usb_fs_device.in_ep[ep_idx].is_stalled = 1U;
-    }
-
-    switch (ep_idx) {
-        case 0:
-            tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL);
-            BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal);
-            break;
-        case 1:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL);
-            BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal);
-            break;
-        case 2:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL);
-            BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal);
-            break;
-        case 3:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL);
-            BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal);
-            break;
-        case 4:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL);
-            BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal);
-            break;
-        case 5:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL);
-            BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal);
-            break;
-        case 6:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL);
-            BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal);
-            break;
-        case 7:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL);
-            BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal);
-            break;
-
-        default:
-            break;
-    }
-    return 0;
+int usb_dc_ep_set_stall(const uint8_t ep) {
+  uint32_t tmpVal = 0;
+  uint8_t  ep_idx = USB_EP_GET_IDX(ep);
+
+  if (USB_EP_DIR_IS_OUT(ep)) {
+    usb_fs_device.out_ep[ep_idx].is_stalled = 1U;
+  } else {
+    usb_fs_device.in_ep[ep_idx].is_stalled = 1U;
+  }
+
+  switch (ep_idx) {
+  case 0:
+    tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL);
+    BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal);
+    break;
+  case 1:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL);
+    BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal);
+    break;
+  case 2:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL);
+    BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal);
+    break;
+  case 3:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL);
+    BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal);
+    break;
+  case 4:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL);
+    BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal);
+    break;
+  case 5:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL);
+    BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal);
+    break;
+  case 6:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL);
+    BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal);
+    break;
+  case 7:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL);
+    BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal);
+    break;
+
+  default:
+    break;
+  }
+  return 0;
 }
 /**
  * @brief Clear stall condition for the selected endpoint
@@ -642,72 +623,71 @@ int usb_dc_ep_set_stall(const uint8_t ep)
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_ep_clear_stall(const uint8_t ep)
-{
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
-    uint32_t tmpVal = 0;
-    if (USB_EP_DIR_IS_OUT(ep)) {
-        usb_fs_device.out_ep[ep_idx].is_stalled = 0;
-    } else {
-        usb_fs_device.in_ep[ep_idx].is_stalled = 0;
-    }
-    switch (ep_idx) {
-        case 0:
-            break;
-        case 1:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL);
-            BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal);
-            break;
-        case 2:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL);
-            BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal);
-            break;
-        case 3:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL);
-            BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal);
-            break;
-        case 4:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL);
-            BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal);
-            break;
-        case 5:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL);
-            BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal);
-            break;
-        case 6:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL);
-            BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal);
-            break;
-        case 7:
-            tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_RDY);
-            tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK);
-            tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL);
-            BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal);
-            break;
-
-        default:
-            break;
-    }
-    return 0;
+int usb_dc_ep_clear_stall(const uint8_t ep) {
+  uint8_t  ep_idx = USB_EP_GET_IDX(ep);
+  uint32_t tmpVal = 0;
+  if (USB_EP_DIR_IS_OUT(ep)) {
+    usb_fs_device.out_ep[ep_idx].is_stalled = 0;
+  } else {
+    usb_fs_device.in_ep[ep_idx].is_stalled = 0;
+  }
+  switch (ep_idx) {
+  case 0:
+    break;
+  case 1:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL);
+    BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal);
+    break;
+  case 2:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL);
+    BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal);
+    break;
+  case 3:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL);
+    BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal);
+    break;
+  case 4:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL);
+    BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal);
+    break;
+  case 5:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL);
+    BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal);
+    break;
+  case 6:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL);
+    BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal);
+    break;
+  case 7:
+    tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_RDY);
+    tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK);
+    tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL);
+    BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal);
+    break;
+
+  default:
+    break;
+  }
+  return 0;
 }
 
 /**
@@ -720,27 +700,26 @@ int usb_dc_ep_clear_stall(const uint8_t ep)
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_ep_is_stalled(struct device *dev, const uint8_t ep, uint8_t *stalled)
-{
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
+int usb_dc_ep_is_stalled(struct device *dev, const uint8_t ep, uint8_t *stalled) {
+  uint8_t ep_idx = USB_EP_GET_IDX(ep);
 
-    if (!stalled) {
-        return -1;
-    }
+  if (!stalled) {
+    return -1;
+  }
 
-    *stalled = 0U;
+  *stalled = 0U;
 
-    if (USB_EP_DIR_IS_OUT(ep)) {
-        if ((USB_Get_EPx_Status(ep_idx) & USB_EP_STATUS_STALL) && usb_fs_device.out_ep[ep_idx].is_stalled) {
-            *stalled = 1U;
-        }
-    } else {
-        if ((USB_Get_EPx_Status(ep_idx) & USB_EP_STATUS_STALL) && usb_fs_device.in_ep[ep_idx].is_stalled) {
-            *stalled = 1U;
-        }
+  if (USB_EP_DIR_IS_OUT(ep)) {
+    if ((USB_Get_EPx_Status(ep_idx) & USB_EP_STATUS_STALL) && usb_fs_device.out_ep[ep_idx].is_stalled) {
+      *stalled = 1U;
+    }
+  } else {
+    if ((USB_Get_EPx_Status(ep_idx) & USB_EP_STATUS_STALL) && usb_fs_device.in_ep[ep_idx].is_stalled) {
+      *stalled = 1U;
     }
+  }
 
-    return 0;
+  return 0;
 }
 
 /**
@@ -762,93 +741,92 @@ int usb_dc_ep_is_stalled(struct device *dev, const uint8_t ep, uint8_t *stalled)
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_ep_write(struct device *dev, const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes)
-{
-    uint8_t ep_idx;
-    uint32_t timeout = 0x00FFFFFF;
-    uint32_t ep_tx_fifo_addr;
-
-    ep_idx = USB_EP_GET_IDX(ep);
-
-    /* Check if IN ep */
-    if (USB_EP_GET_DIR(ep) != USB_EP_DIR_IN) {
-        return -USB_DC_EP_DIR_ERR;
-    }
-
-    /* Check if ep enabled */
-    if (!usb_ep_is_enabled(ep)) {
-        return -USB_DC_EP_EN_ERR;
-    }
-
-    if (!data && data_len) {
-        USB_DC_LOG_ERR("data is null\r\n");
-        return -USB_DC_ADDR_ERR;
+int usb_dc_ep_write(struct device *dev, const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes) {
+  uint8_t  ep_idx;
+  uint32_t timeout = 0x00FFFFFF;
+  uint32_t ep_tx_fifo_addr;
+
+  ep_idx = USB_EP_GET_IDX(ep);
+
+  /* Check if IN ep */
+  if (USB_EP_GET_DIR(ep) != USB_EP_DIR_IN) {
+    return -USB_DC_EP_DIR_ERR;
+  }
+
+  /* Check if ep enabled */
+  if (!usb_ep_is_enabled(ep)) {
+    return -USB_DC_EP_EN_ERR;
+  }
+
+  if (!data && data_len) {
+    USB_DC_LOG_ERR("data is null\r\n");
+    return -USB_DC_ADDR_ERR;
+  }
+
+  /* Check if ep free */
+  while (!USB_Is_EPx_RDY_Free(ep_idx) && (usb_fs_device.in_ep[ep_idx].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
+    timeout--;
+
+    if (!timeout) {
+      USB_DC_LOG_ERR("ep%d wait free timeout\r\n", ep);
+      return -USB_DC_EP_TIMEOUT_ERR;
     }
-
-    /* Check if ep free */
-    while (!USB_Is_EPx_RDY_Free(ep_idx) && (usb_fs_device.in_ep[ep_idx].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
-        timeout--;
-
-        if (!timeout) {
-            USB_DC_LOG_ERR("ep%d wait free timeout\r\n", ep);
-            return -USB_DC_EP_TIMEOUT_ERR;
-        }
-    }
-
-    if (!data_len) {
-        /* Zero length packet */
-        if ((USB_EP_GET_IDX(ep) != 0)) {
-            /* Clear NAK and enable ep */
-            USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
-            return USB_DC_OK;
-        }
-        return USB_DC_OK;
-    }
-
-    if (data_len > usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps) {
-        /* Check if transfer len is too big */
-        data_len = usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps;
+  }
+
+  if (!data_len) {
+    /* Zero length packet */
+    if ((USB_EP_GET_IDX(ep) != 0)) {
+      /* Clear NAK and enable ep */
+      USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
+      return USB_DC_OK;
     }
+    return USB_DC_OK;
+  }
 
-    /* Wait for FIFO space available */
-    do {
-        uint32_t avail_space = USB_Get_EPx_TX_FIFO_CNT(ep_idx);
-
-        if (avail_space >= usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps) {
-            break;
-        }
-
-        //USB_DC_LOG_ERR("EP%d have remain data\r\n", ep_idx);
-    } while (1);
-
-    /*
-     * Write data to FIFO, make sure that we are protected against
-     * other USB register accesses.  According to "DesignWare Cores
-     * USB 1.1/2.0 Device Subsystem-AHB/VCI Databook": "During FIFO
-     * access, the application must not access the UDC/Subsystem
-     * registers or vendor registers (for ULPI mode). After starting
-     * to access a FIFO, the application must complete the transaction
-     * before accessing the register."
-     */
-    ep_tx_fifo_addr = USB_BASE + USB_EP0_TX_FIFO_WDATA_OFFSET + ep_idx * 0x10;
-
-    if ((data_len == 1) && (ep_idx == 0)) {
-        USB_Set_EPx_Xfer_Size(EP_ID0, 1);
-    } else if (ep_idx == 0) {
-        USB_Set_EPx_Xfer_Size(EP_ID0, 64);
-    }
+  if (data_len > usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps) {
+    /* Check if transfer len is too big */
+    data_len = usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps;
+  }
 
-    memcopy_to_fifo((void *)ep_tx_fifo_addr, (uint8_t *)data, data_len);
-    /* Clear NAK and enable ep */
-    if (USB_EP_GET_IDX(ep) != 0)
-        USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
-    USB_DC_LOG_DBG("EP%d write %u bytes\r\n", ep_idx, data_len);
+  /* Wait for FIFO space available */
+  do {
+    uint32_t avail_space = USB_Get_EPx_TX_FIFO_CNT(ep_idx);
 
-    if (ret_bytes) {
-        *ret_bytes = data_len;
+    if (avail_space >= usb_fs_device.in_ep[ep_idx].ep_cfg.ep_mps) {
+      break;
     }
 
-    return USB_DC_OK;
+    // USB_DC_LOG_ERR("EP%d have remain data\r\n", ep_idx);
+  } while (1);
+
+  /*
+   * Write data to FIFO, make sure that we are protected against
+   * other USB register accesses.  According to "DesignWare Cores
+   * USB 1.1/2.0 Device Subsystem-AHB/VCI Databook": "During FIFO
+   * access, the application must not access the UDC/Subsystem
+   * registers or vendor registers (for ULPI mode). After starting
+   * to access a FIFO, the application must complete the transaction
+   * before accessing the register."
+   */
+  ep_tx_fifo_addr = USB_BASE + USB_EP0_TX_FIFO_WDATA_OFFSET + ep_idx * 0x10;
+
+  if ((data_len == 1) && (ep_idx == 0)) {
+    USB_Set_EPx_Xfer_Size(EP_ID0, 1);
+  } else if (ep_idx == 0) {
+    USB_Set_EPx_Xfer_Size(EP_ID0, 64);
+  }
+
+  memcopy_to_fifo((void *)ep_tx_fifo_addr, (uint8_t *)data, data_len);
+  /* Clear NAK and enable ep */
+  if (USB_EP_GET_IDX(ep) != 0)
+    USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
+  USB_DC_LOG_DBG("EP%d write %u bytes\r\n", ep_idx, data_len);
+
+  if (ret_bytes) {
+    *ret_bytes = data_len;
+  }
+
+  return USB_DC_OK;
 }
 
 /**
@@ -870,61 +848,60 @@ int usb_dc_ep_write(struct device *dev, const uint8_t ep, const uint8_t *data, u
  *
  * @return 0 on success, negative errno code on fail.
  */
-int usb_dc_ep_read(struct device *dev, const uint8_t ep, uint8_t *data, uint32_t data_len, uint32_t *read_bytes)
-{
-    uint8_t ep_idx = USB_EP_GET_IDX(ep);
-    uint32_t read_count;
-    uint32_t ep_rx_fifo_addr;
-    uint32_t timeout = 0x00FFFFFF;
-
-    /* Check if OUT ep */
-    if (USB_EP_GET_DIR(ep) != USB_EP_DIR_OUT) {
-        USB_DC_LOG_ERR("Wrong endpoint direction\r\n");
-        return -USB_DC_EP_DIR_ERR;
-    }
-
-    /* Check if ep enabled */
-    if (!usb_ep_is_enabled(ep)) {
-        USB_DC_LOG_ERR("Not enabled endpoint\r\n");
-        return -USB_DC_EP_EN_ERR;
-    }
-
-    if (!data && data_len) {
-        USB_DC_LOG_ERR("data is null\r\n");
-        return -USB_DC_ADDR_ERR;
+int usb_dc_ep_read(struct device *dev, const uint8_t ep, uint8_t *data, uint32_t data_len, uint32_t *read_bytes) {
+  uint8_t  ep_idx = USB_EP_GET_IDX(ep);
+  uint32_t read_count;
+  uint32_t ep_rx_fifo_addr;
+  uint32_t timeout = 0x00FFFFFF;
+
+  /* Check if OUT ep */
+  if (USB_EP_GET_DIR(ep) != USB_EP_DIR_OUT) {
+    USB_DC_LOG_ERR("Wrong endpoint direction\r\n");
+    return -USB_DC_EP_DIR_ERR;
+  }
+
+  /* Check if ep enabled */
+  if (!usb_ep_is_enabled(ep)) {
+    USB_DC_LOG_ERR("Not enabled endpoint\r\n");
+    return -USB_DC_EP_EN_ERR;
+  }
+
+  if (!data && data_len) {
+    USB_DC_LOG_ERR("data is null\r\n");
+    return -USB_DC_ADDR_ERR;
+  }
+
+  /* Check if ep free */
+  while (!USB_Is_EPx_RDY_Free(ep_idx) && (usb_fs_device.out_ep[ep_idx].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
+    timeout--;
+
+    if (!timeout) {
+      USB_DC_LOG_ERR("ep%d wait free timeout\r\n", ep);
+      return -USB_DC_EP_TIMEOUT_ERR;
     }
+  }
 
-    /* Check if ep free */
-    while (!USB_Is_EPx_RDY_Free(ep_idx) && (usb_fs_device.out_ep[ep_idx].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
-        timeout--;
-
-        if (!timeout) {
-            USB_DC_LOG_ERR("ep%d wait free timeout\r\n", ep);
-            return -USB_DC_EP_TIMEOUT_ERR;
-        }
+  if (!data_len) {
+    if ((USB_EP_GET_IDX(ep) != 0)) {
+      /* Clear NAK and enable ep */
+      USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
+      return USB_DC_OK;
     }
+  }
 
-    if (!data_len) {
-        if ((USB_EP_GET_IDX(ep) != 0)) {
-            /* Clear NAK and enable ep */
-            USB_Set_EPx_Rdy(USB_EP_GET_IDX(ep));
-            return USB_DC_OK;
-        }
-    }
+  read_count = USB_Get_EPx_RX_FIFO_CNT(ep_idx);
+  read_count = MIN(read_count, data_len);
 
-    read_count = USB_Get_EPx_RX_FIFO_CNT(ep_idx);
-    read_count = MIN(read_count, data_len);
+  /* Data in the FIFOs is always stored per 8-bit word*/
+  ep_rx_fifo_addr = (USB_BASE + USB_EP0_RX_FIFO_RDATA_OFFSET + ep_idx * 0x10);
+  fifocopy_to_mem((void *)ep_rx_fifo_addr, data, read_count);
+  USB_DC_LOG_DBG("Read EP%d, req %d, read %d bytes\r\n", ep, data_len, read_count);
 
-    /* Data in the FIFOs is always stored per 8-bit word*/
-    ep_rx_fifo_addr = (USB_BASE + USB_EP0_RX_FIFO_RDATA_OFFSET + ep_idx * 0x10);
-    fifocopy_to_mem((void *)ep_rx_fifo_addr, data, read_count);
-    USB_DC_LOG_DBG("Read EP%d, req %d, read %d bytes\r\n", ep, data_len, read_count);
-
-    if (read_bytes) {
-        *read_bytes = read_count;
-    }
+  if (read_bytes) {
+    *read_bytes = read_count;
+  }
 
-    return USB_DC_OK;
+  return USB_DC_OK;
 }
 /**
  * @brief
@@ -934,46 +911,45 @@ int usb_dc_ep_read(struct device *dev, const uint8_t ep, uint8_t *data, uint32_t
  * @param ep
  * @return int
  */
-int usb_dc_receive_to_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8_t ep)
-{
-    uint8_t ep_idx;
-    uint8_t recv_len;
-    static bool overflow_flag = false;
-
-    /* Check if OUT ep */
-    if (USB_EP_GET_DIR(ep) != USB_EP_DIR_OUT) {
-        USB_DC_LOG_ERR("Wrong endpoint direction\r\n");
-        return -USB_DC_EP_DIR_ERR;
-    }
+int usb_dc_receive_to_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8_t ep) {
+  uint8_t     ep_idx;
+  uint8_t     recv_len;
+  static bool overflow_flag = false;
+
+  /* Check if OUT ep */
+  if (USB_EP_GET_DIR(ep) != USB_EP_DIR_OUT) {
+    USB_DC_LOG_ERR("Wrong endpoint direction\r\n");
+    return -USB_DC_EP_DIR_ERR;
+  }
+
+  /* Check if ep enabled */
+  if (!usb_ep_is_enabled(ep)) {
+    return -USB_DC_EP_EN_ERR;
+  }
+
+  ep_idx = USB_EP_GET_IDX(ep);
+
+  recv_len = USB_Get_EPx_RX_FIFO_CNT(ep_idx);
+
+  /*if rx fifo count equal 0,it means last is send nack and ringbuffer is smaller than 64,
+   * so,if ringbuffer is larger than 64,set ack to recv next data.
+   */
+  if (overflow_flag && (Ring_Buffer_Get_Empty_Length(rb) > 64) && (!recv_len)) {
+    overflow_flag = false;
+    USB_Set_EPx_Rdy(ep_idx);
+    return 0;
+  } else {
+    uint32_t addr = USB_BASE + 0x11C + (ep_idx - 1) * 0x10;
+    Ring_Buffer_Write_Callback(rb, recv_len, fifocopy_to_mem, (void *)addr);
 
-    /* Check if ep enabled */
-    if (!usb_ep_is_enabled(ep)) {
-        return -USB_DC_EP_EN_ERR;
+    if (Ring_Buffer_Get_Empty_Length(rb) < 64) {
+      overflow_flag = true;
+      return -USB_DC_RB_SIZE_SMALL_ERR;
     }
 
-    ep_idx = USB_EP_GET_IDX(ep);
-
-    recv_len = USB_Get_EPx_RX_FIFO_CNT(ep_idx);
-
-    /*if rx fifo count equal 0,it means last is send nack and ringbuffer is smaller than 64,
-    * so,if ringbuffer is larger than 64,set ack to recv next data.
-    */
-    if (overflow_flag && (Ring_Buffer_Get_Empty_Length(rb) > 64) && (!recv_len)) {
-        overflow_flag = false;
-        USB_Set_EPx_Rdy(ep_idx);
-        return 0;
-    } else {
-        uint32_t addr = USB_BASE + 0x11C + (ep_idx - 1) * 0x10;
-        Ring_Buffer_Write_Callback(rb, recv_len, fifocopy_to_mem, (void *)addr);
-
-        if (Ring_Buffer_Get_Empty_Length(rb) < 64) {
-            overflow_flag = true;
-            return -USB_DC_RB_SIZE_SMALL_ERR;
-        }
-
-        USB_Set_EPx_Rdy(ep_idx);
-        return 0;
-    }
+    USB_Set_EPx_Rdy(ep_idx);
+    return 0;
+  }
 }
 /**
  * @brief
@@ -983,46 +959,45 @@ int usb_dc_receive_to_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8
  * @param ep
  * @return int
  */
-int usb_dc_send_from_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8_t ep)
-{
-    uint8_t ep_idx;
-    static bool zlp_flag = false;
-    static uint32_t send_total_len = 0;
+int usb_dc_send_from_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8_t ep) {
+  uint8_t         ep_idx;
+  static bool     zlp_flag       = false;
+  static uint32_t send_total_len = 0;
 
-    ep_idx = USB_EP_GET_IDX(ep);
+  ep_idx = USB_EP_GET_IDX(ep);
 
-    /* Check if IN ep */
-    if (USB_EP_GET_DIR(ep) != USB_EP_DIR_IN) {
-        return -USB_DC_EP_DIR_ERR;
-    }
+  /* Check if IN ep */
+  if (USB_EP_GET_DIR(ep) != USB_EP_DIR_IN) {
+    return -USB_DC_EP_DIR_ERR;
+  }
 
-    /* Check if ep enabled */
-    if (!usb_ep_is_enabled(ep)) {
-        return -USB_DC_EP_EN_ERR;
-    }
+  /* Check if ep enabled */
+  if (!usb_ep_is_enabled(ep)) {
+    return -USB_DC_EP_EN_ERR;
+  }
 
-    uint32_t addr = USB_BASE + 0x118 + (ep_idx - 1) * 0x10;
+  uint32_t addr = USB_BASE + 0x118 + (ep_idx - 1) * 0x10;
 
-    if (zlp_flag == false) {
-        if ((USB_Get_EPx_TX_FIFO_CNT(ep_idx) == USB_FS_MAX_PACKET_SIZE) && Ring_Buffer_Get_Length(rb)) {
-            uint32_t actual_len = Ring_Buffer_Read_Callback(rb, USB_FS_MAX_PACKET_SIZE, memcopy_to_fifo, (void *)addr);
-            send_total_len += actual_len;
+  if (zlp_flag == false) {
+    if ((USB_Get_EPx_TX_FIFO_CNT(ep_idx) == USB_FS_MAX_PACKET_SIZE) && Ring_Buffer_Get_Length(rb)) {
+      uint32_t actual_len = Ring_Buffer_Read_Callback(rb, USB_FS_MAX_PACKET_SIZE, memcopy_to_fifo, (void *)addr);
+      send_total_len += actual_len;
 
-            if (!Ring_Buffer_Get_Length(rb) && (!(send_total_len % 64))) {
-                zlp_flag = true;
-            }
+      if (!Ring_Buffer_Get_Length(rb) && (!(send_total_len % 64))) {
+        zlp_flag = true;
+      }
 
-            USB_Set_EPx_Rdy(ep_idx);
-            return 0;
-        } else {
-            return -USB_DC_RB_SIZE_SMALL_ERR;
-        }
+      USB_Set_EPx_Rdy(ep_idx);
+      return 0;
     } else {
-        zlp_flag = false;
-        send_total_len = 0;
-        USB_Set_EPx_Rdy(ep_idx);
-        return -USB_DC_ZLP_ERR;
+      return -USB_DC_RB_SIZE_SMALL_ERR;
     }
+  } else {
+    zlp_flag       = false;
+    send_total_len = 0;
+    USB_Set_EPx_Rdy(ep_idx);
+    return -USB_DC_ZLP_ERR;
+  }
 }
 
 /**
@@ -1030,144 +1005,140 @@ int usb_dc_send_from_ringbuffer(struct device *dev, Ring_Buffer_Type *rb, uint8_
  *
  * @param device
  */
-void usb_dc_isr(usb_dc_device_t *device)
-{
-    USB_EP_ID epnum = EP_ID0;
-
-    /* EP1_DONE -> EP2_DONE -> ...... -> EP7_DONE*/
-    for (USB_INT_Type epint = USB_INT_EP1_DONE; epint <= USB_INT_EP7_DONE; epint += 2) {
-        if (USB_Get_IntStatus(epint)) {
-            epnum = (epint - USB_INT_EP0_OUT_CMD) >> 1;
-            if (!USB_Is_EPx_RDY_Free(epnum) && (device->out_ep[epnum].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
-                USB_DC_LOG_ERR("ep%d out busy\r\n", epnum);
-                continue;
-            }
-            USB_Clr_IntStatus(epint);
-            device->parent.callback(&device->parent, (void *)((uint32_t)USB_SET_EP_OUT(epnum)), 0, USB_DC_EVENT_EP_OUT_NOTIFY);
-        }
-    }
-
-    /* EP1_CMD -> EP2_CMD -> ...... -> EP7_CMD*/
-    for (USB_INT_Type epint = USB_INT_EP1_CMD; epint <= USB_INT_EP7_CMD; epint += 2) {
-        if (USB_Get_IntStatus(epint)) {
-            epnum = (epint - USB_INT_EP0_OUT_CMD) >> 1;
-            if (!USB_Is_EPx_RDY_Free(epnum) && (device->in_ep[epnum].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
-                USB_DC_LOG_DBG("ep%d in busy\r\n", epnum);
-                continue;
-            }
-            USB_Clr_IntStatus(epint);
-            device->parent.callback(&device->parent, (void *)((uint32_t)USB_SET_EP_IN(epnum)), 0, USB_DC_EVENT_EP_IN_NOTIFY);
-        }
-    }
-
-    /* EP0 setup done */
-    if (USB_Get_IntStatus(USB_INT_EP0_SETUP_DONE)) {
-        if (!USB_Is_EPx_RDY_Free(0)) {
-            USB_DC_LOG_DBG("ep0 setup busy\r\n");
-            return;
-        }
-        USB_Clr_IntStatus(USB_INT_EP0_SETUP_DONE);
-        device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_SETUP_NOTIFY);
-        USB_Set_EPx_Rdy(EP_ID0);
-        return;
-    }
-
-    /* EP0 in done */
-    if (USB_Get_IntStatus(USB_INT_EP0_IN_DONE)) {
-        if (!USB_Is_EPx_RDY_Free(0)) {
-            USB_DC_LOG_DBG("ep0 in busy\r\n");
-            return;
-        }
-        USB_Clr_IntStatus(USB_INT_EP0_IN_DONE);
-        device->parent.callback(&device->parent, (void *)0x80, 0, USB_DC_EVENT_EP0_IN_NOTIFY);
-        USB_Set_EPx_Rdy(EP_ID0);
-        return;
+void usb_dc_isr(usb_dc_device_t *device) {
+  USB_EP_ID epnum = EP_ID0;
+
+  /* EP1_DONE -> EP2_DONE -> ...... -> EP7_DONE*/
+  for (USB_INT_Type epint = USB_INT_EP1_DONE; epint <= USB_INT_EP7_DONE; epint += 2) {
+    if (USB_Get_IntStatus(epint)) {
+      epnum = (epint - USB_INT_EP0_OUT_CMD) >> 1;
+      if (!USB_Is_EPx_RDY_Free(epnum) && (device->out_ep[epnum].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
+        USB_DC_LOG_ERR("ep%d out busy\r\n", epnum);
+        continue;
+      }
+      USB_Clr_IntStatus(epint);
+      device->parent.callback(&device->parent, (void *)((uint32_t)USB_SET_EP_OUT(epnum)), 0, USB_DC_EVENT_EP_OUT_NOTIFY);
     }
-
-    /* EP0 out done */
-    if (USB_Get_IntStatus(USB_INT_EP0_OUT_DONE)) {
-        if (!USB_Is_EPx_RDY_Free(0)) {
-            USB_DC_LOG_DBG("ep0 out busy\r\n");
-            return;
-        }
-        USB_Clr_IntStatus(USB_INT_EP0_OUT_DONE);
-        device->parent.callback(&device->parent, (void *)0x00, 0, USB_DC_EVENT_EP0_OUT_NOTIFY);
-        USB_Set_EPx_Rdy(EP_ID0);
-        return;
+  }
+
+  /* EP1_CMD -> EP2_CMD -> ...... -> EP7_CMD*/
+  for (USB_INT_Type epint = USB_INT_EP1_CMD; epint <= USB_INT_EP7_CMD; epint += 2) {
+    if (USB_Get_IntStatus(epint)) {
+      epnum = (epint - USB_INT_EP0_OUT_CMD) >> 1;
+      if (!USB_Is_EPx_RDY_Free(epnum) && (device->in_ep[epnum].ep_cfg.ep_type != USBD_EP_TYPE_ISOC)) {
+        USB_DC_LOG_DBG("ep%d in busy\r\n", epnum);
+        continue;
+      }
+      USB_Clr_IntStatus(epint);
+      device->parent.callback(&device->parent, (void *)((uint32_t)USB_SET_EP_IN(epnum)), 0, USB_DC_EVENT_EP_IN_NOTIFY);
     }
+  }
 
-    /* sof */
-    if (USB_Get_IntStatus(USB_INT_SOF)) {
-        USB_Clr_IntStatus(USB_INT_SOF);
-        device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_SOF);
-        return;
+  /* EP0 setup done */
+  if (USB_Get_IntStatus(USB_INT_EP0_SETUP_DONE)) {
+    if (!USB_Is_EPx_RDY_Free(0)) {
+      USB_DC_LOG_DBG("ep0 setup busy\r\n");
+      return;
     }
-
-    /* reset */
-    if (USB_Get_IntStatus(USB_INT_RESET)) {
-        USB_Clr_IntStatus(USB_INT_RESET);
-        device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_RESET);
-        return;
+    USB_Clr_IntStatus(USB_INT_EP0_SETUP_DONE);
+    device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_SETUP_NOTIFY);
+    USB_Set_EPx_Rdy(EP_ID0);
+    return;
+  }
+
+  /* EP0 in done */
+  if (USB_Get_IntStatus(USB_INT_EP0_IN_DONE)) {
+    if (!USB_Is_EPx_RDY_Free(0)) {
+      USB_DC_LOG_DBG("ep0 in busy\r\n");
+      return;
     }
-
-    /* reset end */
-    if (USB_Get_IntStatus(USB_INT_RESET_END)) {
-        USB_Clr_IntStatus(USB_INT_RESET_END);
-        USB_Set_EPx_Rdy(EP_ID0);
-        return;
-    }
-
-    /* vbus toggle */
-    if (USB_Get_IntStatus(USB_INT_VBUS_TGL)) {
-        USB_Clr_IntStatus(USB_INT_VBUS_TGL);
-        return;
+    USB_Clr_IntStatus(USB_INT_EP0_IN_DONE);
+    device->parent.callback(&device->parent, (void *)0x80, 0, USB_DC_EVENT_EP0_IN_NOTIFY);
+    USB_Set_EPx_Rdy(EP_ID0);
+    return;
+  }
+
+  /* EP0 out done */
+  if (USB_Get_IntStatus(USB_INT_EP0_OUT_DONE)) {
+    if (!USB_Is_EPx_RDY_Free(0)) {
+      USB_DC_LOG_DBG("ep0 out busy\r\n");
+      return;
     }
+    USB_Clr_IntStatus(USB_INT_EP0_OUT_DONE);
+    device->parent.callback(&device->parent, (void *)0x00, 0, USB_DC_EVENT_EP0_OUT_NOTIFY);
+    USB_Set_EPx_Rdy(EP_ID0);
+    return;
+  }
+
+  /* sof */
+  if (USB_Get_IntStatus(USB_INT_SOF)) {
+    USB_Clr_IntStatus(USB_INT_SOF);
+    device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_SOF);
+    return;
+  }
+
+  /* reset */
+  if (USB_Get_IntStatus(USB_INT_RESET)) {
+    USB_Clr_IntStatus(USB_INT_RESET);
+    device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_RESET);
+    return;
+  }
+
+  /* reset end */
+  if (USB_Get_IntStatus(USB_INT_RESET_END)) {
+    USB_Clr_IntStatus(USB_INT_RESET_END);
+    USB_Set_EPx_Rdy(EP_ID0);
+    return;
+  }
+
+  /* vbus toggle */
+  if (USB_Get_IntStatus(USB_INT_VBUS_TGL)) {
+    USB_Clr_IntStatus(USB_INT_VBUS_TGL);
+    return;
+  }
 #ifdef ENABLE_LPM_INT
-    /* LPM wakeup */
-    if (USB_Get_IntStatus(USB_INT_LPM_WAKEUP)) {
-        USB_Clr_IntStatus(USB_INT_LPM_WAKEUP);
-        return;
+  /* LPM wakeup */
+  if (USB_Get_IntStatus(USB_INT_LPM_WAKEUP)) {
+    USB_Clr_IntStatus(USB_INT_LPM_WAKEUP);
+    return;
+  }
+
+  /* LPM packet */
+  if (USB_Get_IntStatus(USB_INT_LPM_PACKET)) {
+    /*************************************/
+    /* Force low-power mode in the macrocell */
+    if (USB_Get_IntStatus(USB_INT_LPM_WAKEUP) == 0) {
     }
 
-    /* LPM packet */
-    if (USB_Get_IntStatus(USB_INT_LPM_PACKET)) {
-        /*************************************/
-        /* Force low-power mode in the macrocell */
-        if (USB_Get_IntStatus(USB_INT_LPM_WAKEUP) == 0) {
-        }
-
-        /*************************************/
-        USB_Clr_IntStatus(USB_INT_LPM_PACKET);
-        return;
-    }
+    /*************************************/
+    USB_Clr_IntStatus(USB_INT_LPM_PACKET);
+    return;
+  }
 #endif
 #ifdef ENABLE_SOF3MS_INT
-    /* lost 3 SOF */
-    if (USB_Get_IntStatus(USB_INT_LOST_SOF_3_TIMES)) {
-        USB_DC_LOG_ERR("Lost 3 SOFs\r\n");
-        /*************************************/
-        /*************************************/
-        USB_Clr_IntStatus(USB_INT_LOST_SOF_3_TIMES);
-        return;
-    }
+  /* lost 3 SOF */
+  if (USB_Get_IntStatus(USB_INT_LOST_SOF_3_TIMES)) {
+    USB_DC_LOG_ERR("Lost 3 SOFs\r\n");
+    /*************************************/
+    /*************************************/
+    USB_Clr_IntStatus(USB_INT_LOST_SOF_3_TIMES);
+    return;
+  }
 #endif
 #ifdef ENABLE_ERROR_INT
-    /* error */
-    if (USB_Get_IntStatus(USB_INT_ERROR)) {
-        USB_DC_LOG("USB bus error 0x%08x; EP2 fifo status 0x%08x\r\n", *(volatile uint32_t *)(0x4000D81C), *(volatile uint32_t *)(0x4000D920));
-        /*************************************/
-        /*************************************/
-        device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_ERROR);
-        USB_Clr_IntStatus(USB_INT_ERROR);
-        return;
-    }
+  /* error */
+  if (USB_Get_IntStatus(USB_INT_ERROR)) {
+    USB_DC_LOG("USB bus error 0x%08x; EP2 fifo status 0x%08x\r\n", *(volatile uint32_t *)(0x4000D81C), *(volatile uint32_t *)(0x4000D920));
+    /*************************************/
+    /*************************************/
+    device->parent.callback(&device->parent, NULL, 0, USB_DC_EVENT_ERROR);
+    USB_Clr_IntStatus(USB_INT_ERROR);
+    return;
+  }
 #endif
 }
 /**
  * @brief
  *
  */
-void USB_FS_IRQ(void)
-{
-    usb_dc_isr(&usb_fs_device);
-}
\ No newline at end of file
+void USB_FS_IRQ(void) { usb_dc_isr(&usb_fs_device); }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_wdt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_wdt.c
index 8b9ace43f..bad6cf980 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_wdt.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/hal_drv/src/hal_wdt.c
@@ -33,138 +33,132 @@ static wdt_device_t wdtx_device[WDT_MAX_INDEX] = {
 #endif
 };
 
-int wdt_open(struct device *dev, uint16_t oflag)
-{
-    // uint32_t tmpval;
-
-    /* watchdog timer disable*/
-    // tmpval = BL_RD_REG(TIMER_BASE, TIMER_WMER);
-    // BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpval, TIMER_WE));
-    // // MSG("wdt timeout %d \r\n", wdt_device->wdt_timeout);
-    // /* Set watchdog timer match register value */
-    // BL_WR_REG(TIMER_BASE, TIMER_WMR, (uint16_t)wdt_device->wdt_timeout);
-
-    if (oflag & DEVICE_OFLAG_INT_TX) {
+int wdt_open(struct device *dev, uint16_t oflag) {
+  // uint32_t tmpval;
+
+  /* watchdog timer disable*/
+  // tmpval = BL_RD_REG(TIMER_BASE, TIMER_WMER);
+  // BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpval, TIMER_WE));
+  // // MSG("wdt timeout %d \r\n", wdt_device->wdt_timeout);
+  // /* Set watchdog timer match register value */
+  // BL_WR_REG(TIMER_BASE, TIMER_WMR, (uint16_t)wdt_device->wdt_timeout);
+
+  if (oflag & DEVICE_OFLAG_INT_TX) {
 #ifdef BSP_USING_WDT
-        wdt_device_t *wdt_device = (wdt_device_t *)dev;
-        // WDT_IntMask(WDT_INT, UNMASK);
-        if (wdt_device->id == 0) {
-            Interrupt_Handler_Register(TIMER_WDT_IRQn, WDT_IRQ);
-        }
-#endif
-    } else {
-        WDT_IntMask(WDT_INT, MASK);
+    wdt_device_t *wdt_device = (wdt_device_t *)dev;
+    // WDT_IntMask(WDT_INT, UNMASK);
+    if (wdt_device->id == 0) {
+      Interrupt_Handler_Register(TIMER_WDT_IRQn, WDT_IRQ);
     }
+#endif
+  } else {
+    WDT_IntMask(WDT_INT, MASK);
+  }
 
-    // /* enable watchdog timer */
-    WDT_Enable();
-    return 0;
+  // /* enable watchdog timer */
+  WDT_Enable();
+  return 0;
 }
 
-int wdt_close(struct device *dev)
-{
-    // wdt_device_t *wdt_device = (wdt_device_t *)(dev);
-    WDT_Disable();
-    return 0;
+int wdt_close(struct device *dev) {
+  // wdt_device_t *wdt_device = (wdt_device_t *)(dev);
+  WDT_Disable();
+  return 0;
 }
 
-int wdt_control(struct device *dev, int cmd, void *args)
-{
-    // wdt_device_t *wdt_device = (wdt_device_t *)dev;
-
-    switch (cmd) {
-        case DEVICE_CTRL_SET_INT: {
-            WDT_IntMask(WDT_INT, UNMASK);
-            CPU_Interrupt_Pending_Clear(TIMER_WDT_IRQn);
-            CPU_Interrupt_Enable(TIMER_WDT_IRQn);
-            break;
-        }
-        case DEVICE_CTRL_CLR_INT: {
-            WDT_IntMask(WDT_INT, MASK);
-            CPU_Interrupt_Disable(TIMER_WDT_IRQn);
-            break;
-        }
-        case DEVICE_CTRL_CONFIG: {
-            break;
-        }
-        case DEVICE_CTRL_RESUME: {
-            WDT_Enable();
-            break;
-        }
-        case DEVICE_CTRL_SUSPEND: {
-            WDT_Disable();
-            break;
-        }
-        case DEVICE_CTRL_GET_WDT_COUNTER: {
-            return WDT_GetCounterValue();
-            break;
-        }
-        case DEVICE_CTRL_RST_WDT_COUNTER: {
-            WDT_ResetCounterValue();
-            break;
-        }
-        case DEVICE_CTRL_GET_RST_STATUS: {
-            return WDT_GetResetStatus();
-            break;
-        }
-        case DEVICE_CTRL_CLR_RST_STATUS: {
-            WDT_ClearResetStatus();
-            break;
-        }
-        default:
-            break;
-    }
-
-    return 0;
+int wdt_control(struct device *dev, int cmd, void *args) {
+  // wdt_device_t *wdt_device = (wdt_device_t *)dev;
+
+  switch (cmd) {
+  case DEVICE_CTRL_SET_INT: {
+    WDT_IntMask(WDT_INT, UNMASK);
+    CPU_Interrupt_Pending_Clear(TIMER_WDT_IRQn);
+    CPU_Interrupt_Enable(TIMER_WDT_IRQn);
+    break;
+  }
+  case DEVICE_CTRL_CLR_INT: {
+    WDT_IntMask(WDT_INT, MASK);
+    CPU_Interrupt_Disable(TIMER_WDT_IRQn);
+    break;
+  }
+  case DEVICE_CTRL_CONFIG: {
+    break;
+  }
+  case DEVICE_CTRL_RESUME: {
+    WDT_Enable();
+    break;
+  }
+  case DEVICE_CTRL_SUSPEND: {
+    WDT_Disable();
+    break;
+  }
+  case DEVICE_CTRL_GET_WDT_COUNTER: {
+    return WDT_GetCounterValue();
+    break;
+  }
+  case DEVICE_CTRL_RST_WDT_COUNTER: {
+    WDT_ResetCounterValue();
+    break;
+  }
+  case DEVICE_CTRL_GET_RST_STATUS: {
+    return WDT_GetResetStatus();
+    break;
+  }
+  case DEVICE_CTRL_CLR_RST_STATUS: {
+    WDT_ClearResetStatus();
+    break;
+  }
+  default:
+    break;
+  }
+
+  return 0;
 }
 
-int wdt_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size)
-{
-    // wdt_device_t *wdt_device = (wdt_device_t *)dev;
-    uint16_t wdt_timeout = (uint16_t)(uint32_t)buffer;
+int wdt_write(struct device *dev, uint32_t pos, const void *buffer, uint32_t size) {
+  // wdt_device_t *wdt_device = (wdt_device_t *)dev;
+  uint16_t wdt_timeout = (uint16_t)(uint32_t)buffer;
 
-    WDT_Disable();
-    WDT_SetCompValue(wdt_timeout);
-    WDT_Enable();
+  WDT_Disable();
+  WDT_SetCompValue(wdt_timeout);
+  WDT_Enable();
 
-    return 0;
+  return 0;
 }
 
-int wdt_register(enum wdt_index_type index, const char *name)
-{
-    struct device *dev;
+int wdt_register(enum wdt_index_type index, const char *name) {
+  struct device *dev;
 
-    if (WDT_MAX_INDEX == 0) {
-        return -DEVICE_EINVAL;
-    }
+  if (WDT_MAX_INDEX == 0) {
+    return -DEVICE_EINVAL;
+  }
 
-    dev = &(wdtx_device[index].parent);
+  dev = &(wdtx_device[index].parent);
 
-    dev->open = wdt_open;
-    dev->close = wdt_close;
-    dev->control = wdt_control;
-    dev->write = wdt_write;
-    // dev->read = NULL;
+  dev->open    = wdt_open;
+  dev->close   = wdt_close;
+  dev->control = wdt_control;
+  dev->write   = wdt_write;
+  // dev->read = NULL;
 
-    dev->status = DEVICE_UNREGISTER;
-    dev->type = DEVICE_CLASS_TIMER;
-    dev->handle = NULL;
+  dev->status = DEVICE_UNREGISTER;
+  dev->type   = DEVICE_CLASS_TIMER;
+  dev->handle = NULL;
 
-    return device_register(dev, name);
+  return device_register(dev, name);
 }
 
-void wdt_isr(wdt_device_t *handle)
-{
-    uint32_t tmpval;
+void wdt_isr(wdt_device_t *handle) {
+  uint32_t tmpval;
 
-    if (!handle->parent.callback) {
-        return;
-    }
+  if (!handle->parent.callback) {
+    return;
+  }
 
-    tmpval = BL_RD_REG(TIMER_BASE, TIMER_WICR);
-    BL_WR_REG(TIMER_BASE, TIMER_WICR, BL_SET_REG_BIT(tmpval, TIMER_WICLR));
+  tmpval = BL_RD_REG(TIMER_BASE, TIMER_WICR);
+  BL_WR_REG(TIMER_BASE, TIMER_WICR, BL_SET_REG_BIT(tmpval, TIMER_WICLR));
 
-    handle->parent.callback(&handle->parent, NULL, 0, WDT_EVENT);
+  handle->parent.callback(&handle->parent, NULL, 0, WDT_EVENT);
 }
 
 #ifdef BSP_USING_WDT
@@ -172,8 +166,5 @@ void wdt_isr(wdt_device_t *handle)
  * @brief
  *
  */
-void WDT_IRQ(void)
-{
-    wdt_isr(&wdtx_device[WDT_INDEX]);
-}
+void WDT_IRQ(void) { wdt_isr(&wdtx_device[WDT_INDEX]); }
 #endif
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c
index 7369b7c50..a073e57d9 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/drv_mmheap.c
@@ -29,25 +29,13 @@
 #define MEM_MANAGE_MINUM_MEM_SIZE         (MEM_MANAGE_MEM_STRUCT_SIZE << 1)
 #define MEM_MANAGE_ALLOCA_LABAL           ((size_t)((size_t)1 << (sizeof(size_t) * MEM_MANAGE_BITS_PER_BYTE - 1)))
 
-static inline size_t mmheap_align_down(size_t data, size_t align_byte)
-{
-    return data & ~(align_byte - 1);
-}
+static inline size_t mmheap_align_down(size_t data, size_t align_byte) { return data & ~(align_byte - 1); }
 
-static inline size_t mmheap_align_up(size_t data, size_t align_byte)
-{
-    return (data + align_byte - 1) & ~(align_byte - 1);
-}
+static inline size_t mmheap_align_up(size_t data, size_t align_byte) { return (data + align_byte - 1) & ~(align_byte - 1); }
 
-static inline struct heap_node *mmheap_addr_sub(const void *addr)
-{
-    return (struct heap_node *)((const uint8_t *)addr - MEM_MANAGE_MEM_STRUCT_SIZE);
-}
+static inline struct heap_node *mmheap_addr_sub(const void *addr) { return (struct heap_node *)((const uint8_t *)addr - MEM_MANAGE_MEM_STRUCT_SIZE); }
 
-static inline void *mmheap_addr_add(const struct heap_node *mem_node)
-{
-    return (void *)((const uint8_t *)mem_node + MEM_MANAGE_MEM_STRUCT_SIZE);
-}
+static inline void *mmheap_addr_add(const struct heap_node *mem_node) { return (void *)((const uint8_t *)mem_node + MEM_MANAGE_MEM_STRUCT_SIZE); }
 
 /**
  * @brief mmheap_insert_node_to_freelist
@@ -55,40 +43,39 @@ static inline void *mmheap_addr_add(const struct heap_node *mem_node)
  * @param pRoot
  * @param pNode
  */
-static inline void mmheap_insert_node_to_freelist(struct heap_info *pRoot, struct heap_node *pNode)
-{
-    struct heap_node *pPriv_Node;
-    struct heap_node *pNext_Node;
-    /*Find the node with an address similar to pNode*/
-    for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pNode; pPriv_Node = pPriv_Node->next_node) {
-    }
+static inline void mmheap_insert_node_to_freelist(struct heap_info *pRoot, struct heap_node *pNode) {
+  struct heap_node *pPriv_Node;
+  struct heap_node *pNext_Node;
+  /*Find the node with an address similar to pNode*/
+  for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pNode; pPriv_Node = pPriv_Node->next_node) {
+  }
 
-    pNext_Node = pPriv_Node->next_node;
-    /*Try to merge the pNode with the previous block*/
-    if ((uint8_t *)mmheap_addr_add(pPriv_Node) + pPriv_Node->mem_size == (uint8_t *)pNode) {
-        if (pPriv_Node != pRoot->pStart) { /*can merge if not start block*/
-            pPriv_Node->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNode->mem_size;
-            pNode = pPriv_Node;
-        } else {
-            /*The latter is not merged if it is a Start block to avoid wasting memory*/
-            pRoot->pStart->next_node = pNode;
-        }
+  pNext_Node = pPriv_Node->next_node;
+  /*Try to merge the pNode with the previous block*/
+  if ((uint8_t *)mmheap_addr_add(pPriv_Node) + pPriv_Node->mem_size == (uint8_t *)pNode) {
+    if (pPriv_Node != pRoot->pStart) { /*can merge if not start block*/
+      pPriv_Node->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNode->mem_size;
+      pNode = pPriv_Node;
     } else {
-        /*Insert directly into the free single-chain table when merging is not possible*/
-        pPriv_Node->next_node = pNode;
+      /*The latter is not merged if it is a Start block to avoid wasting memory*/
+      pRoot->pStart->next_node = pNode;
     }
-    /*Try to merge the pNode with the next block*/
-    if ((uint8_t *)mmheap_addr_add(pNode) + pNode->mem_size == (uint8_t *)pNext_Node) {
-        if (pNext_Node != pRoot->pEnd) {
-            pNode->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNext_Node->mem_size;
-            pNode->next_node = pNext_Node->next_node;
-        } else {
-            pNode->next_node = pRoot->pEnd;
-        }
+  } else {
+    /*Insert directly into the free single-chain table when merging is not possible*/
+    pPriv_Node->next_node = pNode;
+  }
+  /*Try to merge the pNode with the next block*/
+  if ((uint8_t *)mmheap_addr_add(pNode) + pNode->mem_size == (uint8_t *)pNext_Node) {
+    if (pNext_Node != pRoot->pEnd) {
+      pNode->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNext_Node->mem_size;
+      pNode->next_node = pNext_Node->next_node;
     } else {
-        /*Insert directly into the free single-chain table when merging is not possible*/
-        pNode->next_node = pNext_Node;
+      pNode->next_node = pRoot->pEnd;
     }
+  } else {
+    /*Insert directly into the free single-chain table when merging is not possible*/
+    pNode->next_node = pNext_Node;
+  }
 }
 
 /**
@@ -97,24 +84,25 @@ static inline void mmheap_insert_node_to_freelist(struct heap_info *pRoot, struc
  * @param pRoot
  * @param pState
  */
-void mmheap_get_state(struct heap_info *pRoot, struct heap_state *pState)
-{
-    MMHEAP_ASSERT(pRoot->pStart != NULL);
-    MMHEAP_ASSERT(pRoot->pEnd != NULL);
-    pState->max_node_size = pRoot->pStart->next_node->mem_size;
-    pState->min_node_size = pRoot->pStart->next_node->mem_size;
-    pState->remain_size = 0;
-    pState->free_node_num = 0;
-    MMHEAP_LOCK();
-    for (struct heap_node *pNode = pRoot->pStart->next_node; pNode->next_node != NULL; pNode = pNode->next_node) {
-        pState->remain_size += pNode->mem_size;
-        pState->free_node_num++;
-        if (pNode->mem_size > pState->max_node_size)
-            pState->max_node_size = pNode->mem_size;
-        if (pNode->mem_size < pState->min_node_size)
-            pState->min_node_size = pNode->mem_size;
+void mmheap_get_state(struct heap_info *pRoot, struct heap_state *pState) {
+  MMHEAP_ASSERT(pRoot->pStart != NULL);
+  MMHEAP_ASSERT(pRoot->pEnd != NULL);
+  pState->max_node_size = pRoot->pStart->next_node->mem_size;
+  pState->min_node_size = pRoot->pStart->next_node->mem_size;
+  pState->remain_size   = 0;
+  pState->free_node_num = 0;
+  MMHEAP_LOCK();
+  for (struct heap_node *pNode = pRoot->pStart->next_node; pNode->next_node != NULL; pNode = pNode->next_node) {
+    pState->remain_size += pNode->mem_size;
+    pState->free_node_num++;
+    if (pNode->mem_size > pState->max_node_size) {
+      pState->max_node_size = pNode->mem_size;
     }
-    MMHEAP_UNLOCK();
+    if (pNode->mem_size < pState->min_node_size) {
+      pState->min_node_size = pNode->mem_size;
+    }
+  }
+  MMHEAP_UNLOCK();
 }
 /**
  * @brief mmheap_align_alloc
@@ -124,88 +112,88 @@ void mmheap_get_state(struct heap_info *pRoot, struct heap_state *pState)
  * @param want_size
  * @return void*
  */
-void *mmheap_align_alloc(struct heap_info *pRoot, size_t align_size, size_t want_size)
-{
-    void *pReturn = NULL;
-    struct heap_node *pPriv_Node, *pNow_Node;
+void *mmheap_align_alloc(struct heap_info *pRoot, size_t align_size, size_t want_size) {
+  void             *pReturn = NULL;
+  struct heap_node *pPriv_Node, *pNow_Node;
 
-    MMHEAP_ASSERT(pRoot->pStart != NULL);
-    MMHEAP_ASSERT(pRoot->pEnd != NULL);
+  MMHEAP_ASSERT(pRoot->pStart != NULL);
+  MMHEAP_ASSERT(pRoot->pEnd != NULL);
 
-    if (want_size == 0) {
-        return NULL;
-    }
+  if (want_size == 0) {
+    return NULL;
+  }
 
-    if ((want_size & MEM_MANAGE_ALLOCA_LABAL) != 0) {
-        MMHEAP_MALLOC_FAIL();
-        return NULL;
-    }
+  if ((want_size & MEM_MANAGE_ALLOCA_LABAL) != 0) {
+    MMHEAP_MALLOC_FAIL();
+    return NULL;
+  }
 
-    if (align_size & (align_size - 1)) {
-        MMHEAP_MALLOC_FAIL();
-        return NULL;
-    }
+  if (align_size & (align_size - 1)) {
+    MMHEAP_MALLOC_FAIL();
+    return NULL;
+  }
 
-    MMHEAP_LOCK();
-    if (want_size < MEM_MANAGE_MINUM_MEM_SIZE)
-        want_size = MEM_MANAGE_MINUM_MEM_SIZE;
-    if (align_size < MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT)
-        align_size = MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT;
+  MMHEAP_LOCK();
+  if (want_size < MEM_MANAGE_MINUM_MEM_SIZE) {
+    want_size = MEM_MANAGE_MINUM_MEM_SIZE;
+  }
+  if (align_size < MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT) {
+    align_size = MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT;
+  }
 
-    want_size = mmheap_align_up(want_size, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
+  want_size = mmheap_align_up(want_size, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
 
-    pPriv_Node = pRoot->pStart;
-    pNow_Node = pRoot->pStart->next_node;
+  pPriv_Node = pRoot->pStart;
+  pNow_Node  = pRoot->pStart->next_node;
 
-    while (pNow_Node->next_node != NULL) {
-        if (pNow_Node->mem_size >= want_size + MEM_MANAGE_MEM_STRUCT_SIZE) {
-            size_t use_align_size;
-            size_t new_size;
-            pReturn = (void *)mmheap_align_up((size_t)mmheap_addr_add(pNow_Node), align_size); /*Calculate the aligned address*/
-            use_align_size = (uint8_t *)pReturn - (uint8_t *)mmheap_addr_add(pNow_Node);       /*Calculate the memory consumed by the alignment*/
-            if (use_align_size != 0) {                                                         /*if Memory misalignment*/
-                if (use_align_size < MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) { /*The unaligned value is too small*/
-                    pReturn = (void *)mmheap_align_up(
-                        (size_t)mmheap_addr_add(pNow_Node) + MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE, align_size);
-                    use_align_size = (uint8_t *)pReturn - (uint8_t *)mmheap_addr_add(pNow_Node);
-                }
-                if (use_align_size <= pNow_Node->mem_size) {
-                    new_size = pNow_Node->mem_size - use_align_size; /*Calculate the remaining memory size by removing the memory consumed by alignment*/
-                    if (new_size >= want_size) {                     /*Meet the conditions for distribution*/
-                        struct heap_node *pNew_Node = mmheap_addr_sub(pReturn);
-                        pNow_Node->mem_size -= new_size + MEM_MANAGE_MEM_STRUCT_SIZE; /*Split Node*/
-                        pNew_Node->mem_size = new_size;                               /*The new node is also not in the free chain and does not need to be discharged from the free chain*/
-                        pNew_Node->next_node = NULL;
-                        pNow_Node = pNew_Node;
-                        break;
-                    }
-                }
-            } else { /*Memory is directly aligned*/
-                pPriv_Node->next_node = pNow_Node->next_node;
-                pNow_Node->next_node = NULL;
-                break;
-            }
+  while (pNow_Node->next_node != NULL) {
+    if (pNow_Node->mem_size >= want_size + MEM_MANAGE_MEM_STRUCT_SIZE) {
+      size_t use_align_size;
+      size_t new_size;
+      pReturn        = (void *)mmheap_align_up((size_t)mmheap_addr_add(pNow_Node), align_size); /*Calculate the aligned address*/
+      use_align_size = (uint8_t *)pReturn - (uint8_t *)mmheap_addr_add(pNow_Node);              /*Calculate the memory consumed by the alignment*/
+      if (use_align_size != 0) {                                                                /*if Memory misalignment*/
+        if (use_align_size < MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) {          /*The unaligned value is too small*/
+          pReturn        = (void *)mmheap_align_up((size_t)mmheap_addr_add(pNow_Node) + MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE, align_size);
+          use_align_size = (uint8_t *)pReturn - (uint8_t *)mmheap_addr_add(pNow_Node);
         }
-        pPriv_Node = pNow_Node;
-        pNow_Node = pNow_Node->next_node;
-    }
-
-    if (pNow_Node == pRoot->pEnd) {
-        MMHEAP_UNLOCK();
-        MMHEAP_MALLOC_FAIL();
-        return NULL;
+        if (use_align_size <= pNow_Node->mem_size) {
+          new_size = pNow_Node->mem_size - use_align_size; /*Calculate the remaining memory size by removing the memory consumed by alignment*/
+          if (new_size >= want_size) {                     /*Meet the conditions for distribution*/
+            struct heap_node *pNew_Node = mmheap_addr_sub(pReturn);
+            pNow_Node->mem_size -= new_size + MEM_MANAGE_MEM_STRUCT_SIZE; /*Split Node*/
+            pNew_Node->mem_size  = new_size;                              /*The new node is also not in the free chain and does not need to be discharged from the free chain*/
+            pNew_Node->next_node = NULL;
+            pNow_Node            = pNew_Node;
+            break;
+          }
+        }
+      } else { /*Memory is directly aligned*/
+        pPriv_Node->next_node = pNow_Node->next_node;
+        pNow_Node->next_node  = NULL;
+        break;
+      }
     }
+    pPriv_Node = pNow_Node;
+    pNow_Node  = pNow_Node->next_node;
+  }
 
-    if (pNow_Node->mem_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE + want_size) {           /*Node memory is still available*/
-        struct heap_node *pNew_Node = (struct heap_node *)((uint8_t *)mmheap_addr_add(pNow_Node) + want_size); /*Calculate the address of the node that will be moved into the free chain table*/
-        pNew_Node->mem_size = pNow_Node->mem_size - want_size - MEM_MANAGE_MEM_STRUCT_SIZE;
-        pNew_Node->next_node = NULL;
-        pNow_Node->mem_size = want_size;
-        mmheap_insert_node_to_freelist(pRoot, pNew_Node);
-    }
-    pNow_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+  if (pNow_Node == pRoot->pEnd) {
     MMHEAP_UNLOCK();
-    return pReturn;
+    MMHEAP_MALLOC_FAIL();
+    return NULL;
+  }
+
+  if (pNow_Node->mem_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE + want_size) {         /*Node memory is still available*/
+    struct heap_node *pNew_Node = (struct heap_node *)((uint8_t *)mmheap_addr_add(pNow_Node) + want_size); /*Calculate the address of the node that will be moved into the free chain table*/
+    pNew_Node->mem_size         = pNow_Node->mem_size - want_size - MEM_MANAGE_MEM_STRUCT_SIZE;
+    pNew_Node->next_node        = NULL;
+    pNow_Node->mem_size         = want_size;
+    mmheap_insert_node_to_freelist(pRoot, pNew_Node);
+  }
+  pNow_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+  MMHEAP_UNLOCK();
+  return pReturn;
 }
 /**
  * @brief mmheap_alloc
@@ -214,10 +202,7 @@ void *mmheap_align_alloc(struct heap_info *pRoot, size_t align_size, size_t want
  * @param want_size
  * @return void*
  */
-void *mmheap_alloc(struct heap_info *pRoot, size_t want_size)
-{
-    return mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size);
-}
+void *mmheap_alloc(struct heap_info *pRoot, size_t want_size) { return mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size); }
 /**
  * @brief mmheap_realloc
  *
@@ -226,81 +211,78 @@ void *mmheap_alloc(struct heap_info *pRoot, size_t want_size)
  * @param want_size
  * @return void*
  */
-void *mmheap_realloc(struct heap_info *pRoot, void *src_addr, size_t want_size)
-{
-    void *pReturn = NULL;
-    struct heap_node *pNext_Node, *pPriv_Node;
-    struct heap_node *pSrc_Node;
-    MMHEAP_ASSERT(pRoot->pStart != NULL);
-    MMHEAP_ASSERT(pRoot->pEnd != NULL);
-    if (src_addr == NULL) {
-        return mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size);
-    }
-    if (want_size == 0) {
-        mmheap_free(pRoot, src_addr);
-        return NULL;
-    }
+void *mmheap_realloc(struct heap_info *pRoot, void *src_addr, size_t want_size) {
+  void             *pReturn = NULL;
+  struct heap_node *pNext_Node, *pPriv_Node;
+  struct heap_node *pSrc_Node;
+  MMHEAP_ASSERT(pRoot->pStart != NULL);
+  MMHEAP_ASSERT(pRoot->pEnd != NULL);
+  if (src_addr == NULL) {
+    return mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size);
+  }
+  if (want_size == 0) {
+    mmheap_free(pRoot, src_addr);
+    return NULL;
+  }
 
-    MMHEAP_LOCK();
-    if ((want_size & MEM_MANAGE_ALLOCA_LABAL) != 0) {
-        MMHEAP_UNLOCK();
-        MMHEAP_MALLOC_FAIL();
-        return NULL;
-    }
+  MMHEAP_LOCK();
+  if ((want_size & MEM_MANAGE_ALLOCA_LABAL) != 0) {
+    MMHEAP_UNLOCK();
+    MMHEAP_MALLOC_FAIL();
+    return NULL;
+  }
 
-    pSrc_Node = mmheap_addr_sub(src_addr);
+  pSrc_Node = mmheap_addr_sub(src_addr);
 
-    if ((pSrc_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) == 0) {
-        MMHEAP_UNLOCK();
-        MMHEAP_ASSERT((pSrc_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) != 0);
-        MMHEAP_MALLOC_FAIL();
-        return NULL;
-    }
+  if ((pSrc_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) == 0) {
+    MMHEAP_UNLOCK();
+    MMHEAP_ASSERT((pSrc_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) != 0);
+    MMHEAP_MALLOC_FAIL();
+    return NULL;
+  }
 
-    pSrc_Node->mem_size &= ~MEM_MANAGE_ALLOCA_LABAL;
-    if (pSrc_Node->mem_size >= want_size) {
-        pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
-        pReturn = src_addr;
-        MMHEAP_UNLOCK();
-        return pReturn;
-    }
-    /*Start looking in the free list for blocks similar to this block*/
-    for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pSrc_Node; pPriv_Node = pPriv_Node->next_node) {
-    }
-    pNext_Node = pPriv_Node->next_node;
+  pSrc_Node->mem_size &= ~MEM_MANAGE_ALLOCA_LABAL;
+  if (pSrc_Node->mem_size >= want_size) {
+    pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+    pReturn = src_addr;
+    MMHEAP_UNLOCK();
+    return pReturn;
+  }
+  /*Start looking in the free list for blocks similar to this block*/
+  for (pPriv_Node = pRoot->pStart; pPriv_Node->next_node < pSrc_Node; pPriv_Node = pPriv_Node->next_node) {
+  }
+  pNext_Node = pPriv_Node->next_node;
 
-    if (pNext_Node != pRoot->pEnd &&
-        ((uint8_t *)src_addr + pSrc_Node->mem_size == (uint8_t *)pNext_Node) &&
-        (pSrc_Node->mem_size + pNext_Node->mem_size + MEM_MANAGE_MEM_STRUCT_SIZE >= want_size)) {
-        /*Meet next node non-end, memory contiguous, enough memory left*/
-        pReturn = src_addr;
-        pPriv_Node->next_node = pNext_Node->next_node;
-        pSrc_Node->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNext_Node->mem_size;
-        want_size = mmheap_align_up(want_size, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
-        if (pSrc_Node->mem_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE + want_size) { /*Removing the remaining space allocated is enough to open new blocks*/
-            struct heap_node *pNew_Node = (struct heap_node *)((uint8_t *)mmheap_addr_add(pSrc_Node) + want_size);
-            pNew_Node->next_node = NULL;
-            pNew_Node->mem_size = pSrc_Node->mem_size - want_size - MEM_MANAGE_MEM_STRUCT_SIZE;
-            pSrc_Node->mem_size = want_size;
-            mmheap_insert_node_to_freelist(pRoot, pNew_Node);
-        }
-        pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
-        MMHEAP_UNLOCK();
-    } else {
-        MMHEAP_UNLOCK();
-        pReturn = mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size);
-        if (pReturn == NULL) {
-            pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
-            MMHEAP_MALLOC_FAIL();
-            return NULL;
-        }
-        MMHEAP_LOCK();
-        memcpy(pReturn, src_addr, pSrc_Node->mem_size);
-        pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
-        MMHEAP_UNLOCK();
-        mmheap_free(pRoot, src_addr);
+  if (pNext_Node != pRoot->pEnd && ((uint8_t *)src_addr + pSrc_Node->mem_size == (uint8_t *)pNext_Node) && (pSrc_Node->mem_size + pNext_Node->mem_size + MEM_MANAGE_MEM_STRUCT_SIZE >= want_size)) {
+    /*Meet next node non-end, memory contiguous, enough memory left*/
+    pReturn               = src_addr;
+    pPriv_Node->next_node = pNext_Node->next_node;
+    pSrc_Node->mem_size += MEM_MANAGE_MEM_STRUCT_SIZE + pNext_Node->mem_size;
+    want_size = mmheap_align_up(want_size, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
+    if (pSrc_Node->mem_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE + want_size) { /*Removing the remaining space allocated is enough to open new blocks*/
+      struct heap_node *pNew_Node = (struct heap_node *)((uint8_t *)mmheap_addr_add(pSrc_Node) + want_size);
+      pNew_Node->next_node        = NULL;
+      pNew_Node->mem_size         = pSrc_Node->mem_size - want_size - MEM_MANAGE_MEM_STRUCT_SIZE;
+      pSrc_Node->mem_size         = want_size;
+      mmheap_insert_node_to_freelist(pRoot, pNew_Node);
     }
-    return pReturn;
+    pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+    MMHEAP_UNLOCK();
+  } else {
+    MMHEAP_UNLOCK();
+    pReturn = mmheap_align_alloc(pRoot, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT, want_size);
+    if (pReturn == NULL) {
+      pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+      MMHEAP_MALLOC_FAIL();
+      return NULL;
+    }
+    MMHEAP_LOCK();
+    memcpy(pReturn, src_addr, pSrc_Node->mem_size);
+    pSrc_Node->mem_size |= MEM_MANAGE_ALLOCA_LABAL;
+    MMHEAP_UNLOCK();
+    mmheap_free(pRoot, src_addr);
+  }
+  return pReturn;
 }
 /**
  * @brief
@@ -310,17 +292,16 @@ void *mmheap_realloc(struct heap_info *pRoot, void *src_addr, size_t want_size)
  * @param size
  * @return void*
  */
-void *mmheap_calloc(struct heap_info *pRoot, size_t num, size_t size)
-{
-    void *pReturn = NULL;
+void *mmheap_calloc(struct heap_info *pRoot, size_t num, size_t size) {
+  void *pReturn = NULL;
 
-    pReturn = (void *)mmheap_alloc(pRoot, size * num);
+  pReturn = (void *)mmheap_alloc(pRoot, size * num);
 
-    if (pReturn) {
-        memset(pReturn, 0, num * size);
-    }
+  if (pReturn) {
+    memset(pReturn, 0, num * size);
+  }
 
-    return pReturn;
+  return pReturn;
 }
 /**
  * @brief mmheap_free
@@ -328,32 +309,31 @@ void *mmheap_calloc(struct heap_info *pRoot, size_t num, size_t size)
  * @param pRoot
  * @param addr
  */
-void mmheap_free(struct heap_info *pRoot, void *addr)
-{
-    struct heap_node *pFree_Node;
-    MMHEAP_ASSERT(pRoot->pStart != NULL);
-    MMHEAP_ASSERT(pRoot->pEnd != NULL);
-    MMHEAP_LOCK();
-    if (addr == NULL) {
-        MMHEAP_UNLOCK();
-        return;
-    }
-    pFree_Node = mmheap_addr_sub(addr);
+void mmheap_free(struct heap_info *pRoot, void *addr) {
+  struct heap_node *pFree_Node;
+  MMHEAP_ASSERT(pRoot->pStart != NULL);
+  MMHEAP_ASSERT(pRoot->pEnd != NULL);
+  MMHEAP_LOCK();
+  if (addr == NULL) {
+    MMHEAP_UNLOCK();
+    return;
+  }
+  pFree_Node = mmheap_addr_sub(addr);
 
-    if ((pFree_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) == 0) {
-        MMHEAP_UNLOCK();
-        MMHEAP_ASSERT((pFree_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) != 0);
-        return;
-    }
+  if ((pFree_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) == 0) {
+    MMHEAP_UNLOCK();
+    MMHEAP_ASSERT((pFree_Node->mem_size & MEM_MANAGE_ALLOCA_LABAL) != 0);
+    return;
+  }
 
-    if (pFree_Node->next_node != NULL) {
-        MMHEAP_UNLOCK();
-        MMHEAP_ASSERT(pFree_Node->next_node == NULL);
-        return;
-    }
-    pFree_Node->mem_size &= ~MEM_MANAGE_ALLOCA_LABAL;
-    mmheap_insert_node_to_freelist(pRoot, pFree_Node);
+  if (pFree_Node->next_node != NULL) {
     MMHEAP_UNLOCK();
+    MMHEAP_ASSERT(pFree_Node->next_node == NULL);
+    return;
+  }
+  pFree_Node->mem_size &= ~MEM_MANAGE_ALLOCA_LABAL;
+  mmheap_insert_node_to_freelist(pRoot, pFree_Node);
+  MMHEAP_UNLOCK();
 }
 /**
  * @brief mmheap_init
@@ -361,61 +341,62 @@ void mmheap_free(struct heap_info *pRoot, void *addr)
  * @param pRoot
  * @param pRegion
  */
-void mmheap_init(struct heap_info *pRoot, const struct heap_region *pRegion)
-{
-    struct heap_node *align_addr;
-    size_t align_size;
-    struct heap_node *pPriv_node = NULL;
+void mmheap_init(struct heap_info *pRoot, const struct heap_region *pRegion) {
+  struct heap_node *align_addr;
+  size_t            align_size;
+  struct heap_node *pPriv_node = NULL;
 
-    pRoot->total_size = 0;
-    pRoot->pEnd = NULL;
-    pRoot->pStart = NULL;
+  pRoot->total_size = 0;
+  pRoot->pEnd       = NULL;
+  pRoot->pStart     = NULL;
 
-    for (; pRegion->addr != NULL; pRegion++) {
-        align_addr = (struct heap_node *)mmheap_align_up((size_t)pRegion->addr, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT); /*Calculate the aligned address*/
-        if ((uint8_t *)align_addr > pRegion->mem_size + (uint8_t *)pRegion->addr)                                   /*Alignment consumes more memory than the memory area*/
-            continue;
-        align_size = pRegion->mem_size - ((uint8_t *)align_addr - (uint8_t *)pRegion->addr); /*Calculate the size of memory left after alignment*/
-        if (align_size < MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE)             /*if Aligning the remaining memory is too small*/
-            continue;
-        align_size -= MEM_MANAGE_MEM_STRUCT_SIZE; /*Find the size of the memory block after removing the table header*/
-        align_addr->mem_size = align_size;
-        align_addr->next_node = NULL;
-        if (pRoot->pStart == NULL) {
-            pRoot->pStart = align_addr;                                                                   /*set current addr for start*/
-            if (align_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) {                   /*If the remaining blocks are large enough*/
-                align_size -= MEM_MANAGE_MEM_STRUCT_SIZE;                                                 /*Remove the next block of table headers remaining memory size*/
-                align_addr = (struct heap_node *)((uint8_t *)pRoot->pStart + MEM_MANAGE_MEM_STRUCT_SIZE); //the next block addr
-                align_addr->mem_size = align_size;
-                align_addr->next_node = NULL;
-                pRoot->pStart->mem_size = 0;
-                pRoot->pStart->next_node = align_addr;
-                pRoot->total_size = align_addr->mem_size;
-            } else { /*The memory is too small, and the address of the current memory block is recorded as start*/
-                pRoot->total_size = 0;
-                pRoot->pStart->mem_size = 0;
-            }
-        } else {
-            pPriv_node->next_node = align_addr;
-            pRoot->total_size += align_size;
-        }
-        pPriv_node = align_addr;
+  for (; pRegion->addr != NULL; pRegion++) {
+    align_addr = (struct heap_node *)mmheap_align_up((size_t)pRegion->addr, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT); /*Calculate the aligned address*/
+    if ((uint8_t *)align_addr > pRegion->mem_size + (uint8_t *)pRegion->addr) {                                 /*Alignment consumes more memory than the memory area*/
+      continue;
+    }
+    align_size = pRegion->mem_size - ((uint8_t *)align_addr - (uint8_t *)pRegion->addr); /*Calculate the size of memory left after alignment*/
+    if (align_size < MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) {           /*if Aligning the remaining memory is too small*/
+      continue;
     }
-    //At this point, pPriv_node is the last block, then place the end of the table at the end of the block, find the address to place the end block, end block is only convenient for traversal, so as small as possible, assigned to MEM_MANAGE_MEM_STRUCT_SIZE
-    align_addr = (struct heap_node *)mmheap_align_down(
-        (size_t)mmheap_addr_add(pPriv_node) + pPriv_node->mem_size - MEM_MANAGE_MEM_STRUCT_SIZE, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
-    align_size = (uint8_t *)align_addr - (uint8_t *)mmheap_addr_add(pPriv_node); /*Find the remaining size of the previous block after the end block is allocated*/
-    if (align_size >= MEM_MANAGE_MINUM_MEM_SIZE) {
-        pRoot->total_size -= pPriv_node->mem_size - align_size; /*Removing memory consumed by allocating end blocks*/
-        pRoot->pEnd = align_addr;                               /*Update the address at the end of the list*/
-        pPriv_node->next_node = align_addr;
-        pPriv_node->mem_size = align_size;
-        align_addr->next_node = NULL;
-        align_addr->mem_size = 0; /*The end block is not involved in memory allocation, so a direct 0 is sufficient*/
-    } else {                      /*The last block is too small, directly as the end block*/
-        pRoot->pEnd = pPriv_node;
-        pRoot->total_size -= pPriv_node->mem_size;
+    align_size -= MEM_MANAGE_MEM_STRUCT_SIZE; /*Find the size of the memory block after removing the table header*/
+    align_addr->mem_size  = align_size;
+    align_addr->next_node = NULL;
+    if (pRoot->pStart == NULL) {
+      pRoot->pStart = align_addr;                                                                               /*set current addr for start*/
+      if (align_size >= MEM_MANAGE_MINUM_MEM_SIZE + MEM_MANAGE_MEM_STRUCT_SIZE) {                               /*If the remaining blocks are large enough*/
+        align_size -= MEM_MANAGE_MEM_STRUCT_SIZE;                                                               /*Remove the next block of table headers remaining memory size*/
+        align_addr               = (struct heap_node *)((uint8_t *)pRoot->pStart + MEM_MANAGE_MEM_STRUCT_SIZE); // the next block addr
+        align_addr->mem_size     = align_size;
+        align_addr->next_node    = NULL;
+        pRoot->pStart->mem_size  = 0;
+        pRoot->pStart->next_node = align_addr;
+        pRoot->total_size        = align_addr->mem_size;
+      } else { /*The memory is too small, and the address of the current memory block is recorded as start*/
+        pRoot->total_size       = 0;
+        pRoot->pStart->mem_size = 0;
+      }
+    } else {
+      pPriv_node->next_node = align_addr;
+      pRoot->total_size += align_size;
     }
-    MMHEAP_ASSERT(pRoot->pStart != NULL);
-    MMHEAP_ASSERT(pRoot->pEnd != NULL);
+    pPriv_node = align_addr;
+  }
+  // At this point, pPriv_node is the last block, then place the end of the table at the end of the block, find the address to place the end block, end block is only convenient for traversal, so as
+  // small as possible, assigned to MEM_MANAGE_MEM_STRUCT_SIZE
+  align_addr = (struct heap_node *)mmheap_align_down((size_t)mmheap_addr_add(pPriv_node) + pPriv_node->mem_size - MEM_MANAGE_MEM_STRUCT_SIZE, MEM_MANAGE_ALIGNMENT_BYTE_DEFAULT);
+  align_size = (uint8_t *)align_addr - (uint8_t *)mmheap_addr_add(pPriv_node); /*Find the remaining size of the previous block after the end block is allocated*/
+  if (align_size >= MEM_MANAGE_MINUM_MEM_SIZE) {
+    pRoot->total_size -= pPriv_node->mem_size - align_size; /*Removing memory consumed by allocating end blocks*/
+    pRoot->pEnd           = align_addr;                     /*Update the address at the end of the list*/
+    pPriv_node->next_node = align_addr;
+    pPriv_node->mem_size  = align_size;
+    align_addr->next_node = NULL;
+    align_addr->mem_size  = 0; /*The end block is not involved in memory allocation, so a direct 0 is sufficient*/
+  } else {                     /*The last block is too small, directly as the end block*/
+    pRoot->pEnd = pPriv_node;
+    pRoot->total_size -= pPriv_node->mem_size;
+  }
+  MMHEAP_ASSERT(pRoot->pStart != NULL);
+  MMHEAP_ASSERT(pRoot->pEnd != NULL);
 }
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c
index 65ef20a26..65f2f55f4 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/interrupt.c
@@ -20,12 +20,12 @@
  * under the License.
  *
  */
-#include "bl702_common.h"
 #include "bflb_platform.h"
+#include "bl702_common.h"
 #include "risc-v/Core/Include/clic.h"
 #include "risc-v/Core/Include/riscv_encoding.h"
 
-pFunc __Interrupt_Handlers[IRQn_LAST] = { 0 };
+pFunc __Interrupt_Handlers[IRQn_LAST] = {0};
 
 void Interrupt_Handler_Stub(void);
 
@@ -91,17 +91,18 @@ void MAC_PORT_TRG_IRQHandler_Wrapper(void) __attribute__((weak, alias("Interrupt
 void WIFI_IPC_PUBLIC_IRQHandler_Wrapper(void) __attribute__((weak, alias("Interrupt_Handler_Stub")));
 
 const pFunc __Vectors[] __attribute__((section(".init"), aligned(64))) = {
-    0,                                   /*         */
-    0,                                   /*         */
-    0,                                   /*         */
-    clic_msip_handler_Wrapper,           /* 3       */
-    0,                                   /*         */
-    0,                                   /*         */
-    0,                                   /*         */
-    clic_mtimer_handler_Wrapper,         /* 7       */
-    (pFunc)0x00000001,                   /*         */
-    0,                                   /*         */
-    (pFunc)0x00000102, /*         */     //disable log as default
+    0,                           /*         */
+    0,                           /*         */
+    0,                           /*         */
+    clic_msip_handler_Wrapper,   /* 3       */
+    0,                           /*         */
+    0,                           /*         */
+    0,                           /*         */
+    clic_mtimer_handler_Wrapper, /* 7       */
+    (pFunc)0x00000001,           /*         */
+    0,                           /*         */
+    (pFunc)0x00000102,
+    /*         */                        // disable log as default
     clic_mext_handler_Wrapper,           /* 11      */
     clic_csoft_handler_Wrapper,          /* 12      */
     0,                                   /*         */
@@ -180,204 +181,162 @@ void vAssertCalled(void) {
   epc = get_pc();
   MSG("mepc:0x%08x\r\n", (uint32_t)epc);
 
-//   PWM_Channel_Disable(PWM_Channel);
-//   gpio_set_mode(PWM_Out_Pin, GPIO_INPUT_PD_MODE);
+  //   PWM_Channel_Disable(PWM_Channel);
+  //   gpio_set_mode(PWM_Out_Pin, GPIO_INPUT_PD_MODE);
 
-  while (1)
-    ;
+  while (1) {
+  }
 }
 
+void Trap_Handler(void) {
+  unsigned long cause;
+  unsigned long epc;
+  unsigned long tval;
+  uint8_t       isecall = 0;
 
-void Trap_Handler(void)
-{
-    unsigned long cause;
-    unsigned long epc;
-    unsigned long tval;
-    uint8_t isecall = 0;
-
-    MSG("Trap_Handler\r\n");
-
-    cause = read_csr(mcause);
-    MSG("mcause=%08x\r\n", (uint32_t)cause);
-    epc = get_pc();
-    MSG("mepc:%08x\r\n", (uint32_t)epc);
-    tval = read_csr(mtval);
-    MSG("mtval:%08x\r\n", (uint32_t)tval);
-
-    cause = (cause & 0x3ff);
-
-    switch (cause) {
-        case 1:
-            MSG("Instruction access fault\r\n");
-            break;
-
-        case 2:
-            MSG("Illegal instruction\r\n");
-            break;
-
-        case 3:
-            MSG("Breakpoint\r\n");
-            break;
-
-        case 4:
-            MSG("Load address misaligned\r\n");
-            break;
-
-        case 5:
-            MSG("Load access fault\r\n");
-            break;
-
-        case 6:
-            MSG("Store/AMO address misaligned\r\n");
-            break;
-
-        case 7:
-            MSG("Store/AMO access fault\r\n");
-            break;
-
-        case 8:
-            MSG("Environment call from U-mode\r\n");
-            epc += 4;
-            write_csr(mepc, epc);
-            break;
-
-        case 11:
-            MSG("Environment call from M-mode\r\n");
-            epc += 4;
-            write_csr(mepc, epc);
-            isecall = 1;
-            break;
-
-        default:
-            MSG("Cause num=%d\r\n", (uint32_t)cause);
-            epc += 4;
-            write_csr(mepc, epc);
-            break;
-    }
+  MSG("Trap_Handler\r\n");
 
-    if (!isecall) {
-        while (1)
-            ;
+  cause = read_csr(mcause);
+  MSG("mcause=%08x\r\n", (uint32_t)cause);
+  epc = get_pc();
+  MSG("mepc:%08x\r\n", (uint32_t)epc);
+  tval = read_csr(mtval);
+  MSG("mtval:%08x\r\n", (uint32_t)tval);
+
+  cause = (cause & 0x3ff);
+
+  switch (cause) {
+  case 1:
+    MSG("Instruction access fault\r\n");
+    break;
+
+  case 2:
+    MSG("Illegal instruction\r\n");
+    break;
+
+  case 3:
+    MSG("Breakpoint\r\n");
+    break;
+
+  case 4:
+    MSG("Load address misaligned\r\n");
+    break;
+
+  case 5:
+    MSG("Load access fault\r\n");
+    break;
+
+  case 6:
+    MSG("Store/AMO address misaligned\r\n");
+    break;
+
+  case 7:
+    MSG("Store/AMO access fault\r\n");
+    break;
+
+  case 8:
+    MSG("Environment call from U-mode\r\n");
+    epc += 4;
+    write_csr(mepc, epc);
+    break;
+
+  case 11:
+    MSG("Environment call from M-mode\r\n");
+    epc += 4;
+    write_csr(mepc, epc);
+    isecall = 1;
+    break;
+
+  default:
+    MSG("Cause num=%d\r\n", (uint32_t)cause);
+    epc += 4;
+    write_csr(mepc, epc);
+    break;
+  }
+
+  if (!isecall) {
+    while (1) {
     }
+  }
 }
 
-void Interrupt_Handler(void)
-{
-    pFunc interruptFun;
-    uint32_t num = 0;
-    volatile uint32_t ulMEPC = 0UL, ulMCAUSE = 0UL;
-
-    /* Store a few register values that might be useful when determining why this
-    function was called. */
-    __asm volatile("csrr %0, mepc"
-                   : "=r"(ulMEPC));
-    __asm volatile("csrr %0, mcause"
-                   : "=r"(ulMCAUSE));
-
-    if ((ulMCAUSE & 0x80000000) == 0) {
-        /*Exception*/
-        MSG("Exception should not be here\r\n");
-    } else {
-        num = ulMCAUSE & 0x3FF;
+void Interrupt_Handler(void) {
+  pFunc             interruptFun;
+  uint32_t          num    = 0;
+  volatile uint32_t ulMEPC = 0UL, ulMCAUSE = 0UL;
+
+  /* Store a few register values that might be useful when determining why this
+  function was called. */
+  __asm volatile("csrr %0, mepc" : "=r"(ulMEPC));
+  __asm volatile("csrr %0, mcause" : "=r"(ulMCAUSE));
 
-        if (num < IRQn_LAST) {
-            interruptFun = __Interrupt_Handlers[num];
+  if ((ulMCAUSE & 0x80000000) == 0) {
+    /*Exception*/
+    MSG("Exception should not be here\r\n");
+  } else {
+    num = ulMCAUSE & 0x3FF;
 
-            if (NULL != interruptFun) {
-                interruptFun();
-            } else {
-                MSG("Interrupt num:%d IRQHandler not installed\r\n", (unsigned int)num);
+    if (num < IRQn_LAST) {
+      interruptFun = __Interrupt_Handlers[num];
 
-                if (num >= IRQ_NUM_BASE) {
-                    MSG("Peripheral Interrupt num:%d \r\n", (unsigned int)num - IRQ_NUM_BASE);
-                }
+      if (NULL != interruptFun) {
+        interruptFun();
+      } else {
+        MSG("Interrupt num:%d IRQHandler not installed\r\n", (unsigned int)num);
 
-                while (1)
-                    ;
-            }
-        } else {
-            MSG("Unexpected interrupt num:%d\r\n", (unsigned int)num);
+        if (num >= IRQ_NUM_BASE) {
+          MSG("Peripheral Interrupt num:%d \r\n", (unsigned int)num - IRQ_NUM_BASE);
         }
+
+        while (1) {
+        }
+      }
+    } else {
+      MSG("Unexpected interrupt num:%d\r\n", (unsigned int)num);
     }
+  }
 }
 
-void handle_trap(void)
-{
+void handle_trap(void) {
 #define MCAUSE_INT_MASK  0x80000000 // [31]=1 interrupt, else exception
 #define MCAUSE_CODE_MASK 0x7FFFFFFF // low bits show code
 
-    unsigned long mcause_value = read_csr(mcause);
-    if (mcause_value & MCAUSE_INT_MASK) {
-        // Branch to interrupt handler here
-        Interrupt_Handler();
-    } else {
-        // Branch to exception handle
-        Trap_Handler();
-    }
-}
-
-void __IRQ_ALIGN64 Trap_Handler_Stub(void)
-{
+  unsigned long mcause_value = read_csr(mcause);
+  if (mcause_value & MCAUSE_INT_MASK) {
+    // Branch to interrupt handler here
+    Interrupt_Handler();
+  } else {
+    // Branch to exception handle
     Trap_Handler();
+  }
 }
 
-void __IRQ Interrupt_Handler_Stub(void)
-{
-    Interrupt_Handler();
-}
+void __IRQ_ALIGN64 Trap_Handler_Stub(void) { Trap_Handler(); }
 
-void FreeRTOS_Interrupt_Handler(void)
-{
-    Interrupt_Handler();
-}
+void __IRQ Interrupt_Handler_Stub(void) { Interrupt_Handler(); }
 
-void Interrupt_Handler_Register(IRQn_Type irq, pFunc interruptFun)
-{
-    if (irq < IRQn_LAST) {
-        __Interrupt_Handlers[irq] = interruptFun;
-    }
-}
+void FreeRTOS_Interrupt_Handler(void) { Interrupt_Handler(); }
 
-void System_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority)
-{
+void Interrupt_Handler_Register(IRQn_Type irq, pFunc interruptFun) {
+  if (irq < IRQn_LAST) {
+    __Interrupt_Handlers[irq] = interruptFun;
+  }
 }
 
-void clic_enable_interrupt(uint32_t source)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIE + source) = 1;
-}
+void System_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority) {}
 
-void clic_disable_interrupt(uint32_t source)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIE + source) = 0;
-}
+void clic_enable_interrupt(uint32_t source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIE + source) = 1; }
 
-void clic_clear_pending(uint32_t source)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIP + source) = 0;
-}
+void clic_disable_interrupt(uint32_t source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIE + source) = 0; }
 
-void clic_set_pending(uint32_t source)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIP + source) = 1;
-}
+void clic_clear_pending(uint32_t source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIP + source) = 0; }
 
-void clic_set_intcfg(uint32_t source, uint32_t intcfg)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTCFG + source) = intcfg;
-}
+void clic_set_pending(uint32_t source) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTIP + source) = 1; }
 
-uint8_t clic_get_intcfg(uint32_t source)
-{
-    return *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTCFG + source);
-}
+void clic_set_intcfg(uint32_t source, uint32_t intcfg) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTCFG + source) = intcfg; }
 
-void clic_set_cliccfg(uint32_t cfg)
-{
-    *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_CFG) = cfg;
-}
+uint8_t clic_get_intcfg(uint32_t source) { return *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_INTCFG + source); }
+
+void clic_set_cliccfg(uint32_t cfg) { *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_CFG) = cfg; }
 
-uint8_t clic_get_cliccfg(void)
-{
-    return *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_CFG);
-}
\ No newline at end of file
+uint8_t clic_get_cliccfg(void) { return *(volatile uint8_t *)(CLIC_HART0_ADDR + CLIC_CFG); }
\ No newline at end of file
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/system_bl702.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/system_bl702.c
index c030a5590..19c7d0725 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/system_bl702.c
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/startup/system_bl702.c
@@ -41,6 +41,9 @@ void USB_DoNothing_IRQHandler(void) {
 /*----------------------------------------------------------------------------
   Vector Table
  *----------------------------------------------------------------------------*/
+#define VECT_TAB_OFFSET                                                                                                                                                                                \
+  0x00 /*!< Vector Table base offset field.                                                                                                                                                            \
+             This value must be a multiple of 0x200. */
 
 /*----------------------------------------------------------------------------
   System initialization function
@@ -124,7 +127,7 @@ void SystemInit(void) {
 #ifdef BFLB_EFLASH_LOADER
   Interrupt_Handler_Register(USB_IRQn, USB_DoNothing_IRQHandler);
 #endif
-  /* init for for all platform */
+  /* init bor for all platform */
   system_bor_init();
   /* global IRQ enable */
   __enable_irq();
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_adc.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_adc.h
index 8619541f4..b14eb472a 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_adc.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_adc.h
@@ -40,7 +40,6 @@
 #include "bl702_common.h"
 #include "gpip_reg.h"
 
-
 /** @addtogroup  BL702_Peripheral_Driver
  *  @{
  */
@@ -272,8 +271,8 @@ typedef struct {
 typedef struct {
   int8_t   posChan; /*!< Positive channel */
   int8_t   negChan; /*!< Negative channel */
-  uint16_t value;   /*!< ADC value */
-  float    volt;    /*!< ADC voltage result */
+  uint32_t value;   /*!< ADC value */
+  // float    volt;    /*!< ADC voltage result */
 } ADC_Result_Type;
 
 /**
@@ -325,11 +324,11 @@ typedef struct {
 /** @defgroup  ADC_CHAN_TYPE
  *  @{
  */
-#define IS_ADC_CHAN_TYPE(type)                                                                                                                                                                      \
-  (((type) == ADC_CHAN0) || ((type) == ADC_CHAN1) || ((type) == ADC_CHAN2) || ((type) == ADC_CHAN3) || ((type) == ADC_CHAN4) || ((type) == ADC_CHAN5) || ((type) == ADC_CHAN6)                      \
-   || ((type) == ADC_CHAN7) || ((type) == ADC_CHAN8) || ((type) == ADC_CHAN9) || ((type) == ADC_CHAN10) || ((type) == ADC_CHAN11) || ((type) == ADC_CHAN_DAC_OUTA) || ((type) == ADC_CHAN_DAC_OUTB) \
-   || ((type) == ADC_CHAN_TSEN_P) || ((type) == ADC_CHAN_TSEN_N) || ((type) == ADC_CHAN_VREF) || ((type) == ADC_CHAN_DCTEST) || ((type) == ADC_CHAN_VABT_HALF) || ((type) == ADC_CHAN_SENP3)        \
-   || ((type) == ADC_CHAN_SENP2) || ((type) == ADC_CHAN_SENP1) || ((type) == ADC_CHAN_SENP0) || ((type) == ADC_CHAN_GND))
+#define IS_ADC_CHAN_TYPE(type)                                                                                                                                                                         \
+  (((type) == ADC_CHAN0) || ((type) == ADC_CHAN1) || ((type) == ADC_CHAN2) || ((type) == ADC_CHAN3) || ((type) == ADC_CHAN4) || ((type) == ADC_CHAN5) || ((type) == ADC_CHAN6) ||                      \
+   ((type) == ADC_CHAN7) || ((type) == ADC_CHAN8) || ((type) == ADC_CHAN9) || ((type) == ADC_CHAN10) || ((type) == ADC_CHAN11) || ((type) == ADC_CHAN_DAC_OUTA) || ((type) == ADC_CHAN_DAC_OUTB) ||    \
+   ((type) == ADC_CHAN_TSEN_P) || ((type) == ADC_CHAN_TSEN_N) || ((type) == ADC_CHAN_VREF) || ((type) == ADC_CHAN_DCTEST) || ((type) == ADC_CHAN_VABT_HALF) || ((type) == ADC_CHAN_SENP3) ||           \
+   ((type) == ADC_CHAN_SENP2) || ((type) == ADC_CHAN_SENP1) || ((type) == ADC_CHAN_SENP0) || ((type) == ADC_CHAN_GND))
 
 /** @defgroup  ADC_V18_SEL_TYPE
  *  @{
@@ -344,23 +343,23 @@ typedef struct {
 /** @defgroup  ADC_CLK_TYPE
  *  @{
  */
-#define IS_ADC_CLK_TYPE(type)                                                                                                                                                    \
-  (((type) == ADC_CLK_DIV_1) || ((type) == ADC_CLK_DIV_4) || ((type) == ADC_CLK_DIV_8) || ((type) == ADC_CLK_DIV_12) || ((type) == ADC_CLK_DIV_16) || ((type) == ADC_CLK_DIV_20) \
-   || ((type) == ADC_CLK_DIV_24) || ((type) == ADC_CLK_DIV_32))
+#define IS_ADC_CLK_TYPE(type)                                                                                                                                                                          \
+  (((type) == ADC_CLK_DIV_1) || ((type) == ADC_CLK_DIV_4) || ((type) == ADC_CLK_DIV_8) || ((type) == ADC_CLK_DIV_12) || ((type) == ADC_CLK_DIV_16) || ((type) == ADC_CLK_DIV_20) ||                    \
+   ((type) == ADC_CLK_DIV_24) || ((type) == ADC_CLK_DIV_32))
 
 /** @defgroup  ADC_DELAY_SEL_TYPE
  *  @{
  */
-#define IS_ADC_DELAY_SEL_TYPE(type)                                                                                                                                                       \
-  (((type) == ADC_DELAY_SEL_0) || ((type) == ADC_DELAY_SEL_1) || ((type) == ADC_DELAY_SEL_2) || ((type) == ADC_DELAY_SEL_3) || ((type) == ADC_DELAY_SEL_4) || ((type) == ADC_DELAY_SEL_5) \
-   || ((type) == ADC_DELAY_SEL_6) || ((type) == ADC_DELAY_SEL_7))
+#define IS_ADC_DELAY_SEL_TYPE(type)                                                                                                                                                                    \
+  (((type) == ADC_DELAY_SEL_0) || ((type) == ADC_DELAY_SEL_1) || ((type) == ADC_DELAY_SEL_2) || ((type) == ADC_DELAY_SEL_3) || ((type) == ADC_DELAY_SEL_4) || ((type) == ADC_DELAY_SEL_5) ||           \
+   ((type) == ADC_DELAY_SEL_6) || ((type) == ADC_DELAY_SEL_7))
 
 /** @defgroup  ADC_PGA_GAIN_TYPE
  *  @{
  */
-#define IS_ADC_PGA_GAIN_TYPE(type)                                                                                                                                                      \
-  (((type) == ADC_PGA_GAIN_NONE) || ((type) == ADC_PGA_GAIN_1) || ((type) == ADC_PGA_GAIN_2) || ((type) == ADC_PGA_GAIN_4) || ((type) == ADC_PGA_GAIN_8) || ((type) == ADC_PGA_GAIN_16) \
-   || ((type) == ADC_PGA_GAIN_32))
+#define IS_ADC_PGA_GAIN_TYPE(type)                                                                                                                                                                     \
+  (((type) == ADC_PGA_GAIN_NONE) || ((type) == ADC_PGA_GAIN_1) || ((type) == ADC_PGA_GAIN_2) || ((type) == ADC_PGA_GAIN_4) || ((type) == ADC_PGA_GAIN_8) || ((type) == ADC_PGA_GAIN_16) ||             \
+   ((type) == ADC_PGA_GAIN_32))
 
 /** @defgroup  ADC_BIAS_SEL_TYPE
  *  @{
@@ -395,9 +394,9 @@ typedef struct {
 /** @defgroup  ADC_DATA_WIDTH_TYPE
  *  @{
  */
-#define IS_ADC_DATA_WIDTH_TYPE(type)                                                                                                                                                 \
-  (((type) == ADC_DATA_WIDTH_12) || ((type) == ADC_DATA_WIDTH_14_WITH_16_AVERAGE) || ((type) == ADC_DATA_WIDTH_14_WITH_64_AVERAGE) || ((type) == ADC_DATA_WIDTH_16_WITH_128_AVERAGE) \
-   || ((type) == ADC_DATA_WIDTH_16_WITH_256_AVERAGE))
+#define IS_ADC_DATA_WIDTH_TYPE(type)                                                                                                                                                                   \
+  (((type) == ADC_DATA_WIDTH_12) || ((type) == ADC_DATA_WIDTH_14_WITH_16_AVERAGE) || ((type) == ADC_DATA_WIDTH_14_WITH_64_AVERAGE) || ((type) == ADC_DATA_WIDTH_16_WITH_128_AVERAGE) ||                \
+   ((type) == ADC_DATA_WIDTH_16_WITH_256_AVERAGE))
 
 /** @defgroup  ADC_MICBOOST_DB_TYPE
  *  @{
@@ -422,9 +421,9 @@ typedef struct {
 /** @defgroup  ADC_INT_TYPE
  *  @{
  */
-#define IS_ADC_INT_TYPE(type)                                                                                                                                                         \
-  (((type) == ADC_INT_POS_SATURATION) || ((type) == ADC_INT_NEG_SATURATION) || ((type) == ADC_INT_FIFO_UNDERRUN) || ((type) == ADC_INT_FIFO_OVERRUN) || ((type) == ADC_INT_ADC_READY) \
-   || ((type) == ADC_INT_FIFO_READY) || ((type) == ADC_INT_ALL))
+#define IS_ADC_INT_TYPE(type)                                                                                                                                                                          \
+  (((type) == ADC_INT_POS_SATURATION) || ((type) == ADC_INT_NEG_SATURATION) || ((type) == ADC_INT_FIFO_UNDERRUN) || ((type) == ADC_INT_FIFO_OVERRUN) || ((type) == ADC_INT_ADC_READY) ||               \
+   ((type) == ADC_INT_FIFO_READY) || ((type) == ADC_INT_ALL))
 
 /*@} end of group ADC_Public_Constants */
 
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_dma.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_dma.h
index e94927bbc..c558dd3f1 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_dma.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_dma.h
@@ -39,6 +39,10 @@
 #include "dma_reg.h"
 #include "bl702_common.h"
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /** @addtogroup  BL702_Peripheral_Driver
  *  @{
  */
@@ -168,9 +172,9 @@ typedef struct
     DMA_Chan_Type ch;                    /*!< Channel select 0-7 */
     DMA_Trans_Width_Type srcTransfWidth; /*!< Transfer width. 0: 8  bits, 1: 16  bits, 2: 32  bits */
     DMA_Trans_Width_Type dstTransfWidth; /*!< Transfer width. 0: 8  bits, 1: 16  bits, 2: 32  bits */
-    DMA_Burst_Size_Type srcBurstSzie;    /*!< Number of data items for burst transaction length. Each item width is as same as tansfer width.
+    DMA_Burst_Size_Type srcBurstSize;    /*!< Number of data items for burst transaction length. Each item width is as same as tansfer width.
                                                  0: 1 item, 1: 4 items, 2: 8 items, 3: 16 items */
-    DMA_Burst_Size_Type dstBurstSzie;    /*!< Number of data items for burst transaction length. Each item width is as same as tansfer width.
+    DMA_Burst_Size_Type dstBurstSize;    /*!< Number of data items for burst transaction length. Each item width is as same as tansfer width.
                                                  0: 1 item, 1: 4 items, 2: 8 items, 3: 16 items */
     BL_Fun_Type dstAddMode;              /*!<  */
     BL_Fun_Type dstMinMode;              /*!<  */
@@ -181,16 +185,6 @@ typedef struct
     DMA_Periph_Req_Type dstPeriph;       /*!< Destination peripheral select */
 } DMA_Channel_Cfg_Type;
 
-/**
- *  @brief DMA LLI control structure type definition
- */
-typedef struct
-{
-    uint32_t srcDmaAddr;            /*!< Source address of DMA transfer */
-    uint32_t destDmaAddr;           /*!< Destination address of DMA transfer */
-    uint32_t nextLLI;               /*!< Next LLI address */
-    struct DMA_Control_Reg dmaCtrl; /*!< DMA transaction control */
-} DMA_LLI_Ctrl_Type;
 
 /**
  *  @brief DMA LLI configuration structure type definition
@@ -202,31 +196,6 @@ typedef struct
     DMA_Periph_Req_Type dstPeriph; /*!< Destination peripheral select */
 } DMA_LLI_Cfg_Type;
 
-/**
- *  @brief DMA LLI Ping-Pong Buf definition
- */
-typedef struct
-{
-    uint8_t idleIndex;                             /*!< Index Idle lliListHeader */
-    uint8_t dmaChan;                               /*!< DMA LLI Channel used */
-    DMA_LLI_Ctrl_Type *lliListHeader[2];           /*!< Ping-Pong BUf List Header */
-    void (*onTransCompleted)(DMA_LLI_Ctrl_Type *); /*!< Completed Transmit One List Callback Function */
-} DMA_LLI_PP_Buf;
-
-/**
- *  @brief DMA LLI Ping-Pong Structure definition
- */
-typedef struct
-{
-    uint8_t trans_index;                  /*!< Ping or Pong Trigger TC */
-    uint8_t dmaChan;                      /*!< DMA LLI Channel used */
-    struct DMA_Control_Reg dmaCtrlRegVal; /*!< DMA Basic Pararmeter */
-    DMA_LLI_Cfg_Type *DMA_LLI_Cfg;        /*!< LLI Config parameter */
-    uint32_t operatePeriphAddr;           /*!< Operate Peripheral register address */
-    uint32_t chache_buf_addr[2];          /*!< Ping-Pong structure chache */
-    BL_Fun_Type is_single_mode;           /*!< is Ping-pong running forever or single mode ,if is single mode ping-pong will run only once
-                                                 after one start */
-} DMA_LLI_PP_Struct;
 
 /*@} end of group DMA_Public_Types */
 
@@ -346,16 +315,7 @@ void DMA_Channel_Disable(uint8_t ch);
 void DMA_LLI_Init(uint8_t ch, DMA_LLI_Cfg_Type *lliCfg);
 void DMA_LLI_Update(uint8_t ch, uint32_t LLI);
 void DMA_IntMask(uint8_t ch, DMA_INT_Type intType, BL_Mask_Type intMask);
-void DMA_LLI_PpBuf_Start_New_Transmit(DMA_LLI_PP_Buf *dmaPpBuf);
-DMA_LLI_Ctrl_Type *DMA_LLI_PpBuf_Remove_Completed_List(DMA_LLI_PP_Buf *dmaPpBuf);
-void DMA_LLI_PpBuf_Append(DMA_LLI_PP_Buf *dmaPpBuf, DMA_LLI_Ctrl_Type *dmaLliList);
-void DMA_LLI_PpBuf_Destroy(DMA_LLI_PP_Buf *dmaPpBuf);
 void DMA_Int_Callback_Install(DMA_Chan_Type dmaChan, DMA_INT_Type intType, intCallback_Type *cbFun);
-void DMA_LLI_PpStruct_Start(DMA_LLI_PP_Struct *dmaPpStruct);
-void DMA_LLI_PpStruct_Stop(DMA_LLI_PP_Struct *dmaPpStruct);
-BL_Err_Type DMA_LLI_PpStruct_Init(DMA_LLI_PP_Struct *dmaPpStruct);
-BL_Err_Type DMA_LLI_PpStruct_Set_Transfer_Len(DMA_LLI_PP_Struct *dmaPpStruct,
-                                              uint16_t Ping_Transfer_len, uint16_t Pong_Transfer_len);
 
 /*@} end of group DMA_Public_Functions */
 
@@ -363,4 +323,8 @@ BL_Err_Type DMA_LLI_PpStruct_Set_Transfer_Len(DMA_LLI_PP_Struct *dmaPpStruct,
 
 /*@} end of group BL702_Peripheral_Driver */
 
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
 #endif /* __BL702_DMA_H__ */
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_i2c.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_i2c.h
index 4fbbc179b..ea530a6ea 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_i2c.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/inc/bl702_i2c.h
@@ -1,43 +1,43 @@
 /**
-  ******************************************************************************
-  * @file    bl702_i2c.h
-  * @version V1.0
-  * @date
-  * @brief   This file is the standard driver header file
-  ******************************************************************************
-  * @attention
-  *
-  * 

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_i2c.h + * @version V1.0 + * @date + * @brief This file is the standard driver header file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #ifndef __BL702_I2C_H__ #define __BL702_I2C_H__ -#include "i2c_reg.h" #include "bl702_common.h" +#include "i2c_reg.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -55,75 +55,71 @@ * @brief I2C No. type definition */ typedef enum { - I2C0_ID = 0, /*!< I2C0 define */ - I2C_ID_MAX, /*!< I2C max define */ + I2C0_ID = 0, /*!< I2C0 define */ + I2C_ID_MAX, /*!< I2C max define */ } I2C_ID_Type; /** * @brief I2C read/write type definition */ typedef enum { - I2C_WRITE = 0, /*!< I2C write direction */ - I2C_READ, /*!< I2C read direction */ + I2C_WRITE = 0, /*!< I2C write direction */ + I2C_READ, /*!< I2C read direction */ } I2C_Direction_Type; /** * @brief I2C interrupt type definition */ typedef enum { - I2C_TRANS_END_INT, /*!< I2C transfer end interrupt */ - I2C_TX_FIFO_READY_INT, /*!< I2C TX fifo ready interrupt */ - I2C_RX_FIFO_READY_INT, /*!< I2C RX fifo ready interrupt */ - I2C_NACK_RECV_INT, /*!< I2C nack received interrupt */ - I2C_ARB_LOST_INT, /*!< I2C arbitration lost interrupt */ - I2C_FIFO_ERR_INT, /*!< I2C TX/RX FIFO error interrupt */ - I2C_INT_ALL, /*!< I2C interrupt all type */ + I2C_TRANS_END_INT, /*!< I2C transfer end interrupt */ + I2C_TX_FIFO_READY_INT, /*!< I2C TX fifo ready interrupt */ + I2C_RX_FIFO_READY_INT, /*!< I2C RX fifo ready interrupt */ + I2C_NACK_RECV_INT, /*!< I2C nack received interrupt */ + I2C_ARB_LOST_INT, /*!< I2C arbitration lost interrupt */ + I2C_FIFO_ERR_INT, /*!< I2C TX/RX FIFO error interrupt */ + I2C_INT_ALL, /*!< I2C interrupt all type */ } I2C_INT_Type; /** * @brief I2S start condition phase structure type definition */ -typedef struct -{ - uint8_t len0; /*!< Length of START condition phase 0 */ - uint8_t len1; /*!< Length of START condition phase 1 */ - uint8_t len2; /*!< Length of START condition phase 2 */ - uint8_t len3; /*!< Length of START condition phase 3 */ +typedef struct { + uint8_t len0; /*!< Length of START condition phase 0 */ + uint8_t len1; /*!< Length of START condition phase 1 */ + uint8_t len2; /*!< Length of START condition phase 2 */ + uint8_t len3; /*!< Length of START condition phase 3 */ } I2C_Start_Condition_Phase_Type; /** * @brief I2S stop condition phase structure type definition */ -typedef struct -{ - uint8_t len0; /*!< Length of STOP condition phase 0 */ - uint8_t len1; /*!< Length of STOP condition phase 1 */ - uint8_t len2; /*!< Length of STOP condition phase 2 */ - uint8_t len3; /*!< Length of STOP condition phase 3 */ +typedef struct { + uint8_t len0; /*!< Length of STOP condition phase 0 */ + uint8_t len1; /*!< Length of STOP condition phase 1 */ + uint8_t len2; /*!< Length of STOP condition phase 2 */ + uint8_t len3; /*!< Length of STOP condition phase 3 */ } I2C_Stop_Condition_Phase_Type; /** * @brief I2S data phase structure type definition */ -typedef struct -{ - uint8_t len0; /*!< Length of DATA phase 0 */ - uint8_t len1; /*!< Length of DATA phase 1 */ - uint8_t len2; /*!< Length of DATA phase 2 */ - uint8_t len3; /*!< Length of DATA phase 3 */ +typedef struct { + uint8_t len0; /*!< Length of DATA phase 0 */ + uint8_t len1; /*!< Length of DATA phase 1 */ + uint8_t len2; /*!< Length of DATA phase 2 */ + uint8_t len3; /*!< Length of DATA phase 3 */ } I2C_Data_Phase_Type; /** * @brief I2S transfer structure type definition */ -typedef struct -{ - uint8_t slaveAddr; /*!< I2C slave address */ - BL_Fun_Type stopEveryByte; /*!< I2C all data byte with stop bit */ - uint8_t subAddrSize; /*!< Specifies the size of I2C sub address section */ - uint32_t subAddr; /*!< I2C sub address */ - uint16_t dataSize; /*!< Specifies the size of I2C data section */ - uint8_t *data; /*!< Specifies the pointer of I2C R/W data */ +typedef struct { + uint8_t slaveAddr; /*!< I2C slave address */ + BL_Fun_Type stopEveryByte; /*!< I2C all data byte with stop bit */ + uint8_t subAddrSize; /*!< Specifies the size of I2C sub address section */ + uint32_t subAddr; /*!< I2C sub address */ + uint16_t dataSize; /*!< Specifies the size of I2C data section */ + uint8_t *data; /*!< Specifies the pointer of I2C R/W data */ } I2C_Transfer_Cfg; /*@} end of group I2C_Public_Types */ @@ -135,25 +131,19 @@ typedef struct /** @defgroup I2C_ID_TYPE * @{ */ -#define IS_I2C_ID_TYPE(type) (((type) == I2C0_ID) || \ - ((type) == I2C_ID_MAX)) +#define IS_I2C_ID_TYPE(type) (((type) == I2C0_ID) || ((type) == I2C_ID_MAX)) /** @defgroup I2C_DIRECTION_TYPE * @{ */ -#define IS_I2C_DIRECTION_TYPE(type) (((type) == I2C_WRITE) || \ - ((type) == I2C_READ)) +#define IS_I2C_DIRECTION_TYPE(type) (((type) == I2C_WRITE) || ((type) == I2C_READ)) /** @defgroup I2C_INT_TYPE * @{ */ -#define IS_I2C_INT_TYPE(type) (((type) == I2C_TRANS_END_INT) || \ - ((type) == I2C_TX_FIFO_READY_INT) || \ - ((type) == I2C_RX_FIFO_READY_INT) || \ - ((type) == I2C_NACK_RECV_INT) || \ - ((type) == I2C_ARB_LOST_INT) || \ - ((type) == I2C_FIFO_ERR_INT) || \ - ((type) == I2C_INT_ALL)) +#define IS_I2C_INT_TYPE(type) \ + (((type) == I2C_TRANS_END_INT) || ((type) == I2C_TX_FIFO_READY_INT) || ((type) == I2C_RX_FIFO_READY_INT) || ((type) == I2C_NACK_RECV_INT) || ((type) == I2C_ARB_LOST_INT) || \ + ((type) == I2C_FIFO_ERR_INT) || ((type) == I2C_INT_ALL)) /*@} end of group I2C_Public_Constants */ @@ -173,22 +163,26 @@ typedef struct #ifndef BFLB_USE_HAL_DRIVER void I2C_IRQHandler(void); #endif -void I2C_SendWord(I2C_ID_Type i2cNo, uint32_t data); -uint32_t I2C_RecieveWord(I2C_ID_Type i2cNo); -void I2C_Enable(I2C_ID_Type i2cNo); -void I2C_Disable(I2C_ID_Type i2cNo); +void I2C_SendWord(I2C_ID_Type i2cNo, uint32_t data); +uint32_t I2C_RecieveWord(I2C_ID_Type i2cNo); +void I2C_Enable(I2C_ID_Type i2cNo); +void I2C_Disable(I2C_ID_Type i2cNo); BL_Err_Type I2C_SetDeglitchCount(I2C_ID_Type i2cNo, uint8_t cnt); BL_Err_Type I2C_Reset(I2C_ID_Type i2cNo); -void I2C_SetPrd(I2C_ID_Type i2cNo, uint8_t phase); -void I2C_ClockSet(I2C_ID_Type i2cNo, uint32_t clk); -void I2C_SetSclSync(I2C_ID_Type i2cNo, uint8_t enable); -void I2C_Init(I2C_ID_Type i2cNo, I2C_Direction_Type direct, I2C_Transfer_Cfg *cfg); +uint8_t I2C_GetTXFIFOAvailable(); +uint8_t I2C_GetRXFIFOAvailable(); +void I2C_DMATxEnable(); +void I2C_DMATxDisable(); +void I2C_SetPrd(I2C_ID_Type i2cNo, uint8_t phase); +void I2C_ClockSet(I2C_ID_Type i2cNo, uint32_t clk); +void I2C_SetSclSync(I2C_ID_Type i2cNo, uint8_t enable); +void I2C_Init(I2C_ID_Type i2cNo, I2C_Direction_Type direct, I2C_Transfer_Cfg *cfg); BL_Sts_Type I2C_IsBusy(I2C_ID_Type i2cNo); BL_Sts_Type I2C_TransferEndStatus(I2C_ID_Type i2cNo); BL_Err_Type I2C_MasterSendBlocking(I2C_ID_Type i2cNo, I2C_Transfer_Cfg *cfg); BL_Err_Type I2C_MasterReceiveBlocking(I2C_ID_Type i2cNo, I2C_Transfer_Cfg *cfg); -void I2C_IntMask(I2C_ID_Type i2cNo, I2C_INT_Type intType, BL_Mask_Type intMask); -void I2C_Int_Callback_Install(I2C_ID_Type i2cNo, I2C_INT_Type intType, intCallback_Type *cbFun); +void I2C_IntMask(I2C_ID_Type i2cNo, I2C_INT_Type intType, BL_Mask_Type intMask); +void I2C_Int_Callback_Install(I2C_ID_Type i2cNo, I2C_INT_Type intType, intCallback_Type *cbFun); /*@} end of group I2C_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_acomp.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_acomp.c index 666aa1896..190ccbaa9 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_acomp.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_acomp.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_acomp.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_acomp.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_acomp.h" @@ -85,114 +85,111 @@ */ /****************************************************************************/ /** - * @brief Analog compare init - * - * @param acompNo: Compare ID - * @param cfg: Compare consideration pointer - * - * @return None - * -*******************************************************************************/ -void AON_ACOMP_Init(AON_ACOMP_ID_Type acompNo, AON_ACOMP_CFG_Type *cfg) -{ - uint32_t tmpVal = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); - - if (acompNo == AON_ACOMP0_ID) { - /* Disable ACOMP first */ - tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP0_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_ACOMP0_EN); - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); - - /* Set ACOMP config */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_MUXEN, cfg->muxEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_POS_SEL, cfg->posChanSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_NEG_SEL, cfg->negChanSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_LEVEL_SEL, cfg->levelFactor); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_BIAS_PROG, cfg->biasProg); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_HYST_SELP, cfg->hysteresisPosVolt); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_HYST_SELN, cfg->hysteresisNegVolt); - - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); - - } else { - /* Disable ACOMP first */ - tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP1_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_ACOMP1_EN); - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); - - /* Set ACOMP config */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_MUXEN, cfg->muxEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_POS_SEL, cfg->posChanSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_NEG_SEL, cfg->negChanSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_LEVEL_SEL, cfg->levelFactor); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_BIAS_PROG, cfg->biasProg); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_HYST_SELP, cfg->hysteresisPosVolt); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_HYST_SELN, cfg->hysteresisNegVolt); - - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); - } + * @brief Analog compare init + * + * @param acompNo: Compare ID + * @param cfg: Compare consideration pointer + * + * @return None + * + *******************************************************************************/ +void AON_ACOMP_Init(AON_ACOMP_ID_Type acompNo, AON_ACOMP_CFG_Type *cfg) { + uint32_t tmpVal = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); + + if (acompNo == AON_ACOMP0_ID) { + /* Disable ACOMP first */ + tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP0_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_ACOMP0_EN); + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); + + /* Set ACOMP config */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_MUXEN, cfg->muxEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_POS_SEL, cfg->posChanSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_NEG_SEL, cfg->negChanSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_LEVEL_SEL, cfg->levelFactor); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_BIAS_PROG, cfg->biasProg); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_HYST_SELP, cfg->hysteresisPosVolt); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP0_HYST_SELN, cfg->hysteresisNegVolt); + + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); + + } else { + /* Disable ACOMP first */ + tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP1_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_ACOMP1_EN); + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); + + /* Set ACOMP config */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_MUXEN, cfg->muxEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_POS_SEL, cfg->posChanSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_NEG_SEL, cfg->negChanSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_LEVEL_SEL, cfg->levelFactor); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_BIAS_PROG, cfg->biasProg); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_HYST_SELP, cfg->hysteresisPosVolt); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_ACOMP1_HYST_SELN, cfg->hysteresisNegVolt); + + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); + } } /****************************************************************************/ /** - * @brief Analog compare enable - * - * @param acompNo: Compare ID - * - * @return None - * -*******************************************************************************/ -void AON_ACOMP_Enable(AON_ACOMP_ID_Type acompNo) -{ - uint32_t tmpVal = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); - - if (acompNo == AON_ACOMP0_ID) { - tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP0_CTRL); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_ACOMP0_EN); - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); - } else { - tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP1_CTRL); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_ACOMP1_EN); - tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); - } + * @brief Analog compare enable + * + * @param acompNo: Compare ID + * + * @return None + * + *******************************************************************************/ +void AON_ACOMP_Enable(AON_ACOMP_ID_Type acompNo) { + uint32_t tmpVal = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); + + if (acompNo == AON_ACOMP0_ID) { + tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP0_CTRL); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_ACOMP0_EN); + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP0_CTRL, tmpVal); + } else { + tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP1_CTRL); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_ACOMP1_EN); + tmpVal = BL_WR_REG(AON_BASE, AON_ACOMP1_CTRL, tmpVal); + } } /****************************************************************************/ /** - * @brief Analog compare enable - * - * @param acompNo: Compare ID - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type AON_ACOMP_Get_Result(AON_ACOMP_ID_Type acompNo) -{ - uint32_t tmpVal = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); - - tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP_CTRL); - - /* Disable ACOMP first */ - if (acompNo == AON_ACOMP0_ID) { - if (BL_IS_REG_BIT_SET(tmpVal, AON_ACOMP0_OUT_RAW)) { - return SET; - } else { - return RESET; - } + * @brief Analog compare enable + * + * @param acompNo: Compare ID + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type AON_ACOMP_Get_Result(AON_ACOMP_ID_Type acompNo) { + uint32_t tmpVal = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_AON_ACOMP_ID_TYPE(acompNo)); + + tmpVal = BL_RD_REG(AON_BASE, AON_ACOMP_CTRL); + + /* Disable ACOMP first */ + if (acompNo == AON_ACOMP0_ID) { + if (BL_IS_REG_BIT_SET(tmpVal, AON_ACOMP0_OUT_RAW)) { + return SET; + } else { + return RESET; + } + } else { + if (BL_IS_REG_BIT_SET(tmpVal, AON_ACOMP1_OUT_RAW)) { + return SET; } else { - if (BL_IS_REG_BIT_SET(tmpVal, AON_ACOMP1_OUT_RAW)) { - return SET; - } else { - return RESET; - } + return RESET; } + } } /*@} end of group ACOMP_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_adc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_adc.c index e4bd82137..590283212 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_adc.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_adc.c @@ -50,16 +50,16 @@ */ #undef MSG #define MSG(...) -#define AON_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ +#define AON_CLK_SET_DUMMY_WAIT \ + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ } #define ADC_RESTART_DUMMY_WAIT BL702_Delay_US(100) @@ -74,11 +74,11 @@ /** @defgroup ADC_Private_Variables * @{ */ -static intCallback_Type *adcIntCbfArra[ADC_INT_ALL] = {NULL}; -static ADC_Gain_Coeff_Type adcGainCoeffCal = { - .adcGainCoeffEnable = DISABLE, - .adcgainCoeffVal = 0, - .coe = 1, +static intCallback_Type *adcIntCbfArra[ADC_INT_ALL] = {NULL}; +ADC_Gain_Coeff_Type adcGainCoeffCal = { + .adcGainCoeffEnable = DISABLE, + .adcgainCoeffVal = 0, + .coe = 1, }; /*@} end of group ADC_Private_Variables */ @@ -185,7 +185,7 @@ void ADC_Init(ADC_CFG_Type *cfg) { CHECK_PARAM(IS_ADC_DATA_WIDTH_TYPE(cfg->resWidth)); /* config 1 */ - regCfg1 = 0; // BL_RD_REG(AON_BASE, AON_GPADC_REG_CONFIG1); + regCfg1 = BL_RD_REG(AON_BASE, AON_GPADC_REG_CONFIG1); regCfg1 = BL_SET_REG_BITS_VAL(regCfg1, AON_GPADC_V18_SEL, cfg->v18Sel); regCfg1 = BL_SET_REG_BITS_VAL(regCfg1, AON_GPADC_V11_SEL, cfg->v11Sel); regCfg1 = BL_CLR_REG_BIT(regCfg1, AON_GPADC_DITHER_EN); @@ -200,13 +200,11 @@ void ADC_Init(ADC_CFG_Type *cfg) { /* config 2 */ regCfg2 = BL_RD_REG(AON_BASE, AON_GPADC_REG_CONFIG2); - regCfg2 = BL_SET_REG_BITS_VAL(regCfg2, AON_GPADC_DLY_SEL, 0x00); + regCfg2 = BL_SET_REG_BITS_VAL(regCfg2, AON_GPADC_DLY_SEL, 0x02); regCfg2 = BL_SET_REG_BITS_VAL(regCfg2, AON_GPADC_PGA1_GAIN, cfg->gain1); regCfg2 = BL_SET_REG_BITS_VAL(regCfg2, AON_GPADC_PGA2_GAIN, cfg->gain2); regCfg2 = BL_SET_REG_BITS_VAL(regCfg2, AON_GPADC_BIAS_SEL, cfg->biasSel); regCfg2 = BL_SET_REG_BITS_VAL(regCfg2, AON_GPADC_CHOP_MODE, cfg->chopMode); - regCfg2 = BL_CLR_REG_BIT(regCfg2, AON_GPADC_VBAT_EN); // vbat enabled (off) - regCfg2 = BL_CLR_REG_BIT(regCfg2, AON_GPADC_TSVBE_LOW); // tsen didoe current /* pga_vcmi_en is for mic */ regCfg2 = BL_CLR_REG_BIT(regCfg2, AON_GPADC_PGA_VCMI_EN); @@ -233,7 +231,7 @@ void ADC_Init(ADC_CFG_Type *cfg) { Interrupt_Handler_Register(GPADC_DMA_IRQn, GPADC_DMA_IRQHandler); #endif - // ADC_Gain_Trim(); + ADC_Gain_Trim(); } /****************************************************************************/ @@ -510,8 +508,7 @@ void ADC_Parse_Result(uint32_t *orgVal, uint32_t len, ADC_Result_Type *result) { uint32_t tmpVal1 = 0, tmpVal2 = 0; ADC_Data_Width_Type dataType; ADC_SIG_INPUT_Type sigType; - float ref = 2.0; - uint32_t i = 0; + uint32_t i = 0; float coe = 1.0; @@ -524,54 +521,52 @@ void ADC_Parse_Result(uint32_t *orgVal, uint32_t len, ADC_Result_Type *result) { dataType = BL_GET_REG_BITS_VAL(tmpVal1, AON_GPADC_RES_SEL); sigType = BL_GET_REG_BITS_VAL(tmpVal2, AON_GPADC_DIFF_MODE); - if (BL_GET_REG_BITS_VAL(tmpVal2, AON_GPADC_VREF_SEL) == ADC_VREF_3P2V) { - ref = 3.2; - } - if (sigType == ADC_INPUT_SINGLE_END) { for (i = 0; i < len; i++) { result[i].posChan = orgVal[i] >> 21; result[i].negChan = -1; - + uint32_t sample = 0; if (dataType == ADC_DATA_WIDTH_12) { - result[i].value = (unsigned int)(((orgVal[i] & 0xffff) >> 4) / coe); - result[i].volt = result[i].value / 4096.0 * ref; + sample = ((orgVal[i] & 0xffff) >> 4); } else if ((dataType == ADC_DATA_WIDTH_14_WITH_16_AVERAGE) || (dataType == ADC_DATA_WIDTH_14_WITH_64_AVERAGE)) { - result[i].value = (unsigned int)(((orgVal[i] & 0xffff) >> 2) / coe); - result[i].volt = result[i].value / 16384.0 * ref; + sample = ((orgVal[i] & 0xffff) >> 2); } else if ((dataType == ADC_DATA_WIDTH_16_WITH_128_AVERAGE) || (dataType == ADC_DATA_WIDTH_16_WITH_256_AVERAGE)) { - result[i].value = (unsigned int)((orgVal[i] & 0xffff) / coe); - result[i].volt = result[i].value / 65536.0 * ref; - } - } - } else { - for (i = 0; i < len; i++) { - neg = 0; - result[i].posChan = orgVal[i] >> 21; - result[i].negChan = (orgVal[i] >> 16) & 0x1F; - - if (orgVal[i] & 0x8000) { - orgVal[i] = ~orgVal[i]; - orgVal[i] += 1; - neg = 1; + sample = (orgVal[i] & 0xffff); } - if (dataType == ADC_DATA_WIDTH_12) { - result[i].value = (unsigned int)(((orgVal[i] & 0xffff) >> 4) / coe); - result[i].volt = result[i].value / 2048.0 * ref; - } else if ((dataType == ADC_DATA_WIDTH_14_WITH_16_AVERAGE) || (dataType == ADC_DATA_WIDTH_14_WITH_64_AVERAGE)) { - result[i].value = (unsigned int)(((orgVal[i] & 0xffff) >> 2) / coe); - result[i].volt = result[i].value / 8192.0 * ref; - } else if ((dataType == ADC_DATA_WIDTH_16_WITH_128_AVERAGE) || (dataType == ADC_DATA_WIDTH_16_WITH_256_AVERAGE)) { - result[i].value = (unsigned int)((orgVal[i] & 0xffff) / coe); - result[i].volt = result[i].value / 32768.0 * ref; - } + result[i].value = (unsigned int)(sample / coe); - if (neg) { - result[i].volt = -result[i].volt; + // Saturate at 16 bits + if (result[i].value > 0xFFFF) { + result[i].value = 0xFFFF; } } } + // else { + // for (i = 0; i < len; i++) { + // neg = 0; + // result[i].posChan = orgVal[i] >> 21; + // result[i].negChan = (orgVal[i] >> 16) & 0x1F; + + // if (orgVal[i] & 0x8000) { + // orgVal[i] = ~orgVal[i]; + // orgVal[i] += 1; + // neg = 1; + // } + + // if (dataType == ADC_DATA_WIDTH_12) { + // result[i].value = (unsigned int)(((orgVal[i] & 0xffff) >> 4) / coe); + // } else if ((dataType == ADC_DATA_WIDTH_14_WITH_16_AVERAGE) || (dataType == ADC_DATA_WIDTH_14_WITH_64_AVERAGE)) { + // result[i].value = (unsigned int)(((orgVal[i] & 0xffff) >> 2) / coe); + // } else if ((dataType == ADC_DATA_WIDTH_16_WITH_128_AVERAGE) || (dataType == ADC_DATA_WIDTH_16_WITH_256_AVERAGE)) { + // result[i].value = (unsigned int)((orgVal[i] & 0xffff) / coe); + // } + // // Saturate at 16 bits + // if (result[i].value > 0xFFFF) { + // result[i].value = 0xFFFF; + // } + // } + // } } /****************************************************************************/ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c index d16645586..4e3c276da 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_aon.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_aon.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_aon.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_aon.h" @@ -47,17 +47,17 @@ /** @defgroup AON_Private_Macros * @{ */ -#define AON_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - } +#define AON_CLK_SET_DUMMY_WAIT \ + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + } /*@} end of group AON_Private_Macros */ @@ -96,483 +96,463 @@ */ /****************************************************************************/ /** - * @brief Power on MXX band gap - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power on MXX band gap + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER -__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_MBG(void) -{ - uint32_t tmpVal = 0; +__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_MBG(void) { + uint32_t tmpVal = 0; - /* Power up RF for PLL to work */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_MBG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + /* Power up RF for PLL to work */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_MBG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - BL702_Delay_US(55); + BL702_Delay_US(55); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Power off MXX band gap - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power off MXX band gap + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER -__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_MBG(void) -{ - uint32_t tmpVal = 0; +__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_MBG(void) { + uint32_t tmpVal = 0; - /* Power OFF */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_MBG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + /* Power OFF */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_MBG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Power on XTAL - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power on XTAL + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER -__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_XTAL(void) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_XTAL_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_XTAL_BUF_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - /* Polling for ready */ - do { - BL702_Delay_US(10); - timeOut++; - tmpVal = BL_RD_REG(AON_BASE, AON_TSEN); - } while (!BL_IS_REG_BIT_SET(tmpVal, AON_XTAL_RDY) && timeOut < 120); - - if (timeOut >= 120) { - return TIMEOUT; - } - - return SUCCESS; +__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_XTAL(void) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_XTAL_AON); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_XTAL_BUF_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + /* Polling for ready */ + do { + BL702_Delay_US(10); + timeOut++; + tmpVal = BL_RD_REG(AON_BASE, AON_TSEN); + } while (!BL_IS_REG_BIT_SET(tmpVal, AON_XTAL_RDY) && timeOut < 120); + + if (timeOut >= 120) { + return TIMEOUT; + } + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set XTAL cap code - * - * @param capIn: Cap code in - * @param capOut: Cap code out - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set XTAL cap code + * + * @param capIn: Cap code in + * @param capOut: Cap code out + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER -__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Set_Xtal_CapCode(uint8_t capIn, uint8_t capOut) -{ - uint32_t tmpVal = 0; +__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Set_Xtal_CapCode(uint8_t capIn, uint8_t capOut) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_IN_AON, capIn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_OUT_AON, capOut); - BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); + tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_IN_AON, capIn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_OUT_AON, capOut); + BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); - BL702_Delay_US(100); + BL702_Delay_US(100); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Get XTAL cap code - * - * @param None - * - * @return Cap code - * -*******************************************************************************/ -uint8_t ATTR_CLOCK_SECTION AON_Get_Xtal_CapCode(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); - - return BL_GET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_IN_AON); + * @brief Get XTAL cap code + * + * @param None + * + * @return Cap code + * + *******************************************************************************/ +uint8_t ATTR_CLOCK_SECTION AON_Get_Xtal_CapCode(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); + + return BL_GET_REG_BITS_VAL(tmpVal, AON_XTAL_CAPCODE_IN_AON); } /****************************************************************************/ /** - * @brief Set XTAL cap code - * - * @param extra: cap cpde extra aon - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION AON_Set_Xtal_CapCode_Extra(uint8_t extra) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); - if (extra) { - tmpVal = BL_SET_REG_BIT(tmpVal, AON_XTAL_CAPCODE_EXTRA_AON); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_XTAL_CAPCODE_EXTRA_AON); - } - BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); - - return SUCCESS; + * @brief Set XTAL cap code + * + * @param extra: cap cpde extra aon + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION AON_Set_Xtal_CapCode_Extra(uint8_t extra) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); + if (extra) { + tmpVal = BL_SET_REG_BIT(tmpVal, AON_XTAL_CAPCODE_EXTRA_AON); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_XTAL_CAPCODE_EXTRA_AON); + } + BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off XTAL - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power off XTAL + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER -__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_XTAL(void) -{ - uint32_t tmpVal = 0; +__WEAK BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_XTAL(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_XTAL_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_XTAL_BUF_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_XTAL_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_XTAL_BUF_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Power on bandgap system - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_BG(void) -{ - uint32_t tmpVal = 0; - - /* power up RF for PLL to work */ - tmpVal = BL_RD_REG(AON_BASE, AON_BG_SYS_TOP); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_BG_SYS_AON); - BL_WR_REG(AON_BASE, AON_BG_SYS_TOP, tmpVal); - - BL702_Delay_US(55); - - return SUCCESS; + * @brief Power on bandgap system + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_BG(void) { + uint32_t tmpVal = 0; + + /* power up RF for PLL to work */ + tmpVal = BL_RD_REG(AON_BASE, AON_BG_SYS_TOP); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_BG_SYS_AON); + BL_WR_REG(AON_BASE, AON_BG_SYS_TOP, tmpVal); + + BL702_Delay_US(55); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off bandgap system - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_BG(void) -{ - uint32_t tmpVal = 0; - - /* power up RF for PLL to work */ - tmpVal = BL_RD_REG(AON_BASE, AON_BG_SYS_TOP); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_BG_SYS_AON); - BL_WR_REG(AON_BASE, AON_BG_SYS_TOP, tmpVal); - - BL702_Delay_US(55); - - return SUCCESS; + * @brief Power off bandgap system + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_BG(void) { + uint32_t tmpVal = 0; + + /* power up RF for PLL to work */ + tmpVal = BL_RD_REG(AON_BASE, AON_BG_SYS_TOP); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_BG_SYS_AON); + BL_WR_REG(AON_BASE, AON_BG_SYS_TOP, tmpVal); + + BL702_Delay_US(55); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on LDO11 - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO11_SOC(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO11SOC_AON); - BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); - - BL702_Delay_US(55); - - return SUCCESS; + * @brief Power on LDO11 + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO11_SOC(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO11SOC_AON); + BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); + + BL702_Delay_US(55); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off LDO11 - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO11_SOC(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO11SOC_AON); - BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); - - BL702_Delay_US(55); - - return SUCCESS; + * @brief Power off LDO11 + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO11_SOC(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO11SOC_AON); + BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); + + BL702_Delay_US(55); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on LDO15_RF - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO15_RF(void) -{ - uint32_t tmpVal = 0; - - /* ldo15rf power on */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - BL702_Delay_US(90); - - return SUCCESS; + * @brief Power on LDO15_RF + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO15_RF(void) { + uint32_t tmpVal = 0; + + /* ldo15rf power on */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + BL702_Delay_US(90); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off LDO15_RF - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO15_RF(void) -{ - uint32_t tmpVal = 0; - - /* ldo15rf power off */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - return SUCCESS; + * @brief Power off LDO15_RF + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO15_RF(void) { + uint32_t tmpVal = 0; + + /* ldo15rf power off */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief power on source follow regular - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_SFReg(void) -{ - uint32_t tmpVal = 0; - - /* power on sfreg */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_SFREG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - BL702_Delay_US(10); - - return SUCCESS; + * @brief power on source follow regular + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_SFReg(void) { + uint32_t tmpVal = 0; + + /* power on sfreg */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_SFREG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + BL702_Delay_US(10); + + return SUCCESS; } /****************************************************************************/ /** - * @brief power off source follow regular - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_SFReg(void) -{ - uint32_t tmpVal = 0; - - /* power off sfreg */ - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_SFREG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - return SUCCESS; + * @brief power off source follow regular + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_SFReg(void) { + uint32_t tmpVal = 0; + + /* power off sfreg */ + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_SFREG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off the power can be shut down in PDS0 - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Enter_PDS0(void) -{ - uint32_t tmpVal = 0; - - /* power off bz */ - tmpVal = BL_RD_REG(AON_BASE, AON_MISC); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_SW_BZ_EN_AON); - BL_WR_REG(AON_BASE, AON_MISC, tmpVal); - - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_SFREG_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); - tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_MBG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - - /* gating Clock, no more use */ - //tmpVal=BL_RD_REG(GLB_BASE,GLB_CGEN_CFG0); - //tmpVal=tmpVal&(~(1<<6)); - //tmpVal=tmpVal&(~(1<<7)); - //BL_WR_REG(GLB_BASE,GLB_CGEN_CFG0,tmpVal); - - return SUCCESS; + * @brief Power off the power can be shut down in PDS0 + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Enter_PDS0(void) { + uint32_t tmpVal = 0; + + /* power off bz */ + tmpVal = BL_RD_REG(AON_BASE, AON_MISC); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_SW_BZ_EN_AON); + BL_WR_REG(AON_BASE, AON_MISC, tmpVal); + + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_SFREG_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); + tmpVal = BL_CLR_REG_BIT(tmpVal, AON_PU_MBG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + + /* gating Clock, no more use */ + // tmpVal=BL_RD_REG(GLB_BASE,GLB_CGEN_CFG0); + // tmpVal=tmpVal&(~(1<<6)); + // tmpVal=tmpVal&(~(1<<7)); + // BL_WR_REG(GLB_BASE,GLB_CGEN_CFG0,tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on the power powered down in PDS0 - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Exit_PDS0(void) -{ - uint32_t tmpVal = 0; + * @brief Power on the power powered down in PDS0 + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Exit_PDS0(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); + tmpVal = BL_RD_REG(AON_BASE, AON_RF_TOP_AON); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_MBG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_MBG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - BL702_Delay_US(20); + BL702_Delay_US(20); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_LDO15RF_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - BL702_Delay_US(60); + BL702_Delay_US(60); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_SFREG_AON); - BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_PU_SFREG_AON); + BL_WR_REG(AON_BASE, AON_RF_TOP_AON, tmpVal); - BL702_Delay_US(20); + BL702_Delay_US(20); - /* power on bz */ - tmpVal = BL_RD_REG(AON_BASE, AON_MISC); - tmpVal = BL_SET_REG_BIT(tmpVal, AON_SW_BZ_EN_AON); - BL_WR_REG(AON_BASE, AON_MISC, tmpVal); + /* power on bz */ + tmpVal = BL_RD_REG(AON_BASE, AON_MISC); + tmpVal = BL_SET_REG_BIT(tmpVal, AON_SW_BZ_EN_AON); + BL_WR_REG(AON_BASE, AON_MISC, tmpVal); - /* ungating Clock, no more use */ - //tmpVal=BL_RD_REG(GLB_BASE,GLB_CGEN_CFG0); - //tmpVal=tmpVal|((1<<6)); - //tmpVal=tmpVal|((1<<7)); - //BL_WR_REG(GLB_BASE,GLB_CGEN_CFG0,tmpVal); + /* ungating Clock, no more use */ + // tmpVal=BL_RD_REG(GLB_BASE,GLB_CGEN_CFG0); + // tmpVal=tmpVal|((1<<6)); + // tmpVal=tmpVal|((1<<7)); + // BL_WR_REG(GLB_BASE,GLB_CGEN_CFG0,tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on the power powered down in PDS0 - * - * @param delay: None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION AON_Set_LDO11_SOC_Sstart_Delay(uint8_t delay) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM((delay <= 0x3)); - - /* config ldo11soc_sstart_delay_aon */ - tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_LDO11SOC_SSTART_DELAY_AON, delay); - BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); - - return SUCCESS; + * @brief Power on the power powered down in PDS0 + * + * @param delay: None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION AON_Set_LDO11_SOC_Sstart_Delay(uint8_t delay) { + uint32_t tmpVal = 0; + + CHECK_PARAM((delay <= 0x3)); + + /* config ldo11soc_sstart_delay_aon */ + tmpVal = BL_RD_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_LDO11SOC_SSTART_DELAY_AON, delay); + BL_WR_REG(AON_BASE, AON_LDO11SOC_AND_DCTEST, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief - * - * @param - * - * @return - * -*******************************************************************************/ -BL_Err_Type AON_Set_DCDC18_Top_0(uint8_t voutSel, uint8_t vpfm) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_DCDC18_TOP_0); - //dcdc18_vout_sel_aon, 1.425V*1.05=1.5V - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_DCDC18_VOUT_SEL_AON, voutSel); - //dcdc18_vpfm_aon - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_DCDC18_VPFM_AON, vpfm); - BL_WR_REG(AON_BASE, AON_DCDC18_TOP_0, tmpVal); - - return SUCCESS; + * @brief + * + * @param + * + * @return + * + *******************************************************************************/ +BL_Err_Type AON_Set_DCDC18_Top_0(uint8_t voutSel, uint8_t vpfm) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_DCDC18_TOP_0); + // dcdc18_vout_sel_aon, 1.425V*1.05=1.5V + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_DCDC18_VOUT_SEL_AON, voutSel); + // dcdc18_vpfm_aon + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_DCDC18_VPFM_AON, vpfm); + BL_WR_REG(AON_BASE, AON_DCDC18_TOP_0, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief - * - * @param - * - * @return - * -*******************************************************************************/ -BL_Err_Type AON_Set_Xtal_Cfg(uint8_t gmBoost, uint8_t ampCtrl, uint8_t fastStartup) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); - //xtal_gm_boost - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_GM_BOOST_AON, gmBoost); - //xtal_amp_ctrl - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_AMP_CTRL_AON, ampCtrl); - //xtal_fast_startup - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_FAST_STARTUP_AON, fastStartup); - BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); - - return SUCCESS; + * @brief + * + * @param + * + * @return + * + *******************************************************************************/ +BL_Err_Type AON_Set_Xtal_Cfg(uint8_t gmBoost, uint8_t ampCtrl, uint8_t fastStartup) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(AON_BASE, AON_XTAL_CFG); + // xtal_gm_boost + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_GM_BOOST_AON, gmBoost); + // xtal_amp_ctrl + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_AMP_CTRL_AON, ampCtrl); + // xtal_fast_startup + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, AON_XTAL_FAST_STARTUP_AON, fastStartup); + BL_WR_REG(AON_BASE, AON_XTAL_CFG, tmpVal); + + return SUCCESS; } /*@} end of group AON_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_cam.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_cam.c index 211230865..d8192941c 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_cam.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_cam.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_cam.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_cam.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702.h" #include "bl702_cam.h" +#include "bl702.h" #include "bl702_glb.h" /** @addtogroup BL702_Peripheral_Driver @@ -61,7 +61,7 @@ /** @defgroup CAM_Private_Variables * @{ */ -static intCallback_Type *camIntCbfArra[CAM_INT_ALL] = { NULL }; +static intCallback_Type *camIntCbfArra[CAM_INT_ALL] = {NULL}; /*@} end of group CAM_Private_Variables */ @@ -88,670 +88,642 @@ static intCallback_Type *camIntCbfArra[CAM_INT_ALL] = { NULL }; */ /****************************************************************************/ /** - * @brief Camera module init - * - * @param cfg: Camera configuration structure pointer - * - * @return None - * -*******************************************************************************/ -void CAM_Init(CAM_CFG_Type *cfg) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_CAM_SW_MODE_TYPE(cfg->swMode)); - CHECK_PARAM(IS_CAM_FRAME_MODE_TYPE(cfg->frameMode)); - CHECK_PARAM(IS_CAM_YUV_MODE_TYPE(cfg->yuvMode)); - CHECK_PARAM(IS_CAM_FRAME_ACTIVE_POL(cfg->framePol)); - CHECK_PARAM(IS_CAM_LINE_ACTIVE_POL(cfg->linePol)); - CHECK_PARAM(IS_CAM_BURST_TYPE(cfg->burstType)); - CHECK_PARAM(IS_CAM_SENSOR_MODE_TYPE(cfg->camSensorMode)); - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_CAM); - - /* Set camera configuration */ - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_SW_MODE, cfg->swMode); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_INTERLV_MODE, cfg->frameMode); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_FRAM_VLD_POL, cfg->framePol); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_LINE_VLD_POL, cfg->linePol); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_HBURST, cfg->burstType); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_MODE, cfg->camSensorMode); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_WAIT_CYCLE, cfg->waitCount); - - switch (cfg->yuvMode) { - case CAM_YUV422: - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); - break; - - case CAM_YUV420_EVEN: - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EVEN); - break; - - case CAM_YUV420_ODD: - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EVEN); - break; - - case CAM_YUV400_EVEN: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EVEN); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); - break; - - case CAM_YUV400_ODD: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EVEN); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); - break; - - default: - break; - } - - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); - - /* Set frame count to issue interrupt at sw mode */ - tmpVal = BL_RD_REG(CAM_BASE, CAM_INT_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_FRAME_CNT_TRGR_INT, cfg->swIntCnt); - BL_WR_REG(CAM_BASE, CAM_INT_CONTROL, tmpVal); - - /* Set camera memory start address, memory size and frame size in burst */ - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_ADDR_START_0, cfg->memStart0 & 0xFFFFFFF0); + * @brief Camera module init + * + * @param cfg: Camera configuration structure pointer + * + * @return None + * + *******************************************************************************/ +void CAM_Init(CAM_CFG_Type *cfg) { + uint32_t tmpVal; + + CHECK_PARAM(IS_CAM_SW_MODE_TYPE(cfg->swMode)); + CHECK_PARAM(IS_CAM_FRAME_MODE_TYPE(cfg->frameMode)); + CHECK_PARAM(IS_CAM_YUV_MODE_TYPE(cfg->yuvMode)); + CHECK_PARAM(IS_CAM_FRAME_ACTIVE_POL(cfg->framePol)); + CHECK_PARAM(IS_CAM_LINE_ACTIVE_POL(cfg->linePol)); + CHECK_PARAM(IS_CAM_BURST_TYPE(cfg->burstType)); + CHECK_PARAM(IS_CAM_SENSOR_MODE_TYPE(cfg->camSensorMode)); + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_CAM); + + /* Set camera configuration */ + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_SW_MODE, cfg->swMode); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_INTERLV_MODE, cfg->frameMode); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_FRAM_VLD_POL, cfg->framePol); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_LINE_VLD_POL, cfg->linePol); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_HBURST, cfg->burstType); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_MODE, cfg->camSensorMode); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_WAIT_CYCLE, cfg->waitCount); + + switch (cfg->yuvMode) { + case CAM_YUV422: + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); + break; + + case CAM_YUV420_EVEN: + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EVEN); + break; + + case CAM_YUV420_ODD: + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EVEN); + break; + + case CAM_YUV400_EVEN: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DROP_EVEN); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); + break; + + case CAM_YUV400_ODD: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DROP_EVEN); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_SUBSAMPLE_EN); + break; + + default: + break; + } + + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + + /* Set frame count to issue interrupt at sw mode */ + tmpVal = BL_RD_REG(CAM_BASE, CAM_INT_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_FRAME_CNT_TRGR_INT, cfg->swIntCnt); + BL_WR_REG(CAM_BASE, CAM_INT_CONTROL, tmpVal); + + /* Set camera memory start address, memory size and frame size in burst */ + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_ADDR_START_0, cfg->memStart0 & 0xFFFFFFF0); + + if (cfg->burstType == CAM_BURST_TYPE_SINGLE) { + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 4); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 4); + } else if (cfg->burstType == CAM_BURST_TYPE_INCR4) { + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 16); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 16); + } else if (cfg->burstType == CAM_BURST_TYPE_INCR8) { + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 32); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 32); + } else if (cfg->burstType == CAM_BURST_TYPE_INCR16) { + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 64); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 64); + } + + if (!cfg->frameMode) { + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_ADDR_START_1, cfg->memStart1 & 0xFFFFFFF0); if (cfg->burstType == CAM_BURST_TYPE_SINGLE) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 4); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 4); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 4); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 4); } else if (cfg->burstType == CAM_BURST_TYPE_INCR4) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 16); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 16); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 16); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 16); } else if (cfg->burstType == CAM_BURST_TYPE_INCR8) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 32); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 32); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 32); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 32); } else if (cfg->burstType == CAM_BURST_TYPE_INCR16) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_0, cfg->memSize0 / 64); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_0, cfg->frameSize0 / 64); - } - - if (!cfg->frameMode) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_ADDR_START_1, cfg->memStart1 & 0xFFFFFFF0); - - if (cfg->burstType == CAM_BURST_TYPE_SINGLE) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 4); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 4); - } else if (cfg->burstType == CAM_BURST_TYPE_INCR4) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 16); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 16); - } else if (cfg->burstType == CAM_BURST_TYPE_INCR8) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 32); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 32); - } else if (cfg->burstType == CAM_BURST_TYPE_INCR16) { - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 64); - BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 64); - } + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_MEM_BCNT_1, cfg->memSize1 / 64); + BL_WR_REG(CAM_BASE, CAM_DVP2AHB_FRAME_BCNT_1, cfg->frameSize1 / 64); } + } - /* Clear interrupt */ - BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 0xFFFF0); + /* Clear interrupt */ + BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 0xFFFF0); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(CAM_IRQn, CAM_IRQHandler); + Interrupt_Handler_Register(CAM_IRQn, CAM_IRQHandler); #endif } /****************************************************************************/ /** - * @brief Deinit camera module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void CAM_Deinit(void) -{ - //GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_CAM); + * @brief Deinit camera module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void CAM_Deinit(void) { + // GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_CAM); } /****************************************************************************/ /** - * @brief Enable camera module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void CAM_Enable(void) -{ - uint32_t tmpVal; - - /* Enable camera module */ - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + * @brief Enable camera module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void CAM_Enable(void) { + uint32_t tmpVal; + + /* Enable camera module */ + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); } /****************************************************************************/ /** - * @brief Disable camera module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void CAM_Disable(void) -{ - uint32_t tmpVal; - - /* Disable camera module */ - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + * @brief Disable camera module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void CAM_Disable(void) { + uint32_t tmpVal; + + /* Disable camera module */ + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_DVP_ENABLE); + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); } /****************************************************************************/ /** - * @brief Camera clock gate function - * - * @param enable: Enable or disable - * - * @return None - * -*******************************************************************************/ -void CAM_Clock_Gate(BL_Fun_Type enable) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_PIX_CLK_CG, enable); - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + * @brief Camera clock gate function + * + * @param enable: Enable or disable + * + * @return None + * + *******************************************************************************/ +void CAM_Clock_Gate(BL_Fun_Type enable) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_DVP_PIX_CLK_CG, enable); + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); } /****************************************************************************/ /** - * @brief Camera hsync crop function - * - * @param start: Valid hsync start count - * @param end: Valid hsync end count - * - * @return None - * -*******************************************************************************/ -void CAM_Hsync_Crop(uint16_t start, uint16_t end) -{ - BL_WR_REG(CAM_BASE, CAM_HSYNC_CONTROL, (start << 16) + end); -} + * @brief Camera hsync crop function + * + * @param start: Valid hsync start count + * @param end: Valid hsync end count + * + * @return None + * + *******************************************************************************/ +void CAM_Hsync_Crop(uint16_t start, uint16_t end) { BL_WR_REG(CAM_BASE, CAM_HSYNC_CONTROL, (start << 16) + end); } /****************************************************************************/ /** - * @brief Camera vsync crop function - * - * @param start: Valid vsync start count - * @param end: Valid vsync end count - * - * @return None - * -*******************************************************************************/ -void CAM_Vsync_Crop(uint16_t start, uint16_t end) -{ - BL_WR_REG(CAM_BASE, CAM_VSYNC_CONTROL, (start << 16) + end); -} + * @brief Camera vsync crop function + * + * @param start: Valid vsync start count + * @param end: Valid vsync end count + * + * @return None + * + *******************************************************************************/ +void CAM_Vsync_Crop(uint16_t start, uint16_t end) { BL_WR_REG(CAM_BASE, CAM_VSYNC_CONTROL, (start << 16) + end); } /****************************************************************************/ /** - * @brief Camera set total valid pix count in a line function - * - * @param count: Count value - * - * @return None - * -*******************************************************************************/ -void CAM_Set_Hsync_Total_Count(uint16_t count) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_TOTAL_HCNT, count); - BL_WR_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL, tmpVal); + * @brief Camera set total valid pix count in a line function + * + * @param count: Count value + * + * @return None + * + *******************************************************************************/ +void CAM_Set_Hsync_Total_Count(uint16_t count) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_TOTAL_HCNT, count); + BL_WR_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL, tmpVal); } /****************************************************************************/ /** - * @brief Camera set total valid line count in a frame function - * - * @param count: Count value - * - * @return None - * -*******************************************************************************/ -void CAM_Set_Vsync_Total_Count(uint16_t count) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_TOTAL_VCNT, count); - BL_WR_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL, tmpVal); + * @brief Camera set total valid line count in a frame function + * + * @param count: Count value + * + * @return None + * + *******************************************************************************/ +void CAM_Set_Vsync_Total_Count(uint16_t count) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_TOTAL_VCNT, count); + BL_WR_REG(CAM_BASE, CAM_FRAME_SIZE_CONTROL, tmpVal); } /****************************************************************************/ /** - * @brief Get one camera frame in interleave mode - * - * @param info: Interleave mode camera frame infomation pointer - * - * @return None - * -*******************************************************************************/ -void CAM_Interleave_Get_Frame_Info(CAM_Interleave_Frame_Info *info) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); - - info->validFrames = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_0); - info->curFrameAddr = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR0_0); - info->curFrameBytes = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT0_0); - info->status = tmpVal; + * @brief Get one camera frame in interleave mode + * + * @param info: Interleave mode camera frame infomation pointer + * + * @return None + * + *******************************************************************************/ +void CAM_Interleave_Get_Frame_Info(CAM_Interleave_Frame_Info *info) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); + + info->validFrames = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_0); + info->curFrameAddr = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR0_0); + info->curFrameBytes = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT0_0); + info->status = tmpVal; } /****************************************************************************/ /** - * @brief Get one camera frame in planar mode - * - * @param info: Planar mode camera frame infomation pointer - * - * @return None - * -*******************************************************************************/ -void CAM_Planar_Get_Frame_Info(CAM_Planar_Frame_Info *info) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); - - info->validFrames0 = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_0); - info->validFrames1 = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_1); - info->curFrameAddr0 = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR0_0); - info->curFrameAddr1 = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR1_0); - info->curFrameBytes0 = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT0_0); - info->curFrameBytes1 = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT1_0); - info->status = tmpVal; + * @brief Get one camera frame in planar mode + * + * @param info: Planar mode camera frame infomation pointer + * + * @return None + * + *******************************************************************************/ +void CAM_Planar_Get_Frame_Info(CAM_Planar_Frame_Info *info) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); + + info->validFrames0 = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_0); + info->validFrames1 = BL_GET_REG_BITS_VAL(tmpVal, CAM_FRAME_VALID_CNT_1); + info->curFrameAddr0 = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR0_0); + info->curFrameAddr1 = BL_RD_REG(CAM_BASE, CAM_FRAME_START_ADDR1_0); + info->curFrameBytes0 = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT0_0); + info->curFrameBytes1 = BL_RD_REG(CAM_BASE, CAM_FRAME_BYTE_CNT1_0); + info->status = tmpVal; } /****************************************************************************/ /** - * @brief Get available count 0 of frames - * - * @param None - * - * @return Frames count - * -*******************************************************************************/ -uint8_t CAM_Get_Frame_Count_0(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR), CAM_FRAME_VALID_CNT_0); -} + * @brief Get available count 0 of frames + * + * @param None + * + * @return Frames count + * + *******************************************************************************/ +uint8_t CAM_Get_Frame_Count_0(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR), CAM_FRAME_VALID_CNT_0); } /****************************************************************************/ /** - * @brief Get available count 1 of frames - * - * @param None - * - * @return Frames count - * -*******************************************************************************/ -uint8_t CAM_Get_Frame_Count_1(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR), CAM_FRAME_VALID_CNT_1); -} + * @brief Get available count 1 of frames + * + * @param None + * + * @return Frames count + * + *******************************************************************************/ +uint8_t CAM_Get_Frame_Count_1(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR), CAM_FRAME_VALID_CNT_1); } /****************************************************************************/ /** - * @brief Pop one camera frame in interleave mode - * - * @param None - * - * @return None - * -*******************************************************************************/ -void CAM_Interleave_Pop_Frame(void) -{ - /* Pop one frame */ - BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 1); + * @brief Pop one camera frame in interleave mode + * + * @param None + * + * @return None + * + *******************************************************************************/ +void CAM_Interleave_Pop_Frame(void) { + /* Pop one frame */ + BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 1); } /****************************************************************************/ /** - * @brief Pop one camera frame in planar mode - * - * @param None - * - * @return None - * -*******************************************************************************/ -void CAM_Planar_Pop_Frame(void) -{ - /* Pop one frame */ - BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 3); + * @brief Pop one camera frame in planar mode + * + * @param None + * + * @return None + * + *******************************************************************************/ +void CAM_Planar_Pop_Frame(void) { + /* Pop one frame */ + BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, 3); } /****************************************************************************/ /** - * @brief CAMERA Enable Disable Interrupt - * - * @param intType: CAMERA Interrupt Type - * @param intMask: Enable or Disable - * - * @return None - * -*******************************************************************************/ -void CAM_IntMask(CAM_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_CAM_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpVal = BL_RD_REG(CAM_BASE, CAM_INT_CONTROL); - - switch (intType) { - case CAM_INT_NORMAL_0: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_0_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_0_EN); - } - - break; - - case CAM_INT_NORMAL_1: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_1_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_1_EN); - } - - break; - - case CAM_INT_MEMORY_OVERWRITE_0: - case CAM_INT_MEMORY_OVERWRITE_1: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_MEM_EN); - } - - break; - - case CAM_INT_FRAME_OVERWRITE_0: - case CAM_INT_FRAME_OVERWRITE_1: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_FRAME_EN); - } - - break; - - case CAM_INT_FIFO_OVERWRITE_0: - case CAM_INT_FIFO_OVERWRITE_1: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_FIFO_EN); - } - - break; - - case CAM_INT_VSYNC_CNT_ERROR: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_VCNT_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_VCNT_EN); - } - - break; - - case CAM_INT_HSYNC_CNT_ERROR: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_HCNT_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_HCNT_EN); - } - - break; - - case CAM_INT_ALL: - if (intMask == UNMASK) { - /* Enable all interrupt */ - tmpVal |= 0x7F; - } else { - /* Disable all interrupt */ - tmpVal &= 0xFFFFFF80; - } - - break; - - default: - break; + * @brief CAMERA Enable Disable Interrupt + * + * @param intType: CAMERA Interrupt Type + * @param intMask: Enable or Disable + * + * @return None + * + *******************************************************************************/ +void CAM_IntMask(CAM_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_CAM_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpVal = BL_RD_REG(CAM_BASE, CAM_INT_CONTROL); + + switch (intType) { + case CAM_INT_NORMAL_0: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_0_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_0_EN); } - BL_WR_REG(CAM_BASE, CAM_INT_CONTROL, tmpVal); -} + break; -/****************************************************************************/ /** - * @brief CAMERA Interrupt Clear - * - * @param intType: CAMERA Interrupt Type - * - * @return None - * -*******************************************************************************/ -void CAM_IntClr(CAM_INT_Type intType) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP); + case CAM_INT_NORMAL_1: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_1_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_1_EN); + } - switch (intType) { - case CAM_INT_NORMAL_0: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_CLR_0); - break; + break; - case CAM_INT_NORMAL_1: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_CLR_1); - break; + case CAM_INT_MEMORY_OVERWRITE_0: + case CAM_INT_MEMORY_OVERWRITE_1: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_MEM_EN); + } - case CAM_INT_MEMORY_OVERWRITE_0: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_CLR_0); - break; + break; - case CAM_INT_MEMORY_OVERWRITE_1: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_CLR_1); - break; + case CAM_INT_FRAME_OVERWRITE_0: + case CAM_INT_FRAME_OVERWRITE_1: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_FRAME_EN); + } - case CAM_INT_FRAME_OVERWRITE_0: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_CLR_0); - break; + break; - case CAM_INT_FRAME_OVERWRITE_1: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_CLR_1); - break; + case CAM_INT_FIFO_OVERWRITE_0: + case CAM_INT_FIFO_OVERWRITE_1: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_FIFO_EN); + } - case CAM_INT_FIFO_OVERWRITE_0: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_CLR_0); - break; + break; - case CAM_INT_FIFO_OVERWRITE_1: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_CLR_1); - break; + case CAM_INT_VSYNC_CNT_ERROR: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_VCNT_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_VCNT_EN); + } - case CAM_INT_VSYNC_CNT_ERROR: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_VCNT_CLR_0); - break; + break; - case CAM_INT_HSYNC_CNT_ERROR: - tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_HCNT_CLR_0); - break; + case CAM_INT_HSYNC_CNT_ERROR: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_HCNT_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, CAM_REG_INT_HCNT_EN); + } - case CAM_INT_ALL: - tmpVal = 0xFFFF0; + break; - default: - break; + case CAM_INT_ALL: + if (intMask == UNMASK) { + /* Enable all interrupt */ + tmpVal |= 0x7F; + } else { + /* Disable all interrupt */ + tmpVal &= 0xFFFFFF80; } - BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, tmpVal); + break; + + default: + break; + } + + BL_WR_REG(CAM_BASE, CAM_INT_CONTROL, tmpVal); } /****************************************************************************/ /** - * @brief Install camera interrupt callback function - * - * @param intType: CAMERA interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return None - * -*******************************************************************************/ -void CAM_Int_Callback_Install(CAM_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_CAM_INT_TYPE(intType)); + * @brief CAMERA Interrupt Clear + * + * @param intType: CAMERA Interrupt Type + * + * @return None + * + *******************************************************************************/ +void CAM_IntClr(CAM_INT_Type intType) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP); + + switch (intType) { + case CAM_INT_NORMAL_0: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_CLR_0); + break; + + case CAM_INT_NORMAL_1: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_NORMAL_CLR_1); + break; + + case CAM_INT_MEMORY_OVERWRITE_0: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_CLR_0); + break; + + case CAM_INT_MEMORY_OVERWRITE_1: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_MEM_CLR_1); + break; + + case CAM_INT_FRAME_OVERWRITE_0: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_CLR_0); + break; + + case CAM_INT_FRAME_OVERWRITE_1: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FRAME_CLR_1); + break; + + case CAM_INT_FIFO_OVERWRITE_0: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_CLR_0); + break; + + case CAM_INT_FIFO_OVERWRITE_1: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_FIFO_CLR_1); + break; + + case CAM_INT_VSYNC_CNT_ERROR: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_VCNT_CLR_0); + break; + + case CAM_INT_HSYNC_CNT_ERROR: + tmpVal = BL_SET_REG_BIT(tmpVal, CAM_REG_INT_HCNT_CLR_0); + break; + + case CAM_INT_ALL: + tmpVal = 0xFFFF0; + + default: + break; + } + + BL_WR_REG(CAM_BASE, CAM_DVP_FRAME_FIFO_POP, tmpVal); +} - camIntCbfArra[intType] = cbFun; +/****************************************************************************/ /** + * @brief Install camera interrupt callback function + * + * @param intType: CAMERA interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return None + * + *******************************************************************************/ +void CAM_Int_Callback_Install(CAM_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_CAM_INT_TYPE(intType)); + + camIntCbfArra[intType] = cbFun; } /****************************************************************************/ /** - * @brief CAM hardware mode with frame start address wrap to memory address start function enable or disable - * - * @param enable: Enable or disable - * @return None - * -*******************************************************************************/ -void CAM_HW_Mode_Wrap(BL_Fun_Type enable) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_HW_MODE_FWRAP, enable); - BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); + * @brief CAM hardware mode with frame start address wrap to memory address start function enable or disable + * + * @param enable: Enable or disable + * @return None + * + *******************************************************************************/ +void CAM_HW_Mode_Wrap(BL_Fun_Type enable) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, CAM_REG_HW_MODE_FWRAP, enable); + BL_WR_REG(CAM_BASE, CAM_DVP2AXI_CONFIGUE, tmpVal); } /****************************************************************************/ /** - * @brief Camera interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Camera interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void CAM_IRQHandler(void) -{ - uint32_t tmpVal; +void CAM_IRQHandler(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); + tmpVal = BL_RD_REG(CAM_BASE, CAM_DVP_STATUS_AND_ERROR); - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_NORMAL_INT_0)) { - CAM_IntClr(CAM_INT_NORMAL_0); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_NORMAL_INT_0)) { + CAM_IntClr(CAM_INT_NORMAL_0); - if (camIntCbfArra[CAM_INT_NORMAL_0] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_NORMAL_0](); - } + if (camIntCbfArra[CAM_INT_NORMAL_0] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_NORMAL_0](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_NORMAL_INT_1)) { - CAM_IntClr(CAM_INT_NORMAL_1); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_NORMAL_INT_1)) { + CAM_IntClr(CAM_INT_NORMAL_1); - if (camIntCbfArra[CAM_INT_NORMAL_1] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_NORMAL_1](); - } + if (camIntCbfArra[CAM_INT_NORMAL_1] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_NORMAL_1](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_MEM_INT_0)) { - CAM_IntClr(CAM_INT_MEMORY_OVERWRITE_0); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_MEM_INT_0)) { + CAM_IntClr(CAM_INT_MEMORY_OVERWRITE_0); - if (camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_0] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_0](); - } + if (camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_0] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_0](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_MEM_INT_1)) { - CAM_IntClr(CAM_INT_MEMORY_OVERWRITE_1); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_MEM_INT_1)) { + CAM_IntClr(CAM_INT_MEMORY_OVERWRITE_1); - if (camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_1] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_1](); - } + if (camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_1] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_MEMORY_OVERWRITE_1](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FRAME_INT_0)) { - CAM_IntClr(CAM_INT_FRAME_OVERWRITE_0); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FRAME_INT_0)) { + CAM_IntClr(CAM_INT_FRAME_OVERWRITE_0); - if (camIntCbfArra[CAM_INT_FRAME_OVERWRITE_0] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_FRAME_OVERWRITE_0](); - } + if (camIntCbfArra[CAM_INT_FRAME_OVERWRITE_0] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_FRAME_OVERWRITE_0](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FRAME_INT_1)) { - CAM_IntClr(CAM_INT_FRAME_OVERWRITE_1); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FRAME_INT_1)) { + CAM_IntClr(CAM_INT_FRAME_OVERWRITE_1); - if (camIntCbfArra[CAM_INT_FRAME_OVERWRITE_1] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_FRAME_OVERWRITE_1](); - } + if (camIntCbfArra[CAM_INT_FRAME_OVERWRITE_1] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_FRAME_OVERWRITE_1](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FIFO_INT_0)) { - CAM_IntClr(CAM_INT_FIFO_OVERWRITE_0); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FIFO_INT_0)) { + CAM_IntClr(CAM_INT_FIFO_OVERWRITE_0); - if (camIntCbfArra[CAM_INT_FIFO_OVERWRITE_0] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_FIFO_OVERWRITE_0](); - } + if (camIntCbfArra[CAM_INT_FIFO_OVERWRITE_0] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_FIFO_OVERWRITE_0](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FIFO_INT_1)) { - CAM_IntClr(CAM_INT_FIFO_OVERWRITE_1); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_FIFO_INT_1)) { + CAM_IntClr(CAM_INT_FIFO_OVERWRITE_1); - if (camIntCbfArra[CAM_INT_FIFO_OVERWRITE_1] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_FIFO_OVERWRITE_1](); - } + if (camIntCbfArra[CAM_INT_FIFO_OVERWRITE_1] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_FIFO_OVERWRITE_1](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_HCNT_INT)) { - CAM_IntClr(CAM_INT_HSYNC_CNT_ERROR); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_HCNT_INT)) { + CAM_IntClr(CAM_INT_HSYNC_CNT_ERROR); - if (camIntCbfArra[CAM_INT_HSYNC_CNT_ERROR] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_HSYNC_CNT_ERROR](); - } + if (camIntCbfArra[CAM_INT_HSYNC_CNT_ERROR] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_HSYNC_CNT_ERROR](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_VCNT_INT)) { - CAM_IntClr(CAM_INT_VSYNC_CNT_ERROR); + if (BL_IS_REG_BIT_SET(tmpVal, CAM_STS_VCNT_INT)) { + CAM_IntClr(CAM_INT_VSYNC_CNT_ERROR); - if (camIntCbfArra[CAM_INT_VSYNC_CNT_ERROR] != NULL) { - /* call the callback function */ - camIntCbfArra[CAM_INT_VSYNC_CNT_ERROR](); - } + if (camIntCbfArra[CAM_INT_VSYNC_CNT_ERROR] != NULL) { + /* call the callback function */ + camIntCbfArra[CAM_INT_VSYNC_CNT_ERROR](); } + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_clock.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_clock.c index ce869738d..bf5e00e01 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_clock.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_clock.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_clock.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_clock.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_clock.h" @@ -86,77 +86,73 @@ static Clock_Cfg_Type clkCfg; */ /****************************************************************************/ /** - * @brief Set System Clock - * - * @param type: System clock type - * @param clock: System clock value - * - * @return None - * -*******************************************************************************/ -void Clock_System_Clock_Set(BL_System_Clock_Type type, uint32_t clock) -{ - if (type < BL_SYSTEM_CLOCK_MAX) { - clkCfg.systemClock[type] = clock / 1000000; - } + * @brief Set System Clock + * + * @param type: System clock type + * @param clock: System clock value + * + * @return None + * + *******************************************************************************/ +void Clock_System_Clock_Set(BL_System_Clock_Type type, uint32_t clock) { + if (type < BL_SYSTEM_CLOCK_MAX) { + clkCfg.systemClock[type] = clock / 1000000; + } } /****************************************************************************/ /** - * @brief Set Peripheral Clock - * - * @param type: Peripheral clock type - * @param clock: Peripheral clock value - * - * @return None - * -*******************************************************************************/ -void Clock_Peripheral_Clock_Set(BL_AHB_Slave1_Type type, uint32_t clock) -{ - if (type < BL_AHB_SLAVE1_MAX) { - if (type == BL_AHB_SLAVE1_I2S) { - clkCfg.i2sClock = clock; - } else { - clkCfg.peripheralClock[type] = clock / 1000000; - } + * @brief Set Peripheral Clock + * + * @param type: Peripheral clock type + * @param clock: Peripheral clock value + * + * @return None + * + *******************************************************************************/ +void Clock_Peripheral_Clock_Set(BL_AHB_Slave1_Type type, uint32_t clock) { + if (type < BL_AHB_SLAVE1_MAX) { + if (type == BL_AHB_SLAVE1_I2S) { + clkCfg.i2sClock = clock; + } else { + clkCfg.peripheralClock[type] = clock / 1000000; } + } } /****************************************************************************/ /** - * @brief Get System Clock - * - * @param type: System clock type - * - * @return System clock value - * -*******************************************************************************/ -uint32_t Clock_System_Clock_Get(BL_System_Clock_Type type) -{ - if (type < BL_SYSTEM_CLOCK_MAX) { - return clkCfg.systemClock[type] * 1000000; - } - - return 0; + * @brief Get System Clock + * + * @param type: System clock type + * + * @return System clock value + * + *******************************************************************************/ +uint32_t Clock_System_Clock_Get(BL_System_Clock_Type type) { + if (type < BL_SYSTEM_CLOCK_MAX) { + return clkCfg.systemClock[type] * 1000000; + } + + return 0; } /****************************************************************************/ /** - * @brief Get Peripheral Clock - * - * @param type: Peripheral clock type - * - * @return Peripheral clock value - * -*******************************************************************************/ -uint32_t Clock_Peripheral_Clock_Get(BL_AHB_Slave1_Type type) -{ - if (type < BL_AHB_SLAVE1_MAX) { - if (type == BL_AHB_SLAVE1_I2S) { - return clkCfg.i2sClock; - } else { - return clkCfg.peripheralClock[type] * 1000000; - } + * @brief Get Peripheral Clock + * + * @param type: Peripheral clock type + * + * @return Peripheral clock value + * + *******************************************************************************/ +uint32_t Clock_Peripheral_Clock_Get(BL_AHB_Slave1_Type type) { + if (type < BL_AHB_SLAVE1_MAX) { + if (type == BL_AHB_SLAVE1_I2S) { + return clkCfg.i2sClock; + } else { + return clkCfg.peripheralClock[type] * 1000000; } + } - return 0; + return 0; } /*@} end of group CLOCK_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_common.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_common.c index a9fafc035..08bd9c386 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_common.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_common.c @@ -1,195 +1,186 @@ /** - ****************************************************************************** - * @file bl702_common.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#include "l1c_reg.h" + ****************************************************************************** + * @file bl702_common.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_common.h" +#include "l1c_reg.h" /** @addtogroup BL702_Periph_Driver * @{ */ /****************************************************************************/ /** - * @brief delay us - * - * @param[in] core: systemcoreclock - * - * @param[in] cnt: delay cnt us - * - * @return none - * - *******************************************************************************/ + * @brief delay us + * + * @param[in] core: systemcoreclock + * + * @param[in] cnt: delay cnt us + * + * @return none + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER #ifdef ARCH_ARM #ifndef __GNUC__ __WEAK -__ASM void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt) -{ - lsrs r0, #0x10 muls r0, r1, r0 mov r2, r0 lsrs r2, #0x04 lsrs r2, #0x03 cmp r2, #0x01 beq end cmp r2, #0x00 beq end loop mov r0, r0 mov r0, r0 mov r0, r0 mov r0, r0 mov r0, r0 subs r2, r2, #0x01 cmp r2, #0x00 bne loop end bx lr +__ASM void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt){ + lsrs r0, #0x10 muls r0, r1, r0 mov r2, r0 lsrs r2, #0x04 lsrs r2, #0x03 cmp r2, #0x01 beq end cmp r2, #0x00 beq end loop mov r0, r0 mov r0, r0 mov r0, r0 mov r0, r0 mov r0, r0 subs r2, r2, +# 0x01 cmp r2, #0x00 bne loop end bx lr } #else __WEAK -void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt) -{ - __asm__ __volatile__( - "lsr r0,#0x10\n\t" - "mul r0,r1,r0\n\t" - "mov r2,r0\n\t" - "lsr r2,#0x04\n\t" - "lsr r2,#0x03\n\t" - "cmp r2,#0x01\n\t" - "beq end\n\t" - "cmp r2,#0x00\n\t" - "beq end\n" - "loop :" - "mov r0,r0\n\t" - "mov r0,r0\n\t" - "mov r0,r0\n\t" - "mov r0,r0\n\t" - "mov r0,r0\n\t" - "sub r2,r2,#0x01\n\t" - "cmp r2,#0x00\n\t" - "bne loop\n" - "end :" - "mov r0,r0\n\t"); +void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt) { + __asm__ __volatile__("lsr r0,#0x10\n\t" + "mul r0,r1,r0\n\t" + "mov r2,r0\n\t" + "lsr r2,#0x04\n\t" + "lsr r2,#0x03\n\t" + "cmp r2,#0x01\n\t" + "beq end\n\t" + "cmp r2,#0x00\n\t" + "beq end\n" + "loop :" + "mov r0,r0\n\t" + "mov r0,r0\n\t" + "mov r0,r0\n\t" + "mov r0,r0\n\t" + "mov r0,r0\n\t" + "sub r2,r2,#0x01\n\t" + "cmp r2,#0x00\n\t" + "bne loop\n" + "end :" + "mov r0,r0\n\t"); } #endif #endif #ifdef ARCH_RISCV -__WEAK -void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt) -{ - uint32_t codeAddress = 0; - uint32_t divVal = 40; +__WEAK void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core, uint32_t cnt) { + uint32_t codeAddress = 0; + uint32_t divVal = 40; - codeAddress = (uint32_t)&ASM_Delay_Us; + codeAddress = (uint32_t)&ASM_Delay_Us; - /* 1M=100K*10, so multiple is 10 */ - /* loop function take 4 instructions, so instructionNum is 4 */ - /* if codeAddress locate at IROM space and irom_2t_access is 1, then irom2TAccess=2, else irom2TAccess=1 */ - /* divVal = multiple*instructionNum*irom2TAccess */ - if (((codeAddress & (0xF << 24)) >> 24) == 0x01) { - /* IROM space */ - if (BL_GET_REG_BITS_VAL(BL_RD_REG(L1C_BASE, L1C_CONFIG), L1C_IROM_2T_ACCESS)) { - /* instruction 2T */ - divVal = 80; - } + /* 1M=100K*10, so multiple is 10 */ + /* loop function take 4 instructions, so instructionNum is 4 */ + /* if codeAddress locate at IROM space and irom_2t_access is 1, then irom2TAccess=2, else irom2TAccess=1 */ + /* divVal = multiple*instructionNum*irom2TAccess */ + if (((codeAddress & (0xF << 24)) >> 24) == 0x01) { + /* IROM space */ + if (BL_GET_REG_BITS_VAL(BL_RD_REG(L1C_BASE, L1C_CONFIG), L1C_IROM_2T_ACCESS)) { + /* instruction 2T */ + divVal = 80; } + } - __asm__ __volatile__( - ".align 4\n\t" - "lw a4,%1\n\t" - "lui a5,0x18\n\t" - "addi a5,a5,1696\n\t" - "divu a5,a4,a5\n\t" - "sw a5,%1\n\t" - "lw a4,%1\n\t" - "lw a5,%0\n\t" - "mul a5,a4,a5\n\t" - "sw a5,%1\n\t" - "lw a4,%1\n\t" - "lw a5,%2\n\t" - "divu a5,a4,a5\n\t" - "sw a5,%1\n\t" - "lw a5,%1\n\t" - "li a4,0x1\n\t" - "beq a5,zero,end\n\t" - "beq a5,a4,end\n\t" - "nop\n\t" - "nop\n\t" - ".align 4\n\t" - "loop :\n" - "addi a4,a5,-1\n\t" - "mv a5,a4\n\t" - "bnez a5,loop\n\t" - "nop\n\t" - "end :\n\t" - "nop\n" - : /* output */ - : "m"(cnt), "m"(core), "m"(divVal) /* input */ - : "t1", "a4", "a5" /* destruct description */ - ); + __asm__ __volatile__(".align 4\n\t" + "lw a4,%1\n\t" + "lui a5,0x18\n\t" + "addi a5,a5,1696\n\t" + "divu a5,a4,a5\n\t" + "sw a5,%1\n\t" + "lw a4,%1\n\t" + "lw a5,%0\n\t" + "mul a5,a4,a5\n\t" + "sw a5,%1\n\t" + "lw a4,%1\n\t" + "lw a5,%2\n\t" + "divu a5,a4,a5\n\t" + "sw a5,%1\n\t" + "lw a5,%1\n\t" + "li a4,0x1\n\t" + "beq a5,zero,end\n\t" + "beq a5,a4,end\n\t" + "nop\n\t" + "nop\n\t" + ".align 4\n\t" + "loop :\n" + "addi a4,a5,-1\n\t" + "mv a5,a4\n\t" + "bnez a5,loop\n\t" + "nop\n\t" + "end :\n\t" + "nop\n" + : /* output */ + : "m"(cnt), "m"(core), "m"(divVal) /* input */ + : "t1", "a4", "a5" /* destruct description */ + ); } #endif #endif /****************************************************************************/ /** - * @brief delay us - * - * @param[in] cnt: delay cnt us - * - * @return none - * - *******************************************************************************/ + * @brief delay us + * + * @param[in] cnt: delay cnt us + * + * @return none + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION BL702_Delay_US(uint32_t cnt) -{ - ASM_Delay_Us(SystemCoreClockGet(), cnt); -} +void ATTR_TCM_SECTION BL702_Delay_US(uint32_t cnt) { ASM_Delay_Us(SystemCoreClockGet(), cnt); } #endif /****************************************************************************/ /** - * @brief delay ms - * - * @param[in] cnt: delay cnt ms - * - * @return none - * - *******************************************************************************/ + * @brief delay ms + * + * @param[in] cnt: delay cnt ms + * + * @return none + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION BL702_Delay_MS(uint32_t cnt) -{ - uint32_t i = 0; - uint32_t count = 0; +void ATTR_TCM_SECTION BL702_Delay_MS(uint32_t cnt) { + uint32_t i = 0; + uint32_t count = 0; - if (cnt >= 1024) { - /* delay (n*1024) ms */ - count = 1024; + if (cnt >= 1024) { + /* delay (n*1024) ms */ + count = 1024; - for (i = 0; i < (cnt / 1024); i++) { - BL702_Delay_US(1024 * 1000); - } + for (i = 0; i < (cnt / 1024); i++) { + BL702_Delay_US(1024 * 1000); } + } - if (cnt & 0x3FF) { - /* delay (1-1023)ms */ - count = cnt & 0x3FF; - BL702_Delay_US(count * 1000); - } + if (cnt & 0x3FF) { + /* delay (1-1023)ms */ + count = cnt & 0x3FF; + BL702_Delay_US(count * 1000); + } - //BL702_Delay_US(((cnt<<10)-(cnt<<4)-(cnt<<3))); + // BL702_Delay_US(((cnt<<10)-(cnt<<4)-(cnt<<3))); } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c index 943b135f4..296126224 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dac.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_dac.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_dac.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_dac.h" @@ -47,17 +47,17 @@ /** @defgroup DAC_Private_Macros * @{ */ -#define GPIP_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - } +#define GPIP_CLK_SET_DUMMY_WAIT \ + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + } /*@} end of group DAC_Private_Macros */ @@ -96,419 +96,399 @@ */ /****************************************************************************/ /** - * @brief DAC initialization - * - * @param cfg: DAC configuration pointer - * - * @return None - * -*******************************************************************************/ -void GLB_DAC_Init(GLB_DAC_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_GLB_DAC_REF_SEL_TYPE(cfg->refSel)); - - /* Set DAC config */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_REF_SEL, cfg->refSel); - - if (ENABLE == cfg->resetChanA) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - } - - if (ENABLE == cfg->resetChanB) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - } - - /* Clear reset */ - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); + * @brief DAC initialization + * + * @param cfg: DAC configuration pointer + * + * @return None + * + *******************************************************************************/ +void GLB_DAC_Init(GLB_DAC_Cfg_Type *cfg) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_GLB_DAC_REF_SEL_TYPE(cfg->refSel)); + + /* Set DAC config */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_REF_SEL, cfg->refSel); + + if (ENABLE == cfg->resetChanA) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + } + + if (ENABLE == cfg->resetChanB) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + } + + /* Clear reset */ + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); } /****************************************************************************/ /** - * @brief DAC channel A initialization - * - * @param cfg: DAC channel configuration pointer - * - * @return None - * -*******************************************************************************/ -void GLB_DAC_Set_ChanA_Config(GLB_DAC_Chan_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_GLB_DAC_CHAN_TYPE(cfg->outMux)); - - /* Set channel A config */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_ACTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_OUTMUX, cfg->outMux); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOA_EN, cfg->outputEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_EN, cfg->chanEn); - - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_ACTRL, tmpVal); + * @brief DAC channel A initialization + * + * @param cfg: DAC channel configuration pointer + * + * @return None + * + *******************************************************************************/ +void GLB_DAC_Set_ChanA_Config(GLB_DAC_Chan_Cfg_Type *cfg) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_GLB_DAC_CHAN_TYPE(cfg->outMux)); + + /* Set channel A config */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_ACTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_OUTMUX, cfg->outMux); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOA_EN, cfg->outputEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_EN, cfg->chanEn); + + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_ACTRL, tmpVal); } /****************************************************************************/ /** - * @brief DAC channel B initialization - * - * @param cfg: DAC channel configuration pointer - * - * @return None - * -*******************************************************************************/ -void GLB_DAC_Set_ChanB_Config(GLB_DAC_Chan_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_GLB_DAC_CHAN_TYPE(cfg->outMux)); - - /* Set channel A config */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_BCTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_OUTMUX, cfg->outMux); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOB_EN, cfg->outputEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_EN, cfg->chanEn); - - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_BCTRL, tmpVal); + * @brief DAC channel B initialization + * + * @param cfg: DAC channel configuration pointer + * + * @return None + * + *******************************************************************************/ +void GLB_DAC_Set_ChanB_Config(GLB_DAC_Chan_Cfg_Type *cfg) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_GLB_DAC_CHAN_TYPE(cfg->outMux)); + + /* Set channel A config */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_BCTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_OUTMUX, cfg->outMux); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOB_EN, cfg->outputEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_EN, cfg->chanEn); + + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_BCTRL, tmpVal); } /****************************************************************************/ /** - * @brief Select DAC channel B source - * - * @param src: DAC channel B source selection type - * - * @return None - * -*******************************************************************************/ -void GPIP_Set_DAC_ChanB_SRC_SEL(GPIP_DAC_ChanB_SRC_Type src) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(src)); - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_B_SEL, src); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Select DAC channel B source + * + * @param src: DAC channel B source selection type + * + * @return None + * + *******************************************************************************/ +void GPIP_Set_DAC_ChanB_SRC_SEL(GPIP_DAC_ChanB_SRC_Type src) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(src)); + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_B_SEL, src); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Select DAC channel A source - * - * @param src: DAC channel A source selection type - * - * @return None - * -*******************************************************************************/ -void GPIP_Set_DAC_ChanA_SRC_SEL(GPIP_DAC_ChanA_SRC_Type src) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(src)); - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_A_SEL, src); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Select DAC channel A source + * + * @param src: DAC channel A source selection type + * + * @return None + * + *******************************************************************************/ +void GPIP_Set_DAC_ChanA_SRC_SEL(GPIP_DAC_ChanA_SRC_Type src) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(src)); + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_A_SEL, src); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Enable DAC channel B - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_DAC_ChanB_Enable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_EN2); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Enable DAC channel B + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_DAC_ChanB_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_EN2); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Disable DAC channel B - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_DAC_ChanB_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_EN2); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Disable DAC channel B + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_DAC_ChanB_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_EN2); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Enable DAC channel A - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_DAC_ChanA_Enable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_EN); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Enable DAC channel A + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_DAC_ChanA_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_EN); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Disable DAC channel A - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_DAC_ChanA_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_EN); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + * @brief Disable DAC channel A + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_DAC_ChanA_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_EN); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Select DAC DMA TX format - * - * @param fmt: DAC DMA TX format selection type - * - * @return None - * -*******************************************************************************/ -void GPIP_Set_DAC_DMA_TX_FORMAT_SEL(GPIP_DAC_DMA_TX_FORMAT_Type fmt) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(fmt)); - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_FORMAT, fmt); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); + * @brief Select DAC DMA TX format + * + * @param fmt: DAC DMA TX format selection type + * + * @return None + * + *******************************************************************************/ +void GPIP_Set_DAC_DMA_TX_FORMAT_SEL(GPIP_DAC_DMA_TX_FORMAT_Type fmt) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(fmt)); + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_FORMAT, fmt); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Enable DAC DMA TX - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_Set_DAC_DMA_TX_Enable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_DMA_TX_EN); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); + * @brief Enable DAC DMA TX + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_Set_DAC_DMA_TX_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, GPIP_GPDAC_DMA_TX_EN); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Disable DAC DMA TX - * - * @param None - * - * @return None - * -*******************************************************************************/ -void GPIP_Set_DAC_DMA_TX_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_DMA_TX_EN); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); + * @brief Disable DAC DMA TX + * + * @param None + * + * @return None + * + *******************************************************************************/ +void GPIP_Set_DAC_DMA_TX_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, GPIP_GPDAC_DMA_TX_EN); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Disable DAC DMA TX - * - * @param data: The data to be send - * - * @return None - * -*******************************************************************************/ -void GPIP_DAC_DMA_WriteData(uint32_t data) -{ - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_WDATA, data); -} + * @brief Disable DAC DMA TX + * + * @param data: The data to be send + * + * @return None + * + *******************************************************************************/ +void GPIP_DAC_DMA_WriteData(uint32_t data) { BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_WDATA, data); } /****************************************************************************/ /** - * @brief AON and GPIP DAC config - * - * @param cfg: AON and GPIP DAC configuration - * - * @return config success or not - * -*******************************************************************************/ -BL_Err_Type GLB_GPIP_DAC_Init(GLB_GPIP_DAC_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_DAC_REF_SEL_TYPE(cfg->refSel)); - CHECK_PARAM(IS_GPIP_DAC_MOD_TYPE(cfg->div)); - CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(cfg->dmaFmt)); - - /* AON Set DAC config */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_REF_SEL, cfg->refSel); - - if (ENABLE == cfg->resetChanA) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - } - - if (ENABLE == cfg->resetChanB) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - } - - /* AON Clear reset */ - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); + * @brief AON and GPIP DAC config + * + * @param cfg: AON and GPIP DAC configuration + * + * @return config success or not + * + *******************************************************************************/ +BL_Err_Type GLB_GPIP_DAC_Init(GLB_GPIP_DAC_Cfg_Type *cfg) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GLB_DAC_REF_SEL_TYPE(cfg->refSel)); + CHECK_PARAM(IS_GPIP_DAC_MOD_TYPE(cfg->div)); + CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(cfg->dmaFmt)); + + /* AON Set DAC config */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_REF_SEL, cfg->refSel); + + if (ENABLE == cfg->resetChanA) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); - - /* GPIP Set DAC config */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_MODE, cfg->div); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); - - /* GPIP Set DMA config */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_TX_EN, cfg->dmaEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_FORMAT, cfg->dmaFmt); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); - - return SUCCESS; + __NOP(); + __NOP(); + __NOP(); + __NOP(); + } + + if (ENABLE == cfg->resetChanB) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + } + + /* AON Clear reset */ + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACA_RSTN_ANA); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPDACB_RSTN_ANA); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_CTRL, tmpVal); + + /* GPIP Set DAC config */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_MODE, cfg->div); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + + /* GPIP Set DMA config */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_TX_EN, cfg->dmaEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_DMA_FORMAT, cfg->dmaFmt); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_DMA_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief AON and GPIP DAC channel A config - * - * @param cfg: AON and GPIP DAC channel A configuration - * - * @return None - * -*******************************************************************************/ -void GLB_GPIP_DAC_Set_ChanA_Config(GLB_GPIP_DAC_ChanA_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(cfg->src)); - - /* GPIP select source */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_A_SEL, cfg->src); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); - - /* GPIP enable or disable channel */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_EN, cfg->chanEn); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); - - /* AON enable or disable channel */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_ACTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOA_EN, cfg->outputEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_EN, cfg->chanCovtEn); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_ACTRL, tmpVal); + * @brief AON and GPIP DAC channel A config + * + * @param cfg: AON and GPIP DAC channel A configuration + * + * @return None + * + *******************************************************************************/ +void GLB_GPIP_DAC_Set_ChanA_Config(GLB_GPIP_DAC_ChanA_Cfg_Type *cfg) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(cfg->src)); + + /* GPIP select source */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_A_SEL, cfg->src); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + + /* GPIP enable or disable channel */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_EN, cfg->chanEn); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + + /* AON enable or disable channel */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_ACTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOA_EN, cfg->outputEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_EN, cfg->chanCovtEn); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_ACTRL, tmpVal); } /****************************************************************************/ /** - * @brief AON and GPIP DAC channel B config - * - * @param cfg: AON and GPIP DAC channel B configuration - * - * @return None - * -*******************************************************************************/ -void GLB_GPIP_DAC_Set_ChanB_Config(GLB_GPIP_DAC_ChanB_Cfg_Type *cfg) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(cfg->src)); - - /* GPIP select source */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_B_SEL, cfg->src); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); - - /* GPIP enable or disable channel */ - tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_EN2, cfg->chanEn); - BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); - - /* AON enable or disable channel */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_BCTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOB_EN, cfg->outputEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_EN, cfg->chanCovtEn); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_BCTRL, tmpVal); + * @brief AON and GPIP DAC channel B config + * + * @param cfg: AON and GPIP DAC channel B configuration + * + * @return None + * + *******************************************************************************/ +void GLB_GPIP_DAC_Set_ChanB_Config(GLB_GPIP_DAC_ChanB_Cfg_Type *cfg) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(cfg->src)); + + /* GPIP select source */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_CH_B_SEL, cfg->src); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + + /* GPIP enable or disable channel */ + tmpVal = BL_RD_REG(GPIP_BASE, GPIP_GPDAC_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GPIP_GPDAC_EN2, cfg->chanEn); + BL_WR_REG(GPIP_BASE, GPIP_GPDAC_CONFIG, tmpVal); + + /* AON enable or disable channel */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_BCTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_IOB_EN, cfg->outputEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_EN, cfg->chanCovtEn); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_BCTRL, tmpVal); } /****************************************************************************/ /** - * @brief DAC channel A set value - * - * @param val: DAC value - * - * @return None - * -*******************************************************************************/ -void GLB_DAC_Set_ChanA_Value(uint16_t val) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_DATA); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_DATA, val); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_DATA, tmpVal); + * @brief DAC channel A set value + * + * @param val: DAC value + * + * @return None + * + *******************************************************************************/ +void GLB_DAC_Set_ChanA_Value(uint16_t val) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_DATA); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_A_DATA, val); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_DATA, tmpVal); } /****************************************************************************/ /** - * @brief DAC channel B set value - * - * @param val: DAC value - * - * @return None - * -*******************************************************************************/ -void GLB_DAC_Set_ChanB_Value(uint16_t val) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_DATA); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_DATA, val); - tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_DATA, tmpVal); + * @brief DAC channel B set value + * + * @param val: DAC value + * + * @return None + * + *******************************************************************************/ +void GLB_DAC_Set_ChanB_Value(uint16_t val) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPDAC_DATA); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPDAC_B_DATA, val); + tmpVal = BL_WR_REG(GLB_BASE, GLB_GPDAC_DATA, tmpVal); } /*@} end of group DAC_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c index d985ccc1b..7bbcacfdd 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_dma.c @@ -1,43 +1,43 @@ /** - ****************************************************************************** - * @file bl702_dma.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_dma.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702.h" #include "bl702_dma.h" -#include "string.h" +#include "bl702.h" #include "bl702_glb.h" +#include "string.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -51,14 +51,14 @@ * @{ */ #define DMA_CHANNEL_OFFSET 0x100 -#define DMA_Get_Channel(ch) (DMA_BASE + DMA_CHANNEL_OFFSET + (ch)*0x100) +#define DMA_Get_Channel(ch) (DMA_BASE + DMA_CHANNEL_OFFSET + (ch) * 0x100) static intCallback_Type *dmaIntCbfArra[DMA_CH_MAX][DMA_INT_ALL] = { - { NULL, NULL }, - { NULL, NULL }, - { NULL, NULL }, - { NULL, NULL } + {NULL, NULL}, + {NULL, NULL}, + {NULL, NULL}, + {NULL, NULL} }; -static DMA_LLI_Ctrl_Type PingPongListArra[DMA_CH_MAX][2]; +// static DMA_LLI_Ctrl_Type PingPongListArra[DMA_CH_MAX][2]; /*@} end of group DMA_Private_Macros */ @@ -90,58 +90,57 @@ static DMA_LLI_Ctrl_Type PingPongListArra[DMA_CH_MAX][2]; * @{ */ -/****************************************************************************/ /** +/** * @brief DMA interrupt handler * * @param None * * @return None * -*******************************************************************************/ + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void DMA_ALL_IRQHandler(void) -{ - uint32_t tmpVal; - uint32_t intClr; - uint8_t ch; - /* Get DMA register */ - uint32_t DMAChs = DMA_BASE; - - for (ch = 0; ch < DMA_CH_MAX; ch++) { - tmpVal = BL_RD_REG(DMAChs, DMA_INTTCSTATUS); - - if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCSTATUS) & (1 << ch)) != 0) { - /* Clear interrupt */ - tmpVal = BL_RD_REG(DMAChs, DMA_INTTCCLEAR); - intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR); - intClr |= (1 << ch); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR, intClr); - BL_WR_REG(DMAChs, DMA_INTTCCLEAR, tmpVal); - - if (dmaIntCbfArra[ch][DMA_INT_TCOMPLETED] != NULL) { - /* Call the callback function */ - dmaIntCbfArra[ch][DMA_INT_TCOMPLETED](); - } - } +void DMA_ALL_IRQHandler(void) { + uint32_t tmpVal; + uint32_t intClr; + uint8_t ch; + /* Get DMA register */ + uint32_t DMAChs = DMA_BASE; + + for (ch = 0; ch < DMA_CH_MAX; ch++) { + tmpVal = BL_RD_REG(DMAChs, DMA_INTTCSTATUS); + + if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCSTATUS) & (1 << ch)) != 0) { + /* Clear interrupt */ + tmpVal = BL_RD_REG(DMAChs, DMA_INTTCCLEAR); + intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR); + intClr |= (1 << ch); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTTCCLEAR, intClr); + BL_WR_REG(DMAChs, DMA_INTTCCLEAR, tmpVal); + + if (dmaIntCbfArra[ch][DMA_INT_TCOMPLETED] != NULL) { + /* Call the callback function */ + dmaIntCbfArra[ch][DMA_INT_TCOMPLETED](); + } } - - for (ch = 0; ch < DMA_CH_MAX; ch++) { - tmpVal = BL_RD_REG(DMAChs, DMA_INTERRORSTATUS); - - if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRORSTATUS) & (1 << ch)) != 0) { - /*Clear interrupt */ - tmpVal = BL_RD_REG(DMAChs, DMA_INTERRCLR); - intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR); - intClr |= (1 << ch); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR, intClr); - BL_WR_REG(DMAChs, DMA_INTERRCLR, tmpVal); - - if (dmaIntCbfArra[ch][DMA_INT_ERR] != NULL) { - /* Call the callback function */ - dmaIntCbfArra[ch][DMA_INT_ERR](); - } - } + } + + for (ch = 0; ch < DMA_CH_MAX; ch++) { + tmpVal = BL_RD_REG(DMAChs, DMA_INTERRORSTATUS); + + if ((BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRORSTATUS) & (1 << ch)) != 0) { + /*Clear interrupt */ + tmpVal = BL_RD_REG(DMAChs, DMA_INTERRCLR); + intClr = BL_GET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR); + intClr |= (1 << ch); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_INTERRCLR, intClr); + BL_WR_REG(DMAChs, DMA_INTERRCLR, tmpVal); + + if (dmaIntCbfArra[ch][DMA_INT_ERR] != NULL) { + /* Call the callback function */ + dmaIntCbfArra[ch][DMA_INT_ERR](); + } } + } } #endif @@ -151,103 +150,104 @@ void DMA_ALL_IRQHandler(void) * @{ */ -/****************************************************************************/ /** +/** * @brief DMA enable * * @param None * * @return None * -*******************************************************************************/ -void DMA_Enable(void) -{ - uint32_t tmpVal; - /* Get DMA register */ - uint32_t DMAChs = DMA_BASE; + *******************************************************************************/ +void DMA_Enable(void) { + uint32_t tmpVal; + /* Get DMA register */ + uint32_t DMAChs = DMA_BASE; - tmpVal = BL_RD_REG(DMAChs, DMA_TOP_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, DMA_E); - BL_WR_REG(DMAChs, DMA_TOP_CONFIG, tmpVal); + tmpVal = BL_RD_REG(DMAChs, DMA_TOP_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, DMA_E); + BL_WR_REG(DMAChs, DMA_TOP_CONFIG, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(DMA_ALL_IRQn, DMA_ALL_IRQHandler); + Interrupt_Handler_Register(DMA_ALL_IRQn, DMA_ALL_IRQHandler); #endif } -/****************************************************************************/ /** +/** * @brief DMA disable * * @param None * * @return None * -*******************************************************************************/ -void DMA_Disable(void) -{ - uint32_t tmpVal; - /* Get DMA register */ - uint32_t DMAChs = DMA_BASE; + *******************************************************************************/ +void DMA_Disable(void) { + uint32_t tmpVal; + /* Get DMA register */ + uint32_t DMAChs = DMA_BASE; - tmpVal = BL_RD_REG(DMAChs, DMA_TOP_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_E); - BL_WR_REG(DMAChs, DMA_TOP_CONFIG, tmpVal); + tmpVal = BL_RD_REG(DMAChs, DMA_TOP_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_E); + BL_WR_REG(DMAChs, DMA_TOP_CONFIG, tmpVal); } -/****************************************************************************/ /** +/** * @brief DMA channel init * * @param chCfg: DMA configuration * * @return None * -*******************************************************************************/ -void DMA_Channel_Init(DMA_Channel_Cfg_Type *chCfg) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(chCfg->ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(chCfg->ch)); - CHECK_PARAM(IS_DMA_TRANS_WIDTH_TYPE(chCfg->srcTransfWidth)); - CHECK_PARAM(IS_DMA_TRANS_WIDTH_TYPE(chCfg->dstTransfWidth)); - CHECK_PARAM(IS_DMA_BURST_SIZE_TYPE(chCfg->srcBurstSzie)); - CHECK_PARAM(IS_DMA_BURST_SIZE_TYPE(chCfg->dstBurstSzie)); - CHECK_PARAM(IS_DMA_TRANS_DIR_TYPE(chCfg->dir)); - CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(chCfg->dstPeriph)); - CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(chCfg->srcPeriph)); - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_DMA); - - /* Config channel config */ - BL_WR_REG(DMAChs, DMA_SRCADDR, chCfg->srcDmaAddr); - BL_WR_REG(DMAChs, DMA_DSTADDR, chCfg->destDmaAddr); - - tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, chCfg->transfLength); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SWIDTH, chCfg->srcTransfWidth); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DWIDTH, chCfg->dstTransfWidth); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SBSIZE, chCfg->srcBurstSzie); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DBSIZE, chCfg->dstBurstSzie); - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DST_ADD_MODE, chCfg->dstAddMode); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DST_MIN_MODE, chCfg->dstMinMode); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FIX_CNT, chCfg->fixCnt); - - /* FIXME: how to deal with SLargerD */ - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_SLARGERD); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SI, chCfg->srcAddrInc); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DI, chCfg->destAddrInc); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); - - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FLOWCNTRL, chCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DSTPERIPHERAL, chCfg->dstPeriph); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SRCPERIPHERAL, chCfg->srcPeriph); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + *******************************************************************************/ +void DMA_Channel_Init(DMA_Channel_Cfg_Type *chCfg) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(chCfg->ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(chCfg->ch)); + CHECK_PARAM(IS_DMA_TRANS_WIDTH_TYPE(chCfg->srcTransfWidth)); + CHECK_PARAM(IS_DMA_TRANS_WIDTH_TYPE(chCfg->dstTransfWidth)); + CHECK_PARAM(IS_DMA_BURST_SIZE_TYPE(chCfg->srcBurstSize)); + CHECK_PARAM(IS_DMA_BURST_SIZE_TYPE(chCfg->dstBurstSize)); + CHECK_PARAM(IS_DMA_TRANS_DIR_TYPE(chCfg->dir)); + CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(chCfg->dstPeriph)); + CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(chCfg->srcPeriph)); + + /* Disable clock gate */ + // Turns on clock + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_DMA); + + /* Config channel config */ + BL_WR_REG(DMAChs, DMA_SRCADDR, chCfg->srcDmaAddr); + BL_WR_REG(DMAChs, DMA_DSTADDR, chCfg->destDmaAddr); + + tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, chCfg->transfLength); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SWIDTH, chCfg->srcTransfWidth); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DWIDTH, chCfg->dstTransfWidth); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SBSIZE, chCfg->srcBurstSize); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DBSIZE, chCfg->dstBurstSize); + + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DST_ADD_MODE, chCfg->dstAddMode); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DST_MIN_MODE, chCfg->dstMinMode); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FIX_CNT, chCfg->fixCnt); + + /* FIXME: how to deal with SLargerD */ + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_SLARGERD); // Reserved bit 25 + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SI, chCfg->srcAddrInc); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DI, chCfg->destAddrInc); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); + + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FLOWCNTRL, chCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DSTPERIPHERAL, chCfg->dstPeriph); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SRCPERIPHERAL, chCfg->srcPeriph); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + // Clear interrupts + *((uint32_t *)0x4000c008) = 1 << (chCfg->ch); // Clear transfer complete + *((uint32_t *)0x4000c010) = 1 << (chCfg->ch); // Clear Error } -/****************************************************************************/ /** +/** * @brief DMA channel update source memory address and len * * @param ch: DMA channel @@ -256,24 +256,23 @@ void DMA_Channel_Init(DMA_Channel_Cfg_Type *chCfg) * * @return None * -*******************************************************************************/ -void DMA_Channel_Update_SrcMemcfg(uint8_t ch, uint32_t memAddr, uint32_t len) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - - /* config channel config*/ - BL_WR_REG(DMAChs, DMA_SRCADDR, memAddr); - tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, len); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); + *******************************************************************************/ +void DMA_Channel_Update_SrcMemcfg(uint8_t ch, uint32_t memAddr, uint32_t len) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + + /* config channel config*/ + BL_WR_REG(DMAChs, DMA_SRCADDR, memAddr); + tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, len); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); } -/****************************************************************************/ /** +/** * @brief DMA channel update destination memory address and len * * @param ch: DMA channel @@ -282,106 +281,101 @@ void DMA_Channel_Update_SrcMemcfg(uint8_t ch, uint32_t memAddr, uint32_t len) * * @return None * -*******************************************************************************/ -void DMA_Channel_Update_DstMemcfg(uint8_t ch, uint32_t memAddr, uint32_t len) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - - /* config channel config*/ - BL_WR_REG(DMAChs, DMA_DSTADDR, memAddr); - tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, len); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); + *******************************************************************************/ +void DMA_Channel_Update_DstMemcfg(uint8_t ch, uint32_t memAddr, uint32_t len) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + + /* config channel config*/ + BL_WR_REG(DMAChs, DMA_DSTADDR, memAddr); + tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_TRANSFERSIZE, len); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); } -/****************************************************************************/ /** +/** * @brief Get DMA channel tranfersize * * @param ch: DMA channel * * @return tranfersize size * -*******************************************************************************/ -uint32_t DMA_Channel_TranferSize(uint8_t ch) -{ - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); + *******************************************************************************/ +uint32_t DMA_Channel_TranferSize(uint8_t ch) { + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - return BL_GET_REG_BITS_VAL(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_TRANSFERSIZE); + return BL_GET_REG_BITS_VAL(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_TRANSFERSIZE); } -/****************************************************************************/ /** +/** * @brief Get DMA channel busy status * * @param ch: DMA channel * * @return SET or RESET * -*******************************************************************************/ -BL_Sts_Type DMA_Channel_Is_Busy(uint8_t ch) -{ - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); + *******************************************************************************/ +BL_Sts_Type DMA_Channel_Is_Busy(uint8_t ch) { + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - return BL_IS_REG_BIT_SET(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_E) == 1 ? SET : RESET; + return BL_IS_REG_BIT_SET(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_E) == 1 ? SET : RESET; } -/****************************************************************************/ /** +/** * @brief DMA enable * * @param ch: DMA channel number * * @return None * -*******************************************************************************/ -void DMA_Channel_Enable(uint8_t ch) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); + *******************************************************************************/ +void DMA_Channel_Enable(uint8_t ch) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, DMA_E); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, DMA_E); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); } -/****************************************************************************/ /** +/** * @brief DMA disable * * @param ch: DMA channel number * * @return None * -*******************************************************************************/ -void DMA_Channel_Disable(uint8_t ch) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); + *******************************************************************************/ +void DMA_Channel_Disable(uint8_t ch) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_E); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_E); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); } -/****************************************************************************/ /** +/** * @brief DMA init LLI transfer * * @param ch: DMA channel number @@ -389,30 +383,29 @@ void DMA_Channel_Disable(uint8_t ch) * * @return None * -*******************************************************************************/ -void DMA_LLI_Init(uint8_t ch, DMA_LLI_Cfg_Type *lliCfg) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - CHECK_PARAM(IS_DMA_TRANS_DIR_TYPE(lliCfg->dir)); - CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(lliCfg->dstPeriph)); - CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(lliCfg->srcPeriph)); - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_DMA); - - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FLOWCNTRL, lliCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DSTPERIPHERAL, lliCfg->dstPeriph); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SRCPERIPHERAL, lliCfg->srcPeriph); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + *******************************************************************************/ +void DMA_LLI_Init(uint8_t ch, DMA_LLI_Cfg_Type *lliCfg) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + CHECK_PARAM(IS_DMA_TRANS_DIR_TYPE(lliCfg->dir)); + CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(lliCfg->dstPeriph)); + CHECK_PARAM(IS_DMA_PERIPH_REQ_TYPE(lliCfg->srcPeriph)); + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_DMA); + + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_FLOWCNTRL, lliCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_DSTPERIPHERAL, lliCfg->dstPeriph); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, DMA_SRCPERIPHERAL, lliCfg->srcPeriph); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); } -/****************************************************************************/ /** +/** * @brief DMA channel update LLI * * @param ch: DMA channel number @@ -420,241 +413,98 @@ void DMA_LLI_Init(uint8_t ch, DMA_LLI_Cfg_Type *lliCfg) * * @return None * -*******************************************************************************/ -void DMA_LLI_Update(uint8_t ch, uint32_t LLI) -{ - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - - /* Config channel config */ - //BL_WR_REG(DMAChs, DMA_LLI, LLI); - BL702_MemCpy4((uint32_t *)DMAChs, (uint32_t *)LLI, 4); -} - -/****************************************************************************/ /** - * @brief DMA LLI PingPong Structure Start - * - * @param dmaPpStruct: dma pp struct pointer - * @param Ping_Transfer_len: ping len - * @param Pong_Transfer_len: pong len - * - * @return Succrss or not - * -*******************************************************************************/ -BL_Err_Type DMA_LLI_PpStruct_Set_Transfer_Len(DMA_LLI_PP_Struct *dmaPpStruct, uint16_t Ping_Transfer_len, uint16_t Pong_Transfer_len) -{ - struct DMA_Control_Reg dmaCtrlRegVal_temp; - - if (Ping_Transfer_len > 4096 || Pong_Transfer_len > 4096) { - return ERROR; - } - - dmaCtrlRegVal_temp = PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].dmaCtrl; - dmaCtrlRegVal_temp.TransferSize = Ping_Transfer_len; - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].dmaCtrl = dmaCtrlRegVal_temp; - - dmaCtrlRegVal_temp = PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].dmaCtrl; - dmaCtrlRegVal_temp.TransferSize = Pong_Transfer_len; - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].dmaCtrl = dmaCtrlRegVal_temp; - - DMA_LLI_Init(dmaPpStruct->dmaChan, dmaPpStruct->DMA_LLI_Cfg); - DMA_LLI_Update(dmaPpStruct->dmaChan, (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX]); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief DMA LLI Start New Transmit for Ping-Pong Buf - * - * @param dmaPpBuf: DMA LLI Ping-Pong Buf - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_PpBuf_Start_New_Transmit(DMA_LLI_PP_Buf *dmaPpBuf) -{ - CPU_Interrupt_Disable(DMA_ALL_IRQn); + *******************************************************************************/ +void DMA_LLI_Update(uint8_t ch, uint32_t LLI) { + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); - if (dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex] != NULL) { - DMA_LLI_Update(dmaPpBuf->dmaChan, (uint32_t)dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex]); - DMA_Channel_Enable(dmaPpBuf->dmaChan); - dmaPpBuf->idleIndex = (dmaPpBuf->idleIndex == 0) ? 1 : 0; - } + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - CPU_Interrupt_Enable(DMA_ALL_IRQn); + /* Config channel config */ + // BL_WR_REG(DMAChs, DMA_LLI, LLI); + BL702_MemCpy4((uint32_t *)DMAChs, (uint32_t *)LLI, 4); } -/****************************************************************************/ /** - * @brief DMA LLI Remove Completed Ping-Pong Buf List - * - * @param dmaPpBuf: DMA LLI Ping-Pong Buf - * - * @return Next Ping-Pong Buf List Header - * -*******************************************************************************/ -DMA_LLI_Ctrl_Type *DMA_LLI_PpBuf_Remove_Completed_List(DMA_LLI_PP_Buf *dmaPpBuf) -{ - CPU_Interrupt_Disable(DMA_ALL_IRQn); - - dmaPpBuf->lliListHeader[!dmaPpBuf->idleIndex] = NULL; - CPU_Interrupt_Enable(DMA_ALL_IRQn); - return dmaPpBuf->lliListHeader[!dmaPpBuf->idleIndex]; -} - -/****************************************************************************/ /** - * @brief DMA LLI Append Buf to List +/** + * @brief Mask/Unmask the DMA interrupt * - * @param dmaPpBuf: DMA LLI Ping-Pong Buf - * @param dmaLliList: New LLI Buf to Append + * @param ch: DMA channel number + * @param intType: Specifies the interrupt type + * @param intMask: Enable/Disable Specified interrupt type * * @return None * -*******************************************************************************/ -void DMA_LLI_PpBuf_Append(DMA_LLI_PP_Buf *dmaPpBuf, DMA_LLI_Ctrl_Type *dmaLliList) -{ - DMA_LLI_Ctrl_Type *pLliList = NULL; - CPU_Interrupt_Disable(DMA_ALL_IRQn); - - pLliList = dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex]; - - if (pLliList == NULL) { - dmaLliList->nextLLI = 0; - dmaLliList->dmaCtrl.I = 1; - dmaPpBuf->lliListHeader[dmaPpBuf->idleIndex] = dmaLliList; + *******************************************************************************/ +void DMA_IntMask(uint8_t ch, DMA_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + /* Get channel register */ + uint32_t DMAChs = DMA_Get_Channel(ch); + + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); + CHECK_PARAM(IS_DMA_INT_TYPE(intType)); + + switch (intType) { + case DMA_INT_TCOMPLETED: + if (intMask == UNMASK) { + /* UNMASK(Enable) this interrupt */ + tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_ITC); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_I); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); } else { - /*Append to last */ - while (pLliList->nextLLI != 0) { - pLliList = (DMA_LLI_Ctrl_Type *)pLliList->nextLLI; - } - - pLliList->nextLLI = (uint32_t)dmaLliList; - pLliList->dmaCtrl.I = 0; - dmaLliList->nextLLI = 0; - dmaLliList->dmaCtrl.I = 1; + /* MASK(Disable) this interrupt */ + tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_ITC); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_I); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); } - if (DMA_Channel_Is_Busy(dmaPpBuf->dmaChan) == RESET) { - /* DMA stopped: maybe stop just a few minutes ago(not enter INT due to CPU_Interrupt_Disable) - or has already stopped before this function is called */ - if (dmaPpBuf->lliListHeader[!dmaPpBuf->idleIndex] == NULL) { - /* DMA has already stopped before this function is called */ - DMA_LLI_PpBuf_Start_New_Transmit(dmaPpBuf); - } - } + break; - CPU_Interrupt_Enable(DMA_ALL_IRQn); -} - -/****************************************************************************/ /** - * @brief DMA LLi Destroy Ping-Pong Buf - * - * @param dmaPpBuf: DMA LLI Ping-Pong Buf - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_PpBuf_Destroy(DMA_LLI_PP_Buf *dmaPpBuf) -{ - /* DMA LLI Disable */ - DMA_Channel_Disable(dmaPpBuf->dmaChan); - - if (dmaPpBuf->lliListHeader[0] != NULL && dmaPpBuf->onTransCompleted != NULL) { - dmaPpBuf->onTransCompleted(dmaPpBuf->lliListHeader[0]); + case DMA_INT_ERR: + if (intMask == UNMASK) { + /* UNMASK(Enable) this interrupt */ + tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_IE); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + } else { + /* MASK(Disable) this interrupt */ + tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_IE); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); } - dmaPpBuf->lliListHeader[0] = NULL; - - if (dmaPpBuf->lliListHeader[1] != NULL && dmaPpBuf->onTransCompleted != NULL) { - dmaPpBuf->onTransCompleted(dmaPpBuf->lliListHeader[1]); + break; + + case DMA_INT_ALL: + if (intMask == UNMASK) { + /* UNMASK(Enable) this interrupt */ + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_ITC); + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_IE); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); + tmpVal = BL_SET_REG_BIT(tmpVal, DMA_I); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); + } else { + /* MASK(Disable) this interrupt */ + tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, DMA_ITC); + tmpVal = BL_SET_REG_BIT(tmpVal, DMA_IE); + BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); + tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); + tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_I); + BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); } - dmaPpBuf->lliListHeader[1] = NULL; - dmaPpBuf->idleIndex = 0; -} + break; -/****************************************************************************/ /** - * @brief Mask/Unmask the DMA interrupt - * - * @param ch: DMA channel number - * @param intType: Specifies the interrupt type - * @param intMask: Enable/Disable Specified interrupt type - * - * @return None - * -*******************************************************************************/ -void DMA_IntMask(uint8_t ch, DMA_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - /* Get channel register */ - uint32_t DMAChs = DMA_Get_Channel(ch); - - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(ch)); - CHECK_PARAM(IS_DMA_INT_TYPE(intType)); - - switch (intType) { - case DMA_INT_TCOMPLETED: - if (intMask == UNMASK) { - /* UNMASK(Enable) this interrupt */ - tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_ITC); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_I); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); - } else { - /* MASK(Disable) this interrupt */ - tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_ITC); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONTROL), DMA_I); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); - } - - break; - - case DMA_INT_ERR: - if (intMask == UNMASK) { - /* UNMASK(Enable) this interrupt */ - tmpVal = BL_CLR_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_IE); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - } else { - /* MASK(Disable) this interrupt */ - tmpVal = BL_SET_REG_BIT(BL_RD_REG(DMAChs, DMA_CONFIG), DMA_IE); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - } - - break; - - case DMA_INT_ALL: - if (intMask == UNMASK) { - /* UNMASK(Enable) this interrupt */ - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_ITC); - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_IE); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); - tmpVal = BL_SET_REG_BIT(tmpVal, DMA_I); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); - } else { - /* MASK(Disable) this interrupt */ - tmpVal = BL_RD_REG(DMAChs, DMA_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, DMA_ITC); - tmpVal = BL_SET_REG_BIT(tmpVal, DMA_IE); - BL_WR_REG(DMAChs, DMA_CONFIG, tmpVal); - tmpVal = BL_RD_REG(DMAChs, DMA_CONTROL); - tmpVal = BL_CLR_REG_BIT(tmpVal, DMA_I); - BL_WR_REG(DMAChs, DMA_CONTROL, tmpVal); - } - - break; - - default: - break; - } + default: + break; + } } -/****************************************************************************/ /** +/** * @brief Install DMA interrupt callback function * * @param dmaChan: DMA Channel type @@ -663,84 +513,13 @@ void DMA_IntMask(uint8_t ch, DMA_INT_Type intType, BL_Mask_Type intMask) * * @return None * -*******************************************************************************/ -void DMA_Int_Callback_Install(DMA_Chan_Type dmaChan, DMA_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_DMA_CHAN_TYPE(dmaChan)); - CHECK_PARAM(IS_DMA_INT_TYPE(intType)); - - dmaIntCbfArra[dmaChan][intType] = cbFun; -} - -/****************************************************************************/ /** - * @brief DMA LLI PingPong Structure Initial - * - * @param dmaPpStruct: DMA LLI PingPong Config Parameter - * - * @return start success or not - * -*******************************************************************************/ -BL_Err_Type DMA_LLI_PpStruct_Init(DMA_LLI_PP_Struct *dmaPpStruct) -{ - //setup lliList - dmaPpStruct->dmaCtrlRegVal.I = 1; - dmaPpStruct->trans_index = 0; - - if (dmaPpStruct->DMA_LLI_Cfg->dir == DMA_TRNS_M2P) { - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].srcDmaAddr = dmaPpStruct->chache_buf_addr[0]; - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].destDmaAddr = dmaPpStruct->operatePeriphAddr; - - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].srcDmaAddr = dmaPpStruct->chache_buf_addr[1]; - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].destDmaAddr = dmaPpStruct->operatePeriphAddr; - } else if (dmaPpStruct->DMA_LLI_Cfg->dir == DMA_TRNS_P2M) { - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].srcDmaAddr = dmaPpStruct->operatePeriphAddr; - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].destDmaAddr = dmaPpStruct->chache_buf_addr[0]; - - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].srcDmaAddr = dmaPpStruct->operatePeriphAddr; - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].destDmaAddr = dmaPpStruct->chache_buf_addr[1]; - } else { - return ERROR; - /*V1.0 version DMA LLI Ping-Pong structure not support P2P & M2M MODE*/ - } - - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].nextLLI = (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX]; - PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX].dmaCtrl = dmaPpStruct->dmaCtrlRegVal; - - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].nextLLI = (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX]; - PingPongListArra[dmaPpStruct->dmaChan][PONG_INDEX].dmaCtrl = dmaPpStruct->dmaCtrlRegVal; - - DMA_LLI_Init(dmaPpStruct->dmaChan, dmaPpStruct->DMA_LLI_Cfg); - - DMA_LLI_Update(dmaPpStruct->dmaChan, (uint32_t)&PingPongListArra[dmaPpStruct->dmaChan][PING_INDEX]); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief DMA LLI PingPong Structure Start - * - * @param dmaPpStruct: None - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_PpStruct_Start(DMA_LLI_PP_Struct *dmaPpStruct) -{ - DMA_Channel_Enable(dmaPpStruct->dmaChan); -} + *******************************************************************************/ +void DMA_Int_Callback_Install(DMA_Chan_Type dmaChan, DMA_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_DMA_CHAN_TYPE(dmaChan)); + CHECK_PARAM(IS_DMA_INT_TYPE(intType)); -/****************************************************************************/ /** - * @brief DMA LLI PingPong Structure Stop - * - * @param dmaPpStruct: None - * - * @return None - * -*******************************************************************************/ -void DMA_LLI_PpStruct_Stop(DMA_LLI_PP_Struct *dmaPpStruct) -{ - DMA_Channel_Disable(dmaPpStruct->dmaChan); + dmaIntCbfArra[dmaChan][intType] = cbFun; } /*@} end of group DMA_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ef_ctrl.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ef_ctrl.c index 01d991739..2db7810d4 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ef_ctrl.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ef_ctrl.c @@ -111,9 +111,9 @@ __WEAK } } - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_SAHB_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_SAHB_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); } @@ -131,24 +131,24 @@ static void EF_Ctrl_Program_Efuse_0(void) { uint32_t tmpVal; /* Select auto mode and select ef clock */ - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); /* Program */ - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (1 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (1 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (1 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (1 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); /* Add delay for POR to be stable */ BL702_Delay_US(4); /* Trigger */ - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (1 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (1 << EF_CTRL_EF_IF_0_RW_POS) | (1 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (1 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (1 << EF_CTRL_EF_IF_0_RW_POS) | (1 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); } @@ -175,14 +175,14 @@ void ATTR_TCM_SECTION EF_Ctrl_Load_Efuse_R0(void) { EF_CTRL_DATA0_CLEAR; /* Trigger read */ - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (0 << EF_CTRL_EF_IF_0_RW_POS) | (1 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_EF_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (0 << EF_CTRL_EF_IF_0_RW_POS) | (1 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); BL702_Delay_US(10); @@ -200,9 +200,9 @@ void ATTR_TCM_SECTION EF_Ctrl_Load_Efuse_R0(void) { (!BL_IS_REG_BIT_SET(tmpVal, EF_CTRL_EF_IF_0_AUTOLOAD_DONE))); /* Switch to AHB clock */ - tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) - | (EF_CTRL_SAHB_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) - | (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); + tmpVal = (EF_CTRL_EFUSE_CTRL_PROTECT) | (EF_CTRL_OP_MODE_AUTO << EF_CTRL_EF_IF_0_MANUAL_EN_POS) | (EF_CTRL_PARA_DFT << EF_CTRL_EF_IF_0_CYC_MODIFY_POS) | + (EF_CTRL_SAHB_CLK << EF_CTRL_EF_CLK_SAHB_DATA_SEL_POS) | (1 << EF_CTRL_EF_IF_AUTO_RD_EN_POS) | (0 << EF_CTRL_EF_IF_POR_DIG_POS) | (1 << EF_CTRL_EF_IF_0_INT_CLR_POS) | + (0 << EF_CTRL_EF_IF_0_RW_POS) | (0 << EF_CTRL_EF_IF_0_TRIG_POS); BL_WR_REG(EF_CTRL_BASE, EF_CTRL_EF_IF_CTRL_0, tmpVal); } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_emac.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_emac.c index 662ac3091..5e9e5c043 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_emac.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_emac.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_emac.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_emac.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702.h" #include "bl702_emac.h" +#include "bl702.h" #include "bl702_glb.h" /** @addtogroup BL702_Peripheral_Driver @@ -62,7 +62,7 @@ /** @defgroup EMAC_Private_Variables * @{ */ -static intCallback_Type *emacIntCbfArra[EMAC_INT_CNT] = { NULL }; +static intCallback_Type *emacIntCbfArra[EMAC_INT_CNT] = {NULL}; /*@} end of group EMAC_Private_Variables */ @@ -83,123 +83,118 @@ static intCallback_Type *emacIntCbfArra[EMAC_INT_CNT] = { NULL }; */ /****************************************************************************/ /** - * @brief Set MAC Address - * - * @param macAddr[6]: MAC address buffer array - * - * @return None - * -*******************************************************************************/ -static void EMAC_SetMACAddress(uint8_t macAddr[6]) -{ - BL_WR_REG(EMAC_BASE, EMAC_MAC_ADDR1, (macAddr[0] << 8) | macAddr[1]); - BL_WR_REG(EMAC_BASE, EMAC_MAC_ADDR0, (macAddr[2] << 24) | (macAddr[3] << 16) | (macAddr[4] << 8) | (macAddr[5] << 0)); + * @brief Set MAC Address + * + * @param macAddr[6]: MAC address buffer array + * + * @return None + * + *******************************************************************************/ +static void EMAC_SetMACAddress(uint8_t macAddr[6]) { + BL_WR_REG(EMAC_BASE, EMAC_MAC_ADDR1, (macAddr[0] << 8) | macAddr[1]); + BL_WR_REG(EMAC_BASE, EMAC_MAC_ADDR0, (macAddr[2] << 24) | (macAddr[3] << 16) | (macAddr[4] << 8) | (macAddr[5] << 0)); } /****************************************************************************/ /** - * @brief Set PHY Address - * - * @param phyAddress: Phy address - * - * @return None - * -*******************************************************************************/ -void EMAC_Phy_SetAddress(uint16_t phyAddress) -{ - uint32_t tmpVal; - - /* Set Phy Address */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_FIAD, phyAddress); - BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); + * @brief Set PHY Address + * + * @param phyAddress: Phy address + * + * @return None + * + *******************************************************************************/ +void EMAC_Phy_SetAddress(uint16_t phyAddress) { + uint32_t tmpVal; + + /* Set Phy Address */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_FIAD, phyAddress); + BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); } /****************************************************************************/ /** - * @brief Set PHY Address - * - * @param phyAddress: Phy address - * - * @return None - * -*******************************************************************************/ -void EMAC_Phy_Set_Full_Duplex(uint8_t fullDuplex) -{ - uint32_t tmpVal; - - /* Set MAC duplex config */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_FULLD, fullDuplex); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + * @brief Set PHY Address + * + * @param phyAddress: Phy address + * + * @return None + * + *******************************************************************************/ +void EMAC_Phy_Set_Full_Duplex(uint8_t fullDuplex) { + uint32_t tmpVal; + + /* Set MAC duplex config */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_FULLD, fullDuplex); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); } /****************************************************************************/ /** - * @brief Read PHY register - * - * @param phyReg: PHY register - * @param regValue: PHY register value pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Phy_Read(uint16_t phyReg, uint16_t *regValue) -{ - uint32_t tmpVal; - - /* Set Register Address */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RGAD, phyReg); - BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); - - /* Trigger read */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIICOMMAND); - tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_RSTAT); - BL_WR_REG(EMAC_BASE, EMAC_MIICOMMAND, tmpVal); - - BL_DRV_DUMMY; - - do { - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIISTATUS); - BL702_Delay_US(16); - } while (BL_IS_REG_BIT_SET(tmpVal, EMAC_MIIM_BUSY)); - - *regValue = BL_RD_REG(EMAC_BASE, EMAC_MIIRX_DATA); - - return SUCCESS; + * @brief Read PHY register + * + * @param phyReg: PHY register + * @param regValue: PHY register value pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Phy_Read(uint16_t phyReg, uint16_t *regValue) { + uint32_t tmpVal; + + /* Set Register Address */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RGAD, phyReg); + BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); + + /* Trigger read */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIICOMMAND); + tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_RSTAT); + BL_WR_REG(EMAC_BASE, EMAC_MIICOMMAND, tmpVal); + + BL_DRV_DUMMY; + + do { + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIISTATUS); + BL702_Delay_US(16); + } while (BL_IS_REG_BIT_SET(tmpVal, EMAC_MIIM_BUSY)); + + *regValue = BL_RD_REG(EMAC_BASE, EMAC_MIIRX_DATA); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Write PHY register - * - * @param phyReg: PHY register - * @param regValue: PHY register value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Phy_Write(uint16_t phyReg, uint16_t regValue) -{ - uint32_t tmpVal; - - /* Set Register Address */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RGAD, phyReg); - BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); - - /* Set Write data */ - BL_WR_REG(EMAC_BASE, EMAC_MIITX_DATA, regValue); - - /* Trigger write */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIICOMMAND); - tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_WCTRLDATA); - BL_WR_REG(EMAC_BASE, EMAC_MIICOMMAND, tmpVal); - - BL_DRV_DUMMY; - - do { - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIISTATUS); - } while (BL_IS_REG_BIT_SET(tmpVal, EMAC_MIIM_BUSY)); - - return SUCCESS; + * @brief Write PHY register + * + * @param phyReg: PHY register + * @param regValue: PHY register value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Phy_Write(uint16_t phyReg, uint16_t regValue) { + uint32_t tmpVal; + + /* Set Register Address */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIADDRESS); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RGAD, phyReg); + BL_WR_REG(EMAC_BASE, EMAC_MIIADDRESS, tmpVal); + + /* Set Write data */ + BL_WR_REG(EMAC_BASE, EMAC_MIITX_DATA, regValue); + + /* Trigger write */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIICOMMAND); + tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_WCTRLDATA); + BL_WR_REG(EMAC_BASE, EMAC_MIICOMMAND, tmpVal); + + BL_DRV_DUMMY; + + do { + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIISTATUS); + } while (BL_IS_REG_BIT_SET(tmpVal, EMAC_MIIM_BUSY)); + + return SUCCESS; } /*@} end of group EMAC_Private_Functions */ @@ -209,475 +204,451 @@ BL_Err_Type EMAC_Phy_Write(uint16_t phyReg, uint16_t regValue) */ /****************************************************************************/ /** - * @brief Initialize EMAC module - * - * @param cfg: EMAC configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Init(EMAC_CFG_Type *cfg) -{ - uint32_t tmpVal; - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_EMAC); - - /* Set MAC config */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RMII_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RECSMALL, cfg->recvSmallFrame); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_PAD, cfg->padEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_HUGEN, cfg->recvHugeFrame); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_CRCEN, cfg->crcEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_NOPRE, cfg->noPreamble); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_BRO, cfg->recvBroadCast); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_PRO, ENABLE); - //tmpVal |= (1 << 7); /* local loopback in emac */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_IFG, cfg->interFrameGapCheck); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); - - /* Set inter frame gap value */ - BL_WR_REG(EMAC_BASE, EMAC_IPGT, cfg->interFrameGapValue); - - /* Set MII interface */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIMODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MIINOPRE, cfg->miiNoPreamble); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_CLKDIV, cfg->miiClkDiv); - BL_WR_REG(EMAC_BASE, EMAC_MIIMODE, tmpVal); - - /* Set collision */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_COLLCONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MAXRET, cfg->maxTxRetry); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_COLLVALID, cfg->collisionValid); - BL_WR_REG(EMAC_BASE, EMAC_COLLCONFIG, tmpVal); - - /* Set frame length */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_PACKETLEN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MINFL, cfg->minFrameLen); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MAXFL, cfg->maxFrameLen); - BL_WR_REG(EMAC_BASE, EMAC_PACKETLEN, tmpVal); - - EMAC_SetMACAddress(cfg->macAddr); - - void EMAC_IRQHandler(void); - Interrupt_Handler_Register(EMAC_IRQn, EMAC_IRQHandler); - - return SUCCESS; + * @brief Initialize EMAC module + * + * @param cfg: EMAC configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Init(EMAC_CFG_Type *cfg) { + uint32_t tmpVal; + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_EMAC); + + /* Set MAC config */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RMII_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_RECSMALL, cfg->recvSmallFrame); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_PAD, cfg->padEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_HUGEN, cfg->recvHugeFrame); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_CRCEN, cfg->crcEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_NOPRE, cfg->noPreamble); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_BRO, cfg->recvBroadCast); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_PRO, ENABLE); + // tmpVal |= (1 << 7); /* local loopback in emac */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_IFG, cfg->interFrameGapCheck); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + + /* Set inter frame gap value */ + BL_WR_REG(EMAC_BASE, EMAC_IPGT, cfg->interFrameGapValue); + + /* Set MII interface */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MIIMODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MIINOPRE, cfg->miiNoPreamble); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_CLKDIV, cfg->miiClkDiv); + BL_WR_REG(EMAC_BASE, EMAC_MIIMODE, tmpVal); + + /* Set collision */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_COLLCONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MAXRET, cfg->maxTxRetry); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_COLLVALID, cfg->collisionValid); + BL_WR_REG(EMAC_BASE, EMAC_COLLCONFIG, tmpVal); + + /* Set frame length */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_PACKETLEN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MINFL, cfg->minFrameLen); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, EMAC_MAXFL, cfg->maxFrameLen); + BL_WR_REG(EMAC_BASE, EMAC_PACKETLEN, tmpVal); + + EMAC_SetMACAddress(cfg->macAddr); + + void EMAC_IRQHandler(void); + Interrupt_Handler_Register(EMAC_IRQn, EMAC_IRQHandler); + + return SUCCESS; } /****************************************************************************/ /** - * @brief DeInitialize EMAC module - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_DeInit(void) -{ - EMAC_Disable(); - - return SUCCESS; + * @brief DeInitialize EMAC module + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_DeInit(void) { + EMAC_Disable(); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Initialize EMAC TX RX MDA buffer - * - * @param handle: EMAC handle pointer - * @param txBuff: TX buffer - * @param txBuffCount: TX buffer count - * @param rxBuff: RX buffer - * @param rxBuffCount: RX buffer count - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_DMADescListInit(EMAC_Handle_Type *handle, uint8_t *txBuff, uint32_t txBuffCount, uint8_t *rxBuff, uint32_t rxBuffCount) -{ - uint32_t i = 0; - - /* Set the Ethernet handler env */ - handle->bd = (EMAC_BD_Desc_Type *)(EMAC_BASE + EMAC_DMA_DESC_OFFSET); - handle->txIndexEMAC = 0; - handle->txIndexCPU = 0; - handle->txBuffLimit = txBuffCount - 1; - /* The receive descriptors' address starts right after the last transmit BD. */ - handle->rxIndexEMAC = txBuffCount; - handle->rxIndexCPU = txBuffCount; - handle->rxBuffLimit = txBuffCount + rxBuffCount - 1; - - /* Fill each DMARxDesc descriptor with the right values */ - for (i = 0; i < txBuffCount; i++) { - /* Get the pointer on the ith member of the Tx Desc list */ - handle->bd[i].Buffer = (NULL == txBuff) ? 0 : (uint32_t)(txBuff + (ETH_MAX_PACKET_SIZE * i)); - handle->bd[i].C_S_L = 0; - } - - /* For the last TX DMA Descriptor, it should be wrap back */ - handle->bd[handle->txBuffLimit].C_S_L |= EMAC_BD_FIELD_MSK(TX_WR); - - for (i = txBuffCount; i < (txBuffCount + rxBuffCount); i++) { - /* Get the pointer on the ith member of the Rx Desc list */ - handle->bd[i].Buffer = (NULL == rxBuff) ? 0 : (uint32_t)(rxBuff + (ETH_MAX_PACKET_SIZE * (i - txBuffCount))); - handle->bd[i].C_S_L = (ETH_MAX_PACKET_SIZE << 16) | - EMAC_BD_FIELD_MSK(RX_IRQ) | - EMAC_BD_FIELD_MSK(RX_E); - } - - /* For the last RX DMA Descriptor, it should be wrap back */ - handle->bd[handle->rxBuffLimit].C_S_L |= EMAC_BD_FIELD_MSK(RX_WR); - - /* For the TX DMA Descriptor, it will wrap to 0 according to EMAC_TX_BD_NUM*/ - BL_WR_REG(EMAC_BASE, EMAC_TX_BD_NUM, txBuffCount); - - return SUCCESS; + * @brief Initialize EMAC TX RX MDA buffer + * + * @param handle: EMAC handle pointer + * @param txBuff: TX buffer + * @param txBuffCount: TX buffer count + * @param rxBuff: RX buffer + * @param rxBuffCount: RX buffer count + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_DMADescListInit(EMAC_Handle_Type *handle, uint8_t *txBuff, uint32_t txBuffCount, uint8_t *rxBuff, uint32_t rxBuffCount) { + uint32_t i = 0; + + /* Set the Ethernet handler env */ + handle->bd = (EMAC_BD_Desc_Type *)(EMAC_BASE + EMAC_DMA_DESC_OFFSET); + handle->txIndexEMAC = 0; + handle->txIndexCPU = 0; + handle->txBuffLimit = txBuffCount - 1; + /* The receive descriptors' address starts right after the last transmit BD. */ + handle->rxIndexEMAC = txBuffCount; + handle->rxIndexCPU = txBuffCount; + handle->rxBuffLimit = txBuffCount + rxBuffCount - 1; + + /* Fill each DMARxDesc descriptor with the right values */ + for (i = 0; i < txBuffCount; i++) { + /* Get the pointer on the ith member of the Tx Desc list */ + handle->bd[i].Buffer = (NULL == txBuff) ? 0 : (uint32_t)(txBuff + (ETH_MAX_PACKET_SIZE * i)); + handle->bd[i].C_S_L = 0; + } + + /* For the last TX DMA Descriptor, it should be wrap back */ + handle->bd[handle->txBuffLimit].C_S_L |= EMAC_BD_FIELD_MSK(TX_WR); + + for (i = txBuffCount; i < (txBuffCount + rxBuffCount); i++) { + /* Get the pointer on the ith member of the Rx Desc list */ + handle->bd[i].Buffer = (NULL == rxBuff) ? 0 : (uint32_t)(rxBuff + (ETH_MAX_PACKET_SIZE * (i - txBuffCount))); + handle->bd[i].C_S_L = (ETH_MAX_PACKET_SIZE << 16) | EMAC_BD_FIELD_MSK(RX_IRQ) | EMAC_BD_FIELD_MSK(RX_E); + } + + /* For the last RX DMA Descriptor, it should be wrap back */ + handle->bd[handle->rxBuffLimit].C_S_L |= EMAC_BD_FIELD_MSK(RX_WR); + + /* For the TX DMA Descriptor, it will wrap to 0 according to EMAC_TX_BD_NUM*/ + BL_WR_REG(EMAC_BASE, EMAC_TX_BD_NUM, txBuffCount); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Get TX MDA buffer descripter for data to send - * - * @param handle: EMAC handle pointer - * @param txDMADesc: TX DMA descriptor pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_DMATxDescGet(EMAC_Handle_Type *handle, EMAC_BD_Desc_Type **txDMADesc) -{ - return SUCCESS; -} + * @brief Get TX MDA buffer descripter for data to send + * + * @param handle: EMAC handle pointer + * @param txDMADesc: TX DMA descriptor pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_DMATxDescGet(EMAC_Handle_Type *handle, EMAC_BD_Desc_Type **txDMADesc) { return SUCCESS; } /****************************************************************************/ /** - * @brief Start TX - * - * @param handle: EMAC handle pointer - * @param txDMADesc: TX DMA descriptor pointer - * @param len: len - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_StartTx(EMAC_Handle_Type *handle, EMAC_BD_Desc_Type *txDMADesc, uint32_t len) -{ - return SUCCESS; -} + * @brief Start TX + * + * @param handle: EMAC handle pointer + * @param txDMADesc: TX DMA descriptor pointer + * @param len: len + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_StartTx(EMAC_Handle_Type *handle, EMAC_BD_Desc_Type *txDMADesc, uint32_t len) { return SUCCESS; } /****************************************************************************/ /** - * @brief Enable EMAC module - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Enable(void) -{ - uint32_t tmpVal; - - /* Enable EMAC */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_TXEN); - tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_RXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); - - return SUCCESS; + * @brief Enable EMAC module + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Enable(void) { + uint32_t tmpVal; + + /* Enable EMAC */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_TXEN); + tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_RXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_Enable_TX - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Enable_TX(void) -{ - uint32_t tmpVal; - - /* Enable EMAC */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_TXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); - - return SUCCESS; + * @brief EMAC_Enable_TX + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Enable_TX(void) { + uint32_t tmpVal; + + /* Enable EMAC */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_SET_REG_BIT(tmpVal, EMAC_TXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_Disable_TX - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Disable_TX(void) -{ - uint32_t tmpVal; - - /* Enable EMAC */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_TXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); - - return SUCCESS; + * @brief EMAC_Disable_TX + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Disable_TX(void) { + uint32_t tmpVal; + + /* Enable EMAC */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_TXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_Enable_RX - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Enable_RX(void) -{ - uint32_t tmpval; - - /* Enable EMAC TX*/ - tmpval = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpval = BL_SET_REG_BIT(tmpval, EMAC_RXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpval); - - return SUCCESS; + * @brief EMAC_Enable_RX + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Enable_RX(void) { + uint32_t tmpval; + + /* Enable EMAC TX*/ + tmpval = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpval = BL_SET_REG_BIT(tmpval, EMAC_RXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpval); + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_Disable_RX - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Disable_RX(void) -{ - uint32_t tmpval; - - /* Disable EMAC RX*/ - tmpval = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpval = BL_CLR_REG_BIT(tmpval, EMAC_RXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpval); - - return SUCCESS; + * @brief EMAC_Disable_RX + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Disable_RX(void) { + uint32_t tmpval; + + /* Disable EMAC RX*/ + tmpval = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpval = BL_CLR_REG_BIT(tmpval, EMAC_RXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpval); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable EMAC module - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_Disable(void) -{ - uint32_t tmpVal; - - /* Enable EMAC */ - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_TXEN); - tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_RXEN); - BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); - - return SUCCESS; + * @brief Disable EMAC module + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_Disable(void) { + uint32_t tmpVal; + + /* Enable EMAC */ + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_TXEN); + tmpVal = BL_CLR_REG_BIT(tmpVal, EMAC_RXEN); + BL_WR_REG(EMAC_BASE, EMAC_MODE, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC mask or unmask certain or all interrupt - * - * @param intType: EMAC interrupt type - * @param intMask: EMAC interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_IntMask(EMAC_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_MASK); - - /* Mask or unmask certain or all interrupt */ - if (MASK == intMask) { - tmpVal |= intType; - } else { - tmpVal &= (~intType); - } - - /* Write back */ - BL_WR_REG(EMAC_BASE, EMAC_INT_MASK, tmpVal); - - return SUCCESS; + * @brief EMAC mask or unmask certain or all interrupt + * + * @param intType: EMAC interrupt type + * @param intMask: EMAC interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_IntMask(EMAC_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_MASK); + + /* Mask or unmask certain or all interrupt */ + if (MASK == intMask) { + tmpVal |= intType; + } else { + tmpVal &= (~intType); + } + + /* Write back */ + BL_WR_REG(EMAC_BASE, EMAC_INT_MASK, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Get EMAC interrupt status - * - * @param intType: EMAC interrupt type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Sts_Type EMAC_GetIntStatus(EMAC_INT_Type intType) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_EMAC_INT_TYPE(intType)); - - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_SOURCE); - - return (tmpVal & intType) ? SET : RESET; + * @brief Get EMAC interrupt status + * + * @param intType: EMAC interrupt type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Sts_Type EMAC_GetIntStatus(EMAC_INT_Type intType) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_EMAC_INT_TYPE(intType)); + + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_SOURCE); + + return (tmpVal & intType) ? SET : RESET; } /****************************************************************************/ /** - * @brief Clear EMAC interrupt - * - * @param intType: EMAC interrupt type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_ClrIntStatus(EMAC_INT_Type intType) -{ - uint32_t tmpVal; + * @brief Clear EMAC interrupt + * + * @param intType: EMAC interrupt type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_ClrIntStatus(EMAC_INT_Type intType) { + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_EMAC_INT_TYPE(intType)); + /* Check the parameters */ + CHECK_PARAM(IS_EMAC_INT_TYPE(intType)); - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_SOURCE); + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_SOURCE); - BL_WR_REG(EMAC_BASE, EMAC_INT_SOURCE, tmpVal | intType); + BL_WR_REG(EMAC_BASE, EMAC_INT_SOURCE, tmpVal | intType); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_Int_Callback_Install - * - * @param intIdx: EMAC_INT_Index - * @param cbFun: call back - * - * @return None - * -*******************************************************************************/ -BL_Err_Type EMAC_Int_Callback_Install(EMAC_INT_Index intIdx, intCallback_Type *cbFun) -{ - /* Check the parameters */ - - emacIntCbfArra[intIdx] = cbFun; - - return SUCCESS; + * @brief EMAC_Int_Callback_Install + * + * @param intIdx: EMAC_INT_Index + * @param cbFun: call back + * + * @return None + * + *******************************************************************************/ +BL_Err_Type EMAC_Int_Callback_Install(EMAC_INT_Index intIdx, intCallback_Type *cbFun) { + /* Check the parameters */ + + emacIntCbfArra[intIdx] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief EMAC_IRQHandler - * - * @param None - * - * @return None - * -*******************************************************************************/ -void EMAC_IRQHandler(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_MASK); - - if (SET == EMAC_GetIntStatus(EMAC_INT_TX_DONE) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXB_M)) { - EMAC_ClrIntStatus(EMAC_INT_TX_DONE); - - if (emacIntCbfArra[EMAC_INT_TX_DONE_IDX]) { - emacIntCbfArra[EMAC_INT_TX_DONE_IDX](); - } + * @brief EMAC_IRQHandler + * + * @param None + * + * @return None + * + *******************************************************************************/ +void EMAC_IRQHandler(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(EMAC_BASE, EMAC_INT_MASK); + + if (SET == EMAC_GetIntStatus(EMAC_INT_TX_DONE) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXB_M)) { + EMAC_ClrIntStatus(EMAC_INT_TX_DONE); + + if (emacIntCbfArra[EMAC_INT_TX_DONE_IDX]) { + emacIntCbfArra[EMAC_INT_TX_DONE_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_TX_ERROR) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXE_M)) { - EMAC_ClrIntStatus(EMAC_INT_TX_ERROR); + if (SET == EMAC_GetIntStatus(EMAC_INT_TX_ERROR) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXE_M)) { + EMAC_ClrIntStatus(EMAC_INT_TX_ERROR); - if (emacIntCbfArra[EMAC_INT_TX_ERROR_IDX]) { - emacIntCbfArra[EMAC_INT_TX_ERROR_IDX](); - } + if (emacIntCbfArra[EMAC_INT_TX_ERROR_IDX]) { + emacIntCbfArra[EMAC_INT_TX_ERROR_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_RX_DONE) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXB_M)) { - EMAC_ClrIntStatus(EMAC_INT_RX_DONE); + if (SET == EMAC_GetIntStatus(EMAC_INT_RX_DONE) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXB_M)) { + EMAC_ClrIntStatus(EMAC_INT_RX_DONE); - if (emacIntCbfArra[EMAC_INT_RX_DONE_IDX]) { - emacIntCbfArra[EMAC_INT_RX_DONE_IDX](); - } + if (emacIntCbfArra[EMAC_INT_RX_DONE_IDX]) { + emacIntCbfArra[EMAC_INT_RX_DONE_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_RX_ERROR) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXE_M)) { - EMAC_ClrIntStatus(EMAC_INT_RX_ERROR); + if (SET == EMAC_GetIntStatus(EMAC_INT_RX_ERROR) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXE_M)) { + EMAC_ClrIntStatus(EMAC_INT_RX_ERROR); - if (emacIntCbfArra[EMAC_INT_RX_ERROR_IDX]) { - emacIntCbfArra[EMAC_INT_RX_ERROR_IDX](); - } + if (emacIntCbfArra[EMAC_INT_RX_ERROR_IDX]) { + emacIntCbfArra[EMAC_INT_RX_ERROR_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_RX_BUSY) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_BUSY_M)) { - EMAC_ClrIntStatus(EMAC_INT_RX_BUSY); + if (SET == EMAC_GetIntStatus(EMAC_INT_RX_BUSY) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_BUSY_M)) { + EMAC_ClrIntStatus(EMAC_INT_RX_BUSY); - if (emacIntCbfArra[EMAC_INT_RX_BUSY_IDX]) { - emacIntCbfArra[EMAC_INT_RX_BUSY_IDX](); - } + if (emacIntCbfArra[EMAC_INT_RX_BUSY_IDX]) { + emacIntCbfArra[EMAC_INT_RX_BUSY_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_TX_CTRL) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXC_M)) { - EMAC_ClrIntStatus(EMAC_INT_TX_CTRL); + if (SET == EMAC_GetIntStatus(EMAC_INT_TX_CTRL) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_TXC_M)) { + EMAC_ClrIntStatus(EMAC_INT_TX_CTRL); - if (emacIntCbfArra[EMAC_INT_TX_CTRL_IDX]) { - emacIntCbfArra[EMAC_INT_TX_CTRL_IDX](); - } + if (emacIntCbfArra[EMAC_INT_TX_CTRL_IDX]) { + emacIntCbfArra[EMAC_INT_TX_CTRL_IDX](); } + } - if (SET == EMAC_GetIntStatus(EMAC_INT_RX_CTRL) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXC_M)) { - EMAC_ClrIntStatus(EMAC_INT_RX_CTRL); + if (SET == EMAC_GetIntStatus(EMAC_INT_RX_CTRL) && !BL_IS_REG_BIT_SET(tmpVal, EMAC_RXC_M)) { + EMAC_ClrIntStatus(EMAC_INT_RX_CTRL); - if (emacIntCbfArra[EMAC_INT_RX_CTRL_IDX]) { - emacIntCbfArra[EMAC_INT_RX_CTRL_IDX](); - } + if (emacIntCbfArra[EMAC_INT_RX_CTRL_IDX]) { + emacIntCbfArra[EMAC_INT_RX_CTRL_IDX](); } + } } /****************************************************************************/ /** - * @brief Request to pause TX - * - * @param timeCount: Pause time count - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_TxPauseReq(uint16_t timeCount) -{ - BL_WR_REG(EMAC_BASE, EMAC_TXCTRL, (1 << 16) | timeCount); - - return SUCCESS; + * @brief Request to pause TX + * + * @param timeCount: Pause time count + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_TxPauseReq(uint16_t timeCount) { + BL_WR_REG(EMAC_BASE, EMAC_TXCTRL, (1 << 16) | timeCount); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Set hash value - * - * @param hash0: Hash value one - * @param hash1: Hash value two - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type EMAC_SetHash(uint32_t hash0, uint32_t hash1) -{ - BL_WR_REG(EMAC_BASE, EMAC_HASH0_ADDR, hash0); - - BL_WR_REG(EMAC_BASE, EMAC_HASH1_ADDR, hash1); - - return SUCCESS; + * @brief Set hash value + * + * @param hash0: Hash value one + * @param hash1: Hash value two + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type EMAC_SetHash(uint32_t hash0, uint32_t hash1) { + BL_WR_REG(EMAC_BASE, EMAC_HASH0_ADDR, hash0); + + BL_WR_REG(EMAC_BASE, EMAC_HASH1_ADDR, hash1); + + return SUCCESS; } /*@} end of group EMAC_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c index 97c6d7697..7499cbf13 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_glb.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_glb.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_glb.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_glb.h" #include "bl702_hbn.h" @@ -48,17 +48,17 @@ /** @defgroup GLB_Private_Macros * @{ */ -#define GLB_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - } +#define GLB_CLK_SET_DUMMY_WAIT \ + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + } #define GLB_GPIO_Get_Reg(pin) (glb_gpio_reg_t *)(GLB_BASE + GLB_GPIO_OFFSET + (pin / 2) * 4) #define GLB_GPIO_INT0_NUM (32) #define GLB_REG_BCLK_DIS_TRUE (*(volatile uint32_t *)(0x40000FFC) = (0x00000001)) @@ -76,16 +76,12 @@ /** @defgroup GLB_Private_Variables * @{ */ -static intCallback_Type *glbBmxErrIntCbfArra[BMX_ERR_INT_ALL] = { NULL }; -static intCallback_Type *glbBmxToIntCbfArra[BMX_TO_INT_ALL] = { NULL }; -static intCallback_Type *glbGpioInt0CbfArra[GLB_GPIO_INT0_NUM] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; -static intCallback_Type *glbGpioInt0CbfArra2[GLB_GPIO_INT0_NUM] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; +static intCallback_Type *glbBmxErrIntCbfArra[BMX_ERR_INT_ALL] = {NULL}; +static intCallback_Type *glbBmxToIntCbfArra[BMX_TO_INT_ALL] = {NULL}; +static intCallback_Type *glbGpioInt0CbfArra[GLB_GPIO_INT0_NUM] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; +static intCallback_Type *glbGpioInt0CbfArra2[GLB_GPIO_INT0_NUM] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; /*@} end of group GLB_Private_Variables */ @@ -112,3922 +108,3788 @@ static intCallback_Type *glbGpioInt0CbfArra2[GLB_GPIO_INT0_NUM] = { NULL, NULL, */ /****************************************************************************/ /** - * @brief get root clock selection - * - * @param None - * - * @return root clock selection - * -*******************************************************************************/ + * @brief get root clock selection + * + * @param None + * + * @return root clock selection + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -GLB_ROOT_CLK_Type ATTR_CLOCK_SECTION GLB_Get_Root_CLK_Sel(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - - switch (BL_GET_REG_BITS_VAL(tmpVal, GLB_HBN_ROOT_CLK_SEL)) { - case 0: - return GLB_ROOT_CLK_RC32M; - case 1: - return GLB_ROOT_CLK_XTAL; - case 2: - case 3: - return GLB_ROOT_CLK_DLL; - default: - return GLB_ROOT_CLK_RC32M; - } +GLB_ROOT_CLK_Type ATTR_CLOCK_SECTION GLB_Get_Root_CLK_Sel(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + + switch (BL_GET_REG_BITS_VAL(tmpVal, GLB_HBN_ROOT_CLK_SEL)) { + case 0: + return GLB_ROOT_CLK_RC32M; + case 1: + return GLB_ROOT_CLK_XTAL; + case 2: + case 3: + return GLB_ROOT_CLK_DLL; + default: + return GLB_ROOT_CLK_RC32M; + } } #endif /****************************************************************************/ /** - * @brief Set System clock divider - * - * @param hclkDiv: HCLK divider - * @param bclkDiv: BCLK divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK_Div(uint8_t hclkDiv, uint8_t bclkDiv) -{ - /***********************************************************************************/ - /* NOTE */ - /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ - /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ - /***********************************************************************************/ - uint32_t tmpVal; - - /* recommend: fclk<=160MHz, bclk<=80MHz */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, hclkDiv); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, bclkDiv); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - GLB_REG_BCLK_DIS_TRUE; - GLB_REG_BCLK_DIS_FALSE; - //SystemCoreClockSet(SystemCoreClockGet() / ((uint16_t)hclkDiv + 1)); - GLB_CLK_SET_DUMMY_WAIT; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_HCLK_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_BCLK_EN); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - GLB_CLK_SET_DUMMY_WAIT; - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Get Bus clock divider - * - * @param None - * - * @return Clock Divider - * -*******************************************************************************/ + * @brief Set System clock divider + * + * @param hclkDiv: HCLK divider + * @param bclkDiv: BCLK divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK_Div(uint8_t hclkDiv, uint8_t bclkDiv) { + /***********************************************************************************/ + /* NOTE */ + /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ + /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ + /***********************************************************************************/ + uint32_t tmpVal; + + /* recommend: fclk<=160MHz, bclk<=80MHz */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, hclkDiv); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, bclkDiv); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + GLB_REG_BCLK_DIS_TRUE; + GLB_REG_BCLK_DIS_FALSE; + // SystemCoreClockSet(SystemCoreClockGet() / ((uint16_t)hclkDiv + 1)); + GLB_CLK_SET_DUMMY_WAIT; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_HCLK_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_BCLK_EN); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + GLB_CLK_SET_DUMMY_WAIT; + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Get Bus clock divider + * + * @param None + * + * @return Clock Divider + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint8_t ATTR_CLOCK_SECTION GLB_Get_BCLK_Div(void) -{ - uint32_t tmpVal; +uint8_t ATTR_CLOCK_SECTION GLB_Get_BCLK_Div(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV); + return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV); } #endif /****************************************************************************/ /** - * @brief Get CPU clock divider - * - * @param None - * - * @return Clock Divider - * -*******************************************************************************/ + * @brief Get CPU clock divider + * + * @param None + * + * @return Clock Divider + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint8_t ATTR_CLOCK_SECTION GLB_Get_HCLK_Div(void) -{ - uint32_t tmpVal; +uint8_t ATTR_CLOCK_SECTION GLB_Get_HCLK_Div(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV); + return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV); } #endif /****************************************************************************/ /** - * @brief update SystemCoreClock value - * - * @param xtalType: XTAL frequency type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief update SystemCoreClock value + * + * @param xtalType: XTAL frequency type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION Update_SystemCoreClockWith_XTAL(GLB_DLL_XTAL_Type xtalType) -{ - CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); - - switch (xtalType) { - case GLB_DLL_XTAL_NONE: - break; - case GLB_DLL_XTAL_32M: - SystemCoreClockSet(32000000); - break; - case GLB_DLL_XTAL_RC32M: - SystemCoreClockSet(32000000); - break; - default: - break; - } - - return SUCCESS; +BL_Err_Type ATTR_CLOCK_SECTION Update_SystemCoreClockWith_XTAL(GLB_DLL_XTAL_Type xtalType) { + CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); + + switch (xtalType) { + case GLB_DLL_XTAL_NONE: + break; + case GLB_DLL_XTAL_32M: + SystemCoreClockSet(32000000); + break; + case GLB_DLL_XTAL_RC32M: + SystemCoreClockSet(32000000); + break; + default: + break; + } + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set System clock - * - * @param xtalType: XTAL frequency type - * @param clkFreq: clock frequency selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set System clock + * + * @param xtalType: XTAL frequency type + * @param clkFreq: clock frequency selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK(GLB_DLL_XTAL_Type xtalType, GLB_SYS_CLK_Type clkFreq) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); - CHECK_PARAM(IS_GLB_SYS_CLK_TYPE(clkFreq)); - - /* reg_bclk_en = reg_hclk_en = reg_fclk_en = 1, cannot be zero */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_BCLK_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_HCLK_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_FCLK_EN); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - - /* Before config XTAL and DLL ,make sure root clk is from RC32M */ - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_RC32M); - GLB_Set_System_CLK_Div(0, 0); - SystemCoreClockSet(32 * 1000 * 1000); - - if (xtalType == GLB_DLL_XTAL_NONE) { - if (clkFreq == GLB_SYS_CLK_RC32M) { - return SUCCESS; - } else { - return ERROR; - } +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK(GLB_DLL_XTAL_Type xtalType, GLB_SYS_CLK_Type clkFreq) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); + CHECK_PARAM(IS_GLB_SYS_CLK_TYPE(clkFreq)); + + /* reg_bclk_en = reg_hclk_en = reg_fclk_en = 1, cannot be zero */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_BCLK_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_HCLK_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_FCLK_EN); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + + /* Before config XTAL and DLL ,make sure root clk is from RC32M */ + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_RC32M); + GLB_Set_System_CLK_Div(0, 0); + SystemCoreClockSet(32 * 1000 * 1000); + + if (xtalType == GLB_DLL_XTAL_NONE) { + if (clkFreq == GLB_SYS_CLK_RC32M) { + return SUCCESS; + } else { + return ERROR; } + } - if (xtalType != GLB_DLL_XTAL_RC32M) { - /* power on xtal first */ - AON_Power_On_XTAL(); - } + if (xtalType != GLB_DLL_XTAL_RC32M) { + /* power on xtal first */ + AON_Power_On_XTAL(); + } - /* Bl702 make PLL Setting out of RF, so following setting can be removed*/ - //AON_Power_On_MBG(); - //AON_Power_On_LDO15_RF(); + /* Bl702 make PLL Setting out of RF, so following setting can be removed*/ + // AON_Power_On_MBG(); + // AON_Power_On_LDO15_RF(); - /* always power up PLL and enable all PLL clock output */ - //PDS_Power_On_PLL((PDS_PLL_XTAL_Type)xtalType); - //BL702_Delay_US(55); - //PDS_Enable_PLL_All_Clks(); + /* always power up PLL and enable all PLL clock output */ + // PDS_Power_On_PLL((PDS_PLL_XTAL_Type)xtalType); + // BL702_Delay_US(55); + // PDS_Enable_PLL_All_Clks(); - /* always power up DLL and enable all DLL clock output */ - GLB_Power_Off_DLL(); - GLB_Power_On_DLL(xtalType); - GLB_Enable_DLL_All_Clks(); + /* always power up DLL and enable all DLL clock output */ + GLB_Power_Off_DLL(); + GLB_Power_On_DLL(xtalType); + GLB_Enable_DLL_All_Clks(); - /* reg_pll_en = 1, cannot be zero */ + /* reg_pll_en = 1, cannot be zero */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_PLL_EN); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + + /* select pll output clock before select root clock */ + if (clkFreq >= GLB_SYS_CLK_DLL57P6M) { tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_PLL_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_PLL_SEL, clkFreq - GLB_SYS_CLK_DLL57P6M); BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - - /* select pll output clock before select root clock */ - if (clkFreq >= GLB_SYS_CLK_DLL57P6M) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_PLL_SEL, clkFreq - GLB_SYS_CLK_DLL57P6M); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - } - /* select root clock */ - switch (clkFreq) { - case GLB_SYS_CLK_RC32M: - break; - case GLB_SYS_CLK_XTAL: - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - Update_SystemCoreClockWith_XTAL(xtalType); - break; - case GLB_SYS_CLK_DLL57P6M: - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); - SystemCoreClockSet(57 * 6000 * 1000); - break; - case GLB_SYS_CLK_DLL96M: - L1C_IROM_2T_Access_Set(ENABLE); - GLB_Set_System_CLK_Div(0, 1); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); - SystemCoreClockSet(96 * 1000 * 1000); - break; - case GLB_SYS_CLK_DLL144M: - L1C_IROM_2T_Access_Set(ENABLE); - GLB_Set_System_CLK_Div(0, 1); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); - SystemCoreClockSet(144 * 1000 * 1000); - break; - default: - break; - } - - GLB_CLK_SET_DUMMY_WAIT; - - return SUCCESS; + } + /* select root clock */ + switch (clkFreq) { + case GLB_SYS_CLK_RC32M: + break; + case GLB_SYS_CLK_XTAL: + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + Update_SystemCoreClockWith_XTAL(xtalType); + break; + case GLB_SYS_CLK_DLL57P6M: + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); + SystemCoreClockSet(57 * 6000 * 1000); + break; + case GLB_SYS_CLK_DLL96M: + L1C_IROM_2T_Access_Set(ENABLE); + GLB_Set_System_CLK_Div(0, 1); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); + SystemCoreClockSet(96 * 1000 * 1000); + break; + case GLB_SYS_CLK_DLL144M: + L1C_IROM_2T_Access_Set(ENABLE); + GLB_Set_System_CLK_Div(0, 1); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_DLL); + SystemCoreClockSet(144 * 1000 * 1000); + break; + default: + break; + } + + GLB_CLK_SET_DUMMY_WAIT; + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief This is demo for user that use RC32M as default bootup clock instead of DLL,when APP is - * started, this function can be called to set DLL to 160M - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief This is demo for user that use RC32M as default bootup clock instead of DLL,when APP is + * started, this function can be called to set DLL to 160M + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION System_Core_Clock_Update_From_RC32M(void) -{ - SF_Ctrl_Cfg_Type sfCtrlCfg = { - .owner = SF_CTRL_OWNER_IAHB, - .clkDelay = 1, - .clkInvert = 1, - .rxClkInvert = 1, - .doDelay = 0, - .diDelay = 0, - .oeDelay = 0, - }; - /* Use RC32M as DLL ref source to set up DLL to 144M */ - GLB_Set_System_CLK(GLB_DLL_XTAL_RC32M, GLB_SYS_CLK_DLL144M); - /* Flash controller also need changes since system (bus) clock changed */ - SF_Ctrl_Enable(&sfCtrlCfg); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - return SUCCESS; +BL_Err_Type ATTR_CLOCK_SECTION System_Core_Clock_Update_From_RC32M(void) { + SF_Ctrl_Cfg_Type sfCtrlCfg = { + .owner = SF_CTRL_OWNER_IAHB, + .clkDelay = 1, + .clkInvert = 1, + .rxClkInvert = 1, + .doDelay = 0, + .diDelay = 0, + .oeDelay = 0, + }; + /* Use RC32M as DLL ref source to set up DLL to 144M */ + GLB_Set_System_CLK(GLB_DLL_XTAL_RC32M, GLB_SYS_CLK_DLL144M); + /* Flash controller also need changes since system (bus) clock changed */ + SF_Ctrl_Enable(&sfCtrlCfg); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief set CAM clock - * - * @param enable: Enable or disable CAM clock - * @param clkSel: CAM clock type - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_CAM_CLK(uint8_t enable, GLB_CAM_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal = 0; + * @brief set CAM clock + * + * @param enable: Enable or disable CAM clock + * @param clkSel: CAM clock type + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_CAM_CLK(uint8_t enable, GLB_CAM_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_CAM_CLK_TYPE(clkSel)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_CAM_REF_CLK_SRC_SEL, clkSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_CAM_REF_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set mac154 and zigbee clock + * + * @param enable: Enable or disable mac154 and zigbee clock + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_MAC154_ZIGBEE_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_M154_ZBEN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_M154_ZBEN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} - CHECK_PARAM(IS_GLB_CAM_CLK_TYPE(clkSel)); +/****************************************************************************/ /** + * @brief set BLE clock + * + * @param enable: Enable or disable BLE clock + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_BLE_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BLE_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BLE_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set I2S clock + * + * @param enable: Enable or disable I2S clock + * @param outRef: I2S output ref clock type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_I2S_CLK(uint8_t enable, GLB_I2S_OUT_REF_CLK_Type outRef) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_I2S_OUT_REF_CLK_TYPE(outRef)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_I2S_0_REF_CLK_OE, outRef); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_I2S0_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_I2S0_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set USB clock + * + * @param enable: Enable or disable USB clock + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_USB_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_48M_DIV_EN, 1); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_USB_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_USB_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set QDEC clock + * + * @param clkSel: QDEC clock type + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_QDEC_CLK(GLB_QDEC_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_QDEC_CLK_TYPE(clkSel)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_QDEC_CLK_SEL, clkSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_QDEC_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set DMA clock + * + * @param enable: Enable or disable DMA clock + * @param clk: DMA ID type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_DMA_CLK(uint8_t enable, GLB_DMA_CLK_ID_Type clk) { + uint32_t tmpVal; + uint32_t tmpVal2; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, GLB_DMA_CLK_EN); + if (enable) { + tmpVal2 |= (1 << clk); + } else { + tmpVal2 &= (~(1 << clk)); + } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DMA_CLK_EN, tmpVal2); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set IR clock divider + * + * @param enable: enable or disable IR clock + * @param clkSel: IR clock type + * @param div: divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_IR_CLK(uint8_t enable, GLB_IR_CLK_SRC_Type clkSel, uint8_t div) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_IR_CLK_SRC_TYPE(clkSel)); + CHECK_PARAM((div <= 0x3F)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_IR_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_IR_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_IR_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set sflash clock + * + * @param enable: Enable or disable sflash clock + * @param clkSel: sflash clock type + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_SF_CLK(uint8_t enable, GLB_SFLASH_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal = 0; + GLB_DLL_CLK_Type clk; + + CHECK_PARAM(IS_GLB_SFLASH_CLK_TYPE(clkSel)); + CHECK_PARAM((div <= 0x7)); + + /* disable SFLASH clock first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SF_CLK_EN); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + /* Select flash clock, all Flash CLKs are divied by DLL_288M */ + clk = GLB_DLL_CLK_288M; + GLB_Enable_DLL_Clk(clk); + /* clock divider */ + /* Select flash clock, all Flash CLKs are divied by DLL_288M */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_DIV, div); + switch (clkSel) { + case GLB_SFLASH_CLK_144M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x0); + break; + case GLB_SFLASH_CLK_XCLK: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x1); + break; + case GLB_SFLASH_CLK_57P6M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x3); + break; + case GLB_SFLASH_CLK_72M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x1); + break; + case GLB_SFLASH_CLK_BCLK: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x2); + break; + case GLB_SFLASH_CLK_96M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x3); + break; + default: + break; + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + /* enable or disable flash clock */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_SF_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SF_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_CAM_REF_CLK_SRC_SEL, clkSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_CAM_REF_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + return SUCCESS; +} +#endif - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CAM_REF_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); +/****************************************************************************/ /** + * @brief set UART clock + * + * @param enable: Enable or disable UART clock + * @param clkSel: UART clock type + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_UART_CLK(uint8_t enable, HBN_UART_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal = 0; + + CHECK_PARAM((div <= 0x7)); + CHECK_PARAM(IS_HBN_UART_CLK_TYPE(clkSel)); + + /* disable UART clock first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_UART_CLK_EN); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + /* Set div */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UART_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + + /* Select clock source for uart */ + HBN_Set_UART_CLK_Sel(clkSel); + + /* Set enable or disable */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_UART_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_UART_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief set mac154 and zigbee clock - * - * @param enable: Enable or disable mac154 and zigbee clock - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_MAC154_ZIGBEE_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief select chip clock out 0 type + * + * @param clkSel: chip clock out type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_Chip_Out_0_CLK_Sel(GLB_CHIP_CLK_OUT_Type clkSel) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_M154_ZBEN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_M154_ZBEN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + CHECK_PARAM(IS_GLB_CHIP_CLK_OUT_TYPE(clkSel)); - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CHIP_CLK_OUT_0_SEL, clkSel); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set BLE clock - * - * @param enable: Enable or disable BLE clock - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_BLE_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief select chip clock out 1 type + * + * @param clkSel: chip clock out type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_Chip_Out_1_CLK_Sel(GLB_CHIP_CLK_OUT_Type clkSel) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BLE_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BLE_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + CHECK_PARAM(IS_GLB_CHIP_CLK_OUT_TYPE(clkSel)); - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CHIP_CLK_OUT_1_SEL, clkSel); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set I2S clock - * - * @param enable: Enable or disable I2S clock - * @param outRef: I2S output ref clock type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_I2S_CLK(uint8_t enable, GLB_I2S_OUT_REF_CLK_Type outRef) -{ - uint32_t tmpVal = 0; + * @brief set I2C clock + * + * @param enable: Enable or disable I2C clock + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_I2C_CLK(uint8_t enable, uint8_t div) { + uint32_t tmpVal = 0; - CHECK_PARAM(IS_GLB_I2S_OUT_REF_CLK_TYPE(outRef)); + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_I2C_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_I2S_0_REF_CLK_OE, outRef); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_I2S0_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_I2S0_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_I2C_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_I2C_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief set USB clock - * - * @param enable: Enable or disable USB clock - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_USB_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief invert eth rx clock + * + * @param enable: invert or not invert + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Invert_ETH_RX_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_RX_CLK); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_RX_CLK); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_48M_DIV_EN, 1); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + return SUCCESS; +} - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_USB_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_USB_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); +/****************************************************************************/ /** + * @brief invert rf test clock out + * + * @param enable: invert or not invert + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Invert_RF_TEST_O_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_RF_TEST_CLK_O); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_RF_TEST_CLK_O); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - return SUCCESS; + return SUCCESS; } -/****************************************************************************/ /** - * @brief set QDEC clock - * - * @param clkSel: QDEC clock type - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_QDEC_CLK(GLB_QDEC_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal = 0; +/****************************************************************************/ /** + * @brief set SPI clock + * + * @param enable: Enable or disable SPI clock + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_SPI_CLK(uint8_t enable, uint8_t div) { + uint32_t tmpVal = 0; - CHECK_PARAM(IS_GLB_QDEC_CLK_TYPE(clkSel)); + CHECK_PARAM((div <= 0x1F)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_QDEC_CLK_SEL, clkSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_QDEC_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG1, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SPI_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_SPI_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SPI_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief invert eth tx clock + * + * @param enable: invert or not invert + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Invert_ETH_TX_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_TX_CLK); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_TX_CLK); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set DMA clock - * - * @param enable: Enable or disable DMA clock - * @param clk: DMA ID type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_DMA_CLK(uint8_t enable, GLB_DMA_CLK_ID_Type clk) -{ - uint32_t tmpVal; - uint32_t tmpVal2; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, GLB_DMA_CLK_EN); - if (enable) { - tmpVal2 |= (1 << clk); - } else { - tmpVal2 &= (~(1 << clk)); - } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DMA_CLK_EN, tmpVal2); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + * @brief invert eth ref clock out + * + * @param enable: invert or not invert + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Invert_ETH_REF_O_CLK(uint8_t enable) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_REF_CLK_O); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_REF_CLK_O); + } + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief set IR clock divider - * - * @param enable: enable or disable IR clock - * @param clkSel: IR clock type - * @param div: divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_IR_CLK(uint8_t enable, GLB_IR_CLK_SRC_Type clkSel, uint8_t div) -{ - uint32_t tmpVal = 0; + * @brief select eth ref clock out + * + * @param clkSel: eth ref clock type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_ETH_REF_O_CLK_Sel(GLB_ETH_REF_CLK_OUT_Type clkSel) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_SEL_ETH_REF_CLK_O, clkSel); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - CHECK_PARAM(IS_GLB_IR_CLK_SRC_TYPE(clkSel)); - CHECK_PARAM((div <= 0x3F)); + return SUCCESS; +} - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_IR_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); +/****************************************************************************/ /** + * @brief select PKA clock source + * + * @param clkSel: PKA clock selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_PKA_CLK_Sel(GLB_PKA_CLK_Type clkSel) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_PKA_CLK_TYPE(clkSel)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PKA_CLK_SEL, clkSel); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_IR_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_IR_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + return SUCCESS; +} - return SUCCESS; +/****************************************************************************/ /** + * @brief Software system reset + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_SW_System_Reset(void) { + /***********************************************************************************/ + /* NOTE */ + /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ + /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ + /***********************************************************************************/ + uint32_t tmpVal; + + /* Swicth clock to 32M as default */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + GLB_CLK_SET_DUMMY_WAIT; + + /* HCLK is RC32M , so BCLK/HCLK no need divider */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + GLB_REG_BCLK_DIS_TRUE; + GLB_REG_BCLK_DIS_FALSE; + GLB_CLK_SET_DUMMY_WAIT; + + /* Do reset */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + // tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + /* waiting for reset */ + while (1) { + BL702_Delay_US(10); + } + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief set sflash clock - * - * @param enable: Enable or disable sflash clock - * @param clkSel: sflash clock type - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Software CPU reset + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_SF_CLK(uint8_t enable, GLB_SFLASH_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal = 0; - GLB_DLL_CLK_Type clk; +BL_Err_Type ATTR_TCM_SECTION GLB_SW_CPU_Reset(void) { + /***********************************************************************************/ + /* NOTE */ + /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ + /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ + /***********************************************************************************/ + uint32_t tmpVal; + + /* Swicth clock to 32M as default */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + GLB_CLK_SET_DUMMY_WAIT; + + /* HCLK is RC32M , so BCLK/HCLK no need divider */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + GLB_REG_BCLK_DIS_TRUE; + GLB_REG_BCLK_DIS_FALSE; + GLB_CLK_SET_DUMMY_WAIT; + + /* Do reset */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + // tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + // tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + /* waiting for reset */ + while (1) { + BL702_Delay_US(10); + } + + return SUCCESS; +} +#endif - CHECK_PARAM(IS_GLB_SFLASH_CLK_TYPE(clkSel)); - CHECK_PARAM((div <= 0x7)); +/****************************************************************************/ /** + * @brief Software power on reset + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_SW_POR_Reset(void) { + /***********************************************************************************/ + /* NOTE */ + /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ + /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ + /***********************************************************************************/ + uint32_t tmpVal; + + /* Swicth clock to 32M as default */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + GLB_CLK_SET_DUMMY_WAIT; + + /* HCLK is RC32M , so BCLK/HCLK no need divider */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); + BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); + GLB_REG_BCLK_DIS_TRUE; + GLB_REG_BCLK_DIS_FALSE; + GLB_CLK_SET_DUMMY_WAIT; + + /* Do reset */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + + /* waiting for reset */ + while (1) { + BL702_Delay_US(10); + } + + return SUCCESS; +} +#endif - /* disable SFLASH clock first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SF_CLK_EN); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); - - /* Select flash clock, all Flash CLKs are divied by DLL_288M */ - clk = GLB_DLL_CLK_288M; - GLB_Enable_DLL_Clk(clk); - /* clock divider */ - /* Select flash clock, all Flash CLKs are divied by DLL_288M */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_DIV, div); - switch (clkSel) { - case GLB_SFLASH_CLK_144M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x0); - break; - case GLB_SFLASH_CLK_XCLK: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x1); - break; - case GLB_SFLASH_CLK_57P6M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL2, 0x3); - break; - case GLB_SFLASH_CLK_72M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x1); - break; - case GLB_SFLASH_CLK_BCLK: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x2); - break; - case GLB_SFLASH_CLK_96M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SF_CLK_SEL, 0x3); - break; - default: - break; +/****************************************************************************/ /** + * @brief Reset slave 1 + * + * @param slave1: slave num + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_AHB_Slave1_Reset(BL_AHB_Slave1_Type slave1) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); + tmpVal &= (~(1 << slave1)); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); + BL_DRV_DUMMY; + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); + tmpVal |= (1 << slave1); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); + BL_DRV_DUMMY; + tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); + tmpVal &= (~(1 << slave1)); + BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief clock gate + * + * @param enable: ENABLE or DISABLE + * @param slave1: AHB slaveClk type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_AHB_Slave1_Clock_Gate(uint8_t enable, BL_AHB_Slave1_Type slave1) { + /* gate QDEC <=> gate QDEC0 + QDEC1 +QDEC2 + I2S */ + /* gate I2S <=> gate I2S + QDEC2 */ + + uint32_t tmpVal = 0; + + if ((BL_AHB_SLAVE1_GLB == slave1) || (BL_AHB_SLAVE1_TZ2 == slave1) || (BL_AHB_SLAVE1_CCI == slave1) || (BL_AHB_SLAVE1_L1C == slave1) || (BL_AHB_SLAVE1_PDS_HBN_AON_HBNRAM == slave1)) { + /* not support */ + return ERROR; + } + + /* gate QDEC and I2S */ + if (BL_AHB_SLAVE1_QDEC == slave1) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + if (enable) { + /* clear bit means clock gate */ + tmpVal &= (~(1 << 0x18)); + tmpVal &= (~(1 << 0x19)); + tmpVal &= (~(1 << 0x1A)); + } else { + /* set bit means clock pass */ + tmpVal |= (1 << 0x18); + tmpVal |= (1 << 0x19); + tmpVal |= (1 << 0x1A); } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); + return SUCCESS; + } - /* enable or disable flash clock */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); + /* gate KYS */ + if (BL_AHB_SLAVE1_KYS == slave1) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_SF_CLK_EN); + /* clear bit means clock gate */ + tmpVal &= (~(1 << 0x1B)); } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SF_CLK_EN); + /* set bit means clock pass */ + tmpVal |= (1 << 0x1B); } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); + return SUCCESS; + } + /* gate I2S and QDEC2 */ + if (BL_AHB_SLAVE1_I2S == slave1) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + if (enable) { + /* clear bit means clock gate */ + tmpVal &= (~(1 << 0x1A)); + } else { + /* set bit means clock pass */ + tmpVal |= (1 << 0x1A); + } + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); return SUCCESS; -} + } + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + if (enable) { + /* clear bit means clock gate */ + tmpVal &= (~(1 << slave1)); + } else { + /* set bit means clock pass */ + tmpVal |= (1 << slave1); + } + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief get IPs clock gate value + * + * @param None + * + * @return clock gate value + * + *******************************************************************************/ +uint64_t GLB_PER_Clock_Gate_Status_Get(void) { + /* api request from cjy */ + + uint32_t tmpValCfg0 = 0; + uint32_t tmpValCfg1 = 0; + uint32_t tmpValCfg2 = 0; + uint32_t targetBit = 0; + uint64_t targetVal = 0; + + tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); + tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); + for (uint8_t i = 0; i < 64; i++) { + targetBit = 0; + switch (i) { + case GLB_AHB_CLOCK_IP_CPU: + targetBit = tmpValCfg0 & (1 << 0); + break; + case GLB_AHB_CLOCK_IP_SDU: + targetBit = tmpValCfg0 & (1 << 1); + break; + case GLB_AHB_CLOCK_IP_SEC: + targetBit = (tmpValCfg0 & (1 << 2)) && (tmpValCfg1 & (1 << 3)) && (tmpValCfg1 & (1 << 4)); + break; + case GLB_AHB_CLOCK_IP_DMA_0: + targetBit = (tmpValCfg0 & (1 << 3)) && (tmpValCfg1 & (1 << 12)); + break; + case GLB_AHB_CLOCK_IP_DMA_1: + break; + case GLB_AHB_CLOCK_IP_DMA_2: + break; + case GLB_AHB_CLOCK_IP_CCI: + targetBit = tmpValCfg0 & (1 << 4); + break; + case GLB_AHB_CLOCK_IP_RF_TOP: + break; + case GLB_AHB_CLOCK_IP_GPIP: + targetBit = tmpValCfg1 & (1 << 2); + break; + case GLB_AHB_CLOCK_IP_TZC: + targetBit = tmpValCfg1 & (1 << 5); + break; + case GLB_AHB_CLOCK_IP_EF_CTRL: + targetBit = tmpValCfg1 & (1 << 7); + break; + case GLB_AHB_CLOCK_IP_SF_CTRL: + targetBit = tmpValCfg1 & (1 << 11); + break; + case GLB_AHB_CLOCK_IP_EMAC: + targetBit = tmpValCfg1 & (1 << 13); + break; + case GLB_AHB_CLOCK_IP_UART0: + targetBit = tmpValCfg1 & (1 << 16); + break; + case GLB_AHB_CLOCK_IP_UART1: + targetBit = tmpValCfg1 & (1 << 17); + break; + case GLB_AHB_CLOCK_IP_UART2: + break; + case GLB_AHB_CLOCK_IP_UART3: + break; + case GLB_AHB_CLOCK_IP_UART4: + break; + case GLB_AHB_CLOCK_IP_SPI: + targetBit = tmpValCfg1 & (1 << 18); + break; + case GLB_AHB_CLOCK_IP_I2C: + targetBit = tmpValCfg1 & (1 << 19); + break; + case GLB_AHB_CLOCK_IP_PWM: + targetBit = tmpValCfg1 & (1 << 20); + break; + case GLB_AHB_CLOCK_IP_TIMER: + targetBit = tmpValCfg1 & (1 << 21); + break; + case GLB_AHB_CLOCK_IP_IR: + targetBit = tmpValCfg1 & (1 << 22); + break; + case GLB_AHB_CLOCK_IP_CHECKSUM: + targetBit = tmpValCfg1 & (1 << 23); + break; + case GLB_AHB_CLOCK_IP_QDEC: + targetBit = (tmpValCfg1 & (1 << 24)) && (tmpValCfg1 & (1 << 25)) && (tmpValCfg1 & (1 << 26)); + break; + case GLB_AHB_CLOCK_IP_KYS: + targetBit = tmpValCfg1 & (1 << 27); + break; + case GLB_AHB_CLOCK_IP_I2S: + targetBit = tmpValCfg1 & (1 << 26); + break; + case GLB_AHB_CLOCK_IP_USB11: + targetBit = tmpValCfg1 & (1 << 28); + break; + case GLB_AHB_CLOCK_IP_CAM: + targetBit = tmpValCfg1 & (1 << 29); + break; + case GLB_AHB_CLOCK_IP_MJPEG: + targetBit = tmpValCfg1 & (1 << 30); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: + targetBit = (tmpValCfg2 & (1 << 0)) && (tmpValCfg2 & (1 << 4)); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_LP: + break; + case GLB_AHB_CLOCK_IP_ZB_NORMAL: + targetBit = tmpValCfg2 & (1 << 0); + break; + case GLB_AHB_CLOCK_IP_ZB_LP: + break; + case GLB_AHB_CLOCK_IP_WIFI_NORMAL: + break; + case GLB_AHB_CLOCK_IP_WIFI_LP: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: + break; + case GLB_AHB_CLOCK_IP_EMI_MISC: + break; + case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: + break; + case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: + break; + case GLB_AHB_CLOCK_IP_USB20: + break; + case GLB_AHB_CLOCK_IP_MIX2: + break; + case GLB_AHB_CLOCK_IP_AUDIO: + break; + case GLB_AHB_CLOCK_IP_SDH: + break; + default: + break; + } + if (!targetBit) { + targetVal |= ((uint64_t)1 << i); + } + } + + return targetVal; +} + +/****************************************************************************/ /** + * @brief get first 1 from u64, then clear it + * + * @param val: target value + * @param bit: first 1 in bit + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +static BL_Err_Type GLB_Get_And_Clr_First_Set_From_U64(uint64_t *val, uint32_t *bit) { + if (!*val) { + return ERROR; + } + + for (uint8_t i = 0; i < 64; i++) { + if ((*val) & ((uint64_t)1 << i)) { + *bit = i; + (*val) &= ~((uint64_t)1 << i); + break; + } + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief hold IPs clock + * + * @param ips: GLB_AHB_CLOCK_IP_xxx | GLB_AHB_CLOCK_IP_xxx | ...... + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_PER_Clock_Gate(uint64_t ips) { + /* api request from cjy */ + + uint32_t tmpValCfg0 = 0; + uint32_t tmpValCfg1 = 0; + uint32_t tmpValCfg2 = 0; + uint32_t bitfield = 0; + + tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); + tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); + while (ips) { + if (SUCCESS == GLB_Get_And_Clr_First_Set_From_U64(&ips, &bitfield)) { + switch (bitfield) { + case GLB_AHB_CLOCK_IP_CPU: + tmpValCfg0 &= ~(1 << 0); + break; + case GLB_AHB_CLOCK_IP_SDU: + tmpValCfg0 &= ~(1 << 1); + break; + case GLB_AHB_CLOCK_IP_SEC: + tmpValCfg0 &= ~(1 << 2); + tmpValCfg1 &= ~(1 << 3); + tmpValCfg1 &= ~(1 << 4); + break; + case GLB_AHB_CLOCK_IP_DMA_0: + tmpValCfg0 &= ~(1 << 3); + tmpValCfg1 &= ~(1 << 12); + break; + case GLB_AHB_CLOCK_IP_DMA_1: + break; + case GLB_AHB_CLOCK_IP_DMA_2: + break; + case GLB_AHB_CLOCK_IP_CCI: + tmpValCfg0 &= ~(1 << 4); + break; + case GLB_AHB_CLOCK_IP_RF_TOP: + break; + case GLB_AHB_CLOCK_IP_GPIP: + tmpValCfg1 &= ~(1 << 2); + break; + case GLB_AHB_CLOCK_IP_TZC: + tmpValCfg1 &= ~(1 << 5); + break; + case GLB_AHB_CLOCK_IP_EF_CTRL: + tmpValCfg1 &= ~(1 << 7); + break; + case GLB_AHB_CLOCK_IP_SF_CTRL: + tmpValCfg1 &= ~(1 << 11); + break; + case GLB_AHB_CLOCK_IP_EMAC: + tmpValCfg1 &= ~(1 << 13); + break; + case GLB_AHB_CLOCK_IP_UART0: + tmpValCfg1 &= ~(1 << 16); + break; + case GLB_AHB_CLOCK_IP_UART1: + tmpValCfg1 &= ~(1 << 17); + break; + case GLB_AHB_CLOCK_IP_UART2: + break; + case GLB_AHB_CLOCK_IP_UART3: + break; + case GLB_AHB_CLOCK_IP_UART4: + break; + case GLB_AHB_CLOCK_IP_SPI: + tmpValCfg1 &= ~(1 << 18); + break; + case GLB_AHB_CLOCK_IP_I2C: + tmpValCfg1 &= ~(1 << 19); + break; + case GLB_AHB_CLOCK_IP_PWM: + tmpValCfg1 &= ~(1 << 20); + break; + case GLB_AHB_CLOCK_IP_TIMER: + tmpValCfg1 &= ~(1 << 21); + break; + case GLB_AHB_CLOCK_IP_IR: + tmpValCfg1 &= ~(1 << 22); + break; + case GLB_AHB_CLOCK_IP_CHECKSUM: + tmpValCfg1 &= ~(1 << 23); + break; + case GLB_AHB_CLOCK_IP_QDEC: + tmpValCfg1 &= ~(1 << 24); + tmpValCfg1 &= ~(1 << 25); + tmpValCfg1 &= ~(1 << 26); + break; + case GLB_AHB_CLOCK_IP_KYS: + tmpValCfg1 &= ~(1 << 27); + break; + case GLB_AHB_CLOCK_IP_I2S: + tmpValCfg1 &= ~(1 << 26); + break; + case GLB_AHB_CLOCK_IP_USB11: + tmpValCfg1 &= ~(1 << 28); + break; + case GLB_AHB_CLOCK_IP_CAM: + tmpValCfg1 &= ~(1 << 29); + break; + case GLB_AHB_CLOCK_IP_MJPEG: + tmpValCfg1 &= ~(1 << 30); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: + tmpValCfg2 &= ~(1 << 0); + tmpValCfg2 &= ~(1 << 4); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_LP: + break; + case GLB_AHB_CLOCK_IP_ZB_NORMAL: + tmpValCfg2 &= ~(1 << 0); + break; + case GLB_AHB_CLOCK_IP_ZB_LP: + break; + case GLB_AHB_CLOCK_IP_WIFI_NORMAL: + break; + case GLB_AHB_CLOCK_IP_WIFI_LP: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: + break; + case GLB_AHB_CLOCK_IP_EMI_MISC: + break; + case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: + break; + case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: + break; + case GLB_AHB_CLOCK_IP_USB20: + break; + case GLB_AHB_CLOCK_IP_MIX2: + break; + case GLB_AHB_CLOCK_IP_AUDIO: + break; + case GLB_AHB_CLOCK_IP_SDH: + break; + default: + break; + } + } + } + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG0, tmpValCfg0); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpValCfg1); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG2, tmpValCfg2); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief release IPs clock + * + * @param ips: GLB_AHB_CLOCK_IP_xxx | GLB_AHB_CLOCK_IP_xxx | ...... + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_PER_Clock_UnGate(uint64_t ips) { + /* api request from cjy */ + + uint32_t tmpValCfg0 = 0; + uint32_t tmpValCfg1 = 0; + uint32_t tmpValCfg2 = 0; + uint32_t bitfield = 0; + + tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); + tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); + tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); + while (ips) { + if (SUCCESS == GLB_Get_And_Clr_First_Set_From_U64(&ips, &bitfield)) { + switch (bitfield) { + case GLB_AHB_CLOCK_IP_CPU: + tmpValCfg0 |= (1 << 0); + break; + case GLB_AHB_CLOCK_IP_SDU: + tmpValCfg0 |= (1 << 1); + break; + case GLB_AHB_CLOCK_IP_SEC: + tmpValCfg0 |= (1 << 2); + tmpValCfg1 |= (1 << 3); + tmpValCfg1 |= (1 << 4); + break; + case GLB_AHB_CLOCK_IP_DMA_0: + tmpValCfg0 |= (1 << 3); + tmpValCfg1 |= (1 << 12); + break; + case GLB_AHB_CLOCK_IP_DMA_1: + break; + case GLB_AHB_CLOCK_IP_DMA_2: + break; + case GLB_AHB_CLOCK_IP_CCI: + tmpValCfg0 |= (1 << 4); + break; + case GLB_AHB_CLOCK_IP_RF_TOP: + break; + case GLB_AHB_CLOCK_IP_GPIP: + tmpValCfg1 |= (1 << 2); + break; + case GLB_AHB_CLOCK_IP_TZC: + tmpValCfg1 |= (1 << 5); + break; + case GLB_AHB_CLOCK_IP_EF_CTRL: + tmpValCfg1 |= (1 << 7); + break; + case GLB_AHB_CLOCK_IP_SF_CTRL: + tmpValCfg1 |= (1 << 11); + break; + case GLB_AHB_CLOCK_IP_EMAC: + tmpValCfg1 |= (1 << 13); + break; + case GLB_AHB_CLOCK_IP_UART0: + tmpValCfg1 |= (1 << 16); + break; + case GLB_AHB_CLOCK_IP_UART1: + tmpValCfg1 |= (1 << 17); + break; + case GLB_AHB_CLOCK_IP_UART2: + break; + case GLB_AHB_CLOCK_IP_UART3: + break; + case GLB_AHB_CLOCK_IP_UART4: + break; + case GLB_AHB_CLOCK_IP_SPI: + tmpValCfg1 |= (1 << 18); + break; + case GLB_AHB_CLOCK_IP_I2C: + tmpValCfg1 |= (1 << 19); + break; + case GLB_AHB_CLOCK_IP_PWM: + tmpValCfg1 |= (1 << 20); + break; + case GLB_AHB_CLOCK_IP_TIMER: + tmpValCfg1 |= (1 << 21); + break; + case GLB_AHB_CLOCK_IP_IR: + tmpValCfg1 |= (1 << 22); + break; + case GLB_AHB_CLOCK_IP_CHECKSUM: + tmpValCfg1 |= (1 << 23); + break; + case GLB_AHB_CLOCK_IP_QDEC: + tmpValCfg1 |= (1 << 24); + tmpValCfg1 |= (1 << 25); + tmpValCfg1 |= (1 << 26); + break; + case GLB_AHB_CLOCK_IP_KYS: + tmpValCfg1 |= (1 << 27); + break; + case GLB_AHB_CLOCK_IP_I2S: + tmpValCfg1 |= (1 << 26); + break; + case GLB_AHB_CLOCK_IP_USB11: + tmpValCfg1 |= (1 << 28); + break; + case GLB_AHB_CLOCK_IP_CAM: + tmpValCfg1 |= (1 << 29); + break; + case GLB_AHB_CLOCK_IP_MJPEG: + tmpValCfg1 |= (1 << 30); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: + tmpValCfg2 |= (1 << 0); + tmpValCfg2 |= (1 << 4); + break; + case GLB_AHB_CLOCK_IP_BT_BLE_LP: + break; + case GLB_AHB_CLOCK_IP_ZB_NORMAL: + tmpValCfg2 |= (1 << 0); + break; + case GLB_AHB_CLOCK_IP_ZB_LP: + break; + case GLB_AHB_CLOCK_IP_WIFI_NORMAL: + break; + case GLB_AHB_CLOCK_IP_WIFI_LP: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: + break; + case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: + break; + case GLB_AHB_CLOCK_IP_EMI_MISC: + break; + case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: + break; + case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: + break; + case GLB_AHB_CLOCK_IP_USB20: + break; + case GLB_AHB_CLOCK_IP_MIX2: + break; + case GLB_AHB_CLOCK_IP_AUDIO: + break; + case GLB_AHB_CLOCK_IP_SDH: + break; + default: + break; + } + } + } + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG0, tmpValCfg0); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpValCfg1); + BL_WR_REG(GLB_BASE, GLB_CGEN_CFG2, tmpValCfg2); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief BMX init + * + * @param BmxCfg: BMX config + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_BMX_Init(BMX_Cfg_Type *BmxCfg) { + uint32_t tmpVal = 0; + + CHECK_PARAM((BmxCfg->timeoutEn) <= 0xF); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_TIMEOUT_EN, BmxCfg->timeoutEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_EN, BmxCfg->errEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_ARB_MODE, BmxCfg->arbMod); + BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); + +#ifndef BFLB_USE_HAL_DRIVER + Interrupt_Handler_Register(BMX_ERR_IRQn, BMX_ERR_IRQHandler); + Interrupt_Handler_Register(BMX_TO_IRQn, BMX_TO_IRQHandler); #endif -/****************************************************************************/ /** - * @brief set UART clock - * - * @param enable: Enable or disable UART clock - * @param clkSel: UART clock type - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_UART_CLK(uint8_t enable, HBN_UART_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal = 0; + return SUCCESS; +} - CHECK_PARAM((div <= 0x7)); - CHECK_PARAM(IS_HBN_UART_CLK_TYPE(clkSel)); +/****************************************************************************/ /** + * @brief BMX address monitor enable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_BMX_Addr_Monitor_Enable(void) { + uint32_t tmpVal = 0; - /* disable UART clock first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_UART_CLK_EN); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BMX_ERR_ADDR_DIS); + BL_WR_REG(GLB_BASE, GLB_BMX_CFG2, tmpVal); - /* Set div */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UART_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + return SUCCESS; +} - /* Select clock source for uart */ - HBN_Set_UART_CLK_Sel(clkSel); +/****************************************************************************/ /** + * @brief BMX address monitor disable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_BMX_Addr_Monitor_Disable(void) { + uint32_t tmpVal = 0; - /* Set enable or disable */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG2); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_UART_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_UART_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG2, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BMX_ERR_ADDR_DIS); + BL_WR_REG(GLB_BASE, GLB_BMX_CFG2, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief select chip clock out 0 type - * - * @param clkSel: chip clock out type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_Chip_Out_0_CLK_Sel(GLB_CHIP_CLK_OUT_Type clkSel) -{ - uint32_t tmpVal = 0; + * @brief BMX bus error response enable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_BMX_BusErrResponse_Enable(void) { + uint32_t tmpVal = 0; - CHECK_PARAM(IS_GLB_CHIP_CLK_OUT_TYPE(clkSel)); + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BMX_ERR_EN); + BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CHIP_CLK_OUT_0_SEL, clkSel); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); - - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief select chip clock out 1 type - * - * @param clkSel: chip clock out type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_Chip_Out_1_CLK_Sel(GLB_CHIP_CLK_OUT_Type clkSel) -{ - uint32_t tmpVal = 0; + * @brief BMX bus error response disable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_BMX_BusErrResponse_Disable(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BMX_ERR_EN); + BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); - CHECK_PARAM(IS_GLB_CHIP_CLK_OUT_TYPE(clkSel)); + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Get BMX error status + * + * @param errType: BMX error status type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type GLB_BMX_Get_Status(BMX_BUS_ERR_Type errType) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CHIP_CLK_OUT_1_SEL, clkSel); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + CHECK_PARAM(IS_BMX_BUS_ERR_TYPE(errType)); - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); + if (errType == BMX_BUS_ERR_TRUSTZONE_DECODE) { + return BL_GET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_TZ) ? SET : RESET; + } else { + return BL_GET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_DEC) ? SET : RESET; + } } /****************************************************************************/ /** - * @brief set I2C clock - * - * @param enable: Enable or disable I2C clock - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_I2C_CLK(uint8_t enable, uint8_t div) -{ - uint32_t tmpVal = 0; + * @brief Get BMX error address + * + * @param None + * + * @return NP BMX error address + * + *******************************************************************************/ +uint32_t GLB_BMX_Get_Err_Addr(void) { return BL_RD_REG(GLB_BASE, GLB_BMX_ERR_ADDR); } - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_I2C_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); +/****************************************************************************/ /** + * @brief BMX error interrupt callback install + * + * @param intType: BMX error interrupt type + * @param cbFun: callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type BMX_ERR_INT_Callback_Install(BMX_ERR_INT_Type intType, intCallback_Type *cbFun) { + CHECK_PARAM(IS_BMX_ERR_INT_TYPE(intType)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_I2C_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_I2C_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + glbBmxErrIntCbfArra[intType] = cbFun; - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief invert eth rx clock - * - * @param enable: invert or not invert - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Invert_ETH_RX_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief BMX ERR interrupt IRQ handler + * + * @param None + * + * @return None + * + *******************************************************************************/ +#ifndef BFLB_USE_HAL_DRIVER +void BMX_ERR_IRQHandler(void) { + BMX_ERR_INT_Type intType; - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_RX_CLK); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_RX_CLK); + for (intType = BMX_ERR_INT_ERR; intType < BMX_ERR_INT_ALL; intType++) { + if (glbBmxErrIntCbfArra[intType] != NULL) { + glbBmxErrIntCbfArra[intType](); } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + } - return SUCCESS; + while (1) { + // MSG("BMX_ERR_IRQHandler\r\n"); + BL702_Delay_MS(1000); + } } +#endif /****************************************************************************/ /** - * @brief invert rf test clock out - * - * @param enable: invert or not invert - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Invert_RF_TEST_O_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief BMX timeout interrupt callback install + * + * @param intType: BMX timeout interrupt type + * @param cbFun: callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type BMX_TIMEOUT_INT_Callback_Install(BMX_TO_INT_Type intType, intCallback_Type *cbFun) { + CHECK_PARAM(IS_BMX_TO_INT_TYPE(intType)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_RF_TEST_CLK_O); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_RF_TEST_CLK_O); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + glbBmxToIntCbfArra[intType] = cbFun; - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief set SPI clock - * - * @param enable: Enable or disable SPI clock - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_SPI_CLK(uint8_t enable, uint8_t div) -{ - uint32_t tmpVal = 0; + * @brief BMX Time Out interrupt IRQ handler + * + * @param None + * + * @return None + * + *******************************************************************************/ +#ifndef BFLB_USE_HAL_DRIVER +void BMX_TO_IRQHandler(void) { + BMX_TO_INT_Type intType; - CHECK_PARAM((div <= 0x1F)); + for (intType = BMX_TO_INT_TIMEOUT; intType < BMX_TO_INT_ALL; intType++) { + if (glbBmxToIntCbfArra[intType] != NULL) { + glbBmxToIntCbfArra[intType](); + } + } - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_SPI_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); + while (1) { + // MSG("BMX_TO_IRQHandler\r\n"); + BL702_Delay_MS(1000); + } +} +#endif - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_SPI_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_SPI_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); +/****************************************************************************/ /** + * @brief set sram_ret value + * + * @param value: value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_SRAM_RET(uint32_t value) { + BL_WR_REG(GLB_BASE, GLB_SRAM_RET, value); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief invert eth tx clock - * - * @param enable: invert or not invert - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Invert_ETH_TX_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief get sram_ret value + * + * @param None + * + * @return value + * + *******************************************************************************/ +uint32_t GLB_Get_SRAM_RET(void) { return BL_RD_REG(GLB_BASE, GLB_SRAM_RET); } - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_TX_CLK); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_TX_CLK); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); +/****************************************************************************/ /** + * @brief set sram_slp value + * + * @param value: value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_SRAM_SLP(uint32_t value) { + BL_WR_REG(GLB_BASE, GLB_SRAM_SLP, value); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief invert eth ref clock out - * - * @param enable: invert or not invert - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Invert_ETH_REF_O_CLK(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief get sram_slp value + * + * @param None + * + * @return value + * + *******************************************************************************/ +uint32_t GLB_Get_SRAM_SLP(void) { return BL_RD_REG(GLB_BASE, GLB_SRAM_SLP); } - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_INV_ETH_REF_CLK_O); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_INV_ETH_REF_CLK_O); - } - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); +/****************************************************************************/ /** + * @brief set sram_param value + * + * @param value: value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_SRAM_PARM(uint32_t value) { + BL_WR_REG(GLB_BASE, GLB_SRAM_PARM, value); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief select eth ref clock out - * - * @param clkSel: eth ref clock type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_ETH_REF_O_CLK_Sel(GLB_ETH_REF_CLK_OUT_Type clkSel) -{ - uint32_t tmpVal = 0; + * @brief get sram_parm value + * + * @param None + * + * @return value + * + *******************************************************************************/ +uint32_t GLB_Get_SRAM_PARM(void) { return BL_RD_REG(GLB_BASE, GLB_SRAM_PARM); } - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_SEL_ETH_REF_CLK_O, clkSel); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG3, tmpVal); +/****************************************************************************/ /** + * @brief select EM type + * + * @param emType: EM type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_EM_Sel(GLB_EM_Type emType) { + uint32_t tmpVal = 0; - return SUCCESS; + CHECK_PARAM(IS_GLB_EM_TYPE(emType)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_SEAM_MISC); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EM_SEL, emType); + BL_WR_REG(GLB_BASE, GLB_SEAM_MISC, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief select PKA clock source - * - * @param clkSel: PKA clock selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_PKA_CLK_Sel(GLB_PKA_CLK_Type clkSel) -{ - uint32_t tmpVal = 0; + * @brief select pin as EMAC or CAM + * + * @param pinType: pin type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_SWAP_EMAC_CAM_Pin(GLB_EMAC_CAM_PIN_Type pinType) { + uint32_t tmpVal = 0; - CHECK_PARAM(IS_GLB_PKA_CLK_TYPE(clkSel)); + CHECK_PARAM(IS_GLB_EMAC_CAM_PIN_TYPE(pinType)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PKA_CLK_SEL, clkSel); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PIN_SEL_EMAC_CAM, pinType); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Software system reset - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_SW_System_Reset(void) -{ - /***********************************************************************************/ - /* NOTE */ - /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ - /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ - /***********************************************************************************/ - uint32_t tmpVal; - - /* Swicth clock to 32M as default */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - GLB_CLK_SET_DUMMY_WAIT; - - /* HCLK is RC32M , so BCLK/HCLK no need divider */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - GLB_REG_BCLK_DIS_TRUE; - GLB_REG_BCLK_DIS_FALSE; - GLB_CLK_SET_DUMMY_WAIT; - - /* Do reset */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - //tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - /* waiting for reset */ - while (1) { - BL702_Delay_US(10); - } - - return SUCCESS; -} -#endif + * @brief EXT_RST PAD SMT + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_Ext_Rst_Smt(uint8_t enable) { + uint32_t tmpVal = 0; -/****************************************************************************/ /** - * @brief Software CPU reset - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_SW_CPU_Reset(void) -{ - /***********************************************************************************/ - /* NOTE */ - /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ - /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ - /***********************************************************************************/ - uint32_t tmpVal; - - /* Swicth clock to 32M as default */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - GLB_CLK_SET_DUMMY_WAIT; - - /* HCLK is RC32M , so BCLK/HCLK no need divider */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - GLB_REG_BCLK_DIS_TRUE; - GLB_REG_BCLK_DIS_FALSE; - GLB_CLK_SET_DUMMY_WAIT; - - /* Do reset */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - //tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - //tmpVal=BL_CLR_REG_BIT(tmpVal,GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - /* waiting for reset */ - while (1) { - BL702_Delay_US(10); - } + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_EXT_RST_SMT); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_EXT_RST_SMT); + } + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } -#endif /****************************************************************************/ /** - * @brief Software power on reset - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_SW_POR_Reset(void) -{ - /***********************************************************************************/ - /* NOTE */ - /* "GLB_REG_BCLK_DIS_TRUE + GLB_REG_BCLK_DIS_FALSE" will stop bclk a little while. */ - /* OCRAM use bclk as source clock. Pay attention to risks when using this API. */ - /***********************************************************************************/ - uint32_t tmpVal; - - /* Swicth clock to 32M as default */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - GLB_CLK_SET_DUMMY_WAIT; - - /* HCLK is RC32M , so BCLK/HCLK no need divider */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CLK_CFG0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_BCLK_DIV, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_HCLK_DIV, 0); - BL_WR_REG(GLB_BASE, GLB_CLK_CFG0, tmpVal); - GLB_REG_BCLK_DIS_TRUE; - GLB_REG_BCLK_DIS_FALSE; - GLB_CLK_SET_DUMMY_WAIT; - - /* Do reset */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG2); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_SYS_RESET); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_CPU_RESET); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CTRL_PWRON_RST); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG2, tmpVal); - - /* waiting for reset */ - while (1) { - BL702_Delay_US(10); - } + * @brief Key Scan Column Drive + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_Kys_Drv_Col(uint8_t enable) { + uint32_t tmpVal = 0; - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_KYS_DRV_VAL); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_KYS_DRV_VAL); + } + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + + return SUCCESS; } -#endif /****************************************************************************/ /** - * @brief Reset slave 1 - * - * @param slave1: slave num - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_AHB_Slave1_Reset(BL_AHB_Slave1_Type slave1) -{ - uint32_t tmpVal = 0; + * @brief swap UART gpio pins sig function + * + * @param swapSel: UART swap set gpio pins selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_UART_Sig_Swap_Set(uint8_t swapSel) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); - tmpVal &= (~(1 << slave1)); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); - BL_DRV_DUMMY; - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); - tmpVal |= (1 << slave1); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); - BL_DRV_DUMMY; - tmpVal = BL_RD_REG(GLB_BASE, GLB_SWRST_CFG1); - tmpVal &= (~(1 << slave1)); - BL_WR_REG(GLB_BASE, GLB_SWRST_CFG1, tmpVal); + CHECK_PARAM((swapSel <= 0xF)); - return SUCCESS; + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UART_SWAP_SET, swapSel); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief clock gate - * - * @param enable: ENABLE or DISABLE - * @param slave1: AHB slaveClk type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_AHB_Slave1_Clock_Gate(uint8_t enable, BL_AHB_Slave1_Type slave1) -{ - /* gate QDEC <=> gate QDEC0 + QDEC1 +QDEC2 + I2S */ - /* gate I2S <=> gate I2S + QDEC2 */ - - uint32_t tmpVal = 0; - - if ((BL_AHB_SLAVE1_GLB == slave1) || (BL_AHB_SLAVE1_TZ2 == slave1) || - (BL_AHB_SLAVE1_CCI == slave1) || (BL_AHB_SLAVE1_L1C == slave1) || - (BL_AHB_SLAVE1_PDS_HBN_AON_HBNRAM == slave1)) { - /* not support */ - return ERROR; - } - - /* gate QDEC and I2S */ - if (BL_AHB_SLAVE1_QDEC == slave1) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - if (enable) { - /* clear bit means clock gate */ - tmpVal &= (~(1 << 0x18)); - tmpVal &= (~(1 << 0x19)); - tmpVal &= (~(1 << 0x1A)); - } else { - /* set bit means clock pass */ - tmpVal |= (1 << 0x18); - tmpVal |= (1 << 0x19); - tmpVal |= (1 << 0x1A); - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); - return SUCCESS; - } - - /* gate KYS */ - if (BL_AHB_SLAVE1_KYS == slave1) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - if (enable) { - /* clear bit means clock gate */ - tmpVal &= (~(1 << 0x1B)); - } else { - /* set bit means clock pass */ - tmpVal |= (1 << 0x1B); - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); - return SUCCESS; - } + * @brief swap JTAG gpio pins function + * + * @param swapSel: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_JTAG_Sig_Swap_Set(uint8_t swapSel) { + uint32_t tmpVal = 0; - /* gate I2S and QDEC2 */ - if (BL_AHB_SLAVE1_I2S == slave1) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - if (enable) { - /* clear bit means clock gate */ - tmpVal &= (~(1 << 0x1A)); - } else { - /* set bit means clock pass */ - tmpVal |= (1 << 0x1A); - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); - return SUCCESS; - } + CHECK_PARAM((swapSel <= 0xFF)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - if (enable) { - /* clear bit means clock gate */ - tmpVal &= (~(1 << slave1)); - } else { - /* set bit means clock pass */ - tmpVal |= (1 << slave1); - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_JTAG_SWAP_SET, swapSel); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief get IPs clock gate value - * - * @param None - * - * @return clock gate value - * -*******************************************************************************/ -uint64_t GLB_PER_Clock_Gate_Status_Get(void) -{ - /* api request from cjy */ - - uint32_t tmpValCfg0 = 0; - uint32_t tmpValCfg1 = 0; - uint32_t tmpValCfg2 = 0; - uint32_t targetBit = 0; - uint64_t targetVal = 0; - - tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); - tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); - for (uint8_t i = 0; i < 64; i++) { - targetBit = 0; - switch (i) { - case GLB_AHB_CLOCK_IP_CPU: - targetBit = tmpValCfg0 & (1 << 0); - break; - case GLB_AHB_CLOCK_IP_SDU: - targetBit = tmpValCfg0 & (1 << 1); - break; - case GLB_AHB_CLOCK_IP_SEC: - targetBit = (tmpValCfg0 & (1 << 2)) && (tmpValCfg1 & (1 << 3)) && (tmpValCfg1 & (1 << 4)); - break; - case GLB_AHB_CLOCK_IP_DMA_0: - targetBit = (tmpValCfg0 & (1 << 3)) && (tmpValCfg1 & (1 << 12)); - break; - case GLB_AHB_CLOCK_IP_DMA_1: - break; - case GLB_AHB_CLOCK_IP_DMA_2: - break; - case GLB_AHB_CLOCK_IP_CCI: - targetBit = tmpValCfg0 & (1 << 4); - break; - case GLB_AHB_CLOCK_IP_RF_TOP: - break; - case GLB_AHB_CLOCK_IP_GPIP: - targetBit = tmpValCfg1 & (1 << 2); - break; - case GLB_AHB_CLOCK_IP_TZC: - targetBit = tmpValCfg1 & (1 << 5); - break; - case GLB_AHB_CLOCK_IP_EF_CTRL: - targetBit = tmpValCfg1 & (1 << 7); - break; - case GLB_AHB_CLOCK_IP_SF_CTRL: - targetBit = tmpValCfg1 & (1 << 11); - break; - case GLB_AHB_CLOCK_IP_EMAC: - targetBit = tmpValCfg1 & (1 << 13); - break; - case GLB_AHB_CLOCK_IP_UART0: - targetBit = tmpValCfg1 & (1 << 16); - break; - case GLB_AHB_CLOCK_IP_UART1: - targetBit = tmpValCfg1 & (1 << 17); - break; - case GLB_AHB_CLOCK_IP_UART2: - break; - case GLB_AHB_CLOCK_IP_UART3: - break; - case GLB_AHB_CLOCK_IP_UART4: - break; - case GLB_AHB_CLOCK_IP_SPI: - targetBit = tmpValCfg1 & (1 << 18); - break; - case GLB_AHB_CLOCK_IP_I2C: - targetBit = tmpValCfg1 & (1 << 19); - break; - case GLB_AHB_CLOCK_IP_PWM: - targetBit = tmpValCfg1 & (1 << 20); - break; - case GLB_AHB_CLOCK_IP_TIMER: - targetBit = tmpValCfg1 & (1 << 21); - break; - case GLB_AHB_CLOCK_IP_IR: - targetBit = tmpValCfg1 & (1 << 22); - break; - case GLB_AHB_CLOCK_IP_CHECKSUM: - targetBit = tmpValCfg1 & (1 << 23); - break; - case GLB_AHB_CLOCK_IP_QDEC: - targetBit = (tmpValCfg1 & (1 << 24)) && (tmpValCfg1 & (1 << 25)) && (tmpValCfg1 & (1 << 26)); - break; - case GLB_AHB_CLOCK_IP_KYS: - targetBit = tmpValCfg1 & (1 << 27); - break; - case GLB_AHB_CLOCK_IP_I2S: - targetBit = tmpValCfg1 & (1 << 26); - break; - case GLB_AHB_CLOCK_IP_USB11: - targetBit = tmpValCfg1 & (1 << 28); - break; - case GLB_AHB_CLOCK_IP_CAM: - targetBit = tmpValCfg1 & (1 << 29); - break; - case GLB_AHB_CLOCK_IP_MJPEG: - targetBit = tmpValCfg1 & (1 << 30); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: - targetBit = (tmpValCfg2 & (1 << 0)) && (tmpValCfg2 & (1 << 4)); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_LP: - break; - case GLB_AHB_CLOCK_IP_ZB_NORMAL: - targetBit = tmpValCfg2 & (1 << 0); - break; - case GLB_AHB_CLOCK_IP_ZB_LP: - break; - case GLB_AHB_CLOCK_IP_WIFI_NORMAL: - break; - case GLB_AHB_CLOCK_IP_WIFI_LP: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: - break; - case GLB_AHB_CLOCK_IP_EMI_MISC: - break; - case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: - break; - case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: - break; - case GLB_AHB_CLOCK_IP_USB20: - break; - case GLB_AHB_CLOCK_IP_MIX2: - break; - case GLB_AHB_CLOCK_IP_AUDIO: - break; - case GLB_AHB_CLOCK_IP_SDH: - break; - default: - break; - } - if (!targetBit) { - targetVal |= ((uint64_t)1 << i); - } - } + * @brief CCI use GPIO 0 1 2 7 + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_CCI_Use_IO_0_1_2_7(uint8_t enable) { + uint32_t tmpVal = 0; - return targetVal; + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_P3_CCI_USE_IO_0_2_7); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_P3_CCI_USE_IO_0_2_7); + } + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief get first 1 from u64, then clear it - * - * @param val: target value - * @param bit: first 1 in bit - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -static BL_Err_Type GLB_Get_And_Clr_First_Set_From_U64(uint64_t *val, uint32_t *bit) -{ - if (!*val) { - return ERROR; - } + * @brief CCI use JTAG pin + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_CCI_Use_Jtag_Pin(uint8_t enable) { + uint32_t tmpVal = 0; - for (uint8_t i = 0; i < 64; i++) { - if ((*val) & ((uint64_t)1 << i)) { - *bit = i; - (*val) &= ~((uint64_t)1 << i); - break; - } - } + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CCI_USE_JTAG_PIN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CCI_USE_JTAG_PIN); + } + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief hold IPs clock - * - * @param ips: GLB_AHB_CLOCK_IP_xxx | GLB_AHB_CLOCK_IP_xxx | ...... - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_PER_Clock_Gate(uint64_t ips) -{ - /* api request from cjy */ - - uint32_t tmpValCfg0 = 0; - uint32_t tmpValCfg1 = 0; - uint32_t tmpValCfg2 = 0; - uint32_t bitfield = 0; - - tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); - tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); - while (ips) { - if (SUCCESS == GLB_Get_And_Clr_First_Set_From_U64(&ips, &bitfield)) { - switch (bitfield) { - case GLB_AHB_CLOCK_IP_CPU: - tmpValCfg0 &= ~(1 << 0); - break; - case GLB_AHB_CLOCK_IP_SDU: - tmpValCfg0 &= ~(1 << 1); - break; - case GLB_AHB_CLOCK_IP_SEC: - tmpValCfg0 &= ~(1 << 2); - tmpValCfg1 &= ~(1 << 3); - tmpValCfg1 &= ~(1 << 4); - break; - case GLB_AHB_CLOCK_IP_DMA_0: - tmpValCfg0 &= ~(1 << 3); - tmpValCfg1 &= ~(1 << 12); - break; - case GLB_AHB_CLOCK_IP_DMA_1: - break; - case GLB_AHB_CLOCK_IP_DMA_2: - break; - case GLB_AHB_CLOCK_IP_CCI: - tmpValCfg0 &= ~(1 << 4); - break; - case GLB_AHB_CLOCK_IP_RF_TOP: - break; - case GLB_AHB_CLOCK_IP_GPIP: - tmpValCfg1 &= ~(1 << 2); - break; - case GLB_AHB_CLOCK_IP_TZC: - tmpValCfg1 &= ~(1 << 5); - break; - case GLB_AHB_CLOCK_IP_EF_CTRL: - tmpValCfg1 &= ~(1 << 7); - break; - case GLB_AHB_CLOCK_IP_SF_CTRL: - tmpValCfg1 &= ~(1 << 11); - break; - case GLB_AHB_CLOCK_IP_EMAC: - tmpValCfg1 &= ~(1 << 13); - break; - case GLB_AHB_CLOCK_IP_UART0: - tmpValCfg1 &= ~(1 << 16); - break; - case GLB_AHB_CLOCK_IP_UART1: - tmpValCfg1 &= ~(1 << 17); - break; - case GLB_AHB_CLOCK_IP_UART2: - break; - case GLB_AHB_CLOCK_IP_UART3: - break; - case GLB_AHB_CLOCK_IP_UART4: - break; - case GLB_AHB_CLOCK_IP_SPI: - tmpValCfg1 &= ~(1 << 18); - break; - case GLB_AHB_CLOCK_IP_I2C: - tmpValCfg1 &= ~(1 << 19); - break; - case GLB_AHB_CLOCK_IP_PWM: - tmpValCfg1 &= ~(1 << 20); - break; - case GLB_AHB_CLOCK_IP_TIMER: - tmpValCfg1 &= ~(1 << 21); - break; - case GLB_AHB_CLOCK_IP_IR: - tmpValCfg1 &= ~(1 << 22); - break; - case GLB_AHB_CLOCK_IP_CHECKSUM: - tmpValCfg1 &= ~(1 << 23); - break; - case GLB_AHB_CLOCK_IP_QDEC: - tmpValCfg1 &= ~(1 << 24); - tmpValCfg1 &= ~(1 << 25); - tmpValCfg1 &= ~(1 << 26); - break; - case GLB_AHB_CLOCK_IP_KYS: - tmpValCfg1 &= ~(1 << 27); - break; - case GLB_AHB_CLOCK_IP_I2S: - tmpValCfg1 &= ~(1 << 26); - break; - case GLB_AHB_CLOCK_IP_USB11: - tmpValCfg1 &= ~(1 << 28); - break; - case GLB_AHB_CLOCK_IP_CAM: - tmpValCfg1 &= ~(1 << 29); - break; - case GLB_AHB_CLOCK_IP_MJPEG: - tmpValCfg1 &= ~(1 << 30); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: - tmpValCfg2 &= ~(1 << 0); - tmpValCfg2 &= ~(1 << 4); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_LP: - break; - case GLB_AHB_CLOCK_IP_ZB_NORMAL: - tmpValCfg2 &= ~(1 << 0); - break; - case GLB_AHB_CLOCK_IP_ZB_LP: - break; - case GLB_AHB_CLOCK_IP_WIFI_NORMAL: - break; - case GLB_AHB_CLOCK_IP_WIFI_LP: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: - break; - case GLB_AHB_CLOCK_IP_EMI_MISC: - break; - case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: - break; - case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: - break; - case GLB_AHB_CLOCK_IP_USB20: - break; - case GLB_AHB_CLOCK_IP_MIX2: - break; - case GLB_AHB_CLOCK_IP_AUDIO: - break; - case GLB_AHB_CLOCK_IP_SDH: - break; - default: - break; - } - } - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG0, tmpValCfg0); - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpValCfg1); - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG2, tmpValCfg2); - - return SUCCESS; -} + * @brief swap SPI0 MOSI with MISO + * + * @param newState: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Swap_SPI_0_MOSI_With_MISO(BL_Fun_Type newState) { + uint32_t tmpVal = 0; -/****************************************************************************/ /** - * @brief release IPs clock - * - * @param ips: GLB_AHB_CLOCK_IP_xxx | GLB_AHB_CLOCK_IP_xxx | ...... - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_PER_Clock_UnGate(uint64_t ips) -{ - /* api request from cjy */ - - uint32_t tmpValCfg0 = 0; - uint32_t tmpValCfg1 = 0; - uint32_t tmpValCfg2 = 0; - uint32_t bitfield = 0; - - tmpValCfg0 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG0); - tmpValCfg1 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG1); - tmpValCfg2 = BL_RD_REG(GLB_BASE, GLB_CGEN_CFG2); - while (ips) { - if (SUCCESS == GLB_Get_And_Clr_First_Set_From_U64(&ips, &bitfield)) { - switch (bitfield) { - case GLB_AHB_CLOCK_IP_CPU: - tmpValCfg0 |= (1 << 0); - break; - case GLB_AHB_CLOCK_IP_SDU: - tmpValCfg0 |= (1 << 1); - break; - case GLB_AHB_CLOCK_IP_SEC: - tmpValCfg0 |= (1 << 2); - tmpValCfg1 |= (1 << 3); - tmpValCfg1 |= (1 << 4); - break; - case GLB_AHB_CLOCK_IP_DMA_0: - tmpValCfg0 |= (1 << 3); - tmpValCfg1 |= (1 << 12); - break; - case GLB_AHB_CLOCK_IP_DMA_1: - break; - case GLB_AHB_CLOCK_IP_DMA_2: - break; - case GLB_AHB_CLOCK_IP_CCI: - tmpValCfg0 |= (1 << 4); - break; - case GLB_AHB_CLOCK_IP_RF_TOP: - break; - case GLB_AHB_CLOCK_IP_GPIP: - tmpValCfg1 |= (1 << 2); - break; - case GLB_AHB_CLOCK_IP_TZC: - tmpValCfg1 |= (1 << 5); - break; - case GLB_AHB_CLOCK_IP_EF_CTRL: - tmpValCfg1 |= (1 << 7); - break; - case GLB_AHB_CLOCK_IP_SF_CTRL: - tmpValCfg1 |= (1 << 11); - break; - case GLB_AHB_CLOCK_IP_EMAC: - tmpValCfg1 |= (1 << 13); - break; - case GLB_AHB_CLOCK_IP_UART0: - tmpValCfg1 |= (1 << 16); - break; - case GLB_AHB_CLOCK_IP_UART1: - tmpValCfg1 |= (1 << 17); - break; - case GLB_AHB_CLOCK_IP_UART2: - break; - case GLB_AHB_CLOCK_IP_UART3: - break; - case GLB_AHB_CLOCK_IP_UART4: - break; - case GLB_AHB_CLOCK_IP_SPI: - tmpValCfg1 |= (1 << 18); - break; - case GLB_AHB_CLOCK_IP_I2C: - tmpValCfg1 |= (1 << 19); - break; - case GLB_AHB_CLOCK_IP_PWM: - tmpValCfg1 |= (1 << 20); - break; - case GLB_AHB_CLOCK_IP_TIMER: - tmpValCfg1 |= (1 << 21); - break; - case GLB_AHB_CLOCK_IP_IR: - tmpValCfg1 |= (1 << 22); - break; - case GLB_AHB_CLOCK_IP_CHECKSUM: - tmpValCfg1 |= (1 << 23); - break; - case GLB_AHB_CLOCK_IP_QDEC: - tmpValCfg1 |= (1 << 24); - tmpValCfg1 |= (1 << 25); - tmpValCfg1 |= (1 << 26); - break; - case GLB_AHB_CLOCK_IP_KYS: - tmpValCfg1 |= (1 << 27); - break; - case GLB_AHB_CLOCK_IP_I2S: - tmpValCfg1 |= (1 << 26); - break; - case GLB_AHB_CLOCK_IP_USB11: - tmpValCfg1 |= (1 << 28); - break; - case GLB_AHB_CLOCK_IP_CAM: - tmpValCfg1 |= (1 << 29); - break; - case GLB_AHB_CLOCK_IP_MJPEG: - tmpValCfg1 |= (1 << 30); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_NORMAL: - tmpValCfg2 |= (1 << 0); - tmpValCfg2 |= (1 << 4); - break; - case GLB_AHB_CLOCK_IP_BT_BLE_LP: - break; - case GLB_AHB_CLOCK_IP_ZB_NORMAL: - tmpValCfg2 |= (1 << 0); - break; - case GLB_AHB_CLOCK_IP_ZB_LP: - break; - case GLB_AHB_CLOCK_IP_WIFI_NORMAL: - break; - case GLB_AHB_CLOCK_IP_WIFI_LP: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_NORMAL: - break; - case GLB_AHB_CLOCK_IP_BT_BLE_2_LP: - break; - case GLB_AHB_CLOCK_IP_EMI_MISC: - break; - case GLB_AHB_CLOCK_IP_PSRAM0_CTRL: - break; - case GLB_AHB_CLOCK_IP_PSRAM1_CTRL: - break; - case GLB_AHB_CLOCK_IP_USB20: - break; - case GLB_AHB_CLOCK_IP_MIX2: - break; - case GLB_AHB_CLOCK_IP_AUDIO: - break; - case GLB_AHB_CLOCK_IP_SDH: - break; - default: - break; - } - } - } - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG0, tmpValCfg0); - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG1, tmpValCfg1); - BL_WR_REG(GLB_BASE, GLB_CGEN_CFG2, tmpValCfg2); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_SPI_0_SWAP, newState); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief BMX init - * - * @param BmxCfg: BMX config - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_BMX_Init(BMX_Cfg_Type *BmxCfg) -{ - uint32_t tmpVal = 0; + * @brief Select SPI_0 act mode + * + * @param mod: SPI work mode + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_SPI_0_ACT_MOD_Sel(GLB_SPI_PAD_ACT_AS_Type mod) { + uint32_t tmpVal; - CHECK_PARAM((BmxCfg->timeoutEn) <= 0xF); + CHECK_PARAM(IS_GLB_SPI_PAD_ACT_AS_TYPE(mod)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_TIMEOUT_EN, BmxCfg->timeoutEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_EN, BmxCfg->errEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_BMX_ARB_MODE, BmxCfg->arbMod); - BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); - -#ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(BMX_ERR_IRQn, BMX_ERR_IRQHandler); - Interrupt_Handler_Register(BMX_TO_IRQn, BMX_TO_IRQHandler); -#endif + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_SPI_0_MASTER_MODE, mod); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief BMX address monitor enable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_BMX_Addr_Monitor_Enable(void) -{ - uint32_t tmpVal = 0; + * @brief use internal flash + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Select_Internal_Flash(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BMX_ERR_ADDR_DIS); - BL_WR_REG(GLB_BASE, GLB_BMX_CFG2, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x3f); + BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief BMX address monitor disable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_BMX_Addr_Monitor_Disable(void) -{ - uint32_t tmpVal = 0; + * @brief use external flash + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Select_External_Flash(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BMX_ERR_ADDR_DIS); - BL_WR_REG(GLB_BASE, GLB_BMX_CFG2, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00); + BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief BMX bus error response enable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_BMX_BusErrResponse_Enable(void) -{ - uint32_t tmpVal = 0; + * @brief Deswap internal flash pin + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Deswap_Flash_Pin(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_BMX_ERR_EN); - BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief BMX bus error response disable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_BMX_BusErrResponse_Disable(void) -{ - uint32_t tmpVal = 0; + * @brief Swap internal flash CS and IO2 pin + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_CS_IO2_Pin(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG1); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_BMX_ERR_EN); - BL_WR_REG(GLB_BASE, GLB_BMX_CFG1, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief Get BMX error status - * - * @param errType: BMX error status type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type GLB_BMX_Get_Status(BMX_BUS_ERR_Type errType) -{ - uint32_t tmpVal = 0; + * @brief Swap internal flash IO3 and IO0 pin + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_IO0_IO3_Pin(void) { + uint32_t tmpVal; - CHECK_PARAM(IS_BMX_BUS_ERR_TYPE(errType)); + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - tmpVal = BL_RD_REG(GLB_BASE, GLB_BMX_CFG2); - if (errType == BMX_BUS_ERR_TRUSTZONE_DECODE) { - return BL_GET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_TZ) ? SET : RESET; - } else { - return BL_GET_REG_BITS_VAL(tmpVal, GLB_BMX_ERR_DEC) ? SET : RESET; - } + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief Get BMX error address - * - * @param None - * - * @return NP BMX error address - * -*******************************************************************************/ -uint32_t GLB_BMX_Get_Err_Addr(void) -{ - return BL_RD_REG(GLB_BASE, GLB_BMX_ERR_ADDR); + * @brief Swap internal flash IO3 and IO0 pin + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_Pin(void) { + /*To be removed*/ + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief BMX error interrupt callback install - * - * @param intType: BMX error interrupt type - * @param cbFun: callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type BMX_ERR_INT_Callback_Install(BMX_ERR_INT_Type intType, intCallback_Type *cbFun) -{ - CHECK_PARAM(IS_BMX_ERR_INT_TYPE(intType)); + * @brief Select internal psram + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_TCM_SECTION GLB_Select_Internal_PSram(void) { + uint32_t tmpVal; - glbBmxErrIntCbfArra[intType] = cbFun; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00); + BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief BMX ERR interrupt IRQ handler - * - * @param None - * - * @return None - * -*******************************************************************************/ -#ifndef BFLB_USE_HAL_DRIVER -void BMX_ERR_IRQHandler(void) -{ - BMX_ERR_INT_Type intType; - - for (intType = BMX_ERR_INT_ERR; intType < BMX_ERR_INT_ALL; intType++) { - if (glbBmxErrIntCbfArra[intType] != NULL) { - glbBmxErrIntCbfArra[intType](); - } - } + * @brief set PDM clock + * + * @param enable: Enable or disable PDM clock + * @param div: clock divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_PDM_CLK(uint8_t enable, uint8_t div) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); + BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_PDM0_CLK_DIV, div); + BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); + } + BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set MTimer clock + * + * @param enable: enable or disable MTimer clock + * @param clkSel: clock selection + * @param div: divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_MTimer_CLK(uint8_t enable, GLB_MTIMER_CLK_Type clkSel, uint32_t div) { + uint32_t tmpVal; + + CHECK_PARAM(IS_GLB_MTIMER_CLK_TYPE(clkSel)); + CHECK_PARAM((div <= 0x1FFFF)); + + /* disable MTimer clock first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CPU_RTC_EN); + BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CPU_RTC_SEL, clkSel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CPU_RTC_DIV, div); + BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CPU_RTC_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CPU_RTC_EN); + } + BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); - while (1) { - //MSG("BMX_ERR_IRQHandler\r\n"); - BL702_Delay_MS(1000); - } + return SUCCESS; } -#endif /****************************************************************************/ /** - * @brief BMX timeout interrupt callback install - * - * @param intType: BMX timeout interrupt type - * @param cbFun: callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type BMX_TIMEOUT_INT_Callback_Install(BMX_TO_INT_Type intType, intCallback_Type *cbFun) -{ - CHECK_PARAM(IS_BMX_TO_INT_TYPE(intType)); + * @brief set ADC clock + * + * @param enable: enable or disable ADC clock + * @param clkSel: ADC clock selection + * @param div: divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_ADC_CLK(uint8_t enable, GLB_ADC_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal; - glbBmxToIntCbfArra[intType] = cbFun; + CHECK_PARAM(IS_GLB_ADC_CLK_TYPE(clkSel)); - return SUCCESS; -} + /* disable ADC clock first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); + BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); -/****************************************************************************/ /** - * @brief BMX Time Out interrupt IRQ handler - * - * @param None - * - * @return None - * -*******************************************************************************/ -#ifndef BFLB_USE_HAL_DRIVER -void BMX_TO_IRQHandler(void) -{ - BMX_TO_INT_Type intType; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPADC_32M_CLK_DIV, div); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPADC_32M_CLK_SEL, clkSel); + BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); - for (intType = BMX_TO_INT_TIMEOUT; intType < BMX_TO_INT_ALL; intType++) { - if (glbBmxToIntCbfArra[intType] != NULL) { - glbBmxToIntCbfArra[intType](); - } - } + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); + } + BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); - while (1) { - //MSG("BMX_TO_IRQHandler\r\n"); - BL702_Delay_MS(1000); - } + return SUCCESS; } -#endif /****************************************************************************/ /** - * @brief set sram_ret value - * - * @param value: value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_SRAM_RET(uint32_t value) -{ - BL_WR_REG(GLB_BASE, GLB_SRAM_RET, value); + * @brief set DAC clock + * + * @param enable: enable frequency divider or not + * @param clkSel: ADC clock selection + * @param div: src divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_DAC_CLK(uint8_t enable, GLB_DAC_CLK_Type clkSel, uint8_t div) { + uint32_t tmpVal; - return SUCCESS; + CHECK_PARAM(IS_GLB_DAC_CLK_TYPE(clkSel)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_COMP); + + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_CLK_SRC_SEL, clkSel); + + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_DIV, div); + + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); + } + + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief select DIG clock source + * + * @param clkSel: DIG clock selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_DIG_CLK_Sel(GLB_DIG_CLK_Type clkSel) { + uint32_t tmpVal; + uint32_t dig512kEn; + uint32_t dig32kEn; + + /* disable DIG512K and DIG32K clock first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + dig512kEn = BL_GET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_EN); + dig32kEn = BL_GET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_EN); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_CLK_SRC_SEL, clkSel); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + /* repristinate DIG512K and DIG32K clock */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_EN, dig512kEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_EN, dig32kEn); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set DIG 512K clock + * + * @param enable: enable or disable DIG 512K clock + * @param compensation: enable or disable DIG 512K clock compensation + * @param div: divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_DIG_512K_CLK(uint8_t enable, uint8_t compensation, uint8_t div) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + if (compensation) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_COMP); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_COMP); + } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_DIV, div); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); + } + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set DIG 32K clock + * + * @param enable: enable or disable DIG 32K clock + * @param compensation: enable or disable DIG 32K clock compensation + * @param div: divider + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_DIG_32K_CLK(uint8_t enable, uint8_t compensation, uint8_t div) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + if (compensation) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_32K_COMP); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_COMP); + } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_DIV, div); + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_32K_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_EN); + } + BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief set BT coex signal + * + * @param enable: ENABLE or DISABLE, if enable, the AP JTAG will be replaced by BT Coex Signal + * @param bandWidth: BT Bandwidth + * @param pti: BT Packet Traffic Information + * @param channel: BT Channel + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_BT_Coex_Signal(uint8_t enable, GLB_BT_BANDWIDTH_Type bandWidth, uint8_t pti, uint8_t channel) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_BT_BANDWIDTH_TYPE(bandWidth)); + CHECK_PARAM((pti <= 0xF)); + CHECK_PARAM((channel <= 78)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_BW, bandWidth); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_PTI, pti); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_CHANNEL, channel); + BL_WR_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL, tmpVal); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL); + if (enable) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EN_GPIO_BT_COEX, 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EN_GPIO_BT_COEX, 0); + } + BL_WR_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Select UART signal function + * + * @param sig: UART signal + * @param fun: UART function + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_UART_Fun_Sel(GLB_UART_SIG_Type sig, GLB_UART_SIG_FUN_Type fun) { + uint32_t sig_pos = 0; + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_UART_SIG_TYPE(sig)); + CHECK_PARAM(IS_GLB_UART_SIG_FUN_TYPE(fun)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_UART_SIG_SEL_0); + sig_pos = (sig * 4); + /* Clear original val */ + tmpVal &= (~(0xf << sig_pos)); + /* Set new value */ + tmpVal |= (fun << sig_pos); + BL_WR_REG(GLB_BASE, GLB_UART_SIG_SEL_0, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief power off DLL + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_Off_DLL(void) { + uint32_t tmpVal = 0; + + /* GLB->dll.BF.ppu_dll = 0; */ + /* GLB->dll.BF.pu_dll = 0; */ + /* GLB->dll.BF.dll_reset = 1; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PPU_DLL, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_DLL, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_RESET, 1); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief get sram_ret value - * - * @param None - * - * @return value - * -*******************************************************************************/ -uint32_t GLB_Get_SRAM_RET(void) -{ - return BL_RD_REG(GLB_BASE, GLB_SRAM_RET); + * @brief power on DLL + * + * @param xtalType: DLL xtal type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_On_DLL(GLB_DLL_XTAL_Type xtalType) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); + + /* GLB->dll.BF.dll_refclk_sel = XXX; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + switch (xtalType) { + case GLB_DLL_XTAL_NONE: + return ERROR; + case GLB_DLL_XTAL_32M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_REFCLK_SEL, 0); + break; + case GLB_DLL_XTAL_RC32M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_REFCLK_SEL, 1); + break; + default: + break; + } + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + /* GLB->dll.BF.dll_prechg_sel = 1; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_PRECHG_SEL, 1); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + /* GLB->dll.BF.ppu_dll = 1; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PPU_DLL, 1); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + BL702_Delay_US(2); + + /* GLB->dll.BF.pu_dll = 1; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_DLL, 1); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + BL702_Delay_US(2); + + /* GLB->dll.BF.dll_reset = 0; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_RESET, 0); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + /* delay for settling */ + BL702_Delay_US(5); + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief set sram_slp value - * - * @param value: value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_SRAM_SLP(uint32_t value) -{ - BL_WR_REG(GLB_BASE, GLB_SRAM_SLP, value); + * @brief enable all DLL output clock + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Enable_DLL_All_Clks(void) { + uint32_t tmpVal = 0; - return SUCCESS; -} + /* GLB->dll.WORD = GLB->dll.WORD | 0x000000f8; include 288m and mmdiv */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 1); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); -/****************************************************************************/ /** - * @brief get sram_slp value - * - * @param None - * - * @return value - * -*******************************************************************************/ -uint32_t GLB_Get_SRAM_SLP(void) -{ - return BL_RD_REG(GLB_BASE, GLB_SRAM_SLP); + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief set sram_param value - * - * @param value: value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_SRAM_PARM(uint32_t value) -{ - BL_WR_REG(GLB_BASE, GLB_SRAM_PARM, value); + * @brief enable one of DLL output clock + * + * @param dllClk: None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Enable_DLL_Clk(GLB_DLL_CLK_Type dllClk) { + uint32_t tmpVal = 0; - return SUCCESS; + CHECK_PARAM(IS_GLB_DLL_CLK_TYPE(dllClk)); + + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + switch (dllClk) { + case GLB_DLL_CLK_57P6M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 1); + break; + case GLB_DLL_CLK_96M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 1); + break; + case GLB_DLL_CLK_144M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 1); + break; + case GLB_DLL_CLK_288M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 1); + break; + case GLB_DLL_CLK_MMDIV: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 1); + break; + default: + break; + } + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief get sram_parm value - * - * @param None - * - * @return value - * -*******************************************************************************/ -uint32_t GLB_Get_SRAM_PARM(void) -{ - return BL_RD_REG(GLB_BASE, GLB_SRAM_PARM); + * @brief disable all DLL output clock + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Disable_DLL_All_Clks(void) { + uint32_t tmpVal = 0; + + /* GLB->dll.WORD = GLB->dll.WORD & ~0x000000f8; */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 0); + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); + + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief select EM type - * - * @param emType: EM type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_EM_Sel(GLB_EM_Type emType) -{ - uint32_t tmpVal = 0; + * @brief disable one of DLL output clock + * + * @param dllClk: None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +#ifndef BFLB_USE_ROM_DRIVER +__WEAK +BL_Err_Type ATTR_CLOCK_SECTION GLB_Disable_DLL_Clk(GLB_DLL_CLK_Type dllClk) { + uint32_t tmpVal = 0; - CHECK_PARAM(IS_GLB_EM_TYPE(emType)); + CHECK_PARAM(IS_GLB_DLL_CLK_TYPE(dllClk)); - tmpVal = BL_RD_REG(GLB_BASE, GLB_SEAM_MISC); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EM_SEL, emType); - BL_WR_REG(GLB_BASE, GLB_SEAM_MISC, tmpVal); + tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); + switch (dllClk) { + case GLB_DLL_CLK_57P6M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 0); + break; + case GLB_DLL_CLK_96M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 0); + break; + case GLB_DLL_CLK_144M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 0); + break; + case GLB_DLL_CLK_288M: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 0); + break; + case GLB_DLL_CLK_MMDIV: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 0); + break; + default: + break; + } + BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - return SUCCESS; + return SUCCESS; } +#endif /****************************************************************************/ /** - * @brief select pin as EMAC or CAM - * - * @param pinType: pin type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_SWAP_EMAC_CAM_Pin(GLB_EMAC_CAM_PIN_Type pinType) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_EMAC_CAM_PIN_TYPE(pinType)); + * @brief Select ir rx gpio (gpio17~gpio31) + * + * @param gpio: IR gpio selected + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_RX_GPIO_Sel(GLB_GPIO_Type gpio) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PIN_SEL_EMAC_CAM, pinType); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + /* Select gpio between gpio17 and gpio31 */ + if (gpio > 16 && gpio < 32) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_IR_RX_GPIO_SEL, gpio - 16); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief EXT_RST PAD SMT - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_Ext_Rst_Smt(uint8_t enable) -{ - uint32_t tmpVal = 0; + * @brief Enable ir led driver + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_LED_Driver_Enable(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_EXT_RST_SMT); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_EXT_RST_SMT); - } - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + /* Enable led driver */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_PU_LEDDRV); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Key Scan Column Drive - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_Kys_Drv_Col(uint8_t enable) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_KYS_DRV_VAL); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_KYS_DRV_VAL); - } - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief swap UART gpio pins sig function - * - * @param swapSel: UART swap set gpio pins selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_UART_Sig_Swap_Set(uint8_t swapSel) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM((swapSel <= 0xF)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_UART_SWAP_SET, swapSel); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief swap JTAG gpio pins function - * - * @param swapSel: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_JTAG_Sig_Swap_Set(uint8_t swapSel) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM((swapSel <= 0xFF)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_JTAG_SWAP_SET, swapSel); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief CCI use GPIO 0 1 2 7 - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_CCI_Use_IO_0_1_2_7(uint8_t enable) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_P3_CCI_USE_IO_0_2_7); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_P3_CCI_USE_IO_0_2_7); - } - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief CCI use JTAG pin - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_CCI_Use_Jtag_Pin(uint8_t enable) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_CCI_USE_JTAG_PIN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_CCI_USE_JTAG_PIN); - } - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief swap SPI0 MOSI with MISO - * - * @param newState: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Swap_SPI_0_MOSI_With_MISO(BL_Fun_Type newState) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_SPI_0_SWAP, newState); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Select SPI_0 act mode - * - * @param mod: SPI work mode - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_SPI_0_ACT_MOD_Sel(GLB_SPI_PAD_ACT_AS_Type mod) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_SPI_PAD_ACT_AS_TYPE(mod)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_SPI_0_MASTER_MODE, mod); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief use internal flash - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Select_Internal_Flash(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x3f); - BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief use external flash - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Select_External_Flash(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00); - BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Deswap internal flash pin - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Deswap_Flash_Pin(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Swap internal flash CS and IO2 pin - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_CS_IO2_Pin(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Swap internal flash IO3 and IO0 pin - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_IO0_IO3_Pin(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Swap internal flash IO3 and IO0 pin - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_Pin(void) -{ - /*To be removed*/ - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Select internal psram - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_TCM_SECTION GLB_Select_Internal_PSram(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO, 0x00); - BL_WR_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief set PDM clock - * - * @param enable: Enable or disable PDM clock - * @param div: clock divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_PDM_CLK(uint8_t enable, uint8_t div) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); - BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_PDM0_CLK_DIV, div); - BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PDM_CLK_CTRL); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_PDM0_CLK_EN); - } - BL_WR_REG(GLB_BASE, GLB_PDM_CLK_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set MTimer clock - * - * @param enable: enable or disable MTimer clock - * @param clkSel: clock selection - * @param div: divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_MTimer_CLK(uint8_t enable, GLB_MTIMER_CLK_Type clkSel, uint32_t div) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_MTIMER_CLK_TYPE(clkSel)); - CHECK_PARAM((div <= 0x1FFFF)); - - /* disable MTimer clock first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CPU_RTC_EN); - BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CPU_RTC_SEL, clkSel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_CPU_RTC_DIV, div); - BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_CPU_CLK_CFG); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CPU_RTC_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CPU_RTC_EN); - } - BL_WR_REG(GLB_BASE, GLB_CPU_CLK_CFG, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set ADC clock - * - * @param enable: enable or disable ADC clock - * @param clkSel: ADC clock selection - * @param div: divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_ADC_CLK(uint8_t enable, GLB_ADC_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_ADC_CLK_TYPE(clkSel)); - - /* disable ADC clock first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); - BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPADC_32M_CLK_DIV, div); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_GPADC_32M_CLK_SEL, clkSel); - BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_GPADC_32M_DIV_EN); - } - BL_WR_REG(GLB_BASE, GLB_GPADC_32M_SRC_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set DAC clock - * - * @param enable: enable frequency divider or not - * @param clkSel: ADC clock selection - * @param div: src divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_DAC_CLK(uint8_t enable, GLB_DAC_CLK_Type clkSel, uint8_t div) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_GLB_DAC_CLK_TYPE(clkSel)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_COMP); - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_CLK_SRC_SEL, clkSel); - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_DIV, div); - - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); - } - - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief select DIG clock source - * - * @param clkSel: DIG clock selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_DIG_CLK_Sel(GLB_DIG_CLK_Type clkSel) -{ - uint32_t tmpVal; - uint32_t dig512kEn; - uint32_t dig32kEn; - - /* disable DIG512K and DIG32K clock first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - dig512kEn = BL_GET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_EN); - dig32kEn = BL_GET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_EN); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_CLK_SRC_SEL, clkSel); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - /* repristinate DIG512K and DIG32K clock */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_EN, dig512kEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_EN, dig32kEn); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set DIG 512K clock - * - * @param enable: enable or disable DIG 512K clock - * @param compensation: enable or disable DIG 512K clock compensation - * @param div: divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_DIG_512K_CLK(uint8_t enable, uint8_t compensation, uint8_t div) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - if (compensation) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_COMP); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_COMP); - } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_512K_DIV, div); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_512K_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_512K_EN); - } - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set DIG 32K clock - * - * @param enable: enable or disable DIG 32K clock - * @param compensation: enable or disable DIG 32K clock compensation - * @param div: divider - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_DIG_32K_CLK(uint8_t enable, uint8_t compensation, uint8_t div) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - if (compensation) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_32K_COMP); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_COMP); - } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DIG_32K_DIV, div); - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_DIG_32K_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_DIG_32K_EN); - } - BL_WR_REG(GLB_BASE, GLB_DIG32K_WAKEUP_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief set BT coex signal - * - * @param enable: ENABLE or DISABLE, if enable, the AP JTAG will be replaced by BT Coex Signal - * @param bandWidth: BT Bandwidth - * @param pti: BT Packet Traffic Information - * @param channel: BT Channel - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_BT_Coex_Signal(uint8_t enable, GLB_BT_BANDWIDTH_Type bandWidth, uint8_t pti, uint8_t channel) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_BT_BANDWIDTH_TYPE(bandWidth)); - CHECK_PARAM((pti <= 0xF)); - CHECK_PARAM((channel <= 78)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_BW, bandWidth); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_PTI, pti); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_COEX_BT_CHANNEL, channel); - BL_WR_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL, tmpVal); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL); - if (enable) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EN_GPIO_BT_COEX, 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_EN_GPIO_BT_COEX, 0); - } - BL_WR_REG(GLB_BASE, GLB_WIFI_BT_COEX_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Select UART signal function - * - * @param sig: UART signal - * @param fun: UART function - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_UART_Fun_Sel(GLB_UART_SIG_Type sig, GLB_UART_SIG_FUN_Type fun) -{ - uint32_t sig_pos = 0; - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_UART_SIG_TYPE(sig)); - CHECK_PARAM(IS_GLB_UART_SIG_FUN_TYPE(fun)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_UART_SIG_SEL_0); - sig_pos = (sig * 4); - /* Clear original val */ - tmpVal &= (~(0xf << sig_pos)); - /* Set new value */ - tmpVal |= (fun << sig_pos); - BL_WR_REG(GLB_BASE, GLB_UART_SIG_SEL_0, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief power off DLL - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_Off_DLL(void) -{ - uint32_t tmpVal = 0; - - /* GLB->dll.BF.ppu_dll = 0; */ - /* GLB->dll.BF.pu_dll = 0; */ - /* GLB->dll.BF.dll_reset = 1; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PPU_DLL, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_DLL, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_RESET, 1); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief power on DLL - * - * @param xtalType: DLL xtal type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Power_On_DLL(GLB_DLL_XTAL_Type xtalType) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_DLL_XTAL_TYPE(xtalType)); - - /* GLB->dll.BF.dll_refclk_sel = XXX; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - switch (xtalType) { - case GLB_DLL_XTAL_NONE: - return ERROR; - case GLB_DLL_XTAL_32M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_REFCLK_SEL, 0); - break; - case GLB_DLL_XTAL_RC32M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_REFCLK_SEL, 1); - break; - default: - break; - } - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - /* GLB->dll.BF.dll_prechg_sel = 1; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_PRECHG_SEL, 1); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - /* GLB->dll.BF.ppu_dll = 1; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PPU_DLL, 1); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - BL702_Delay_US(2); - - /* GLB->dll.BF.pu_dll = 1; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_PU_DLL, 1); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - BL702_Delay_US(2); - - /* GLB->dll.BF.dll_reset = 0; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_RESET, 0); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - /* delay for settling */ - BL702_Delay_US(5); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief enable all DLL output clock - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Enable_DLL_All_Clks(void) -{ - uint32_t tmpVal = 0; - - /* GLB->dll.WORD = GLB->dll.WORD | 0x000000f8; include 288m and mmdiv */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 1); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief enable one of DLL output clock - * - * @param dllClk: None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Enable_DLL_Clk(GLB_DLL_CLK_Type dllClk) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_DLL_CLK_TYPE(dllClk)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - switch (dllClk) { - case GLB_DLL_CLK_57P6M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 1); - break; - case GLB_DLL_CLK_96M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 1); - break; - case GLB_DLL_CLK_144M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 1); - break; - case GLB_DLL_CLK_288M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 1); - break; - case GLB_DLL_CLK_MMDIV: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 1); - break; - default: - break; - } - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief disable all DLL output clock - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Disable_DLL_All_Clks(void) -{ - uint32_t tmpVal = 0; - - /* GLB->dll.WORD = GLB->dll.WORD & ~0x000000f8; */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 0); - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief disable one of DLL output clock - * - * @param dllClk: None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -#ifndef BFLB_USE_ROM_DRIVER -__WEAK -BL_Err_Type ATTR_CLOCK_SECTION GLB_Disable_DLL_Clk(GLB_DLL_CLK_Type dllClk) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_GLB_DLL_CLK_TYPE(dllClk)); - - tmpVal = BL_RD_REG(GLB_BASE, GLB_DLL); - switch (dllClk) { - case GLB_DLL_CLK_57P6M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_57P6M_EN, 0); - break; - case GLB_DLL_CLK_96M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_96M_EN, 0); - break; - case GLB_DLL_CLK_144M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_144M_EN, 0); - break; - case GLB_DLL_CLK_288M: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_288M_EN, 0); - break; - case GLB_DLL_CLK_MMDIV: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_DLL_CLK_MMDIV_EN, 0); - break; - default: - break; - } - BL_WR_REG(GLB_BASE, GLB_DLL, tmpVal); - - return SUCCESS; -} -#endif - -/****************************************************************************/ /** - * @brief Select ir rx gpio (gpio17~gpio31) - * - * @param gpio: IR gpio selected - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_RX_GPIO_Sel(GLB_GPIO_Type gpio) -{ - uint32_t tmpVal = 0; - - /* Select gpio between gpio17 and gpio31 */ - if (gpio > 16 && gpio < 32) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_IR_RX_GPIO_SEL, gpio - 16); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Enable ir led driver - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_LED_Driver_Enable(void) -{ - uint32_t tmpVal = 0; - - /* Enable led driver */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_PU_LEDDRV); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Disable ir led driver - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_LED_Driver_Disable(void) -{ - uint32_t tmpVal = 0; - - /* Disable led driver */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_PU_LEDDRV); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Enable ir led driver gpio output(gpio 22 or 23) - * - * @param gpio: IR gpio selected - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_LED_Driver_Output_Enable(GLB_GPIO_Type gpio) -{ - uint32_t tmpVal = 0; - - if (gpio == GLB_GPIO_PIN_22) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) | 1); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - } else if (gpio == GLB_GPIO_PIN_23) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) | 2); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - } + * @brief Disable ir led driver + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_LED_Driver_Disable(void) { + uint32_t tmpVal = 0; - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Disable ir led driver gpio output(gpio 22 or 23) - * - * @param gpio: IR gpio selected - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_LED_Driver_Output_Disable(GLB_GPIO_Type gpio) -{ - uint32_t tmpVal = 0; - - if (gpio == GLB_GPIO_PIN_22) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) & ~1); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - } else if (gpio == GLB_GPIO_PIN_23) { - tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) & ~2); - BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - } + /* Disable led driver */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_PU_LEDDRV); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set ir led driver ibias - * - * @param ibias: Ibias value,0x0:0mA~0xf:120mA,8mA/step - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_IR_LED_Driver_Ibias(uint8_t ibias) -{ - uint32_t tmpVal = 0; + * @brief Enable ir led driver gpio output(gpio 22 or 23) + * + * @param gpio: IR gpio selected + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_LED_Driver_Output_Enable(GLB_GPIO_Type gpio) { + uint32_t tmpVal = 0; - /* Set driver ibias */ + if (gpio == GLB_GPIO_PIN_22) { tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_IBIAS, ibias & 0xF); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) | 1); BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + } else if (gpio == GLB_GPIO_PIN_23) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) | 2); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief GPIO initialization - * - * @param cfg: GPIO configuration - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Init(GLB_GPIO_Cfg_Type *cfg) -{ - uint8_t gpioPin = cfg->gpioPin; - uint8_t realPin; - uint32_t *pOut; - uint32_t pos; - uint32_t tmpOut; - uint32_t tmpVal; - - /* drive strength(drive) = 0 <=> 8.0mA @ 3.3V */ - /* drive strength(drive) = 1 <=> 9.6mA @ 3.3V */ - /* drive strength(drive) = 2 <=> 11.2mA @ 3.3V */ - /* drive strength(drive) = 3 <=> 12.8mA @ 3.3V */ - - pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); - pos = gpioPin % 32; - tmpOut = *pOut; - - /* Disable output anyway*/ - tmpOut &= (~(1 << pos)); - *pOut = tmpOut; - - realPin = gpioPin; - /* sf pad use exclusive ie/pd/pu/drive/smtctrl */ - if (gpioPin >= 23 && gpioPin <= 28) { - if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { - realPin += 9; - } - } - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4); - if (realPin % 2 == 0) { - if (cfg->gpioMode != GPIO_MODE_ANALOG) { - /* not analog mode */ - - /* Set input or output */ - if (cfg->gpioMode == GPIO_MODE_OUTPUT) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); - tmpOut |= (1 << pos); - } else { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); - } - - /* Set pull up or down */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); - if (cfg->pullType == GPIO_PULL_UP) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); - } else if (cfg->pullType == GPIO_PULL_DOWN) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); - } - } else { - /* analog mode */ - - /* clear ie && oe */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); - tmpOut &= ~(1 << pos); - - /* clear pu && pd */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); - } + * @brief Disable ir led driver gpio output(gpio 22 or 23) + * + * @param gpio: IR gpio selected + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_LED_Driver_Output_Disable(GLB_GPIO_Type gpio) { + uint32_t tmpVal = 0; - /* set drive && smt && func */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_DRV, cfg->drive); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_SMT, cfg->smtCtrl); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL, cfg->gpioFun); + if (gpio == GLB_GPIO_PIN_22) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) & ~1); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + } else if (gpio == GLB_GPIO_PIN_23) { + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN, BL_GET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_OUT_EN) & ~2); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Set ir led driver ibias + * + * @param ibias: Ibias value,0x0:0mA~0xf:120mA,8mA/step + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_IR_LED_Driver_Ibias(uint8_t ibias) { + uint32_t tmpVal = 0; + + /* Set driver ibias */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_LED_DRIVER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_LEDDRV_IBIAS, ibias & 0xF); + BL_WR_REG(GLB_BASE, GLB_LED_DRIVER, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO initialization + * + * @param cfg: GPIO configuration + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Init(GLB_GPIO_Cfg_Type *cfg) { + uint8_t gpioPin = cfg->gpioPin; + uint8_t realPin; + uint32_t *pOut; + uint32_t pos; + uint32_t tmpOut; + uint32_t tmpVal; + + /* drive strength(drive) = 0 <=> 8.0mA @ 3.3V */ + /* drive strength(drive) = 1 <=> 9.6mA @ 3.3V */ + /* drive strength(drive) = 2 <=> 11.2mA @ 3.3V */ + /* drive strength(drive) = 3 <=> 12.8mA @ 3.3V */ + + pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); + pos = gpioPin % 32; + tmpOut = *pOut; + + /* Disable output anyway*/ + tmpOut &= (~(1 << pos)); + *pOut = tmpOut; + + realPin = gpioPin; + /* sf pad use exclusive ie/pd/pu/drive/smtctrl */ + if (gpioPin >= 23 && gpioPin <= 28) { + if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { + realPin += 9; + } + } + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4); + if (realPin % 2 == 0) { + if (cfg->gpioMode != GPIO_MODE_ANALOG) { + /* not analog mode */ + + /* Set input or output */ + if (cfg->gpioMode == GPIO_MODE_OUTPUT) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + tmpOut |= (1 << pos); + } else { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + } + + /* Set pull up or down */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); + if (cfg->pullType == GPIO_PULL_UP) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); + } else if (cfg->pullType == GPIO_PULL_DOWN) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); + } } else { - if (cfg->gpioMode != GPIO_MODE_ANALOG) { - /* not analog mode */ - - /* Set input or output */ - if (cfg->gpioMode == GPIO_MODE_OUTPUT) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); - tmpOut |= (1 << pos); - } else { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); - } - - /* Set pull up or down */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); - if (cfg->pullType == GPIO_PULL_UP) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); - } else if (cfg->pullType == GPIO_PULL_DOWN) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); - } - } else { - /* analog mode */ - - /* clear ie && oe */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); - tmpOut &= ~(1 << pos); - - /* clear pu && pd */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); - } - - /* set drive && smt && func */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_DRV, cfg->drive); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_SMT, cfg->smtCtrl); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL, cfg->gpioFun); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4, tmpVal); - - *pOut = tmpOut; + /* analog mode */ - /* always on pads IE control (in HBN) */ - if (gpioPin >= 9 && gpioPin <= 13) { - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - uint32_t aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); + /* clear ie && oe */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + tmpOut &= ~(1 << pos); - if (cfg->gpioMode != GPIO_MODE_ANALOG) { - /* not analog mode */ - - if (cfg->gpioMode == GPIO_MODE_OUTPUT) { - aonPadIeSmt &= ~(1 << (gpioPin - 9)); - } else { - aonPadIeSmt |= (1 << (gpioPin - 9)); - } - } else { - /* analog mode */ - - /* clear aon pad ie */ - aonPadIeSmt &= ~(1 << (gpioPin - 9)); - } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + /* clear pu && pd */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PU); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_PD); } - if (gpioPin >= 23 && gpioPin <= 28) { - if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); - if (gpioPin % 2 == 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL, cfg->gpioFun); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL, cfg->gpioFun); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4, tmpVal); - - /* sf pad use GPIO23-GPIO28 pinmux&&outputEn */ - pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); - pos = gpioPin % 32; - tmpOut = *pOut; - /* Disable output anyway*/ - tmpOut &= (~(1 << pos)); - *pOut = tmpOut; - if (cfg->gpioMode != GPIO_MODE_ANALOG) { - /* not analog mode */ - - if (cfg->gpioMode == GPIO_MODE_OUTPUT) { - tmpOut |= (1 << pos); - } - } - *pOut = tmpOut; - } - } + /* set drive && smt && func */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_DRV, cfg->drive); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_SMT, cfg->smtCtrl); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL, cfg->gpioFun); + } else { + if (cfg->gpioMode != GPIO_MODE_ANALOG) { + /* not analog mode */ - return SUCCESS; -} + /* Set input or output */ + if (cfg->gpioMode == GPIO_MODE_OUTPUT) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); + tmpOut |= (1 << pos); + } else { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); + } + + /* Set pull up or down */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); + if (cfg->pullType == GPIO_PULL_UP) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); + } else if (cfg->pullType == GPIO_PULL_DOWN) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); + } + } else { + /* analog mode */ -/****************************************************************************/ /** - * @brief init GPIO function in pin list - * - * @param gpioFun: GPIO pin function - * @param pinList: GPIO pin list - * @param cnt: GPIO pin count - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_Func_Init(GLB_GPIO_FUNC_Type gpioFun, GLB_GPIO_Type *pinList, uint8_t cnt) -{ - GLB_GPIO_Cfg_Type gpioCfg = { - .gpioPin = GLB_GPIO_PIN_0, - .gpioFun = (uint8_t)gpioFun, - .gpioMode = GPIO_MODE_AF, - .pullType = GPIO_PULL_UP, - .drive = 3, - .smtCtrl = 1 - }; - - if (gpioFun == GPIO_FUN_ANALOG) { - gpioCfg.gpioMode = GPIO_MODE_ANALOG; - } + /* clear ie && oe */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); + tmpOut &= ~(1 << pos); - for (uint8_t i = 0; i < cnt; i++) { - gpioCfg.gpioPin = pinList[i]; - GLB_GPIO_Init(&gpioCfg); + /* clear pu && pd */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PU); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_PD); } - return SUCCESS; -} + /* set drive && smt && func */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_DRV, cfg->drive); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_SMT, cfg->smtCtrl); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL, cfg->gpioFun); + } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4, tmpVal); -/****************************************************************************/ /** - * @brief GPIO set input function enable - * - * @param gpioPin: GPIO pin - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_INPUT_Enable(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - uint32_t pinOffset; - uint32_t aonPadIeSmt; - - pinOffset = (gpioPin >> 1) << 2; - tmpVal = *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset); - if (gpioPin % 2 == 0) { - /* [0] is ie */ - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); - } else { - /* [16] is ie */ - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); - } - *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset) = tmpVal; + *pOut = tmpOut; - /* always on pads IE control (in HBN) */ - if (gpioPin >= 9 && gpioPin <= 13) { - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); - aonPadIeSmt |= (1 << (gpioPin - 9)); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - } + /* always on pads IE control (in HBN) */ + if (gpioPin >= 9 && gpioPin <= 13) { + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + uint32_t aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); - return SUCCESS; -} + if (cfg->gpioMode != GPIO_MODE_ANALOG) { + /* not analog mode */ -/****************************************************************************/ /** - * @brief GPIO set input function disable - * - * @param gpioPin: GPIO pin - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_INPUT_Disable(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - uint32_t pinOffset; - uint32_t aonPadIeSmt; - - pinOffset = (gpioPin >> 1) << 2; - tmpVal = *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset); - if (gpioPin % 2 == 0) { - /* [0] is ie */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + if (cfg->gpioMode == GPIO_MODE_OUTPUT) { + aonPadIeSmt &= ~(1 << (gpioPin - 9)); + } else { + aonPadIeSmt |= (1 << (gpioPin - 9)); + } } else { - /* [16] is ie */ - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); - } - *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset) = tmpVal; + /* analog mode */ - /* always on pads IE control (in HBN) */ - if (gpioPin >= 9 && gpioPin <= 13) { - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); - aonPadIeSmt &= ~(1 << (gpioPin - 9)); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + /* clear aon pad ie */ + aonPadIeSmt &= ~(1 << (gpioPin - 9)); } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + } - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief GPIO set output function enable - * - * @param gpioPin: GPIO pin - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Enable(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_CFGCTL34); - tmpVal = tmpVal | (1 << gpioPin); - BL_WR_REG(GLB_BASE, GLB_GPIO_CFGCTL34, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief GPIO set output function disable - * - * @param gpioPin: GPIO pin - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Disable(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_CFGCTL34); - tmpVal = tmpVal & ~(1 << gpioPin); - BL_WR_REG(GLB_BASE, GLB_GPIO_CFGCTL34, tmpVal); - - return SUCCESS; -} + if (gpioPin >= 23 && gpioPin <= 28) { + if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); + if (gpioPin % 2 == 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL, cfg->gpioFun); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL, cfg->gpioFun); + } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4, tmpVal); + + /* sf pad use GPIO23-GPIO28 pinmux&&outputEn */ + pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); + pos = gpioPin % 32; + tmpOut = *pOut; + /* Disable output anyway*/ + tmpOut &= (~(1 << pos)); + *pOut = tmpOut; + if (cfg->gpioMode != GPIO_MODE_ANALOG) { + /* not analog mode */ + + if (cfg->gpioMode == GPIO_MODE_OUTPUT) { + tmpOut |= (1 << pos); + } + } + *pOut = tmpOut; + } + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief init GPIO function in pin list + * + * @param gpioFun: GPIO pin function + * @param pinList: GPIO pin list + * @param cnt: GPIO pin count + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_Func_Init(GLB_GPIO_FUNC_Type gpioFun, GLB_GPIO_Type *pinList, uint8_t cnt) { + GLB_GPIO_Cfg_Type gpioCfg = {.gpioPin = GLB_GPIO_PIN_0, .gpioFun = (uint8_t)gpioFun, .gpioMode = GPIO_MODE_AF, .pullType = GPIO_PULL_UP, .drive = 3, .smtCtrl = 1}; + + if (gpioFun == GPIO_FUN_ANALOG) { + gpioCfg.gpioMode = GPIO_MODE_ANALOG; + } + + for (uint8_t i = 0; i < cnt; i++) { + gpioCfg.gpioPin = pinList[i]; + GLB_GPIO_Init(&gpioCfg); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO set input function enable + * + * @param gpioPin: GPIO pin + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_INPUT_Enable(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + uint32_t pinOffset; + uint32_t aonPadIeSmt; + + pinOffset = (gpioPin >> 1) << 2; + tmpVal = *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset); + if (gpioPin % 2 == 0) { + /* [0] is ie */ + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + } else { + /* [16] is ie */ + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); + } + *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset) = tmpVal; + + /* always on pads IE control (in HBN) */ + if (gpioPin >= 9 && gpioPin <= 13) { + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); + aonPadIeSmt |= (1 << (gpioPin - 9)); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO set input function disable + * + * @param gpioPin: GPIO pin + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_INPUT_Disable(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + uint32_t pinOffset; + uint32_t aonPadIeSmt; + + pinOffset = (gpioPin >> 1) << 2; + tmpVal = *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset); + if (gpioPin % 2 == 0) { + /* [0] is ie */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_0_IE); + } else { + /* [16] is ie */ + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_REG_GPIO_1_IE); + } + *(uint32_t *)(GLB_BASE + GLB_GPIO_OFFSET + pinOffset) = tmpVal; + + /* always on pads IE control (in HBN) */ + if (gpioPin >= 9 && gpioPin <= 13) { + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); + aonPadIeSmt &= ~(1 << (gpioPin - 9)); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO set output function enable + * + * @param gpioPin: GPIO pin + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Enable(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_CFGCTL34); + tmpVal = tmpVal | (1 << gpioPin); + BL_WR_REG(GLB_BASE, GLB_GPIO_CFGCTL34, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO set output function disable + * + * @param gpioPin: GPIO pin + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Disable(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_CFGCTL34); + tmpVal = tmpVal & ~(1 << gpioPin); + BL_WR_REG(GLB_BASE, GLB_GPIO_CFGCTL34, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief GPIO set High-Z + * + * @param gpioPin: GPIO pin + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Set_HZ(GLB_GPIO_Type gpioPin) { + uint32_t *pOut; + uint32_t pos; + uint32_t tmpOut; + uint32_t tmpVal; + uint32_t aonPadIeSmt; + uint8_t realPin; + + /* always on pads IE control (in HBN) */ + if (gpioPin >= 9 && gpioPin <= 13) { + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); + aonPadIeSmt &= ~(1 << (gpioPin - 9)); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + } + + realPin = gpioPin; + /* sf pad use exclusive ie/pd/pu/drive/smtctrl */ + if (gpioPin >= 23 && gpioPin <= 28) { + if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { + realPin += 9; + } + } + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4); + + /* pu=0, pd=0, ie=0 */ + if (realPin % 2 == 0) { + tmpVal = (tmpVal & 0xffffff00); + } else { + tmpVal = (tmpVal & 0xff00ffff); + } + + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4, tmpVal); + + pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); + pos = gpioPin % 32; + tmpOut = *pOut; + + /* Disable output anyway*/ + tmpOut &= (~(1 << pos)); + *pOut = tmpOut; + + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); + + /* func_sel=swgpio */ + if (gpioPin % 2 == 0) { + tmpVal = (tmpVal & 0xffff00ff); + tmpVal |= 0x0B00; + } else { + tmpVal = (tmpVal & 0x00ffffff); + tmpVal |= (0x0B00 << 16); + } -/****************************************************************************/ /** - * @brief GPIO set High-Z - * - * @param gpioPin: GPIO pin - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Set_HZ(GLB_GPIO_Type gpioPin) -{ - uint32_t *pOut; - uint32_t pos; - uint32_t tmpOut; - uint32_t tmpVal; - uint32_t aonPadIeSmt; - uint8_t realPin; - - /* always on pads IE control (in HBN) */ - if (gpioPin >= 9 && gpioPin <= 13) { - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - aonPadIeSmt = BL_GET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT); - aonPadIeSmt &= ~(1 << (gpioPin - 9)); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aonPadIeSmt); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4, tmpVal); + + /* Disable output anyway*/ + *pOut = tmpOut; + + return SUCCESS; +} + +BL_Err_Type ATTR_TCM_SECTION GLB_Set_Flash_Pad_HZ(void) { + uint32_t tmpVal; + uint32_t offset; - realPin = gpioPin; - /* sf pad use exclusive ie/pd/pu/drive/smtctrl */ - if (gpioPin >= 23 && gpioPin <= 28) { - if ((BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) & (1 << (gpioPin - 23))) > 0) { - realPin += 9; - } - } - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4); + if (BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) != 0x00) { + return ERROR; + } + for (offset = 23; offset <= 28; offset++) { + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); /* pu=0, pd=0, ie=0 */ - if (realPin % 2 == 0) { - tmpVal = (tmpVal & 0xffffff00); + if (offset % 2 == 0) { + tmpVal = (tmpVal & 0xffffff00); } else { - tmpVal = (tmpVal & 0xff00ffff); + tmpVal = (tmpVal & 0xff00ffff); } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + realPin / 2 * 4, tmpVal); - - pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET + ((gpioPin >> 5) << 2)); - pos = gpioPin % 32; - tmpOut = *pOut; - - /* Disable output anyway*/ - tmpOut &= (~(1 << pos)); - *pOut = tmpOut; - - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); - + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); /* func_sel=swgpio */ - if (gpioPin % 2 == 0) { - tmpVal = (tmpVal & 0xffff00ff); - tmpVal |= 0x0B00; + if (offset % 2 == 0) { + tmpVal = (tmpVal & 0xffff00ff); + tmpVal |= 0x0B00; } else { - tmpVal = (tmpVal & 0x00ffffff); - tmpVal |= (0x0B00 << 16); + tmpVal = (tmpVal & 0x00ffffff); + tmpVal |= (0x0B00 << 16); } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); + } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4, tmpVal); + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET); + tmpVal &= 0xE07FFFFF; + BL_WR_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET, tmpVal); - /* Disable output anyway*/ - *pOut = tmpOut; - - return SUCCESS; + return SUCCESS; } -BL_Err_Type ATTR_TCM_SECTION GLB_Set_Flash_Pad_HZ(void) -{ - uint32_t tmpVal; - uint32_t offset; - - if (BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) != 0x00) { - return ERROR; - } - - for (offset = 23; offset <= 28; offset++) { - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); - /* pu=0, pd=0, ie=0 */ - if (offset % 2 == 0) { - tmpVal = (tmpVal & 0xffffff00); - } else { - tmpVal = (tmpVal & 0xff00ffff); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); - - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); - /* func_sel=swgpio */ - if (offset % 2 == 0) { - tmpVal = (tmpVal & 0xffff00ff); - tmpVal |= 0x0B00; - } else { - tmpVal = (tmpVal & 0x00ffffff); - tmpVal |= (0x0B00 << 16); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); - } - - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET); - tmpVal &= 0xE07FFFFF; - BL_WR_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET, tmpVal); - - return SUCCESS; -} +BL_Err_Type ATTR_TCM_SECTION GLB_Set_Psram_Pad_HZ(void) { + uint32_t tmpVal; + uint32_t offset; -BL_Err_Type ATTR_TCM_SECTION GLB_Set_Psram_Pad_HZ(void) -{ - uint32_t tmpVal; - uint32_t offset; + if (BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) != 0x3F) { + return ERROR; + } - if (BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO) != 0x3F) { - return ERROR; + for (offset = 32; offset <= 37; offset++) { + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); + /* pu=0, pd=0, ie=0 */ + if (offset % 2 == 0) { + tmpVal = (tmpVal & 0xffffff00); + } else { + tmpVal = (tmpVal & 0xff00ffff); } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); - for (offset = 32; offset <= 37; offset++) { - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4); - /* pu=0, pd=0, ie=0 */ - if (offset % 2 == 0) { - tmpVal = (tmpVal & 0xffffff00); - } else { - tmpVal = (tmpVal & 0xff00ffff); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + offset / 2 * 4, tmpVal); - - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + (offset - 9) / 2 * 4); - /* func_sel=swgpio */ - if ((offset - 9) % 2 == 0) { - tmpVal = (tmpVal & 0xffff00ff); - tmpVal |= 0x0B00; - } else { - tmpVal = (tmpVal & 0x00ffffff); - tmpVal |= (0x0B00 << 16); - } - BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + (offset - 9) / 2 * 4, tmpVal); + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + (offset - 9) / 2 * 4); + /* func_sel=swgpio */ + if ((offset - 9) % 2 == 0) { + tmpVal = (tmpVal & 0xffff00ff); + tmpVal |= 0x0B00; + } else { + tmpVal = (tmpVal & 0x00ffffff); + tmpVal |= (0x0B00 << 16); } + BL_WR_WORD(GLB_BASE + GLB_GPIO_OFFSET + (offset - 9) / 2 * 4, tmpVal); + } - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET); - tmpVal &= 0xE07FFFFF; - BL_WR_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET, tmpVal); + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET); + tmpVal &= 0xE07FFFFF; + BL_WR_WORD(GLB_BASE + GLB_GPIO_OUTPUT_EN_OFFSET, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Get GPIO function - * - * @param gpioPin: GPIO type - * - * @return GPIO function - * -*******************************************************************************/ + * @brief Get GPIO function + * + * @param gpioPin: GPIO type + * + * @return GPIO function + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint8_t ATTR_TCM_SECTION GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; +uint8_t ATTR_TCM_SECTION GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; - tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); + tmpVal = BL_RD_WORD(GLB_BASE + GLB_GPIO_OFFSET + gpioPin / 2 * 4); - if (gpioPin % 2 == 0) { - return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL); - } else { - return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL); - } + if (gpioPin % 2 == 0) { + return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_0_FUNC_SEL); + } else { + return BL_GET_REG_BITS_VAL(tmpVal, GLB_REG_GPIO_1_FUNC_SEL); + } } #endif /****************************************************************************/ /** - * @brief Write GPIO - * - * @param gpioPin: GPIO type - * @param val: GPIO value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_Write(GLB_GPIO_Type gpioPin, uint32_t val) -{ - uint32_t *pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_OFFSET + ((gpioPin >> 5) << 2)); - uint32_t pos = gpioPin % 32; - uint32_t tmpOut; - - tmpOut = *pOut; - if (val > 0) { - tmpOut |= (1 << pos); - } else { - tmpOut &= (~(1 << pos)); - } - *pOut = tmpOut; - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Read GPIO - * - * @param gpioPin: GPIO type - * - * @return GPIO value - * -*******************************************************************************/ -uint32_t GLB_GPIO_Read(GLB_GPIO_Type gpioPin) -{ - uint32_t *p = (uint32_t *)(GLB_BASE + GLB_GPIO_INPUT_OFFSET + ((gpioPin >> 5) << 2)); - uint32_t pos = gpioPin % 32; - - if ((*p) & (1 << pos)) { - return 1; + * @brief Write GPIO + * + * @param gpioPin: GPIO type + * @param val: GPIO value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_Write(GLB_GPIO_Type gpioPin, uint32_t val) { + uint32_t *pOut = (uint32_t *)(GLB_BASE + GLB_GPIO_OUTPUT_OFFSET + ((gpioPin >> 5) << 2)); + uint32_t pos = gpioPin % 32; + uint32_t tmpOut; + + tmpOut = *pOut; + if (val > 0) { + tmpOut |= (1 << pos); + } else { + tmpOut &= (~(1 << pos)); + } + *pOut = tmpOut; + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Read GPIO + * + * @param gpioPin: GPIO type + * + * @return GPIO value + * + *******************************************************************************/ +uint32_t GLB_GPIO_Read(GLB_GPIO_Type gpioPin) { + uint32_t *p = (uint32_t *)(GLB_BASE + GLB_GPIO_INPUT_OFFSET + ((gpioPin >> 5) << 2)); + uint32_t pos = gpioPin % 32; + + if ((*p) & (1 << pos)) { + return 1; + } else { + return 0; + } +} + +/****************************************************************************/ /** + * @brief Set GLB GPIO interrupt mask + * + * @param gpioPin: GPIO type + * @param intMask: GPIO interrupt MASK or UNMASK + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_IntMask(GLB_GPIO_Type gpioPin, BL_Mask_Type intMask) { + uint32_t tmpVal; + + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MASK1); + if (intMask == MASK) { + tmpVal = tmpVal | (1 << gpioPin); } else { - return 0; - } -} - -/****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mask - * - * @param gpioPin: GPIO type - * @param intMask: GPIO interrupt MASK or UNMASK - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_IntMask(GLB_GPIO_Type gpioPin, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MASK1); - if (intMask == MASK) { - tmpVal = tmpVal | (1 << gpioPin); - } else { - tmpVal = tmpVal & ~(1 << gpioPin); - } - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MASK1, tmpVal); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mask - * - * @param gpioPin: GPIO type - * @param intClear: GPIO interrupt clear or unclear - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_IntClear(GLB_GPIO_Type gpioPin, BL_Sts_Type intClear) -{ - uint32_t tmpVal; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_CLR1); - if (intClear == SET) { - tmpVal = tmpVal | (1 << gpioPin); - } else { - tmpVal = tmpVal & ~(1 << gpioPin); - } - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_CLR1, tmpVal); + tmpVal = tmpVal & ~(1 << gpioPin); } + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MASK1, tmpVal); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Get GLB GPIO interrrupt status - * - * @param gpioPin: GPIO type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type GLB_Get_GPIO_IntStatus(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal = 0; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_STAT1); - } - - return (tmpVal & (1 << gpioPin)) ? SET : RESET; -} + * @brief Set GLB GPIO interrupt mask + * + * @param gpioPin: GPIO type + * @param intClear: GPIO interrupt clear or unclear + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_IntClear(GLB_GPIO_Type gpioPin, BL_Sts_Type intClear) { + uint32_t tmpVal; -/****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mode - * - * @param gpioPin: GPIO type - * @param intCtlMod: GPIO interrupt control mode - * @param intTrgMod: GPIO interrupt trigger mode - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_GPIO_IntMod(GLB_GPIO_Type gpioPin, GLB_GPIO_INT_CONTROL_Type intCtlMod, GLB_GPIO_INT_TRIG_Type intTrgMod) -{ - uint32_t tmpVal; - uint32_t tmpGpioPin; - - CHECK_PARAM(IS_GLB_GPIO_INT_CONTROL_TYPE(intCtlMod)); - CHECK_PARAM(IS_GLB_GPIO_INT_TRIG_TYPE(intTrgMod)); - - if (gpioPin < GLB_GPIO_PIN_10) { - /* GPIO0 ~ GPIO9 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1); - tmpGpioPin = gpioPin; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1, tmpVal); - } else if (gpioPin < GLB_GPIO_PIN_20) { - /* GPIO10 ~ GPIO19 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_10; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2, tmpVal); - } else if (gpioPin < GLB_GPIO_PIN_30) { - /* GPIO20 ~ GPIO29 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_20; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3, tmpVal); + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_CLR1); + if (intClear == SET) { + tmpVal = tmpVal | (1 << gpioPin); } else { - /* GPIO30 ~ GPIO31 not recommend */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_30; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4, tmpVal); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief get GPIO interrupt control mode - * - * @param gpioPin: GPIO pin type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -GLB_GPIO_INT_CONTROL_Type GLB_Get_GPIO_IntCtlMod(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - uint32_t bitVal; - - if (gpioPin < GLB_GPIO_PIN_10) { - /* GPIO0 - GPIO9 */ - bitVal = gpioPin - 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } else if ((gpioPin > GLB_GPIO_PIN_9) && (gpioPin < GLB_GPIO_PIN_20)) { - /* GPIO10 - GPIO19 */ - bitVal = gpioPin - 10; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } else if ((gpioPin > GLB_GPIO_PIN_19) && (gpioPin < GLB_GPIO_PIN_30)) { - /* GPIO20 - GPIO29 */ - bitVal = gpioPin - 20; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + tmpVal = tmpVal & ~(1 << gpioPin); + } + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_CLR1, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Get GLB GPIO interrrupt status + * + * @param gpioPin: GPIO type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type GLB_Get_GPIO_IntStatus(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal = 0; + + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_STAT1); + } + + return (tmpVal & (1 << gpioPin)) ? SET : RESET; +} + +/****************************************************************************/ /** + * @brief Set GLB GPIO interrupt mode + * + * @param gpioPin: GPIO type + * @param intCtlMod: GPIO interrupt control mode + * @param intTrgMod: GPIO interrupt trigger mode + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_GPIO_IntMod(GLB_GPIO_Type gpioPin, GLB_GPIO_INT_CONTROL_Type intCtlMod, GLB_GPIO_INT_TRIG_Type intTrgMod) { + uint32_t tmpVal; + uint32_t tmpGpioPin; + + CHECK_PARAM(IS_GLB_GPIO_INT_CONTROL_TYPE(intCtlMod)); + CHECK_PARAM(IS_GLB_GPIO_INT_TRIG_TYPE(intTrgMod)); + + if (gpioPin < GLB_GPIO_PIN_10) { + /* GPIO0 ~ GPIO9 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1); + tmpGpioPin = gpioPin; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1, tmpVal); + } else if (gpioPin < GLB_GPIO_PIN_20) { + /* GPIO10 ~ GPIO19 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_10; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2, tmpVal); + } else if (gpioPin < GLB_GPIO_PIN_30) { + /* GPIO20 ~ GPIO29 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_20; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3, tmpVal); + } else { + /* GPIO30 ~ GPIO31 not recommend */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_30; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief get GPIO interrupt control mode + * + * @param gpioPin: GPIO pin type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +GLB_GPIO_INT_CONTROL_Type GLB_Get_GPIO_IntCtlMod(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + uint32_t bitVal; + + if (gpioPin < GLB_GPIO_PIN_10) { + /* GPIO0 - GPIO9 */ + bitVal = gpioPin - 0; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET1); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else if ((gpioPin > GLB_GPIO_PIN_9) && (gpioPin < GLB_GPIO_PIN_20)) { + /* GPIO10 - GPIO19 */ + bitVal = gpioPin - 10; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET2); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else if ((gpioPin > GLB_GPIO_PIN_19) && (gpioPin < GLB_GPIO_PIN_30)) { + /* GPIO20 - GPIO29 */ + bitVal = gpioPin - 20; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET3); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else { + /* GPIO30 ~ GPIO31 not recommend */ + bitVal = gpioPin - 30; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } +} + +/****************************************************************************/ /** + * @brief Set GLB GPIO interrupt mask 2 + * + * @param gpioPin: GPIO type + * @param intMask: GPIO interrupt MASK or UNMASK + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_Int2Mask(GLB_GPIO_Type gpioPin, BL_Mask_Type intMask) { + uint32_t tmpVal; + + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MASK1); + if (intMask == MASK) { + tmpVal = tmpVal | (1 << gpioPin); } else { - /* GPIO30 ~ GPIO31 not recommend */ - bitVal = gpioPin - 30; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT_MODE_SET4); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } -} - -/****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mask 2 - * - * @param gpioPin: GPIO type - * @param intMask: GPIO interrupt MASK or UNMASK - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_Int2Mask(GLB_GPIO_Type gpioPin, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MASK1); - if (intMask == MASK) { - tmpVal = tmpVal | (1 << gpioPin); - } else { - tmpVal = tmpVal & ~(1 << gpioPin); - } - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MASK1, tmpVal); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mask 2 - * - * @param gpioPin: GPIO type - * @param intClear: GPIO interrupt clear or unclear - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_Int2Clear(GLB_GPIO_Type gpioPin, BL_Sts_Type intClear) -{ - uint32_t tmpVal; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_CLR1); - if (intClear == SET) { - tmpVal = tmpVal | (1 << gpioPin); - } else { - tmpVal = tmpVal & ~(1 << gpioPin); - } - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_CLR1, tmpVal); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Get GLB GPIO interrrupt status 2 - * - * @param gpioPin: GPIO type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type GLB_Get_GPIO_Int2Status(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal = 0; - - if (gpioPin < 32) { - /* GPIO0 ~ GPIO31 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_STAT1); + tmpVal = tmpVal & ~(1 << gpioPin); } + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MASK1, tmpVal); + } - return (tmpVal & (1 << gpioPin)) ? SET : RESET; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set GLB GPIO interrupt mode 2 - * - * @param gpioPin: GPIO type - * @param intCtlMod: GPIO interrupt control mode - * @param intTrgMod: GPIO interrupt trigger mode - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_Set_GPIO_Int2Mod(GLB_GPIO_Type gpioPin, GLB_GPIO_INT_CONTROL_Type intCtlMod, GLB_GPIO_INT_TRIG_Type intTrgMod) -{ - uint32_t tmpVal; - uint32_t tmpGpioPin; - - CHECK_PARAM(IS_GLB_GPIO_INT_CONTROL_TYPE(intCtlMod)); - CHECK_PARAM(IS_GLB_GPIO_INT_TRIG_TYPE(intTrgMod)); - - if (gpioPin < GLB_GPIO_PIN_10) { - /* GPIO0 ~ GPIO9 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1); - tmpGpioPin = gpioPin; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1, tmpVal); - } else if (gpioPin < GLB_GPIO_PIN_20) { - /* GPIO10 ~ GPIO19 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_10; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2, tmpVal); - } else if (gpioPin < GLB_GPIO_PIN_30) { - /* GPIO20 ~ GPIO29 */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_20; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3, tmpVal); - } else { - /* GPIO30 ~ GPIO31 not recommend */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4); - tmpGpioPin = gpioPin - GLB_GPIO_PIN_30; - tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); - BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4, tmpVal); - } - - return SUCCESS; -} + * @brief Set GLB GPIO interrupt mask 2 + * + * @param gpioPin: GPIO type + * @param intClear: GPIO interrupt clear or unclear + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_Int2Clear(GLB_GPIO_Type gpioPin, BL_Sts_Type intClear) { + uint32_t tmpVal; -/****************************************************************************/ /** - * @brief get GPIO interrupt control mode 2 - * - * @param gpioPin: GPIO pin type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -GLB_GPIO_INT_CONTROL_Type GLB_Get_GPIO_Int2CtlMod(GLB_GPIO_Type gpioPin) -{ - uint32_t tmpVal; - uint32_t bitVal; - - if (gpioPin < GLB_GPIO_PIN_10) { - /* GPIO0 - GPIO9 */ - bitVal = gpioPin - 0; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } else if ((gpioPin > GLB_GPIO_PIN_9) && (gpioPin < GLB_GPIO_PIN_20)) { - /* GPIO10 - GPIO19 */ - bitVal = gpioPin - 10; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } else if ((gpioPin > GLB_GPIO_PIN_19) && (gpioPin < GLB_GPIO_PIN_30)) { - /* GPIO20 - GPIO29 */ - bitVal = gpioPin - 20; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_CLR1); + if (intClear == SET) { + tmpVal = tmpVal | (1 << gpioPin); } else { - /* GPIO30 ~ GPIO31 not recommend */ - bitVal = gpioPin - 30; - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4); - tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); - return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; - } -} - -/****************************************************************************/ /** - * @brief GPIO INT0 IRQHandler install - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_INT0_IRQHandler_Install(void) -{ + tmpVal = tmpVal & ~(1 << gpioPin); + } + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_CLR1, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Get GLB GPIO interrrupt status 2 + * + * @param gpioPin: GPIO type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type GLB_Get_GPIO_Int2Status(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal = 0; + + if (gpioPin < 32) { + /* GPIO0 ~ GPIO31 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_STAT1); + } + + return (tmpVal & (1 << gpioPin)) ? SET : RESET; +} + +/****************************************************************************/ /** + * @brief Set GLB GPIO interrupt mode 2 + * + * @param gpioPin: GPIO type + * @param intCtlMod: GPIO interrupt control mode + * @param intTrgMod: GPIO interrupt trigger mode + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_Set_GPIO_Int2Mod(GLB_GPIO_Type gpioPin, GLB_GPIO_INT_CONTROL_Type intCtlMod, GLB_GPIO_INT_TRIG_Type intTrgMod) { + uint32_t tmpVal; + uint32_t tmpGpioPin; + + CHECK_PARAM(IS_GLB_GPIO_INT_CONTROL_TYPE(intCtlMod)); + CHECK_PARAM(IS_GLB_GPIO_INT_TRIG_TYPE(intTrgMod)); + + if (gpioPin < GLB_GPIO_PIN_10) { + /* GPIO0 ~ GPIO9 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1); + tmpGpioPin = gpioPin; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1, tmpVal); + } else if (gpioPin < GLB_GPIO_PIN_20) { + /* GPIO10 ~ GPIO19 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_10; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2, tmpVal); + } else if (gpioPin < GLB_GPIO_PIN_30) { + /* GPIO20 ~ GPIO29 */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_20; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3, tmpVal); + } else { + /* GPIO30 ~ GPIO31 not recommend */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4); + tmpGpioPin = gpioPin - GLB_GPIO_PIN_30; + tmpVal = (tmpVal & ~(0x7 << (3 * tmpGpioPin))) | (((intCtlMod << 2) | intTrgMod) << (3 * tmpGpioPin)); + BL_WR_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4, tmpVal); + } + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief get GPIO interrupt control mode 2 + * + * @param gpioPin: GPIO pin type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +GLB_GPIO_INT_CONTROL_Type GLB_Get_GPIO_Int2CtlMod(GLB_GPIO_Type gpioPin) { + uint32_t tmpVal; + uint32_t bitVal; + + if (gpioPin < GLB_GPIO_PIN_10) { + /* GPIO0 - GPIO9 */ + bitVal = gpioPin - 0; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET1); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else if ((gpioPin > GLB_GPIO_PIN_9) && (gpioPin < GLB_GPIO_PIN_20)) { + /* GPIO10 - GPIO19 */ + bitVal = gpioPin - 10; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET2); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else if ((gpioPin > GLB_GPIO_PIN_19) && (gpioPin < GLB_GPIO_PIN_30)) { + /* GPIO20 - GPIO29 */ + bitVal = gpioPin - 20; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET3); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } else { + /* GPIO30 ~ GPIO31 not recommend */ + bitVal = gpioPin - 30; + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_INT2_MODE_SET4); + tmpVal = (tmpVal & (0x7 << (bitVal * 3))) >> (bitVal * 3); + return (tmpVal >> 2) ? GLB_GPIO_INT_CONTROL_ASYNC : GLB_GPIO_INT_CONTROL_SYNC; + } +} + +/****************************************************************************/ /** + * @brief GPIO INT0 IRQHandler install + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_INT0_IRQHandler_Install(void) { #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(GPIO_INT0_IRQn, GPIO_INT0_IRQHandler); + Interrupt_Handler_Register(GPIO_INT0_IRQn, GPIO_INT0_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief GPIO interrupt IRQ handler callback install - * - * @param gpioPin: GPIO pin type - * @param cbFun: callback function - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_INT0_Callback_Install(GLB_GPIO_Type gpioPin, intCallback_Type *cbFun) -{ - if (gpioPin < 32) { - glbGpioInt0CbfArra[gpioPin] = cbFun; - } + * @brief GPIO interrupt IRQ handler callback install + * + * @param gpioPin: GPIO pin type + * @param cbFun: callback function + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_INT0_Callback_Install(GLB_GPIO_Type gpioPin, intCallback_Type *cbFun) { + if (gpioPin < 32) { + glbGpioInt0CbfArra[gpioPin] = cbFun; + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief GPIO interrupt IRQ handler callback install2 - * - * @param gpioPin: GPIO pin type - * @param cbFun: callback function - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type GLB_GPIO_INT0_Callback_Install2(GLB_GPIO_Type gpioPin, intCallback_Type *cbFun) -{ - if (gpioPin < 32) { - glbGpioInt0CbfArra2[gpioPin] = cbFun; - } + * @brief GPIO interrupt IRQ handler callback install2 + * + * @param gpioPin: GPIO pin type + * @param cbFun: callback function + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type GLB_GPIO_INT0_Callback_Install2(GLB_GPIO_Type gpioPin, intCallback_Type *cbFun) { + if (gpioPin < 32) { + glbGpioInt0CbfArra2[gpioPin] = cbFun; + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief GPIO interrupt IRQ handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief GPIO interrupt IRQ handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void GPIO_INT0_IRQHandler(void) -{ - GLB_GPIO_Type gpioPin; - uint32_t timeOut = 0; - - for (gpioPin = GLB_GPIO_PIN_0; gpioPin <= GLB_GPIO_PIN_31; gpioPin++) { - if (SET == GLB_Get_GPIO_IntStatus(gpioPin)) { - GLB_GPIO_IntClear(gpioPin, SET); - - /* timeout check */ - timeOut = GLB_GPIO_INT0_CLEAR_TIMEOUT; - do { - timeOut--; - } while ((SET == GLB_Get_GPIO_IntStatus(gpioPin)) && timeOut); - if (!timeOut) { - //MSG("WARNING: Clear GPIO interrupt status fail.\r\n"); - } - - /* if timeOut==0, GPIO interrupt status not cleared */ - GLB_GPIO_IntClear(gpioPin, RESET); - - if (glbGpioInt0CbfArra[gpioPin] != NULL) { - /* Call the callback function */ - glbGpioInt0CbfArra[gpioPin](); - } - } - if (SET == GLB_Get_GPIO_Int2Status(gpioPin)) { - GLB_GPIO_Int2Clear(gpioPin, SET); - - /* timeout check */ - timeOut = GLB_GPIO_INT0_CLEAR_TIMEOUT; - do { - timeOut--; - } while ((SET == GLB_Get_GPIO_Int2Status(gpioPin)) && timeOut); - if (!timeOut) { - //MSG("WARNING: Clear GPIO interrupt status fail.\r\n"); - } - - /* if timeOut==0, GPIO interrupt status not cleared */ - GLB_GPIO_Int2Clear(gpioPin, RESET); - - if (glbGpioInt0CbfArra2[gpioPin] != NULL) { - /* Call the callback function */ - glbGpioInt0CbfArra2[gpioPin](); - } - } - } +void GPIO_INT0_IRQHandler(void) { + GLB_GPIO_Type gpioPin; + uint32_t timeOut = 0; + + for (gpioPin = GLB_GPIO_PIN_0; gpioPin <= GLB_GPIO_PIN_31; gpioPin++) { + if (SET == GLB_Get_GPIO_IntStatus(gpioPin)) { + GLB_GPIO_IntClear(gpioPin, SET); + + /* timeout check */ + timeOut = GLB_GPIO_INT0_CLEAR_TIMEOUT; + do { + timeOut--; + } while ((SET == GLB_Get_GPIO_IntStatus(gpioPin)) && timeOut); + if (!timeOut) { + // MSG("WARNING: Clear GPIO interrupt status fail.\r\n"); + } + + /* if timeOut==0, GPIO interrupt status not cleared */ + GLB_GPIO_IntClear(gpioPin, RESET); + + if (glbGpioInt0CbfArra[gpioPin] != NULL) { + /* Call the callback function */ + glbGpioInt0CbfArra[gpioPin](); + } + } + if (SET == GLB_Get_GPIO_Int2Status(gpioPin)) { + GLB_GPIO_Int2Clear(gpioPin, SET); + + /* timeout check */ + timeOut = GLB_GPIO_INT0_CLEAR_TIMEOUT; + do { + timeOut--; + } while ((SET == GLB_Get_GPIO_Int2Status(gpioPin)) && timeOut); + if (!timeOut) { + // MSG("WARNING: Clear GPIO interrupt status fail.\r\n"); + } + + /* if timeOut==0, GPIO interrupt status not cleared */ + GLB_GPIO_Int2Clear(gpioPin, RESET); + + if (glbGpioInt0CbfArra2[gpioPin] != NULL) { + /* Call the callback function */ + glbGpioInt0CbfArra2[gpioPin](); + } + } + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c index 9ddf2f9bf..3cd799b97 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_hbn.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_hbn.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_hbn.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_hbn.h" #include "bl702_glb.h" @@ -49,17 +49,17 @@ /** @defgroup HBN_Private_Macros * @{ */ -#define HBN_CLK_SET_DUMMY_WAIT \ - { \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - __NOP(); \ - } +#define HBN_CLK_SET_DUMMY_WAIT \ + { \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + __NOP(); \ + } /*@} end of group HBN_Private_Macros */ @@ -72,8 +72,8 @@ /** @defgroup HBN_Private_Variables * @{ */ -static intCallback_Type *hbnInt0CbfArra[HBN_OUT0_MAX] = { NULL, NULL, NULL, NULL, NULL, NULL }; -static intCallback_Type *hbnInt1CbfArra[HBN_OUT1_MAX] = { NULL, NULL, NULL, NULL }; +static intCallback_Type *hbnInt0CbfArra[HBN_OUT0_MAX] = {NULL, NULL, NULL, NULL, NULL, NULL}; +static intCallback_Type *hbnInt1CbfArra[HBN_OUT1_MAX] = {NULL, NULL, NULL, NULL}; /*@} end of group HBN_Private_Variables */ @@ -100,1927 +100,1847 @@ static intCallback_Type *hbnInt1CbfArra[HBN_OUT1_MAX] = { NULL, NULL, NULL, NULL */ /****************************************************************************/ /** - * @brief Enter HBN - * - * @param cfg: HBN APP Config - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION HBN_Mode_Enter(HBN_APP_CFG_Type *cfg) -{ - uint32_t valLow = 0, valHigh = 0; - uint64_t val; - - /* work clock select */ - if (cfg->useXtal32k) { - HBN_32K_Sel(HBN_32K_XTAL); - } else { - HBN_32K_Sel(HBN_32K_RC); - HBN_Power_Off_Xtal_32K(); - } - - /* turn off RC32K during HBN */ - if ((cfg->hbnLevel) >= HBN_LEVEL_2) { - HBN_Power_Off_RC32K(); - } else { - HBN_Power_On_RC32K(); - } - - /* clear aon pad interrupt before config them */ - HBN_Clear_IRQ(HBN_INT_GPIO9); - HBN_Clear_IRQ(HBN_INT_GPIO10); - HBN_Clear_IRQ(HBN_INT_GPIO11); - HBN_Clear_IRQ(HBN_INT_GPIO12); - HBN_Clear_IRQ(HBN_INT_GPIO13); - - /* always disable HBN pin pull up/down to reduce PDS/HBN current, 0x4000F014[16]=0 */ - HBN_Hw_Pu_Pd_Cfg(DISABLE); - - HBN_Pin_WakeUp_Mask(~(cfg->gpioWakeupSrc)); - - if (cfg->gpioWakeupSrc != 0) { - HBN_Aon_Pad_IeSmt_Cfg(cfg->gpioWakeupSrc); - HBN_GPIO_INT_Enable(cfg->gpioTrigType); - } else { - HBN_Aon_Pad_IeSmt_Cfg(0); - } - - /* HBN RTC config and enable */ - if (cfg->sleepTime != 0) { - // set rtc enable flag - BL_WR_WORD(0x40010FFC, 0x1); - - HBN_Clear_RTC_Counter(); - HBN_Get_RTC_Timer_Val(&valLow, &valHigh); - val = valLow + ((uint64_t)valHigh << 32); - val += cfg->sleepTime; - HBN_Set_RTC_Timer(HBN_RTC_INT_DELAY_0T, val & 0xffffffff, val >> 32, HBN_RTC_COMP_BIT0_39); - HBN_Enable_RTC_Counter(); - } - - HBN_Power_Down_Flash(cfg->flashCfg); - - switch (cfg->flashPinCfg) { - case 0: - HBN_Set_Pad_23_28_Pullup(); - break; - - case 1: - /* need do nothing */ - break; - - case 2: - /* need do nothing */ - break; - - case 3: - /* can do nothing */ - break; - - default: - break; - } - - GLB_Set_System_CLK(GLB_DLL_XTAL_NONE, GLB_SYS_CLK_RC32M); - - /* power off xtal */ - AON_Power_Off_XTAL(); - - HBN_Enable_Ext(cfg->gpioWakeupSrc, cfg->ldoLevel, cfg->hbnLevel); -} - -/****************************************************************************/ /** - * @brief power down and switch clock - * - * @param flashCfg: None - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION HBN_Power_Down_Flash(SPI_Flash_Cfg_Type *flashCfg) -{ - SPI_Flash_Cfg_Type bhFlashCfg; - - if (flashCfg == NULL) { - /* fix this some time */ - /* SFlash_Cache_Flush(); */ - XIP_SFlash_Read_Via_Cache_Need_Lock(BL702_FLASH_XIP_BASE + 8 + 4, (uint8_t *)(&bhFlashCfg), sizeof(SPI_Flash_Cfg_Type)); - /* fix this some time */ - /* SFlash_Cache_Flush(); */ - - SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); - SFlash_Reset_Continue_Read(&bhFlashCfg); - } else { - SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); - SFlash_Reset_Continue_Read(flashCfg); - } - - SFlash_Powerdown(); -} - -/****************************************************************************/ /** - * @brief Enable HBN mode - * - * @param aGPIOIeCfg: AON GPIO IE config,Bit0->GPIO18. Bit(s) of Wakeup GPIO(s) must not be set to - * 0(s),say when use GPIO7 as wake up pin,aGPIOIeCfg should be 0x01. - * @param ldoLevel: LDO volatge level - * @param hbnLevel: HBN work level - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION HBN_Enable_Ext(uint8_t aGPIOIeCfg, HBN_LDO_LEVEL_Type ldoLevel, HBN_LEVEL_Type hbnLevel) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - CHECK_PARAM(IS_HBN_LEVEL_TYPE(hbnLevel)); - - /* Setting from guide */ - /* RAM Retion, no longer use */ - /* BL_WR_REG(HBN_BASE,HBN_SRAM,0x24); */ - - /* AON GPIO IE */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aGPIOIeCfg); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - - /* HBN mode LDO level */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_AON_VOUT_SEL, ldoLevel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_RT_VOUT_SEL, ldoLevel); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - - /* Select RC32M */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - /* Set HBN flag */ - BL_WR_REG(HBN_BASE, HBN_RSV0, HBN_STATUS_ENTER_FLAG); - - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - - /* Set HBN level, (HBN_PWRDN_HBN_RAM not use) */ - switch (hbnLevel) { - case HBN_LEVEL_0: - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_1: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_2: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_3: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - default: - break; - } - - /* Set power on option:0 for por reset twice for robust 1 for reset only once*/ - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWR_ON_OPTION); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - - /* Enable HBN mode */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_MODE); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - - while (1) { - BL702_Delay_MS(1000); - } -} - -/****************************************************************************/ /** - * @brief Reset HBN mode - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Enter HBN + * + * @param cfg: HBN APP Config + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION HBN_Mode_Enter(HBN_APP_CFG_Type *cfg) { + uint32_t valLow = 0, valHigh = 0; + uint64_t val; + + /* work clock select */ + if (cfg->useXtal32k) { + HBN_32K_Sel(HBN_32K_XTAL); + } else { + HBN_32K_Sel(HBN_32K_RC); + HBN_Power_Off_Xtal_32K(); + } + + /* turn off RC32K during HBN */ + if ((cfg->hbnLevel) >= HBN_LEVEL_2) { + HBN_Power_Off_RC32K(); + } else { + HBN_Power_On_RC32K(); + } + + /* clear aon pad interrupt before config them */ + HBN_Clear_IRQ(HBN_INT_GPIO9); + HBN_Clear_IRQ(HBN_INT_GPIO10); + HBN_Clear_IRQ(HBN_INT_GPIO11); + HBN_Clear_IRQ(HBN_INT_GPIO12); + HBN_Clear_IRQ(HBN_INT_GPIO13); + + /* always disable HBN pin pull up/down to reduce PDS/HBN current, 0x4000F014[16]=0 */ + HBN_Hw_Pu_Pd_Cfg(DISABLE); + + HBN_Pin_WakeUp_Mask(~(cfg->gpioWakeupSrc)); + + if (cfg->gpioWakeupSrc != 0) { + HBN_Aon_Pad_IeSmt_Cfg(cfg->gpioWakeupSrc); + HBN_GPIO_INT_Enable(cfg->gpioTrigType); + } else { + HBN_Aon_Pad_IeSmt_Cfg(0); + } + + /* HBN RTC config and enable */ + if (cfg->sleepTime != 0) { + // set rtc enable flag + BL_WR_WORD(0x40010FFC, 0x1); + + HBN_Clear_RTC_Counter(); + HBN_Get_RTC_Timer_Val(&valLow, &valHigh); + val = valLow + ((uint64_t)valHigh << 32); + val += cfg->sleepTime; + HBN_Set_RTC_Timer(HBN_RTC_INT_DELAY_0T, val & 0xffffffff, val >> 32, HBN_RTC_COMP_BIT0_39); + HBN_Enable_RTC_Counter(); + } + + HBN_Power_Down_Flash(cfg->flashCfg); + + switch (cfg->flashPinCfg) { + case 0: + HBN_Set_Pad_23_28_Pullup(); + break; + + case 1: + /* need do nothing */ + break; + + case 2: + /* need do nothing */ + break; + + case 3: + /* can do nothing */ + break; + + default: + break; + } + + GLB_Set_System_CLK(GLB_DLL_XTAL_NONE, GLB_SYS_CLK_RC32M); + + /* power off xtal */ + AON_Power_Off_XTAL(); + + HBN_Enable_Ext(cfg->gpioWakeupSrc, cfg->ldoLevel, cfg->hbnLevel); +} + +/****************************************************************************/ /** + * @brief power down and switch clock + * + * @param flashCfg: None + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION HBN_Power_Down_Flash(SPI_Flash_Cfg_Type *flashCfg) { + SPI_Flash_Cfg_Type bhFlashCfg; + + if (flashCfg == NULL) { + /* fix this some time */ + /* SFlash_Cache_Flush(); */ + XIP_SFlash_Read_Via_Cache_Need_Lock(BL702_FLASH_XIP_BASE + 8 + 4, (uint8_t *)(&bhFlashCfg), sizeof(SPI_Flash_Cfg_Type)); + /* fix this some time */ + /* SFlash_Cache_Flush(); */ + + SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); + SFlash_Reset_Continue_Read(&bhFlashCfg); + } else { + SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); + SFlash_Reset_Continue_Read(flashCfg); + } + + SFlash_Powerdown(); +} + +/****************************************************************************/ /** + * @brief Enable HBN mode + * + * @param aGPIOIeCfg: AON GPIO IE config,Bit0->GPIO18. Bit(s) of Wakeup GPIO(s) must not be set to + * 0(s),say when use GPIO7 as wake up pin,aGPIOIeCfg should be 0x01. + * @param ldoLevel: LDO volatge level + * @param hbnLevel: HBN work level + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION HBN_Enable_Ext(uint8_t aGPIOIeCfg, HBN_LDO_LEVEL_Type ldoLevel, HBN_LEVEL_Type hbnLevel) { + uint32_t tmpVal; + + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LEVEL_TYPE(hbnLevel)); + + /* Setting from guide */ + /* RAM Retion, no longer use */ + /* BL_WR_REG(HBN_BASE,HBN_SRAM,0x24); */ + + /* AON GPIO IE */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aGPIOIeCfg); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + + /* HBN mode LDO level */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_AON_VOUT_SEL, ldoLevel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_RT_VOUT_SEL, ldoLevel); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + /* Select RC32M */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + /* Set HBN flag */ + BL_WR_REG(HBN_BASE, HBN_RSV0, HBN_STATUS_ENTER_FLAG); + + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + + /* Set HBN level, (HBN_PWRDN_HBN_RAM not use) */ + switch (hbnLevel) { + case HBN_LEVEL_0: + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_1: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_2: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_3: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + default: + break; + } + + /* Set power on option:0 for por reset twice for robust 1 for reset only once*/ + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWR_ON_OPTION); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + /* Enable HBN mode */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_MODE); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + while (1) { + BL702_Delay_MS(1000); + } +} + +/****************************************************************************/ /** + * @brief Reset HBN mode + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION HBN_Reset(void) -{ - uint32_t tmpVal; +BL_Err_Type ATTR_TCM_SECTION HBN_Reset(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Reset HBN mode */ - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_SW_RST); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Reset HBN mode */ + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_SW_RST); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_SW_RST); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_SW_RST); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_SW_RST); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_SW_RST); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief reset HBN by software - * - * @param npXtalType: NP clock type - * @param bclkDiv: NP clock div - * @param apXtalType: AP clock type - * @param fclkDiv: AP clock div - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_App_Reset(uint8_t npXtalType, uint8_t bclkDiv, uint8_t apXtalType, uint8_t fclkDiv) -{ - uint32_t tmp[12]; - - tmp[0] = BL_RD_REG(HBN_BASE, HBN_CTL); - tmp[1] = BL_RD_REG(HBN_BASE, HBN_TIME_L); - tmp[2] = BL_RD_REG(HBN_BASE, HBN_TIME_H); - tmp[3] = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmp[4] = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); - tmp[5] = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - tmp[6] = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); - tmp[7] = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); - tmp[8] = BL_RD_REG(HBN_BASE, HBN_SRAM); - tmp[9] = BL_RD_REG(HBN_BASE, HBN_RSV0); - tmp[10] = BL_RD_REG(HBN_BASE, HBN_RSV1); - tmp[11] = BL_RD_REG(HBN_BASE, HBN_RSV2); - /* DO HBN reset */ - HBN_Reset(); - /* HBN need 3 32k cyclce to recovery */ - BL702_Delay_US(100); - /* Recover HBN value */ - BL_WR_REG(HBN_BASE, HBN_TIME_L, tmp[1]); - BL_WR_REG(HBN_BASE, HBN_TIME_H, tmp[2]); - BL_WR_REG(HBN_BASE, HBN_CTL, tmp[0]); - - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmp[3]); - BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmp[4]); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmp[5]); - BL_WR_REG(HBN_BASE, HBN_PIR_VTH, tmp[6]); - BL_WR_REG(HBN_BASE, HBN_PIR_INTERVAL, tmp[7]); - BL_WR_REG(HBN_BASE, HBN_SRAM, tmp[8]); - BL_WR_REG(HBN_BASE, HBN_RSV0, tmp[9]); - BL_WR_REG(HBN_BASE, HBN_RSV1, tmp[10]); - BL_WR_REG(HBN_BASE, HBN_RSV2, tmp[11]); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Disable HBN mode - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Disable(void) -{ - uint32_t tmpVal; + * @brief reset HBN by software + * + * @param npXtalType: NP clock type + * @param bclkDiv: NP clock div + * @param apXtalType: AP clock type + * @param fclkDiv: AP clock div + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_App_Reset(uint8_t npXtalType, uint8_t bclkDiv, uint8_t apXtalType, uint8_t fclkDiv) { + uint32_t tmp[12]; + + tmp[0] = BL_RD_REG(HBN_BASE, HBN_CTL); + tmp[1] = BL_RD_REG(HBN_BASE, HBN_TIME_L); + tmp[2] = BL_RD_REG(HBN_BASE, HBN_TIME_H); + tmp[3] = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmp[4] = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); + tmp[5] = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); + tmp[6] = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); + tmp[7] = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); + tmp[8] = BL_RD_REG(HBN_BASE, HBN_SRAM); + tmp[9] = BL_RD_REG(HBN_BASE, HBN_RSV0); + tmp[10] = BL_RD_REG(HBN_BASE, HBN_RSV1); + tmp[11] = BL_RD_REG(HBN_BASE, HBN_RSV2); + /* DO HBN reset */ + HBN_Reset(); + /* HBN need 3 32k cyclce to recovery */ + BL702_Delay_US(100); + /* Recover HBN value */ + BL_WR_REG(HBN_BASE, HBN_TIME_L, tmp[1]); + BL_WR_REG(HBN_BASE, HBN_TIME_H, tmp[2]); + BL_WR_REG(HBN_BASE, HBN_CTL, tmp[0]); + + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmp[3]); + BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmp[4]); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmp[5]); + BL_WR_REG(HBN_BASE, HBN_PIR_VTH, tmp[6]); + BL_WR_REG(HBN_BASE, HBN_PIR_INTERVAL, tmp[7]); + BL_WR_REG(HBN_BASE, HBN_SRAM, tmp[8]); + BL_WR_REG(HBN_BASE, HBN_RSV0, tmp[9]); + BL_WR_REG(HBN_BASE, HBN_RSV1, tmp[10]); + BL_WR_REG(HBN_BASE, HBN_RSV2, tmp[11]); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Disable HBN mode + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Disable HBN mode */ + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_MODE); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Enable HBN PIR + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_PIR_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PIR_EN); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Disable HBN PIR + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_PIR_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PIR_EN); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief Config HBN PIR interrupt + * + * @param pirIntCfg: HBN PIR interrupt configuration + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_PIR_INT_Config(HBN_PIR_INT_CFG_Type *pirIntCfg) { + uint32_t tmpVal; + uint32_t bit4 = 0; + uint32_t bit5 = 0; + uint32_t bitVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Disable HBN mode */ - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_MODE); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - return SUCCESS; -} + /* low trigger interrupt */ + if (pirIntCfg->lowIntEn == ENABLE) { + bit5 = 0; + } else { + bit5 = 1; + } -/****************************************************************************/ /** - * @brief Enable HBN PIR - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_PIR_Enable(void) -{ - uint32_t tmpVal; + /* high trigger interrupt */ + if (pirIntCfg->highIntEn == ENABLE) { + bit4 = 0; + } else { + bit4 = 1; + } - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PIR_EN); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + bitVal = bit4 | (bit5 << 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_DIS, bitVal); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable HBN PIR - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_PIR_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PIR_EN); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + * @brief Select HBN PIR low pass filter + * + * @param lpf: HBN PIR low pass filter selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_PIR_LPF_Sel(HBN_PIR_LPF_Type lpf) { + uint32_t tmpVal; - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Config HBN PIR interrupt - * - * @param pirIntCfg: HBN PIR interrupt configuration - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_PIR_INT_Config(HBN_PIR_INT_CFG_Type *pirIntCfg) -{ - uint32_t tmpVal; - uint32_t bit4 = 0; - uint32_t bit5 = 0; - uint32_t bitVal = 0; - - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - - /* low trigger interrupt */ - if (pirIntCfg->lowIntEn == ENABLE) { - bit5 = 0; - } else { - bit5 = 1; - } + CHECK_PARAM(IS_HBN_PIR_LPF_TYPE(lpf)); - /* high trigger interrupt */ - if (pirIntCfg->highIntEn == ENABLE) { - bit4 = 0; - } else { - bit4 = 1; - } + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_LPF_SEL, lpf); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); - bitVal = bit4 | (bit5 << 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_DIS, bitVal); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); - - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Select HBN PIR low pass filter - * - * @param lpf: HBN PIR low pass filter selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_PIR_LPF_Sel(HBN_PIR_LPF_Type lpf) -{ - uint32_t tmpVal; + * @brief Select HBN PIR high pass filter + * + * @param hpf: HBN PIR high pass filter selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_PIR_HPF_Sel(HBN_PIR_HPF_Type hpf) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_PIR_LPF_TYPE(lpf)); + CHECK_PARAM(IS_HBN_PIR_HPF_TYPE(hpf)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_LPF_SEL, lpf); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_HPF_SEL, hpf); + BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Select HBN PIR high pass filter - * - * @param hpf: HBN PIR high pass filter selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_PIR_HPF_Sel(HBN_PIR_HPF_Type hpf) -{ - uint32_t tmpVal; + * @brief Set HBN PIR threshold value + * + * @param threshold: HBN PIR threshold value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_PIR_Threshold(uint16_t threshold) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_PIR_HPF_TYPE(hpf)); + CHECK_PARAM((threshold <= 0x3FFF)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_CFG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_HPF_SEL, hpf); - BL_WR_REG(HBN_BASE, HBN_PIR_CFG, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_VTH, threshold); + BL_WR_REG(HBN_BASE, HBN_PIR_VTH, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set HBN PIR threshold value - * - * @param threshold: HBN PIR threshold value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_PIR_Threshold(uint16_t threshold) -{ - uint32_t tmpVal; - - CHECK_PARAM((threshold <= 0x3FFF)); + * @brief Get HBN PIR threshold value + * + * @param None + * + * @return HBN PIR threshold value + * + *******************************************************************************/ +uint16_t HBN_Get_PIR_Threshold(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_VTH, threshold); - BL_WR_REG(HBN_BASE, HBN_PIR_VTH, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); - return SUCCESS; + return BL_GET_REG_BITS_VAL(tmpVal, HBN_PIR_VTH); } /****************************************************************************/ /** - * @brief Get HBN PIR threshold value - * - * @param None - * - * @return HBN PIR threshold value - * -*******************************************************************************/ -uint16_t HBN_Get_PIR_Threshold(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_VTH); - - return BL_GET_REG_BITS_VAL(tmpVal, HBN_PIR_VTH); -} + * @brief Set HBN PIR interval value + * + * @param interval: HBN PIR interval value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_PIR_Interval(uint16_t interval) { + uint32_t tmpVal; -/****************************************************************************/ /** - * @brief Set HBN PIR interval value - * - * @param interval: HBN PIR interval value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_PIR_Interval(uint16_t interval) -{ - uint32_t tmpVal; + CHECK_PARAM((interval <= 0xFFF)); - CHECK_PARAM((interval <= 0xFFF)); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_INTERVAL, interval); + BL_WR_REG(HBN_BASE, HBN_PIR_INTERVAL, tmpVal); - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIR_INTERVAL, interval); - BL_WR_REG(HBN_BASE, HBN_PIR_INTERVAL, tmpVal); - - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Get HBN PIR interval value - * - * @param None - * - * @return HBN PIR interval value - * -*******************************************************************************/ -uint16_t HBN_Get_PIR_Interval(void) -{ - uint32_t tmpVal; + * @brief Get HBN PIR interval value + * + * @param None + * + * @return HBN PIR interval value + * + *******************************************************************************/ +uint16_t HBN_Get_PIR_Interval(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); + tmpVal = BL_RD_REG(HBN_BASE, HBN_PIR_INTERVAL); - return BL_GET_REG_BITS_VAL(tmpVal, HBN_PIR_INTERVAL); + return BL_GET_REG_BITS_VAL(tmpVal, HBN_PIR_INTERVAL); } /****************************************************************************/ /** - * @brief get HBN bor out state - * - * @param None - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type HBN_Get_BOR_OUT_State(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(HBN_BASE, HBN_MISC), HBN_R_BOR_OUT) ? SET : RESET; -} + * @brief get HBN bor out state + * + * @param None + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type HBN_Get_BOR_OUT_State(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(HBN_BASE, HBN_MISC), HBN_R_BOR_OUT) ? SET : RESET; } /****************************************************************************/ /** - * @brief set HBN bor config - * - * @param enable: ENABLE or DISABLE, if enable, Power up Brown Out Reset - * @param threshold: bor threshold - * @param mode: bor work mode with por - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_BOR_Config(uint8_t enable, HBN_BOR_THRES_Type threshold, HBN_BOR_MODE_Type mode) -{ - uint32_t tmpVal; + * @brief set HBN bor config + * + * @param enable: ENABLE or DISABLE, if enable, Power up Brown Out Reset + * @param threshold: bor threshold + * @param mode: bor work mode with por + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_BOR_Config(uint8_t enable, HBN_BOR_THRES_Type threshold, HBN_BOR_MODE_Type mode) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_BOR_THRES_TYPE(threshold)); - CHECK_PARAM(IS_HBN_BOR_MODE_TYPE(mode)); + CHECK_PARAM(IS_HBN_BOR_THRES_TYPE(threshold)); + CHECK_PARAM(IS_HBN_BOR_MODE_TYPE(mode)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - if (enable) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PU_BOR, 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PU_BOR, 0); - } + if (enable) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PU_BOR, 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PU_BOR, 0); + } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_VTH, threshold); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_SEL, mode); - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_VTH, threshold); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_SEL, mode); + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN set ldo11aon voltage out - * - * @param ldoLevel: LDO volatge level - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Aon_Vout(HBN_LDO_LEVEL_Type ldoLevel) -{ - uint32_t tmpVal; + * @brief HBN set ldo11aon voltage out + * + * @param ldoLevel: LDO volatge level + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Aon_Vout(HBN_LDO_LEVEL_Type ldoLevel) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_AON_VOUT_SEL, ldoLevel); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_AON_VOUT_SEL, ldoLevel); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN set ldo11rt voltage out - * - * @param ldoLevel: LDO volatge level - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Rt_Vout(HBN_LDO_LEVEL_Type ldoLevel) -{ - uint32_t tmpVal; + * @brief HBN set ldo11rt voltage out + * + * @param ldoLevel: LDO volatge level + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Rt_Vout(HBN_LDO_LEVEL_Type ldoLevel) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_RT_VOUT_SEL, ldoLevel); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_RT_VOUT_SEL, ldoLevel); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN set ldo11soc voltage out - * - * @param ldoLevel: LDO volatge level - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Soc_Vout(HBN_LDO_LEVEL_Type ldoLevel) -{ - uint32_t tmpVal; + * @brief HBN set ldo11soc voltage out + * + * @param ldoLevel: LDO volatge level + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Soc_Vout(HBN_LDO_LEVEL_Type ldoLevel) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11SOC_VOUT_SEL_AON, ldoLevel); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11SOC_VOUT_SEL_AON, ldoLevel); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN set ldo11 all voltage out - * - * @param ldoLevel: LDO volatge level - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_All_Vout(HBN_LDO_LEVEL_Type ldoLevel) -{ - uint32_t tmpVal; + * @brief HBN set ldo11 all voltage out + * + * @param ldoLevel: LDO volatge level + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_All_Vout(HBN_LDO_LEVEL_Type ldoLevel) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_AON_VOUT_SEL, ldoLevel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_RT_VOUT_SEL, ldoLevel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11SOC_VOUT_SEL_AON, ldoLevel); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_AON_VOUT_SEL, ldoLevel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11_RT_VOUT_SEL, ldoLevel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_SW_LDO11SOC_VOUT_SEL_AON, ldoLevel); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN set ldo11rt drive strength - * - * @param strength: ldo11rt drive strength - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11rt_Drive_Strength(HBN_LDO11RT_DRIVE_STRENGTH_Type strength) -{ - uint32_t tmpVal; + * @brief HBN set ldo11rt drive strength + * + * @param strength: ldo11rt drive strength + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11rt_Drive_Strength(HBN_LDO11RT_DRIVE_STRENGTH_Type strength) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_LDO11RT_DRIVE_STRENGTH_TYPE(strength)); + CHECK_PARAM(IS_HBN_LDO11RT_DRIVE_STRENGTH_TYPE(strength)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_RT_ILOAD_SEL, strength); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_LDO11_RT_ILOAD_SEL, strength); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN select 32K - * - * @param clkType: HBN 32k clock type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION HBN_32K_Sel(HBN_32K_CLK_Type clkType) -{ - uint32_t tmpVal; + * @brief HBN select 32K + * + * @param clkType: HBN 32k clock type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION HBN_32K_Sel(HBN_32K_CLK_Type clkType) { + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_HBN_32K_CLK_TYPE(clkType)); + /* Check the parameters */ + CHECK_PARAM(IS_HBN_32K_CLK_TYPE(clkType)); - HBN_Trim_RC32K(); + HBN_Trim_RC32K(); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_F32K_SEL, clkType); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_F32K_SEL, clkType); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Select uart clock source - * - * @param clkSel: uart clock type selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_UART_CLK_Sel(HBN_UART_CLK_Type clkSel) -{ - uint32_t tmpVal; + * @brief Select uart clock source + * + * @param clkSel: uart clock type selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_UART_CLK_Sel(HBN_UART_CLK_Type clkSel) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_UART_CLK_TYPE(clkSel)); + CHECK_PARAM(IS_HBN_UART_CLK_TYPE(clkSel)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_UART_CLK_SEL, clkSel); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_UART_CLK_SEL, clkSel); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Select xclk clock source - * - * @param xClk: xclk clock type selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_XCLK_CLK_Sel(HBN_XCLK_CLK_Type xClk) -{ - uint32_t tmpVal; - uint32_t tmpVal2; + * @brief Select xclk clock source + * + * @param xClk: xclk clock type selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_XCLK_CLK_Sel(HBN_XCLK_CLK_Type xClk) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_XCLK_CLK_TYPE(xClk)); + CHECK_PARAM(IS_HBN_XCLK_CLK_TYPE(xClk)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL); - switch (xClk) { - case HBN_XCLK_CLK_RC32M: - tmpVal2 &= (~(1 << 0)); - break; + switch (xClk) { + case HBN_XCLK_CLK_RC32M: + tmpVal2 &= (~(1 << 0)); + break; - case HBN_XCLK_CLK_XTAL: - tmpVal2 |= (1 << 0); - break; + case HBN_XCLK_CLK_XTAL: + tmpVal2 |= (1 << 0); + break; - default: - break; - } + default: + break; + } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - HBN_CLK_SET_DUMMY_WAIT; + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + HBN_CLK_SET_DUMMY_WAIT; - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Select root clk source - * - * @param rootClk: root clock type selection - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Select root clk source + * + * @param rootClk: root clock type selection + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_Type rootClk) -{ - uint32_t tmpVal; - uint32_t tmpVal2; +BL_Err_Type ATTR_CLOCK_SECTION HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_Type rootClk) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_ROOT_CLK_TYPE(rootClk)); + CHECK_PARAM(IS_HBN_ROOT_CLK_TYPE(rootClk)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL); - switch (rootClk) { - case HBN_ROOT_CLK_RC32M: - tmpVal2 = 0x0; - break; + switch (rootClk) { + case HBN_ROOT_CLK_RC32M: + tmpVal2 = 0x0; + break; - case HBN_ROOT_CLK_XTAL: - tmpVal2 = 0x1; - break; + case HBN_ROOT_CLK_XTAL: + tmpVal2 = 0x1; + break; - case HBN_ROOT_CLK_DLL: - tmpVal2 |= (1 << 1); - break; + case HBN_ROOT_CLK_DLL: + tmpVal2 |= (1 << 1); + break; - default: - break; - } + default: + break; + } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - HBN_CLK_SET_DUMMY_WAIT; + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + HBN_CLK_SET_DUMMY_WAIT; - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief set HBN_RAM sleep mode - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_HRAM_slp(void) -{ - uint32_t tmpVal = 0; + * @brief set HBN_RAM sleep mode + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_HRAM_slp(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_SRAM); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RETRAM_SLP); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RETRAM_RET); - BL_WR_REG(HBN_BASE, HBN_SRAM, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_SRAM); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RETRAM_SLP); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RETRAM_RET); + BL_WR_REG(HBN_BASE, HBN_SRAM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief set HBN_RAM retension mode - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_HRAM_Ret(void) -{ - uint32_t tmpVal = 0; + * @brief set HBN_RAM retension mode + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_HRAM_Ret(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_SRAM); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RETRAM_SLP); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RETRAM_RET); - BL_WR_REG(HBN_BASE, HBN_SRAM, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_SRAM); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RETRAM_SLP); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RETRAM_RET); + BL_WR_REG(HBN_BASE, HBN_SRAM, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on XTAL 32K - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_Xtal_32K(void) -{ - uint32_t tmpVal = 0; + * @brief Power on XTAL 32K + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_Xtal_32K(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_XTAL32K); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_XTAL32K); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_XTAL32K_BUF); - BL_WR_REG(HBN_BASE, HBN_XTAL32K, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_XTAL32K); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_XTAL32K); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_XTAL32K_BUF); + BL_WR_REG(HBN_BASE, HBN_XTAL32K, tmpVal); - /* Delay >1s */ - BL702_Delay_US(1100); + /* Delay >1s */ + BL702_Delay_US(1100); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off XTAL 32K - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_Xtal_32K(void) -{ - uint32_t tmpVal = 0; + * @brief Power off XTAL 32K + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_Xtal_32K(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_XTAL32K); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_XTAL32K); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_XTAL32K_BUF); - BL_WR_REG(HBN_BASE, HBN_XTAL32K, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_XTAL32K); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_XTAL32K); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_XTAL32K_BUF); + BL_WR_REG(HBN_BASE, HBN_XTAL32K, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Power on RC32K - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_RC32K(void) -{ - uint32_t tmpVal = 0; + * @brief Power on RC32K + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_RC32K(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_RC32K); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_RC32K); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - /* Delay >800us */ - BL702_Delay_US(880); + /* Delay >800us */ + BL702_Delay_US(880); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Power off RC3K - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_RC32K(void) -{ - uint32_t tmpVal = 0; + * @brief Power off RC3K + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_RC32K(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_RC32K); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_RC32K); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Trim RC32K - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Trim RC32K + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION HBN_Trim_RC32K(void) -{ - Efuse_Ana_RC32K_Trim_Type trim; - int32_t tmpVal = 0; - - EF_Ctrl_Read_RC32K_Trim(&trim); - - if (trim.trimRc32kExtCodeEn) { - if (trim.trimRc32kCodeFrExtParity == EF_Ctrl_Get_Trim_Parity(trim.trimRc32kCodeFrExt, 10)) { - tmpVal = BL_RD_REG(HBN_BASE, HBN_RC32K_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RC32K_CODE_FR_EXT, trim.trimRc32kCodeFrExt); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RC32K_EXT_CODE_EN); - BL_WR_REG(HBN_BASE, HBN_RC32K_CTRL0, tmpVal); - BL702_Delay_US(2); - return SUCCESS; - } +BL_Err_Type ATTR_CLOCK_SECTION HBN_Trim_RC32K(void) { + Efuse_Ana_RC32K_Trim_Type trim; + int32_t tmpVal = 0; + + EF_Ctrl_Read_RC32K_Trim(&trim); + + if (trim.trimRc32kExtCodeEn) { + if (trim.trimRc32kCodeFrExtParity == EF_Ctrl_Get_Trim_Parity(trim.trimRc32kCodeFrExt, 10)) { + tmpVal = BL_RD_REG(HBN_BASE, HBN_RC32K_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RC32K_CODE_FR_EXT, trim.trimRc32kCodeFrExt); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RC32K_EXT_CODE_EN); + BL_WR_REG(HBN_BASE, HBN_RC32K_CTRL0, tmpVal); + BL702_Delay_US(2); + return SUCCESS; } + } - return ERROR; + return ERROR; } #endif /****************************************************************************/ /** - * @brief Get HBN status flag - * - * @param None - * - * @return HBN status flag value - * -*******************************************************************************/ -uint32_t HBN_Get_Status_Flag(void) -{ - return BL_RD_REG(HBN_BASE, HBN_RSV0); -} + * @brief Get HBN status flag + * + * @param None + * + * @return HBN status flag value + * + *******************************************************************************/ +uint32_t HBN_Get_Status_Flag(void) { return BL_RD_REG(HBN_BASE, HBN_RSV0); } -/****************************************************************************/ /** - * @brief Set HBN status flag - * - * @param flag: Status Flag - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_Status_Flag(uint32_t flag) -{ - BL_WR_REG(HBN_BASE, HBN_RSV0, flag); +/****************************************************************************/ /** + * @brief Set HBN status flag + * + * @param flag: Status Flag + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_Status_Flag(uint32_t flag) { + BL_WR_REG(HBN_BASE, HBN_RSV0, flag); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Get HBN wakeup address - * - * @param None - * - * @return HBN wakeup address - * -*******************************************************************************/ -uint32_t HBN_Get_Wakeup_Addr(void) -{ - return BL_RD_REG(HBN_BASE, HBN_RSV1); -} + * @brief Get HBN wakeup address + * + * @param None + * + * @return HBN wakeup address + * + *******************************************************************************/ +uint32_t HBN_Get_Wakeup_Addr(void) { return BL_RD_REG(HBN_BASE, HBN_RSV1); } -/****************************************************************************/ /** - * @brief Set HBN wakeup address - * - * @param addr: HBN wakeup address - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_Wakeup_Addr(uint32_t addr) -{ - BL_WR_REG(HBN_BASE, HBN_RSV1, addr); +/****************************************************************************/ /** + * @brief Set HBN wakeup address + * + * @param addr: HBN wakeup address + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_Wakeup_Addr(uint32_t addr) { + BL_WR_REG(HBN_BASE, HBN_RSV1, addr); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN clear RTC timer counter - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Clear_RTC_Counter(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Clear RTC control bit0 */ - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffffe); - - return SUCCESS; -} + * @brief HBN clear RTC timer counter + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Clear_RTC_Counter(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Clear RTC control bit0 */ + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffffe); + + return SUCCESS; +} /****************************************************************************/ /** - * @brief HBN clear RTC timer counter - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Enable_RTC_Counter(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Set RTC control bit0 */ - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal | 0x01); - - return SUCCESS; -} + * @brief HBN clear RTC timer counter + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Enable_RTC_Counter(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Set RTC control bit0 */ + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal | 0x01); + + return SUCCESS; +} /****************************************************************************/ /** - * @brief HBN set RTC timer configuration - * - * @param delay: RTC interrupt delay 32 clocks - * @param compValLow: RTC interrupt commpare value low 32 bits - * @param compValHigh: RTC interrupt commpare value high 32 bits - * @param compMode: RTC interrupt commpare - * mode:HBN_RTC_COMP_BIT0_39,HBN_RTC_COMP_BIT0_23,HBN_RTC_COMP_BIT13_39 - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_RTC_Timer(HBN_RTC_INT_Delay_Type delay, uint32_t compValLow, uint32_t compValHigh, uint8_t compMode) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_HBN_RTC_INT_DELAY_TYPE(delay)); + * @brief HBN set RTC timer configuration + * + * @param delay: RTC interrupt delay 32 clocks + * @param compValLow: RTC interrupt commpare value low 32 bits + * @param compValHigh: RTC interrupt commpare value high 32 bits + * @param compMode: RTC interrupt commpare + * mode:HBN_RTC_COMP_BIT0_39,HBN_RTC_COMP_BIT0_23,HBN_RTC_COMP_BIT13_39 + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_RTC_Timer(HBN_RTC_INT_Delay_Type delay, uint32_t compValLow, uint32_t compValHigh, uint8_t compMode) { + uint32_t tmpVal; - BL_WR_REG(HBN_BASE, HBN_TIME_L, compValLow); - BL_WR_REG(HBN_BASE, HBN_TIME_H, compValHigh & 0xff); + /* Check the parameters */ + CHECK_PARAM(IS_HBN_RTC_INT_DELAY_TYPE(delay)); + + BL_WR_REG(HBN_BASE, HBN_TIME_L, compValLow); + BL_WR_REG(HBN_BASE, HBN_TIME_H, compValHigh & 0xff); - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Set interrupt delay option */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RTC_DLY_OPTION, delay); - /* Set RTC compare mode */ - tmpVal |= (compMode << 1); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Set interrupt delay option */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_RTC_DLY_OPTION, delay); + /* Set RTC compare mode */ + tmpVal |= (compMode << 1); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN get RTC async timer count value - * - * @param valLow: RTC count value pointer for low 32 bits - * @param valHigh: RTC count value pointer for high 8 bits - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -static BL_Err_Type HBN_Get_RTC_Timer_Async_Val(uint32_t *valLow, uint32_t *valHigh) -{ - uint32_t tmpVal; + * @brief HBN get RTC async timer count value + * + * @param valLow: RTC count value pointer for low 32 bits + * @param valHigh: RTC count value pointer for high 8 bits + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +static BL_Err_Type HBN_Get_RTC_Timer_Async_Val(uint32_t *valLow, uint32_t *valHigh) { + uint32_t tmpVal; - /* Tigger RTC val read */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH); - BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH); - BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal); + /* Tigger RTC val read */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH); + BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_RTC_TIME_LATCH); + BL_WR_REG(HBN_BASE, HBN_RTC_TIME_H, tmpVal); - /* Read RTC val */ - *valLow = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L); - *valHigh = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff); + /* Read RTC val */ + *valLow = BL_RD_REG(HBN_BASE, HBN_RTC_TIME_L); + *valHigh = (BL_RD_REG(HBN_BASE, HBN_RTC_TIME_H) & 0xff); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN get RTC timer count value - * - * @param valLow: RTC count value pointer for low 32 bits - * @param valHigh: RTC count value pointer for high 8 bits - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Get_RTC_Timer_Val(uint32_t *valLow, uint32_t *valHigh) -{ - uint32_t tmpValLow, tmpValHigh, tmpValLow1, tmpValHigh1; - uint64_t val, val1; + * @brief HBN get RTC timer count value + * + * @param valLow: RTC count value pointer for low 32 bits + * @param valHigh: RTC count value pointer for high 8 bits + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Get_RTC_Timer_Val(uint32_t *valLow, uint32_t *valHigh) { + uint32_t tmpValLow, tmpValHigh, tmpValLow1, tmpValHigh1; + uint64_t val, val1; - do { - HBN_Get_RTC_Timer_Async_Val(&tmpValLow, &tmpValHigh); - val = ((uint64_t)tmpValHigh << 32) | ((uint64_t)tmpValLow); - HBN_Get_RTC_Timer_Async_Val(&tmpValLow1, &tmpValHigh1); - val1 = ((uint64_t)tmpValHigh1 << 32) | ((uint64_t)tmpValLow1); - } while (val1 < val); + do { + HBN_Get_RTC_Timer_Async_Val(&tmpValLow, &tmpValHigh); + val = ((uint64_t)tmpValHigh << 32) | ((uint64_t)tmpValLow); + HBN_Get_RTC_Timer_Async_Val(&tmpValLow1, &tmpValHigh1); + val1 = ((uint64_t)tmpValHigh1 << 32) | ((uint64_t)tmpValLow1); + } while (val1 < val); - *valLow = tmpValLow1; - *valHigh = tmpValHigh1; + *valLow = tmpValLow1; + *valHigh = tmpValHigh1; - return SUCCESS; + return SUCCESS; } -/****************************************************************************/ /** - * @brief HBN clear RTC timer interrupt,this function must be called to clear delayed rtc IRQ - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Clear_RTC_INT(void) -{ - uint32_t tmpVal; +/****************************************************************************/ /** + * @brief HBN clear RTC timer interrupt,this function must be called to clear delayed rtc IRQ + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Clear_RTC_INT(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - /* Clear RTC commpare:bit1-3 for clearing Delayed RTC IRQ */ - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffff1); + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + /* Clear RTC commpare:bit1-3 for clearing Delayed RTC IRQ */ + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal & 0xfffffff1); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN enable GPIO interrupt - * - * @param gpioIntTrigType: HBN GPIO interrupt trigger type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_GPIO_INT_Enable(HBN_GPIO_INT_Trigger_Type gpioIntTrigType) -{ - uint32_t tmpVal; + * @brief HBN enable GPIO interrupt + * + * @param gpioIntTrigType: HBN GPIO interrupt trigger type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_GPIO_INT_Enable(HBN_GPIO_INT_Trigger_Type gpioIntTrigType) { + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_HBN_GPIO_INT_TRIGGER_TYPE(gpioIntTrigType)); + /* Check the parameters */ + CHECK_PARAM(IS_HBN_GPIO_INT_TRIGGER_TYPE(gpioIntTrigType)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MODE, gpioIntTrigType); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MODE, gpioIntTrigType); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN disable GPIO interrupt - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_GPIO_INT_Disable(void) -{ - uint32_t tmpVal; + * @brief HBN disable GPIO interrupt + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_GPIO_INT_Disable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MASK, 0); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MASK, 0); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN get interrupt status - * - * @param irqType: HBN interrupt type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type HBN_Get_INT_State(HBN_INT_Type irqType) -{ - uint32_t tmpVal; + * @brief HBN get interrupt status + * + * @param irqType: HBN interrupt type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type HBN_Get_INT_State(HBN_INT_Type irqType) { + uint32_t tmpVal; - /* Check the parameters */ + /* Check the parameters */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_STAT); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_STAT); - if (tmpVal & (1 << irqType)) { - return SET; - } else { - return RESET; - } + if (tmpVal & (1 << irqType)) { + return SET; + } else { + return RESET; + } } /****************************************************************************/ /** - * @brief HBN get pin wakeup mode value - * - * @param None - * - * @return HBN pin wakeup mode value - * -*******************************************************************************/ -uint8_t HBN_Get_Pin_Wakeup_Mode(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(HBN_BASE, HBN_IRQ_MODE), HBN_PIN_WAKEUP_MODE); -} + * @brief HBN get pin wakeup mode value + * + * @param None + * + * @return HBN pin wakeup mode value + * + *******************************************************************************/ +uint8_t HBN_Get_Pin_Wakeup_Mode(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(HBN_BASE, HBN_IRQ_MODE), HBN_PIN_WAKEUP_MODE); } /****************************************************************************/ /** - * @brief HBN clear interrupt status - * - * @param irqType: HBN interrupt type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Clear_IRQ(HBN_INT_Type irqType) -{ - uint32_t tmpVal; + * @brief HBN clear interrupt status + * + * @param irqType: HBN interrupt type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Clear_IRQ(HBN_INT_Type irqType) { + uint32_t tmpVal; - CHECK_PARAM(IS_HBN_INT_TYPE(irqType)); + CHECK_PARAM(IS_HBN_INT_TYPE(irqType)); - /* set clear bit */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); - tmpVal |= (1 << irqType); - BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmpVal); + /* set clear bit */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); + tmpVal |= (1 << irqType); + BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmpVal); - /* unset clear bit */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); - tmpVal &= (~(1 << irqType)); - BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmpVal); + /* unset clear bit */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_CLR); + tmpVal &= (~(1 << irqType)); + BL_WR_REG(HBN_BASE, HBN_IRQ_CLR, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN hardware pullup or pulldown configuration - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Hw_Pu_Pd_Cfg(uint8_t enable) -{ - uint32_t tmpVal; + * @brief HBN hardware pullup or pulldown configuration + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Hw_Pu_Pd_Cfg(uint8_t enable) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); - } + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); + } - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN Config AON pad input and SMT - * - * @param padCfg: AON pad config - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Aon_Pad_IeSmt_Cfg(uint8_t padCfg) -{ - uint32_t tmpVal; + * @brief HBN Config AON pad input and SMT + * + * @param padCfg: AON pad config + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Aon_Pad_IeSmt_Cfg(uint8_t padCfg) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, padCfg); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, padCfg); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN wakeup pin mask configuration - * - * @param maskVal: mask value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Pin_WakeUp_Mask(uint8_t maskVal) -{ - uint32_t tmpVal; + * @brief HBN wakeup pin mask configuration + * + * @param maskVal: mask value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Pin_WakeUp_Mask(uint8_t maskVal) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MASK, maskVal); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_MASK, maskVal); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN enable ACOMP0 interrupt - * - * @param edge: HBN acomp interrupt edge type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Enable_AComp0_IRQ(HBN_ACOMP_INT_EDGE_Type edge) -{ - uint32_t tmpVal; - uint32_t tmpVal2; + * @brief HBN enable ACOMP0 interrupt + * + * @param edge: HBN acomp interrupt edge type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Enable_AComp0_IRQ(HBN_ACOMP_INT_EDGE_Type edge) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); + CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN); - tmpVal2 = tmpVal2 | (1 << edge); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN); + tmpVal2 = tmpVal2 | (1 << edge); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN disable ACOMP0 interrupt - * - * @param edge: HBN acomp interrupt edge type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Disable_AComp0_IRQ(HBN_ACOMP_INT_EDGE_Type edge) -{ - uint32_t tmpVal; - uint32_t tmpVal2; + * @brief HBN disable ACOMP0 interrupt + * + * @param edge: HBN acomp interrupt edge type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Disable_AComp0_IRQ(HBN_ACOMP_INT_EDGE_Type edge) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); + CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN); - tmpVal2 = tmpVal2 & (~(1 << edge)); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN); + tmpVal2 = tmpVal2 & (~(1 << edge)); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP0_EN, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN enable ACOMP1 interrupt - * - * @param edge: HBN acomp interrupt edge type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Enable_AComp1_IRQ(HBN_ACOMP_INT_EDGE_Type edge) -{ - uint32_t tmpVal; - uint32_t tmpVal2; + * @brief HBN enable ACOMP1 interrupt + * + * @param edge: HBN acomp interrupt edge type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Enable_AComp1_IRQ(HBN_ACOMP_INT_EDGE_Type edge) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); + CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN); - tmpVal2 = tmpVal2 | (1 << edge); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN); + tmpVal2 = tmpVal2 | (1 << edge); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN disable ACOMP1 interrupt - * - * @param edge: HBN acomp interrupt edge type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Disable_AComp1_IRQ(HBN_ACOMP_INT_EDGE_Type edge) -{ - uint32_t tmpVal; - uint32_t tmpVal2; + * @brief HBN disable ACOMP1 interrupt + * + * @param edge: HBN acomp interrupt edge type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Disable_AComp1_IRQ(HBN_ACOMP_INT_EDGE_Type edge) { + uint32_t tmpVal; + uint32_t tmpVal2; - CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); + CHECK_PARAM(IS_HBN_ACOMP_INT_EDGE_TYPE(edge)); - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN); - tmpVal2 = tmpVal2 & (~(1 << edge)); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN, tmpVal2); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal2 = BL_GET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN); + tmpVal2 = tmpVal2 & (~(1 << edge)); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_IRQ_ACOMP1_EN, tmpVal2); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN enable BOR interrupt - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Enable_BOR_IRQ(void) -{ - uint32_t tmpVal; + * @brief HBN enable BOR interrupt + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Enable_BOR_IRQ(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_IRQ_BOR_EN); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_IRQ_BOR_EN); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN disable BOR interrupt - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Disable_BOR_IRQ(void) -{ - uint32_t tmpVal; + * @brief HBN disable BOR interrupt + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Disable_BOR_IRQ(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_IRQ_BOR_EN); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_IRQ_BOR_EN); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief get HBN reset event status - * - * @param event: HBN reset event type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type HBN_Get_Reset_Event(HBN_RST_EVENT_Type event) -{ - uint32_t tmpVal; + * @brief get HBN reset event status + * + * @param event: HBN reset event type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type HBN_Get_Reset_Event(HBN_RST_EVENT_Type event) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, HBN_RESET_EVENT); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, HBN_RESET_EVENT); - return (tmpVal & (1 << event)) ? SET : RESET; + return (tmpVal & (1 << event)) ? SET : RESET; } /****************************************************************************/ /** - * @brief clear HBN reset event status - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Clear_Reset_Event(void) -{ - uint32_t tmpVal; + * @brief clear HBN reset event status + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Clear_Reset_Event(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_CLEAR_RESET_EVENT); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN out0 install interrupt callback - * - * @param intType: HBN out0 interrupt type - * @param cbFun: HBN out0 interrupt callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Out0_Callback_Install(HBN_OUT0_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_HBN_OUT0_INT_TYPE(intType)); + * @brief HBN out0 install interrupt callback + * + * @param intType: HBN out0 interrupt type + * @param cbFun: HBN out0 interrupt callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Out0_Callback_Install(HBN_OUT0_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_HBN_OUT0_INT_TYPE(intType)); - hbnInt0CbfArra[intType] = cbFun; + hbnInt0CbfArra[intType] = cbFun; - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN out1 install interrupt callback - * - * @param intType: HBN out1 interrupt type - * @param cbFun: HBN out1 interrupt callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Out1_Callback_Install(HBN_OUT1_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_HBN_OUT1_INT_TYPE(intType)); + * @brief HBN out1 install interrupt callback + * + * @param intType: HBN out1 interrupt type + * @param cbFun: HBN out1 interrupt callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Out1_Callback_Install(HBN_OUT1_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_HBN_OUT1_INT_TYPE(intType)); - hbnInt1CbfArra[intType] = cbFun; + hbnInt1CbfArra[intType] = cbFun; - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN GPIO debug pull config - * - * @param pupdEn: Enable or disable GPIO pull down and pull up - * @param dlyEn: Enable or disable GPIO wakeup delay function - * @param dlySec: GPIO wakeup delay sec 1 to 7 - * @param gpioIrq: HBN GPIO num - * @param gpioMask: HBN GPIO MASK or UNMASK - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief HBN GPIO debug pull config + * + * @param pupdEn: Enable or disable GPIO pull down and pull up + * @param dlyEn: Enable or disable GPIO wakeup delay function + * @param dlySec: GPIO wakeup delay sec 1 to 7 + * @param gpioIrq: HBN GPIO num + * @param gpioMask: HBN GPIO MASK or UNMASK + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION HBN_GPIO_Dbg_Pull_Cfg(BL_Fun_Type pupdEn, BL_Fun_Type dlyEn, uint8_t dlySec, HBN_INT_Type gpioIrq, BL_Mask_Type gpioMask) -{ - uint32_t tmpVal; - - CHECK_PARAM(((dlySec >= 1) && (dlySec <= 7))); - CHECK_PARAM((gpioIrq >= HBN_INT_GPIO9) && (gpioIrq <= HBN_INT_GPIO13)); - - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_EN, dlyEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_SEL, dlySec); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_EN_HW_PU_PD, pupdEn); - - if (gpioMask != UNMASK) { - tmpVal = tmpVal | (1 << (gpioIrq + 8)); - } else { - tmpVal = tmpVal & ~(1 << (gpioIrq + 8)); - } +BL_Err_Type ATTR_TCM_SECTION HBN_GPIO_Dbg_Pull_Cfg(BL_Fun_Type pupdEn, BL_Fun_Type dlyEn, uint8_t dlySec, HBN_INT_Type gpioIrq, BL_Mask_Type gpioMask) { + uint32_t tmpVal; + + CHECK_PARAM(((dlySec >= 1) && (dlySec <= 7))); + CHECK_PARAM((gpioIrq >= HBN_INT_GPIO9) && (gpioIrq <= HBN_INT_GPIO13)); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_EN, dlyEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_PIN_WAKEUP_SEL, dlySec); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_EN_HW_PU_PD, pupdEn); - return SUCCESS; + if (gpioMask != UNMASK) { + tmpVal = tmpVal | (1 << (gpioIrq + 8)); + } else { + tmpVal = tmpVal & ~(1 << (gpioIrq + 8)); + } + + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set pad 23-28 pull none - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pullnone(void) -{ - uint32_t tmpVal = 0; + * @brief Set pad 23-28 pull none + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pullnone(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x00); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x00); - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x00); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x00); + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set pad 23-28 pull up - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pullup(void) -{ - uint32_t tmpVal = 0; + * @brief Set pad 23-28 pull up + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pullup(void) { + uint32_t tmpVal = 0; - /********************************************/ - /* GPIO28 is bootpin, so leave it pull none */ - /********************************************/ + /********************************************/ + /* GPIO28 is bootpin, so leave it pull none */ + /********************************************/ - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x00); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x1F); - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x00); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x1F); + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set pad 23-28 pull down - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pulldown(void) -{ - uint32_t tmpVal = 0; + * @brief Set pad 23-28 pull down + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_Pulldown(void) { + uint32_t tmpVal = 0; - /********************************************/ - /* GPIO28 is bootpin, so leave it pull none */ - /********************************************/ + /********************************************/ + /* GPIO28 is bootpin, so leave it pull none */ + /********************************************/ - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x1F); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x00); - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x1F); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x00); + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set pad 23-28 active ie - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_ActiveIE(void) -{ - uint32_t tmpVal = 0; + * @brief Set pad 23-28 active ie + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Pad_23_28_ActiveIE(void) { + uint32_t tmpVal = 0; - /********************************************/ - /* GPIO28 is bootpin, so leave it pull none */ - /********************************************/ + /********************************************/ + /* GPIO28 is bootpin, so leave it pull none */ + /********************************************/ - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x1F); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x1F); - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLDOWN_AON, 0x1F); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_FLASH_PULLUP_AON, 0x1F); + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Set BOR config - * - * @param cfg: Enable or disable - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Set_BOR_Cfg(HBN_BOR_CFG_Type *cfg) -{ - uint32_t tmpVal = 0; - - if (cfg->enableBorInt) { - HBN_Enable_BOR_IRQ(); - } else { - HBN_Disable_BOR_IRQ(); - } + * @brief Set BOR config + * + * @param cfg: Enable or disable + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Set_BOR_Cfg(HBN_BOR_CFG_Type *cfg) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); + if (cfg->enableBorInt) { + HBN_Enable_BOR_IRQ(); + } else { + HBN_Disable_BOR_IRQ(); + } - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_VTH, cfg->borThreshold); + tmpVal = BL_RD_REG(HBN_BASE, HBN_MISC); - if (cfg->enablePorInBor) { - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_BOR_SEL); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_BOR_SEL); - } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_BOR_VTH, cfg->borThreshold); - if (cfg->enableBor) { - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_BOR); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_BOR); - } + if (cfg->enablePorInBor) { + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_BOR_SEL); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_BOR_SEL); + } - BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); + if (cfg->enableBor) { + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PU_BOR); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PU_BOR); + } + + BL_WR_REG(HBN_BASE, HBN_MISC, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief HBN OUT0 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ -void HBN_OUT0_IRQHandler(void) -{ - if (SET == HBN_Get_INT_State(HBN_INT_GPIO9)) { - HBN_Clear_IRQ(HBN_INT_GPIO9); - - if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO9] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_GPIO9](); - } + * @brief HBN OUT0 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ +void HBN_OUT0_IRQHandler(void) { + if (SET == HBN_Get_INT_State(HBN_INT_GPIO9)) { + HBN_Clear_IRQ(HBN_INT_GPIO9); + + if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO9] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_GPIO9](); } + } - if (SET == HBN_Get_INT_State(HBN_INT_GPIO10)) { - HBN_Clear_IRQ(HBN_INT_GPIO10); + if (SET == HBN_Get_INT_State(HBN_INT_GPIO10)) { + HBN_Clear_IRQ(HBN_INT_GPIO10); - if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO10] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_GPIO10](); - } + if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO10] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_GPIO10](); } + } - if (SET == HBN_Get_INT_State(HBN_INT_GPIO11)) { - HBN_Clear_IRQ(HBN_INT_GPIO11); + if (SET == HBN_Get_INT_State(HBN_INT_GPIO11)) { + HBN_Clear_IRQ(HBN_INT_GPIO11); - if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO11] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_GPIO11](); - } + if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO11] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_GPIO11](); } + } - if (SET == HBN_Get_INT_State(HBN_INT_GPIO12)) { - HBN_Clear_IRQ(HBN_INT_GPIO12); + if (SET == HBN_Get_INT_State(HBN_INT_GPIO12)) { + HBN_Clear_IRQ(HBN_INT_GPIO12); - if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO12] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_GPIO12](); - } + if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO12] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_GPIO12](); } + } - if (SET == HBN_Get_INT_State(HBN_INT_GPIO13)) { - HBN_Clear_IRQ(HBN_INT_GPIO13); + if (SET == HBN_Get_INT_State(HBN_INT_GPIO13)) { + HBN_Clear_IRQ(HBN_INT_GPIO13); - if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO13] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_GPIO13](); - } + if (hbnInt0CbfArra[HBN_OUT0_INT_GPIO13] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_GPIO13](); } + } - if (SET == HBN_Get_INT_State(HBN_INT_RTC)) { - HBN_Clear_IRQ(HBN_INT_RTC); - HBN_Clear_RTC_INT(); + if (SET == HBN_Get_INT_State(HBN_INT_RTC)) { + HBN_Clear_IRQ(HBN_INT_RTC); + HBN_Clear_RTC_INT(); - if (hbnInt0CbfArra[HBN_OUT0_INT_RTC] != NULL) { - hbnInt0CbfArra[HBN_OUT0_INT_RTC](); - } + if (hbnInt0CbfArra[HBN_OUT0_INT_RTC] != NULL) { + hbnInt0CbfArra[HBN_OUT0_INT_RTC](); } + } } /****************************************************************************/ /** - * @brief HBN OUT1 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ -void HBN_OUT1_IRQHandler(void) -{ - /* PIR */ - if (SET == HBN_Get_INT_State(HBN_INT_PIR)) { - HBN_Clear_IRQ(HBN_INT_PIR); - - if (hbnInt1CbfArra[HBN_OUT1_INT_PIR] != NULL) { - hbnInt1CbfArra[HBN_OUT1_INT_PIR](); - } - } + * @brief HBN OUT1 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ +void HBN_OUT1_IRQHandler(void) { + /* PIR */ + if (SET == HBN_Get_INT_State(HBN_INT_PIR)) { + HBN_Clear_IRQ(HBN_INT_PIR); - /* BOR */ - if (SET == HBN_Get_INT_State(HBN_INT_BOR)) { - HBN_Clear_IRQ(HBN_INT_BOR); - - if (hbnInt1CbfArra[HBN_OUT1_INT_BOR] != NULL) { - hbnInt1CbfArra[HBN_OUT1_INT_BOR](); - } + if (hbnInt1CbfArra[HBN_OUT1_INT_PIR] != NULL) { + hbnInt1CbfArra[HBN_OUT1_INT_PIR](); } + } - /* ACOMP0 */ - if (SET == HBN_Get_INT_State(HBN_INT_ACOMP0)) { - HBN_Clear_IRQ(HBN_INT_ACOMP0); + /* BOR */ + if (SET == HBN_Get_INT_State(HBN_INT_BOR)) { + HBN_Clear_IRQ(HBN_INT_BOR); - if (hbnInt1CbfArra[HBN_OUT1_INT_ACOMP0] != NULL) { - hbnInt1CbfArra[HBN_OUT1_INT_ACOMP0](); - } + if (hbnInt1CbfArra[HBN_OUT1_INT_BOR] != NULL) { + hbnInt1CbfArra[HBN_OUT1_INT_BOR](); } + } - /* ACOMP1 */ - if (SET == HBN_Get_INT_State(HBN_INT_ACOMP1)) { - HBN_Clear_IRQ(HBN_INT_ACOMP1); - - if (hbnInt1CbfArra[HBN_OUT1_INT_ACOMP1] != NULL) { - hbnInt1CbfArra[HBN_OUT1_INT_ACOMP1](); - } - } -} + /* ACOMP0 */ + if (SET == HBN_Get_INT_State(HBN_INT_ACOMP0)) { + HBN_Clear_IRQ(HBN_INT_ACOMP0); -/****************************************************************************/ /** - * @brief Enable HBN mode - * - * @param aGPIOIeCfg: AON GPIO IE config,Bit0->GPIO18. Bit(s) of Wakeup GPIO(s) must not be set to - * 0(s),say when use GPIO7 as wake up pin,aGPIOIeCfg should be 0x01. - * @param ldoLevel: LDO volatge level - * @param hbnLevel: HBN work level - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION HBN_Enable(uint8_t aGPIOIeCfg, HBN_LDO_LEVEL_Type ldoLevel, HBN_LEVEL_Type hbnLevel) -{ - uint32_t tmpVal; - - CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); - CHECK_PARAM(IS_HBN_LEVEL_TYPE(hbnLevel)); - - /* Setting from guide */ - /* RAM Retion */ - BL_WR_REG(HBN_BASE, HBN_SRAM, 0x24); - /* AON GPIO IE */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aGPIOIeCfg); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); - BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); - ///* Power off 1.8V */ - //tmpVal=BL_RD_REG(AON_BASE,AON_PMIP); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO11_SOC); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO18_RF); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO18_IO); - ///* SOC11 enum is not the same as VDD11*/ - //tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_TOPLDO11_SOC_VOUT_SEL,ldoLevel-1); - //BL_WR_REG(AON_BASE,AON_PMIP,tmpVal); - // - ///* Set RT voltage */ - //tmpVal=BL_RD_REG(AON_BASE,AON); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW3); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW2); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW1); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_BYPASS); - //tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_LDO18_AON); - ///* RT11 enum is not the same as VDD11*/ - //tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_TOPLDO11_RT_VOUT_SEL,ldoLevel-1); - //tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_VDD11_SEL,ldoLevel); - //BL_WR_REG(AON_BASE,AON,tmpVal); - - /* Select RC32M */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); - BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - /* Set HBN flag */ - BL_WR_REG(HBN_BASE, HBN_RSV0, HBN_STATUS_ENTER_FLAG); - - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - - /* Set HBN level, (HBN_PWRDN_HBN_RAM not use) */ - switch (hbnLevel) { - case HBN_LEVEL_0: - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_1: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_2: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - case HBN_LEVEL_3: - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); - break; - - default: - break; + if (hbnInt1CbfArra[HBN_OUT1_INT_ACOMP0] != NULL) { + hbnInt1CbfArra[HBN_OUT1_INT_ACOMP0](); } + } - /* Set power on option:0 for por reset twice for robust 1 for reset only once*/ - tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWR_ON_OPTION); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); - - /* Enable HBN mode */ - tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); - tmpVal = BL_SET_REG_BIT(tmpVal, HBN_MODE); - BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + /* ACOMP1 */ + if (SET == HBN_Get_INT_State(HBN_INT_ACOMP1)) { + HBN_Clear_IRQ(HBN_INT_ACOMP1); - while (1) { - BL702_Delay_MS(1000); + if (hbnInt1CbfArra[HBN_OUT1_INT_ACOMP1] != NULL) { + hbnInt1CbfArra[HBN_OUT1_INT_ACOMP1](); } -} - -/****************************************************************************/ /** - * @brief HBN out0 IRQHandler install - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Out0_IRQHandler_Install(void) -{ - Interrupt_Handler_Register(HBN_OUT0_IRQn, HBN_OUT0_IRQHandler); - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief HBN out1 IRQHandler install - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type HBN_Out1_IRQHandler_Install(void) -{ - Interrupt_Handler_Register(HBN_OUT1_IRQn, HBN_OUT1_IRQHandler); - return SUCCESS; + } +} + +/****************************************************************************/ /** + * @brief Enable HBN mode + * + * @param aGPIOIeCfg: AON GPIO IE config,Bit0->GPIO18. Bit(s) of Wakeup GPIO(s) must not be set to + * 0(s),say when use GPIO7 as wake up pin,aGPIOIeCfg should be 0x01. + * @param ldoLevel: LDO volatge level + * @param hbnLevel: HBN work level + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION HBN_Enable(uint8_t aGPIOIeCfg, HBN_LDO_LEVEL_Type ldoLevel, HBN_LEVEL_Type hbnLevel) { + uint32_t tmpVal; + + CHECK_PARAM(IS_HBN_LDO_LEVEL_TYPE(ldoLevel)); + CHECK_PARAM(IS_HBN_LEVEL_TYPE(hbnLevel)); + + /* Setting from guide */ + /* RAM Retion */ + BL_WR_REG(HBN_BASE, HBN_SRAM, 0x24); + /* AON GPIO IE */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_IRQ_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_REG_AON_PAD_IE_SMT, aGPIOIeCfg); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_REG_EN_HW_PU_PD); + BL_WR_REG(HBN_BASE, HBN_IRQ_MODE, tmpVal); + ///* Power off 1.8V */ + // tmpVal=BL_RD_REG(AON_BASE,AON_PMIP); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO11_SOC); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO18_RF); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_TOPLDO18_IO); + ///* SOC11 enum is not the same as VDD11*/ + // tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_TOPLDO11_SOC_VOUT_SEL,ldoLevel-1); + // BL_WR_REG(AON_BASE,AON_PMIP,tmpVal); + // + ///* Set RT voltage */ + // tmpVal=BL_RD_REG(AON_BASE,AON); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW3); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW2); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_SW1); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_TOPLDO18_IO_BYPASS); + // tmpVal=BL_CLR_REG_BIT(tmpVal,AON_PU_LDO18_AON); + ///* RT11 enum is not the same as VDD11*/ + // tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_TOPLDO11_RT_VOUT_SEL,ldoLevel-1); + // tmpVal=BL_SET_REG_BITS_VAL(tmpVal,AON_VDD11_SEL,ldoLevel); + // BL_WR_REG(AON_BASE,AON,tmpVal); + + /* Select RC32M */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_GLB); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, HBN_ROOT_CLK_SEL, 0); + BL_WR_REG(HBN_BASE, HBN_GLB, tmpVal); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + /* Set HBN flag */ + BL_WR_REG(HBN_BASE, HBN_RSV0, HBN_STATUS_ENTER_FLAG); + + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + + /* Set HBN level, (HBN_PWRDN_HBN_RAM not use) */ + switch (hbnLevel) { + case HBN_LEVEL_0: + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_1: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_2: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + case HBN_LEVEL_3: + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_CORE); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_PWRDN_HBN_RTC); + break; + + default: + break; + } + + /* Set power on option:0 for por reset twice for robust 1 for reset only once*/ + tmpVal = BL_CLR_REG_BIT(tmpVal, HBN_PWR_ON_OPTION); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + /* Enable HBN mode */ + tmpVal = BL_RD_REG(HBN_BASE, HBN_CTL); + tmpVal = BL_SET_REG_BIT(tmpVal, HBN_MODE); + BL_WR_REG(HBN_BASE, HBN_CTL, tmpVal); + + while (1) { + BL702_Delay_MS(1000); + } +} + +/****************************************************************************/ /** + * @brief HBN out0 IRQHandler install + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Out0_IRQHandler_Install(void) { + Interrupt_Handler_Register(HBN_OUT0_IRQn, HBN_OUT0_IRQHandler); + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief HBN out1 IRQHandler install + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type HBN_Out1_IRQHandler_Install(void) { + Interrupt_Handler_Register(HBN_OUT1_IRQn, HBN_OUT1_IRQHandler); + return SUCCESS; } /*@} end of group HBN_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2c.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2c.c index b43c892a1..c87153568 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2c.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2c.c @@ -50,12 +50,12 @@ * @{ */ #define I2C_FIFO_STATUS_TIMEOUT (160 * 1000 * 2) -#define PUT_UINT32_LE(n, b, i) \ - { \ - (b)[(i)] = (uint8_t)((n)); \ - (b)[(i) + 1] = (uint8_t)((n) >> 8); \ - (b)[(i) + 2] = (uint8_t)((n) >> 16); \ - (b)[(i) + 3] = (uint8_t)((n) >> 24); \ +#define PUT_UINT32_LE(n, b, i) \ + { \ + (b)[(i)] = (uint8_t)((n)); \ + (b)[(i) + 1] = (uint8_t)((n) >> 8); \ + (b)[(i) + 2] = (uint8_t)((n) >> 16); \ + (b)[(i) + 3] = (uint8_t)((n) >> 24); \ } /*@} end of group I2C_Private_Macros */ @@ -205,11 +205,67 @@ void I2C_Enable(I2C_ID_Type i2cNo) { /* Check the parameters */ CHECK_PARAM(IS_I2C_ID_TYPE(i2cNo)); + // Set the M_EN bit + tmpVal = BL_RD_REG(I2Cx, I2C_CONFIG); tmpVal = BL_SET_REG_BIT(tmpVal, I2C_CR_I2C_M_EN); BL_WR_REG(I2Cx, I2C_CONFIG, tmpVal); } +uint8_t I2C_GetTXFIFOAvailable() { + + volatile uint32_t tmpVal; + uint32_t I2Cx = I2C_BASE; + + tmpVal = BL_RD_REG(I2Cx, I2C_FIFO_CONFIG_1); + return tmpVal & 0b11; // Lowest two bits +} + +uint8_t I2C_GetRXFIFOAvailable() { + + volatile uint32_t tmpVal; + uint32_t I2Cx = I2C_BASE; + + tmpVal = BL_RD_REG(I2Cx, I2C_FIFO_CONFIG_1); + return (tmpVal >> 8) & 0b11; // Lowest two bits of byte 2 +} + +void I2C_DMATxEnable() { + uint32_t tmpVal; + uint32_t I2Cx = I2C_BASE; + + tmpVal = BL_RD_REG(I2Cx, I2C_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, I2C_DMA_TX_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, I2C_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, I2C_RX_FIFO_CLR); + + // tmpVal = BL_SET_REG_BIT(tmpVal, I2C_DMA_RX_EN); + + BL_WR_REG(I2Cx, I2C_FIFO_CONFIG_0, tmpVal); + + // Ensure fifo setpoint is as we expect + tmpVal = BL_RD_REG(I2Cx, I2C_FIFO_CONFIG_1); + tmpVal &= I2C_TX_FIFO_CNT_UMSK; + tmpVal |= 1; + + BL_WR_REG(I2Cx, I2C_FIFO_CONFIG_1, tmpVal); +} +void I2C_DMATxDisable() { + uint32_t tmpVal; + uint32_t I2Cx = I2C_BASE; + + tmpVal = BL_RD_REG(I2Cx, I2C_FIFO_CONFIG_0); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2C_DMA_TX_EN); + // tmpVal = BL_CLR_REG_BIT(tmpVal, I2C_DMA_RX_EN); + BL_WR_REG(I2Cx, I2C_FIFO_CONFIG_0, tmpVal); + + tmpVal = BL_RD_REG(I2Cx, I2C_FIFO_CONFIG_1); + tmpVal &= I2C_TX_FIFO_CNT_UMSK; + tmpVal |= 1; + + BL_WR_REG(I2Cx, I2C_FIFO_CONFIG_1, tmpVal); +} + /** * @brief I2C disable * @@ -297,15 +353,15 @@ void I2C_Init(I2C_ID_Type i2cNo, I2C_Direction_Type direct, I2C_Transfer_Cfg *cf tmpVal = BL_CLR_REG_BIT(tmpVal, I2C_CR_I2C_SUB_ADDR_EN); } + // Packet length <=256 bytes per transaction + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2C_CR_I2C_PKT_LEN, cfg->dataSize - 1); BL_WR_REG(I2Cx, I2C_CONFIG, tmpVal); /* Set sub address */ BL_WR_REG(I2Cx, I2C_SUB_ADDR, cfg->subAddr); -#ifndef BFLB_USE_HAL_DRIVER Interrupt_Handler_Register(I2C_IRQn, I2C_IRQHandler); -#endif } /** @@ -491,6 +547,8 @@ BL_Err_Type I2C_MasterSendBlocking(I2C_ID_Type i2cNo, I2C_Transfer_Cfg *cfg) { uint32_t timeOut = 0; uint32_t temp = 0; uint32_t I2Cx = I2C_BASE; + I2C_IntMask(I2C0_ID, I2C_TRANS_END_INT, UNMASK); // This function needs to be able to use the irq status bits + I2C_IntMask(I2C0_ID, I2C_NACK_RECV_INT, UNMASK); // This function needs to be able to use the irq status bits /* Check the parameters */ CHECK_PARAM(IS_I2C_ID_TYPE(i2cNo)); @@ -571,6 +629,9 @@ BL_Err_Type I2C_MasterReceiveBlocking(I2C_ID_Type i2cNo, I2C_Transfer_Cfg *cfg) I2C_Disable(i2cNo); I2C_Init(i2cNo, I2C_READ, cfg); I2C_Enable(i2cNo); + I2C_IntMask(I2C0_ID, I2C_TRANS_END_INT, UNMASK); // This function needs to be able to use the irq status bits + I2C_IntMask(I2C0_ID, I2C_NACK_RECV_INT, UNMASK); // This function needs to be able to use the irq status bits + timeOut = I2C_FIFO_STATUS_TIMEOUT; if (cfg->dataSize == 0 && cfg->subAddrSize == 0) { while (BL_RD_REG(I2C_BASE, I2C_BUS_BUSY)) { @@ -589,6 +650,7 @@ BL_Err_Type I2C_MasterReceiveBlocking(I2C_ID_Type i2cNo, I2C_Transfer_Cfg *cfg) return TIMEOUT; } } + /* Read I2C data */ while (cfg->dataSize - i >= 4) { timeOut = I2C_FIFO_STATUS_TIMEOUT; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c index b79a18720..bb3972aa3 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_i2s.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_i2s.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_i2s.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_i2s.h" #include "bl702_glb.h" @@ -86,380 +86,363 @@ */ /****************************************************************************/ /** - * @brief I2S BCLK config - * - * @param i2sCfg: I2S configuration pointer - * - * @return NONE - * -*******************************************************************************/ -void I2S_SetBclkPeriod(I2S_CFG_Type *i2sCfg) -{ - uint32_t overSampleRate; - uint32_t bclkDivCnt; - uint32_t tmpVal; - - CHECK_PARAM(IS_I2S_FRAME_SIZE_TYPE(i2sCfg->frameSize)); - - overSampleRate = i2sCfg->audioFreqHz / i2sCfg->sampleFreqHz; - - switch (i2sCfg->frameSize) { - case I2S_SIZE_FRAME_8: - bclkDivCnt = overSampleRate / 16; - break; - - case I2S_SIZE_FRAME_16: - bclkDivCnt = overSampleRate / 32; - break; - - case I2S_SIZE_FRAME_24: - bclkDivCnt = overSampleRate / 48; - break; - - case I2S_SIZE_FRAME_32: - bclkDivCnt = overSampleRate / 64; - break; - - default: - bclkDivCnt = overSampleRate / 16; - break; - } - - bclkDivCnt = (bclkDivCnt / 2) - 1; - - tmpVal = (bclkDivCnt << 16) | bclkDivCnt; - BL_WR_REG(I2S_BASE, I2S_BCLK_CONFIG, tmpVal); + * @brief I2S BCLK config + * + * @param i2sCfg: I2S configuration pointer + * + * @return NONE + * + *******************************************************************************/ +void I2S_SetBclkPeriod(I2S_CFG_Type *i2sCfg) { + uint32_t overSampleRate; + uint32_t bclkDivCnt; + uint32_t tmpVal; + + CHECK_PARAM(IS_I2S_FRAME_SIZE_TYPE(i2sCfg->frameSize)); + + overSampleRate = i2sCfg->audioFreqHz / i2sCfg->sampleFreqHz; + + switch (i2sCfg->frameSize) { + case I2S_SIZE_FRAME_8: + bclkDivCnt = overSampleRate / 16; + break; + + case I2S_SIZE_FRAME_16: + bclkDivCnt = overSampleRate / 32; + break; + + case I2S_SIZE_FRAME_24: + bclkDivCnt = overSampleRate / 48; + break; + + case I2S_SIZE_FRAME_32: + bclkDivCnt = overSampleRate / 64; + break; + + default: + bclkDivCnt = overSampleRate / 16; + break; + } + + bclkDivCnt = (bclkDivCnt / 2) - 1; + + tmpVal = (bclkDivCnt << 16) | bclkDivCnt; + BL_WR_REG(I2S_BASE, I2S_BCLK_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief I2S configuration - * - * @param i2sCfg: I2S configuration pointer - * - * @return NONE - * -*******************************************************************************/ -void I2S_Init(I2S_CFG_Type *i2sCfg) -{ - uint32_t tmpVal; + * @brief I2S configuration + * + * @param i2sCfg: I2S configuration pointer + * + * @return NONE + * + *******************************************************************************/ +void I2S_Init(I2S_CFG_Type *i2sCfg) { + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_I2S_ENDIAN_TYPE(i2sCfg->endianType)); - CHECK_PARAM(IS_I2S_MODE_TYPE(i2sCfg->modeType)); - CHECK_PARAM(IS_I2S_FRAME_SIZE_TYPE(i2sCfg->frameSize)); - CHECK_PARAM(IS_I2S_FS_MODE_TYPE(i2sCfg->fsMode)); - CHECK_PARAM(IS_I2S_FS_CHANNEL_TYPE(i2sCfg->fsChannel)); - CHECK_PARAM(IS_I2S_DATA_SIZE_TYPE(i2sCfg->dataSize)); - CHECK_PARAM(IS_I2S_MONO_MODE_CHANNEL(i2sCfg->monoModeChannel)); + /* Check the parameters */ + CHECK_PARAM(IS_I2S_ENDIAN_TYPE(i2sCfg->endianType)); + CHECK_PARAM(IS_I2S_MODE_TYPE(i2sCfg->modeType)); + CHECK_PARAM(IS_I2S_FRAME_SIZE_TYPE(i2sCfg->frameSize)); + CHECK_PARAM(IS_I2S_FS_MODE_TYPE(i2sCfg->fsMode)); + CHECK_PARAM(IS_I2S_FS_CHANNEL_TYPE(i2sCfg->fsChannel)); + CHECK_PARAM(IS_I2S_DATA_SIZE_TYPE(i2sCfg->dataSize)); + CHECK_PARAM(IS_I2S_MONO_MODE_CHANNEL(i2sCfg->monoModeChannel)); - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_I2S); + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_I2S); - tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); + tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); - /* Set data endian*/ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_ENDIAN, i2sCfg->endianType); + /* Set data endian*/ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_ENDIAN, i2sCfg->endianType); - /* Set I2S mode */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_MODE, i2sCfg->modeType); + /* Set I2S mode */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_MODE, i2sCfg->modeType); - /* Set BCLK invert */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_BCLK_INV, i2sCfg->bclkInvert); + /* Set BCLK invert */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_BCLK_INV, i2sCfg->bclkInvert); - /* Set FS size */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FRAME_SIZE, i2sCfg->frameSize); + /* Set FS size */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FRAME_SIZE, i2sCfg->frameSize); - /* Set FS invert */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_FS_INV, i2sCfg->fsInvert); + /* Set FS invert */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_FS_INV, i2sCfg->fsInvert); - /* Set FS mode */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FS_1T_MODE, i2sCfg->fsMode); + /* Set FS mode */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FS_1T_MODE, i2sCfg->fsMode); - /* Set FS channel mode */ + /* Set FS channel mode */ - switch (i2sCfg->fsChannel) { - case I2S_FS_CHANNELS_2: - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); - break; + switch (i2sCfg->fsChannel) { + case I2S_FS_CHANNELS_2: + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); + break; - case I2S_FS_CHANNELS_3: - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); - break; + case I2S_FS_CHANNELS_3: + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); + break; - case I2S_FS_CHANNELS_4: - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); - break; + case I2S_FS_CHANNELS_4: + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_FS_3CH_MODE); + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_FS_4CH_MODE); + break; - default: - break; - } + default: + break; + } - /* Set Data size */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DATA_SIZE, i2sCfg->dataSize); + /* Set Data size */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DATA_SIZE, i2sCfg->dataSize); - /* Set Data offset */ - if (i2sCfg->dataOffset != 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_OFS_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_OFS_CNT, i2sCfg->dataOffset - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_OFS_EN); - } + /* Set Data offset */ + if (i2sCfg->dataOffset != 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_OFS_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_OFS_CNT, i2sCfg->dataOffset - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_OFS_EN); + } - /* Set mono mode */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_MONO_MODE, i2sCfg->monoMode); + /* Set mono mode */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_MONO_MODE, i2sCfg->monoMode); - /* Set rx mono mode channel left or right */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_MONO_RX_CH, i2sCfg->monoModeChannel); + /* Set rx mono mode channel left or right */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_MONO_RX_CH, i2sCfg->monoModeChannel); - /* Clear mute mode */ - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); + /* Clear mute mode */ + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); - BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); + BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); - I2S_SetBclkPeriod(i2sCfg); + I2S_SetBclkPeriod(i2sCfg); } /****************************************************************************/ /** - * @brief I2S configure FIFO function - * - * @param fifoCfg: FIFO configuration structure pointer - * - * @return None - * -*******************************************************************************/ -void I2S_FifoConfig(I2S_FifoCfg_Type *fifoCfg) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_0); - /* Set packed mode */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_LR_MERGE, fifoCfg->lRMerge); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_LR_EXCHG, fifoCfg->frameDataExchange); - /* Clear tx and rx FIFO signal */ - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_RX_FIFO_CLR); - - /* Set DMA config */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_DMA_TX_EN, fifoCfg->txfifoDmaEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_DMA_RX_EN, fifoCfg->rxfifoDmaEnable); - - BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); - - /* Set CLR signal to 0*/ - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_TX_FIFO_CLR); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_RX_FIFO_CLR); - BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); - - tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1); - /* Set TX and RX FIFO threshold */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_TX_FIFO_TH, fifoCfg->txFifoLevel); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_RX_FIFO_TH, fifoCfg->rxFifoLevel); - - BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_1, tmpVal); + * @brief I2S configure FIFO function + * + * @param fifoCfg: FIFO configuration structure pointer + * + * @return None + * + *******************************************************************************/ +void I2S_FifoConfig(I2S_FifoCfg_Type *fifoCfg) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_0); + /* Set packed mode */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_LR_MERGE, fifoCfg->lRMerge); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_LR_EXCHG, fifoCfg->frameDataExchange); + /* Clear tx and rx FIFO signal */ + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_RX_FIFO_CLR); + + /* Set DMA config */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_DMA_TX_EN, fifoCfg->txfifoDmaEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_DMA_RX_EN, fifoCfg->rxfifoDmaEnable); + + BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); + + /* Set CLR signal to 0*/ + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_TX_FIFO_CLR); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_RX_FIFO_CLR); + BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); + + tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1); + /* Set TX and RX FIFO threshold */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_TX_FIFO_TH, fifoCfg->txFifoLevel); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_RX_FIFO_TH, fifoCfg->rxFifoLevel); + + BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_1, tmpVal); } /****************************************************************************/ /** - * @brief I2S configure IO function - * - * @param ioCfg: IO configuration structure pointer - * - * @return None - * -*******************************************************************************/ -void I2S_IOConfig(I2S_IOCfg_Type *ioCfg) -{ - uint32_t tmpVal; + * @brief I2S configure IO function + * + * @param ioCfg: IO configuration structure pointer + * + * @return None + * + *******************************************************************************/ +void I2S_IOConfig(I2S_IOCfg_Type *ioCfg) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(I2S_BASE, I2S_IO_CONFIG); - /* Enable or disable deglitch */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DEG_EN, ioCfg->deglitchEn); + tmpVal = BL_RD_REG(I2S_BASE, I2S_IO_CONFIG); + /* Enable or disable deglitch */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DEG_EN, ioCfg->deglitchEn); - /* Set deglitch cycle count */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DEG_CNT, ioCfg->deglitchCnt); + /* Set deglitch cycle count */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_DEG_CNT, ioCfg->deglitchCnt); - /* Enable or disable inverse BCLK signal */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_BCLK_INV, ioCfg->inverseBCLK); + /* Enable or disable inverse BCLK signal */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_BCLK_INV, ioCfg->inverseBCLK); - /* Enable or disable inverse FS signal */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_FS_INV, ioCfg->inverseFS); + /* Enable or disable inverse FS signal */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_FS_INV, ioCfg->inverseFS); - /* Enable or disable inverse RX signal */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_RXD_INV, ioCfg->inverseRX); + /* Enable or disable inverse RX signal */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_RXD_INV, ioCfg->inverseRX); - /* Enable or disable inverse TX signal */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_TXD_INV, ioCfg->inverseTX); + /* Enable or disable inverse TX signal */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_I2S_TXD_INV, ioCfg->inverseTX); - BL_WR_REG(I2S_BASE, I2S_IO_CONFIG, tmpVal); + BL_WR_REG(I2S_BASE, I2S_IO_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Enable I2S - * - * @param roleType: I2S master or slave - * - * @return None - * -*******************************************************************************/ -void I2S_Enable(I2S_Role_Type roleType) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_I2S_ROLE_TYPE(roleType)); - - tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_TXD_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_RXD_EN); - - /* Set role type */ - if (I2S_ROLE_MASTER == roleType) { - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); - } else if (I2S_ROLE_SLAVE == roleType) { - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); - } - - BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); + * @brief Enable I2S + * + * @param roleType: I2S master or slave + * + * @return None + * + *******************************************************************************/ +void I2S_Enable(I2S_Role_Type roleType) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_I2S_ROLE_TYPE(roleType)); + + tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_TXD_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_RXD_EN); + + /* Set role type */ + if (I2S_ROLE_MASTER == roleType) { + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); + } else if (I2S_ROLE_SLAVE == roleType) { + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); + } + + BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief Disable I2S - * - * @param None - * - * @return None - * -*******************************************************************************/ -void I2S_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_TXD_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_RXD_EN); - - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); - BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); + * @brief Disable I2S + * + * @param None + * + * @return None + * + *******************************************************************************/ +void I2S_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_TXD_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_RXD_EN); + + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_M_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_I2S_S_EN); + BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief I2S read data - * - * @param None - * - * @return Data read - * -*******************************************************************************/ -uint32_t I2S_Read(void) -{ - while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_RX_FIFO_CNT)) { - }; - - return BL_RD_REG(I2S_BASE, I2S_FIFO_RDATA); + * @brief I2S read data + * + * @param None + * + * @return Data read + * + *******************************************************************************/ +uint32_t I2S_Read(void) { + while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_RX_FIFO_CNT)) { + }; + + return BL_RD_REG(I2S_BASE, I2S_FIFO_RDATA); } /****************************************************************************/ /** - * @brief I2S write data - * - * @param data: write data - * - * @return None - * -*******************************************************************************/ -void I2S_Write(uint32_t data) -{ - while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_TX_FIFO_CNT)) { - }; - - BL_WR_REG(I2S_BASE, I2S_FIFO_WDATA, data); + * @brief I2S write data + * + * @param data: write data + * + * @return None + * + *******************************************************************************/ +void I2S_Write(uint32_t data) { + while (0 == BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_TX_FIFO_CNT)) { + }; + + BL_WR_REG(I2S_BASE, I2S_FIFO_WDATA, data); } /****************************************************************************/ /** - * @brief I2S set mute - * - * @param enabled: mute enabled or not - * - * @return None - * -*******************************************************************************/ -void I2S_Mute(BL_Fun_Type enabled) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); - - if (enabled ? 1 : 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); - } + * @brief I2S set mute + * + * @param enabled: mute enabled or not + * + * @return None + * + *******************************************************************************/ +void I2S_Mute(BL_Fun_Type enabled) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(I2S_BASE, I2S_CONFIG); + + if (enabled ? 1 : 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, I2S_CR_MUTE_MODE); + } - BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); + BL_WR_REG(I2S_BASE, I2S_CONFIG, tmpVal); } /****************************************************************************/ /** - * @brief I2S set 24-bit data align mode in fifo - * - * @param justType: Align mode - * - * @return None - * -*******************************************************************************/ -void I2S_SetFifoJustified(I2S_FIFO_24_Justified_Type justType) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_I2S_FIFO_24_JUSTIFIED_TYPE(justType)); - - tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_24B_LJ, justType); - BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); + * @brief I2S set 24-bit data align mode in fifo + * + * @param justType: Align mode + * + * @return None + * + *******************************************************************************/ +void I2S_SetFifoJustified(I2S_FIFO_24_Justified_Type justType) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_I2S_FIFO_24_JUSTIFIED_TYPE(justType)); + + tmpVal = BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, I2S_CR_FIFO_24B_LJ, justType); + BL_WR_REG(I2S_BASE, I2S_FIFO_CONFIG_0, tmpVal); } /****************************************************************************/ /** - * @brief I2S flush - * - * @param None - * - * @return data count in TX FIFO - * -*******************************************************************************/ -uint32_t I2S_GetTxFIFO_AvlCnt(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_TX_FIFO_CNT); -} + * @brief I2S flush + * + * @param None + * + * @return data count in TX FIFO + * + *******************************************************************************/ +uint32_t I2S_GetTxFIFO_AvlCnt(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_TX_FIFO_CNT); } /****************************************************************************/ /** - * @brief I2S flush - * - * @param None - * - * @return data count in RX FIFO - * -*******************************************************************************/ -uint32_t I2S_GetRxFIFO_AvlCnt(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_RX_FIFO_CNT); -} + * @brief I2S flush + * + * @param None + * + * @return data count in RX FIFO + * + *******************************************************************************/ +uint32_t I2S_GetRxFIFO_AvlCnt(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(I2S_BASE, I2S_FIFO_CONFIG_1), I2S_RX_FIFO_CNT); } /****************************************************************************/ /** - * @brief I2S flush - * - * @param None - * - * @return None - * -*******************************************************************************/ -void I2S_Flush(void) -{ - while (I2S_TX_FIFO_SIZE != I2S_GetTxFIFO_AvlCnt()) - ; + * @brief I2S flush + * + * @param None + * + * @return None + * + *******************************************************************************/ +void I2S_Flush(void) { + while (I2S_TX_FIFO_SIZE != I2S_GetTxFIFO_AvlCnt()) + ; } /*@} end of group I2S_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c index 681f8a1c5..ca097a056 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_ir.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_ir.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_ir.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_ir.h" #include "bl702_glb.h" @@ -72,7 +72,7 @@ /** @defgroup IR_Private_Variables * @{ */ -static intCallback_Type *irIntCbfArra[IR_INT_ALL] = { NULL, NULL }; +static intCallback_Type *irIntCbfArra[IR_INT_ALL] = {NULL, NULL}; /*@} end of group IR_Private_Variables */ @@ -99,1054 +99,1025 @@ static intCallback_Type *irIntCbfArra[IR_INT_ALL] = { NULL, NULL }; */ /****************************************************************************/ /** - * @brief IR RX IRQ handler function - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief IR RX IRQ handler function + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void IRRX_IRQHandler(void) -{ - uint32_t tmpVal; +void IRRX_IRQHandler(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - if (BL_IS_REG_BIT_SET(tmpVal, IRRX_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, IR_CR_IRRX_END_MASK)) { - BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); + if (BL_IS_REG_BIT_SET(tmpVal, IRRX_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, IR_CR_IRRX_END_MASK)) { + BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); - if (irIntCbfArra[IR_INT_RX] != NULL) { - irIntCbfArra[IR_INT_RX](); - } + if (irIntCbfArra[IR_INT_RX] != NULL) { + irIntCbfArra[IR_INT_RX](); } + } } #endif /****************************************************************************/ /** - * @brief IR TX IRQ handler function - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief IR TX IRQ handler function + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void IRTX_IRQHandler(void) -{ - uint32_t tmpVal; +void IRTX_IRQHandler(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); + tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); - if (BL_IS_REG_BIT_SET(tmpVal, IRTX_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, IR_CR_IRTX_END_MASK)) { - BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_END_CLR)); + if (BL_IS_REG_BIT_SET(tmpVal, IRTX_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, IR_CR_IRTX_END_MASK)) { + BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_END_CLR)); - if (irIntCbfArra[IR_INT_TX] != NULL) { - irIntCbfArra[IR_INT_TX](); - } + if (irIntCbfArra[IR_INT_TX] != NULL) { + irIntCbfArra[IR_INT_TX](); } + } } #endif /****************************************************************************/ /** - * @brief IR tx initialization function - * - * @param irTxCfg: IR tx configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_TxInit(IR_TxCfg_Type *irTxCfg) -{ - uint32_t tmpVal; - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); - - tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); - /* Set data bit */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_DATA_NUM, irTxCfg->dataBits - 1); - /* Set tail pulse */ - ENABLE == irTxCfg->tailPulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_HL_INV)); - ENABLE == irTxCfg->tailPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_EN)); - /* Set head pulse */ - ENABLE == irTxCfg->headPulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_HL_INV)); - ENABLE == irTxCfg->headPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_EN)); - /* Enable or disable logic 1 and 0 pulse inverse */ - ENABLE == irTxCfg->logic1PulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC1_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC1_HL_INV)); - ENABLE == irTxCfg->logic0PulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC0_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC0_HL_INV)); - /* Enable or disable data pulse */ - ENABLE == irTxCfg->dataPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_DATA_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_DATA_EN)); - /* Enable or disable output modulation */ - ENABLE == irTxCfg->outputModulation ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_MOD_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_MOD_EN)); - /* Enable or disable output inverse */ - ENABLE == irTxCfg->outputInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_OUT_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_OUT_INV)); - - /* Write back */ - BL_WR_REG(IR_BASE, IRTX_CONFIG, tmpVal); + * @brief IR tx initialization function + * + * @param irTxCfg: IR tx configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_TxInit(IR_TxCfg_Type *irTxCfg) { + uint32_t tmpVal; + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); + + tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); + /* Set data bit */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_DATA_NUM, irTxCfg->dataBits - 1); + /* Set tail pulse */ + ENABLE == irTxCfg->tailPulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_HL_INV)); + ENABLE == irTxCfg->tailPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_TAIL_EN)); + /* Set head pulse */ + ENABLE == irTxCfg->headPulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_HL_INV)); + ENABLE == irTxCfg->headPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_HEAD_EN)); + /* Enable or disable logic 1 and 0 pulse inverse */ + ENABLE == irTxCfg->logic1PulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC1_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC1_HL_INV)); + ENABLE == irTxCfg->logic0PulseInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC0_HL_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_LOGIC0_HL_INV)); + /* Enable or disable data pulse */ + ENABLE == irTxCfg->dataPulse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_DATA_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_DATA_EN)); + /* Enable or disable output modulation */ + ENABLE == irTxCfg->outputModulation ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_MOD_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_MOD_EN)); + /* Enable or disable output inverse */ + ENABLE == irTxCfg->outputInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_OUT_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_OUT_INV)); + + /* Write back */ + BL_WR_REG(IR_BASE, IRTX_CONFIG, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(IRTX_IRQn, IRTX_IRQHandler); + Interrupt_Handler_Register(IRTX_IRQn, IRTX_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR tx pulse width configure function - * - * @param irTxPulseWidthCfg: IR tx pulse width configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_TxPulseWidthConfig(IR_TxPulseWidthCfg_Type *irTxPulseWidthCfg) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(IR_BASE, IRTX_PW); - /* Set logic 0 pulse phase 0 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC0_PH0_W, irTxPulseWidthCfg->logic0PulseWidth_0 - 1); - /* Set logic 0 pulse phase 1 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC0_PH1_W, irTxPulseWidthCfg->logic0PulseWidth_1 - 1); - /* Set logic 1 pulse phase 0 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC1_PH0_W, irTxPulseWidthCfg->logic1PulseWidth_0 - 1); - /* Set logic 1 pulse phase 1 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC1_PH1_W, irTxPulseWidthCfg->logic1PulseWidth_1 - 1); - /* Set head pulse phase 0 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_HEAD_PH0_W, irTxPulseWidthCfg->headPulseWidth_0 - 1); - /* Set head pulse phase 1 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_HEAD_PH1_W, irTxPulseWidthCfg->headPulseWidth_1 - 1); - /* Set tail pulse phase 0 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_TAIL_PH0_W, irTxPulseWidthCfg->tailPulseWidth_0 - 1); - /* Set tail pulse phase 1 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_TAIL_PH1_W, irTxPulseWidthCfg->tailPulseWidth_1 - 1); - BL_WR_REG(IR_BASE, IRTX_PW, tmpVal); - - tmpVal = BL_RD_REG(IR_BASE, IRTX_PULSE_WIDTH); - /* Set modulation phase 0 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_MOD_PH0_W, irTxPulseWidthCfg->moduWidth_0 - 1); - /* Set modulation phase 1 width */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_MOD_PH1_W, irTxPulseWidthCfg->moduWidth_1 - 1); - /* Set pulse width unit */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_PW_UNIT, irTxPulseWidthCfg->pulseWidthUnit - 1); - BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, tmpVal); - - return SUCCESS; + * @brief IR tx pulse width configure function + * + * @param irTxPulseWidthCfg: IR tx pulse width configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_TxPulseWidthConfig(IR_TxPulseWidthCfg_Type *irTxPulseWidthCfg) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(IR_BASE, IRTX_PW); + /* Set logic 0 pulse phase 0 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC0_PH0_W, irTxPulseWidthCfg->logic0PulseWidth_0 - 1); + /* Set logic 0 pulse phase 1 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC0_PH1_W, irTxPulseWidthCfg->logic0PulseWidth_1 - 1); + /* Set logic 1 pulse phase 0 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC1_PH0_W, irTxPulseWidthCfg->logic1PulseWidth_0 - 1); + /* Set logic 1 pulse phase 1 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_LOGIC1_PH1_W, irTxPulseWidthCfg->logic1PulseWidth_1 - 1); + /* Set head pulse phase 0 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_HEAD_PH0_W, irTxPulseWidthCfg->headPulseWidth_0 - 1); + /* Set head pulse phase 1 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_HEAD_PH1_W, irTxPulseWidthCfg->headPulseWidth_1 - 1); + /* Set tail pulse phase 0 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_TAIL_PH0_W, irTxPulseWidthCfg->tailPulseWidth_0 - 1); + /* Set tail pulse phase 1 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_TAIL_PH1_W, irTxPulseWidthCfg->tailPulseWidth_1 - 1); + BL_WR_REG(IR_BASE, IRTX_PW, tmpVal); + + tmpVal = BL_RD_REG(IR_BASE, IRTX_PULSE_WIDTH); + /* Set modulation phase 0 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_MOD_PH0_W, irTxPulseWidthCfg->moduWidth_0 - 1); + /* Set modulation phase 1 width */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_MOD_PH1_W, irTxPulseWidthCfg->moduWidth_1 - 1); + /* Set pulse width unit */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_PW_UNIT, irTxPulseWidthCfg->pulseWidthUnit - 1); + BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR tx software mode pulse width(multiples of pulse width unit) configure function - * - * @param irTxSWMPulseWidthCfg: IR tx software mode pulse width configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_TxSWMPulseWidthConfig(IR_TxSWMPulseWidthCfg_Type *irTxSWMPulseWidthCfg) -{ - /* Set swm pulse width,multiples of pulse width unit */ - BL_WR_REG(IR_BASE, IRTX_SWM_PW_0, irTxSWMPulseWidthCfg->swmData0); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_1, irTxSWMPulseWidthCfg->swmData1); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_2, irTxSWMPulseWidthCfg->swmData2); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_3, irTxSWMPulseWidthCfg->swmData3); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_4, irTxSWMPulseWidthCfg->swmData4); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_5, irTxSWMPulseWidthCfg->swmData5); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_6, irTxSWMPulseWidthCfg->swmData6); - BL_WR_REG(IR_BASE, IRTX_SWM_PW_7, irTxSWMPulseWidthCfg->swmData7); - - return SUCCESS; + * @brief IR tx software mode pulse width(multiples of pulse width unit) configure function + * + * @param irTxSWMPulseWidthCfg: IR tx software mode pulse width configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_TxSWMPulseWidthConfig(IR_TxSWMPulseWidthCfg_Type *irTxSWMPulseWidthCfg) { + /* Set swm pulse width,multiples of pulse width unit */ + BL_WR_REG(IR_BASE, IRTX_SWM_PW_0, irTxSWMPulseWidthCfg->swmData0); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_1, irTxSWMPulseWidthCfg->swmData1); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_2, irTxSWMPulseWidthCfg->swmData2); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_3, irTxSWMPulseWidthCfg->swmData3); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_4, irTxSWMPulseWidthCfg->swmData4); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_5, irTxSWMPulseWidthCfg->swmData5); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_6, irTxSWMPulseWidthCfg->swmData6); + BL_WR_REG(IR_BASE, IRTX_SWM_PW_7, irTxSWMPulseWidthCfg->swmData7); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR rx initialization function - * - * @param irRxCfg: IR rx configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_RxInit(IR_RxCfg_Type *irRxCfg) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_RXMODE_TYPE(irRxCfg->rxMode)); - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); - - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - - /* Set rx mode */ - switch (irRxCfg->rxMode) { - case IR_RX_NEC: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x0); - break; - - case IR_RX_RC5: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x1); - break; - - case IR_RX_SWM: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x2); - break; - - default: - break; - } - - /* Enable or disable input inverse */ - ENABLE == irRxCfg->inputInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV)); - /* Enable or disable rx input de-glitch function */ - ENABLE == irRxCfg->rxDeglitch ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_DEG_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_DEG_EN)); - /* Set de-glitch function cycle count */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_DEG_CNT, irRxCfg->DeglitchCnt); - /* Write back */ - BL_WR_REG(IR_BASE, IRRX_CONFIG, tmpVal); - - tmpVal = BL_RD_REG(IR_BASE, IRRX_PW_CONFIG); - /* Set pulse width threshold to trigger end condition */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_TH, irRxCfg->endThreshold - 1); - /* Set pulse width threshold for logic0/1 detection */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_DATA_TH, irRxCfg->dataThreshold - 1); - /* Write back */ - BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, tmpVal); + * @brief IR rx initialization function + * + * @param irRxCfg: IR rx configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_RxInit(IR_RxCfg_Type *irRxCfg) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_RXMODE_TYPE(irRxCfg->rxMode)); + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); + + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + + /* Set rx mode */ + switch (irRxCfg->rxMode) { + case IR_RX_NEC: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x0); + break; + + case IR_RX_RC5: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x1); + break; + + case IR_RX_SWM: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x2); + break; + + default: + break; + } + + /* Enable or disable input inverse */ + ENABLE == irRxCfg->inputInverse ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV)); + /* Enable or disable rx input de-glitch function */ + ENABLE == irRxCfg->rxDeglitch ? (tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_DEG_EN)) : (tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_DEG_EN)); + /* Set de-glitch function cycle count */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_DEG_CNT, irRxCfg->DeglitchCnt); + /* Write back */ + BL_WR_REG(IR_BASE, IRRX_CONFIG, tmpVal); + + tmpVal = BL_RD_REG(IR_BASE, IRRX_PW_CONFIG); + /* Set pulse width threshold to trigger end condition */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_TH, irRxCfg->endThreshold - 1); + /* Set pulse width threshold for logic0/1 detection */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_DATA_TH, irRxCfg->dataThreshold - 1); + /* Write back */ + BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(IRRX_IRQn, IRRX_IRQHandler); + Interrupt_Handler_Register(IRRX_IRQn, IRRX_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR set default value of all registers function - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_DeInit(void) -{ - GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_IRR); - - return SUCCESS; + * @brief IR set default value of all registers function + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_DeInit(void) { + GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_IRR); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR enable function - * - * @param direct: IR direction type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_Enable(IR_Direction_Type direct) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_DIRECTION_TYPE(direct)); - - if (direct == IR_TX || direct == IR_TXRX) { - /* Enable ir tx unit */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); - BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_EN)); - } - - if (direct == IR_RX || direct == IR_TXRX) { - /* Enable ir rx unit */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_EN)); - } - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief IR disable function - * - * @param direct: IR direction type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_Disable(IR_Direction_Type direct) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_DIRECTION_TYPE(direct)); - - if (direct == IR_TX || direct == IR_TXRX) { - /* Disable ir tx unit */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); - BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_EN)); - } + * @brief IR enable function + * + * @param direct: IR direction type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_Enable(IR_Direction_Type direct) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_DIRECTION_TYPE(direct)); + + if (direct == IR_TX || direct == IR_TXRX) { + /* Enable ir tx unit */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); + BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_EN)); + } - if (direct == IR_RX || direct == IR_TXRX) { - /* Disable ir rx unit */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN)); - } + if (direct == IR_RX || direct == IR_TXRX) { + /* Enable ir rx unit */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_EN)); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR tx software mode enable or disable function - * - * @param txSWM: Enable or disable - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_TxSWM(BL_Fun_Type txSWM) -{ - uint32_t tmpVal; - - /* Enable or disable tx swm */ + * @brief IR disable function + * + * @param direct: IR direction type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_Disable(IR_Direction_Type direct) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_DIRECTION_TYPE(direct)); + + if (direct == IR_TX || direct == IR_TXRX) { + /* Disable ir tx unit */ tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); + BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_EN)); + } - if (ENABLE == txSWM) { - BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_SWM_EN)); - } else { - BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_SWM_EN)); - } + if (direct == IR_RX || direct == IR_TXRX) { + /* Disable ir rx unit */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN)); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR clear rx fifo function - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_RxFIFOClear(void) -{ - uint32_t tmpVal; - - /* Clear rx fifo */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); - BL_WR_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, IR_RX_FIFO_CLR)); - - return SUCCESS; + * @brief IR tx software mode enable or disable function + * + * @param txSWM: Enable or disable + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_TxSWM(BL_Fun_Type txSWM) { + uint32_t tmpVal; + + /* Enable or disable tx swm */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); + + if (ENABLE == txSWM) { + BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_SWM_EN)); + } else { + BL_WR_REG(IR_BASE, IRTX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRTX_SWM_EN)); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR send data function - * - * @param irWord: IR tx data word 0 or 1 - * @param data: data to send - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_SendData(IR_Word_Type irWord, uint32_t data) -{ - /* Check the parameters */ - CHECK_PARAM(IS_IR_WORD_TYPE(irWord)); - - /* Write word 0 or word 1 */ - if (IR_WORD_0 == irWord) { - BL_WR_REG(IR_BASE, IRTX_DATA_WORD0, data); - } else { - BL_WR_REG(IR_BASE, IRTX_DATA_WORD1, data); - } - - return SUCCESS; + * @brief IR clear rx fifo function + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_RxFIFOClear(void) { + uint32_t tmpVal; + + /* Clear rx fifo */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); + BL_WR_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, IR_RX_FIFO_CLR)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR software mode send pulse width data function - * - * @param data: data to send - * @param length: Length of send buffer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_SWMSendData(uint16_t *data, uint8_t length) -{ - uint8_t i = 0, j = 0; - uint16_t minData = data[0]; - uint32_t tmpVal; - uint32_t pwVal = 0; - uint32_t count = (length + 7) / 8; - - /* Search for min value */ - for (i = 1; i < length; i++) { - if (minData > data[i] && data[i] != 0) { - minData = data[i]; - } - } - - /* Set pulse width unit */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_PULSE_WIDTH); - BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_PW_UNIT, minData)); - - /* Set tx SWM pulse width data as multiples of pulse width unit */ - for (i = 0; i < count; i++) { - pwVal = 0; - - if (i < count - 1) { - for (j = 0; j < 8; j++) { - tmpVal = ((2 * data[j + i * 8] + minData) / (2 * minData) - 1) & 0xf; - pwVal |= tmpVal << (4 * j); - } - - *(volatile uint32_t *)(IR_BASE + IRTX_SWM_PW_0_OFFSET + i * 4) = pwVal; - } else { - for (j = 0; j < length % 8; j++) { - tmpVal = ((2 * data[j + i * 8] + minData) / (2 * minData) - 1) & 0xf; - pwVal |= tmpVal << (4 * j); - } - - *(volatile uint32_t *)(IR_BASE + IRTX_SWM_PW_0_OFFSET + i * 4) = pwVal; - } - } - - return SUCCESS; + * @brief IR send data function + * + * @param irWord: IR tx data word 0 or 1 + * @param data: data to send + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_SendData(IR_Word_Type irWord, uint32_t data) { + /* Check the parameters */ + CHECK_PARAM(IS_IR_WORD_TYPE(irWord)); + + /* Write word 0 or word 1 */ + if (IR_WORD_0 == irWord) { + BL_WR_REG(IR_BASE, IRTX_DATA_WORD0, data); + } else { + BL_WR_REG(IR_BASE, IRTX_DATA_WORD1, data); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR send command function - * - * @param word1: IR send data word 1 - * @param word0: IR send data word 0 - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_SendCommand(uint32_t word1, uint32_t word0) -{ - uint32_t timeoutCnt = IR_TX_INT_TIMEOUT_COUNT; + * @brief IR software mode send pulse width data function + * + * @param data: data to send + * @param length: Length of send buffer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_SWMSendData(uint16_t *data, uint8_t length) { + uint8_t i = 0, j = 0; + uint16_t minData = data[0]; + uint32_t tmpVal; + uint32_t pwVal = 0; + uint32_t count = (length + 7) / 8; + + /* Search for min value */ + for (i = 1; i < length; i++) { + if (minData > data[i] && data[i] != 0) { + minData = data[i]; + } + } - /* Write data */ - IR_SendData(IR_WORD_1, word1); - IR_SendData(IR_WORD_0, word0); + /* Set pulse width unit */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_PULSE_WIDTH); + BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_PW_UNIT, minData)); - /* Mask tx interrupt */ - IR_IntMask(IR_INT_TX, MASK); + /* Set tx SWM pulse width data as multiples of pulse width unit */ + for (i = 0; i < count; i++) { + pwVal = 0; - /* Clear tx interrupt */ - IR_ClrIntStatus(IR_INT_TX); + if (i < count - 1) { + for (j = 0; j < 8; j++) { + tmpVal = ((2 * data[j + i * 8] + minData) / (2 * minData) - 1) & 0xf; + pwVal |= tmpVal << (4 * j); + } - /* Enable ir tx */ - IR_Enable(IR_TX); + *(volatile uint32_t *)(IR_BASE + IRTX_SWM_PW_0_OFFSET + i * 4) = pwVal; + } else { + for (j = 0; j < length % 8; j++) { + tmpVal = ((2 * data[j + i * 8] + minData) / (2 * minData) - 1) & 0xf; + pwVal |= tmpVal << (4 * j); + } - /* Wait for tx interrupt */ - while (SET != IR_GetIntStatus(IR_INT_TX)) { - timeoutCnt--; + *(volatile uint32_t *)(IR_BASE + IRTX_SWM_PW_0_OFFSET + i * 4) = pwVal; + } + } - if (timeoutCnt == 0) { - IR_Disable(IR_TX); + return SUCCESS; +} - return TIMEOUT; - } +/****************************************************************************/ /** + * @brief IR send command function + * + * @param word1: IR send data word 1 + * @param word0: IR send data word 0 + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_SendCommand(uint32_t word1, uint32_t word0) { + uint32_t timeoutCnt = IR_TX_INT_TIMEOUT_COUNT; + + /* Write data */ + IR_SendData(IR_WORD_1, word1); + IR_SendData(IR_WORD_0, word0); + + /* Mask tx interrupt */ + IR_IntMask(IR_INT_TX, MASK); + + /* Clear tx interrupt */ + IR_ClrIntStatus(IR_INT_TX); + + /* Enable ir tx */ + IR_Enable(IR_TX); + + /* Wait for tx interrupt */ + while (SET != IR_GetIntStatus(IR_INT_TX)) { + timeoutCnt--; + + if (timeoutCnt == 0) { + IR_Disable(IR_TX); + + return TIMEOUT; } + } - /* Disable ir tx */ - IR_Disable(IR_TX); + /* Disable ir tx */ + IR_Disable(IR_TX); - /* Clear tx interrupt */ - IR_ClrIntStatus(IR_INT_TX); + /* Clear tx interrupt */ + IR_ClrIntStatus(IR_INT_TX); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR send command in software mode function - * - * @param data: IR fifo data to send - * @param length: Length of data - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_SWMSendCommand(uint16_t *data, uint8_t length) -{ - uint32_t timeoutCnt = IR_TX_INT_TIMEOUT_COUNT; + * @brief IR send command in software mode function + * + * @param data: IR fifo data to send + * @param length: Length of data + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_SWMSendCommand(uint16_t *data, uint8_t length) { + uint32_t timeoutCnt = IR_TX_INT_TIMEOUT_COUNT; - /* Write fifo */ - IR_SWMSendData(data, length); + /* Write fifo */ + IR_SWMSendData(data, length); - /* Mask tx interrupt */ - IR_IntMask(IR_INT_TX, MASK); + /* Mask tx interrupt */ + IR_IntMask(IR_INT_TX, MASK); - /* Clear tx interrupt */ - IR_ClrIntStatus(IR_INT_TX); + /* Clear tx interrupt */ + IR_ClrIntStatus(IR_INT_TX); - /* Enable ir tx */ - IR_Enable(IR_TX); + /* Enable ir tx */ + IR_Enable(IR_TX); - /* Wait for tx interrupt */ - while (SET != IR_GetIntStatus(IR_INT_TX)) { - timeoutCnt--; + /* Wait for tx interrupt */ + while (SET != IR_GetIntStatus(IR_INT_TX)) { + timeoutCnt--; - if (timeoutCnt == 0) { - IR_Disable(IR_TX); + if (timeoutCnt == 0) { + IR_Disable(IR_TX); - return TIMEOUT; - } + return TIMEOUT; } + } - /* Disable ir tx */ - IR_Disable(IR_TX); + /* Disable ir tx */ + IR_Disable(IR_TX); - /* Clear tx interrupt */ - IR_ClrIntStatus(IR_INT_TX); + /* Clear tx interrupt */ + IR_ClrIntStatus(IR_INT_TX); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR send in NEC protocol - * - * @param address: Address - * @param command: Command - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_SendNEC(uint8_t address, uint8_t command) -{ - uint32_t tmpVal = ((~command & 0xff) << 24) + (command << 16) + ((~address & 0xff) << 8) + address; - - IR_SendCommand(0, tmpVal); - - return SUCCESS; + * @brief IR send in NEC protocol + * + * @param address: Address + * @param command: Command + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_SendNEC(uint8_t address, uint8_t command) { + uint32_t tmpVal = ((~command & 0xff) << 24) + (command << 16) + ((~address & 0xff) << 8) + address; + + IR_SendCommand(0, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR interrupt mask or unmask function - * - * @param intType: IR interrupt type - * @param intMask: Mask or unmask - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_IntMask(IR_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_INT_TYPE(intType)); - - if (intType == IR_INT_TX || intType == IR_INT_ALL) { - /* Mask or unmask tx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); - BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_END_MASK, intMask)); - } + * @brief IR interrupt mask or unmask function + * + * @param intType: IR interrupt type + * @param intMask: Mask or unmask + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_IntMask(IR_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_INT_TYPE(intType)); + + if (intType == IR_INT_TX || intType == IR_INT_ALL) { + /* Mask or unmask tx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); + BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_END_MASK, intMask)); + } - if (intType == IR_INT_RX || intType == IR_INT_ALL) { - /* Mask or unmask rx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_MASK, intMask)); - } + if (intType == IR_INT_RX || intType == IR_INT_ALL) { + /* Mask or unmask rx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_MASK, intMask)); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Clear ir interrupt function - * - * @param intType: IR interrupt type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_ClrIntStatus(IR_INT_Type intType) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_INT_TYPE(intType)); - - if (intType == IR_INT_TX || intType == IR_INT_ALL) { - /* Clear tx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); - BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_END_CLR)); - } + * @brief Clear ir interrupt function + * + * @param intType: IR interrupt type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_ClrIntStatus(IR_INT_Type intType) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_INT_TYPE(intType)); + + if (intType == IR_INT_TX || intType == IR_INT_ALL) { + /* Clear tx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); + BL_WR_REG(IR_BASE, IRTX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRTX_END_CLR)); + } - if (intType == IR_INT_RX || intType == IR_INT_ALL) { - /* Clear rx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); - } + if (intType == IR_INT_RX || intType == IR_INT_ALL) { + /* Clear rx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief IR install interrupt callback function - * - * @param intType: IR interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_Int_Callback_Install(IR_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_IR_INT_TYPE(intType)); - - irIntCbfArra[intType] = cbFun; - - return SUCCESS; + * @brief IR install interrupt callback function + * + * @param intType: IR interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_Int_Callback_Install(IR_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_IR_INT_TYPE(intType)); + + irIntCbfArra[intType] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR get interrupt status function - * - * @param intType: IR int type - * - * @return IR tx or rx interrupt status - * -*******************************************************************************/ -BL_Sts_Type IR_GetIntStatus(IR_INT_Type intType) -{ - uint32_t tmpVal = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_INT_TYPE(intType)); - - /* Read tx or rx interrupt status */ - if (IR_INT_TX == intType) { - tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IRTX_END_INT); - } else if (IR_INT_RX == intType) { - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IRRX_END_INT); - } - - if (tmpVal) { - return SET; - } else { - return RESET; - } + * @brief IR get interrupt status function + * + * @param intType: IR int type + * + * @return IR tx or rx interrupt status + * + *******************************************************************************/ +BL_Sts_Type IR_GetIntStatus(IR_INT_Type intType) { + uint32_t tmpVal = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_INT_TYPE(intType)); + + /* Read tx or rx interrupt status */ + if (IR_INT_TX == intType) { + tmpVal = BL_RD_REG(IR_BASE, IRTX_INT_STS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IRTX_END_INT); + } else if (IR_INT_RX == intType) { + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IRRX_END_INT); + } + + if (tmpVal) { + return SET; + } else { + return RESET; + } } /****************************************************************************/ /** - * @brief IR get rx fifo underflow or overflow status function - * - * @param fifoSts: IR fifo status type - * - * @return IR rx fifo status - * -*******************************************************************************/ -BL_Sts_Type IR_GetRxFIFOStatus(IR_FifoStatus_Type fifoSts) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_FIFOSTATUS_TYPE(fifoSts)); - - /* Read rx fifo status */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); - - if (fifoSts == IR_RX_FIFO_UNDERFLOW) { - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_UNDERFLOW); - } else { - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_OVERFLOW); - } - - if (tmpVal) { - return SET; - } else { - return RESET; - } + * @brief IR get rx fifo underflow or overflow status function + * + * @param fifoSts: IR fifo status type + * + * @return IR rx fifo status + * + *******************************************************************************/ +BL_Sts_Type IR_GetRxFIFOStatus(IR_FifoStatus_Type fifoSts) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_FIFOSTATUS_TYPE(fifoSts)); + + /* Read rx fifo status */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); + + if (fifoSts == IR_RX_FIFO_UNDERFLOW) { + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_UNDERFLOW); + } else { + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_OVERFLOW); + } + + if (tmpVal) { + return SET; + } else { + return RESET; + } } /****************************************************************************/ /** - * @brief IR receive data function - * - * @param irWord: IR rx data word 0 or 1 - * - * @return Data received - * -*******************************************************************************/ -uint32_t IR_ReceiveData(IR_Word_Type irWord) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_WORD_TYPE(irWord)); - - /* Read word 0 or word 1 */ - if (IR_WORD_0 == irWord) { - tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_WORD0); - } else { - tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_WORD1); - } - - return tmpVal; + * @brief IR receive data function + * + * @param irWord: IR rx data word 0 or 1 + * + * @return Data received + * + *******************************************************************************/ +uint32_t IR_ReceiveData(IR_Word_Type irWord) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_WORD_TYPE(irWord)); + + /* Read word 0 or word 1 */ + if (IR_WORD_0 == irWord) { + tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_WORD0); + } else { + tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_WORD1); + } + + return tmpVal; } /****************************************************************************/ /** - * @brief IR software mode receive pulse width data function - * - * @param data: Data received - * @param length: Max length of receive buffer - * - * @return Length of datas received - * -*******************************************************************************/ -uint8_t IR_SWMReceiveData(uint16_t *data, uint8_t length) -{ - uint8_t rxLen = 0; - - while (rxLen < length && IR_GetRxFIFOCount() > 0) { - /* Read data */ - data[rxLen++] = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_RDATA) & 0xffff; - } - - return rxLen; + * @brief IR software mode receive pulse width data function + * + * @param data: Data received + * @param length: Max length of receive buffer + * + * @return Length of datas received + * + *******************************************************************************/ +uint8_t IR_SWMReceiveData(uint16_t *data, uint8_t length) { + uint8_t rxLen = 0; + + while (rxLen < length && IR_GetRxFIFOCount() > 0) { + /* Read data */ + data[rxLen++] = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_RDATA) & 0xffff; + } + + return rxLen; } /****************************************************************************/ /** - * @brief IR receive in NEC protocol - * - * @param address: Address - * @param command: Command - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type IR_ReceiveNEC(uint8_t *address, uint8_t *command) -{ - uint32_t tmpVal = IR_ReceiveData(IR_WORD_0); - - *address = tmpVal & 0xff; - *command = (tmpVal >> 16) & 0xff; - - if ((~(*address) & 0xff) != ((tmpVal >> 8) & 0xff) || (~(*command) & 0xff) != ((tmpVal >> 24) & 0xff)) { - return ERROR; - } - - return SUCCESS; + * @brief IR receive in NEC protocol + * + * @param address: Address + * @param command: Command + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type IR_ReceiveNEC(uint8_t *address, uint8_t *command) { + uint32_t tmpVal = IR_ReceiveData(IR_WORD_0); + + *address = tmpVal & 0xff; + *command = (tmpVal >> 16) & 0xff; + + if ((~(*address) & 0xff) != ((tmpVal >> 8) & 0xff) || (~(*command) & 0xff) != ((tmpVal >> 24) & 0xff)) { + return ERROR; + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR get rx data bit count function - * - * @param None - * - * @return IR rx data bit count - * -*******************************************************************************/ -uint8_t IR_GetRxDataBitCount(void) -{ - uint32_t tmpVal; - - /* Read rx data bit count */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_COUNT); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_STS_IRRX_DATA_CNT); - - return tmpVal; + * @brief IR get rx data bit count function + * + * @param None + * + * @return IR rx data bit count + * + *******************************************************************************/ +uint8_t IR_GetRxDataBitCount(void) { + uint32_t tmpVal; + + /* Read rx data bit count */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_DATA_COUNT); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_STS_IRRX_DATA_CNT); + + return tmpVal; } /****************************************************************************/ /** - * @brief IR get rx fifo count function - * - * @param None - * - * @return IR rx fifo available count - * -*******************************************************************************/ -uint8_t IR_GetRxFIFOCount(void) -{ - uint32_t tmpVal; - - /* Read rx fifo count */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_CNT); - - return tmpVal; + * @brief IR get rx fifo count function + * + * @param None + * + * @return IR rx fifo available count + * + *******************************************************************************/ +uint8_t IR_GetRxFIFOCount(void) { + uint32_t tmpVal; + + /* Read rx fifo count */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_SWM_FIFO_CONFIG_0); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_RX_FIFO_CNT); + + return tmpVal; } /****************************************************************************/ /** - * @brief IR learning to set rx and tx mode function - * - * @param data: Buffer to save data - * @param length: Length of data - * - * @return Protocol type - * -*******************************************************************************/ -IR_RxMode_Type IR_LearnToInit(uint32_t *data, uint8_t *length) -{ - uint32_t tmpVal; - uint32_t timeoutCnt = IR_RX_INT_TIMEOUT_COUNT; + * @brief IR learning to set rx and tx mode function + * + * @param data: Buffer to save data + * @param length: Length of data + * + * @return Protocol type + * + *******************************************************************************/ +IR_RxMode_Type IR_LearnToInit(uint32_t *data, uint8_t *length) { + uint32_t tmpVal; + uint32_t timeoutCnt = IR_RX_INT_TIMEOUT_COUNT; + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); + + /* Disable rx,set rx in software mode and enable rx input inverse */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x2); + tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV); + BL_WR_REG(IR_BASE, IRRX_CONFIG, tmpVal); + /* Set pulse width threshold to trigger end condition */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_PW_CONFIG); + BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_TH, 19999)); + + /* Clear and mask rx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_MASK); + BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); + + /* Enable rx */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_EN)); + + /* Wait for rx interrupt */ + while (SET != IR_GetIntStatus(IR_INT_RX)) { + timeoutCnt--; + + if (timeoutCnt == 0) { + IR_Disable(IR_RX); + + return IR_RX_SWM; + } + } - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_IRR); + /* Disable rx */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN)); - /* Disable rx,set rx in software mode and enable rx input inverse */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x2); - tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_IN_INV); - BL_WR_REG(IR_BASE, IRRX_CONFIG, tmpVal); - /* Set pulse width threshold to trigger end condition */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_PW_CONFIG); - BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_END_TH, 19999)); + /* Clear rx interrupt */ + tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); + BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); - /* Clear and mask rx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - tmpVal = BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_MASK); - BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); + /*Receive data */ + *length = IR_GetRxFIFOCount(); + *length = IR_SWMReceiveData((uint16_t *)data, *length); - /* Enable rx */ + /* Judge protocol type */ + if (NEC_HEAD_H_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < NEC_HEAD_H_MAX && NEC_HEAD_L_MIN < (data[0] >> 16) && (data[0] >> 16) < NEC_HEAD_L_MAX && NEC_BIT0_H_MIN < (data[1] & 0xffff) && + (data[1] & 0xffff) < NEC_BIT0_H_MAX) { + /* Set rx in NEC mode */ tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_EN)); - - /* Wait for rx interrupt */ - while (SET != IR_GetIntStatus(IR_INT_RX)) { - timeoutCnt--; - - if (timeoutCnt == 0) { - IR_Disable(IR_RX); - - return IR_RX_SWM; - } - } - - /* Disable rx */ + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x0)); + /* Set pulse width threshold to trigger end condition and pulse width threshold for logic0/1 detection */ + BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, 0x23270d47); + /* Set tx in NEC mode */ + /* Tx configure */ + BL_WR_REG(IR_BASE, IRTX_CONFIG, 0x1f514); + /* Set logic 0,logic 1,head and tail pulse width */ + BL_WR_REG(IR_BASE, IRTX_PW, 0x7f2000); + /* Set modulation phase width and pulse width unit */ + BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x22110464); + + return IR_RX_NEC; + } else if (RC5_ONE_PLUSE_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < RC5_ONE_PLUSE_MAX && + ((RC5_ONE_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_TWO_PLUSE_MAX)) && + ((RC5_ONE_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_TWO_PLUSE_MAX))) { + /* Set rx in RC-5 mode */ tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_CLR_REG_BIT(tmpVal, IR_CR_IRRX_EN)); - - /* Clear rx interrupt */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_INT_STS); - BL_WR_REG(IR_BASE, IRRX_INT_STS, BL_SET_REG_BIT(tmpVal, IR_CR_IRRX_END_CLR)); + BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x1)); + /* Set pulse width threshold to trigger end condition and pulse width threshold for logic0/1 detection */ + BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, 0x13870a6a); + /* Set tx in RC-5 mode */ + /* Tx configure */ + BL_WR_REG(IR_BASE, IRTX_CONFIG, 0xc134); + /* Set logic 0,logic 1,head and tail pulse width */ + BL_WR_REG(IR_BASE, IRTX_PW, 0); + /* Set modulation phase width and pulse width unit */ + BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x221106f1); + + return IR_RX_RC5; + } else if ((data[0] >> 16) != 0) { + /* Set tx in software mode */ + /* Tx configure */ + BL_WR_REG(IR_BASE, IRTX_CONFIG, *length << 12 | 0xc); + /* Set modulation phase width */ + BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x22110000); + + return IR_RX_SWM; + } else { + tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE); - /*Receive data */ - *length = IR_GetRxFIFOCount(); - *length = IR_SWMReceiveData((uint16_t *)data, *length); - - /* Judge protocol type */ - if (NEC_HEAD_H_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < NEC_HEAD_H_MAX && NEC_HEAD_L_MIN < (data[0] >> 16) && (data[0] >> 16) < NEC_HEAD_L_MAX && NEC_BIT0_H_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < NEC_BIT0_H_MAX) { - /* Set rx in NEC mode */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x0)); - /* Set pulse width threshold to trigger end condition and pulse width threshold for logic0/1 detection */ - BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, 0x23270d47); - /* Set tx in NEC mode */ - /* Tx configure */ - BL_WR_REG(IR_BASE, IRTX_CONFIG, 0x1f514); - /* Set logic 0,logic 1,head and tail pulse width */ - BL_WR_REG(IR_BASE, IRTX_PW, 0x7f2000); - /* Set modulation phase width and pulse width unit */ - BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x22110464); - - return IR_RX_NEC; - } else if (RC5_ONE_PLUSE_MIN < (data[0] & 0xffff) && (data[0] & 0xffff) < RC5_ONE_PLUSE_MAX && ((RC5_ONE_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[0] >> 16) && (data[0] >> 16) < RC5_TWO_PLUSE_MAX)) && - ((RC5_ONE_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_ONE_PLUSE_MAX) || (RC5_TWO_PLUSE_MIN < (data[1] & 0xffff) && (data[1] & 0xffff) < RC5_TWO_PLUSE_MAX))) { - /* Set rx in RC-5 mode */ - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - BL_WR_REG(IR_BASE, IRRX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE, 0x1)); - /* Set pulse width threshold to trigger end condition and pulse width threshold for logic0/1 detection */ - BL_WR_REG(IR_BASE, IRRX_PW_CONFIG, 0x13870a6a); - /* Set tx in RC-5 mode */ - /* Tx configure */ - BL_WR_REG(IR_BASE, IRTX_CONFIG, 0xc134); - /* Set logic 0,logic 1,head and tail pulse width */ - BL_WR_REG(IR_BASE, IRTX_PW, 0); - /* Set modulation phase width and pulse width unit */ - BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x221106f1); - - return IR_RX_RC5; - } else if ((data[0] >> 16) != 0) { - /* Set tx in software mode */ - /* Tx configure */ - BL_WR_REG(IR_BASE, IRTX_CONFIG, *length << 12 | 0xc); - /* Set modulation phase width */ - BL_WR_REG(IR_BASE, IRTX_PULSE_WIDTH, 0x22110000); - - return IR_RX_SWM; + if (tmpVal == 0) { + return IR_RX_NEC; + } else if (tmpVal == 1) { + return IR_RX_RC5; } else { - tmpVal = BL_RD_REG(IR_BASE, IRRX_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, IR_CR_IRRX_MODE); - - if (tmpVal == 0) { - return IR_RX_NEC; - } else if (tmpVal == 1) { - return IR_RX_RC5; - } else { - return IR_RX_SWM; - } + return IR_RX_SWM; } + } } /****************************************************************************/ /** - * @brief IR receive data according to mode which is learned function - * - * @param mode: Protocol type - * @param data: Buffer to save data - * - * @return Length of data - * -*******************************************************************************/ -uint8_t IR_LearnToReceive(IR_RxMode_Type mode, uint32_t *data) -{ - uint8_t length = 0; - uint32_t timeoutCnt = IR_RX_INT_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_RXMODE_TYPE(mode)); - - /* Disable ir rx */ - IR_Disable(IR_RX); - - /* Clear and mask rx interrupt */ - IR_ClrIntStatus(IR_INT_RX); - IR_IntMask(IR_INT_RX, MASK); - - /* Enable ir rx */ - IR_Enable(IR_RX); - - /* Wait for rx interrupt */ - while (SET != IR_GetIntStatus(IR_INT_RX)) { - timeoutCnt--; - - if (timeoutCnt == 0) { - IR_Disable(IR_RX); - - return TIMEOUT; - } - } - - /* Disable ir rx */ - IR_Disable(IR_RX); - - /* Clear rx interrupt */ - IR_ClrIntStatus(IR_INT_RX); - - /* Receive data according to mode */ - if (mode == IR_RX_NEC || mode == IR_RX_RC5) { - /* Get data bit count */ - length = IR_GetRxDataBitCount(); - data[0] = IR_ReceiveData(IR_WORD_0); - } else { - /* Get fifo count */ - length = IR_GetRxFIFOCount(); - length = IR_SWMReceiveData((uint16_t *)data, length); + * @brief IR receive data according to mode which is learned function + * + * @param mode: Protocol type + * @param data: Buffer to save data + * + * @return Length of data + * + *******************************************************************************/ +uint8_t IR_LearnToReceive(IR_RxMode_Type mode, uint32_t *data) { + uint8_t length = 0; + uint32_t timeoutCnt = IR_RX_INT_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_RXMODE_TYPE(mode)); + + /* Disable ir rx */ + IR_Disable(IR_RX); + + /* Clear and mask rx interrupt */ + IR_ClrIntStatus(IR_INT_RX); + IR_IntMask(IR_INT_RX, MASK); + + /* Enable ir rx */ + IR_Enable(IR_RX); + + /* Wait for rx interrupt */ + while (SET != IR_GetIntStatus(IR_INT_RX)) { + timeoutCnt--; + + if (timeoutCnt == 0) { + IR_Disable(IR_RX); + + return TIMEOUT; } - - return length; + } + + /* Disable ir rx */ + IR_Disable(IR_RX); + + /* Clear rx interrupt */ + IR_ClrIntStatus(IR_INT_RX); + + /* Receive data according to mode */ + if (mode == IR_RX_NEC || mode == IR_RX_RC5) { + /* Get data bit count */ + length = IR_GetRxDataBitCount(); + data[0] = IR_ReceiveData(IR_WORD_0); + } else { + /* Get fifo count */ + length = IR_GetRxFIFOCount(); + length = IR_SWMReceiveData((uint16_t *)data, length); + } + + return length; } /****************************************************************************/ /** - * @brief IR send data according to mode which is learned function - * - * @param mode: Protocol type - * @param data: Buffer of data to send - * @param length: Length of data - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_LearnToSend(IR_RxMode_Type mode, uint32_t *data, uint8_t length) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_IR_RXMODE_TYPE(mode)); - - /* Set send length */ - tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_DATA_NUM, length - 1); - BL_WR_REG(IR_BASE, IRTX_CONFIG, tmpVal); - - if (mode == IR_RX_NEC || mode == IR_RX_RC5) { - IR_SendCommand(0, data[0]); - } else { - IR_SWMSendCommand((uint16_t *)data, length); - } - - return SUCCESS; + * @brief IR send data according to mode which is learned function + * + * @param mode: Protocol type + * @param data: Buffer of data to send + * @param length: Length of data + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_LearnToSend(IR_RxMode_Type mode, uint32_t *data, uint8_t length) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_IR_RXMODE_TYPE(mode)); + + /* Set send length */ + tmpVal = BL_RD_REG(IR_BASE, IRTX_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, IR_CR_IRTX_DATA_NUM, length - 1); + BL_WR_REG(IR_BASE, IRTX_CONFIG, tmpVal); + + if (mode == IR_RX_NEC || mode == IR_RX_RC5) { + IR_SendCommand(0, data[0]); + } else { + IR_SWMSendCommand((uint16_t *)data, length); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR init to control led function - * - * @param clk: Clock source - * @param div: Clock division(1~64) - * @param unit: Pulse width unit(multiples of clock pulse width, 1~4096) - * @param code0H: code 0 high level time(multiples of pulse width unit, 1~16) - * @param code0L: code 0 low level time(multiples of pulse width unit, 1~16) - * @param code1H: code 1 high level time(multiples of pulse width unit, 1~16) - * @param code1L: code 1 low level time(multiples of pulse width unit, 1~16) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_LEDInit(HBN_XCLK_CLK_Type clk, uint8_t div, uint8_t unit, uint8_t code0H, uint8_t code0L, uint8_t code1H, uint8_t code1L) -{ - IR_TxCfg_Type txCfg = { - 24, /* 24-bit data */ - DISABLE, /* Disable signal of tail pulse inverse */ - DISABLE, /* Disable signal of tail pulse */ - DISABLE, /* Disable signal of head pulse inverse */ - DISABLE, /* Disable signal of head pulse */ - DISABLE, /* Disable signal of logic 1 pulse inverse */ - DISABLE, /* Disable signal of logic 0 pulse inverse */ - ENABLE, /* Enable signal of data pulse */ - DISABLE, /* Disable signal of output modulation */ - ENABLE /* Enable signal of output inverse */ - }; - - IR_TxPulseWidthCfg_Type txPWCfg = { - code0L, /* Pulse width of logic 0 pulse phase 1 */ - code0H, /* Pulse width of logic 0 pulse phase 0 */ - code1L, /* Pulse width of logic 1 pulse phase 1 */ - code1H, /* Pulse width of logic 1 pulse phase 0 */ - 1, /* Pulse width of head pulse phase 1 */ - 1, /* Pulse width of head pulse phase 0 */ - 1, /* Pulse width of tail pulse phase 1 */ - 1, /* Pulse width of tail pulse phase 0 */ - 1, /* Modulation phase 1 width */ - 1, /* Modulation phase 0 width */ - unit /* Pulse width unit */ - }; - - HBN_Set_XCLK_CLK_Sel(clk); - GLB_Set_IR_CLK(ENABLE, GLB_IR_CLK_SRC_XCLK, div - 1); - - /* Disable ir before config */ - IR_Disable(IR_TXRX); - - /* IR tx init */ - IR_TxInit(&txCfg); - IR_TxPulseWidthConfig(&txPWCfg); - - return SUCCESS; + * @brief IR init to control led function + * + * @param clk: Clock source + * @param div: Clock division(1~64) + * @param unit: Pulse width unit(multiples of clock pulse width, 1~4096) + * @param code0H: code 0 high level time(multiples of pulse width unit, 1~16) + * @param code0L: code 0 low level time(multiples of pulse width unit, 1~16) + * @param code1H: code 1 high level time(multiples of pulse width unit, 1~16) + * @param code1L: code 1 low level time(multiples of pulse width unit, 1~16) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_LEDInit(HBN_XCLK_CLK_Type clk, uint8_t div, uint8_t unit, uint8_t code0H, uint8_t code0L, uint8_t code1H, uint8_t code1L) { + IR_TxCfg_Type txCfg = { + 24, /* 24-bit data */ + DISABLE, /* Disable signal of tail pulse inverse */ + DISABLE, /* Disable signal of tail pulse */ + DISABLE, /* Disable signal of head pulse inverse */ + DISABLE, /* Disable signal of head pulse */ + DISABLE, /* Disable signal of logic 1 pulse inverse */ + DISABLE, /* Disable signal of logic 0 pulse inverse */ + ENABLE, /* Enable signal of data pulse */ + DISABLE, /* Disable signal of output modulation */ + ENABLE /* Enable signal of output inverse */ + }; + + IR_TxPulseWidthCfg_Type txPWCfg = { + code0L, /* Pulse width of logic 0 pulse phase 1 */ + code0H, /* Pulse width of logic 0 pulse phase 0 */ + code1L, /* Pulse width of logic 1 pulse phase 1 */ + code1H, /* Pulse width of logic 1 pulse phase 0 */ + 1, /* Pulse width of head pulse phase 1 */ + 1, /* Pulse width of head pulse phase 0 */ + 1, /* Pulse width of tail pulse phase 1 */ + 1, /* Pulse width of tail pulse phase 0 */ + 1, /* Modulation phase 1 width */ + 1, /* Modulation phase 0 width */ + unit /* Pulse width unit */ + }; + + HBN_Set_XCLK_CLK_Sel(clk); + GLB_Set_IR_CLK(ENABLE, GLB_IR_CLK_SRC_XCLK, div - 1); + + /* Disable ir before config */ + IR_Disable(IR_TXRX); + + /* IR tx init */ + IR_TxInit(&txCfg); + IR_TxPulseWidthConfig(&txPWCfg); + + return SUCCESS; } /****************************************************************************/ /** - * @brief IR send 24-bit data to control led function - * - * @param data: Data to send(24-bit) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type IR_LEDSend(uint32_t data) -{ - /* Change MSB_first to LSB_first */ - data = ((data >> 1) & 0x55555555) | ((data << 1) & 0xaaaaaaaa); - data = ((data >> 2) & 0x33333333) | ((data << 2) & 0xcccccccc); - data = ((data >> 4) & 0x0f0f0f0f) | ((data << 4) & 0xf0f0f0f0); - data = ((data >> 16) & 0xff) | (data & 0xff00) | ((data << 16) & 0xff0000); - IR_SendCommand(0, data); - - return SUCCESS; + * @brief IR send 24-bit data to control led function + * + * @param data: Data to send(24-bit) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type IR_LEDSend(uint32_t data) { + /* Change MSB_first to LSB_first */ + data = ((data >> 1) & 0x55555555) | ((data << 1) & 0xaaaaaaaa); + data = ((data >> 2) & 0x33333333) | ((data << 2) & 0xcccccccc); + data = ((data >> 4) & 0x0f0f0f0f) | ((data << 4) & 0xf0f0f0f0); + data = ((data >> 16) & 0xff) | (data & 0xff00) | ((data << 16) & 0xff0000); + IR_SendCommand(0, data); + + return SUCCESS; } /*@} end of group IR_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_kys.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_kys.c index 45ca6a29d..a96962200 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_kys.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_kys.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_kys.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_kys.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_kys.h" @@ -59,7 +59,7 @@ /** @defgroup KYS_Private_Variables * @{ */ -static intCallback_Type *KYSIntCbfArra[1] = { NULL }; +static intCallback_Type *KYSIntCbfArra[1] = {NULL}; /*@} end of group KYS_Private_Variables */ @@ -86,185 +86,174 @@ static intCallback_Type *KYSIntCbfArra[1] = { NULL }; */ /****************************************************************************/ /** - * @brief KYS interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief KYS interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void KYS_IRQHandler(void) -{ - if (KYSIntCbfArra[0] != NULL) { - KYSIntCbfArra[0](); - } +void KYS_IRQHandler(void) { + if (KYSIntCbfArra[0] != NULL) { + KYSIntCbfArra[0](); + } } #endif /****************************************************************************/ /** - * @brief KYS initialization function - * - * @param kysCfg: KYS configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_Init(KYS_CFG_Type *kysCfg) -{ - uint32_t tmpVal; + * @brief KYS initialization function + * + * @param kysCfg: KYS configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_Init(KYS_CFG_Type *kysCfg) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); - /* Set col and row */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_COL_NUM, kysCfg->col - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_ROW_NUM, kysCfg->row - 1); + tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); + /* Set col and row */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_COL_NUM, kysCfg->col - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_ROW_NUM, kysCfg->row - 1); - /* Set idle duration between column scans */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_RC_EXT, kysCfg->idleDuration); + /* Set idle duration between column scans */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_RC_EXT, kysCfg->idleDuration); - /* Enable or disable ghost key event detection */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_GHOST_EN, kysCfg->ghostEn); + /* Enable or disable ghost key event detection */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_GHOST_EN, kysCfg->ghostEn); - /* Enable or disable deglitch function */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_DEG_EN, kysCfg->deglitchEn); + /* Enable or disable deglitch function */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_DEG_EN, kysCfg->deglitchEn); - /* Set deglitch count */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_DEG_CNT, kysCfg->deglitchCnt); + /* Set deglitch count */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, KYS_DEG_CNT, kysCfg->deglitchCnt); - /* Write back */ - BL_WR_REG(KYS_BASE, KYS_KS_CTRL, tmpVal); + /* Write back */ + BL_WR_REG(KYS_BASE, KYS_KS_CTRL, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(KYS_IRQn, KYS_IRQHandler); + Interrupt_Handler_Register(KYS_IRQn, KYS_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Enable KYS - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_Enable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); - BL_WR_REG(KYS_BASE, KYS_KS_CTRL, BL_SET_REG_BIT(tmpVal, KYS_KS_EN)); - - return SUCCESS; + * @brief Enable KYS + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); + BL_WR_REG(KYS_BASE, KYS_KS_CTRL, BL_SET_REG_BIT(tmpVal, KYS_KS_EN)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable KYS - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_Disable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); - BL_WR_REG(KYS_BASE, KYS_KS_CTRL, BL_CLR_REG_BIT(tmpVal, KYS_KS_EN)); - - return SUCCESS; + * @brief Disable KYS + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_Disable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); + BL_WR_REG(KYS_BASE, KYS_KS_CTRL, BL_CLR_REG_BIT(tmpVal, KYS_KS_EN)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief KYS mask or unmask interrupt - * - * @param intMask: KYS interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_IntMask(BL_Mask_Type intMask) -{ - if (MASK == intMask) { - BL_WR_REG(KYS_BASE, KYS_KS_INT_EN, 0); - } else { - BL_WR_REG(KYS_BASE, KYS_KS_INT_EN, 1); - } - - return SUCCESS; + * @brief KYS mask or unmask interrupt + * + * @param intMask: KYS interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_IntMask(BL_Mask_Type intMask) { + if (MASK == intMask) { + BL_WR_REG(KYS_BASE, KYS_KS_INT_EN, 0); + } else { + BL_WR_REG(KYS_BASE, KYS_KS_INT_EN, 1); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief KYS clear interrupt - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_IntClear(void) -{ - BL_WR_REG(KYS_BASE, KYS_KEYCODE_CLR, 0xf); - - return SUCCESS; + * @brief KYS clear interrupt + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_IntClear(void) { + BL_WR_REG(KYS_BASE, KYS_KEYCODE_CLR, 0xf); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Install KYS interrupt callback function - * - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type KYS_Int_Callback_Install(intCallback_Type *cbFun) -{ - KYSIntCbfArra[0] = cbFun; - - return SUCCESS; + * @brief Install KYS interrupt callback function + * + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type KYS_Int_Callback_Install(intCallback_Type *cbFun) { + KYSIntCbfArra[0] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief KYS get interrupt status - * - * @param None - * - * @return Status of interrupt - * -*******************************************************************************/ -uint8_t KYS_GetIntStatus(void) -{ - return BL_RD_REG(KYS_BASE, KYS_KS_INT_STS) & 0xf; -} + * @brief KYS get interrupt status + * + * @param None + * + * @return Status of interrupt + * + *******************************************************************************/ +uint8_t KYS_GetIntStatus(void) { return BL_RD_REG(KYS_BASE, KYS_KS_INT_STS) & 0xf; } /****************************************************************************/ /** - * @brief KYS get keycode value - * - * @param keycode: KYS keycode type - * @param col: Col of key - * @param row: Row of key - * - * @return Keycode value - * -*******************************************************************************/ -uint8_t KYS_GetKeycode(KYS_Keycode_Type keycode, uint8_t *col, uint8_t *row) -{ - uint32_t tmpVal; - uint8_t keyValue; - - /* Get keycode value */ - keyValue = BL_RD_REG(KYS_BASE, KYS_KEYCODE_VALUE) >> (8 * keycode) & 0xff; - - /* Get total row number of keyboard */ - tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, KYS_ROW_NUM); - - /* Calculate col and row of the key */ - *col = keyValue / (tmpVal + 1); - *row = keyValue % (tmpVal + 1); - - return keyValue; + * @brief KYS get keycode value + * + * @param keycode: KYS keycode type + * @param col: Col of key + * @param row: Row of key + * + * @return Keycode value + * + *******************************************************************************/ +uint8_t KYS_GetKeycode(KYS_Keycode_Type keycode, uint8_t *col, uint8_t *row) { + uint32_t tmpVal; + uint8_t keyValue; + + /* Get keycode value */ + keyValue = BL_RD_REG(KYS_BASE, KYS_KEYCODE_VALUE) >> (8 * keycode) & 0xff; + + /* Get total row number of keyboard */ + tmpVal = BL_RD_REG(KYS_BASE, KYS_KS_CTRL); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, KYS_ROW_NUM); + + /* Calculate col and row of the key */ + *col = keyValue / (tmpVal + 1); + *row = keyValue % (tmpVal + 1); + + return keyValue; } /*@} end of group KYS_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_l1c.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_l1c.c index 303ebd138..88fcd26c5 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_l1c.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_l1c.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_l1c.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_l1c.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_l1c.h" #include "bl702_common.h" @@ -60,8 +60,8 @@ /** @defgroup L1C_Private_Variables * @{ */ -static intCallback_Type *l1cBmxErrIntCbfArra[L1C_BMX_ERR_INT_ALL] = { NULL }; -static intCallback_Type *l1cBmxToIntCbfArra[L1C_BMX_TO_INT_ALL] = { NULL }; +static intCallback_Type *l1cBmxErrIntCbfArra[L1C_BMX_ERR_INT_ALL] = {NULL}; +static intCallback_Type *l1cBmxToIntCbfArra[L1C_BMX_TO_INT_ALL] = {NULL}; /*@} end of group L1C_Private_Variables */ @@ -88,573 +88,548 @@ static intCallback_Type *l1cBmxToIntCbfArra[L1C_BMX_TO_INT_ALL] = { NULL }; */ /****************************************************************************/ /** - * @brief Enable cache - * - * @param wayDisable: cache way disable config - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Enable cache + * + * @param wayDisable: cache way disable config + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Enable_Set(uint8_t wayDisable) -{ - L1C_Cache_Flush(wayDisable); +BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Enable_Set(uint8_t wayDisable) { + L1C_Cache_Flush(wayDisable); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief L1C cache write set - * - * @param wtEn: L1C write through enable - * @param wbEn: L1C write back enable - * @param waEn: L1C write allocate enable - * - * @return None - * -*******************************************************************************/ + * @brief L1C cache write set + * + * @param wtEn: L1C write through enable + * @param wbEn: L1C write back enable + * @param waEn: L1C write allocate enable + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION L1C_Cache_Write_Set(BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - - if (wtEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WT_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WT_EN); - } - - if (wbEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WB_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WB_EN); - } - - if (waEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WA_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WA_EN); - } - - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); +void ATTR_TCM_SECTION L1C_Cache_Write_Set(BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + + if (wtEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WT_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WT_EN); + } + + if (wbEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WB_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WB_EN); + } + + if (waEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WA_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WA_EN); + } + + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); } #endif /****************************************************************************/ /** - * @brief Flush cache - * - * @param wayDisable: cache way disable config - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Flush cache + * + * @param wayDisable: cache way disable config + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Flush(uint8_t wayDisable) -{ - uint32_t tmpVal; - uint32_t cnt = 0; - uint8_t finWayDisable = 0; - +BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Flush(uint8_t wayDisable) { + uint32_t tmpVal; + uint32_t cnt = 0; + uint8_t finWayDisable = 0; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BYPASS); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WAY_DIS); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CNT_EN); + finWayDisable = BL_GET_REG_BITS_VAL(tmpVal, L1C_WAY_DIS); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + + /*Set Tag RAM to zero */ + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_INVALID_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + /* Left space for hardware change status*/ + __NOP(); + __NOP(); + __NOP(); + __NOP(); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_INVALID_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + /* Left space for hardware change status*/ + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + /* Polling for invalid done */ + do { + BL702_Delay_US(1); + cnt++; tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BYPASS); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WAY_DIS); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CNT_EN); - finWayDisable = BL_GET_REG_BITS_VAL(tmpVal, L1C_WAY_DIS); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + } while (!BL_IS_REG_BIT_SET(tmpVal, L1C_INVALID_DONE) && cnt < 100); + + /* data flush */ + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_FLUSH_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + /* Left space for hardware change status*/ + __NOP(); + __NOP(); + __NOP(); + __NOP(); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_FLUSH_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + /* Left space for hardware change status*/ + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + /* Polling for flush done */ + do { + BL702_Delay_US(1); + cnt++; + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + } while (!BL_IS_REG_BIT_SET(tmpVal, L1C_FLUSH_DONE) && cnt < 100); - /*Set Tag RAM to zero */ - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_INVALID_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - /* Left space for hardware change status*/ - __NOP(); - __NOP(); - __NOP(); - __NOP(); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_INVALID_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - /* Left space for hardware change status*/ - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - /* Polling for invalid done */ - do { - BL702_Delay_US(1); - cnt++; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - } while (!BL_IS_REG_BIT_SET(tmpVal, L1C_INVALID_DONE) && cnt < 100); - - /* data flush */ - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_FLUSH_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - /* Left space for hardware change status*/ - __NOP(); - __NOP(); - __NOP(); - __NOP(); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_FLUSH_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - /* Left space for hardware change status*/ - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - /* Polling for flush done */ - do { - BL702_Delay_US(1); - cnt++; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - } while (!BL_IS_REG_BIT_SET(tmpVal, L1C_FLUSH_DONE) && cnt < 100); - - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_FLUSH_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_FLUSH_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BYPASS); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BYPASS); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BYPASS); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CNT_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BYPASS); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CNT_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - if (wayDisable != 0xff) { - finWayDisable = wayDisable; - } + if (wayDisable != 0xff) { + finWayDisable = wayDisable; + } - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WAY_DIS); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WAY_DIS); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - tmpVal |= (finWayDisable << L1C_WAY_DIS_POS); + tmpVal |= (finWayDisable << L1C_WAY_DIS_POS); - /* If way disable is 0x0f, cacheable can't be set */ - if (finWayDisable != 0x0f) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - } + /* If way disable is 0x0f, cacheable can't be set */ + if (finWayDisable != 0x0f) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + } - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Flush cache external api - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Flush_Ext(void) -{ - uint32_t tmpVal; - - /* Disable early respone */ - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - L1C_Cache_Flush((tmpVal >> L1C_WAY_DIS_POS) & 0xf); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - return SUCCESS; + * @brief Flush cache external api + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION L1C_Cache_Flush_Ext(void) { + uint32_t tmpVal; + + /* Disable early respone */ + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + L1C_Cache_Flush((tmpVal >> L1C_WAY_DIS_POS) & 0xf); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + __NOP(); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Get cache hit count - * - * @param hitCountLow: hit count low 32 bits pointer - * @param hitCountHigh: hit count high 32 bits pointer - * - * @return None - * -*******************************************************************************/ + * @brief Get cache hit count + * + * @param hitCountLow: hit count low 32 bits pointer + * @param hitCountHigh: hit count high 32 bits pointer + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION L1C_Cache_Hit_Count_Get(uint32_t *hitCountLow, uint32_t *hitCountHigh) -{ - *hitCountLow = BL_RD_REG(L1C_BASE, L1C_HIT_CNT_LSB); - *hitCountHigh = BL_RD_REG(L1C_BASE, L1C_HIT_CNT_MSB); +void ATTR_TCM_SECTION L1C_Cache_Hit_Count_Get(uint32_t *hitCountLow, uint32_t *hitCountHigh) { + *hitCountLow = BL_RD_REG(L1C_BASE, L1C_HIT_CNT_LSB); + *hitCountHigh = BL_RD_REG(L1C_BASE, L1C_HIT_CNT_MSB); } #endif /****************************************************************************/ /** - * @brief Get cache miss count - * - * @param None - * - * @return Cache miss count - * -*******************************************************************************/ + * @brief Get cache miss count + * + * @param None + * + * @return Cache miss count + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint32_t ATTR_TCM_SECTION L1C_Cache_Miss_Count_Get(void) -{ - return BL_RD_REG(L1C_BASE, L1C_MISS_CNT); -} +uint32_t ATTR_TCM_SECTION L1C_Cache_Miss_Count_Get(void) { return BL_RD_REG(L1C_BASE, L1C_MISS_CNT); } #endif /****************************************************************************/ /** - * @brief Disable read from flash or psram with cache - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Disable read from flash or psram with cache + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION L1C_Cache_Read_Disable(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION L1C_Cache_Read_Disable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); } #endif /****************************************************************************/ /** - * @brief wrap set - * - * @param wrap: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief wrap set + * + * @param wrap: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION L1C_Set_Wrap(BL_Fun_Type wrap) -{ - uint32_t tmpVal = 0; - uint8_t cacheEn = 0; +BL_Err_Type ATTR_TCM_SECTION L1C_Set_Wrap(BL_Fun_Type wrap) { + uint32_t tmpVal = 0; + uint8_t cacheEn = 0; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - cacheEn = BL_IS_REG_BIT_SET(L1C_BASE, L1C_CACHEABLE); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + cacheEn = BL_IS_REG_BIT_SET(L1C_BASE, L1C_CACHEABLE); - if (cacheEn != 0) { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - } + if (cacheEn != 0) { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + } - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - if (wrap == ENABLE) { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WRAP_DIS); - } else { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WRAP_DIS); - } + if (wrap == ENABLE) { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_WRAP_DIS); + } else { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_WRAP_DIS); + } - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - if (cacheEn != 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - } + if (cacheEn != 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief cache way disable set - * - * @param disableVal: cache way disable value - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief cache way disable set + * + * @param disableVal: cache way disable value + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION L1C_Set_Way_Disable(uint8_t disableVal) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_TCM_SECTION L1C_Set_Way_Disable(uint8_t disableVal) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_WAY_DIS, disableVal); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_WAY_DIS, disableVal); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - if (disableVal != 0x0f) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); - } + if (disableVal != 0x0f) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_CACHEABLE); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_CACHEABLE); + } - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set for ROM 2T access if CPU freq >120MHz - * - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set for ROM 2T access if CPU freq >120MHz + * + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION L1C_IROM_2T_Access_Set(uint8_t enable) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_TCM_SECTION L1C_IROM_2T_Access_Set(uint8_t enable) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_IROM_2T_ACCESS); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_IROM_2T_ACCESS); - } + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_IROM_2T_ACCESS); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_IROM_2T_ACCESS); + } - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief L1C BMX init - * - * @param l1cBmxCfg: L1C BMX config - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_Init(L1C_BMX_Cfg_Type *l1cBmxCfg) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM((l1cBmxCfg->timeoutEn) <= 0xF); - - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_TIMEOUT_EN, l1cBmxCfg->timeoutEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_EN, l1cBmxCfg->errEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_ARB_MODE, l1cBmxCfg->arbMod); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + * @brief L1C BMX init + * + * @param l1cBmxCfg: L1C BMX config + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_Init(L1C_BMX_Cfg_Type *l1cBmxCfg) { + uint32_t tmpVal = 0; + + CHECK_PARAM((l1cBmxCfg->timeoutEn) <= 0xF); + + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_TIMEOUT_EN, l1cBmxCfg->timeoutEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_EN, l1cBmxCfg->errEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, L1C_BMX_ARB_MODE, l1cBmxCfg->arbMod); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(L1C_BMX_ERR_IRQn, L1C_BMX_ERR_IRQHandler); - Interrupt_Handler_Register(L1C_BMX_TO_IRQn, L1C_BMX_TO_IRQHandler); + Interrupt_Handler_Register(L1C_BMX_ERR_IRQn, L1C_BMX_ERR_IRQHandler); + Interrupt_Handler_Register(L1C_BMX_TO_IRQn, L1C_BMX_TO_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX address monitor enable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_Addr_Monitor_Enable(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BMX_ERR_ADDR_DIS); - BL_WR_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN, tmpVal); - - return SUCCESS; + * @brief L1C BMX address monitor enable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_Addr_Monitor_Enable(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BMX_ERR_ADDR_DIS); + BL_WR_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX address monitor disable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_Addr_Monitor_Disable(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BMX_ERR_ADDR_DIS); - BL_WR_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN, tmpVal); - - return SUCCESS; + * @brief L1C BMX address monitor disable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_Addr_Monitor_Disable(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BMX_ERR_ADDR_DIS); + BL_WR_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX bus error response enable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_BusErrResponse_Enable(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BMX_ERR_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - - return SUCCESS; + * @brief L1C BMX bus error response enable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_BusErrResponse_Enable(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, L1C_BMX_ERR_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX bus error response disable - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_BusErrResponse_Disable(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BMX_ERR_EN); - BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); - - return SUCCESS; + * @brief L1C BMX bus error response disable + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_BusErrResponse_Disable(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(L1C_BASE, L1C_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, L1C_BMX_ERR_EN); + BL_WR_REG(L1C_BASE, L1C_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Get L1C BMX error status - * - * @param errType: L1C BMX error status type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type L1C_BMX_Get_Status(L1C_BMX_BUS_ERR_Type errType) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_L1C_BMX_BUS_ERR_TYPE(errType)); - - tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); - - if (errType == L1C_BMX_BUS_ERR_TRUSTZONE_DECODE) { - return BL_GET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_TZ) ? SET : RESET; - } else { - return BL_GET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_DEC) ? SET : RESET; - } + * @brief Get L1C BMX error status + * + * @param errType: L1C BMX error status type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type L1C_BMX_Get_Status(L1C_BMX_BUS_ERR_Type errType) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_L1C_BMX_BUS_ERR_TYPE(errType)); + + tmpVal = BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR_EN); + + if (errType == L1C_BMX_BUS_ERR_TRUSTZONE_DECODE) { + return BL_GET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_TZ) ? SET : RESET; + } else { + return BL_GET_REG_BITS_VAL(tmpVal, L1C_BMX_ERR_DEC) ? SET : RESET; + } } /****************************************************************************/ /** - * @brief Get L1C BMX error address - * - * @param None - * - * @return NP L1C BMX error address - * -*******************************************************************************/ -uint32_t L1C_BMX_Get_Err_Addr(void) -{ - return BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR); -} + * @brief Get L1C BMX error address + * + * @param None + * + * @return NP L1C BMX error address + * + *******************************************************************************/ +uint32_t L1C_BMX_Get_Err_Addr(void) { return BL_RD_REG(L1C_BASE, L1C_BMX_ERR_ADDR); } /****************************************************************************/ /** - * @brief L1C BMX error interrupt callback install - * - * @param intType: L1C BMX error interrupt type - * @param cbFun: callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_ERR_INT_Callback_Install(L1C_BMX_ERR_INT_Type intType, intCallback_Type *cbFun) -{ - CHECK_PARAM(IS_L1C_BMX_ERR_INT_TYPE(intType)); - - l1cBmxErrIntCbfArra[intType] = cbFun; - - return SUCCESS; + * @brief L1C BMX error interrupt callback install + * + * @param intType: L1C BMX error interrupt type + * @param cbFun: callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_ERR_INT_Callback_Install(L1C_BMX_ERR_INT_Type intType, intCallback_Type *cbFun) { + CHECK_PARAM(IS_L1C_BMX_ERR_INT_TYPE(intType)); + + l1cBmxErrIntCbfArra[intType] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX ERR interrupt IRQ handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief L1C BMX ERR interrupt IRQ handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void L1C_BMX_ERR_IRQHandler(void) -{ - L1C_BMX_ERR_INT_Type intType; - - for (intType = L1C_BMX_ERR_INT_ERR; intType < L1C_BMX_ERR_INT_ALL; intType++) { - if (l1cBmxErrIntCbfArra[intType] != NULL) { - l1cBmxErrIntCbfArra[intType](); - } - } +void L1C_BMX_ERR_IRQHandler(void) { + L1C_BMX_ERR_INT_Type intType; - while (1) { - //MSG("L1C_BMX_ERR_IRQHandler\r\n"); - BL702_Delay_MS(1000); + for (intType = L1C_BMX_ERR_INT_ERR; intType < L1C_BMX_ERR_INT_ALL; intType++) { + if (l1cBmxErrIntCbfArra[intType] != NULL) { + l1cBmxErrIntCbfArra[intType](); } + } + + while (1) { + // MSG("L1C_BMX_ERR_IRQHandler\r\n"); + BL702_Delay_MS(1000); + } } #endif /****************************************************************************/ /** - * @brief L1C BMX timeout interrupt callback install - * - * @param intType: L1C BMX timeout interrupt type - * @param cbFun: callback - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type L1C_BMX_TIMEOUT_INT_Callback_Install(L1C_BMX_TO_INT_Type intType, intCallback_Type *cbFun) -{ - CHECK_PARAM(IS_L1C_BMX_TO_INT_TYPE(intType)); - - l1cBmxToIntCbfArra[intType] = cbFun; - - return SUCCESS; + * @brief L1C BMX timeout interrupt callback install + * + * @param intType: L1C BMX timeout interrupt type + * @param cbFun: callback + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type L1C_BMX_TIMEOUT_INT_Callback_Install(L1C_BMX_TO_INT_Type intType, intCallback_Type *cbFun) { + CHECK_PARAM(IS_L1C_BMX_TO_INT_TYPE(intType)); + + l1cBmxToIntCbfArra[intType] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief L1C BMX Time Out interrupt IRQ handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief L1C BMX Time Out interrupt IRQ handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void L1C_BMX_TO_IRQHandler(void) -{ - L1C_BMX_TO_INT_Type intType; - - for (intType = L1C_BMX_TO_INT_TIMEOUT; intType < L1C_BMX_TO_INT_ALL; intType++) { - if (l1cBmxToIntCbfArra[intType] != NULL) { - l1cBmxToIntCbfArra[intType](); - } - } +void L1C_BMX_TO_IRQHandler(void) { + L1C_BMX_TO_INT_Type intType; - while (1) { - //MSG("L1C_BMX_TO_IRQHandler\r\n"); - BL702_Delay_MS(1000); + for (intType = L1C_BMX_TO_INT_TIMEOUT; intType < L1C_BMX_TO_INT_ALL; intType++) { + if (l1cBmxToIntCbfArra[intType] != NULL) { + l1cBmxToIntCbfArra[intType](); } + } + + while (1) { + // MSG("L1C_BMX_TO_IRQHandler\r\n"); + BL702_Delay_MS(1000); + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_mjpeg.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_mjpeg.c index 06ff2f951..144d3c9ad 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_mjpeg.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_mjpeg.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_mjpeg.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_mjpeg.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702.h" #include "bl702_mjpeg.h" +#include "bl702.h" #include "bl702_glb.h" /** @addtogroup BL702_Peripheral_Driver @@ -61,7 +61,7 @@ /** @defgroup MJPEG_Private_Variables * @{ */ -static intCallback_Type *mjpegIntCbfArra[MJPEG_INT_ALL] = { NULL }; +static intCallback_Type *mjpegIntCbfArra[MJPEG_INT_ALL] = {NULL}; /*@} end of group MJPEG_Private_Variables */ @@ -88,648 +88,611 @@ static intCallback_Type *mjpegIntCbfArra[MJPEG_INT_ALL] = { NULL }; */ /****************************************************************************/ /** - * @brief Mjpeg module init - * - * @param cfg: Mjpeg configuration structure pointer - * - * @return None - * -*******************************************************************************/ -void MJPEG_Init(MJPEG_CFG_Type *cfg) -{ - uint32_t tmpVal; - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_MJPEG); - - /* disable mjpeg */ - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); - - /* basic stuff */ - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YUV_MODE, cfg->yuv); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Q_MODE, cfg->quality); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_H_BUST, cfg->burst); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_MJPEG_BIT_ORDER, cfg->bitOrderEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_ORDER_U_EVEN, cfg->evenOrderEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_WR_OVER_STOP, cfg->overStopEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_REFLECT_DMY, cfg->reflectDmy); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_LAST_HF_HBLK_DMY, cfg->verticalDmy); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_LAST_HF_WBLK_DMY, cfg->horizationalDmy); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_MJPEG_WAIT_CYCLE, cfg->waitCount); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_FRAME_SIZE); - - switch (cfg->yuv) { - case MJPEG_YUV422_INTERLEAVE: - case MJPEG_YUV422_PLANAR: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 15) >> 4); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 7) >> 3); - break; - - case MJPEG_YUV420: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 15) >> 4); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 15) >> 4); - break; - - case MJPEG_YUV400: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 7) >> 3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 7) >> 3); - break; - - default: - break; - } - - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_SIZE, tmpVal); - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_W_SWAP_MODE, cfg->swapModeEnable); - BL_WR_REG(MJPEG_BASE, MJPEG_SWAP_MODE, tmpVal); - - /*align buffer to 16 bytes boundary, should be kept the same as CAM module*/ - BL_WR_REG(MJPEG_BASE, MJPEG_YY_FRAME_ADDR, (cfg->bufferCamYY & 0xFFFFFFF0)); - BL_WR_REG(MJPEG_BASE, MJPEG_UV_FRAME_ADDR, (cfg->bufferCamUV & 0xFFFFFFF0)); - BL_WR_REG(MJPEG_BASE, MJPEG_YUV_MEM, (cfg->sizeCamUV << 16) + cfg->sizeCamYY); - - /*align buffer to 16 bytes boundary*/ - BL_WR_REG(MJPEG_BASE, MJPEG_JPEG_FRAME_ADDR, (cfg->bufferMjpeg & 0xFFFFFFF0)); - /*align buffer size in unit of 64 bytes */ - BL_WR_REG(MJPEG_BASE, MJPEG_JPEG_STORE_MEMORY, cfg->sizeMjpeg >> 6); - - /* Clear interrupt */ - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x3F00); + * @brief Mjpeg module init + * + * @param cfg: Mjpeg configuration structure pointer + * + * @return None + * + *******************************************************************************/ +void MJPEG_Init(MJPEG_CFG_Type *cfg) { + uint32_t tmpVal; + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_MJPEG); + + /* disable mjpeg */ + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); + + /* basic stuff */ + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YUV_MODE, cfg->yuv); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Q_MODE, cfg->quality); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_H_BUST, cfg->burst); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_MJPEG_BIT_ORDER, cfg->bitOrderEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_ORDER_U_EVEN, cfg->evenOrderEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_WR_OVER_STOP, cfg->overStopEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_REFLECT_DMY, cfg->reflectDmy); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_LAST_HF_HBLK_DMY, cfg->verticalDmy); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_LAST_HF_WBLK_DMY, cfg->horizationalDmy); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_MJPEG_WAIT_CYCLE, cfg->waitCount); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_FRAME_SIZE); + + switch (cfg->yuv) { + case MJPEG_YUV422_INTERLEAVE: + case MJPEG_YUV422_PLANAR: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 15) >> 4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 7) >> 3); + break; + + case MJPEG_YUV420: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 15) >> 4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 15) >> 4); + break; + + case MJPEG_YUV400: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_WBLK, (cfg->resolutionX + 7) >> 3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_HBLK, (cfg->resolutionY + 7) >> 3); + break; + + default: + break; + } + + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_SIZE, tmpVal); + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_W_SWAP_MODE, cfg->swapModeEnable); + BL_WR_REG(MJPEG_BASE, MJPEG_SWAP_MODE, tmpVal); + + /*align buffer to 16 bytes boundary, should be kept the same as CAM module*/ + BL_WR_REG(MJPEG_BASE, MJPEG_YY_FRAME_ADDR, (cfg->bufferCamYY & 0xFFFFFFF0)); + BL_WR_REG(MJPEG_BASE, MJPEG_UV_FRAME_ADDR, (cfg->bufferCamUV & 0xFFFFFFF0)); + BL_WR_REG(MJPEG_BASE, MJPEG_YUV_MEM, (cfg->sizeCamUV << 16) + cfg->sizeCamYY); + + /*align buffer to 16 bytes boundary*/ + BL_WR_REG(MJPEG_BASE, MJPEG_JPEG_FRAME_ADDR, (cfg->bufferMjpeg & 0xFFFFFFF0)); + /*align buffer size in unit of 64 bytes */ + BL_WR_REG(MJPEG_BASE, MJPEG_JPEG_STORE_MEMORY, cfg->sizeMjpeg >> 6); + + /* Clear interrupt */ + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x3F00); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(MJPEG_IRQn, MJPEG_IRQHandler); + Interrupt_Handler_Register(MJPEG_IRQn, MJPEG_IRQHandler); #endif } /****************************************************************************/ /** - * @brief Mjpeg packet mode configure - * - * @param cfg: Packet configuration - * - * @return None - * -*******************************************************************************/ -void MJPEG_Packet_Config(MJPEG_Packet_Type *cfg) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_PAKET_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_PKET_EN, cfg->packetEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_JEND_TO_PEND, cfg->endToTail); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_PKET_BODY_BYTE, cfg->packetBody); - BL_WR_REG(MJPEG_BASE, MJPEG_PAKET_CTRL, tmpVal); - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_HEADER_BYTE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_HEAD_BYTE, cfg->frameHead); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_TAIL_EXP, cfg->frameTail); - BL_WR_REG(MJPEG_BASE, MJPEG_HEADER_BYTE, tmpVal); - - BL_WR_REG(MJPEG_BASE, MJPEG_PAKET_HEAD_TAIL, (cfg->packetTail << 16) + cfg->packetHead); + * @brief Mjpeg packet mode configure + * + * @param cfg: Packet configuration + * + * @return None + * + *******************************************************************************/ +void MJPEG_Packet_Config(MJPEG_Packet_Type *cfg) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_PAKET_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_PKET_EN, cfg->packetEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_JEND_TO_PEND, cfg->endToTail); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_PKET_BODY_BYTE, cfg->packetBody); + BL_WR_REG(MJPEG_BASE, MJPEG_PAKET_CTRL, tmpVal); + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_HEADER_BYTE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_HEAD_BYTE, cfg->frameHead); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_TAIL_EXP, cfg->frameTail); + BL_WR_REG(MJPEG_BASE, MJPEG_HEADER_BYTE, tmpVal); + + BL_WR_REG(MJPEG_BASE, MJPEG_PAKET_HEAD_TAIL, (cfg->packetTail << 16) + cfg->packetHead); } /****************************************************************************/ /** - * @brief Mjpeg set YUYV order, only work in interleave mode - * - * @param y0: Y0 order - * @param u0: U0 order - * @param y1: Y1 order - * @param v0: V0 order - * - * @return None - * -*******************************************************************************/ -void MJPEG_Set_YUYV_Order_Interleave(uint8_t y0, uint8_t u0, uint8_t y1, uint8_t v0) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Y0_ORDER, y0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_U0_ORDER, u0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Y1_ORDER, y1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_V0_ORDER, v0); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); - - MJPEG_Set_YUYV_Order_Planar(0, 1); + * @brief Mjpeg set YUYV order, only work in interleave mode + * + * @param y0: Y0 order + * @param u0: U0 order + * @param y1: Y1 order + * @param v0: V0 order + * + * @return None + * + *******************************************************************************/ +void MJPEG_Set_YUYV_Order_Interleave(uint8_t y0, uint8_t u0, uint8_t y1, uint8_t v0) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Y0_ORDER, y0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_U0_ORDER, u0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_Y1_ORDER, y1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_V0_ORDER, v0); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); + + MJPEG_Set_YUYV_Order_Planar(0, 1); } /****************************************************************************/ /** - * @brief Mjpeg set YY/UV order, only work in planar mode - * - * @param yy: YY order - * @param uv: UV order - * - * @return None - * -*******************************************************************************/ -void MJPEG_Set_YUYV_Order_Planar(uint8_t yy, uint8_t uv) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YY_DVP2AHB_LSEL, yy); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YY_DVP2AHB_FSEL, yy); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_UV_DVP2AHB_LSEL, uv); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_UV_DVP2AHB_FSEL, uv); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + * @brief Mjpeg set YY/UV order, only work in planar mode + * + * @param yy: YY order + * @param uv: UV order + * + * @return None + * + *******************************************************************************/ +void MJPEG_Set_YUYV_Order_Planar(uint8_t yy, uint8_t uv) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YY_DVP2AHB_LSEL, yy); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_YY_DVP2AHB_FSEL, yy); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_UV_DVP2AHB_LSEL, uv); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_UV_DVP2AHB_FSEL, uv); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); } /****************************************************************************/ /** - * @brief Deinit mjpeg module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_Deinit(void) -{ - //GLB_AHB_Slave2_Reset(BL_AHB_SLAVE2_MJPEG); + * @brief Deinit mjpeg module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_Deinit(void) { + // GLB_AHB_Slave2_Reset(BL_AHB_SLAVE2_MJPEG); } /****************************************************************************/ /** - * @brief Enable mjpeg module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_Enable(void) -{ - uint32_t tmpVal; - - /* Enable mjpeg module */ - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); + * @brief Enable mjpeg module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_Enable(void) { + uint32_t tmpVal; + + /* Enable mjpeg module */ + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); } /****************************************************************************/ /** - * @brief Disable mjpeg module - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_Disable(void) -{ - uint32_t tmpVal; - - /* Disable mjpeg module */ - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); + * @brief Disable mjpeg module + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_Disable(void) { + uint32_t tmpVal; + + /* Disable mjpeg module */ + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_1); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_ENABLE); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_1, tmpVal); } /****************************************************************************/ /** - * @brief Enable&disable mjpeg software mode and set frame count - * - * @param count: Frame count - * - * @return None - * -*******************************************************************************/ -void MJPEG_SW_Enable(uint8_t count) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_SW_FRAME, count); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_MODE); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_MODE); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + * @brief Enable&disable mjpeg software mode and set frame count + * + * @param count: Frame count + * + * @return None + * + *******************************************************************************/ +void MJPEG_SW_Enable(uint8_t count) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_SW_FRAME, count); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_MODE); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_MODE); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); } /****************************************************************************/ /** - * @brief MJPEG software mode run, software mode enable first - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_SW_Run(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_RUN); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_RUN); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + * @brief MJPEG software mode run, software mode enable first + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_SW_Run(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_2); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_RUN); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_MJPEG_SW_RUN); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_2, tmpVal); } /****************************************************************************/ /** - * @brief Get one mjpeg frame - * - * @param info: Mjpeg frame infomation pointer - * - * @return None - * -*******************************************************************************/ -void MJPEG_Get_Frame_Info(MJPEG_Frame_Info *info) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); - - info->validFrames = BL_GET_REG_BITS_VAL(tmpVal, MJPEG_FRAME_VALID_CNT); - info->curFrameAddr = BL_RD_REG(MJPEG_BASE, MJPEG_START_ADDR0); - info->curFrameBytes = (BL_RD_REG(MJPEG_BASE, MJPEG_BIT_CNT0) + 7) >> 3; - info->curFrameQ = BL_RD_REG(MJPEG_BASE, MJPEG_Q_MODE0) & 0x3f; - info->status = tmpVal; + * @brief Get one mjpeg frame + * + * @param info: Mjpeg frame infomation pointer + * + * @return None + * + *******************************************************************************/ +void MJPEG_Get_Frame_Info(MJPEG_Frame_Info *info) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); + + info->validFrames = BL_GET_REG_BITS_VAL(tmpVal, MJPEG_FRAME_VALID_CNT); + info->curFrameAddr = BL_RD_REG(MJPEG_BASE, MJPEG_START_ADDR0); + info->curFrameBytes = (BL_RD_REG(MJPEG_BASE, MJPEG_BIT_CNT0) + 7) >> 3; + info->curFrameQ = BL_RD_REG(MJPEG_BASE, MJPEG_Q_MODE0) & 0x3f; + info->status = tmpVal; } /****************************************************************************/ /** - * @brief Get available count of frames - * - * @param None - * - * @return Frames count - * -*******************************************************************************/ -uint8_t MJPEG_Get_Frame_Count(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3), MJPEG_FRAME_VALID_CNT); -} + * @brief Get available count of frames + * + * @param None + * + * @return Frames count + * + *******************************************************************************/ +uint8_t MJPEG_Get_Frame_Count(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3), MJPEG_FRAME_VALID_CNT); } /****************************************************************************/ /** - * @brief Pop one mjpeg frame - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_Pop_Frame(void) -{ - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 1); -} + * @brief Pop one mjpeg frame + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_Pop_Frame(void) { BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 1); } /****************************************************************************/ /** - * @brief Free current read memory block - * - * @param None - * - * @return None - * -*******************************************************************************/ -void MJPEG_Current_Block_Clear(void) -{ - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x2); -} + * @brief Free current read memory block + * + * @param None + * + * @return None + * + *******************************************************************************/ +void MJPEG_Current_Block_Clear(void) { BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x2); } /****************************************************************************/ /** - * @brief Current read memory block index - * - * @param None - * - * @return Block number - * -*******************************************************************************/ -MJPEG_Swap_Block_Type MJPEG_Get_Current_Block(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_READ_SWAP_IDX); -} + * @brief Current read memory block index + * + * @param None + * + * @return Block number + * + *******************************************************************************/ +MJPEG_Swap_Block_Type MJPEG_Get_Current_Block(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_READ_SWAP_IDX); } /****************************************************************************/ /** - * @brief Get block status, full or not full - * - * @param block: Block number - * - * @return Block status - * -*******************************************************************************/ -BL_Sts_Type MJPEG_Block_Is_Full(MJPEG_Swap_Block_Type block) -{ - CHECK_PARAM(IS_MJPEG_SWAP_BLOCK_TYPE(block)); - - if (MJPEG_BLOCK_0 == block) { - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP0_FULL); - } else { - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP1_FULL); - } + * @brief Get block status, full or not full + * + * @param block: Block number + * + * @return Block status + * + *******************************************************************************/ +BL_Sts_Type MJPEG_Block_Is_Full(MJPEG_Swap_Block_Type block) { + CHECK_PARAM(IS_MJPEG_SWAP_BLOCK_TYPE(block)); + + if (MJPEG_BLOCK_0 == block) { + return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP0_FULL); + } else { + return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP1_FULL); + } } /****************************************************************************/ /** - * @brief Current read memory block is frame start - * - * @param None - * - * @return Set or reset - * -*******************************************************************************/ -BL_Sts_Type MJPEG_Current_Block_Is_Start(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP_FSTART); -} + * @brief Current read memory block is frame start + * + * @param None + * + * @return Set or reset + * + *******************************************************************************/ +BL_Sts_Type MJPEG_Current_Block_Is_Start(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP_FSTART); } /****************************************************************************/ /** - * @brief Current read memory block is frame end - * - * @param None - * - * @return Set or reset - * -*******************************************************************************/ -BL_Sts_Type MJPEG_Current_Block_Is_End(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP_FEND); -} + * @brief Current read memory block is frame end + * + * @param None + * + * @return Set or reset + * + *******************************************************************************/ +BL_Sts_Type MJPEG_Current_Block_Is_End(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_MODE), MJPEG_STS_SWAP_FEND); } /****************************************************************************/ /** - * @brief Get frame remain bit count in last block, only valid when current read memory block is - * frame end - * - * @param None - * - * @return Bit count - * -*******************************************************************************/ -uint32_t MJPEG_Get_Remain_Bit(void) -{ - return BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_BIT_CNT); -} + * @brief Get frame remain bit count in last block, only valid when current read memory block is + * frame end + * + * @param None + * + * @return Bit count + * + *******************************************************************************/ +uint32_t MJPEG_Get_Remain_Bit(void) { return BL_RD_REG(MJPEG_BASE, MJPEG_SWAP_BIT_CNT); } /****************************************************************************/ /** - * @brief Set frame threshold to issue normal interrupt - * - * @param count: Frame threshold - * - * @return None - * -*******************************************************************************/ -void MJPEG_Set_Frame_Threshold(uint8_t count) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_CNT_TRGR_INT, count); - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_3, tmpVal); + * @brief Set frame threshold to issue normal interrupt + * + * @param count: Frame threshold + * + * @return None + * + *******************************************************************************/ +void MJPEG_Set_Frame_Threshold(uint8_t count) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, MJPEG_REG_FRAME_CNT_TRGR_INT, count); + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_3, tmpVal); } /****************************************************************************/ /** - * @brief MJPEG Enable Disable Interrupt - * - * @param intType: MJPEG Interrupt Type - * @param intMask: Enable or Disable - * - * @return None - * -*******************************************************************************/ -void MJPEG_IntMask(MJPEG_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); - - switch (intType) { - case MJPEG_INT_NORMAL: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); - } - - break; - - case MJPEG_INT_CAM_OVERWRITE: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); - } - - break; - - case MJPEG_INT_MEM_OVERWRITE: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); - } - - break; - - case MJPEG_INT_FRAME_OVERWRITE: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); - } - - break; - - case MJPEG_INT_BACK_IDLE: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); - } - - break; - - case MJPEG_INT_SWAP: - if (intMask == UNMASK) { - /* Enable this interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); - } else { - /* Disable this interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); - } - - break; - - case MJPEG_INT_ALL: - if (intMask == UNMASK) { - /* Enable all interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); - } else { - /* Disable all interrupt */ - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); - } - - break; - - default: - break; + * @brief MJPEG Enable Disable Interrupt + * + * @param intType: MJPEG Interrupt Type + * @param intMask: Enable or Disable + * + * @return None + * + *******************************************************************************/ +void MJPEG_IntMask(MJPEG_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); + + switch (intType) { + case MJPEG_INT_NORMAL: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); + } + + break; + + case MJPEG_INT_CAM_OVERWRITE: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); + } + + break; + + case MJPEG_INT_MEM_OVERWRITE: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); + } + + break; + + case MJPEG_INT_FRAME_OVERWRITE: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); } - BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_3, tmpVal); + break; + + case MJPEG_INT_BACK_IDLE: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); + } + + break; + + case MJPEG_INT_SWAP: + if (intMask == UNMASK) { + /* Enable this interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); + } else { + /* Disable this interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); + } + + break; + + case MJPEG_INT_ALL: + if (intMask == UNMASK) { + /* Enable all interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); + } else { + /* Disable all interrupt */ + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_EN); + } + + break; + + default: + break; + } + + BL_WR_REG(MJPEG_BASE, MJPEG_CONTROL_3, tmpVal); } /****************************************************************************/ /** - * @brief MJPEG Interrupt Clear - * - * @param intType: MJPEG Interrupt Type - * - * @return None - * -*******************************************************************************/ -void MJPEG_IntClr(MJPEG_INT_Type intType) -{ - uint32_t tmpVal; + * @brief MJPEG Interrupt Clear + * + * @param intType: MJPEG Interrupt Type + * + * @return None + * + *******************************************************************************/ +void MJPEG_IntClr(MJPEG_INT_Type intType) { + uint32_t tmpVal; - CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); + CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP); + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP); - switch (intType) { - case MJPEG_INT_NORMAL: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_CLR); - break; + switch (intType) { + case MJPEG_INT_NORMAL: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_NORMAL_CLR); + break; - case MJPEG_INT_CAM_OVERWRITE: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_CLR); - break; + case MJPEG_INT_CAM_OVERWRITE: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_CAM_CLR); + break; - case MJPEG_INT_MEM_OVERWRITE: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_CLR); - break; + case MJPEG_INT_MEM_OVERWRITE: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_MEM_CLR); + break; - case MJPEG_INT_FRAME_OVERWRITE: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_CLR); - break; + case MJPEG_INT_FRAME_OVERWRITE: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_FRAME_CLR); + break; - case MJPEG_INT_BACK_IDLE: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_CLR); - break; + case MJPEG_INT_BACK_IDLE: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_IDLE_CLR); + break; - case MJPEG_INT_SWAP: - tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_CLR); - break; + case MJPEG_INT_SWAP: + tmpVal = BL_SET_REG_BIT(tmpVal, MJPEG_REG_INT_SWAP_CLR); + break; - case MJPEG_INT_ALL: - tmpVal = 0x3F00; + case MJPEG_INT_ALL: + tmpVal = 0x3F00; - default: - break; - } + default: + break; + } - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, tmpVal); + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, tmpVal); } /****************************************************************************/ /** - * @brief Install mjpeg interrupt callback function - * - * @param intType: MJPEG interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return None - * -*******************************************************************************/ -void MJPEG_Int_Callback_Install(MJPEG_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); - - mjpegIntCbfArra[intType] = cbFun; + * @brief Install mjpeg interrupt callback function + * + * @param intType: MJPEG interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return None + * + *******************************************************************************/ +void MJPEG_Int_Callback_Install(MJPEG_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_MJPEG_INT_TYPE(intType)); + + mjpegIntCbfArra[intType] = cbFun; } /****************************************************************************/ /** - * @brief Mjpeg interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Mjpeg interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void MJPEG_IRQHandler(void) -{ - uint32_t tmpVal; +void MJPEG_IRQHandler(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); + tmpVal = BL_RD_REG(MJPEG_BASE, MJPEG_CONTROL_3); - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_NORMAL_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x100); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_NORMAL_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x100); - if (mjpegIntCbfArra[MJPEG_INT_NORMAL] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_NORMAL](); - } + if (mjpegIntCbfArra[MJPEG_INT_NORMAL] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_NORMAL](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_CAM_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x200); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_CAM_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x200); - if (mjpegIntCbfArra[MJPEG_INT_CAM_OVERWRITE] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_CAM_OVERWRITE](); - } + if (mjpegIntCbfArra[MJPEG_INT_CAM_OVERWRITE] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_CAM_OVERWRITE](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_MEM_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x400); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_MEM_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x400); - if (mjpegIntCbfArra[MJPEG_INT_MEM_OVERWRITE] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_MEM_OVERWRITE](); - } + if (mjpegIntCbfArra[MJPEG_INT_MEM_OVERWRITE] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_MEM_OVERWRITE](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_FRAME_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x800); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_FRAME_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x800); - if (mjpegIntCbfArra[MJPEG_INT_FRAME_OVERWRITE] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_FRAME_OVERWRITE](); - } + if (mjpegIntCbfArra[MJPEG_INT_FRAME_OVERWRITE] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_FRAME_OVERWRITE](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_IDLE_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x1000); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_IDLE_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x1000); - if (mjpegIntCbfArra[MJPEG_INT_BACK_IDLE] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_BACK_IDLE](); - } + if (mjpegIntCbfArra[MJPEG_INT_BACK_IDLE] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_BACK_IDLE](); } + } - if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_SWAP_INT)) { - BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x2000); + if (BL_IS_REG_BIT_SET(tmpVal, MJPEG_STS_SWAP_INT)) { + BL_WR_REG(MJPEG_BASE, MJPEG_FRAME_FIFO_POP, 0x2000); - if (mjpegIntCbfArra[MJPEG_INT_SWAP] != NULL) { - /* call the callback function */ - mjpegIntCbfArra[MJPEG_INT_SWAP](); - } + if (mjpegIntCbfArra[MJPEG_INT_SWAP] != NULL) { + /* call the callback function */ + mjpegIntCbfArra[MJPEG_INT_SWAP](); } + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c index 28b6cbcf5..de47c5f10 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pds.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_pds.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_pds.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702.h" #include "bl702_pds.h" +#include "bl702.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -60,7 +60,7 @@ /** @defgroup PDS_Private_Variables * @{ */ -static intCallback_Type *pdsIntCbfArra[PDS_INT_MAX][1] = { { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL }, { NULL } }; +static intCallback_Type *pdsIntCbfArra[PDS_INT_MAX][1] = {{NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}, {NULL}}; /*@} end of group PDS_Private_Variables */ @@ -87,804 +87,773 @@ static intCallback_Type *pdsIntCbfArra[PDS_INT_MAX][1] = { { NULL }, { NULL }, { */ /****************************************************************************/ /** - * @brief power down sleep ram configure - * - * @param ramCfg: power down sleep force ram configuration - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION PDS_RAM_Config(PDS_RAM_CFG_Type *ramCfg) -{ - if (NULL == ramCfg) { - return ERROR; - } + * @brief power down sleep ram configure + * + * @param ramCfg: power down sleep force ram configuration + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION PDS_RAM_Config(PDS_RAM_CFG_Type *ramCfg) { + if (NULL == ramCfg) { + return ERROR; + } - /* PDS_RAM1 config */ - BL_WR_REG(PDS_BASE, PDS_RAM1, *(uint32_t *)ramCfg); + /* PDS_RAM1 config */ + BL_WR_REG(PDS_BASE, PDS_RAM1, *(uint32_t *)ramCfg); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief power down sleep set pad configure - * - * @param pin: power down sleep pad num - * @param cfg: power down sleep pad type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION PDS_Set_Pad_Config(PDS_PAD_PIN_Type pin, PDS_PAD_CFG_Type cfg) -{ - uint32_t tmpVal = 0; - uint32_t tmpPu = 0; - uint32_t tmpPd = 0; - - if (pin < PDS_PAD_PIN_GPIO_23) { - /* GPIO17 - GPIO22 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_SET_PU_PD); - - switch (cfg) { - case PDS_PAD_CFG_PULL_NONE: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) & ~(1 << pin); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) & ~(1 << pin); - break; - - case PDS_PAD_CFG_PULL_DOWN: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) | (1 << pin); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) & ~(1 << pin); - break; - - case PDS_PAD_CFG_PULL_UP: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) & ~(1 << pin); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) | (1 << pin); - break; - - case PDS_PAD_CFG_ACTIVE_IE: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) | (1 << pin); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) | (1 << pin); - break; - - default: - break; - } - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD, tmpPd); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU, tmpPu); - BL_WR_REG(PDS_BASE, PDS_GPIO_SET_PU_PD, tmpVal); - } else { - /* GPIO23 - GPIO28 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_SET_PU_PD); - - switch (cfg) { - case PDS_PAD_CFG_PULL_NONE: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); - break; - - case PDS_PAD_CFG_PULL_DOWN: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); - break; - - case PDS_PAD_CFG_PULL_UP: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); - break; - - case PDS_PAD_CFG_ACTIVE_IE: - tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); - tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); - break; - - default: - break; - } - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD, tmpPd); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU, tmpPu); - BL_WR_REG(PDS_BASE, PDS_GPIO_SET_PU_PD, tmpVal); + * @brief power down sleep set pad configure + * + * @param pin: power down sleep pad num + * @param cfg: power down sleep pad type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION PDS_Set_Pad_Config(PDS_PAD_PIN_Type pin, PDS_PAD_CFG_Type cfg) { + uint32_t tmpVal = 0; + uint32_t tmpPu = 0; + uint32_t tmpPd = 0; + + if (pin < PDS_PAD_PIN_GPIO_23) { + /* GPIO17 - GPIO22 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_SET_PU_PD); + + switch (cfg) { + case PDS_PAD_CFG_PULL_NONE: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) & ~(1 << pin); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) & ~(1 << pin); + break; + + case PDS_PAD_CFG_PULL_DOWN: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) | (1 << pin); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) & ~(1 << pin); + break; + + case PDS_PAD_CFG_PULL_UP: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) & ~(1 << pin); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) | (1 << pin); + break; + + case PDS_PAD_CFG_ACTIVE_IE: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD) | (1 << pin); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU) | (1 << pin); + break; + + default: + break; } - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief Enable power down sleep - * - * @param cfg: power down sleep configuration 1 - * @param cfg4: power down sleep configuration 2 - * @param pdsSleepCnt: power down sleep count cycle - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION PDS_App_Enable(PDS_CTL_Type *cfg, PDS_CTL4_Type *cfg4, uint32_t pdsSleepCnt) -{ - /* PDS sleep time 0 <=> sleep forever */ - /* PDS sleep time 1~PDS_WARMUP_LATENCY_CNT <=> error */ - /* PDS sleep time >PDS_WARMUP_LATENCY_CNT <=> correct */ - if (!pdsSleepCnt) { - cfg->sleepForever = 0; - } else if ((pdsSleepCnt) && (pdsSleepCnt <= PDS_WARMUP_LATENCY_CNT)) { - return ERROR; - } else { - BL_WR_REG(PDS_BASE, PDS_TIME1, pdsSleepCnt - PDS_WARMUP_LATENCY_CNT); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PD, tmpPd); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_22_17_PU, tmpPu); + BL_WR_REG(PDS_BASE, PDS_GPIO_SET_PU_PD, tmpVal); + } else { + /* GPIO23 - GPIO28 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_SET_PU_PD); + + switch (cfg) { + case PDS_PAD_CFG_PULL_NONE: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); + break; + + case PDS_PAD_CFG_PULL_DOWN: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); + break; + + case PDS_PAD_CFG_PULL_UP: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) & ~(1 << (pin - PDS_PAD_PIN_GPIO_23)); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); + break; + + case PDS_PAD_CFG_ACTIVE_IE: + tmpPd = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); + tmpPu = BL_GET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU) | (1 << (pin - PDS_PAD_PIN_GPIO_23)); + break; + + default: + break; } - /* PDS_CTL4 config */ - BL_WR_REG(PDS_BASE, PDS_CTL4, *(uint32_t *)cfg4); - - /* PDS_CTL config */ - if (cfg->pdsStart) { - BL_WR_REG(PDS_BASE, PDS_CTL, (*(uint32_t *)cfg & ~(1 << 0))); - BL_WR_REG(PDS_BASE, PDS_CTL, (*(uint32_t *)cfg | (1 << 0))); - } else { - BL_WR_REG(PDS_BASE, PDS_CTL, *(uint32_t *)cfg); - } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PD, tmpPd); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CR_PDS_GPIO_28_23_PU, tmpPu); + BL_WR_REG(PDS_BASE, PDS_GPIO_SET_PU_PD, tmpVal); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief power down sleep force configure - * - * @param cfg2: power down sleep force configuration 1 - * @param cfg3: power down sleep force configuration 2 - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION PDS_Force_Config(PDS_CTL2_Type *cfg2, PDS_CTL3_Type *cfg3) -{ - /* PDS_CTL2 config */ - BL_WR_REG(PDS_BASE, PDS_CTL2, *(uint32_t *)cfg2); - - /* PDS_CTL3 config */ - BL_WR_REG(PDS_BASE, PDS_CTL3, *(uint32_t *)cfg3); - - return SUCCESS; + * @brief Enable power down sleep + * + * @param cfg: power down sleep configuration 1 + * @param cfg4: power down sleep configuration 2 + * @param pdsSleepCnt: power down sleep count cycle + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION PDS_App_Enable(PDS_CTL_Type *cfg, PDS_CTL4_Type *cfg4, uint32_t pdsSleepCnt) { + /* PDS sleep time 0 <=> sleep forever */ + /* PDS sleep time 1~PDS_WARMUP_LATENCY_CNT <=> error */ + /* PDS sleep time >PDS_WARMUP_LATENCY_CNT <=> correct */ + if (!pdsSleepCnt) { + cfg->sleepForever = 0; + } else if ((pdsSleepCnt) && (pdsSleepCnt <= PDS_WARMUP_LATENCY_CNT)) { + return ERROR; + } else { + BL_WR_REG(PDS_BASE, PDS_TIME1, pdsSleepCnt - PDS_WARMUP_LATENCY_CNT); + } + + /* PDS_CTL4 config */ + BL_WR_REG(PDS_BASE, PDS_CTL4, *(uint32_t *)cfg4); + + /* PDS_CTL config */ + if (cfg->pdsStart) { + BL_WR_REG(PDS_BASE, PDS_CTL, (*(uint32_t *)cfg & ~(1 << 0))); + BL_WR_REG(PDS_BASE, PDS_CTL, (*(uint32_t *)cfg | (1 << 0))); + } else { + BL_WR_REG(PDS_BASE, PDS_CTL, *(uint32_t *)cfg); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief power down sleep force configure - * - * @param defaultLvCfg: power down sleep default level configuration - * @param pdsSleepCnt: power down sleep time count - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION PDS_Default_Level_Config(PDS_DEFAULT_LV_CFG_Type *defaultLvCfg, uint32_t pdsSleepCnt) -{ - PDS_Force_Config((PDS_CTL2_Type *)&(defaultLvCfg->pdsCtl2), (PDS_CTL3_Type *)&(defaultLvCfg->pdsCtl3)); - PDS_App_Enable((PDS_CTL_Type *)&(defaultLvCfg->pdsCtl), (PDS_CTL4_Type *)&(defaultLvCfg->pdsCtl4), pdsSleepCnt); - - return SUCCESS; + * @brief power down sleep force configure + * + * @param cfg2: power down sleep force configuration 1 + * @param cfg3: power down sleep force configuration 2 + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION PDS_Force_Config(PDS_CTL2_Type *cfg2, PDS_CTL3_Type *cfg3) { + /* PDS_CTL2 config */ + BL_WR_REG(PDS_BASE, PDS_CTL2, *(uint32_t *)cfg2); + + /* PDS_CTL3 config */ + BL_WR_REG(PDS_BASE, PDS_CTL3, *(uint32_t *)cfg3); + + return SUCCESS; } /****************************************************************************/ /** - * @brief power down sleep int enable - * - * @param intType: PDS int type - * @param enable: ENABLE or DISABLE - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_IntEn(PDS_INT_Type intType, BL_Fun_Type enable) -{ - uint32_t offset = 0; - uint32_t tmpVal = 0; - - if ((intType < PDS_INT_PDS_SLEEP_CNT) || (intType > PDS_INT_KYS_QDEC)) { - return ERROR; - } - - switch (intType) { - case PDS_INT_WAKEUP: - case PDS_INT_RF_DONE: - case PDS_INT_PLL_DONE: - return ERROR; - - case PDS_INT_PDS_SLEEP_CNT: - offset = 16; - break; - - case PDS_INT_HBN_IRQ_OUT0: - offset = 17; - break; - - case PDS_INT_HBN_IRQ_OUT1: - offset = 18; - break; - - case PDS_INT_GPIO_IRQ: - offset = 19; - break; - - case PDS_INT_IRRX: - offset = 20; - break; - - case PDS_INT_BLE_SLP_IRQ: - offset = 21; - break; - - case PDS_INT_USB_WKUP: - offset = 22; - break; - - case PDS_INT_KYS_QDEC: - offset = 23; - break; - - case PDS_INT_MAX: - break; - - default: - break; - } - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - - if (enable) { - tmpVal = tmpVal | (1 << offset); - } else { - tmpVal = tmpVal & ~(1 << offset); - } - - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - - return SUCCESS; + * @brief power down sleep force configure + * + * @param defaultLvCfg: power down sleep default level configuration + * @param pdsSleepCnt: power down sleep time count + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION PDS_Default_Level_Config(PDS_DEFAULT_LV_CFG_Type *defaultLvCfg, uint32_t pdsSleepCnt) { + PDS_Force_Config((PDS_CTL2_Type *)&(defaultLvCfg->pdsCtl2), (PDS_CTL3_Type *)&(defaultLvCfg->pdsCtl3)); + PDS_App_Enable((PDS_CTL_Type *)&(defaultLvCfg->pdsCtl), (PDS_CTL4_Type *)&(defaultLvCfg->pdsCtl4), pdsSleepCnt); + + return SUCCESS; } /****************************************************************************/ /** - * @brief power down sleep int mask - * - * @param intType: PDS int type - * @param intMask: MASK or UNMASK - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_IntMask(PDS_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t offset = 0; - uint32_t tmpVal = 0; - - if (intType > PDS_INT_PLL_DONE) { - return ERROR; - } - - switch (intType) { - case PDS_INT_WAKEUP: - offset = 8; - break; - - case PDS_INT_RF_DONE: - offset = 10; - break; - - case PDS_INT_PLL_DONE: - offset = 11; - break; - - case PDS_INT_PDS_SLEEP_CNT: - case PDS_INT_HBN_IRQ_OUT0: - case PDS_INT_HBN_IRQ_OUT1: - case PDS_INT_GPIO_IRQ: - case PDS_INT_IRRX: - case PDS_INT_BLE_SLP_IRQ: - case PDS_INT_USB_WKUP: - case PDS_INT_KYS_QDEC: - case PDS_INT_MAX: - default: - return ERROR; - } - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - - if (intMask != UNMASK) { - tmpVal = tmpVal | (1 << offset); - } else { - tmpVal = tmpVal & ~(1 << offset); - } - - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - - return SUCCESS; -} + * @brief power down sleep int enable + * + * @param intType: PDS int type + * @param enable: ENABLE or DISABLE + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_IntEn(PDS_INT_Type intType, BL_Fun_Type enable) { + uint32_t offset = 0; + uint32_t tmpVal = 0; + + if ((intType < PDS_INT_PDS_SLEEP_CNT) || (intType > PDS_INT_KYS_QDEC)) { + return ERROR; + } -/****************************************************************************/ /** - * @brief get power down sleep int status - * - * @param intType: PDS int type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type PDS_Get_IntStatus(PDS_INT_Type intType) -{ - uint32_t offset = 0; + switch (intType) { + case PDS_INT_WAKEUP: + case PDS_INT_RF_DONE: + case PDS_INT_PLL_DONE: + return ERROR; - switch (intType) { - case PDS_INT_WAKEUP: - offset = 0; - break; + case PDS_INT_PDS_SLEEP_CNT: + offset = 16; + break; - case PDS_INT_RF_DONE: - offset = 2; - break; + case PDS_INT_HBN_IRQ_OUT0: + offset = 17; + break; - case PDS_INT_PLL_DONE: - offset = 3; - break; + case PDS_INT_HBN_IRQ_OUT1: + offset = 18; + break; - case PDS_INT_PDS_SLEEP_CNT: - offset = 24; - break; + case PDS_INT_GPIO_IRQ: + offset = 19; + break; - case PDS_INT_HBN_IRQ_OUT0: - offset = 25; - break; + case PDS_INT_IRRX: + offset = 20; + break; - case PDS_INT_HBN_IRQ_OUT1: - offset = 26; - break; + case PDS_INT_BLE_SLP_IRQ: + offset = 21; + break; - case PDS_INT_GPIO_IRQ: - offset = 27; - break; + case PDS_INT_USB_WKUP: + offset = 22; + break; - case PDS_INT_IRRX: - offset = 28; - break; + case PDS_INT_KYS_QDEC: + offset = 23; + break; - case PDS_INT_BLE_SLP_IRQ: - offset = 29; - break; + case PDS_INT_MAX: + break; - case PDS_INT_USB_WKUP: - offset = 30; - break; + default: + break; + } - case PDS_INT_KYS_QDEC: - offset = 31; - break; + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - case PDS_INT_MAX: - break; + if (enable) { + tmpVal = tmpVal | (1 << offset); + } else { + tmpVal = tmpVal & ~(1 << offset); + } - default: - break; - } + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - return (BL_RD_REG(PDS_BASE, PDS_INT) & (1 << offset)) ? SET : RESET; + return SUCCESS; } /****************************************************************************/ /** - * @brief clear power down sleep int status - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_IntClear(void) -{ - uint32_t tmpVal = 0; + * @brief power down sleep int mask + * + * @param intType: PDS int type + * @param intMask: MASK or UNMASK + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_IntMask(PDS_INT_Type intType, BL_Mask_Type intMask) { + uint32_t offset = 0; + uint32_t tmpVal = 0; + + if (intType > PDS_INT_PLL_DONE) { + return ERROR; + } + + switch (intType) { + case PDS_INT_WAKEUP: + offset = 8; + break; + + case PDS_INT_RF_DONE: + offset = 10; + break; + + case PDS_INT_PLL_DONE: + offset = 11; + break; + + case PDS_INT_PDS_SLEEP_CNT: + case PDS_INT_HBN_IRQ_OUT0: + case PDS_INT_HBN_IRQ_OUT1: + case PDS_INT_GPIO_IRQ: + case PDS_INT_IRRX: + case PDS_INT_BLE_SLP_IRQ: + case PDS_INT_USB_WKUP: + case PDS_INT_KYS_QDEC: + case PDS_INT_MAX: + default: + return ERROR; + } - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + if (intMask != UNMASK) { + tmpVal = tmpVal | (1 << offset); + } else { + tmpVal = tmpVal & ~(1 << offset); + } - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief get power down sleep PLL status - * - * @param None - * - * @return PDS PLL status - * -*******************************************************************************/ -PDS_PLL_STS_Type PDS_Get_PdsPllStstus(void) -{ - return (PDS_PLL_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_PLL_STATE); + * @brief get power down sleep int status + * + * @param intType: PDS int type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type PDS_Get_IntStatus(PDS_INT_Type intType) { + uint32_t offset = 0; + + switch (intType) { + case PDS_INT_WAKEUP: + offset = 0; + break; + + case PDS_INT_RF_DONE: + offset = 2; + break; + + case PDS_INT_PLL_DONE: + offset = 3; + break; + + case PDS_INT_PDS_SLEEP_CNT: + offset = 24; + break; + + case PDS_INT_HBN_IRQ_OUT0: + offset = 25; + break; + + case PDS_INT_HBN_IRQ_OUT1: + offset = 26; + break; + + case PDS_INT_GPIO_IRQ: + offset = 27; + break; + + case PDS_INT_IRRX: + offset = 28; + break; + + case PDS_INT_BLE_SLP_IRQ: + offset = 29; + break; + + case PDS_INT_USB_WKUP: + offset = 30; + break; + + case PDS_INT_KYS_QDEC: + offset = 31; + break; + + case PDS_INT_MAX: + break; + + default: + break; + } + + return (BL_RD_REG(PDS_BASE, PDS_INT) & (1 << offset)) ? SET : RESET; } /****************************************************************************/ /** - * @brief get power down sleep RF status - * - * @param None - * - * @return PDS RF status - * -*******************************************************************************/ -PDS_RF_STS_Type PDS_Get_PdsRfStstus(void) -{ - return (PDS_RF_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_RF_STATE); + * @brief clear power down sleep int status + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_IntClear(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CR_PDS_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief get power down sleep status - * - * @param None - * - * @return PDS status - * -*******************************************************************************/ -PDS_STS_Type PDS_Get_PdsStstus(void) -{ - return (PDS_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_STATE); -} + * @brief get power down sleep PLL status + * + * @param None + * + * @return PDS PLL status + * + *******************************************************************************/ +PDS_PLL_STS_Type PDS_Get_PdsPllStstus(void) { return (PDS_PLL_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_PLL_STATE); } /****************************************************************************/ /** - * @brief power down sleep clear reset event - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_Clear_Reset_Event(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); - BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); - - return SUCCESS; -} + * @brief get power down sleep RF status + * + * @param None + * + * @return PDS RF status + * + *******************************************************************************/ +PDS_RF_STS_Type PDS_Get_PdsRfStstus(void) { return (PDS_RF_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_RF_STATE); } /****************************************************************************/ /** - * @brief get power down sleep reset event - * - * @param event: power down sleep reset event - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type PDS_Get_Reset_Event(PDS_RST_EVENT_Type event) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, PDS_RESET_EVENT); + * @brief get power down sleep status + * + * @param None + * + * @return PDS status + * + *******************************************************************************/ +PDS_STS_Type PDS_Get_PdsStstus(void) { return (PDS_STS_Type)BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_STAT), PDS_RO_PDS_STATE); } - return (tmpVal & (1 << event)) ? SET : RESET; +/****************************************************************************/ /** + * @brief power down sleep clear reset event + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_Clear_Reset_Event(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLR_RESET_EVENT); + BL_WR_REG(PDS_BASE, PDS_INT, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set power down sleep VDDCORE gpio interrupt config - * - * @param src: PDS VDDCORE src pin num - * @param mode: PDS VDDCORE src pin interrupt type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_Set_Vddcore_GPIO_IntCfg(PDS_VDDCORE_GPIO_SRC_Type src, PDS_AON_GPIO_INT_Trigger_Type mode) -{ - uint32_t tmpVal = 0; - - CHECK_PARAM(IS_PDS_VDDCORE_GPIO_SRC_TYPE(src)); - CHECK_PARAM(IS_PDS_AON_GPIO_INT_Trigger_TYPE(mode)); - - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_GPIO_INT_SELECT, src); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_GPIO_INT_MODE, mode); - BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); - - return SUCCESS; + * @brief get power down sleep reset event + * + * @param event: power down sleep reset event + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type PDS_Get_Reset_Event(PDS_RST_EVENT_Type event) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_INT); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, PDS_RESET_EVENT); + + return (tmpVal & (1 << event)) ? SET : RESET; } /****************************************************************************/ /** - * @brief set power down sleep VDDCORE gpio interrupt mask - * - * @param intMask: None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_Set_Vddcore_GPIO_IntMask(BL_Mask_Type intMask) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); - - if (intMask != UNMASK) { - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_GPIO_INT_MASK); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_MASK); - } - - BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); - - return SUCCESS; + * @brief set power down sleep VDDCORE gpio interrupt config + * + * @param src: PDS VDDCORE src pin num + * @param mode: PDS VDDCORE src pin interrupt type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_Set_Vddcore_GPIO_IntCfg(PDS_VDDCORE_GPIO_SRC_Type src, PDS_AON_GPIO_INT_Trigger_Type mode) { + uint32_t tmpVal = 0; + + CHECK_PARAM(IS_PDS_VDDCORE_GPIO_SRC_TYPE(src)); + CHECK_PARAM(IS_PDS_AON_GPIO_INT_Trigger_TYPE(mode)); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_GPIO_INT_SELECT, src); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_GPIO_INT_MODE, mode); + BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set power down sleep VDDCORE gpio interrupt mask - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Sts_Type PDS_Get_Vddcore_GPIO_IntStatus(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_GPIO_INT), PDS_GPIO_INT_STAT) ? SET : RESET; + * @brief set power down sleep VDDCORE gpio interrupt mask + * + * @param intMask: None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_Set_Vddcore_GPIO_IntMask(BL_Mask_Type intMask) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); + + if (intMask != UNMASK) { + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_GPIO_INT_MASK); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_MASK); + } + + BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief set power down sleep VDDCORE gpio interrupt mask - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_Set_Vddcore_GPIO_IntClear(void) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); - - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + * @brief set power down sleep VDDCORE gpio interrupt mask + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Sts_Type PDS_Get_Vddcore_GPIO_IntStatus(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(PDS_BASE, PDS_GPIO_INT), PDS_GPIO_INT_STAT) ? SET : RESET; } - tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); - BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); - - return SUCCESS; +/****************************************************************************/ /** + * @brief set power down sleep VDDCORE gpio interrupt mask + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_Set_Vddcore_GPIO_IntClear(void) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + + tmpVal = BL_RD_REG(PDS_BASE, PDS_GPIO_INT); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_GPIO_INT_CLR); + BL_WR_REG(PDS_BASE, PDS_GPIO_INT, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Install PDS interrupt callback function - * - * @param intType: PDS int type - * @param cbFun: cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_Int_Callback_Install(PDS_INT_Type intType, intCallback_Type *cbFun) -{ - pdsIntCbfArra[intType][0] = cbFun; - - return SUCCESS; + * @brief Install PDS interrupt callback function + * + * @param intType: PDS int type + * @param cbFun: cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_Int_Callback_Install(PDS_INT_Type intType, intCallback_Type *cbFun) { + pdsIntCbfArra[intType][0] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief Trim RC32M - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Trim RC32M + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Trim_RC32M(void) -{ - Efuse_Ana_RC32M_Trim_Type trim; - int32_t tmpVal = 0; - - EF_Ctrl_Read_RC32M_Trim(&trim); - - if (trim.trimRc32mExtCodeEn) { - if (trim.trimRc32mCodeFrExtParity == EF_Ctrl_Get_Trim_Parity(trim.trimRc32mCodeFrExt, 8)) { - tmpVal = BL_RD_REG(PDS_BASE, PDS_RC32M_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_RC32M_CODE_FR_EXT, trim.trimRc32mCodeFrExt); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_RC32M_EXT_CODE_EN); - BL_WR_REG(PDS_BASE, PDS_RC32M_CTRL0, tmpVal); - BL702_Delay_US(2); - return SUCCESS; - } +BL_Err_Type ATTR_CLOCK_SECTION PDS_Trim_RC32M(void) { + Efuse_Ana_RC32M_Trim_Type trim; + int32_t tmpVal = 0; + + EF_Ctrl_Read_RC32M_Trim(&trim); + + if (trim.trimRc32mExtCodeEn) { + if (trim.trimRc32mCodeFrExtParity == EF_Ctrl_Get_Trim_Parity(trim.trimRc32mCodeFrExt, 8)) { + tmpVal = BL_RD_REG(PDS_BASE, PDS_RC32M_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_RC32M_CODE_FR_EXT, trim.trimRc32mCodeFrExt); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_RC32M_EXT_CODE_EN); + BL_WR_REG(PDS_BASE, PDS_RC32M_CTRL0, tmpVal); + BL702_Delay_US(2); + return SUCCESS; } + } - return ERROR; + return ERROR; } #endif /****************************************************************************/ /** - * @brief Select RC32M as PLL ref source - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Select RC32M as PLL ref source + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_RC32M_As_PLL_Ref(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_RC32M_As_PLL_Ref(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_XTAL_RC32M_SEL); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_XTAL_RC32M_SEL); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Select XTAL as PLL ref source - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Select XTAL as PLL ref source + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_XTAL_As_PLL_Ref(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_XTAL_As_PLL_Ref(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_XTAL_RC32M_SEL); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_XTAL_RC32M_SEL); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Power on PLL - * - * @param xtalType: xtal type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power on PLL + * + * @param xtalType: xtal type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType) -{ - uint32_t tmpVal = 0; - - /* Check parameter*/ - CHECK_PARAM(IS_PDS_PLL_XTAL_TYPE(xtalType)); - - /**************************/ - /* select PLL XTAL source */ - /**************************/ - - if ((xtalType == PDS_PLL_XTAL_RC32M) || (xtalType == PDS_PLL_XTAL_NONE)) { - PDS_Trim_RC32M(); - PDS_Select_RC32M_As_PLL_Ref(); - } else { - PDS_Select_XTAL_As_PLL_Ref(); - } - - /*******************************************/ - /* PLL power down first, not indispensable */ - /*******************************************/ - /* power off PLL first, this step is not indispensable */ - PDS_Power_Off_PLL(); - - /********************/ - /* PLL param config */ - /********************/ - - /* clkpll_icp_1u */ - /* clkpll_icp_5u */ - /* clkpll_int_frac_sw */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_CP); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_ICP_1U, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_ICP_5U, 2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_INT_FRAC_SW, 0); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_CP, tmpVal); - - /* clkpll_c3 */ - /* clkpll_cz */ - /* clkpll_rz */ - /* clkpll_r4 */ - /* clkpll_r4_short */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_RZ); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_C3, 3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_CZ, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RZ, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_R4_SHORT, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_R4, 2); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_RZ, tmpVal); - - /* clkpll_refdiv_ratio */ - /* clkpll_postdiv */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 0x14); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_REFDIV_RATIO, 2); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - - /* clkpll_sdmin */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_SDM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SDMIN, 0x3C0000); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_SDM, tmpVal); - - /* clkpll_sel_fb_clk */ - /* clkpll_sel_sample_clk can be 0/1, default is 1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_FBDV); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SEL_FB_CLK, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SEL_SAMPLE_CLK, 1); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_FBDV, tmpVal); - - /*************************/ - /* PLL power up sequence */ - /*************************/ - - /* pu_clkpll_sfreg=1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_PU_CLKPLL_SFREG); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - BL702_Delay_US(5); - - /* pu_clkpll=1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_PU_CLKPLL); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - /* clkpll_pu_cp=1 */ - /* clkpll_pu_pfd=1 */ - /* clkpll_pu_fbdv=1 */ - /* clkpll_pu_postdiv=1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_CP); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_PFD); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_FBDV); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_POSTDIV); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - BL702_Delay_US(5); - - /* clkpll_sdm_reset=1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_SDM_RESET); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - BL702_Delay_US(1); - /* clkpll_reset_fbdv=1 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_RESET_FBDV); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - BL702_Delay_US(2); - /* clkpll_reset_fbdv=0 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_RESET_FBDV); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - BL702_Delay_US(1); - /* clkpll_sdm_reset=0 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_SDM_RESET); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - return SUCCESS; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType) { + uint32_t tmpVal = 0; + + /* Check parameter*/ + CHECK_PARAM(IS_PDS_PLL_XTAL_TYPE(xtalType)); + + /**************************/ + /* select PLL XTAL source */ + /**************************/ + + if ((xtalType == PDS_PLL_XTAL_RC32M) || (xtalType == PDS_PLL_XTAL_NONE)) { + PDS_Trim_RC32M(); + PDS_Select_RC32M_As_PLL_Ref(); + } else { + PDS_Select_XTAL_As_PLL_Ref(); + } + + /*******************************************/ + /* PLL power down first, not indispensable */ + /*******************************************/ + /* power off PLL first, this step is not indispensable */ + PDS_Power_Off_PLL(); + + /********************/ + /* PLL param config */ + /********************/ + + /* clkpll_icp_1u */ + /* clkpll_icp_5u */ + /* clkpll_int_frac_sw */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_CP); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_ICP_1U, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_ICP_5U, 2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_INT_FRAC_SW, 0); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_CP, tmpVal); + + /* clkpll_c3 */ + /* clkpll_cz */ + /* clkpll_rz */ + /* clkpll_r4 */ + /* clkpll_r4_short */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_RZ); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_C3, 3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_CZ, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RZ, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_R4_SHORT, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_R4, 2); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_RZ, tmpVal); + + /* clkpll_refdiv_ratio */ + /* clkpll_postdiv */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 0x14); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_REFDIV_RATIO, 2); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + + /* clkpll_sdmin */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_SDM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SDMIN, 0x3C0000); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_SDM, tmpVal); + + /* clkpll_sel_fb_clk */ + /* clkpll_sel_sample_clk can be 0/1, default is 1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_FBDV); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SEL_FB_CLK, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SEL_SAMPLE_CLK, 1); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_FBDV, tmpVal); + + /*************************/ + /* PLL power up sequence */ + /*************************/ + + /* pu_clkpll_sfreg=1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_PU_CLKPLL_SFREG); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + BL702_Delay_US(5); + + /* pu_clkpll=1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_PU_CLKPLL); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + /* clkpll_pu_cp=1 */ + /* clkpll_pu_pfd=1 */ + /* clkpll_pu_fbdv=1 */ + /* clkpll_pu_postdiv=1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_CP); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_PFD); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_FBDV); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_PU_POSTDIV); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + BL702_Delay_US(5); + + /* clkpll_sdm_reset=1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_SDM_RESET); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + BL702_Delay_US(1); + /* clkpll_reset_fbdv=1 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_SET_REG_BIT(tmpVal, PDS_CLKPLL_RESET_FBDV); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + BL702_Delay_US(2); + /* clkpll_reset_fbdv=0 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_RESET_FBDV); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + BL702_Delay_US(1); + /* clkpll_sdm_reset=0 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_SDM_RESET); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + return SUCCESS; } #endif /** PLL output config **/ @@ -901,451 +870,420 @@ BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType) */ /****************************************************************************/ /** - * @brief Enable all PLL clock - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Enable all PLL clock + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_All_Clks(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_All_Clks(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); - tmpVal |= 0x1FF; - BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); + tmpVal |= 0x1FF; + BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Disable all PLL clock - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Disable all PLL clock + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_All_Clks(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_All_Clks(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); - tmpVal &= (~0x1FF); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); + tmpVal &= (~0x1FF); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Enable PLL clock - * - * @param pllClk: PLL clock type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Enable PLL clock + * + * @param pllClk: PLL clock type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_Clk(PDS_PLL_CLK_Type pllClk) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_Clk(PDS_PLL_CLK_Type pllClk) { + uint32_t tmpVal = 0; - /* Check parameter*/ - CHECK_PARAM(IS_PDS_PLL_CLK_TYPE(pllClk)); + /* Check parameter*/ + CHECK_PARAM(IS_PDS_PLL_CLK_TYPE(pllClk)); - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); - tmpVal |= (1 << pllClk); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); + tmpVal |= (1 << pllClk); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Disable PLL clock - * - * @param pllClk: PLL clock type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Disable PLL clock + * + * @param pllClk: PLL clock type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_Clk(PDS_PLL_CLK_Type pllClk) -{ - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_Clk(PDS_PLL_CLK_Type pllClk) { + uint32_t tmpVal = 0; - /* Check parameter*/ - CHECK_PARAM(IS_PDS_PLL_CLK_TYPE(pllClk)); + /* Check parameter*/ + CHECK_PARAM(IS_PDS_PLL_CLK_TYPE(pllClk)); - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); - tmpVal &= (~(1 << pllClk)); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN); + tmpVal &= (~(1 << pllClk)); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_OUTPUT_EN, tmpVal); - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Power off PLL - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Power off PLL + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_Off_PLL(void) -{ - uint32_t tmpVal = 0; - - /* pu_clkpll_sfreg=0 */ - /* pu_clkpll=0 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_PU_CLKPLL_SFREG); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_PU_CLKPLL); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - /* clkpll_pu_cp=0 */ - /* clkpll_pu_pfd=0 */ - /* clkpll_pu_fbdv=0 */ - /* clkpll_pu_postdiv=0 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_CP); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_PFD); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_FBDV); - tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_POSTDIV); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - - return SUCCESS; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_Off_PLL(void) { + uint32_t tmpVal = 0; + + /* pu_clkpll_sfreg=0 */ + /* pu_clkpll=0 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_PU_CLKPLL_SFREG); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_PU_CLKPLL); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + /* clkpll_pu_cp=0 */ + /* clkpll_pu_pfd=0 */ + /* clkpll_pu_fbdv=0 */ + /* clkpll_pu_postdiv=0 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_CP); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_PFD); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_FBDV); + tmpVal = BL_CLR_REG_BIT(tmpVal, PDS_CLKPLL_PU_POSTDIV); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set Audio PLL clock - * - * @param audioPLLFreq: Audio PLL sel frequency , have two vaild input 12.288 or 11.289 MHZ - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set Audio PLL clock + * + * @param audioPLLFreq: Audio PLL sel frequency , have two vaild input 12.288 or 11.289 MHZ + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_CLOCK_SECTION PDS_Set_Audio_PLL_Freq(PDS_AUDIO_PLL_Type audioPLLFreq) -{ - uint32_t sdmin_table[] = { 0x374BC6, 0x32CCED, 0x32CCED, 0x6E978D, 0x6C0000 }; - uint32_t tmpVal = 0; +BL_Err_Type ATTR_CLOCK_SECTION PDS_Set_Audio_PLL_Freq(PDS_AUDIO_PLL_Type audioPLLFreq) { + uint32_t sdmin_table[] = {0x374BC6, 0x32CCED, 0x32CCED, 0x6E978D, 0x6C0000}; + uint32_t tmpVal = 0; - CHECK_PARAM(IS_PDS_AUDIO_PLL_TYPE(audioPLLFreq)); + CHECK_PARAM(IS_PDS_AUDIO_PLL_TYPE(audioPLLFreq)); - /*set PDS_CLKPLL_REFDIV_RATIO as 0x2 */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_REFDIV_RATIO, 0x2); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + /*set PDS_CLKPLL_REFDIV_RATIO as 0x2 */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_REFDIV_RATIO, 0x2); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - /*set clkpll_sdmin as sdmin*/ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_SDM); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SDMIN, (uint32_t)sdmin_table[audioPLLFreq % (sizeof(sdmin_table) / sizeof(sdmin_table[0]))]); + /*set clkpll_sdmin as sdmin*/ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_SDM); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_SDMIN, (uint32_t)sdmin_table[audioPLLFreq % (sizeof(sdmin_table) / sizeof(sdmin_table[0]))]); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_SDM, tmpVal); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_SDM, tmpVal); - /*reset pll */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); + /*reset pll */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_PU_RST_CLKPLL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_PU_CLKPLL_SFREG, 1); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_PU_CLKPLL_SFREG, 1); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - BL702_Delay_MS(10); + BL702_Delay_MS(10); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_PU_CLKPLL, 1); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_PU_CLKPLL, 1); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RESET_FBDV, 1); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RESET_FBDV, 1); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - BL702_Delay_MS(10); + BL702_Delay_MS(10); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RESET_FBDV, 0); - BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_RESET_FBDV, 0); + BL_WR_REG(PDS_BASE, PDS_PU_RST_CLKPLL, tmpVal); - /*set div for audio pll */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + /*set div for audio pll */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - if (audioPLLFreq != AUDIO_PLL_5644800_HZ) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 36); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 72); - } + if (audioPLLFreq != AUDIO_PLL_5644800_HZ) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 36); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_POSTDIV, 72); + } - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief PDS software reset - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief PDS software reset + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Reset(void) -{ - uint32_t tmpVal = 0; +void ATTR_TCM_SECTION PDS_Reset(void) { + uint32_t tmpVal = 0; - tmpVal = *(uint32_t *)0x40000010; - tmpVal = tmpVal | (1 << 14); - *(uint32_t *)0x40000010 = tmpVal; + tmpVal = *(uint32_t *)0x40000010; + tmpVal = tmpVal | (1 << 14); + *(uint32_t *)0x40000010 = tmpVal; - tmpVal = *(uint32_t *)0x40000010; - tmpVal = tmpVal & ~(1 << 14); - *(uint32_t *)0x40000010 = tmpVal; + tmpVal = *(uint32_t *)0x40000010; + tmpVal = tmpVal & ~(1 << 14); + *(uint32_t *)0x40000010 = tmpVal; } #endif /****************************************************************************/ /** - * @brief Enable power down sleep - * - * @param cfg: power down sleep configuration 1 - * @param pdsSleepCnt: power down sleep count cycle - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Enable power down sleep + * + * @param cfg: power down sleep configuration 1 + * @param pdsSleepCnt: power down sleep count cycle + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Enable(PDS_CFG_Type *cfg, uint32_t pdsSleepCnt) -{ - uint32_t *p = (uint32_t *)cfg; +void ATTR_TCM_SECTION PDS_Enable(PDS_CFG_Type *cfg, uint32_t pdsSleepCnt) { + uint32_t *p = (uint32_t *)cfg; - if (pdsSleepCnt - PDS_WARMUP_CNT <= 0) { - return; - } + if (pdsSleepCnt - PDS_WARMUP_CNT <= 0) { + return; + } - BL_WR_REG(PDS_BASE, PDS_TIME1, pdsSleepCnt - PDS_WARMUP_CNT); + BL_WR_REG(PDS_BASE, PDS_TIME1, pdsSleepCnt - PDS_WARMUP_CNT); - /* Set PDS control register */ - BL_WR_REG(PDS_BASE, PDS_CTL, *p); + /* Set PDS control register */ + BL_WR_REG(PDS_BASE, PDS_CTL, *p); } #endif /****************************************************************************/ /** - * @brief PDS Auto mode wake up counter config - * - * @param sleepDuration: sleep time, total pds = sleep_duration + max_warmup_cnt (32K clock cycles), - * recommend maxWarmCnt*N+2 - * - * @return None - * -*******************************************************************************/ + * @brief PDS Auto mode wake up counter config + * + * @param sleepDuration: sleep time, total pds = sleep_duration + max_warmup_cnt (32K clock cycles), + * recommend maxWarmCnt*N+2 + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Auto_Time_Config(uint32_t sleepDuration) -{ - /* PDS_TIME1 */ - BL_WR_REG(PDS_BASE, PDS_TIME1, sleepDuration); +void ATTR_TCM_SECTION PDS_Auto_Time_Config(uint32_t sleepDuration) { + /* PDS_TIME1 */ + BL_WR_REG(PDS_BASE, PDS_TIME1, sleepDuration); } #endif /****************************************************************************/ /** - * @brief PDS Auto mode config and enable - * - * @param powerCfg: PDS Auto mode power domain config - * @param normalCfg: PDS Auto mode power normal config - * @param enable: PDS Auto mode Enable or Disable - * - * @return None - * -*******************************************************************************/ + * @brief PDS Auto mode config and enable + * + * @param powerCfg: PDS Auto mode power domain config + * @param normalCfg: PDS Auto mode power normal config + * @param enable: PDS Auto mode Enable or Disable + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Auto_Enable(PDS_AUTO_POWER_DOWN_CFG_Type *powerCfg, PDS_AUTO_NORMAL_CFG_Type *normalCfg, BL_Fun_Type enable) -{ - uint32_t pdsCtl = 0; - - CHECK_PARAM(IS_PDS_LDO_VOLTAGE_TYPE(normalCfg->vddcoreVol)); - - /* power config */ - pdsCtl |= (powerCfg->mbgPower << 31) | - (powerCfg->ldo18rfPower << 30) | - (powerCfg->sfregPower << 29) | - (powerCfg->pllPower << 28) | - (powerCfg->cpu0Power << 19) | - (powerCfg->rc32mPower << 17) | - (powerCfg->xtalPower << 14) | - (powerCfg->allPower << 13) | - (powerCfg->isoPower << 11) | - (powerCfg->bzPower << 10) | - (powerCfg->sramDisStanby << 9) | - (powerCfg->cgPower << 8) | - (powerCfg->cpu1Power << 7) | - (powerCfg->usbPower << 3); - pdsCtl = BL_SET_REG_BITS_VAL(pdsCtl, PDS_CR_PDS_LDO_VOL, normalCfg->vddcoreVol); - pdsCtl |= (normalCfg->vddcoreVolEn << 18) | - (normalCfg->cpu0NotNeedWFI << 21) | - (normalCfg->cpu1NotNeedWFI << 20) | - (normalCfg->busReset << 16) | - (normalCfg->disIrqWakeUp << 15) | - (normalCfg->powerOffXtalForever << 2) | - (normalCfg->sleepForever << 1); - BL_WR_REG(PDS_BASE, PDS_CTL, pdsCtl); - - pdsCtl = BL_RD_REG(PDS_BASE, PDS_CTL); - - if (enable) { - pdsCtl |= (1 << 0); - } else { - pdsCtl &= ~(1 << 0); - } +void ATTR_TCM_SECTION PDS_Auto_Enable(PDS_AUTO_POWER_DOWN_CFG_Type *powerCfg, PDS_AUTO_NORMAL_CFG_Type *normalCfg, BL_Fun_Type enable) { + uint32_t pdsCtl = 0; + + CHECK_PARAM(IS_PDS_LDO_VOLTAGE_TYPE(normalCfg->vddcoreVol)); + + /* power config */ + pdsCtl |= (powerCfg->mbgPower << 31) | (powerCfg->ldo18rfPower << 30) | (powerCfg->sfregPower << 29) | (powerCfg->pllPower << 28) | (powerCfg->cpu0Power << 19) | (powerCfg->rc32mPower << 17) | + (powerCfg->xtalPower << 14) | (powerCfg->allPower << 13) | (powerCfg->isoPower << 11) | (powerCfg->bzPower << 10) | (powerCfg->sramDisStanby << 9) | (powerCfg->cgPower << 8) | + (powerCfg->cpu1Power << 7) | (powerCfg->usbPower << 3); + pdsCtl = BL_SET_REG_BITS_VAL(pdsCtl, PDS_CR_PDS_LDO_VOL, normalCfg->vddcoreVol); + pdsCtl |= (normalCfg->vddcoreVolEn << 18) | (normalCfg->cpu0NotNeedWFI << 21) | (normalCfg->cpu1NotNeedWFI << 20) | (normalCfg->busReset << 16) | (normalCfg->disIrqWakeUp << 15) | + (normalCfg->powerOffXtalForever << 2) | (normalCfg->sleepForever << 1); + BL_WR_REG(PDS_BASE, PDS_CTL, pdsCtl); + + pdsCtl = BL_RD_REG(PDS_BASE, PDS_CTL); - BL_WR_REG(PDS_BASE, PDS_CTL, pdsCtl); + if (enable) { + pdsCtl |= (1 << 0); + } else { + pdsCtl &= ~(1 << 0); + } + + BL_WR_REG(PDS_BASE, PDS_CTL, pdsCtl); } #endif /****************************************************************************/ /** - * @brief PDS force turn off XXX domain - * - * @param domain: PDS domain - * - * @return None - * -*******************************************************************************/ + * @brief PDS force turn off XXX domain + * + * @param domain: PDS domain + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Manual_Force_Turn_Off(PDS_FORCE_Type domain) -{ - uint32_t tmpVal = 0; - - /* memory sleep */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal |= 1 << (domain + PDS_FORCE_MEM_STBY_OFFSET); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* gate clock */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal |= 1 << (domain + PDS_FORCE_GATE_CLK_OFFSET); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* pds reset */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal |= 1 << (domain + PDS_FORCE_PDS_RST_OFFSET); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* isolation on */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal |= 1 << (domain + PDS_FORCE_ISO_EN_OFFSET); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* power off */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal |= 1 << (domain + PDS_FORCE_PWR_OFF_OFFSET); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); +void ATTR_TCM_SECTION PDS_Manual_Force_Turn_Off(PDS_FORCE_Type domain) { + uint32_t tmpVal = 0; + + /* memory sleep */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal |= 1 << (domain + PDS_FORCE_MEM_STBY_OFFSET); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* gate clock */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal |= 1 << (domain + PDS_FORCE_GATE_CLK_OFFSET); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* pds reset */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal |= 1 << (domain + PDS_FORCE_PDS_RST_OFFSET); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* isolation on */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal |= 1 << (domain + PDS_FORCE_ISO_EN_OFFSET); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* power off */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal |= 1 << (domain + PDS_FORCE_PWR_OFF_OFFSET); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); } #endif /****************************************************************************/ /** - * @brief PDS force turn on XXX domain - * - * @param domain: PDS domain - * - * @return None - * -*******************************************************************************/ + * @brief PDS force turn on XXX domain + * + * @param domain: PDS domain + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION PDS_Manual_Force_Turn_On(PDS_FORCE_Type domain) -{ - uint32_t tmpVal = 0; - - /* power on */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal &= ~(1 << (domain + PDS_FORCE_PWR_OFF_OFFSET)); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* isolation off */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal &= ~(1 << (domain + PDS_FORCE_ISO_EN_OFFSET)); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* pds de_reset */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal &= ~(1 << (domain + PDS_FORCE_PDS_RST_OFFSET)); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* memory active */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal &= ~(1 << (domain + PDS_FORCE_MEM_STBY_OFFSET)); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); - - /* clock on */ - tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); - tmpVal &= ~(1 << (domain + PDS_FORCE_GATE_CLK_OFFSET)); - BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); +void ATTR_TCM_SECTION PDS_Manual_Force_Turn_On(PDS_FORCE_Type domain) { + uint32_t tmpVal = 0; + + /* power on */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal &= ~(1 << (domain + PDS_FORCE_PWR_OFF_OFFSET)); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* isolation off */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal &= ~(1 << (domain + PDS_FORCE_ISO_EN_OFFSET)); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* pds de_reset */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal &= ~(1 << (domain + PDS_FORCE_PDS_RST_OFFSET)); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* memory active */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal &= ~(1 << (domain + PDS_FORCE_MEM_STBY_OFFSET)); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); + + /* clock on */ + tmpVal = BL_RD_REG(PDS_BASE, PDS_CTL2); + tmpVal &= ~(1 << (domain + PDS_FORCE_GATE_CLK_OFFSET)); + BL_WR_REG(PDS_BASE, PDS_CTL2, tmpVal); } #endif /****************************************************************************/ /** - * @brief Power down sleep wake up interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ -void PDS_WAKEUP_IRQHandler(void) -{ - for (PDS_INT_Type intType = PDS_INT_WAKEUP; intType < PDS_INT_MAX; intType++) { - if (PDS_Get_IntStatus(intType) && (pdsIntCbfArra[intType][0] != NULL)) { - pdsIntCbfArra[intType][0](); - } + * @brief Power down sleep wake up interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ +void PDS_WAKEUP_IRQHandler(void) { + for (PDS_INT_Type intType = PDS_INT_WAKEUP; intType < PDS_INT_MAX; intType++) { + if (PDS_Get_IntStatus(intType) && (pdsIntCbfArra[intType][0] != NULL)) { + pdsIntCbfArra[intType][0](); } - PDS_Set_Vddcore_GPIO_IntClear(); - PDS_IntClear(); + } + PDS_Set_Vddcore_GPIO_IntClear(); + PDS_IntClear(); } /****************************************************************************/ /** - * @brief PDS wakeup IRQHandler install - * - * @param None - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type PDS_WAKEUP_IRQHandler_Install(void) -{ - Interrupt_Handler_Register(PDS_WAKEUP_IRQn, PDS_WAKEUP_IRQHandler); - return SUCCESS; + * @brief PDS wakeup IRQHandler install + * + * @param None + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type PDS_WAKEUP_IRQHandler_Install(void) { + Interrupt_Handler_Register(PDS_WAKEUP_IRQn, PDS_WAKEUP_IRQHandler); + return SUCCESS; } /****************************************************************************/ /** - * @brief - * - * @param - * - * @return - * -*******************************************************************************/ -BL_Err_Type PDS_Set_Clkpll_Top_Ctrl(uint8_t vg11Sel) -{ - uint32_t tmpVal = 0; - - tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); - //clkpll_vg11_sel - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_VG11_SEL, vg11Sel); - BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); - - return SUCCESS; + * @brief + * + * @param + * + * @return + * + *******************************************************************************/ +BL_Err_Type PDS_Set_Clkpll_Top_Ctrl(uint8_t vg11Sel) { + uint32_t tmpVal = 0; + + tmpVal = BL_RD_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL); + // clkpll_vg11_sel + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, PDS_CLKPLL_VG11_SEL, vg11Sel); + BL_WR_REG(PDS_BASE, PDS_CLKPLL_TOP_CTRL, tmpVal); + + return SUCCESS; } /*@} end of group PDS_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c index a56c2d105..a35fef2bd 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_psram.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_psram.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_psram.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_psram.h" #include "bl702_l1c.h" @@ -86,674 +86,656 @@ */ /****************************************************************************/ /** - * @brief Init serial psram control interface - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param cmdsCfg: Serial Serial Flash controller configuration pointer - * @param sfCtrlPsramCfg: Serial psram controller configuration pointer - * - * @return None - * -*******************************************************************************/ -//#ifndef BFLB_USE_ROM_DRIVER + * @brief Init serial psram control interface + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param cmdsCfg: Serial Serial Flash controller configuration pointer + * @param sfCtrlPsramCfg: Serial psram controller configuration pointer + * + * @return None + * + *******************************************************************************/ +// #ifndef BFLB_USE_ROM_DRIVER //__WEAK -void ATTR_TCM_SECTION Psram_Init(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_Cmds_Cfg *cmdsCfg, SF_Ctrl_Psram_Cfg *sfCtrlPsramCfg) -{ - SF_Ctrl_Psram_Init(sfCtrlPsramCfg); - SF_Ctrl_Cmds_Set(cmdsCfg); +void ATTR_TCM_SECTION Psram_Init(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_Cmds_Cfg *cmdsCfg, SF_Ctrl_Psram_Cfg *sfCtrlPsramCfg) { + SF_Ctrl_Psram_Init(sfCtrlPsramCfg); + SF_Ctrl_Cmds_Set(cmdsCfg); - Psram_SetDriveStrength(psramCfg); - Psram_SetBurstWrap(psramCfg); + Psram_SetDriveStrength(psramCfg); + Psram_SetBurstWrap(psramCfg); } -//#endif +// #endif /****************************************************************************/ /** - * @brief Read psram register - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param regValue: Register value pointer to store data - * - * @return None - * -*******************************************************************************/ + * @brief Read psram register + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param regValue: Register value pointer to store data + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION Psram_ReadReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) -{ - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_CTRL_MODE(psramCfg->ctrlMode)); +void ATTR_TCM_SECTION Psram_ReadReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) { + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_CTRL_MODE(psramCfg->ctrlMode)); - uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - SF_Ctrl_Cmd_Cfg_Type psramCmd; + uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + SF_Ctrl_Cmd_Cfg_Type psramCmd; - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } - if (psramCfg->ctrlMode == PSRAM_QPI_CTRL_MODE) { - psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - } + if (psramCfg->ctrlMode == PSRAM_QPI_CTRL_MODE) { + psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + } - psramCmd.cmdBuf[0] = (psramCfg->readRegCmd) << 24; - psramCmd.rwFlag = SF_CTRL_READ; - psramCmd.addrSize = 3; - psramCmd.dummyClks = psramCfg->readRegDmyClk; - psramCmd.nbData = 1; + psramCmd.cmdBuf[0] = (psramCfg->readRegCmd) << 24; + psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.addrSize = 3; + psramCmd.dummyClks = psramCfg->readRegDmyClk; + psramCmd.nbData = 1; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) { + } - BL702_MemCpy(regValue, psramCtrlBuf, 1); + BL702_MemCpy(regValue, psramCtrlBuf, 1); } #endif /****************************************************************************/ /** - * @brief Write psram register - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param regValue: Register value pointer storing data - * - * @return None - * -*******************************************************************************/ + * @brief Write psram register + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param regValue: Register value pointer storing data + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION Psram_WriteReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) -{ - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_CTRL_MODE(psramCfg->ctrlMode)); +void ATTR_TCM_SECTION Psram_WriteReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) { + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_CTRL_MODE(psramCfg->ctrlMode)); - uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - SF_Ctrl_Cmd_Cfg_Type psramCmd; + uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + SF_Ctrl_Cmd_Cfg_Type psramCmd; - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } - BL702_MemCpy(psramCtrlBuf, regValue, 1); + BL702_MemCpy(psramCtrlBuf, regValue, 1); - if (psramCfg->ctrlMode == PSRAM_QPI_CTRL_MODE) { - psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - } + if (psramCfg->ctrlMode == PSRAM_QPI_CTRL_MODE) { + psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + } - psramCmd.cmdBuf[0] = (psramCfg->writeRegCmd) << 24; - psramCmd.rwFlag = SF_CTRL_WRITE; - psramCmd.addrSize = 3; - psramCmd.nbData = 1; + psramCmd.cmdBuf[0] = (psramCfg->writeRegCmd) << 24; + psramCmd.rwFlag = SF_CTRL_WRITE; + psramCmd.addrSize = 3; + psramCmd.nbData = 1; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); } #endif /****************************************************************************/ /** - * @brief Set psram driver strength - * - * @param psramCfg: Serial psram parameter configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set psram driver strength + * + * @param psramCfg: Serial psram parameter configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_SetDriveStrength(SPI_Psram_Cfg_Type *psramCfg) -{ - uint32_t stat = 0; - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_DRIVE_STRENGTH(psramCfg->driveStrength)); +BL_Err_Type ATTR_TCM_SECTION Psram_SetDriveStrength(SPI_Psram_Cfg_Type *psramCfg) { + uint32_t stat = 0; + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_DRIVE_STRENGTH(psramCfg->driveStrength)); - Psram_ReadReg(psramCfg, (uint8_t *)&stat); + Psram_ReadReg(psramCfg, (uint8_t *)&stat); - if ((stat & 0x3) == psramCfg->driveStrength) { - return SUCCESS; - } + if ((stat & 0x3) == psramCfg->driveStrength) { + return SUCCESS; + } - stat &= (~0x3); - stat |= psramCfg->driveStrength; + stat &= (~0x3); + stat |= psramCfg->driveStrength; - Psram_WriteReg(psramCfg, (uint8_t *)&stat); - /* Wait for write done */ + Psram_WriteReg(psramCfg, (uint8_t *)&stat); + /* Wait for write done */ - Psram_ReadReg(psramCfg, (uint8_t *)&stat); + Psram_ReadReg(psramCfg, (uint8_t *)&stat); - if ((stat & 0x3) == psramCfg->driveStrength) { - return SUCCESS; - } + if ((stat & 0x3) == psramCfg->driveStrength) { + return SUCCESS; + } - return ERROR; + return ERROR; } #endif /****************************************************************************/ /** - * @brief Set psram burst wrap size - * - * @param psramCfg: Serial psram parameter configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set psram burst wrap size + * + * @param psramCfg: Serial psram parameter configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_SetBurstWrap(SPI_Psram_Cfg_Type *psramCfg) -{ - uint32_t stat = 0; - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_BURST_LENGTH(psramCfg->burstLength)); +BL_Err_Type ATTR_TCM_SECTION Psram_SetBurstWrap(SPI_Psram_Cfg_Type *psramCfg) { + uint32_t stat = 0; + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_BURST_LENGTH(psramCfg->burstLength)); - Psram_ReadReg(psramCfg, (uint8_t *)&stat); + Psram_ReadReg(psramCfg, (uint8_t *)&stat); - if (((stat >> 5) & 0x3) == psramCfg->burstLength) { - return SUCCESS; - } + if (((stat >> 5) & 0x3) == psramCfg->burstLength) { + return SUCCESS; + } - stat &= (~(0x3 << 5)); - stat |= (psramCfg->burstLength << 5); + stat &= (~(0x3 << 5)); + stat |= (psramCfg->burstLength << 5); - Psram_WriteReg(psramCfg, (uint8_t *)&stat); - /* Wait for write done */ + Psram_WriteReg(psramCfg, (uint8_t *)&stat); + /* Wait for write done */ - Psram_ReadReg(psramCfg, (uint8_t *)&stat); + Psram_ReadReg(psramCfg, (uint8_t *)&stat); - if (((stat >> 5) & 0x3) == psramCfg->burstLength) { - return SUCCESS; - } + if (((stat >> 5) & 0x3) == psramCfg->burstLength) { + return SUCCESS; + } - return ERROR; + return ERROR; } #endif /****************************************************************************/ /** - * @brief Get psram ID - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param data: Data pointer to store read data - * - * @return None - * -*******************************************************************************/ + * @brief Get psram ID + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param data: Data pointer to store read data + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION Psram_ReadId(SPI_Psram_Cfg_Type *psramCfg, uint8_t *data) -{ - uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - SF_Ctrl_Cmd_Cfg_Type psramCmd; +void ATTR_TCM_SECTION Psram_ReadId(SPI_Psram_Cfg_Type *psramCfg, uint8_t *data) { + uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + SF_Ctrl_Cmd_Cfg_Type psramCmd; - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } - psramCmd.cmdBuf[0] = (psramCfg->readIdCmd) << 24; - psramCmd.rwFlag = SF_CTRL_READ; - psramCmd.addrSize = 3; - psramCmd.dummyClks = psramCfg->readIdDmyClk; - psramCmd.nbData = 8; + psramCmd.cmdBuf[0] = (psramCfg->readIdCmd) << 24; + psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.addrSize = 3; + psramCmd.dummyClks = psramCfg->readIdDmyClk; + psramCmd.nbData = 8; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) { + } - BL702_MemCpy(data, psramCtrlBuf, 8); + BL702_MemCpy(data, psramCtrlBuf, 8); } #endif /****************************************************************************/ /** - * @brief Psram enter quad mode - * - * @param psramCfg: Serial psram parameter configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Psram enter quad mode + * + * @param psramCfg: Serial psram parameter configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_EnterQuadMode(SPI_Psram_Cfg_Type *psramCfg) -{ - SF_Ctrl_Cmd_Cfg_Type psramCmd; +BL_Err_Type ATTR_TCM_SECTION Psram_EnterQuadMode(SPI_Psram_Cfg_Type *psramCfg) { + SF_Ctrl_Cmd_Cfg_Type psramCmd; - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } - psramCmd.cmdBuf[0] = (psramCfg->enterQuadModeCmd) << 24; - psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.cmdBuf[0] = (psramCfg->enterQuadModeCmd) << 24; + psramCmd.rwFlag = SF_CTRL_READ; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) { + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Psram exit quad mode - * - * @param psramCfg: Serial psram parameter configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Psram exit quad mode + * + * @param psramCfg: Serial psram parameter configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_ExitQuadMode(SPI_Psram_Cfg_Type *psramCfg) -{ - SF_Ctrl_Cmd_Cfg_Type psramCmd; +BL_Err_Type ATTR_TCM_SECTION Psram_ExitQuadMode(SPI_Psram_Cfg_Type *psramCfg) { + SF_Ctrl_Cmd_Cfg_Type psramCmd; - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } - psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - psramCmd.cmdBuf[0] = (psramCfg->exitQuadModeCmd) << 24; - psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.cmdBuf[0] = (psramCfg->exitQuadModeCmd) << 24; + psramCmd.rwFlag = SF_CTRL_READ; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) { + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Psram toggle burst length - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ctrlMode: Psram ctrl mode type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Psram toggle burst length + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ctrlMode: Psram ctrl mode type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_ToggleBurstLength(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) -{ - SF_Ctrl_Cmd_Cfg_Type psramCmd; - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_CTRL_MODE(ctrlMode)); - - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } - - if (ctrlMode == PSRAM_QPI_CTRL_MODE) { - psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - } +BL_Err_Type ATTR_TCM_SECTION Psram_ToggleBurstLength(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) { + SF_Ctrl_Cmd_Cfg_Type psramCmd; + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_CTRL_MODE(ctrlMode)); + + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (ctrlMode == PSRAM_QPI_CTRL_MODE) { + psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + } - psramCmd.cmdBuf[0] = (psramCfg->burstToggleCmd) << 24; - psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.cmdBuf[0] = (psramCfg->burstToggleCmd) << 24; + psramCmd.rwFlag = SF_CTRL_READ; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) { + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Psram software reset - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ctrlMode: Psram ctrl mode type - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Psram software reset + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ctrlMode: Psram ctrl mode type + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_SoftwareReset(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) -{ - SF_Ctrl_Cmd_Cfg_Type psramCmd; - /* Check the parameters */ - CHECK_PARAM(IS_PSRAM_CTRL_MODE(ctrlMode)); - - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } +BL_Err_Type ATTR_TCM_SECTION Psram_SoftwareReset(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) { + SF_Ctrl_Cmd_Cfg_Type psramCmd; + /* Check the parameters */ + CHECK_PARAM(IS_PSRAM_CTRL_MODE(ctrlMode)); + + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (ctrlMode == PSRAM_QPI_CTRL_MODE) { + psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + } - if (ctrlMode == PSRAM_QPI_CTRL_MODE) { - psramCmd.cmdMode = SF_CTRL_CMD_4_LINES; - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - } + /* Reset enable */ + psramCmd.cmdBuf[0] = (psramCfg->resetEnableCmd) << 24; + /* rwFlag don't care */ + psramCmd.rwFlag = SF_CTRL_READ; + /* Wait for write done */ - /* Reset enable */ - psramCmd.cmdBuf[0] = (psramCfg->resetEnableCmd) << 24; - /* rwFlag don't care */ - psramCmd.rwFlag = SF_CTRL_READ; - /* Wait for write done */ + SF_Ctrl_SendCmd(&psramCmd); - SF_Ctrl_SendCmd(&psramCmd); + while (SET == SF_Ctrl_GetBusyState()) { + } - while (SET == SF_Ctrl_GetBusyState()) { - } - - /* Reset */ - psramCmd.cmdBuf[0] = (psramCfg->resetCmd) << 24; - /* rwFlag don't care */ - psramCmd.rwFlag = SF_CTRL_READ; - SF_Ctrl_SendCmd(&psramCmd); + /* Reset */ + psramCmd.cmdBuf[0] = (psramCfg->resetCmd) << 24; + /* rwFlag don't care */ + psramCmd.rwFlag = SF_CTRL_READ; + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) { + } - BL702_Delay_US(50); - return SUCCESS; + BL702_Delay_US(50); + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Psram set IDbus config - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ioMode: Psram ctrl mode type - * @param addr: Address to read/write - * @param len: Data length to read/write - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Psram set IDbus config + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ioMode: Psram ctrl mode type + * @param addr: Address to read/write + * @param len: Data length to read/write + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_Set_IDbus_Cfg(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint32_t len) -{ - uint8_t cmd, dummyClks; - SF_Ctrl_Cmd_Cfg_Type psramCmd; - uint8_t cmdValid = 1; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); - - SF_Ctrl_Set_Owner(SF_CTRL_OWNER_IAHB); - - /* read mode cache set */ - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } - - if (SF_CTRL_NIO_MODE == ioMode) { - cmd = psramCfg->fReadCmd; - dummyClks = psramCfg->fReadDmyClk; - } else if (SF_CTRL_QIO_MODE == ioMode) { - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - cmd = psramCfg->fReadQuadCmd; - dummyClks = psramCfg->fReadQuadDmyClk; - } else { - return ERROR; - } - - /* prepare command */ - psramCmd.rwFlag = SF_CTRL_READ; - psramCmd.addrSize = 3; - psramCmd.cmdBuf[0] = (cmd << 24) | addr; - psramCmd.dummyClks = dummyClks; - psramCmd.nbData = len; - SF_Ctrl_Psram_Read_Icache_Set(&psramCmd, cmdValid); - - /* write mode cache set */ - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } - - if (SF_CTRL_NIO_MODE == ioMode) { - cmd = psramCfg->writeCmd; - } else if (SF_CTRL_QIO_MODE == ioMode) { - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - cmd = psramCfg->quadWriteCmd; - } else { - return ERROR; - } - - dummyClks = 0; - - /* prepare command */ - psramCmd.rwFlag = SF_CTRL_WRITE; - psramCmd.addrSize = 3; - psramCmd.cmdBuf[0] = (cmd << 24) | addr; - psramCmd.dummyClks = dummyClks; - psramCmd.nbData = len; - SF_Ctrl_Psram_Write_Icache_Set(&psramCmd, cmdValid); - return SUCCESS; +BL_Err_Type ATTR_TCM_SECTION Psram_Set_IDbus_Cfg(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint32_t len) { + uint8_t cmd, dummyClks; + SF_Ctrl_Cmd_Cfg_Type psramCmd; + uint8_t cmdValid = 1; + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); + + SF_Ctrl_Set_Owner(SF_CTRL_OWNER_IAHB); + + /* read mode cache set */ + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (SF_CTRL_NIO_MODE == ioMode) { + cmd = psramCfg->fReadCmd; + dummyClks = psramCfg->fReadDmyClk; + } else if (SF_CTRL_QIO_MODE == ioMode) { + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + cmd = psramCfg->fReadQuadCmd; + dummyClks = psramCfg->fReadQuadDmyClk; + } else { + return ERROR; + } + + /* prepare command */ + psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.addrSize = 3; + psramCmd.cmdBuf[0] = (cmd << 24) | addr; + psramCmd.dummyClks = dummyClks; + psramCmd.nbData = len; + SF_Ctrl_Psram_Read_Icache_Set(&psramCmd, cmdValid); + + /* write mode cache set */ + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (SF_CTRL_NIO_MODE == ioMode) { + cmd = psramCfg->writeCmd; + } else if (SF_CTRL_QIO_MODE == ioMode) { + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + cmd = psramCfg->quadWriteCmd; + } else { + return ERROR; + } + + dummyClks = 0; + + /* prepare command */ + psramCmd.rwFlag = SF_CTRL_WRITE; + psramCmd.addrSize = 3; + psramCmd.cmdBuf[0] = (cmd << 24) | addr; + psramCmd.dummyClks = dummyClks; + psramCmd.nbData = len; + SF_Ctrl_Psram_Write_Icache_Set(&psramCmd, cmdValid); + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Set cache write to psram with cache - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ioMode: Psram controller interface mode - * @param wtEn: Psram cache write through enable - * @param wbEn: Psram cache write back enable - * @param waEn: Psram cache write allocate enable - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Set cache write to psram with cache + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ioMode: Psram controller interface mode + * @param wtEn: Psram cache write through enable + * @param wbEn: Psram cache write back enable + * @param waEn: Psram cache write allocate enable + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_Cache_Write_Set(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, - BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) -{ - BL_Err_Type stat; +BL_Err_Type ATTR_TCM_SECTION Psram_Cache_Write_Set(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) { + BL_Err_Type stat; - /* Cache now only support 32 bytes read */ - stat = Psram_Set_IDbus_Cfg(psramCfg, ioMode, 0, 32); + /* Cache now only support 32 bytes read */ + stat = Psram_Set_IDbus_Cfg(psramCfg, ioMode, 0, 32); - if (SUCCESS != stat) { - return stat; - } + if (SUCCESS != stat) { + return stat; + } - L1C_Cache_Write_Set(wtEn, wbEn, waEn); - return SUCCESS; + L1C_Cache_Write_Set(wtEn, wbEn, waEn); + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Write psram one region - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ioMode: Write mode: SPI mode or QPI mode - * @param addr: Start address to be write - * @param data: Data pointer to be write - * @param len: Data length to be write - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Write psram one region + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ioMode: Write mode: SPI mode or QPI mode + * @param addr: Start address to be write + * @param data: Data pointer to be write + * @param len: Data length to be write + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_Write(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - uint32_t i = 0, curLen = 0; - uint32_t burstLen = 512; - uint8_t cmd; - SF_Ctrl_Cmd_Cfg_Type psramCmd; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); - - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } +BL_Err_Type ATTR_TCM_SECTION Psram_Write(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + uint32_t i = 0, curLen = 0; + uint32_t burstLen = 512; + uint8_t cmd; + SF_Ctrl_Cmd_Cfg_Type psramCmd; + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); + + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (SF_CTRL_NIO_MODE == ioMode) { + cmd = psramCfg->writeCmd; + } else if (SF_CTRL_QIO_MODE == ioMode) { + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + cmd = psramCfg->quadWriteCmd; + } else { + return ERROR; + } - if (SF_CTRL_NIO_MODE == ioMode) { - cmd = psramCfg->writeCmd; - } else if (SF_CTRL_QIO_MODE == ioMode) { - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - cmd = psramCfg->quadWriteCmd; - } else { - return ERROR; - } + /* Prepare command */ + psramCmd.rwFlag = SF_CTRL_WRITE; + psramCmd.addrSize = 3; - /* Prepare command */ - psramCmd.rwFlag = SF_CTRL_WRITE; - psramCmd.addrSize = 3; - - if (psramCfg->burstLength == PSRAM_BURST_LENGTH_16_BYTES) { - burstLen = 16; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_32_BYTES) { - burstLen = 32; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_64_BYTES) { - burstLen = 64; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_512_BYTES) { - burstLen = 512; - } + if (psramCfg->burstLength == PSRAM_BURST_LENGTH_16_BYTES) { + burstLen = 16; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_32_BYTES) { + burstLen = 32; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_64_BYTES) { + burstLen = 64; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_512_BYTES) { + burstLen = 512; + } - for (i = 0; i < len;) { - /* Get current programmed length within page size */ - curLen = burstLen - addr % burstLen; + for (i = 0; i < len;) { + /* Get current programmed length within page size */ + curLen = burstLen - addr % burstLen; - if (curLen > len - i) { - curLen = len - i; - } + if (curLen > len - i) { + curLen = len - i; + } - /* Prepare command */ - BL702_MemCpy_Fast(psramCtrlBuf, data, curLen); - psramCmd.cmdBuf[0] = (cmd << 24) | (addr); - psramCmd.nbData = curLen; + /* Prepare command */ + BL702_MemCpy_Fast(psramCtrlBuf, data, curLen); + psramCmd.cmdBuf[0] = (cmd << 24) | (addr); + psramCmd.nbData = curLen; - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - /* Adjust address and programmed length */ - addr += curLen; - i += curLen; - data += curLen; + /* Adjust address and programmed length */ + addr += curLen; + i += curLen; + data += curLen; - /* Wait for write done */ - } + /* Wait for write done */ + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Read data from psram - * - * @param psramCfg: Serial psram parameter configuration pointer - * @param ioMode: IoMode: psram controller interface mode - * @param addr: Psram read start address - * @param data: Data pointer to store data read from psram - * @param len: Data length to read - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Read data from psram + * + * @param psramCfg: Serial psram parameter configuration pointer + * @param ioMode: IoMode: psram controller interface mode + * @param addr: Psram read start address + * @param data: Data pointer to store data read from psram + * @param len: Data length to read + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION Psram_Read(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - uint32_t curLen, i; - uint32_t burstLen = 512; - uint8_t cmd, dummyClks; - SF_Ctrl_Cmd_Cfg_Type psramCmd; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); - - if (((uint32_t)&psramCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); - } else { - BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); - } +BL_Err_Type ATTR_TCM_SECTION Psram_Read(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + uint8_t *const psramCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + uint32_t curLen, i; + uint32_t burstLen = 512; + uint8_t cmd, dummyClks; + SF_Ctrl_Cmd_Cfg_Type psramCmd; + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_IO_TYPE(ioMode)); + + if (((uint32_t)&psramCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&psramCmd, 0, sizeof(psramCmd) / 4); + } else { + BL702_MemSet(&psramCmd, 0, sizeof(psramCmd)); + } + + if (SF_CTRL_NIO_MODE == ioMode) { + cmd = psramCfg->fReadCmd; + dummyClks = psramCfg->fReadDmyClk; + } else if (SF_CTRL_QIO_MODE == ioMode) { + psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; + psramCmd.dataMode = SF_CTRL_DATA_4_LINES; + cmd = psramCfg->fReadQuadCmd; + dummyClks = psramCfg->fReadQuadDmyClk; + } else { + return ERROR; + } + + /* Prepare command */ + psramCmd.rwFlag = SF_CTRL_READ; + psramCmd.addrSize = 3; + psramCmd.dummyClks = dummyClks; + + if (psramCfg->burstLength == PSRAM_BURST_LENGTH_16_BYTES) { + burstLen = 16; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_32_BYTES) { + burstLen = 32; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_64_BYTES) { + burstLen = 64; + } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_512_BYTES) { + burstLen = 512; + } + + /* Read data */ + for (i = 0; i < len;) { + /* Prepare command */ + psramCmd.cmdBuf[0] = (cmd << 24) | (addr); + curLen = burstLen - addr % burstLen; - if (SF_CTRL_NIO_MODE == ioMode) { - cmd = psramCfg->fReadCmd; - dummyClks = psramCfg->fReadDmyClk; - } else if (SF_CTRL_QIO_MODE == ioMode) { - psramCmd.addrMode = SF_CTRL_ADDR_4_LINES; - psramCmd.dataMode = SF_CTRL_DATA_4_LINES; - cmd = psramCfg->fReadQuadCmd; - dummyClks = psramCfg->fReadQuadDmyClk; - } else { - return ERROR; + if (curLen > len - i) { + curLen = len - i; } - /* Prepare command */ - psramCmd.rwFlag = SF_CTRL_READ; - psramCmd.addrSize = 3; - psramCmd.dummyClks = dummyClks; - - if (psramCfg->burstLength == PSRAM_BURST_LENGTH_16_BYTES) { - burstLen = 16; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_32_BYTES) { - burstLen = 32; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_64_BYTES) { - burstLen = 64; - } else if (psramCfg->burstLength == PSRAM_BURST_LENGTH_512_BYTES) { - burstLen = 512; + if (curLen >= FLASH_CTRL_BUF_SIZE) { + curLen = FLASH_CTRL_BUF_SIZE; + psramCmd.nbData = curLen; + } else { + /* Make sf_ctrl word read */ + psramCmd.nbData = ((curLen + 3) >> 2) << 2; } - /* Read data */ - for (i = 0; i < len;) { - /* Prepare command */ - psramCmd.cmdBuf[0] = (cmd << 24) | (addr); - curLen = burstLen - addr % burstLen; - - if (curLen > len - i) { - curLen = len - i; - } - - if (curLen >= FLASH_CTRL_BUF_SIZE) { - curLen = FLASH_CTRL_BUF_SIZE; - psramCmd.nbData = curLen; - } else { - /* Make sf_ctrl word read */ - psramCmd.nbData = ((curLen + 3) >> 2) << 2; - } - - SF_Ctrl_SendCmd(&psramCmd); + SF_Ctrl_SendCmd(&psramCmd); - while (SET == SF_Ctrl_GetBusyState()) { - } + while (SET == SF_Ctrl_GetBusyState()) { + } - BL702_MemCpy_Fast(data, psramCtrlBuf, curLen); + BL702_MemCpy_Fast(data, psramCtrlBuf, curLen); - addr += curLen; - i += curLen; - data += curLen; - } + addr += curLen; + i += curLen; + data += curLen; + } - return SUCCESS; + return SUCCESS; } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pwm.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pwm.c index b63158016..80188ee77 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pwm.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_pwm.c @@ -48,7 +48,7 @@ /** @defgroup PWM_Private_Macros * @{ */ -#define PWM_Get_Channel_Reg(ch) (PWM_BASE + PWM_CHANNEL_OFFSET + (ch)*0x20) +#define PWM_Get_Channel_Reg(ch) (PWM_BASE + PWM_CHANNEL_OFFSET + (ch) * 0x20) #define PWM_INT_TIMEOUT_COUNT (160 * 1000) #define PWM_STOP_TIMEOUT_COUNT (160 * 1000) diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c index c34af329e..f503f67e4 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_qdec.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_qdec.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_qdec.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_qdec.h" @@ -59,10 +59,12 @@ /** @defgroup QDEC_Private_Variables * @{ */ -static const uint32_t qdecAddr[QDEC_ID_MAX] = { QDEC0_BASE, QDEC1_BASE, QDEC2_BASE }; -static intCallback_Type *qdecIntCbfArra[QDEC_ID_MAX][QDEC_INT_ALL] = { { NULL, NULL, NULL, NULL }, - { NULL, NULL, NULL, NULL }, - { NULL, NULL, NULL, NULL } }; +static const uint32_t qdecAddr[QDEC_ID_MAX] = {QDEC0_BASE, QDEC1_BASE, QDEC2_BASE}; +static intCallback_Type *qdecIntCbfArra[QDEC_ID_MAX][QDEC_INT_ALL] = { + {NULL, NULL, NULL, NULL}, + {NULL, NULL, NULL, NULL}, + {NULL, NULL, NULL, NULL} +}; /*@} end of group QDEC_Private_Variables */ @@ -83,461 +85,443 @@ static intCallback_Type *qdecIntCbfArra[QDEC_ID_MAX][QDEC_INT_ALL] = { { NULL, N */ /****************************************************************************/ /** - * @brief QDEC init - * - * @param qdecId: QDEC ID - * @param qdecCfg: QDEC config - * - * @return None - * -*******************************************************************************/ -void QDEC_Init(QDEC_ID_Type qdecId, QDEC_CFG_Type *qdecCfg) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - CHECK_PARAM(IS_QDEC_SAMPLE_MODE_TYPE(qdecCfg->sampleCfg.sampleMod)); - CHECK_PARAM(IS_QDEC_SAMPLE_PERIOD_TYPE(qdecCfg->sampleCfg.samplePeriod)); - CHECK_PARAM(IS_QDEC_REPORT_MODE_TYPE(qdecCfg->reportCfg.reportMod)); - CHECK_PARAM((qdecCfg->ledCfg.ledPeriod) <= 0x1FF); - CHECK_PARAM((qdecCfg->deglitchCfg.deglitchStrength) <= 0xF); - - /* qdec_ctrl */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_PERIOD, qdecCfg->sampleCfg.samplePeriod); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_PERIOD, qdecCfg->reportCfg.reportPeriod); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_EN, qdecCfg->ledCfg.ledEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_POL, qdecCfg->ledCfg.ledSwap); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_EN, qdecCfg->deglitchCfg.deglitchEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_CNT, qdecCfg->deglitchCfg.deglitchStrength); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); - - /* qdec_ctrl1 */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_MODE, qdecCfg->sampleCfg.sampleMod); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_MODE, qdecCfg->reportCfg.reportMod); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_PERIOD, qdecCfg->ledCfg.ledPeriod); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_ACC_MODE, qdecCfg->accMod); - BL_WR_REG(QDECx, QDEC0_CTRL1, tmpVal); + * @brief QDEC init + * + * @param qdecId: QDEC ID + * @param qdecCfg: QDEC config + * + * @return None + * + *******************************************************************************/ +void QDEC_Init(QDEC_ID_Type qdecId, QDEC_CFG_Type *qdecCfg) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + CHECK_PARAM(IS_QDEC_SAMPLE_MODE_TYPE(qdecCfg->sampleCfg.sampleMod)); + CHECK_PARAM(IS_QDEC_SAMPLE_PERIOD_TYPE(qdecCfg->sampleCfg.samplePeriod)); + CHECK_PARAM(IS_QDEC_REPORT_MODE_TYPE(qdecCfg->reportCfg.reportMod)); + CHECK_PARAM((qdecCfg->ledCfg.ledPeriod) <= 0x1FF); + CHECK_PARAM((qdecCfg->deglitchCfg.deglitchStrength) <= 0xF); + + /* qdec_ctrl */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_PERIOD, qdecCfg->sampleCfg.samplePeriod); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_PERIOD, qdecCfg->reportCfg.reportPeriod); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_EN, qdecCfg->ledCfg.ledEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_POL, qdecCfg->ledCfg.ledSwap); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_EN, qdecCfg->deglitchCfg.deglitchEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_CNT, qdecCfg->deglitchCfg.deglitchStrength); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + + /* qdec_ctrl1 */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_MODE, qdecCfg->sampleCfg.sampleMod); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_MODE, qdecCfg->reportCfg.reportMod); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_PERIOD, qdecCfg->ledCfg.ledPeriod); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_ACC_MODE, qdecCfg->accMod); + BL_WR_REG(QDECx, QDEC0_CTRL1, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(QDEC0_IRQn, QDEC0_IRQHandler); - Interrupt_Handler_Register(QDEC1_IRQn, QDEC1_IRQHandler); - Interrupt_Handler_Register(QDEC2_IRQn, QDEC2_IRQHandler); + Interrupt_Handler_Register(QDEC0_IRQn, QDEC0_IRQHandler); + Interrupt_Handler_Register(QDEC1_IRQn, QDEC1_IRQHandler); + Interrupt_Handler_Register(QDEC2_IRQn, QDEC2_IRQHandler); #endif } /****************************************************************************/ /** - * @brief QDEC deinit - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -void QDEC_DeInit(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* deconfig qdec */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_PERIOD, 10); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_PERIOD, 2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_CNT, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_POL, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_EN, 0); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_PERIOD, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_INPUT_SWAP, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_MODE, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_MODE, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_ACC_MODE, 1); - BL_WR_REG(QDECx, QDEC0_CTRL1, tmpVal); - - /* enable qdec */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_EN, 1); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); - - /* deconfig interrupt */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN, 1); - BL_WR_REG(QDECx, QDEC0_INT_EN, tmpVal); - - /* clear status */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_CLR); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_CLR, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_CLR, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_CLR, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_CLR, 1); - BL_WR_REG(QDECx, QDEC0_INT_STS, tmpVal); - - /* clear value */ - tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); - - /* disable qdec */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_EN, 0); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + * @brief QDEC deinit + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +void QDEC_DeInit(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* deconfig qdec */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_PERIOD, 10); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_PERIOD, 2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_CNT, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DEG_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_POL, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_EN, 0); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_LED_PERIOD, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_INPUT_SWAP, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_MODE, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_MODE, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_ACC_MODE, 1); + BL_WR_REG(QDECx, QDEC0_CTRL1, tmpVal); + + /* enable qdec */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_EN, 1); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + + /* deconfig interrupt */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN, 1); + BL_WR_REG(QDECx, QDEC0_INT_EN, tmpVal); + + /* clear status */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_CLR); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_CLR, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_CLR, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_CLR, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_CLR, 1); + BL_WR_REG(QDECx, QDEC0_INT_STS, tmpVal); + + /* clear value */ + tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); + + /* disable qdec */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_EN, 0); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); } /****************************************************************************/ /** - * @brief QDEC enable - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -void QDEC_Enable(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* qdec_ctrl */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_EN); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + * @brief QDEC enable + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +void QDEC_Enable(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* qdec_ctrl */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_EN); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); } /****************************************************************************/ /** - * @brief QDEC disable - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -void QDEC_Disable(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* qdec_ctrl */ - tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); - tmpVal = BL_CLR_REG_BIT(tmpVal, QDEC_EN); - BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); + * @brief QDEC disable + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +void QDEC_Disable(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* qdec_ctrl */ + tmpVal = BL_RD_REG(QDECx, QDEC0_CTRL0); + tmpVal = BL_CLR_REG_BIT(tmpVal, QDEC_EN); + BL_WR_REG(QDECx, QDEC0_CTRL0, tmpVal); } /****************************************************************************/ /** - * @brief set QDEC interrupt mask - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * @param intMask: MASK or UNMASK - * - * @return None - * -*******************************************************************************/ -void QDEC_SetIntMask(QDEC_ID_Type qdecId, QDEC_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); - - /* qdec_int_en */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); - - switch (intType) { - case QDEC_INT_REPORT: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN, (intMask ? 0 : 1)); - break; - - case QDEC_INT_SAMPLE: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN, (intMask ? 0 : 1)); - break; - - case QDEC_INT_ERROR: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN, (intMask ? 0 : 1)); - break; - - case QDEC_INT_OVERFLOW: - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN, (intMask ? 0 : 1)); - break; - - default: - break; - } - - BL_WR_REG(QDECx, QDEC0_INT_EN, tmpVal); + * @brief set QDEC interrupt mask + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * @param intMask: MASK or UNMASK + * + * @return None + * + *******************************************************************************/ +void QDEC_SetIntMask(QDEC_ID_Type qdecId, QDEC_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); + + /* qdec_int_en */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); + + switch (intType) { + case QDEC_INT_REPORT: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN, (intMask ? 0 : 1)); + break; + + case QDEC_INT_SAMPLE: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN, (intMask ? 0 : 1)); + break; + + case QDEC_INT_ERROR: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN, (intMask ? 0 : 1)); + break; + + case QDEC_INT_OVERFLOW: + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN, (intMask ? 0 : 1)); + break; + + default: + break; + } + + BL_WR_REG(QDECx, QDEC0_INT_EN, tmpVal); } /****************************************************************************/ /** - * @brief get QDEC interrupt mask - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * - * @return MASK or UNMASK - * -*******************************************************************************/ -BL_Mask_Type QDEC_GetIntMask(QDEC_ID_Type qdecId, QDEC_INT_Type intType) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); - - /* qdec_int_en */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); - - switch (intType) { - case QDEC_INT_REPORT: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN) ? UNMASK : MASK; - - case QDEC_INT_SAMPLE: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN) ? UNMASK : MASK; - - case QDEC_INT_ERROR: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN) ? UNMASK : MASK; - - case QDEC_INT_OVERFLOW: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN) ? UNMASK : MASK; - - default: - return UNMASK; - } + * @brief get QDEC interrupt mask + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * + * @return MASK or UNMASK + * + *******************************************************************************/ +BL_Mask_Type QDEC_GetIntMask(QDEC_ID_Type qdecId, QDEC_INT_Type intType) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); + + /* qdec_int_en */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_EN); + + switch (intType) { + case QDEC_INT_REPORT: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_EN) ? UNMASK : MASK; + + case QDEC_INT_SAMPLE: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_EN) ? UNMASK : MASK; + + case QDEC_INT_ERROR: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_EN) ? UNMASK : MASK; + + case QDEC_INT_OVERFLOW: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_EN) ? UNMASK : MASK; + + default: + return UNMASK; + } } /****************************************************************************/ /** - * @brief QDEC interrupt callback install - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * @param cbFun: interrupt callback - * - * @return None - * -*******************************************************************************/ -void QDEC_Int_Callback_Install(QDEC_ID_Type qdecId, QDEC_INT_Type intType, intCallback_Type *cbFun) -{ - qdecIntCbfArra[qdecId][intType] = cbFun; -} + * @brief QDEC interrupt callback install + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * @param cbFun: interrupt callback + * + * @return None + * + *******************************************************************************/ +void QDEC_Int_Callback_Install(QDEC_ID_Type qdecId, QDEC_INT_Type intType, intCallback_Type *cbFun) { qdecIntCbfArra[qdecId][intType] = cbFun; } /****************************************************************************/ /** - * @brief QDEC get interrupt status - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type QDEC_Get_Int_Status(QDEC_ID_Type qdecId, QDEC_INT_Type intType) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); - - /* qdec_int_sts */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_STS); - - switch (intType) { - case QDEC_INT_REPORT: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_STS) ? SET : RESET; - - case QDEC_INT_SAMPLE: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_STS) ? SET : RESET; - - case QDEC_INT_ERROR: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_STS) ? SET : RESET; - - case QDEC_INT_OVERFLOW: - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_STS) ? SET : RESET; - - default: - return RESET; - } + * @brief QDEC get interrupt status + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type QDEC_Get_Int_Status(QDEC_ID_Type qdecId, QDEC_INT_Type intType) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); + + /* qdec_int_sts */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_STS); + + switch (intType) { + case QDEC_INT_REPORT: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_RPT_RDY_STS) ? SET : RESET; + + case QDEC_INT_SAMPLE: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_RDY_STS) ? SET : RESET; + + case QDEC_INT_ERROR: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_DBL_RDY_STS) ? SET : RESET; + + case QDEC_INT_OVERFLOW: + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_OVERFLOW_STS) ? SET : RESET; + + default: + return RESET; + } } /****************************************************************************/ /** - * @brief QDEC clear interrupt status - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * - * @return None - * -*******************************************************************************/ -void QDEC_Clr_Int_Status(QDEC_ID_Type qdecId, QDEC_INT_Type intType) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); - - /* qdec_int_clr */ - tmpVal = BL_RD_REG(QDECx, QDEC0_INT_CLR); - - switch (intType) { - case QDEC_INT_REPORT: - tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_RPT_RDY_CLR); - break; - - case QDEC_INT_SAMPLE: - tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_SPL_RDY_CLR); - break; - - case QDEC_INT_ERROR: - tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_DBL_RDY_CLR); - break; - - case QDEC_INT_OVERFLOW: - tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_OVERFLOW_CLR); - break; - - default: - break; - } - - BL_WR_REG(QDECx, QDEC0_INT_CLR, tmpVal); + * @brief QDEC clear interrupt status + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * + * @return None + * + *******************************************************************************/ +void QDEC_Clr_Int_Status(QDEC_ID_Type qdecId, QDEC_INT_Type intType) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + CHECK_PARAM(IS_QDEC_INT_TYPE(intType)); + + /* qdec_int_clr */ + tmpVal = BL_RD_REG(QDECx, QDEC0_INT_CLR); + + switch (intType) { + case QDEC_INT_REPORT: + tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_RPT_RDY_CLR); + break; + + case QDEC_INT_SAMPLE: + tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_SPL_RDY_CLR); + break; + + case QDEC_INT_ERROR: + tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_DBL_RDY_CLR); + break; + + case QDEC_INT_OVERFLOW: + tmpVal = BL_SET_REG_BIT(tmpVal, QDEC_OVERFLOW_CLR); + break; + + default: + break; + } + + BL_WR_REG(QDECx, QDEC0_INT_CLR, tmpVal); } /****************************************************************************/ /** - * @brief QDEC get sample direction - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -QDEC_DIRECTION_Type QDEC_Get_Sample_Direction(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* qdec_value */ - tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); - - return (QDEC_DIRECTION_Type)BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_VAL); + * @brief QDEC get sample direction + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +QDEC_DIRECTION_Type QDEC_Get_Sample_Direction(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* qdec_value */ + tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); + + return (QDEC_DIRECTION_Type)BL_GET_REG_BITS_VAL(tmpVal, QDEC_SPL_VAL); } /****************************************************************************/ /** - * @brief QDEC get error count - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -uint8_t QDEC_Get_Err_Cnt(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* qdec_value */ - tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); - - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_ACC2_VAL); + * @brief QDEC get error count + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +uint8_t QDEC_Get_Err_Cnt(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* qdec_value */ + tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); + + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_ACC2_VAL); } /****************************************************************************/ /** - * @brief QDEC get sample value - * - * @param qdecId: QDEC ID - * - * @return None - * -*******************************************************************************/ -uint16_t QDEC_Get_Sample_Val(QDEC_ID_Type qdecId) -{ - uint32_t tmpVal = 0; - uint32_t QDECx = qdecAddr[qdecId]; - - /* qdec_value */ - tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); - - return BL_GET_REG_BITS_VAL(tmpVal, QDEC_ACC1_VAL); + * @brief QDEC get sample value + * + * @param qdecId: QDEC ID + * + * @return None + * + *******************************************************************************/ +uint16_t QDEC_Get_Sample_Val(QDEC_ID_Type qdecId) { + uint32_t tmpVal = 0; + uint32_t QDECx = qdecAddr[qdecId]; + + /* qdec_value */ + tmpVal = BL_RD_REG(QDECx, QDEC0_VALUE); + + return BL_GET_REG_BITS_VAL(tmpVal, QDEC_ACC1_VAL); } /****************************************************************************/ /** - * @brief QDEC interrupt handler - * - * @param qdecId: QDEC ID - * @param intType: QDEC interrupt type - * - * @return None - * -*******************************************************************************/ -void QDEC_IntHandler(QDEC_ID_Type qdecId, QDEC_INT_Type intType) -{ - if (SET == QDEC_Get_Int_Status(qdecId, intType)) { - QDEC_Clr_Int_Status(qdecId, intType); - - if (qdecIntCbfArra[qdecId][intType] != NULL) { - qdecIntCbfArra[qdecId][intType](); - } + * @brief QDEC interrupt handler + * + * @param qdecId: QDEC ID + * @param intType: QDEC interrupt type + * + * @return None + * + *******************************************************************************/ +void QDEC_IntHandler(QDEC_ID_Type qdecId, QDEC_INT_Type intType) { + if (SET == QDEC_Get_Int_Status(qdecId, intType)) { + QDEC_Clr_Int_Status(qdecId, intType); + + if (qdecIntCbfArra[qdecId][intType] != NULL) { + qdecIntCbfArra[qdecId][intType](); } + } } /****************************************************************************/ /** - * @brief QDEC0 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief QDEC0 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void QDEC0_IRQHandler(void) -{ - QDEC_INT_Type intType; - - for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { - if (UNMASK == QDEC_GetIntMask(QDEC0_ID, intType)) { - QDEC_IntHandler(QDEC0_ID, intType); - } +void QDEC0_IRQHandler(void) { + QDEC_INT_Type intType; + + for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { + if (UNMASK == QDEC_GetIntMask(QDEC0_ID, intType)) { + QDEC_IntHandler(QDEC0_ID, intType); } + } } #endif /****************************************************************************/ /** - * @brief QDEC1 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief QDEC1 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void QDEC1_IRQHandler(void) -{ - QDEC_INT_Type intType; - - for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { - if (UNMASK == QDEC_GetIntMask(QDEC1_ID, intType)) { - QDEC_IntHandler(QDEC1_ID, intType); - } +void QDEC1_IRQHandler(void) { + QDEC_INT_Type intType; + + for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { + if (UNMASK == QDEC_GetIntMask(QDEC1_ID, intType)) { + QDEC_IntHandler(QDEC1_ID, intType); } + } } #endif /****************************************************************************/ /** - * @brief QDEC2 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief QDEC2 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void QDEC2_IRQHandler(void) -{ - QDEC_INT_Type intType; - - for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { - if (UNMASK == QDEC_GetIntMask(QDEC2_ID, intType)) { - QDEC_IntHandler(QDEC2_ID, intType); - } +void QDEC2_IRQHandler(void) { + QDEC_INT_Type intType; + + for (intType = QDEC_INT_REPORT; intType < QDEC_INT_ALL; intType++) { + if (UNMASK == QDEC_GetIntMask(QDEC2_ID, intType)) { + QDEC_IntHandler(QDEC2_ID, intType); } + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_romapi.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_romapi.c index 73040c439..2576039c4 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_romapi.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_romapi.c @@ -1,112 +1,46 @@ #include "bl702_romdriver.h" /******************************************************************************/ -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - AON_Power_On_MBG(void) -{ - return RomDriver_AON_Power_On_MBG(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type AON_Power_On_MBG(void) { return RomDriver_AON_Power_On_MBG(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - AON_Power_Off_MBG(void) -{ - return RomDriver_AON_Power_Off_MBG(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type AON_Power_Off_MBG(void) { return RomDriver_AON_Power_Off_MBG(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - AON_Power_On_XTAL(void) -{ - return RomDriver_AON_Power_On_XTAL(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type AON_Power_On_XTAL(void) { return RomDriver_AON_Power_On_XTAL(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - AON_Set_Xtal_CapCode(uint8_t capIn, uint8_t capOut) -{ - return RomDriver_AON_Set_Xtal_CapCode(capIn, capOut); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type AON_Set_Xtal_CapCode(uint8_t capIn, uint8_t capOut) { return RomDriver_AON_Set_Xtal_CapCode(capIn, capOut); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - AON_Power_Off_XTAL(void) -{ - return RomDriver_AON_Power_Off_XTAL(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type AON_Power_Off_XTAL(void) { return RomDriver_AON_Power_Off_XTAL(); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION void ASM_Delay_Us(uint32_t core, uint32_t cnt) -{ - RomDriver_ASM_Delay_Us(core, cnt); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void ASM_Delay_Us(uint32_t core, uint32_t cnt) { RomDriver_ASM_Delay_Us(core, cnt); } -__ALWAYS_INLINE ATTR_TCM_SECTION void BL702_Delay_US(uint32_t cnt) -{ - RomDriver_BL702_Delay_US(cnt); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void BL702_Delay_US(uint32_t cnt) { RomDriver_BL702_Delay_US(cnt); } -__ALWAYS_INLINE ATTR_TCM_SECTION void BL702_Delay_MS(uint32_t cnt) -{ - RomDriver_BL702_Delay_MS(cnt); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void BL702_Delay_MS(uint32_t cnt) { RomDriver_BL702_Delay_MS(cnt); } -__ALWAYS_INLINE ATTR_TCM_SECTION void *BL702_MemCpy(void *dst, const void *src, uint32_t n) -{ - return RomDriver_BL702_MemCpy(dst, src, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void *BL702_MemCpy(void *dst, const void *src, uint32_t n) { return RomDriver_BL702_MemCpy(dst, src, n); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t * - BL702_MemCpy4(uint32_t *dst, const uint32_t *src, uint32_t n) -{ - return RomDriver_BL702_MemCpy4(dst, src, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t *BL702_MemCpy4(uint32_t *dst, const uint32_t *src, uint32_t n) { return RomDriver_BL702_MemCpy4(dst, src, n); } // __ALWAYS_INLINE ATTR_TCM_SECTION // void* BL702_MemCpy_Fast(void *pdst, const void *psrc, uint32_t n) { // return RomDriver_BL702_MemCpy_Fast(pdst, psrc, n); // } -__ALWAYS_INLINE ATTR_TCM_SECTION void *ARCH_MemCpy_Fast(void *pdst, const void *psrc, uint32_t n) -{ - return RomDriver_ARCH_MemCpy_Fast(pdst, psrc, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void *ARCH_MemCpy_Fast(void *pdst, const void *psrc, uint32_t n) { return RomDriver_ARCH_MemCpy_Fast(pdst, psrc, n); } -__ALWAYS_INLINE ATTR_TCM_SECTION void *BL702_MemSet(void *s, uint8_t c, uint32_t n) -{ - return RomDriver_BL702_MemSet(s, c, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void *BL702_MemSet(void *s, uint8_t c, uint32_t n) { return RomDriver_BL702_MemSet(s, c, n); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t * - BL702_MemSet4(uint32_t *dst, const uint32_t val, uint32_t n) -{ - return RomDriver_BL702_MemSet4(dst, val, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t *BL702_MemSet4(uint32_t *dst, const uint32_t val, uint32_t n) { return RomDriver_BL702_MemSet4(dst, val, n); } -__ALWAYS_INLINE ATTR_TCM_SECTION int BL702_MemCmp(const void *s1, const void *s2, uint32_t n) -{ - return RomDriver_BL702_MemCmp(s1, s2, n); -} +__ALWAYS_INLINE ATTR_TCM_SECTION int BL702_MemCmp(const void *s1, const void *s2, uint32_t n) { return RomDriver_BL702_MemCmp(s1, s2, n); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t - BFLB_Soft_CRC32(void *dataIn, uint32_t len) -{ - return RomDriver_BFLB_Soft_CRC32(dataIn, len); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t BFLB_Soft_CRC32(void *dataIn, uint32_t len) { return RomDriver_BFLB_Soft_CRC32(dataIn, len); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_CLOCK_SECTION - GLB_ROOT_CLK_Type - GLB_Get_Root_CLK_Sel(void) -{ - return RomDriver_GLB_Get_Root_CLK_Sel(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION GLB_ROOT_CLK_Type GLB_Get_Root_CLK_Sel(void) { return RomDriver_GLB_Get_Root_CLK_Sel(); } #if 0 __ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type @@ -115,145 +49,45 @@ __ALWAYS_INLINE ATTR_CLOCK_SECTION return RomDriver_GLB_Set_System_CLK_Div(hclkDiv, bclkDiv); } #endif -__ALWAYS_INLINE ATTR_CLOCK_SECTION - uint8_t - GLB_Get_BCLK_Div(void) -{ - return RomDriver_GLB_Get_BCLK_Div(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION uint8_t GLB_Get_BCLK_Div(void) { return RomDriver_GLB_Get_BCLK_Div(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - uint8_t - GLB_Get_HCLK_Div(void) -{ - return RomDriver_GLB_Get_HCLK_Div(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION uint8_t GLB_Get_HCLK_Div(void) { return RomDriver_GLB_Get_HCLK_Div(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - Update_SystemCoreClockWith_XTAL(GLB_DLL_XTAL_Type xtalType) -{ - return RomDriver_Update_SystemCoreClockWith_XTAL(xtalType); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type Update_SystemCoreClockWith_XTAL(GLB_DLL_XTAL_Type xtalType) { return RomDriver_Update_SystemCoreClockWith_XTAL(xtalType); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Set_System_CLK(GLB_DLL_XTAL_Type xtalType, GLB_SYS_CLK_Type clkFreq) -{ - return RomDriver_GLB_Set_System_CLK(xtalType, clkFreq); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Set_System_CLK(GLB_DLL_XTAL_Type xtalType, GLB_SYS_CLK_Type clkFreq) { return RomDriver_GLB_Set_System_CLK(xtalType, clkFreq); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - System_Core_Clock_Update_From_RC32M(void) -{ - return RomDriver_System_Core_Clock_Update_From_RC32M(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type System_Core_Clock_Update_From_RC32M(void) { return RomDriver_System_Core_Clock_Update_From_RC32M(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Set_SF_CLK(uint8_t enable, GLB_SFLASH_CLK_Type clkSel, uint8_t div) -{ - return RomDriver_GLB_Set_SF_CLK(enable, clkSel, div); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Set_SF_CLK(uint8_t enable, GLB_SFLASH_CLK_Type clkSel, uint8_t div) { return RomDriver_GLB_Set_SF_CLK(enable, clkSel, div); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Power_Off_DLL(void) -{ - return RomDriver_GLB_Power_Off_DLL(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Power_Off_DLL(void) { return RomDriver_GLB_Power_Off_DLL(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Power_On_DLL(GLB_DLL_XTAL_Type xtalType) -{ - return RomDriver_GLB_Power_On_DLL(xtalType); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Power_On_DLL(GLB_DLL_XTAL_Type xtalType) { return RomDriver_GLB_Power_On_DLL(xtalType); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Enable_DLL_All_Clks(void) -{ - return RomDriver_GLB_Enable_DLL_All_Clks(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Enable_DLL_All_Clks(void) { return RomDriver_GLB_Enable_DLL_All_Clks(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Enable_DLL_Clk(GLB_DLL_CLK_Type dllClk) -{ - return RomDriver_GLB_Enable_DLL_Clk(dllClk); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Enable_DLL_Clk(GLB_DLL_CLK_Type dllClk) { return RomDriver_GLB_Enable_DLL_Clk(dllClk); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Disable_DLL_All_Clks(void) -{ - return RomDriver_GLB_Disable_DLL_All_Clks(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Disable_DLL_All_Clks(void) { return RomDriver_GLB_Disable_DLL_All_Clks(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - GLB_Disable_DLL_Clk(GLB_DLL_CLK_Type dllClk) -{ - return RomDriver_GLB_Disable_DLL_Clk(dllClk); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type GLB_Disable_DLL_Clk(GLB_DLL_CLK_Type dllClk) { return RomDriver_GLB_Disable_DLL_Clk(dllClk); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_SW_System_Reset(void) -{ - return RomDriver_GLB_SW_System_Reset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_SW_System_Reset(void) { return RomDriver_GLB_SW_System_Reset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_SW_CPU_Reset(void) -{ - return RomDriver_GLB_SW_CPU_Reset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_SW_CPU_Reset(void) { return RomDriver_GLB_SW_CPU_Reset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_SW_POR_Reset(void) -{ - return RomDriver_GLB_SW_POR_Reset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_SW_POR_Reset(void) { return RomDriver_GLB_SW_POR_Reset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Select_Internal_Flash(void) -{ - return RomDriver_GLB_Select_Internal_Flash(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Select_Internal_Flash(void) { return RomDriver_GLB_Select_Internal_Flash(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Swap_Flash_Pin(void) -{ - return RomDriver_GLB_Swap_Flash_Pin(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Swap_Flash_Pin(void) { return RomDriver_GLB_Swap_Flash_Pin(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Swap_Flash_CS_IO2_Pin(void) -{ - return RomDriver_GLB_Swap_Flash_CS_IO2_Pin(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Swap_Flash_CS_IO2_Pin(void) { return RomDriver_GLB_Swap_Flash_CS_IO2_Pin(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Swap_Flash_IO0_IO3_Pin(void) -{ - return RomDriver_GLB_Swap_Flash_IO0_IO3_Pin(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Swap_Flash_IO0_IO3_Pin(void) { return RomDriver_GLB_Swap_Flash_IO0_IO3_Pin(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Select_Internal_PSram(void) -{ - return RomDriver_GLB_Select_Internal_PSram(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Select_Internal_PSram(void) { return RomDriver_GLB_Select_Internal_PSram(); } /* aon pads GPIO9~GPIO13 IE controlled by HBN reg_aon_pad_ie_smt, abandon romdriver for this reason */ #if 0 @@ -289,162 +123,61 @@ BL_Err_Type GLB_GPIO_Set_HZ(GLB_GPIO_Type gpioPin) } #endif -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Deswap_Flash_Pin(void) -{ - return RomDriver_GLB_Deswap_Flash_Pin(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Deswap_Flash_Pin(void) { return RomDriver_GLB_Deswap_Flash_Pin(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - GLB_Select_External_Flash(void) -{ - return RomDriver_GLB_Select_External_Flash(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type GLB_Select_External_Flash(void) { return RomDriver_GLB_Select_External_Flash(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint8_t - GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin) -{ - return RomDriver_GLB_GPIO_Get_Fun(gpioPin); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint8_t GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin) { return RomDriver_GLB_GPIO_Get_Fun(gpioPin); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Sts_Type - EF_Ctrl_Busy(void) -{ - return RomDriver_EF_Ctrl_Busy(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Sts_Type EF_Ctrl_Busy(void) { return RomDriver_EF_Ctrl_Busy(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Sw_AHB_Clk_0(void) -{ - RomDriver_EF_Ctrl_Sw_AHB_Clk_0(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Sw_AHB_Clk_0(void) { RomDriver_EF_Ctrl_Sw_AHB_Clk_0(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Load_Efuse_R0(void) -{ - RomDriver_EF_Ctrl_Load_Efuse_R0(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Load_Efuse_R0(void) { RomDriver_EF_Ctrl_Load_Efuse_R0(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Clear(uint32_t index, uint32_t len) -{ - RomDriver_EF_Ctrl_Clear(index, len); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void EF_Ctrl_Clear(uint32_t index, uint32_t len) { RomDriver_EF_Ctrl_Clear(index, len); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - uint8_t - EF_Ctrl_Get_Trim_Parity(uint32_t val, uint8_t len) -{ - return RomDriver_EF_Ctrl_Get_Trim_Parity(val, len); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION uint8_t EF_Ctrl_Get_Trim_Parity(uint32_t val, uint8_t len) { return RomDriver_EF_Ctrl_Get_Trim_Parity(val, len); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION void EF_Ctrl_Read_RC32K_Trim(Efuse_Ana_RC32K_Trim_Type *trim) -{ - RomDriver_EF_Ctrl_Read_RC32K_Trim(trim); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION void EF_Ctrl_Read_RC32K_Trim(Efuse_Ana_RC32K_Trim_Type *trim) { RomDriver_EF_Ctrl_Read_RC32K_Trim(trim); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION void EF_Ctrl_Read_RC32M_Trim(Efuse_Ana_RC32M_Trim_Type *trim) -{ - RomDriver_EF_Ctrl_Read_RC32M_Trim(trim); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION void EF_Ctrl_Read_RC32M_Trim(Efuse_Ana_RC32M_Trim_Type *trim) { RomDriver_EF_Ctrl_Read_RC32M_Trim(trim); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Trim_RC32M(void) -{ - return RomDriver_PDS_Trim_RC32M(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Trim_RC32M(void) { return RomDriver_PDS_Trim_RC32M(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Select_RC32M_As_PLL_Ref(void) -{ - return RomDriver_PDS_Select_RC32M_As_PLL_Ref(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Select_RC32M_As_PLL_Ref(void) { return RomDriver_PDS_Select_RC32M_As_PLL_Ref(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Select_XTAL_As_PLL_Ref(void) -{ - return RomDriver_PDS_Select_XTAL_As_PLL_Ref(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Select_XTAL_As_PLL_Ref(void) { return RomDriver_PDS_Select_XTAL_As_PLL_Ref(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType) -{ - return RomDriver_PDS_Power_On_PLL(xtalType); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType) { return RomDriver_PDS_Power_On_PLL(xtalType); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Enable_PLL_All_Clks(void) -{ - return RomDriver_PDS_Enable_PLL_All_Clks(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Enable_PLL_All_Clks(void) { return RomDriver_PDS_Enable_PLL_All_Clks(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Disable_PLL_All_Clks(void) -{ - return RomDriver_PDS_Disable_PLL_All_Clks(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Disable_PLL_All_Clks(void) { return RomDriver_PDS_Disable_PLL_All_Clks(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Enable_PLL_Clk(PDS_PLL_CLK_Type pllClk) -{ - return RomDriver_PDS_Enable_PLL_Clk(pllClk); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Enable_PLL_Clk(PDS_PLL_CLK_Type pllClk) { return RomDriver_PDS_Enable_PLL_Clk(pllClk); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Disable_PLL_Clk(PDS_PLL_CLK_Type pllClk) -{ - return RomDriver_PDS_Disable_PLL_Clk(pllClk); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Disable_PLL_Clk(PDS_PLL_CLK_Type pllClk) { return RomDriver_PDS_Disable_PLL_Clk(pllClk); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - PDS_Power_Off_PLL(void) -{ - return RomDriver_PDS_Power_Off_PLL(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type PDS_Power_Off_PLL(void) { return RomDriver_PDS_Power_Off_PLL(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Reset(void) -{ - RomDriver_PDS_Reset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Reset(void) { RomDriver_PDS_Reset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Enable(PDS_CFG_Type *cfg, uint32_t pdsSleepCnt) -{ - RomDriver_PDS_Enable(cfg, pdsSleepCnt); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Enable(PDS_CFG_Type *cfg, uint32_t pdsSleepCnt) { RomDriver_PDS_Enable(cfg, pdsSleepCnt); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Auto_Time_Config(uint32_t sleepDuration) -{ - RomDriver_PDS_Auto_Time_Config(sleepDuration); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Auto_Time_Config(uint32_t sleepDuration) { RomDriver_PDS_Auto_Time_Config(sleepDuration); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Auto_Enable(PDS_AUTO_POWER_DOWN_CFG_Type *powerCfg, PDS_AUTO_NORMAL_CFG_Type *normalCfg, BL_Fun_Type enable) -{ - RomDriver_PDS_Auto_Enable(powerCfg, normalCfg, enable); +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Auto_Enable(PDS_AUTO_POWER_DOWN_CFG_Type *powerCfg, PDS_AUTO_NORMAL_CFG_Type *normalCfg, BL_Fun_Type enable) { + RomDriver_PDS_Auto_Enable(powerCfg, normalCfg, enable); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Manual_Force_Turn_Off(PDS_FORCE_Type domain) -{ - RomDriver_PDS_Manual_Force_Turn_Off(domain); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Manual_Force_Turn_Off(PDS_FORCE_Type domain) { RomDriver_PDS_Manual_Force_Turn_Off(domain); } -__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Manual_Force_Turn_On(PDS_FORCE_Type domain) -{ - RomDriver_PDS_Manual_Force_Turn_On(domain); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void PDS_Manual_Force_Turn_On(PDS_FORCE_Type domain) { RomDriver_PDS_Manual_Force_Turn_On(domain); } /******************************************************************************/ /******************************************************************************/ @@ -456,379 +189,169 @@ void HBN_Enable(uint8_t aGPIOIeCfg, HBN_LDO_LEVEL_Type ldoLevel, HBN_LEVEL_Type } #endif -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - HBN_Reset(void) -{ - return RomDriver_HBN_Reset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type HBN_Reset(void) { return RomDriver_HBN_Reset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - HBN_GPIO_Dbg_Pull_Cfg(BL_Fun_Type pupdEn, BL_Fun_Type dlyEn, uint8_t dlySec, HBN_INT_Type gpioIrq, BL_Mask_Type gpioMask) -{ - return RomDriver_HBN_GPIO_Dbg_Pull_Cfg(pupdEn, dlyEn, dlySec, gpioIrq, gpioMask); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type HBN_GPIO_Dbg_Pull_Cfg(BL_Fun_Type pupdEn, BL_Fun_Type dlyEn, uint8_t dlySec, HBN_INT_Type gpioIrq, BL_Mask_Type gpioMask) { + return RomDriver_HBN_GPIO_Dbg_Pull_Cfg(pupdEn, dlyEn, dlySec, gpioIrq, gpioMask); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - HBN_Trim_RC32K(void) -{ - return RomDriver_HBN_Trim_RC32K(); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type HBN_Trim_RC32K(void) { return RomDriver_HBN_Trim_RC32K(); } -__ALWAYS_INLINE ATTR_CLOCK_SECTION - BL_Err_Type - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_Type rootClk) -{ - return RomDriver_HBN_Set_ROOT_CLK_Sel(rootClk); -} +__ALWAYS_INLINE ATTR_CLOCK_SECTION BL_Err_Type HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_Type rootClk) { return RomDriver_HBN_Set_ROOT_CLK_Sel(rootClk); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_State_Save(SPI_Flash_Cfg_Type *pFlashCfg, uint32_t *offset) -{ - return RomDriver_XIP_SFlash_State_Save(pFlashCfg, offset); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_State_Save(SPI_Flash_Cfg_Type *pFlashCfg, uint32_t *offset) { return RomDriver_XIP_SFlash_State_Save(pFlashCfg, offset); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t offset) -{ - return RomDriver_XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t offset) { + return RomDriver_XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_Erase_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t startaddr, uint32_t endaddr) -{ - return RomDriver_XIP_SFlash_Erase_Need_Lock(pFlashCfg, ioMode, startaddr, endaddr); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_Erase_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t startaddr, uint32_t endaddr) { + return RomDriver_XIP_SFlash_Erase_Need_Lock(pFlashCfg, ioMode, startaddr, endaddr); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_Write_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_XIP_SFlash_Write_Need_Lock(pFlashCfg, ioMode, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_Write_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_XIP_SFlash_Write_Need_Lock(pFlashCfg, ioMode, addr, data, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_Read_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_XIP_SFlash_Read_Need_Lock(pFlashCfg, ioMode, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_Read_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_XIP_SFlash_Read_Need_Lock(pFlashCfg, ioMode, addr, data, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_GetJedecId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) -{ - return RomDriver_XIP_SFlash_GetJedecId_Need_Lock(pFlashCfg, ioMode, data); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_GetJedecId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) { + return RomDriver_XIP_SFlash_GetJedecId_Need_Lock(pFlashCfg, ioMode, data); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_GetDeviceId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) -{ - return RomDriver_XIP_SFlash_GetDeviceId_Need_Lock(pFlashCfg, ioMode, data); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_GetDeviceId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) { + return RomDriver_XIP_SFlash_GetDeviceId_Need_Lock(pFlashCfg, ioMode, data); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_GetUniqueId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data, uint8_t idLen) -{ - return RomDriver_XIP_SFlash_GetUniqueId_Need_Lock(pFlashCfg, ioMode, data, idLen); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_GetUniqueId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data, uint8_t idLen) { + return RomDriver_XIP_SFlash_GetUniqueId_Need_Lock(pFlashCfg, ioMode, data, idLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - XIP_SFlash_Read_Via_Cache_Need_Lock(uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_XIP_SFlash_Read_Via_Cache_Need_Lock(addr, data, len); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type XIP_SFlash_Read_Via_Cache_Need_Lock(uint32_t addr, uint8_t *data, uint32_t len) { return RomDriver_XIP_SFlash_Read_Via_Cache_Need_Lock(addr, data, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Read_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *dst, int len) -{ - return RomDriver_XIP_SFlash_Read_With_Lock(pFlashCfg, ioMode, addr, dst, len); +__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Read_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *dst, int len) { + return RomDriver_XIP_SFlash_Read_With_Lock(pFlashCfg, ioMode, addr, dst, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Write_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *src, int len) -{ - return RomDriver_XIP_SFlash_Write_With_Lock(pFlashCfg, ioMode, addr, src, len); +__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Write_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *src, int len) { + return RomDriver_XIP_SFlash_Write_With_Lock(pFlashCfg, ioMode, addr, src, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Erase_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, int len) -{ - return RomDriver_XIP_SFlash_Erase_With_Lock(pFlashCfg, ioMode, addr, len); +__ALWAYS_INLINE ATTR_TCM_SECTION int XIP_SFlash_Erase_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, int len) { + return RomDriver_XIP_SFlash_Erase_With_Lock(pFlashCfg, ioMode, addr, len); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Init(const SF_Ctrl_Cfg_Type *pSfCtrlCfg) -{ - RomDriver_SFlash_Init(pSfCtrlCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Init(const SF_Ctrl_Cfg_Type *pSfCtrlCfg) { RomDriver_SFlash_Init(pSfCtrlCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_SetSPIMode(SF_Ctrl_Mode_Type mode) -{ - return RomDriver_SFlash_SetSPIMode(mode); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_SetSPIMode(SF_Ctrl_Mode_Type mode) { return RomDriver_SFlash_SetSPIMode(mode); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Read_Reg(SPI_Flash_Cfg_Type *flashCfg, uint8_t regIndex, uint8_t *regValue, uint8_t regLen) -{ - return RomDriver_SFlash_Read_Reg(flashCfg, regIndex, regValue, regLen); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Read_Reg(SPI_Flash_Cfg_Type *flashCfg, uint8_t regIndex, uint8_t *regValue, uint8_t regLen) { + return RomDriver_SFlash_Read_Reg(flashCfg, regIndex, regValue, regLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Write_Reg(SPI_Flash_Cfg_Type *flashCfg, uint8_t regIndex, uint8_t *regValue, uint8_t regLen) -{ - return RomDriver_SFlash_Write_Reg(flashCfg, regIndex, regValue, regLen); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Write_Reg(SPI_Flash_Cfg_Type *flashCfg, uint8_t regIndex, uint8_t *regValue, uint8_t regLen) { + return RomDriver_SFlash_Write_Reg(flashCfg, regIndex, regValue, regLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t readRegCmd, uint8_t *regValue, uint8_t regLen) -{ - return RomDriver_SFlash_Read_Reg_With_Cmd(flashCfg, readRegCmd, regValue, regLen); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t readRegCmd, uint8_t *regValue, uint8_t regLen) { + return RomDriver_SFlash_Read_Reg_With_Cmd(flashCfg, readRegCmd, regValue, regLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t writeRegCmd, uint8_t *regValue, uint8_t regLen) -{ - return RomDriver_SFlash_Write_Reg_With_Cmd(flashCfg, writeRegCmd, regValue, regLen); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t writeRegCmd, uint8_t *regValue, uint8_t regLen) { + return RomDriver_SFlash_Write_Reg_With_Cmd(flashCfg, writeRegCmd, regValue, regLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Sts_Type - SFlash_Busy(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Busy(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Sts_Type SFlash_Busy(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Busy(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Write_Enable(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Write_Enable(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Write_Enable(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Write_Enable(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Qspi_Enable(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Qspi_Enable(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Qspi_Enable(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Qspi_Enable(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Volatile_Reg_Write_Enable(SPI_Flash_Cfg_Type *flashCfg) -{ - RomDriver_SFlash_Volatile_Reg_Write_Enable(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Volatile_Reg_Write_Enable(SPI_Flash_Cfg_Type *flashCfg) { RomDriver_SFlash_Volatile_Reg_Write_Enable(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Chip_Erase(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Chip_Erase(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Chip_Erase(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Chip_Erase(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Sector_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t secNum) -{ - return RomDriver_SFlash_Sector_Erase(flashCfg, secNum); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Sector_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t secNum) { return RomDriver_SFlash_Sector_Erase(flashCfg, secNum); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Blk32_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t blkNum) -{ - return RomDriver_SFlash_Blk32_Erase(flashCfg, blkNum); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Blk32_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t blkNum) { return RomDriver_SFlash_Blk32_Erase(flashCfg, blkNum); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Blk64_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t blkNum) -{ - return RomDriver_SFlash_Blk64_Erase(flashCfg, blkNum); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Blk64_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t blkNum) { return RomDriver_SFlash_Blk64_Erase(flashCfg, blkNum); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t startaddr, uint32_t endaddr) -{ - return RomDriver_SFlash_Erase(flashCfg, startaddr, endaddr); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t startaddr, uint32_t endaddr) { return RomDriver_SFlash_Erase(flashCfg, startaddr, endaddr); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Program(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_SFlash_Program(flashCfg, ioMode, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Program(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_SFlash_Program(flashCfg, ioMode, addr, data, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetUniqueId(uint8_t *data, uint8_t idLen) -{ - RomDriver_SFlash_GetUniqueId(data, idLen); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetUniqueId(uint8_t *data, uint8_t idLen) { RomDriver_SFlash_GetUniqueId(data, idLen); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetJedecId(SPI_Flash_Cfg_Type *flashCfg, uint8_t *data) -{ - RomDriver_SFlash_GetJedecId(flashCfg, data); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetJedecId(SPI_Flash_Cfg_Type *flashCfg, uint8_t *data) { RomDriver_SFlash_GetJedecId(flashCfg, data); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetDeviceId(uint8_t *data) -{ - RomDriver_SFlash_GetDeviceId(data); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_GetDeviceId(uint8_t *data) { RomDriver_SFlash_GetDeviceId(data); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Powerdown(void) -{ - RomDriver_SFlash_Powerdown(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Powerdown(void) { RomDriver_SFlash_Powerdown(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Releae_Powerdown(SPI_Flash_Cfg_Type *flashCfg) -{ - RomDriver_SFlash_Releae_Powerdown(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Releae_Powerdown(SPI_Flash_Cfg_Type *flashCfg) { RomDriver_SFlash_Releae_Powerdown(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Restore_From_Powerdown(SPI_Flash_Cfg_Type *pFlashCfg, uint8_t flashContRead) -{ - return RomDriver_SFlash_Restore_From_Powerdown(pFlashCfg, flashContRead); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Restore_From_Powerdown(SPI_Flash_Cfg_Type *pFlashCfg, uint8_t flashContRead) { + return RomDriver_SFlash_Restore_From_Powerdown(pFlashCfg, flashContRead); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_SetBurstWrap(SPI_Flash_Cfg_Type *flashCfg) -{ - RomDriver_SFlash_SetBurstWrap(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_SetBurstWrap(SPI_Flash_Cfg_Type *flashCfg) { RomDriver_SFlash_SetBurstWrap(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_DisableBurstWrap(SPI_Flash_Cfg_Type *flashCfg) -{ - RomDriver_SFlash_DisableBurstWrap(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_DisableBurstWrap(SPI_Flash_Cfg_Type *flashCfg) { RomDriver_SFlash_DisableBurstWrap(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Software_Reset(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Software_Reset(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Software_Reset(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Software_Reset(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Reset_Continue_Read(SPI_Flash_Cfg_Type *flashCfg) -{ - return RomDriver_SFlash_Reset_Continue_Read(flashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Reset_Continue_Read(SPI_Flash_Cfg_Type *flashCfg) { return RomDriver_SFlash_Reset_Continue_Read(flashCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Set_IDbus_Cfg(SPI_Flash_Cfg_Type *flashCfg, - SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint32_t addr, uint32_t len) -{ - return RomDriver_SFlash_Set_IDbus_Cfg(flashCfg, ioMode, contRead, addr, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Set_IDbus_Cfg(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint32_t addr, uint32_t len) { + return RomDriver_SFlash_Set_IDbus_Cfg(flashCfg, ioMode, contRead, addr, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_IDbus_Read_Enable(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint8_t contRead) -{ - return RomDriver_SFlash_IDbus_Read_Enable(flashCfg, ioMode, contRead); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_IDbus_Read_Enable(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint8_t contRead) { + return RomDriver_SFlash_IDbus_Read_Enable(flashCfg, ioMode, contRead); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Cache_Read_Enable(SPI_Flash_Cfg_Type *flashCfg, - SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint8_t wayDisable) -{ - return RomDriver_SFlash_Cache_Read_Enable(flashCfg, ioMode, contRead, wayDisable); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Cache_Read_Enable(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint8_t wayDisable) { + return RomDriver_SFlash_Cache_Read_Enable(flashCfg, ioMode, contRead, wayDisable); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Cache_Read_Disable(void) -{ - RomDriver_SFlash_Cache_Read_Disable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SFlash_Cache_Read_Disable(void) { RomDriver_SFlash_Cache_Read_Disable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SFlash_Read(SPI_Flash_Cfg_Type *flashCfg, - SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_SFlash_Read(flashCfg, ioMode, contRead, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SFlash_Read(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode, uint8_t contRead, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_SFlash_Read(flashCfg, ioMode, contRead, addr, data, len); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - L1C_Cache_Enable_Set(uint8_t wayDisable) -{ - return RomDriver_L1C_Cache_Enable_Set(wayDisable); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type L1C_Cache_Enable_Set(uint8_t wayDisable) { return RomDriver_L1C_Cache_Enable_Set(wayDisable); } -__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Write_Set(BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) -{ - RomDriver_L1C_Cache_Write_Set(wtEn, wbEn, waEn); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Write_Set(BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) { RomDriver_L1C_Cache_Write_Set(wtEn, wbEn, waEn); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - L1C_Cache_Flush(uint8_t wayDisable) -{ - return RomDriver_L1C_Cache_Flush(wayDisable); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type L1C_Cache_Flush(uint8_t wayDisable) { return RomDriver_L1C_Cache_Flush(wayDisable); } -__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Hit_Count_Get(uint32_t *hitCountLow, uint32_t *hitCountHigh) -{ - RomDriver_L1C_Cache_Hit_Count_Get(hitCountLow, hitCountHigh); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Hit_Count_Get(uint32_t *hitCountLow, uint32_t *hitCountHigh) { RomDriver_L1C_Cache_Hit_Count_Get(hitCountLow, hitCountHigh); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t - L1C_Cache_Miss_Count_Get(void) -{ - return RomDriver_L1C_Cache_Miss_Count_Get(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t L1C_Cache_Miss_Count_Get(void) { return RomDriver_L1C_Cache_Miss_Count_Get(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Read_Disable(void) -{ - RomDriver_L1C_Cache_Read_Disable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void L1C_Cache_Read_Disable(void) { RomDriver_L1C_Cache_Read_Disable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - L1C_Set_Wrap(BL_Fun_Type wrap) -{ - return RomDriver_L1C_Set_Wrap(wrap); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type L1C_Set_Wrap(BL_Fun_Type wrap) { return RomDriver_L1C_Set_Wrap(wrap); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - L1C_Set_Way_Disable(uint8_t disableVal) -{ - return RomDriver_L1C_Set_Way_Disable(disableVal); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type L1C_Set_Way_Disable(uint8_t disableVal) { return RomDriver_L1C_Set_Way_Disable(disableVal); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - L1C_IROM_2T_Access_Set(uint8_t enable) -{ - return RomDriver_L1C_IROM_2T_Access_Set(enable); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type L1C_IROM_2T_Access_Set(uint8_t enable) { return RomDriver_L1C_IROM_2T_Access_Set(enable); } /******************************************************************************/ /******************************************************************************/ -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Enable(const SF_Ctrl_Cfg_Type *cfg) -{ - RomDriver_SF_Ctrl_Enable(cfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Enable(const SF_Ctrl_Cfg_Type *cfg) { RomDriver_SF_Ctrl_Enable(cfg); } #if 0 __ALWAYS_INLINE ATTR_TCM_SECTION @@ -838,156 +361,63 @@ void SF_Ctrl_Psram_Init(SF_Ctrl_Psram_Cfg *sfCtrlPsramCfg) } #endif -__ALWAYS_INLINE ATTR_TCM_SECTION - uint8_t - SF_Ctrl_Get_Clock_Delay(void) -{ - return RomDriver_SF_Ctrl_Get_Clock_Delay(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint8_t SF_Ctrl_Get_Clock_Delay(void) { return RomDriver_SF_Ctrl_Get_Clock_Delay(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Clock_Delay(uint8_t delay) -{ - RomDriver_SF_Ctrl_Set_Clock_Delay(delay); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Clock_Delay(uint8_t delay) { RomDriver_SF_Ctrl_Set_Clock_Delay(delay); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Cmds_Set(SF_Ctrl_Cmds_Cfg *cmdsCfg) -{ - RomDriver_SF_Ctrl_Cmds_Set(cmdsCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Cmds_Set(SF_Ctrl_Cmds_Cfg *cmdsCfg) { RomDriver_SF_Ctrl_Cmds_Set(cmdsCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Owner(SF_Ctrl_Owner_Type owner) -{ - RomDriver_SF_Ctrl_Set_Owner(owner); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Owner(SF_Ctrl_Owner_Type owner) { RomDriver_SF_Ctrl_Set_Owner(owner); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Disable(void) -{ - RomDriver_SF_Ctrl_Disable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Disable(void) { RomDriver_SF_Ctrl_Disable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Pad(SF_Ctrl_Pad_Select sel) -{ - RomDriver_SF_Ctrl_Select_Pad(sel); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Pad(SF_Ctrl_Pad_Select sel) { RomDriver_SF_Ctrl_Select_Pad(sel); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Bank(SF_Ctrl_Select sel) -{ - RomDriver_SF_Ctrl_Select_Bank(sel); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Bank(SF_Ctrl_Select sel) { RomDriver_SF_Ctrl_Select_Bank(sel); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable_BE(void) -{ - RomDriver_SF_Ctrl_AES_Enable_BE(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable_BE(void) { RomDriver_SF_Ctrl_AES_Enable_BE(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable_LE(void) -{ - RomDriver_SF_Ctrl_AES_Enable_LE(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable_LE(void) { RomDriver_SF_Ctrl_AES_Enable_LE(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Region(uint8_t region, uint8_t enable, - uint8_t hwKey, uint32_t startAddr, uint32_t endAddr, uint8_t locked) -{ - RomDriver_SF_Ctrl_AES_Set_Region(region, enable, hwKey, startAddr, endAddr, locked); +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Region(uint8_t region, uint8_t enable, uint8_t hwKey, uint32_t startAddr, uint32_t endAddr, uint8_t locked) { + RomDriver_SF_Ctrl_AES_Set_Region(region, enable, hwKey, startAddr, endAddr, locked); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Key(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) -{ - RomDriver_SF_Ctrl_AES_Set_Key(region, key, keyType); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Key(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) { RomDriver_SF_Ctrl_AES_Set_Key(region, key, keyType); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Key_BE(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) -{ - RomDriver_SF_Ctrl_AES_Set_Key_BE(region, key, keyType); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_Key_BE(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) { RomDriver_SF_Ctrl_AES_Set_Key_BE(region, key, keyType); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_IV(uint8_t region, uint8_t *iv, uint32_t addrOffset) -{ - RomDriver_SF_Ctrl_AES_Set_IV(region, iv, addrOffset); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_IV(uint8_t region, uint8_t *iv, uint32_t addrOffset) { RomDriver_SF_Ctrl_AES_Set_IV(region, iv, addrOffset); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_IV_BE(uint8_t region, uint8_t *iv, uint32_t addrOffset) -{ - RomDriver_SF_Ctrl_AES_Set_IV_BE(region, iv, addrOffset); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Set_IV_BE(uint8_t region, uint8_t *iv, uint32_t addrOffset) { RomDriver_SF_Ctrl_AES_Set_IV_BE(region, iv, addrOffset); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable(void) -{ - RomDriver_SF_Ctrl_AES_Enable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Enable(void) { RomDriver_SF_Ctrl_AES_Enable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Disable(void) -{ - RomDriver_SF_Ctrl_AES_Disable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_AES_Disable(void) { RomDriver_SF_Ctrl_AES_Disable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint8_t - SF_Ctrl_Is_AES_Enable(void) -{ - return RomDriver_SF_Ctrl_Is_AES_Enable(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint8_t SF_Ctrl_Is_AES_Enable(void) { return RomDriver_SF_Ctrl_Is_AES_Enable(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Flash_Image_Offset(uint32_t addrOffset) -{ - RomDriver_SF_Ctrl_Set_Flash_Image_Offset(addrOffset); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Set_Flash_Image_Offset(uint32_t addrOffset) { RomDriver_SF_Ctrl_Set_Flash_Image_Offset(addrOffset); } -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t - SF_Ctrl_Get_Flash_Image_Offset(void) -{ - return RomDriver_SF_Ctrl_Get_Flash_Image_Offset(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t SF_Ctrl_Get_Flash_Image_Offset(void) { return RomDriver_SF_Ctrl_Get_Flash_Image_Offset(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Clock(SF_Ctrl_Sahb_Type sahbType) -{ - RomDriver_SF_Ctrl_Select_Clock(sahbType); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Select_Clock(SF_Ctrl_Sahb_Type sahbType) { RomDriver_SF_Ctrl_Select_Clock(sahbType); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_SendCmd(SF_Ctrl_Cmd_Cfg_Type *cfg) -{ - RomDriver_SF_Ctrl_SendCmd(cfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_SendCmd(SF_Ctrl_Cmd_Cfg_Type *cfg) { RomDriver_SF_Ctrl_SendCmd(cfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Flash_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - RomDriver_SF_Ctrl_Flash_Read_Icache_Set(cfg, cmdValid); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Flash_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { RomDriver_SF_Ctrl_Flash_Read_Icache_Set(cfg, cmdValid); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Psram_Write_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - RomDriver_SF_Ctrl_Psram_Write_Icache_Set(cfg, cmdValid); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Psram_Write_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { RomDriver_SF_Ctrl_Psram_Write_Icache_Set(cfg, cmdValid); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Psram_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - RomDriver_SF_Ctrl_Psram_Read_Icache_Set(cfg, cmdValid); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Ctrl_Psram_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { RomDriver_SF_Ctrl_Psram_Read_Icache_Set(cfg, cmdValid); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Sts_Type - SF_Ctrl_GetBusyState(void) -{ - return RomDriver_SF_Ctrl_GetBusyState(); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Sts_Type SF_Ctrl_GetBusyState(void) { return RomDriver_SF_Ctrl_GetBusyState(); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Cfg_Deinit_Ext_Flash_Gpio(uint8_t extFlashPin) -{ - RomDriver_SF_Cfg_Deinit_Ext_Flash_Gpio(extFlashPin); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Cfg_Deinit_Ext_Flash_Gpio(uint8_t extFlashPin) { RomDriver_SF_Cfg_Deinit_Ext_Flash_Gpio(extFlashPin); } -__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Cfg_Init_Ext_Flash_Gpio(uint8_t extFlashPin) -{ - RomDriver_SF_Cfg_Init_Ext_Flash_Gpio(extFlashPin); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void SF_Cfg_Init_Ext_Flash_Gpio(uint8_t extFlashPin) { RomDriver_SF_Cfg_Init_Ext_Flash_Gpio(extFlashPin); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) -{ - return RomDriver_SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID, pFlashCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) { return RomDriver_SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID, pFlashCfg); } #if 0 __ALWAYS_INLINE ATTR_TCM_SECTION @@ -997,12 +427,8 @@ void SF_Cfg_Init_Flash_Gpio(uint8_t flashPinCfg, uint8_t restoreDefault) } #endif -__ALWAYS_INLINE ATTR_TCM_SECTION - uint32_t - SF_Cfg_Flash_Identify(uint8_t callFromFlash, uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, - SPI_Flash_Cfg_Type *pFlashCfg) -{ - return RomDriver_SF_Cfg_Flash_Identify(callFromFlash, autoScan, flashPinCfg, restoreDefault, pFlashCfg); +__ALWAYS_INLINE ATTR_TCM_SECTION uint32_t SF_Cfg_Flash_Identify(uint8_t callFromFlash, uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, SPI_Flash_Cfg_Type *pFlashCfg) { + return RomDriver_SF_Cfg_Flash_Identify(callFromFlash, autoScan, flashPinCfg, restoreDefault, pFlashCfg); } /******************************************************************************/ @@ -1015,92 +441,37 @@ void Psram_Init(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_Cmds_Cfg *cmdsCfg, SF_Ctrl } #endif -__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_ReadReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) -{ - RomDriver_Psram_ReadReg(psramCfg, regValue); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_ReadReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) { RomDriver_Psram_ReadReg(psramCfg, regValue); } -__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_WriteReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) -{ - RomDriver_Psram_WriteReg(psramCfg, regValue); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_WriteReg(SPI_Psram_Cfg_Type *psramCfg, uint8_t *regValue) { RomDriver_Psram_WriteReg(psramCfg, regValue); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_SetDriveStrength(SPI_Psram_Cfg_Type *psramCfg) -{ - return RomDriver_Psram_SetDriveStrength(psramCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_SetDriveStrength(SPI_Psram_Cfg_Type *psramCfg) { return RomDriver_Psram_SetDriveStrength(psramCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_SetBurstWrap(SPI_Psram_Cfg_Type *psramCfg) -{ - return RomDriver_Psram_SetBurstWrap(psramCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_SetBurstWrap(SPI_Psram_Cfg_Type *psramCfg) { return RomDriver_Psram_SetBurstWrap(psramCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_ReadId(SPI_Psram_Cfg_Type *psramCfg, uint8_t *data) -{ - RomDriver_Psram_ReadId(psramCfg, data); -} +__ALWAYS_INLINE ATTR_TCM_SECTION void Psram_ReadId(SPI_Psram_Cfg_Type *psramCfg, uint8_t *data) { RomDriver_Psram_ReadId(psramCfg, data); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_EnterQuadMode(SPI_Psram_Cfg_Type *psramCfg) -{ - return RomDriver_Psram_EnterQuadMode(psramCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_EnterQuadMode(SPI_Psram_Cfg_Type *psramCfg) { return RomDriver_Psram_EnterQuadMode(psramCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_ExitQuadMode(SPI_Psram_Cfg_Type *psramCfg) -{ - return RomDriver_Psram_ExitQuadMode(psramCfg); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_ExitQuadMode(SPI_Psram_Cfg_Type *psramCfg) { return RomDriver_Psram_ExitQuadMode(psramCfg); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_ToggleBurstLength(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) -{ - return RomDriver_Psram_ToggleBurstLength(psramCfg, ctrlMode); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_ToggleBurstLength(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) { return RomDriver_Psram_ToggleBurstLength(psramCfg, ctrlMode); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_SoftwareReset(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) -{ - return RomDriver_Psram_SoftwareReset(psramCfg, ctrlMode); -} +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_SoftwareReset(SPI_Psram_Cfg_Type *psramCfg, PSRAM_Ctrl_Mode ctrlMode) { return RomDriver_Psram_SoftwareReset(psramCfg, ctrlMode); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_Set_IDbus_Cfg(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint32_t len) -{ - return RomDriver_Psram_Set_IDbus_Cfg(psramCfg, ioMode, addr, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_Set_IDbus_Cfg(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint32_t len) { + return RomDriver_Psram_Set_IDbus_Cfg(psramCfg, ioMode, addr, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_Cache_Write_Set(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, - BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) -{ - return RomDriver_Psram_Cache_Write_Set(psramCfg, ioMode, wtEn, wbEn, waEn); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_Cache_Write_Set(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, BL_Fun_Type wtEn, BL_Fun_Type wbEn, BL_Fun_Type waEn) { + return RomDriver_Psram_Cache_Write_Set(psramCfg, ioMode, wtEn, wbEn, waEn); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_Write(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_Psram_Write(psramCfg, ioMode, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_Write(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_Psram_Write(psramCfg, ioMode, addr, data, len); } -__ALWAYS_INLINE ATTR_TCM_SECTION - BL_Err_Type - Psram_Read(SPI_Psram_Cfg_Type *psramCfg, - SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - return RomDriver_Psram_Read(psramCfg, ioMode, addr, data, len); +__ALWAYS_INLINE ATTR_TCM_SECTION BL_Err_Type Psram_Read(SPI_Psram_Cfg_Type *psramCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + return RomDriver_Psram_Read(psramCfg, ioMode, addr, data, len); } /******************************************************************************/ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_dbg.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_dbg.c index 0db07bef1..214761ae5 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_dbg.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_dbg.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_sec_dbg.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sec_dbg.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "string.h" #include "bl702_sec_dbg.h" +#include "string.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -80,69 +80,61 @@ */ /****************************************************************************/ /** - * @brief Sec Dbg read chip ID - * - * @param id[8]: chip ID buffer - * - * @return None - * -*******************************************************************************/ -void Sec_Dbg_Read_Chip_ID(uint8_t id[8]) -{ - uint32_t idLow, idHigh; - - idLow = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_CHIP_ID_LOW); - BL_WRWD_TO_BYTEP(id, idLow); - - idHigh = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_CHIP_ID_HIGH); - BL_WRWD_TO_BYTEP((id + 4), idHigh); + * @brief Sec Dbg read chip ID + * + * @param id[8]: chip ID buffer + * + * @return None + * + *******************************************************************************/ +void Sec_Dbg_Read_Chip_ID(uint8_t id[8]) { + uint32_t idLow, idHigh; + + idLow = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_CHIP_ID_LOW); + BL_WRWD_TO_BYTEP(id, idLow); + + idHigh = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_CHIP_ID_HIGH); + BL_WRWD_TO_BYTEP((id + 4), idHigh); } /****************************************************************************/ /** - * @brief Sec Dbg read MAC address - * - * @param macAddr[6]: MAC address buffer - * - * @return None - * -*******************************************************************************/ -void Sec_Dbg_Read_WiFi_MAC(uint8_t macAddr[6]) -{ - uint32_t macLow, macHigh; - - macLow = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_WIFI_MAC_LOW); - BL_WRWD_TO_BYTEP(macAddr, macLow); - - macHigh = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_WIFI_MAC_HIGH); - macAddr[4] = (macHigh >> 0) & 0xff; - macAddr[5] = (macHigh >> 8) & 0xff; + * @brief Sec Dbg read MAC address + * + * @param macAddr[6]: MAC address buffer + * + * @return None + * + *******************************************************************************/ +void Sec_Dbg_Read_WiFi_MAC(uint8_t macAddr[6]) { + uint32_t macLow, macHigh; + + macLow = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_WIFI_MAC_LOW); + BL_WRWD_TO_BYTEP(macAddr, macLow); + + macHigh = BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_WIFI_MAC_HIGH); + macAddr[4] = (macHigh >> 0) & 0xff; + macAddr[5] = (macHigh >> 8) & 0xff; } /****************************************************************************/ /** - * @brief Sec Dbg read debug mode - * - * @param None - * - * @return debug mode status - * -*******************************************************************************/ -uint32_t Sec_Dbg_Read_Dbg_Mode(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_STATUS), SEC_DBG_SD_DBG_MODE); -} + * @brief Sec Dbg read debug mode + * + * @param None + * + * @return debug mode status + * + *******************************************************************************/ +uint32_t Sec_Dbg_Read_Dbg_Mode(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_STATUS), SEC_DBG_SD_DBG_MODE); } /****************************************************************************/ /** - * @brief Sec Dbg read debug enable status - * - * @param None - * - * @return enable status - * -*******************************************************************************/ -uint32_t Sec_Dbg_Read_Dbg_Enable(void) -{ - return BL_GET_REG_BITS_VAL(BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_STATUS), SEC_DBG_SD_DBG_ENA); -} + * @brief Sec Dbg read debug enable status + * + * @param None + * + * @return enable status + * + *******************************************************************************/ +uint32_t Sec_Dbg_Read_Dbg_Enable(void) { return BL_GET_REG_BITS_VAL(BL_RD_REG(SEC_DBG_BASE, SEC_DBG_SD_STATUS), SEC_DBG_SD_DBG_ENA); } /*@} end of group SEC_DBG_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c index 8939276de..acff27d1c 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sec_eng.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_sec_eng.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sec_eng.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "string.h" #include "bl702_sec_eng.h" +#include "string.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -48,24 +48,24 @@ /** @defgroup SEC_ENG_Private_Macros * @{ */ -#define PUT_UINT32_BE(n, b, i) \ - { \ - (b)[(i)] = (uint8_t)((n) >> 24); \ - (b)[(i) + 1] = (uint8_t)((n) >> 16); \ - (b)[(i) + 2] = (uint8_t)((n) >> 8); \ - (b)[(i) + 3] = (uint8_t)((n)); \ - } -#define PUT_UINT64_BE(n, b, i) \ - { \ - (b)[(i)] = (uint8_t)((n) >> 56); \ - (b)[(i) + 1] = (uint8_t)((n) >> 48); \ - (b)[(i) + 2] = (uint8_t)((n) >> 40); \ - (b)[(i) + 3] = (uint8_t)((n) >> 32); \ - (b)[(i) + 4] = (uint8_t)((n) >> 24); \ - (b)[(i) + 5] = (uint8_t)((n) >> 16); \ - (b)[(i) + 6] = (uint8_t)((n) >> 8); \ - (b)[(i) + 7] = (uint8_t)((n)); \ - } +#define PUT_UINT32_BE(n, b, i) \ + { \ + (b)[(i)] = (uint8_t)((n) >> 24); \ + (b)[(i) + 1] = (uint8_t)((n) >> 16); \ + (b)[(i) + 2] = (uint8_t)((n) >> 8); \ + (b)[(i) + 3] = (uint8_t)((n)); \ + } +#define PUT_UINT64_BE(n, b, i) \ + { \ + (b)[(i)] = (uint8_t)((n) >> 56); \ + (b)[(i) + 1] = (uint8_t)((n) >> 48); \ + (b)[(i) + 2] = (uint8_t)((n) >> 40); \ + (b)[(i) + 3] = (uint8_t)((n) >> 32); \ + (b)[(i) + 4] = (uint8_t)((n) >> 24); \ + (b)[(i) + 5] = (uint8_t)((n) >> 16); \ + (b)[(i) + 6] = (uint8_t)((n) >> 8); \ + (b)[(i) + 7] = (uint8_t)((n)); \ + } #define SEC_ENG_SHA_BUSY_TIMEOUT_COUNT (100 * 160 * 1000) #define SEC_ENG_AES_BUSY_TIMEOUT_COUNT (100 * 160 * 1000) #define SEC_ENG_TRNG_BUSY_TIMEOUT_COUNT (100 * 160 * 1000) @@ -78,96 +78,89 @@ * @{ */ struct pka0_pld_cfg { - union { - struct - { - uint32_t size : 12; /*[11: 0], r/w, 0x0 */ - uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ - uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t op : 7; /*[30:24], r/w, 0x0 */ - uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t size : 12; /*[11: 0], r/w, 0x0 */ + uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ + uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t op : 7; /*[30:24], r/w, 0x0 */ + uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_pldi_cfg { - union { - struct - { - uint32_t rsvd : 12; /*[11: 0], r/w, 0x0 */ - uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ - uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t op : 7; /*[30:24], r/w, 0x0 */ - uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t rsvd : 12; /*[11: 0], r/w, 0x0 */ + uint32_t d_reg_index : 8; /*[19:12], r/w, 0x0 */ + uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t op : 7; /*[30:24], r/w, 0x0 */ + uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_common_op_first_cfg { - union { - struct - { - uint32_t s0_reg_idx : 8; /*[7: 0], r/w, 0x0 */ - uint32_t s0_reg_type : 4; /*[11:8], r/w, 0x0 */ - uint32_t d_reg_idx : 8; /*[19:12], r/w, 0x0 */ - uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t op : 7; /*[30:24], r/w, 0x0 */ - uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t s0_reg_idx : 8; /*[7: 0], r/w, 0x0 */ + uint32_t s0_reg_type : 4; /*[11:8], r/w, 0x0 */ + uint32_t d_reg_idx : 8; /*[19:12], r/w, 0x0 */ + uint32_t d_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t op : 7; /*[30:24], r/w, 0x0 */ + uint32_t last_op : 1; /*[31:31], r/w, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_common_op_snd_cfg_S1_only { - union { - struct - { - uint32_t reserved_0_11 : 12; /*[11: 0], rsvd, 0x0 */ - uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ - uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t reserved_0_11 : 12; /*[11: 0], rsvd, 0x0 */ + uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ + uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_common_op_snd_cfg_S2_only { - union { - struct - { - uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ - uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ - uint32_t reserved_12_31 : 20; /*[31:12], rsvd, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ + uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ + uint32_t reserved_12_31 : 20; /*[31:12], rsvd, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_common_op_snd_cfg_S1_S2 { - union { - struct - { - uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ - uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ - uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ - uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ - uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t s2_reg_idx : 8; /*[7 : 0], r/w, 0x0 */ + uint32_t s2_reg_type : 4; /*[11: 8], r/w, 0x0 */ + uint32_t s1_reg_idx : 8; /*[19:12], r/w, 0x0 */ + uint32_t s1_reg_type : 4; /*[23:20], r/w, 0x0 */ + uint32_t reserved_24_31 : 8; /*[31:24], rsvd, 0x0 */ + } BF; + uint32_t WORD; + } value; }; struct pka0_bit_shift_op_cfg { - union { - struct - { - uint32_t bit_shift : 15; /*[14: 0], r/w, 0x0 */ - uint32_t reserved_24_31 : 17; /*[31:15], rsvd, 0x0 */ - } BF; - uint32_t WORD; - } value; + union { + struct { + uint32_t bit_shift : 15; /*[14: 0], r/w, 0x0 */ + uint32_t reserved_24_31 : 17; /*[31:15], rsvd, 0x0 */ + } BF; + uint32_t WORD; + } value; }; /*@} end of group SEC_ENG_Private_Types */ @@ -175,7 +168,7 @@ struct pka0_bit_shift_op_cfg { /** @defgroup SEC_ENG_Private_Variables * @{ */ -static intCallback_Type *secEngIntCbfArra[SEC_ENG_INT_ALL] = { NULL }; +static intCallback_Type *secEngIntCbfArra[SEC_ENG_INT_ALL] = {NULL}; /*@} end of group SEC_ENG_Private_Variables */ @@ -196,3188 +189,3045 @@ static intCallback_Type *secEngIntCbfArra[SEC_ENG_INT_ALL] = { NULL }; */ /****************************************************************************/ /** - * @brief SHA256 initialization function - * - * @param shaCtx: SHA256 context pointer - * @param shaNo: SHA ID type - * @param shaType: SHA type - * @param shaTmpBuf[16]: SHA temp buffer for store data that is less than 64 bytes - * @param padding[16]: SHA padding buffer for store padding data - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_SHA256_Init(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, SEC_ENG_SHA_Type shaType, uint32_t shaTmpBuf[16], uint32_t padding[16]) -{ - uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); - CHECK_PARAM(IS_SEC_ENG_SHA_TYPE(shaType)); - - /* Deal SHA control register to set SHA mode */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MODE, shaType); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - - /* Clear context */ - memset(shaCtx, 0, sizeof(SEC_Eng_SHA256_Ctx)); - - /* Init temp buffer and padding buffer */ - shaCtx->shaBuf = shaTmpBuf; - shaCtx->shaPadding = padding; - BL702_MemSet(shaCtx->shaPadding, 0, 64); - BL702_MemSet(shaCtx->shaPadding, 0x80, 1); + * @brief SHA256 initialization function + * + * @param shaCtx: SHA256 context pointer + * @param shaNo: SHA ID type + * @param shaType: SHA type + * @param shaTmpBuf[16]: SHA temp buffer for store data that is less than 64 bytes + * @param padding[16]: SHA padding buffer for store padding data + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_SHA256_Init(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, SEC_ENG_SHA_Type shaType, uint32_t shaTmpBuf[16], uint32_t padding[16]) { + uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + CHECK_PARAM(IS_SEC_ENG_SHA_TYPE(shaType)); + + /* Deal SHA control register to set SHA mode */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MODE, shaType); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + + /* Clear context */ + memset(shaCtx, 0, sizeof(SEC_Eng_SHA256_Ctx)); + + /* Init temp buffer and padding buffer */ + shaCtx->shaBuf = shaTmpBuf; + shaCtx->shaPadding = padding; + BL702_MemSet(shaCtx->shaPadding, 0, 64); + BL702_MemSet(shaCtx->shaPadding, 0x80, 1); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_SHA_IRQn, SEC_SHA_IRQHandler); + Interrupt_Handler_Register(SEC_SHA_IRQn, SEC_SHA_IRQHandler); #endif } /****************************************************************************/ /** - * @brief SHA start function - * - * @param shaNo: SHA ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_SHA_Start(SEC_ENG_SHA_ID_Type shaNo) -{ - uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; - uint32_t tmpVal; + * @brief SHA start function + * + * @param shaNo: SHA ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_SHA_Start(SEC_ENG_SHA_ID_Type shaNo) { + uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); - /* Set SHA enable */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + /* Set SHA enable */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_EN); - /* Hash sel 0 for new start */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_HASH_SEL); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_EN); + /* Hash sel 0 for new start */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_HASH_SEL); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); } /****************************************************************************/ /** - * @brief SHA256 update input data function - * - * @param shaCtx: SHA256 context pointer - * @param shaNo: SHA ID type - * @param input: SHA input data pointer, and the address should be word align - * @param len: SHA input data length - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_SHA256_Update(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, const uint8_t *input, uint32_t len) -{ - uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; - uint32_t tmpVal; - uint32_t fill; - uint32_t left; - uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - if (len == 0) { - return SUCCESS; - } - - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - - /* SHA need set se_sha_sel to 1 to keep the last SHA state */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_HASH_SEL, shaCtx->shaFeed); - - left = shaCtx->total[0] & 0x3F; - fill = 64 - left; + * @brief SHA256 update input data function + * + * @param shaCtx: SHA256 context pointer + * @param shaNo: SHA ID type + * @param input: SHA input data pointer, and the address should be word align + * @param len: SHA input data length + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_SHA256_Update(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, const uint8_t *input, uint32_t len) { + uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; + uint32_t tmpVal; + uint32_t fill; + uint32_t left; + uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - shaCtx->total[0] += (uint32_t)len; - shaCtx->total[0] &= 0xFFFFFFFF; + if (len == 0) { + return SUCCESS; + } - if (shaCtx->total[0] < (uint32_t)len) { - shaCtx->total[1]++; - } + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + timeoutCnt--; - if (left && len >= fill) { - BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, fill); - /* Set data source address */ - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_MSA, (uint32_t)shaCtx->shaBuf); - - /* Set data length */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MSG_LEN, 1); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - /* Trigger */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_TRIG_1T); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - - shaCtx->shaFeed = 1; - input += fill; - len -= fill; - left = 0; + if (timeoutCnt == 0) { + return TIMEOUT; } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - fill = len / 64; - len = len % 64; - - if (fill > 0) { - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + /* SHA need set se_sha_sel to 1 to keep the last SHA state */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_HASH_SEL, shaCtx->shaFeed); - /* SHA need set se_sha_sel to 1 to keep the last sha state */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_HASH_SEL, shaCtx->shaFeed); + left = shaCtx->total[0] & 0x3F; + fill = 64 - left; - /* Fill data */ - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_MSA, (uint32_t)input); + shaCtx->total[0] += (uint32_t)len; + shaCtx->total[0] &= 0xFFFFFFFF; - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MSG_LEN, fill); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + if (shaCtx->total[0] < (uint32_t)len) { + shaCtx->total[1]++; + } - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_TRIG_1T); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + if (left && len >= fill) { + BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, fill); + /* Set data source address */ + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_MSA, (uint32_t)shaCtx->shaBuf); - input += (fill * 64); - shaCtx->shaFeed = 1; - } - - if (len > 0) { - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; + /* Set data length */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MSG_LEN, 1); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + /* Trigger */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_TRIG_1T); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + shaCtx->shaFeed = 1; + input += fill; + len -= fill; + left = 0; + } - /* Copy left data into temp buffer */ - BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, len); - } + fill = len / 64; + len = len % 64; + if (fill > 0) { /* Wait finished */ timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } + if (timeoutCnt == 0) { + return TIMEOUT; + } } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief SHA256 finish to get output function - * - * @param shaCtx: SHA256 context pointer - * @param shaNo: SHA ID type - * @param hash: SHA output data of SHA result - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_SHA256_Finish(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint8_t *hash) -{ - uint32_t last, padn; - uint32_t high, low; - uint8_t shaMode; - uint8_t msgLen[8]; - uint8_t *p = (uint8_t *)hash; - uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); - - /* Wait finished */ - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + /* SHA need set se_sha_sel to 1 to keep the last sha state */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_HASH_SEL, shaCtx->shaFeed); - high = (shaCtx->total[0] >> 29) | (shaCtx->total[1] << 3); - low = (shaCtx->total[0] << 3); + /* Fill data */ + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_MSA, (uint32_t)input); - PUT_UINT32_BE(high, msgLen, 0); - PUT_UINT32_BE(low, msgLen, 4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MSG_LEN, fill); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - last = shaCtx->total[0] & 0x3F; - padn = (last < 56) ? (56 - last) : (120 - last); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_TRIG_1T); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - Sec_Eng_SHA256_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, padn); + input += (fill * 64); + shaCtx->shaFeed = 1; + } - /* Wait for shaPadding idle */ + if (len > 0) { + /* Wait finished */ timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } + if (timeoutCnt == 0) { + return TIMEOUT; + } } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - BL702_MemCpy_Fast(shaCtx->shaPadding, msgLen, 8); - Sec_Eng_SHA256_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, 8); - - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - timeoutCnt--; + /* Copy left data into temp buffer */ + BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, len); + } - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + /* Wait finished */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + do { tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - shaMode = (SEC_ENG_SHA_Type)BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MODE); - /* Copy SHA value */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_0); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_1); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_2); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_3); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_4); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - - if (shaMode == SEC_ENG_SHA224 || shaMode == SEC_ENG_SHA256) { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_5); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_6); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - - if (shaMode == SEC_ENG_SHA256) { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_7); - *p++ = (tmpVal & 0xff); - *p++ = ((tmpVal >> 8) & 0xff); - *p++ = ((tmpVal >> 16) & 0xff); - *p++ = ((tmpVal >> 24) & 0xff); - } - } + timeoutCnt--; - /* Disable SHA engine*/ + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief SHA256 finish to get output function + * + * @param shaCtx: SHA256 context pointer + * @param shaNo: SHA ID type + * @param hash: SHA output data of SHA result + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_SHA256_Finish(SEC_Eng_SHA256_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint8_t *hash) { + uint32_t last, padn; + uint32_t high, low; + uint8_t shaMode; + uint8_t msgLen[8]; + uint8_t *p = (uint8_t *)hash; + uint32_t SHAx = SEC_ENG_BASE + SEC_ENG_SHA_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + + /* Wait finished */ + do { tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_HASH_SEL); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_EN); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); - - return SUCCESS; -} + timeoutCnt--; -/****************************************************************************/ /** - * @brief SHA enable link mode and set link config address - * - * @param shaNo: SHA ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_SHA_Enable_Link(SEC_ENG_SHA_ID_Type shaNo) -{ - uint32_t SHAx = SEC_ENG_BASE; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - /* Enable sha and enable link mode */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_LINK_MODE); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, tmpVal); -} + high = (shaCtx->total[0] >> 29) | (shaCtx->total[1] << 3); + low = (shaCtx->total[0] << 3); -/****************************************************************************/ /** - * @brief SHA disable link mode - * - * @param shaNo: SHA ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_SHA_Disable_Link(SEC_ENG_SHA_ID_Type shaNo) -{ - uint32_t SHAx = SEC_ENG_BASE; - uint32_t tmpVal; + PUT_UINT32_BE(high, msgLen, 0); + PUT_UINT32_BE(low, msgLen, 4); - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + last = shaCtx->total[0] & 0x3F; + padn = (last < 56) ? (56 - last) : (120 - last); - /* Disable sha and disable link mode */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_LINK_MODE); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_EN); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, tmpVal); -} + Sec_Eng_SHA256_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, padn); -/****************************************************************************/ /** - * @brief SHA256 link mode initialization function - * - * @param shaCtx: SHA256 link mode context pointer - * @param shaNo: SHA ID type - * @param linkAddr: SHA link configure address - * @param shaTmpBuf[16]: SHA temp buffer for store data that is less than 64 bytes - * @param padding[16]: SHA padding buffer for store padding data - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_SHA256_Link_Init(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint32_t linkAddr, uint32_t shaTmpBuf[16], uint32_t padding[16]) -{ - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); - - /* Clear context */ - memset(shaCtx, 0, sizeof(SEC_Eng_SHA256_Link_Ctx)); - - /* Init temp buffer,padding buffer and link address */ - shaCtx->shaBuf = shaTmpBuf; - shaCtx->shaPadding = padding; - BL702_MemSet(shaCtx->shaPadding, 0, 64); - BL702_MemSet(shaCtx->shaPadding, 0x80, 1); - shaCtx->linkAddr = linkAddr; + /* Wait for shaPadding idle */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; -#ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_SHA_IRQn, SEC_SHA_IRQHandler); -#endif -} + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + timeoutCnt--; -/****************************************************************************/ /** - * @brief SHA256 link mode update input data function - * - * @param shaCtx: SHA256 link mode context pointer - * @param shaNo: SHA ID type - * @param input: SHA input data pointer, and the address should be word align - * @param len: SHA input data length - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_SHA256_Link_Update(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, const uint8_t *input, uint32_t len) -{ - uint32_t SHAx = SEC_ENG_BASE; - uint32_t tmpVal; - uint32_t fill; - uint32_t left; - uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - if (len == 0) { - return SUCCESS; + if (timeoutCnt == 0) { + return TIMEOUT; } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - - /* Set link address */ - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_LINK, shaCtx->linkAddr); + BL702_MemCpy_Fast(shaCtx->shaPadding, msgLen, 8); + Sec_Eng_SHA256_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, 8); - left = shaCtx->total[0] & 0x3F; - fill = 64 - left; + /* Wait finished */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - shaCtx->total[0] += (uint32_t)len; - shaCtx->total[0] &= 0xFFFFFFFF; + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + timeoutCnt--; - if (shaCtx->total[0] < (uint32_t)len) { - shaCtx->total[1]++; + if (timeoutCnt == 0) { + return TIMEOUT; } - - if (left && len >= fill) { - BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, fill); - /* Set data source address */ - *(uint32_t *)(shaCtx->linkAddr + 4) = (uint32_t)shaCtx->shaBuf; - - /* Set data length */ - *((uint16_t *)shaCtx->linkAddr + 1) = 1; - /* Trigger */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_TRIG_1T)); - - /* Choose accumulating last hash in the next time */ - *((uint32_t *)shaCtx->linkAddr) |= 0x40; - input += fill; - len -= fill; - left = 0; + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_BUSY)); + + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + shaMode = (SEC_ENG_SHA_Type)BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_SHA_MODE); + /* Copy SHA value */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_0); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_1); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_2); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_3); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_4); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + + if (shaMode == SEC_ENG_SHA224 || shaMode == SEC_ENG_SHA256) { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_5); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_6); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); + + if (shaMode == SEC_ENG_SHA256) { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_HASH_L_7); + *p++ = (tmpVal & 0xff); + *p++ = ((tmpVal >> 8) & 0xff); + *p++ = ((tmpVal >> 16) & 0xff); + *p++ = ((tmpVal >> 24) & 0xff); } + } + + /* Disable SHA engine*/ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_HASH_SEL); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_EN); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_CTRL, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief SHA enable link mode and set link config address + * + * @param shaNo: SHA ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_SHA_Enable_Link(SEC_ENG_SHA_ID_Type shaNo) { + uint32_t SHAx = SEC_ENG_BASE; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + + /* Enable sha and enable link mode */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_LINK_MODE); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, tmpVal); +} + +/****************************************************************************/ /** + * @brief SHA disable link mode + * + * @param shaNo: SHA ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_SHA_Disable_Link(SEC_ENG_SHA_ID_Type shaNo) { + uint32_t SHAx = SEC_ENG_BASE; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + + /* Disable sha and disable link mode */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_LINK_MODE); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_EN); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, tmpVal); +} + +/****************************************************************************/ /** + * @brief SHA256 link mode initialization function + * + * @param shaCtx: SHA256 link mode context pointer + * @param shaNo: SHA ID type + * @param linkAddr: SHA link configure address + * @param shaTmpBuf[16]: SHA temp buffer for store data that is less than 64 bytes + * @param padding[16]: SHA padding buffer for store padding data + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_SHA256_Link_Init(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint32_t linkAddr, uint32_t shaTmpBuf[16], uint32_t padding[16]) { + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + + /* Clear context */ + memset(shaCtx, 0, sizeof(SEC_Eng_SHA256_Link_Ctx)); + + /* Init temp buffer,padding buffer and link address */ + shaCtx->shaBuf = shaTmpBuf; + shaCtx->shaPadding = padding; + BL702_MemSet(shaCtx->shaPadding, 0, 64); + BL702_MemSet(shaCtx->shaPadding, 0x80, 1); + shaCtx->linkAddr = linkAddr; - fill = len / 64; - len = len % 64; +#ifndef BFLB_USE_HAL_DRIVER + Interrupt_Handler_Register(SEC_SHA_IRQn, SEC_SHA_IRQHandler); +#endif +} - if (fill > 0) { - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; +/****************************************************************************/ /** + * @brief SHA256 link mode update input data function + * + * @param shaCtx: SHA256 link mode context pointer + * @param shaNo: SHA ID type + * @param input: SHA input data pointer, and the address should be word align + * @param len: SHA input data length + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_SHA256_Link_Update(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, const uint8_t *input, uint32_t len) { + uint32_t SHAx = SEC_ENG_BASE; + uint32_t tmpVal; + uint32_t fill; + uint32_t left; + uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + + if (len == 0) { + return SUCCESS; + } - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - /* Fill data */ - *(uint32_t *)(shaCtx->linkAddr + 4) = (uint32_t)input; - *((uint16_t *)shaCtx->linkAddr + 1) = fill; + /* Set link address */ + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_LINK, shaCtx->linkAddr); - /* Trigger */ - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_TRIG_1T)); + left = shaCtx->total[0] & 0x3F; + fill = 64 - left; - input += (fill * 64); - /* Choose accumulating last hash in the next time */ - *((uint32_t *)shaCtx->linkAddr) |= 0x40; - } + shaCtx->total[0] += (uint32_t)len; + shaCtx->total[0] &= 0xFFFFFFFF; - if (len > 0) { - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + if (shaCtx->total[0] < (uint32_t)len) { + shaCtx->total[1]++; + } - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + if (left && len >= fill) { + BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, fill); + /* Set data source address */ + *(uint32_t *)(shaCtx->linkAddr + 4) = (uint32_t)shaCtx->shaBuf; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + /* Set data length */ + *((uint16_t *)shaCtx->linkAddr + 1) = 1; + /* Trigger */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_TRIG_1T)); - /* Copy left data into temp buffer */ - BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, len); - } + /* Choose accumulating last hash in the next time */ + *((uint32_t *)shaCtx->linkAddr) |= 0x40; + input += fill; + len -= fill; + left = 0; + } + fill = len / 64; + len = len % 64; + + if (fill > 0) { /* Wait finished */ timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } + if (timeoutCnt == 0) { + return TIMEOUT; + } } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - return SUCCESS; -} + /* Fill data */ + *(uint32_t *)(shaCtx->linkAddr + 4) = (uint32_t)input; + *((uint16_t *)shaCtx->linkAddr + 1) = fill; -/****************************************************************************/ /** - * @brief SHA256 link mode finish to get output function - * - * @param shaCtx: SHA256 link mode context pointer - * @param shaNo: SHA ID type - * @param hash: SHA output data of SHA result - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_SHA256_Link_Finish(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint8_t *hash) -{ - uint32_t last, padn; - uint32_t high, low; - uint8_t msgLen[8]; - uint32_t SHAx = SEC_ENG_BASE; - uint32_t tmpVal; - uint32_t shaMode = (*(uint32_t *)shaCtx->linkAddr) >> 2 & 0x7; - uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + /* Trigger */ + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_SHA_0_TRIG_1T)); + + input += (fill * 64); + /* Choose accumulating last hash in the next time */ + *((uint32_t *)shaCtx->linkAddr) |= 0x40; + } + if (len > 0) { /* Wait finished */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } + if (timeoutCnt == 0) { + return TIMEOUT; + } } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - /* Set link address */ - BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_LINK, shaCtx->linkAddr); + /* Copy left data into temp buffer */ + BL702_MemCpy_Fast((void *)((uint8_t *)shaCtx->shaBuf + left), input, len); + } - high = (shaCtx->total[0] >> 29) | (shaCtx->total[1] << 3); - low = (shaCtx->total[0] << 3); + /* Wait finished */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - PUT_UINT32_BE(high, msgLen, 0); - PUT_UINT32_BE(low, msgLen, 4); - - last = shaCtx->total[0] & 0x3F; - padn = (last < 56) ? (56 - last) : (120 - last); - - Sec_Eng_SHA256_Link_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, padn); - - /* Wait for shaPadding idle */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief SHA256 link mode finish to get output function + * + * @param shaCtx: SHA256 link mode context pointer + * @param shaNo: SHA ID type + * @param hash: SHA output data of SHA result + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_SHA256_Link_Finish(SEC_Eng_SHA256_Link_Ctx *shaCtx, SEC_ENG_SHA_ID_Type shaNo, uint8_t *hash) { + uint32_t last, padn; + uint32_t high, low; + uint8_t msgLen[8]; + uint32_t SHAx = SEC_ENG_BASE; + uint32_t tmpVal; + uint32_t shaMode = (*(uint32_t *)shaCtx->linkAddr) >> 2 & 0x7; + uint32_t timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_SHA_ID_TYPE(shaNo)); + + /* Wait finished */ + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - Sec_Eng_SHA256_Link_Update(shaCtx, shaNo, msgLen, 8); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - /* Wait finished */ - timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; + /* Set link address */ + BL_WR_REG(SHAx, SEC_ENG_SE_SHA_0_LINK, shaCtx->linkAddr); - do { - tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); - timeoutCnt--; + high = (shaCtx->total[0] >> 29) | (shaCtx->total[1] << 3); + low = (shaCtx->total[0] << 3); - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + PUT_UINT32_BE(high, msgLen, 0); + PUT_UINT32_BE(low, msgLen, 4); - /* Get result according to SHA mode,result is placed in (link address + offset:8) */ - switch (shaMode) { - case 0: - BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 32); - break; + last = shaCtx->total[0] & 0x3F; + padn = (last < 56) ? (56 - last) : (120 - last); - case 1: - BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 28); - break; + Sec_Eng_SHA256_Link_Update(shaCtx, shaNo, (uint8_t *)shaCtx->shaPadding, padn); - case 2: - BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 20); - break; + /* Wait for shaPadding idle */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; - case 3: - BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 20); - break; + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - default: - break; + if (timeoutCnt == 0) { + return TIMEOUT; } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); - /* Choose new hash in the next time */ - *((uint32_t *)shaCtx->linkAddr) &= ~0x40; + Sec_Eng_SHA256_Link_Update(shaCtx, shaNo, msgLen, 8); - return SUCCESS; -} + /* Wait finished */ + timeoutCnt = SEC_ENG_SHA_BUSY_TIMEOUT_COUNT; -/****************************************************************************/ /** - * @brief AES initialization function - * - * @param aesCtx: AES context pointer - * @param aesNo: AES ID type - * @param aesType: AES type:ECB,CTR,CBC - * @param keyType: AES key type:128,256,192 - * @param enDecType: AES encryption or decryption - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_AES_Init(SEC_Eng_AES_Ctx *aesCtx, SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Type aesType, SEC_ENG_AES_Key_Type keyType, SEC_ENG_AES_EnDec_Type enDecType) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - CHECK_PARAM(IS_SEC_ENG_AES_TYPE(aesType)); - CHECK_PARAM(IS_SEC_ENG_AES_KEY_TYPE(keyType)); - CHECK_PARAM(IS_SEC_ENG_AES_ENDEC_TYPE(enDecType)); + do { + tmpVal = BL_RD_REG(SHAx, SEC_ENG_SE_SHA_0_CTRL); + timeoutCnt--; - /* Wait finished */ - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - timeoutCnt--; + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_SHA_0_BUSY)); + + /* Get result according to SHA mode,result is placed in (link address + offset:8) */ + switch (shaMode) { + case 0: + BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 32); + break; + + case 1: + BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 28); + break; + + case 2: + BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 20); + break; + + case 3: + BL702_MemCpy_Fast(hash, (uint8_t *)(shaCtx->linkAddr + 8), 20); + break; + + default: + break; + } + + /* Choose new hash in the next time */ + *((uint32_t *)shaCtx->linkAddr) &= ~0x40; + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief AES initialization function + * + * @param aesCtx: AES context pointer + * @param aesNo: AES ID type + * @param aesType: AES type:ECB,CTR,CBC + * @param keyType: AES key type:128,256,192 + * @param enDecType: AES encryption or decryption + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_AES_Init(SEC_Eng_AES_Ctx *aesCtx, SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Type aesType, SEC_ENG_AES_Key_Type keyType, SEC_ENG_AES_EnDec_Type enDecType) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + CHECK_PARAM(IS_SEC_ENG_AES_TYPE(aesType)); + CHECK_PARAM(IS_SEC_ENG_AES_KEY_TYPE(keyType)); + CHECK_PARAM(IS_SEC_ENG_AES_ENDEC_TYPE(enDecType)); + + /* Wait finished */ + do { + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); - /* Set AES mode type*/ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_BLOCK_MODE, aesType); + /* Set AES mode type*/ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_BLOCK_MODE, aesType); - /* Set AES key type */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE, keyType); + /* Set AES key type */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE, keyType); - /* Set AES encryption or decryption */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_DEC_EN, enDecType); + /* Set AES encryption or decryption */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_DEC_EN, enDecType); - /* Clear dec_key_sel to select new key */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); + /* Clear dec_key_sel to select new key */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); - /* Clear aes iv sel to select new iv */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_IV_SEL); + /* Clear aes iv sel to select new iv */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_IV_SEL); - /* Clear AES interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_INT_CLR_1T); + /* Clear AES interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_INT_CLR_1T); - /* Enable AES */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_EN); + /* Enable AES */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_EN); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - /* Clear AES context */ - memset(aesCtx, 0, sizeof(SEC_Eng_AES_Ctx)); + /* Clear AES context */ + memset(aesCtx, 0, sizeof(SEC_Eng_AES_Ctx)); - /* Enable ID0 Access for HW Key */ - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_AES_0_CTRL_PROT, 0x03); + /* Enable ID0 Access for HW Key */ + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_AES_0_CTRL_PROT, 0x03); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); + Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief AES enable function,set AES bigendian - * - * @param aesNo: AES ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID_Type aesNo) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + * @brief AES enable function,set AES bigendian + * + * @param aesNo: AES ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID_Type aesNo) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - BL_WR_REG(AESx, SEC_ENG_SE_AES_ENDIAN, 0x0f); + BL_WR_REG(AESx, SEC_ENG_SE_AES_ENDIAN, 0x0f); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); + Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); #endif } /****************************************************************************/ /** - * @brief AES enable function,set AES littleendian - * - * @param aesNo: AES ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Enable_LE(SEC_ENG_AES_ID_Type aesNo) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + * @brief AES enable function,set AES littleendian + * + * @param aesNo: AES ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Enable_LE(SEC_ENG_AES_ID_Type aesNo) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - BL_WR_REG(AESx, SEC_ENG_SE_AES_ENDIAN, 0x00); + BL_WR_REG(AESx, SEC_ENG_SE_AES_ENDIAN, 0x00); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); + Interrupt_Handler_Register(SEC_AES_IRQn, SEC_AES_IRQHandler); #endif } /****************************************************************************/ /** - * @brief AES enable link mode - * - * @param aesNo: AES ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Enable_Link(SEC_ENG_AES_ID_Type aesNo) -{ - uint32_t AESx = SEC_ENG_BASE; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - - /* Enable aes link mode */ - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_LINK_MODE)); - - /* Enable ID0 Access for HW Key */ - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_AES_0_CTRL_PROT, 0x03); -} - -/****************************************************************************/ /** - * @brief AES disable link mode - * - * @param aesNo: AES ID type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Disable_Link(SEC_ENG_AES_ID_Type aesNo) -{ - uint32_t AESx = SEC_ENG_BASE; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - - /* Disable aes link mode */ + * @brief AES enable link mode + * + * @param aesNo: AES ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Enable_Link(SEC_ENG_AES_ID_Type aesNo) { + uint32_t AESx = SEC_ENG_BASE; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + + /* Enable aes link mode */ + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_LINK_MODE)); + + /* Enable ID0 Access for HW Key */ + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_AES_0_CTRL_PROT, 0x03); +} + +/****************************************************************************/ /** + * @brief AES disable link mode + * + * @param aesNo: AES ID type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Disable_Link(SEC_ENG_AES_ID_Type aesNo) { + uint32_t AESx = SEC_ENG_BASE; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + + /* Disable aes link mode */ + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_LINK_MODE)); +} + +/****************************************************************************/ /** + * @brief AES work in link mode + * + * @param aesNo: AES ID type + * @param linkAddr: Address of config structure in link mode + * @param in: AES input data buffer to deal with + * @param len: AES input data length + * @param out: AES output data buffer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_AES_Link_Work(SEC_ENG_AES_ID_Type aesNo, uint32_t linkAddr, const uint8_t *in, uint32_t len, uint8_t *out) { + uint32_t AESx = SEC_ENG_BASE; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + + /* Link address should word align */ + if ((linkAddr & 0x03) != 0 || len % 16 != 0) { + return ERROR; + } + + /* Wait finished */ + do { tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_LINK_MODE)); -} + timeoutCnt--; -/****************************************************************************/ /** - * @brief AES work in link mode - * - * @param aesNo: AES ID type - * @param linkAddr: Address of config structure in link mode - * @param in: AES input data buffer to deal with - * @param len: AES input data length - * @param out: AES output data buffer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_AES_Link_Work(SEC_ENG_AES_ID_Type aesNo, uint32_t linkAddr, const uint8_t *in, uint32_t len, uint8_t *out) -{ - uint32_t AESx = SEC_ENG_BASE; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - - /* Link address should word align */ - if ((linkAddr & 0x03) != 0 || len % 16 != 0) { - return ERROR; + if (timeoutCnt == 0) { + return TIMEOUT; } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_0_BUSY)); - /* Wait finished */ - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_0_BUSY)); + /* Set link address */ + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_LINK, linkAddr); - /* Set link address */ - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_LINK, linkAddr); + /* Change source buffer address and destination buffer address */ + *(uint32_t *)(linkAddr + 4) = (uint32_t)in; + *(uint32_t *)(linkAddr + 8) = (uint32_t)out; - /* Change source buffer address and destination buffer address */ - *(uint32_t *)(linkAddr + 4) = (uint32_t)in; - *(uint32_t *)(linkAddr + 8) = (uint32_t)out; + /* Set data length */ + *((uint16_t *)linkAddr + 1) = len / 16; - /* Set data length */ - *((uint16_t *)linkAddr + 1) = len / 16; + /* Enable aes */ + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_EN)); - /* Enable aes */ - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_EN)); + /* Start aes engine and wait finishing */ + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_TRIG_1T)); + __NOP(); + __NOP(); + timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - /* Start aes engine and wait finishing */ + do { tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_TRIG_1T)); - __NOP(); - __NOP(); - timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_CTRL); - timeoutCnt--; + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_0_BUSY)); - - /* Disable aes */ - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_EN)); - - return SUCCESS; -} + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_0_BUSY)); + + /* Disable aes */ + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_CTRL, BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_0_EN)); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief AES set hardware key source:efuse region for CPU0 or region efuse for CPU1 + * + * @param aesNo: AES ID type + * @param src: AES key source type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Set_Hw_Key_Src(SEC_ENG_AES_ID_Type aesNo, uint8_t src) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_SBOOT); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_SBOOT_KEY_SEL, src); + + BL_WR_REG(AESx, SEC_ENG_SE_AES_SBOOT, tmpVal); +} + +/****************************************************************************/ /** + * @brief AES set KEY and IV + * + * @param aesNo: AES ID type + * @param keySrc: AES KEY type:SEC_ENG_AES_KEY_HW or SEC_ENG_AES_KEY_SW + * @param key: AES KEY pointer + * @param iv: AES IV pointer + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Set_Key_IV(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Key_Src_Type keySrc, const uint8_t *key, const uint8_t *iv) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + uint32_t keyType; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + CHECK_PARAM(IS_SEC_ENG_AES_KEY_SRC_TYPE(keySrc)); + + /* Set IV */ + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_3, __REV(BL_RDWD_FRM_BYTEP(iv))); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_2, __REV(BL_RDWD_FRM_BYTEP(iv))); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_1, __REV(BL_RDWD_FRM_BYTEP(iv))); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_0, __REV(BL_RDWD_FRM_BYTEP(iv))); + iv += 4; + + /* Select hardware key */ + if (keySrc == SEC_ENG_AES_KEY_HW) { + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_HW); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); -/****************************************************************************/ /** - * @brief AES set hardware key source:efuse region for CPU0 or region efuse for CPU1 - * - * @param aesNo: AES ID type - * @param src: AES key source type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Set_Hw_Key_Src(SEC_ENG_AES_ID_Type aesNo, uint8_t src) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_0, *key); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0, tmpVal); - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_1, *key); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1, tmpVal); - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_SBOOT); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_SBOOT_KEY_SEL, src); + return; + } - BL_WR_REG(AESx, SEC_ENG_SE_AES_SBOOT, tmpVal); -} + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_7, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_6, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; -/****************************************************************************/ /** - * @brief AES set KEY and IV - * - * @param aesNo: AES ID type - * @param keySrc: AES KEY type:SEC_ENG_AES_KEY_HW or SEC_ENG_AES_KEY_SW - * @param key: AES KEY pointer - * @param iv: AES IV pointer - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Set_Key_IV(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Key_Src_Type keySrc, const uint8_t *key, const uint8_t *iv) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; - uint32_t keyType; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - CHECK_PARAM(IS_SEC_ENG_AES_KEY_SRC_TYPE(keySrc)); - - /* Set IV */ - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_3, __REV(BL_RDWD_FRM_BYTEP(iv))); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_2, __REV(BL_RDWD_FRM_BYTEP(iv))); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_1, __REV(BL_RDWD_FRM_BYTEP(iv))); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_0, __REV(BL_RDWD_FRM_BYTEP(iv))); - iv += 4; - - /* Select hardware key */ - if (keySrc == SEC_ENG_AES_KEY_HW) { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_HW); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_0, *key); - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0, tmpVal); - - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_1, *key); - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1, tmpVal); - - return; - } + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + keyType = BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE); - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_7, __REV(BL_RDWD_FRM_BYTEP(key))); + if (keyType == (uint32_t)SEC_ENG_AES_KEY_192BITS) { + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, __REV(BL_RDWD_FRM_BYTEP(key))); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_6, __REV(BL_RDWD_FRM_BYTEP(key))); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, __REV(BL_RDWD_FRM_BYTEP(key))); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, __REV(BL_RDWD_FRM_BYTEP(key))); + } else if (keyType == (uint32_t)SEC_ENG_AES_KEY_256BITS || keyType == (uint32_t)SEC_ENG_AES_DOUBLE_KEY_128BITS) { + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, __REV(BL_RDWD_FRM_BYTEP(key))); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, __REV(BL_RDWD_FRM_BYTEP(key))); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, __REV(BL_RDWD_FRM_BYTEP(key))); key += 4; - + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_1, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_0, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + } + + /* Select software key */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_SW); + + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); +} + +/****************************************************************************/ /** + * @brief AES set KEY and IV with bigendian + * + * @param aesNo: AES ID type + * @param keySrc: AES KEY type:SEC_ENG_AES_KEY_HW or SEC_ENG_AES_KEY_SW + * @param key: AES KEY pointer + * @param iv: AES IV pointer + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Key_Src_Type keySrc, const uint8_t *key, const uint8_t *iv) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + uint32_t keyType; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + CHECK_PARAM(IS_SEC_ENG_AES_KEY_SRC_TYPE(keySrc)); + + /* Set IV */ + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_0, BL_RDWD_FRM_BYTEP(iv)); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_1, BL_RDWD_FRM_BYTEP(iv)); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_2, BL_RDWD_FRM_BYTEP(iv)); + iv += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_3, BL_RDWD_FRM_BYTEP(iv)); + iv += 4; + + /* Select hardware key */ + if (keySrc == SEC_ENG_AES_KEY_HW) { tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - keyType = BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE); - - if (keyType == (uint32_t)SEC_ENG_AES_KEY_192BITS) { - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - } else if (keyType == (uint32_t)SEC_ENG_AES_KEY_256BITS || keyType == (uint32_t)SEC_ENG_AES_DOUBLE_KEY_128BITS) { - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_1, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_0, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - } + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_HW); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - /* Select software key */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_SW); + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_0, *key); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0, tmpVal); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); -} + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_1, *key); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1, tmpVal); -/****************************************************************************/ /** - * @brief AES set KEY and IV with bigendian - * - * @param aesNo: AES ID type - * @param keySrc: AES KEY type:SEC_ENG_AES_KEY_HW or SEC_ENG_AES_KEY_SW - * @param key: AES KEY pointer - * @param iv: AES IV pointer - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Key_Src_Type keySrc, const uint8_t *key, const uint8_t *iv) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; - uint32_t keyType; - - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - CHECK_PARAM(IS_SEC_ENG_AES_KEY_SRC_TYPE(keySrc)); - - /* Set IV */ - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_0, BL_RDWD_FRM_BYTEP(iv)); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_1, BL_RDWD_FRM_BYTEP(iv)); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_2, BL_RDWD_FRM_BYTEP(iv)); - iv += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_IV_3, BL_RDWD_FRM_BYTEP(iv)); - iv += 4; - - /* Select hardware key */ - if (keySrc == SEC_ENG_AES_KEY_HW) { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_HW); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_0, *key); - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_0, tmpVal); - - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_KEY_SEL_1, *key); - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_SEL_1, tmpVal); - - return; - } + return; + } + + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_0, BL_RDWD_FRM_BYTEP(key)); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_1, BL_RDWD_FRM_BYTEP(key)); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, BL_RDWD_FRM_BYTEP(key)); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, BL_RDWD_FRM_BYTEP(key)); + key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_0, BL_RDWD_FRM_BYTEP(key)); + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + keyType = BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE); + + if (keyType == (uint32_t)SEC_ENG_AES_KEY_192BITS) { + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, BL_RDWD_FRM_BYTEP(key)); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_1, BL_RDWD_FRM_BYTEP(key)); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, BL_RDWD_FRM_BYTEP(key)); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_2, BL_RDWD_FRM_BYTEP(key)); + } else if (keyType == (uint32_t)SEC_ENG_AES_KEY_256BITS || keyType == (uint32_t)SEC_ENG_AES_DOUBLE_KEY_128BITS) { + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, BL_RDWD_FRM_BYTEP(key)); key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_3, BL_RDWD_FRM_BYTEP(key)); + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, BL_RDWD_FRM_BYTEP(key)); key += 4; - + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_6, BL_RDWD_FRM_BYTEP(key)); + key += 4; + BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_7, BL_RDWD_FRM_BYTEP(key)); + key += 4; + } + + /* Select software key */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_SW); + + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); +} + +/****************************************************************************/ /** + * @brief AES set counter byte type in CTR mode + * + * @param aesNo: AES ID type + * @param counterType: AES counter type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_AES_Set_Counter_Byte(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Counter_Type counterType) { + uint32_t AESx = SEC_ENG_BASE; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); + CHECK_PARAM(IS_SEC_ENG_AES_COUNTER_TYPE(counterType)); + + /* Set counter type */ + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_ENDIAN); + BL_WR_REG(AESx, SEC_ENG_SE_AES_0_ENDIAN, BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_0_CTR_LEN, counterType)); +} + +/****************************************************************************/ /** + * @brief AES encrypt or decrypt input data + * + * @param aesCtx: AES context pointer + * @param aesNo: AES ID type + * @param in: AES input data buffer to deal with + * @param len: AES input data length + * @param out: AES output data buffer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_AES_Crypt(SEC_Eng_AES_Ctx *aesCtx, SEC_ENG_AES_ID_Type aesNo, const uint8_t *in, uint32_t len, uint8_t *out) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; + + if (len % 16 != 0) { + return ERROR; + } + + /* Wait finished */ + do { tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - keyType = BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MODE); - - if (keyType == (uint32_t)SEC_ENG_AES_KEY_192BITS) { - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, BL_RDWD_FRM_BYTEP(key)); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, BL_RDWD_FRM_BYTEP(key)); - key += 4; - } else if (keyType == (uint32_t)SEC_ENG_AES_KEY_256BITS || keyType == (uint32_t)SEC_ENG_AES_DOUBLE_KEY_128BITS) { - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_4, BL_RDWD_FRM_BYTEP(key)); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_5, BL_RDWD_FRM_BYTEP(key)); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_6, BL_RDWD_FRM_BYTEP(key)); - key += 4; - BL_WR_REG(AESx, SEC_ENG_SE_AES_KEY_7, BL_RDWD_FRM_BYTEP(key)); - key += 4; + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); - /* Select software key */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_HW_KEY_EN, SEC_ENG_AES_KEY_SW); + /* Clear trigger */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_TRIG_1T); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); -} + /* Set input and output address */ + BL_WR_REG(AESx, SEC_ENG_SE_AES_MSA, (uint32_t)in); + BL_WR_REG(AESx, SEC_ENG_SE_AES_MDA, (uint32_t)out); -/****************************************************************************/ /** - * @brief AES set counter byte type in CTR mode - * - * @param aesNo: AES ID type - * @param counterType: AES counter type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_AES_Set_Counter_Byte(SEC_ENG_AES_ID_Type aesNo, SEC_ENG_AES_Counter_Type counterType) -{ - uint32_t AESx = SEC_ENG_BASE; - uint32_t tmpVal; + /* Set message length */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MSG_LEN, len / 16); - /* Check the parameters */ - CHECK_PARAM(IS_SEC_ENG_AES_ID_TYPE(aesNo)); - CHECK_PARAM(IS_SEC_ENG_AES_COUNTER_TYPE(counterType)); + if (aesCtx->mode == SEC_ENG_AES_CTR) { + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); + } - /* Set counter type */ - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_0_ENDIAN); - BL_WR_REG(AESx, SEC_ENG_SE_AES_0_ENDIAN, BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_0_CTR_LEN, counterType)); -} + /* Set IV sel:0 for new, 1 for last */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_IV_SEL, aesCtx->aesFeed); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); -/****************************************************************************/ /** - * @brief AES encrypt or decrypt input data - * - * @param aesCtx: AES context pointer - * @param aesNo: AES ID type - * @param in: AES input data buffer to deal with - * @param len: AES input data length - * @param out: AES output data buffer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_AES_Crypt(SEC_Eng_AES_Ctx *aesCtx, SEC_ENG_AES_ID_Type aesNo, const uint8_t *in, uint32_t len, uint8_t *out) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - - if (len % 16 != 0) { - return ERROR; - } + /* Trigger AES Engine */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_TRIG_1T); + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - /* Wait finished */ - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - timeoutCnt--; + /* Wait finished */ + timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); + do { + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + timeoutCnt--; - /* Clear trigger */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_TRIG_1T); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); - /* Set input and output address */ - BL_WR_REG(AESx, SEC_ENG_SE_AES_MSA, (uint32_t)in); - BL_WR_REG(AESx, SEC_ENG_SE_AES_MDA, (uint32_t)out); + aesCtx->aesFeed = 1; - /* Set message length */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_MSG_LEN, len / 16); + return SUCCESS; +} - if (aesCtx->mode == SEC_ENG_AES_CTR) { - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); - } +/****************************************************************************/ /** + * @brief AES finish function, clean register + * + * @param aesNo: AES ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_AES_Finish(SEC_ENG_AES_ID_Type aesNo) { + uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - /* Set IV sel:0 for new, 1 for last */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_AES_IV_SEL, aesCtx->aesFeed); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); + /* Wait finished */ + do { + tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); + timeoutCnt--; - /* Trigger AES Engine */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_AES_TRIG_1T); - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); - /* Wait finished */ - timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_EN); - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - timeoutCnt--; + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_IV_SEL); - aesCtx->aesFeed = 1; + BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief AES finish function, clean register - * - * @param aesNo: AES ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_AES_Finish(SEC_ENG_AES_ID_Type aesNo) -{ - uint32_t AESx = SEC_ENG_BASE + SEC_ENG_AES_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_AES_BUSY_TIMEOUT_COUNT; - - /* Wait finished */ - do { - tmpVal = BL_RD_REG(AESx, SEC_ENG_SE_AES_CTRL); - timeoutCnt--; + * @brief TRNG enable TRNG interrupt + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_Trng_Enable(void) { + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_TRNG_BUSY_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_AES_BUSY)); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_EN); - - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_DEC_KEY_SEL); + /* FIXME:default reseed number is 0x1ff, to verify, use 0xa to speed up */ + // tmpVal=BL_SET_REG_BITS_VAL(tmpVal,SEC_ENG_SE_TRNG_RESEED_N,0x1ff); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_AES_IV_SEL); - - BL_WR_REG(AESx, SEC_ENG_SE_AES_CTRL, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief TRNG enable TRNG interrupt - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_Trng_Enable(void) -{ - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_TRNG_BUSY_TIMEOUT_COUNT; + /* No interrupt as default */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_EN); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + /* busy will be set to 1 after trigger, the gap is 1T */ + __NOP(); + __NOP(); + __NOP(); + __NOP(); + do { tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + timeoutCnt--; - /* FIXME:default reseed number is 0x1ff, to verify, use 0xa to speed up */ - //tmpVal=BL_SET_REG_BITS_VAL(tmpVal,SEC_ENG_SE_TRNG_RESEED_N,0x1ff); - - /* No interrupt as default */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_EN); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - /* busy will be set to 1 after trigger, the gap is 1T */ - __NOP(); - __NOP(); - __NOP(); - __NOP(); - - do { - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_TRNG_BUSY)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_TRNG_BUSY)); - /* Clear trng interrupt */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + /* Clear trng interrupt */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_TRNG_IRQn, SEC_TRNG_IRQHandler); + Interrupt_Handler_Register(SEC_TRNG_IRQn, SEC_TRNG_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief TRNG enable TRNG interrupt - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_Trng_Int_Enable(void) -{ - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; + * @brief TRNG enable TRNG interrupt + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_Trng_Int_Enable(void) { + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_MASK); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_MASK); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); } /****************************************************************************/ /** - * @brief TRNG disable TRNG interrupt - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_Trng_Int_Disable(void) -{ - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; + * @brief TRNG disable TRNG interrupt + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_Trng_Int_Disable(void) { + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_MASK); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_MASK); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); } /****************************************************************************/ /** - * @brief TRNG get random data out - * - * @param data[32]: TRNG output data - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_Trng_Read(uint8_t data[32]) -{ - uint8_t *p = (uint8_t *)data; - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; - uint32_t timeoutCnt = SEC_ENG_TRNG_BUSY_TIMEOUT_COUNT; + * @brief TRNG get random data out + * + * @param data[32]: TRNG output data + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_Trng_Read(uint8_t data[32]) { + uint8_t *p = (uint8_t *)data; + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_TRNG_BUSY_TIMEOUT_COUNT; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - /* Trigger */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + /* Trigger */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - /* busy will be set to 1 after trigger, the gap is 1T */ - __NOP(); - __NOP(); - __NOP(); - __NOP(); + /* busy will be set to 1 after trigger, the gap is 1T */ + __NOP(); + __NOP(); + __NOP(); + __NOP(); - do { - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_TRNG_BUSY)); - - /* copy trng value */ - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_0)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_1)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_2)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_3)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_4)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_5)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_6)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_7)); - p += 4; - - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - - /* Clear data */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief TRNG get random data out - * - * @param data: TRNG output data buffer - * - * @param len: total length to get in bytes - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type Sec_Eng_Trng_Get_Random(uint8_t *data, uint32_t len) -{ - uint8_t tmpBuf[32]; - uint32_t readLen = 0; - uint32_t i = 0, cnt = 0; - - while (readLen < len) { - if (Sec_Eng_Trng_Read(tmpBuf) != SUCCESS) { - return -1; - } + do { + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + timeoutCnt--; - cnt = len - readLen; + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_TRNG_BUSY)); + + /* copy trng value */ + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_0)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_1)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_2)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_3)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_4)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_5)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_6)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_7)); + p += 4; + + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + + /* Clear data */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + + return SUCCESS; +} + +/****************************************************************************/ /** + * @brief TRNG get random data out + * + * @param data: TRNG output data buffer + * + * @param len: total length to get in bytes + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_Trng_Get_Random(uint8_t *data, uint32_t len) { + uint8_t tmpBuf[32]; + uint32_t readLen = 0; + uint32_t i = 0, cnt = 0; + + while (readLen < len) { + if (Sec_Eng_Trng_Read(tmpBuf) != SUCCESS) { + return -1; + } - if (cnt > sizeof(tmpBuf)) { - cnt = sizeof(tmpBuf); - } + cnt = len - readLen; - for (i = 0; i < cnt; i++) { - data[readLen + i] = tmpBuf[i]; - } + if (cnt > sizeof(tmpBuf)) { + cnt = sizeof(tmpBuf); + } - readLen += cnt; + for (i = 0; i < cnt; i++) { + data[readLen + i] = tmpBuf[i]; } - return 0; + readLen += cnt; + } + + return 0; } -/****************************************************************************/ /** - * @brief TRNG Interrupt Read Trigger - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_Trng_Int_Read_Trigger(void) -{ - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; - - Sec_Eng_Trng_Int_Enable(); +/****************************************************************************/ /** + * @brief TRNG Interrupt Read Trigger + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_Trng_Int_Read_Trigger(void) { + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - /* Trigger */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + Sec_Eng_Trng_Int_Enable(); + + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + /* Trigger */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); } /****************************************************************************/ /** - * @brief TRNG get random data out with Interrupt - * - * @param data[32]: TRNG output data - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_Trng_Int_Read(uint8_t data[32]) -{ - uint8_t *p = (uint8_t *)data; - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; + * @brief TRNG get random data out with Interrupt + * + * @param data[32]: TRNG output data + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_Trng_Int_Read(uint8_t data[32]) { + uint8_t *p = (uint8_t *)data; + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - /* copy trng value */ - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_0)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_1)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_2)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_3)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_4)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_5)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_6)); - p += 4; - BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_7)); - p += 4; - - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - - /* Clear data */ - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); -} - -/****************************************************************************/ /** - * @brief Disable TRNG - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_Trng_Disable(void) -{ - uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; - uint32_t tmpVal; + /* copy trng value */ + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_0)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_1)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_2)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_3)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_4)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_5)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_6)); + p += 4; + BL_WRWD_TO_BYTEP(p, BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_DOUT_7)); + p += 4; - tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_TRIG_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_EN); - //tmpVal=BL_CLR_REG_BIT(tmpVal,SEC_ENG_SE_TRNG_RESEED_N); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); + /* Clear data */ + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); - BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_DOUT_CLR_1T); + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); } /****************************************************************************/ /** - * @brief PKA Reset - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Reset(void) -{ - uint8_t val; + * @brief Disable TRNG + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_Trng_Disable(void) { + uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; + uint32_t tmpVal; - //Disable sec engine - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, 0); + tmpVal = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); - //Enable sec engine - val = 1 << 3; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, val); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_EN); + // tmpVal=BL_CLR_REG_BIT(tmpVal,SEC_ENG_SE_TRNG_RESEED_N); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_INT_CLR_1T); + + BL_WR_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0, tmpVal); } /****************************************************************************/ /** - * @brief PKA Enable big endian - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_BigEndian_Enable(void) -{ - uint32_t tmpVal; - - tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_PKA_0_ENDIAN); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, tmpVal); + * @brief PKA Reset + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Reset(void) { + uint8_t val; + + // Disable sec engine + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, 0); + + // Enable sec engine + val = 1 << 3; + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, val); +} + +/****************************************************************************/ /** + * @brief PKA Enable big endian + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_BigEndian_Enable(void) { + uint32_t tmpVal; + + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_PKA_0_ENDIAN); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_PKA_IRQn, SEC_PKA_IRQHandler); + Interrupt_Handler_Register(SEC_PKA_IRQn, SEC_PKA_IRQHandler); #endif } /****************************************************************************/ /** - * @brief PKA Enable little endian - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LittleEndian_Enable(void) -{ - uint32_t tmpVal; + * @brief PKA Enable little endian + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LittleEndian_Enable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_PKA_0_ENDIAN); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, tmpVal); + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + tmpVal = BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_PKA_0_ENDIAN); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SEC_PKA_IRQn, SEC_PKA_IRQHandler); + Interrupt_Handler_Register(SEC_PKA_IRQn, SEC_PKA_IRQHandler); #endif } /****************************************************************************/ /** - * @brief PKA get status function - * - * @param status: Structure pointer of PKA status type - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_GetStatus(SEC_Eng_PKA_Status_Type *status) -{ - uint32_t tmpVal; + * @brief PKA get status function + * + * @param status: Structure pointer of PKA status type + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_GetStatus(SEC_Eng_PKA_Status_Type *status) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - *(uint16_t *)status = (uint16_t)BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_PKA_0_STATUS); + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + *(uint16_t *)status = (uint16_t)BL_GET_REG_BITS_VAL(tmpVal, SEC_ENG_SE_PKA_0_STATUS); } /****************************************************************************/ /** - * @brief PKA clear interrupt - * - * @param None - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Clear_Int(void) -{ - uint32_t ctrl; + * @brief PKA clear interrupt + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Clear_Int(void) { + uint32_t ctrl; - ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - ctrl = BL_SET_REG_BIT(ctrl, SEC_ENG_SE_PKA_0_INT_CLR_1T); + ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + ctrl = BL_SET_REG_BIT(ctrl, SEC_ENG_SE_PKA_0_INT_CLR_1T); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, ctrl); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, ctrl); - ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - ctrl = BL_CLR_REG_BIT(ctrl, SEC_ENG_SE_PKA_0_INT_CLR_1T); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, ctrl); + ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + ctrl = BL_CLR_REG_BIT(ctrl, SEC_ENG_SE_PKA_0_INT_CLR_1T); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0, ctrl); } /****************************************************************************/ /** - * @brief PKA get Register size according to Register type - * - * @param reg_type: PKA Register type - * - * @return Register size - * -*******************************************************************************/ -static uint16_t Sec_Eng_PKA_Get_Reg_Size(SEC_ENG_PKA_REG_SIZE_Type reg_type) -{ - switch (reg_type) { - case SEC_ENG_PKA_REG_SIZE_8: - return 8; - - case SEC_ENG_PKA_REG_SIZE_16: - return 16; - - case SEC_ENG_PKA_REG_SIZE_32: - return 32; - - case SEC_ENG_PKA_REG_SIZE_64: - return 64; - - case SEC_ENG_PKA_REG_SIZE_96: - return 96; - - case SEC_ENG_PKA_REG_SIZE_128: - return 128; - - case SEC_ENG_PKA_REG_SIZE_192: - return 192; + * @brief PKA get Register size according to Register type + * + * @param reg_type: PKA Register type + * + * @return Register size + * + *******************************************************************************/ +static uint16_t Sec_Eng_PKA_Get_Reg_Size(SEC_ENG_PKA_REG_SIZE_Type reg_type) { + switch (reg_type) { + case SEC_ENG_PKA_REG_SIZE_8: + return 8; - case SEC_ENG_PKA_REG_SIZE_256: - return 256; + case SEC_ENG_PKA_REG_SIZE_16: + return 16; - case SEC_ENG_PKA_REG_SIZE_384: - return 384; + case SEC_ENG_PKA_REG_SIZE_32: + return 32; - case SEC_ENG_PKA_REG_SIZE_512: - return 512; + case SEC_ENG_PKA_REG_SIZE_64: + return 64; - default: - return 0; - } -} - -/****************************************************************************/ /** - * @brief PKA set pre-load register configuration - * - * @param size: Data size in word to write - * @param regIndex: Register index - * @param regType: Register type - * @param op: PKA operation - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Write_Pld_Cfg(uint16_t size, uint8_t regIndex, SEC_ENG_PKA_REG_SIZE_Type regType, SEC_ENG_PKA_OP_Type op, uint8_t lastOp) -{ - struct pka0_pld_cfg cfg; + case SEC_ENG_PKA_REG_SIZE_96: + return 96; - cfg.value.BF.size = size; - cfg.value.BF.d_reg_index = regIndex; - cfg.value.BF.d_reg_type = regType; - cfg.value.BF.op = op; - cfg.value.BF.last_op = lastOp; - - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); -} - -/****************************************************************************/ /** - * @brief PKA write common operation first configuration - * - * @param s0RegIndex: Register index - * @param s0RegType: Register type - * @param dRegIndex: Result Register index - * @param dRegType: Result Register type - * @param op: PKA operation - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Write_Common_OP_First_Cfg(uint8_t s0RegIndex, uint8_t s0RegType, uint8_t dRegIndex, uint8_t dRegType, - uint8_t op, uint8_t lastOp) -{ - struct pka0_common_op_first_cfg cfg; - - cfg.value.BF.s0_reg_idx = s0RegIndex; - cfg.value.BF.s0_reg_type = s0RegType; - - if (op != SEC_ENG_PKA_OP_LCMP) { - cfg.value.BF.d_reg_idx = dRegIndex; - cfg.value.BF.d_reg_type = dRegType; - } - - cfg.value.BF.op = op; - cfg.value.BF.last_op = lastOp; - - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); -} - -/****************************************************************************/ /** - * @brief PKA write common operation second configuration1 - * - * @param s1RegIndex: Register index - * @param s1RegType: Register type - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(uint8_t s1RegIndex, uint8_t s1RegType) -{ - struct pka0_common_op_snd_cfg_S1_only cfg; + case SEC_ENG_PKA_REG_SIZE_128: + return 128; - cfg.value.BF.s1_reg_idx = s1RegIndex; - cfg.value.BF.s1_reg_type = s1RegType; + case SEC_ENG_PKA_REG_SIZE_192: + return 192; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); -} + case SEC_ENG_PKA_REG_SIZE_256: + return 256; -/****************************************************************************/ /** - * @brief PKA write common operation second configuration2 - * - * @param s2RegIndex: Register index - * @param s2RegType: Register type - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(uint8_t s2RegIndex, uint8_t s2RegType) -{ - struct pka0_common_op_snd_cfg_S2_only cfg; + case SEC_ENG_PKA_REG_SIZE_384: + return 384; - cfg.value.BF.s2_reg_idx = s2RegIndex; - cfg.value.BF.s2_reg_type = s2RegType; + case SEC_ENG_PKA_REG_SIZE_512: + return 512; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + default: + return 0; + } } -/****************************************************************************/ /** - * @brief PKA write common operation second configuration1 and configuration 2 - * - * @param s1RegIndex: Configuration 1 Register index - * @param s1RegType: Configuration 1 Register type - * @param s2RegIndex: Configuration 2 Register index - * @param s2RegType: Configuration 3 Register type - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(uint8_t s1RegIndex, uint8_t s1RegType, uint8_t s2RegIndex, uint8_t s2RegType) -{ - struct pka0_common_op_snd_cfg_S1_S2 cfg; +/****************************************************************************/ /** + * @brief PKA set pre-load register configuration + * + * @param size: Data size in word to write + * @param regIndex: Register index + * @param regType: Register type + * @param op: PKA operation + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Write_Pld_Cfg(uint16_t size, uint8_t regIndex, SEC_ENG_PKA_REG_SIZE_Type regType, SEC_ENG_PKA_OP_Type op, uint8_t lastOp) { + struct pka0_pld_cfg cfg; - cfg.value.BF.s1_reg_idx = s1RegIndex; - cfg.value.BF.s1_reg_type = s1RegType; - cfg.value.BF.s2_reg_idx = s2RegIndex; - cfg.value.BF.s2_reg_type = s2RegType; + cfg.value.BF.size = size; + cfg.value.BF.d_reg_index = regIndex; + cfg.value.BF.d_reg_type = regType; + cfg.value.BF.op = op; + cfg.value.BF.last_op = lastOp; + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); +} - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); +/****************************************************************************/ /** + * @brief PKA write common operation first configuration + * + * @param s0RegIndex: Register index + * @param s0RegType: Register type + * @param dRegIndex: Result Register index + * @param dRegType: Result Register type + * @param op: PKA operation + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Write_Common_OP_First_Cfg(uint8_t s0RegIndex, uint8_t s0RegType, uint8_t dRegIndex, uint8_t dRegType, uint8_t op, uint8_t lastOp) { + struct pka0_common_op_first_cfg cfg; + + cfg.value.BF.s0_reg_idx = s0RegIndex; + cfg.value.BF.s0_reg_type = s0RegType; + + if (op != SEC_ENG_PKA_OP_LCMP) { + cfg.value.BF.d_reg_idx = dRegIndex; + cfg.value.BF.d_reg_type = dRegType; + } + + cfg.value.BF.op = op; + cfg.value.BF.last_op = lastOp; + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); +} + +/****************************************************************************/ /** + * @brief PKA write common operation second configuration1 + * + * @param s1RegIndex: Register index + * @param s1RegType: Register type + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(uint8_t s1RegIndex, uint8_t s1RegType) { + struct pka0_common_op_snd_cfg_S1_only cfg; + + cfg.value.BF.s1_reg_idx = s1RegIndex; + cfg.value.BF.s1_reg_type = s1RegType; + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); +} + +/****************************************************************************/ /** + * @brief PKA write common operation second configuration2 + * + * @param s2RegIndex: Register index + * @param s2RegType: Register type + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(uint8_t s2RegIndex, uint8_t s2RegType) { + struct pka0_common_op_snd_cfg_S2_only cfg; + + cfg.value.BF.s2_reg_idx = s2RegIndex; + cfg.value.BF.s2_reg_type = s2RegType; + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); +} + +/****************************************************************************/ /** + * @brief PKA write common operation second configuration1 and configuration 2 + * + * @param s1RegIndex: Configuration 1 Register index + * @param s1RegType: Configuration 1 Register type + * @param s2RegIndex: Configuration 2 Register index + * @param s2RegType: Configuration 3 Register type + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(uint8_t s1RegIndex, uint8_t s1RegType, uint8_t s2RegIndex, uint8_t s2RegType) { + struct pka0_common_op_snd_cfg_S1_S2 cfg; + + cfg.value.BF.s1_reg_idx = s1RegIndex; + cfg.value.BF.s1_reg_type = s1RegType; + cfg.value.BF.s2_reg_idx = s2RegIndex; + cfg.value.BF.s2_reg_type = s2RegType; + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); } /****************************************************************************/ /** - * @brief PKA wait for complete interrupt - * - * @param None - * - * @return SUCCESS - * -*******************************************************************************/ -static BL_Err_Type Sec_Eng_PKA_Wait_ISR(void) -{ - uint32_t pka0_ctrl; - uint32_t timeoutCnt = SEC_ENG_PKA_INT_TIMEOUT_COUNT; + * @brief PKA wait for complete interrupt + * + * @param None + * + * @return SUCCESS + * + *******************************************************************************/ +static BL_Err_Type Sec_Eng_PKA_Wait_ISR(void) { + uint32_t pka0_ctrl; + uint32_t timeoutCnt = SEC_ENG_PKA_INT_TIMEOUT_COUNT; - do { - pka0_ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); - timeoutCnt--; + do { + pka0_ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + timeoutCnt--; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } while (!BL_GET_REG_BITS_VAL(pka0_ctrl, SEC_ENG_SE_PKA_0_INT)); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (!BL_GET_REG_BITS_VAL(pka0_ctrl, SEC_ENG_SE_PKA_0_INT)); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief PKA read block data from register - * - * @param dest: Pointer to buffer address - * @param src: Pointer to register address - * @param len: Data len in word - * - * @return None - * -*******************************************************************************/ + * @brief PKA read block data from register + * + * @param dest: Pointer to buffer address + * @param src: Pointer to register address + * @param len: Data len in word + * + * @return None + * + *******************************************************************************/ #ifdef ARCH_ARM #ifndef __GNUC__ -__ASM void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - PUSH {R3-R6,LR} -Start0 - CMP R2,#4 - BLT Finish0 - LDR R3,[R1] - LDR R4,[R1] - LDR R5,[R1] - LDR R6,[R1] - STMIA R0!,{R3-R6} - SUBS R2,R2,#4 - B Start0 -Finish0 - POP {R3-R6,PC} +__ASM void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + PUSH{R3 - R6, LR} Start0 CMP R2, #4 BLT Finish0 LDR R3, [R1] LDR R4, [R1] LDR R5, [R1] LDR R6, [R1] STMIA R0 !, {R3 - R6} SUBS R2, R2, #4 B Start0 Finish0 POP { R3 - R6, PC } } #else -void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - __asm__ __volatile__("push {r3-r6,lr}\n\t" - "Start0 :" - "cmp r2,#4\n\t" - "blt Finish0\n\t" - "ldr r3,[r1]\n\t" - "ldr r4,[r1]\n\t" - "ldr r5,[r1]\n\t" - "ldr r6,[r1]\n\t" - "stmia r0!,{r3-r6}\n\t" - "sub r2,r2,#4\n\t" - "b Start0\n\t" - "Finish0 :" - "pop {r3-r6,pc}\n\t"); +void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + __asm__ __volatile__("push {r3-r6,lr}\n\t" + "Start0 :" + "cmp r2,#4\n\t" + "blt Finish0\n\t" + "ldr r3,[r1]\n\t" + "ldr r4,[r1]\n\t" + "ldr r5,[r1]\n\t" + "ldr r6,[r1]\n\t" + "stmia r0!,{r3-r6}\n\t" + "sub r2,r2,#4\n\t" + "b Start0\n\t" + "Finish0 :" + "pop {r3-r6,pc}\n\t"); } #endif #endif #ifdef ARCH_RISCV -void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - uint32_t wrLen = len - len % 4; - uint32_t i; +void Sec_Eng_PKA_Read_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + uint32_t wrLen = len - len % 4; + uint32_t i; - for (i = 0; i < wrLen; i++) { - dest[i] = *src; - } + for (i = 0; i < wrLen; i++) { + dest[i] = *src; + } } #endif /****************************************************************************/ /** - * @brief PKA Write block data to register - * - * @param dest: Pointer to register address - * @param src: Pointer to buffer address - * @param len: Data len in word - * - * @return None - * -*******************************************************************************/ + * @brief PKA Write block data to register + * + * @param dest: Pointer to register address + * @param src: Pointer to buffer address + * @param len: Data len in word + * + * @return None + * + *******************************************************************************/ #ifdef ARCH_ARM #ifndef __GNUC__ -__ASM void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - PUSH {R3-R6,LR} -Start1 - CMP R2,#4 - BLT Finish1 - LDMIA R1!,{R3-R6} - STR R3,[R0] - STR R4,[R0] - STR R5,[R0] - STR R6,[R0] - SUBS R2,R2,#4 - B Start1 -Finish1 - POP {R3-R6,PC} +__ASM void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + PUSH{R3 - R6, LR} Start1 CMP R2, #4 BLT Finish1 LDMIA R1 !, {R3 - R6} STR R3, [R0] STR R4, [R0] STR R5, [R0] STR R6, [R0] SUBS R2, R2, #4 B Start1 Finish1 POP { R3 - R6, PC } } #else -void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - __asm__ __volatile__("push {r3-r6,lr}\n\t" - "Start1 :" - "cmp r2,#4\n\t" - "blt Finish1\n\t" - "ldmia r1!,{r3-r6}\n\t" - "str r3,[r0]\n\t" - "str r4,[r0]\n\t" - "str r5,[r0]\n\t" - "str r6,[r0]\n\t" - "sub r2,r2,#4\n\t" - "b Start1\n\t" - "Finish1 :" - "pop {r3-r6,pc}\n\t"); +void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + __asm__ __volatile__("push {r3-r6,lr}\n\t" + "Start1 :" + "cmp r2,#4\n\t" + "blt Finish1\n\t" + "ldmia r1!,{r3-r6}\n\t" + "str r3,[r0]\n\t" + "str r4,[r0]\n\t" + "str r5,[r0]\n\t" + "str r6,[r0]\n\t" + "sub r2,r2,#4\n\t" + "b Start1\n\t" + "Finish1 :" + "pop {r3-r6,pc}\n\t"); } #endif #endif #ifdef ARCH_RISCV -void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) -{ - uint32_t wrLen = len - len % 4; - uint32_t i; +void Sec_Eng_PKA_Write_Block(uint32_t *dest, const uint32_t *src, uint32_t len) { + uint32_t wrLen = len - len % 4; + uint32_t i; - for (i = 0; i < wrLen; i++) { - *dest = src[i]; - } + for (i = 0; i < wrLen; i++) { + *dest = src[i]; + } } #endif /****************************************************************************/ /** - * @brief PKA get result - * - * @param result: Pointer to store result - * @param retSize: Result length in word - * @param regLen: register length in byte - * - * @return None - * -*******************************************************************************/ -static void Sec_Eng_PKA_Get_Result(uint32_t *result, uint8_t retSize, uint16_t regLen) -{ - uint32_t ret_data = 0x00; - int index = 0x00; - - /* Wait for the result */ + * @brief PKA get result + * + * @param result: Pointer to store result + * @param retSize: Result length in word + * @param regLen: register length in byte + * + * @return None + * + *******************************************************************************/ +static void Sec_Eng_PKA_Get_Result(uint32_t *result, uint8_t retSize, uint16_t regLen) { + uint32_t ret_data = 0x00; + int index = 0x00; + + /* Wait for the result */ + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + Sec_Eng_PKA_Read_Block(result, (uint32_t *)(SEC_ENG_BASE + SEC_ENG_SE_PKA_0_RW_OFFSET), retSize); + index = retSize - (retSize % 4); + + while (index < retSize) { + ret_data = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW); + result[index] = ret_data; + index++; + } +} + +/****************************************************************************/ /** + * @brief PKA load data to register + * + * @param regType: Register type + * @param regIndex: Register index + * @param data: Data buffer + * @param size: Data length in word + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIndex, const uint32_t *data, uint16_t size, uint8_t lastOp) { + int index = 0x00; + uint16_t regLen = Sec_Eng_PKA_Get_Reg_Size(regType); + + Sec_Eng_PKA_Write_Pld_Cfg(size, regIndex, regType, SEC_ENG_PKA_OP_CTLIR_PLD, lastOp); + + if (size > regLen / 4) { + size = regLen / 4; + } + + Sec_Eng_PKA_Write_Block((uint32_t *)(SEC_ENG_BASE + SEC_ENG_SE_PKA_0_RW_OFFSET), data, size); + index = size - (size % 4); + + while (index < size) { + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, data[index]); + index++; + } +} + +/****************************************************************************/ /** + * @brief PKA read data from register + * + * @param regType: Register type + * @param regIdx: Register index + * @param result: Data buffer + * @param retSize: Data length in word + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Read_Data(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIdx, uint32_t *result, uint8_t retSize) { + uint16_t regSize; + uint32_t dummyData = 0; + + regSize = Sec_Eng_PKA_Get_Reg_Size(regType); + + if (retSize > regSize / 4) { + result = NULL; + return; + } + + Sec_Eng_PKA_Write_Pld_Cfg(retSize, regIdx, regType, SEC_ENG_PKA_OP_CFLIR_BUFFER, 1); + + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + + Sec_Eng_PKA_Get_Result(result, retSize, regSize); +} + +/****************************************************************************/ /** + * @brief PKA clear register + * + * @param dRegType: Register type + * @param dRegIdx: Register index + * @param size: Data length in word + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_CREG(SEC_ENG_PKA_REG_SIZE_Type dRegType, uint8_t dRegIdx, uint8_t size, uint8_t lastOp) { + uint32_t dummyData = 0; + + Sec_Eng_PKA_Write_Pld_Cfg(size, dRegIdx, dRegType, SEC_ENG_PKA_OP_CLIR, lastOp); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + + if (lastOp) { Sec_Eng_PKA_Wait_ISR(); Sec_Eng_PKA_Clear_Int(); - Sec_Eng_PKA_Read_Block(result, (uint32_t *)(SEC_ENG_BASE + SEC_ENG_SE_PKA_0_RW_OFFSET), retSize); - index = retSize - (retSize % 4); - - while (index < retSize) { - ret_data = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW); - result[index] = ret_data; - index++; - } + } } /****************************************************************************/ /** - * @brief PKA load data to register - * - * @param regType: Register type - * @param regIndex: Register index - * @param data: Data buffer - * @param size: Data length in word - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Write_Data(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIndex, const uint32_t *data, uint16_t size, uint8_t lastOp) -{ - int index = 0x00; - uint16_t regLen = Sec_Eng_PKA_Get_Reg_Size(regType); + * @brief PKA load data to register + * + * @param regType: regType: Register type + * @param regIndex: regIndex: Register index + * @param data: data: Data buffer + * @param lastOp: size: Data length in word + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Write_Immediate(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIndex, uint32_t data, uint8_t lastOp) { + struct pka0_pldi_cfg cfg; - Sec_Eng_PKA_Write_Pld_Cfg(size, regIndex, regType, SEC_ENG_PKA_OP_CTLIR_PLD, lastOp); - - if (size > regLen / 4) { - size = regLen / 4; - } + cfg.value.BF.rsvd = 0; + cfg.value.BF.d_reg_index = regIndex; + cfg.value.BF.d_reg_type = regType; + cfg.value.BF.op = SEC_ENG_PKA_OP_SLIR; + cfg.value.BF.last_op = lastOp; - Sec_Eng_PKA_Write_Block((uint32_t *)(SEC_ENG_BASE + SEC_ENG_SE_PKA_0_RW_OFFSET), data, size); - index = size - (size % 4); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, data); - while (index < size) { - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, data[index]); - index++; - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA read data from register - * - * @param regType: Register type - * @param regIdx: Register index - * @param result: Data buffer - * @param retSize: Data length in word - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Read_Data(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIdx, uint32_t *result, uint8_t retSize) -{ - uint16_t regSize; - uint32_t dummyData = 0; + * @brief PKA negative source data:D = (1 << SIZE{S0})-S0 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source Register type + * @param s0RegIdx: Source Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_NREG(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) { + uint32_t dummyData = 0; - regSize = Sec_Eng_PKA_Get_Reg_Size(regType); + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_NLIR, lastOp); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); - if (retSize > regSize / 4) { - result = NULL; - return; - } - - Sec_Eng_PKA_Write_Pld_Cfg(retSize, regIdx, regType, SEC_ENG_PKA_OP_CFLIR_BUFFER, 1); - - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); - - Sec_Eng_PKA_Get_Result(result, retSize, regSize); + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA clear register - * - * @param dRegType: Register type - * @param dRegIdx: Register index - * @param size: Data length in word - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_CREG(SEC_ENG_PKA_REG_SIZE_Type dRegType, uint8_t dRegIdx, uint8_t size, uint8_t lastOp) -{ - uint32_t dummyData = 0; - - Sec_Eng_PKA_Write_Pld_Cfg(size, dRegIdx, dRegType, SEC_ENG_PKA_OP_CLIR, lastOp); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + * @brief PKA move data:D = S0 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source Register type + * @param s0RegIdx: Source Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_Move_Data(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) { + uint32_t dummyData = 0; - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MOVDAT, lastOp); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); -/****************************************************************************/ /** - * @brief PKA load data to register - * - * @param regType: regType: Register type - * @param regIndex: regIndex: Register index - * @param data: data: Data buffer - * @param lastOp: size: Data length in word - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Write_Immediate(SEC_ENG_PKA_REG_SIZE_Type regType, uint8_t regIndex, uint32_t data, uint8_t lastOp) -{ - struct pka0_pldi_cfg cfg; - - cfg.value.BF.rsvd = 0; - cfg.value.BF.d_reg_index = regIndex; - cfg.value.BF.d_reg_type = regType; - cfg.value.BF.op = SEC_ENG_PKA_OP_SLIR; - cfg.value.BF.last_op = lastOp; - - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, data); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA negative source data:D = (1 << SIZE{S0})-S0 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source Register type - * @param s0RegIdx: Source Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_NREG(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) -{ - uint32_t dummyData = 0; + * @brief PKA resize data:D = S0, D.Size = S0.Size + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source Register type + * @param s0RegIdx: Source Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_RESIZE(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) { + uint32_t dummyData = 0; - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_NLIR, lastOp); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_RESIZE, lastOp); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod add:D = (S0 + S1) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MADD(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MADD, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod sub:D = (S0 - S1) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MSUB(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MSUB, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod :D = S0 mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MREM(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MREM, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod mul:D = (S0 * S1) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MMUL(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MMUL, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod sqr:D = (S0 ^ 2) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MSQR(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MSQR, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod exp:D = (S0 ^ S1) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MEXP(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MEXP, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mod exp:D = (S0 ^ (S2-2) ) mod S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_MINV(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MINV, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA Report COUT to 1 when S0 < S1 + * + * @param cout: Compare result + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LCMP(uint8_t *cout, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx) { + uint32_t pka0_ctrl = 0x00; + + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, 0, 0, SEC_ENG_PKA_OP_LCMP, 1); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); + + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + pka0_ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + + *cout = (pka0_ctrl & SEC_ENG_PKA_STATUS_LAST_OPC_MASK) >> SEC_ENG_PKA_STATUS_LAST_OPC_OFFSET; +} + +/****************************************************************************/ /** + * @brief PKA add:D = S0 + S1 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LADD(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LADD, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA sub:D = S0 - S1 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LSUB(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LSUB, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA mul:D = S0 * S1 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s1RegType: Source 1 Register type + * @param s1RegIdx: Source 1 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LMUL(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LMUL, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA move data:D = S0 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source Register type - * @param s0RegIdx: Source Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_Move_Data(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) -{ - uint32_t dummyData = 0; + * @brief PKA sqr:D = S0^2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LSQR(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) { + uint32_t dummyData = 0; - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MOVDAT, lastOp); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LSQR, lastOp); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } +} + +/****************************************************************************/ /** + * @brief PKA div:D = S0 / S2 + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param s2RegType: Source 2 Register type + * @param s2RegIdx: Source 2 Register index + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LDIV(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) { + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LDIV, lastOp); + Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); + + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA resize data:D = S0, D.Size = S0.Size - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source Register type - * @param s0RegIdx: Source Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_RESIZE(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) -{ - uint32_t dummyData = 0; + * @brief PKA shift:D = S0 << BIT SHIFT + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param bit_shift: Bits to shift + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LMUL2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint16_t bit_shift, uint8_t lastOp) { + struct pka0_bit_shift_op_cfg cfg; - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_RESIZE, lastOp); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LMUL2N, 0); - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + cfg.value.BF.bit_shift = bit_shift; + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); -/****************************************************************************/ /** - * @brief PKA mod add:D = (S0 + S1) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MADD(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MADD, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} - -/****************************************************************************/ /** - * @brief PKA mod sub:D = (S0 - S1) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MSUB(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MSUB, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA mod :D = S0 mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MREM(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MREM, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + * @brief PKA shift:D = S0 >> BIT SHIFT + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param bit_shift: Bits to shift + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LDIV2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint16_t bit_shift, uint8_t lastOp) { + struct pka0_bit_shift_op_cfg cfg; -/****************************************************************************/ /** - * @brief PKA mod mul:D = (S0 * S1) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MMUL(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MMUL, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LDIV2N, 0); -/****************************************************************************/ /** - * @brief PKA mod sqr:D = (S0 ^ 2) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MSQR(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MSQR, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + cfg.value.BF.bit_shift = bit_shift; + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); -/****************************************************************************/ /** - * @brief PKA mod exp:D = (S0 ^ S1) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MEXP(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MEXP, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1_S2(s1RegIdx, s1RegType, s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + if (lastOp) { + Sec_Eng_PKA_Wait_ISR(); + Sec_Eng_PKA_Clear_Int(); + } } /****************************************************************************/ /** - * @brief PKA mod exp:D = (S0 ^ (S2-2) ) mod S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_MINV(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MINV, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + * @brief PKA mod 2N:D = S0 % ((1 << BIT SHIFT)-1) + * + * @param dRegType: Destination Register type + * @param dRegIdx: Destination Register index + * @param s0RegType: Source 0 Register type + * @param s0RegIdx: Source 0 Register index + * @param bit_shift: Bits to shift + * @param lastOp: Last operation + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_PKA_LMOD2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint16_t bit_shift, uint8_t lastOp) { + struct pka0_bit_shift_op_cfg cfg; -/****************************************************************************/ /** - * @brief PKA Report COUT to 1 when S0 < S1 - * - * @param cout: Compare result - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LCMP(uint8_t *cout, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t s1RegType, uint8_t s1RegIdx) -{ - uint32_t pka0_ctrl = 0x00; + Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MOD2N, lastOp); - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, 0, 0, SEC_ENG_PKA_OP_LCMP, 1); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); + cfg.value.BF.bit_shift = bit_shift; + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + if (lastOp) { Sec_Eng_PKA_Wait_ISR(); Sec_Eng_PKA_Clear_Int(); - pka0_ctrl = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_CTRL_0); + } +} + +/****************************************************************************/ /** + * @brief PKA GF to Mont filed 2N:d = (a<> SEC_ENG_PKA_STATUS_LAST_OPC_OFFSET; +#ifndef BFLB_USE_HAL_DRIVER + Interrupt_Handler_Register(SEC_GMAC_IRQn, SEC_GMAC_IRQHandler); +#endif } /****************************************************************************/ /** - * @brief PKA add:D = S0 + S1 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LADD(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LADD, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + * @brief Set gmac big endian + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_GMAC_Enable_BE(void) { + uint32_t tmpVal; -/****************************************************************************/ /** - * @brief PKA sub:D = S0 - S1 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LSUB(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LSUB, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_T_ENDIAN); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_H_ENDIAN); + tmpVal = BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_X_ENDIAN); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0, tmpVal); -/****************************************************************************/ /** - * @brief PKA mul:D = S0 * S1 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s1RegType: Source 1 Register type - * @param s1RegIdx: Source 1 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LMUL(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s1RegType, uint8_t s1RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LMUL, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S1(s1RegIdx, s1RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } +#ifndef BFLB_USE_HAL_DRIVER + Interrupt_Handler_Register(SEC_GMAC_IRQn, SEC_GMAC_IRQHandler); +#endif } /****************************************************************************/ /** - * @brief PKA sqr:D = S0^2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LSQR(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, uint8_t lastOp) -{ - uint32_t dummyData = 0; - - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LSQR, lastOp); - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, dummyData); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + * @brief GMAC enable link mode + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_GMAC_Enable_Link(void) { + uint32_t tmpVal; + + /* Enable gmac link mode */ + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_EN)); +} + +/****************************************************************************/ /** + * @brief GMAC disable link mode + * + * @param None + * + * @return None + * + *******************************************************************************/ +void Sec_Eng_GMAC_Disable_Link(void) { + uint32_t tmpVal; + + /* Disable gmac link mode */ + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0); + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_GMAC_0_CTRL_0, BL_CLR_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_EN)); +} + +/****************************************************************************/ /** + * @brief GMAC work in link mode + * + * @param linkAddr: Address of config structure in link mode + * @param in: GMAC input data buffer to deal with + * @param len: GMAC input data length + * @param out: GMAC output data buffer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type Sec_Eng_GMAC_Link_Work(uint32_t linkAddr, const uint8_t *in, uint32_t len, uint8_t *out) { + uint32_t GMACx = SEC_ENG_BASE; + uint32_t tmpVal; + uint32_t timeoutCnt = SEC_ENG_GMAC_BUSY_TIMEOUT_COUNT; + + /* Link address should word align */ + if ((linkAddr & 0x03) != 0 || len % 16 != 0) { + return ERROR; + } + + /* Wait finished */ + do { + tmpVal = BL_RD_REG(GMACx, SEC_ENG_SE_GMAC_0_CTRL_0); + timeoutCnt--; -/****************************************************************************/ /** - * @brief PKA div:D = S0 / S2 - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param s2RegType: Source 2 Register type - * @param s2RegIdx: Source 2 Register index - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LDIV(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint8_t s2RegType, uint8_t s2RegIdx, uint8_t lastOp) -{ - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LDIV, lastOp); - Sec_Eng_PKA_Write_Common_OP_Snd_Cfg_S2(s2RegIdx, s2RegType); - - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); + if (timeoutCnt == 0) { + return TIMEOUT; } -} + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_GMAC_0_BUSY)); -/****************************************************************************/ /** - * @brief PKA shift:D = S0 << BIT SHIFT - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param bit_shift: Bits to shift - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LMUL2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint16_t bit_shift, uint8_t lastOp) -{ - struct pka0_bit_shift_op_cfg cfg; + /* Set link address */ + BL_WR_REG(GMACx, SEC_ENG_SE_GMAC_0_LCA, linkAddr); - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LMUL2N, 0); + /* Change source buffer address */ + *(uint32_t *)(linkAddr + 4) = (uint32_t)in; - cfg.value.BF.bit_shift = bit_shift; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + /* Set data length */ + *((uint16_t *)linkAddr + 1) = len / 16; - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + /* Start gmac engine and wait finishing */ + tmpVal = BL_RD_REG(GMACx, SEC_ENG_SE_GMAC_0_CTRL_0); + BL_WR_REG(GMACx, SEC_ENG_SE_GMAC_0_CTRL_0, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_GMAC_0_TRIG_1T)); + timeoutCnt = SEC_ENG_GMAC_BUSY_TIMEOUT_COUNT; -/****************************************************************************/ /** - * @brief PKA shift:D = S0 >> BIT SHIFT - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param bit_shift: Bits to shift - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LDIV2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint16_t bit_shift, uint8_t lastOp) -{ - struct pka0_bit_shift_op_cfg cfg; + do { + tmpVal = BL_RD_REG(GMACx, SEC_ENG_SE_GMAC_0_CTRL_0); + timeoutCnt--; - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_LDIV2N, 0); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } while (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_GMAC_0_BUSY)); - cfg.value.BF.bit_shift = bit_shift; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + /* Get result */ + BL702_MemCpy_Fast(out, (uint8_t *)(linkAddr + 0x18), 16); - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } + return SUCCESS; } +#ifndef BFLB_USE_HAL_DRIVER /****************************************************************************/ /** - * @brief PKA mod 2N:D = S0 % ((1 << BIT SHIFT)-1) - * - * @param dRegType: Destination Register type - * @param dRegIdx: Destination Register index - * @param s0RegType: Source 0 Register type - * @param s0RegIdx: Source 0 Register index - * @param bit_shift: Bits to shift - * @param lastOp: Last operation - * - * @return None - * -*******************************************************************************/ -void Sec_Eng_PKA_LMOD2N(uint8_t dRegType, uint8_t dRegIdx, uint8_t s0RegType, uint8_t s0RegIdx, - uint16_t bit_shift, uint8_t lastOp) -{ - struct pka0_bit_shift_op_cfg cfg; + * @brief Sec Eng Interrupt Handler + * + * @param intType: IRQ Type + * + * @return None + * + *******************************************************************************/ +static void SEC_Eng_IntHandler(SEC_ENG_INT_Type intType) { + uint32_t tmpVal; - Sec_Eng_PKA_Write_Common_OP_First_Cfg(s0RegIdx, s0RegType, dRegIdx, dRegType, SEC_ENG_PKA_OP_MOD2N, lastOp); + /* Check the parameters */ + CHECK_PARAM(IS_SEC_ENG_INT_TYPE(intType)); - cfg.value.BF.bit_shift = bit_shift; - BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_PKA_0_RW, cfg.value.WORD); + switch (intType) { + case SEC_ENG_INT_TRNG: + tmpVal = BL_RD_REG(SEC_ENG_BASE, SEC_ENG_SE_TRNG_0_CTRL_0); - if (lastOp) { - Sec_Eng_PKA_Wait_ISR(); - Sec_Eng_PKA_Clear_Int(); - } -} + if (BL_IS_REG_BIT_SET(tmpVal, SEC_ENG_SE_TRNG_0_INT)) { + /* Clear interrupt */ + BL_WR_REG(SEC_ENG_BASE, SEC_ENG_SE_TRNG_0_CTRL_0, BL_SET_REG_BIT(tmpVal, SEC_ENG_SE_TRNG_0_INT_CLR_1T)); -/****************************************************************************/ /** - * @brief PKA GF to Mont filed 2N:d = (a<
© COPYRIGHT(c) 2020 Bouffalo Lab
- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sf_cfg.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "bl702_glb.h" #include "bl702_sf_cfg.h" -#include "softcrc.h" +#include "bl702_glb.h" #include "bl702_xip_sflash.h" +#include "softcrc.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -58,11 +58,10 @@ * @{ */ #ifndef BFLB_USE_ROM_DRIVER -typedef struct -{ - uint32_t jedecID; - char *name; - const SPI_Flash_Cfg_Type *cfg; +typedef struct { + uint32_t jedecID; + char *name; + const SPI_Flash_Cfg_Type *cfg; } Flash_Info_t; #endif @@ -73,1985 +72,1985 @@ typedef struct */ #ifndef BFLB_USE_ROM_DRIVER static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Winb_80DV = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xef, + .mid = 0xef, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 0, - .cReadMode = 0xFF, + .frQioDmyClk = 16 / 8, + .cReadSupport = 0, + .cReadMode = 0xFF, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3d, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 3, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 3, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Winb_16DV = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xef, + .mid = 0xef, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, /*Q08BV,Q16DV: 0x02.Q32FW,Q32FV: 0x01 */ - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3d, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 3, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 3, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Winb_80EW_16FW_32JW_32FW_32FV = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xef, + .mid = 0xef, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 400, - .timeE32k = 1600, - .timeE64k = 2000, + .timeE32k = 1600, + .timeE64k = 2000, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 3, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 3, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Issi = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x9d, + .mid = 0x9d, - .deBurstWrapCmd = 0xC0, + .deBurstWrapCmd = 0xC0, .deBurstWrapCmdDmyClk = 0x00, - .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, - .deBurstWrapData = 0x00, + .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, + .deBurstWrapData = 0x00, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0, - .qeBit = 0x06, + .qeIndex = 0, + .qeBit = 0x06, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0xA0, - .burstWrapCmd = 0xC0, + .burstWrapCmd = 0xC0, .burstWrapCmdDmyClk = 0x00, - .burstWrapDataMode = SF_CTRL_DATA_1_LINE, - .burstWrapData = 0x06, + .burstWrapDataMode = SF_CTRL_DATA_1_LINE, + .burstWrapData = 0x06, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 5, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 5, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_Md_40D = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x51, + .mid = 0x51, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 0, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 0, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_DO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_DO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc8, + .mid = 0xc8, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_Q80E_Q16E = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc8, + .mid = 0xc8, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_WQ80E_WQ16E = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc8, + .mid = 0xc8, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 32 / 8, - .cReadSupport = 1, - .cReadMode = 0xA0, + .frQioDmyClk = 32 / 8, + .cReadSupport = 1, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 8 / 8, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 8 / 8, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0x12, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0x12, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_Q32C = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc8, + .mid = 0xc8, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Mxic = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xC2, + .mid = 0xC2, - .deBurstWrapCmd = 0xC0, + .deBurstWrapCmd = 0xC0, .deBurstWrapCmdDmyClk = 0x00, - .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, - .deBurstWrapData = 0x10, + .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, + .deBurstWrapData = 0x10, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0, - .qeBit = 0x06, + .qeIndex = 0, + .qeBit = 0x06, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0xA5, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0xA5, - .burstWrapCmd = 0xC0, + .burstWrapCmd = 0xC0, .burstWrapCmdDmyClk = 0x00, - .burstWrapDataMode = SF_CTRL_DATA_1_LINE, - .burstWrapData = 0x02, + .burstWrapDataMode = SF_CTRL_DATA_1_LINE, + .burstWrapData = 0x02, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x38, - .qppAddrMode = SF_CTRL_ADDR_4_LINES, + .qppAddrMode = SF_CTRL_ADDR_4_LINES, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 45, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 45, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Mxic_1635F = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xC2, + .mid = 0xC2, - .deBurstWrapCmd = 0xC0, + .deBurstWrapCmd = 0xC0, .deBurstWrapCmdDmyClk = 0x00, - .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, - .deBurstWrapData = 0x10, + .deBurstWrapDataMode = SF_CTRL_DATA_1_LINE, + .deBurstWrapData = 0x10, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0, - .qeBit = 0x06, + .qeIndex = 0, + .qeBit = 0x06, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0xA5, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0xA5, - .burstWrapCmd = 0xC0, + .burstWrapCmd = 0xC0, .burstWrapCmdDmyClk = 0x00, - .burstWrapDataMode = SF_CTRL_DATA_1_LINE, - .burstWrapData = 0x02, + .burstWrapDataMode = SF_CTRL_DATA_1_LINE, + .burstWrapData = 0x02, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x38, - .qppAddrMode = SF_CTRL_ADDR_4_LINES, + .qppAddrMode = SF_CTRL_ADDR_4_LINES, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 45, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 45, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Xtx40 = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x0B, + .mid = 0x0B, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0x01, - .qeBit = 0x01, + .qeIndex = 0x01, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_DIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_DIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 6000, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Xtx = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x0B, + .mid = 0x0B, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0x01, - .qeBit = 0x01, + .qeIndex = 0x01, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 6000, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Puya_Q80L_Q80H_Q16H = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x85, + .mid = 0x85, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0x01, - .qeBit = 0x01, + .qeIndex = 0x01, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3d, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 8, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 8, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Puya_Q32H = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x85, + .mid = 0x85, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0x01, - .qeBit = 0x01, + .qeIndex = 0x01, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 8, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 8, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Boya40 = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x68, + .mid = 0x68, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 0, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 0, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_DO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_DO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Boya = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x68, + .mid = 0x68, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 0x01, - .qeBit = 0x01, + .qeIndex = 0x01, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_FT_VQ80 = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xef, + .mid = 0xef, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20 * 1000, - .pdDelay = 8, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 8, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = { { - .jedecID = 0x1440ef, - .name = "Winb_80DV_08_33", - .cfg = &flashCfg_Winb_80DV, - }, + .jedecID = 0x1440ef, + .name = "Winb_80DV_08_33", + .cfg = &flashCfg_Winb_80DV, + }, { - .jedecID = 0x1540ef, - .name = "Winb_16DV_16_33", - .cfg = &flashCfg_Winb_16DV, - }, + .jedecID = 0x1540ef, + .name = "Winb_16DV_16_33", + .cfg = &flashCfg_Winb_16DV, + }, { - .jedecID = 0x1640ef, - .name = "Winb_32FV_32_33", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, + .jedecID = 0x1640ef, + .name = "Winb_32FV_32_33", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, { - .jedecID = 0x1460ef, - .name = "Winb_80EW_08_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, + .jedecID = 0x1460ef, + .name = "Winb_80EW_08_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, { - .jedecID = 0x1560ef, - .name = "Winb_16FW_16_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, + .jedecID = 0x1560ef, + .name = "Winb_16FW_16_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, { - .jedecID = 0x1660ef, - .name = "Winb_32FW_32_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, + .jedecID = 0x1660ef, + .name = "Winb_32FW_32_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, { - .jedecID = 0x1860ef, - .name = "Winb_128FW_128_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, + .jedecID = 0x1860ef, + .name = "Winb_128FW_128_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, { - .jedecID = 0x1680ef, - .name = "Winb_32JW_32_18", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, + .jedecID = 0x1680ef, + .name = "Winb_32JW_32_18", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, { - .jedecID = 0x13605e, - .name = "Zbit_04_33", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, + .jedecID = 0x13605e, + .name = "Zbit_04_33", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, { - .jedecID = 0x14605e, - .name = "Zbit_08_33", - .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, - }, + .jedecID = 0x14605e, + .name = "Zbit_08_33", + .cfg = &flashCfg_Winb_80EW_16FW_32JW_32FW_32FV, + }, { - .jedecID = 0x14609d, - .name = "ISSI_08_33", - .cfg = &flashCfg_Issi, - }, + .jedecID = 0x14609d, + .name = "ISSI_08_33", + .cfg = &flashCfg_Issi, + }, { - .jedecID = 0x15609d, - .name = "ISSI_16_33", - .cfg = &flashCfg_Issi, - }, + .jedecID = 0x15609d, + .name = "ISSI_16_33", + .cfg = &flashCfg_Issi, + }, { - .jedecID = 0x16609d, - .name = "ISSI_32_33", - .cfg = &flashCfg_Issi, - }, + .jedecID = 0x16609d, + .name = "ISSI_32_33", + .cfg = &flashCfg_Issi, + }, { - .jedecID = 0x14709d, - .name = "ISSI_08_18", - .cfg = &flashCfg_Issi, - }, + .jedecID = 0x14709d, + .name = "ISSI_08_18", + .cfg = &flashCfg_Issi, + }, { - .jedecID = 0x15709d, - .name = "ISSI_16_18", - .cfg = &flashCfg_Issi, - }, + .jedecID = 0x15709d, + .name = "ISSI_16_18", + .cfg = &flashCfg_Issi, + }, { - .jedecID = 0x16709d, - .name = "ISSI_32_18", - .cfg = &flashCfg_Issi, - }, + .jedecID = 0x16709d, + .name = "ISSI_32_18", + .cfg = &flashCfg_Issi, + }, { - .jedecID = 0x134051, - .name = "GD_MD04D_04_33", - .cfg = &flashCfg_Gd_Md_40D, - }, + .jedecID = 0x134051, + .name = "GD_MD04D_04_33", + .cfg = &flashCfg_Gd_Md_40D, + }, { - .jedecID = 0x1440C8, - .name = "GD_Q08E_08_33", - .cfg = &flashCfg_Gd_Q80E_Q16E, - }, + .jedecID = 0x1440C8, + .name = "GD_Q08E_08_33", + .cfg = &flashCfg_Gd_Q80E_Q16E, + }, { - .jedecID = 0x1540C8, - .name = "GD_Q16E_16_33", - .cfg = &flashCfg_Gd_Q80E_Q16E, - }, + .jedecID = 0x1540C8, + .name = "GD_Q16E_16_33", + .cfg = &flashCfg_Gd_Q80E_Q16E, + }, { - .jedecID = 0x1640C8, - .name = "GD_Q32C_32_33", - .cfg = &flashCfg_Gd_Q32C, - }, + .jedecID = 0x1640C8, + .name = "GD_Q32C_32_33", + .cfg = &flashCfg_Gd_Q32C, + }, { - .jedecID = 0x1460C8, - .name = "GD_LQ08C_08_18", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, + .jedecID = 0x1460C8, + .name = "GD_LQ08C_08_18", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, { - .jedecID = 0x1560C8, - .name = "GD_LE16C_16_18", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, + .jedecID = 0x1560C8, + .name = "GD_LE16C_16_18", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, { - .jedecID = 0x1660C8, - .name = "GD_LQ32D_32_18", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, + .jedecID = 0x1660C8, + .name = "GD_LQ32D_32_18", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, { - .jedecID = 0x1465C8, - .name = "GD_WQ80E_80_33", - .cfg = &flashCfg_Gd_WQ80E_WQ16E, - }, + .jedecID = 0x1465C8, + .name = "GD_WQ80E_80_33", + .cfg = &flashCfg_Gd_WQ80E_WQ16E, + }, { - .jedecID = 0x1565C8, - .name = "GD_WQ16E_16_33", - .cfg = &flashCfg_Gd_WQ80E_WQ16E, - }, + .jedecID = 0x1565C8, + .name = "GD_WQ16E_16_33", + .cfg = &flashCfg_Gd_WQ80E_WQ16E, + }, { - .jedecID = 0x1665C8, - .name = "GD_WQ32E_32_33", - .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, - }, + .jedecID = 0x1665C8, + .name = "GD_WQ32E_32_33", + .cfg = &flashCfg_Gd_LQ08C_LE16C_LQ32D_WQ32E, + }, { - .jedecID = 0x3425C2, - .name = "MX_25V80_08_18", - .cfg = &flashCfg_Mxic, - }, + .jedecID = 0x3425C2, + .name = "MX_25V80_08_18", + .cfg = &flashCfg_Mxic, + }, { - .jedecID = 0x3525C2, - .name = "MX_25U16_35_18", - .cfg = &flashCfg_Mxic_1635F, - }, + .jedecID = 0x3525C2, + .name = "MX_25U16_35_18", + .cfg = &flashCfg_Mxic_1635F, + }, { - .jedecID = 0x3625C2, - .name = "MX_25V32_32_18", - .cfg = &flashCfg_Mxic, - }, + .jedecID = 0x3625C2, + .name = "MX_25V32_32_18", + .cfg = &flashCfg_Mxic, + }, { - .jedecID = 0x13400B, - .name = "XT_25F04D_04_33", - .cfg = &flashCfg_Xtx40, - }, + .jedecID = 0x13400B, + .name = "XT_25F04D_04_33", + .cfg = &flashCfg_Xtx40, + }, { - .jedecID = 0x15400B, - .name = "XT_25F16B_16_33", - .cfg = &flashCfg_Xtx, - }, + .jedecID = 0x15400B, + .name = "XT_25F16B_16_33", + .cfg = &flashCfg_Xtx, + }, { - .jedecID = 0x16400B, - .name = "XT_25F32B_32_33", - .cfg = &flashCfg_Xtx, - }, + .jedecID = 0x16400B, + .name = "XT_25F32B_32_33", + .cfg = &flashCfg_Xtx, + }, { - .jedecID = 0x14600B, - .name = "XT_25Q80B_08_18", - .cfg = &flashCfg_Xtx, - }, + .jedecID = 0x14600B, + .name = "XT_25Q80B_08_18", + .cfg = &flashCfg_Xtx, + }, { - .jedecID = 0x16600B, - .name = "XT_25Q32B_32_18", - .cfg = &flashCfg_Xtx, - }, + .jedecID = 0x16600B, + .name = "XT_25Q32B_32_18", + .cfg = &flashCfg_Xtx, + }, { - .jedecID = 0x146085, - .name = "Puya_Q80L/H_08_18/33", - .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, - }, + .jedecID = 0x146085, + .name = "Puya_Q80L/H_08_18/33", + .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, + }, { - .jedecID = 0x156085, - .name = "Puya_Q16H_16_33", - .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, - }, + .jedecID = 0x156085, + .name = "Puya_Q16H_16_33", + .cfg = &flashCfg_Puya_Q80L_Q80H_Q16H, + }, { - .jedecID = 0x166085, - .name = "Puya_Q32H_32_33", - .cfg = &flashCfg_Puya_Q32H, - }, + .jedecID = 0x166085, + .name = "Puya_Q32H_32_33", + .cfg = &flashCfg_Puya_Q32H, + }, { - .jedecID = 0x134068, - .name = "Boya_Q04B_04_33", - .cfg = &flashCfg_Boya40, - }, + .jedecID = 0x134068, + .name = "Boya_Q04B_04_33", + .cfg = &flashCfg_Boya40, + }, { - .jedecID = 0x144068, - .name = "Boya_Q08B_08_33", - .cfg = &flashCfg_Boya, - }, + .jedecID = 0x144068, + .name = "Boya_Q08B_08_33", + .cfg = &flashCfg_Boya, + }, { - .jedecID = 0x154068, - .name = "Boya_Q16B_16_33", - .cfg = &flashCfg_Boya, - }, + .jedecID = 0x154068, + .name = "Boya_Q16B_16_33", + .cfg = &flashCfg_Boya, + }, { - .jedecID = 0x164068, - .name = "Boya_Q32B_32_33", - .cfg = &flashCfg_Boya, - }, + .jedecID = 0x164068, + .name = "Boya_Q32B_32_33", + .cfg = &flashCfg_Boya, + }, { - .jedecID = 0x174068, - .name = "Boya_Q64A_64_33", - .cfg = &flashCfg_Boya, - }, + .jedecID = 0x174068, + .name = "Boya_Q64A_64_33", + .cfg = &flashCfg_Boya, + }, { - .jedecID = 0x184068, - .name = "Boya_Q128A_128_33", - .cfg = &flashCfg_Boya, - }, + .jedecID = 0x184068, + .name = "Boya_Q128A_128_33", + .cfg = &flashCfg_Boya, + }, { - .jedecID = 0x14605E, - .name = "FT_VQ80", - .cfg = &flashCfg_FT_VQ80, - } + .jedecID = 0x14605E, + .name = "FT_VQ80", + .cfg = &flashCfg_FT_VQ80, + } }; #endif @@ -2074,116 +2073,114 @@ static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = { */ /****************************************************************************/ /** - * @brief Init external flash GPIO according to flash GPIO config - * - * @param extFlashPin: Flash GPIO config - * - * @return None - * -*******************************************************************************/ + * @brief Init external flash GPIO according to flash GPIO config + * + * @param extFlashPin: Flash GPIO config + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -/* static */ void ATTR_TCM_SECTION SF_Cfg_Init_Ext_Flash_Gpio(uint8_t extFlashPin) -{ - GLB_GPIO_Cfg_Type cfg; - uint8_t gpiopins[6]; - uint8_t i = 0; - - cfg.gpioMode = GPIO_MODE_AF; - cfg.pullType = GPIO_PULL_UP; - cfg.drive = 1; - cfg.smtCtrl = 1; - cfg.gpioFun = GPIO_FUN_FLASH_PSRAM; - - if (extFlashPin == 0) { - gpiopins[0] = BFLB_EXTFLASH_CLK0_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS0_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA00_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA10_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA20_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA30_GPIO; - } else if (extFlashPin == 1) { - gpiopins[0] = BFLB_EXTFLASH_CLK1_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS1_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA01_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA11_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA21_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA31_GPIO; +/* static */ void ATTR_TCM_SECTION SF_Cfg_Init_Ext_Flash_Gpio(uint8_t extFlashPin) { + GLB_GPIO_Cfg_Type cfg; + uint8_t gpiopins[6]; + uint8_t i = 0; + + cfg.gpioMode = GPIO_MODE_AF; + cfg.pullType = GPIO_PULL_UP; + cfg.drive = 1; + cfg.smtCtrl = 1; + cfg.gpioFun = GPIO_FUN_FLASH_PSRAM; + + if (extFlashPin == 0) { + gpiopins[0] = BFLB_EXTFLASH_CLK0_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS0_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA00_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA10_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA20_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA30_GPIO; + } else if (extFlashPin == 1) { + gpiopins[0] = BFLB_EXTFLASH_CLK1_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS1_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA01_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA11_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA21_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA31_GPIO; + } else { + gpiopins[0] = BFLB_EXTFLASH_CLK2_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS2_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA02_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA12_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA22_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA32_GPIO; + } + + for (i = 0; i < sizeof(gpiopins); i++) { + cfg.gpioPin = gpiopins[i]; + + if (i == 0 || i == 1) { + /*flash clk and cs is output*/ + cfg.gpioMode = GPIO_MODE_OUTPUT; } else { - gpiopins[0] = BFLB_EXTFLASH_CLK2_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS2_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA02_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA12_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA22_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA32_GPIO; + /*data are bidir*/ + cfg.gpioMode = GPIO_MODE_AF; } - for (i = 0; i < sizeof(gpiopins); i++) { - cfg.gpioPin = gpiopins[i]; - - if (i == 0 || i == 1) { - /*flash clk and cs is output*/ - cfg.gpioMode = GPIO_MODE_OUTPUT; - } else { - /*data are bidir*/ - cfg.gpioMode = GPIO_MODE_AF; - } - - GLB_GPIO_Init(&cfg); - } + GLB_GPIO_Init(&cfg); + } } #endif /****************************************************************************/ /** - * @brief Deinit external flash GPIO according to flash GPIO config - * - * @param extFlashPin: Flash GPIO config - * - * @return None - * -*******************************************************************************/ + * @brief Deinit external flash GPIO according to flash GPIO config + * + * @param extFlashPin: Flash GPIO config + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -/* static */ void ATTR_TCM_SECTION SF_Cfg_Deinit_Ext_Flash_Gpio(uint8_t extFlashPin) -{ - GLB_GPIO_Cfg_Type cfg; - uint8_t gpiopins[6]; - uint8_t i = 0; - - cfg.gpioMode = GPIO_MODE_INPUT; - cfg.pullType = GPIO_PULL_UP; - cfg.drive = 1; - cfg.smtCtrl = 1; - cfg.gpioFun = GPIO_FUN_GPIO; - - if (extFlashPin == 0) { - gpiopins[0] = BFLB_EXTFLASH_CLK0_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS0_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA00_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA10_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA20_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA30_GPIO; - - } else if (extFlashPin == 1) { - gpiopins[0] = BFLB_EXTFLASH_CLK1_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS1_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA01_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA11_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA21_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA31_GPIO; - } else { - gpiopins[0] = BFLB_EXTFLASH_CLK2_GPIO; - gpiopins[1] = BFLB_EXTFLASH_CS2_GPIO; - gpiopins[2] = BFLB_EXTFLASH_DATA02_GPIO; - gpiopins[3] = BFLB_EXTFLASH_DATA12_GPIO; - gpiopins[4] = BFLB_EXTFLASH_DATA22_GPIO; - gpiopins[5] = BFLB_EXTFLASH_DATA32_GPIO; - } - - for (i = 0; i < sizeof(gpiopins); i++) { - cfg.gpioPin = gpiopins[i]; - GLB_GPIO_Init(&cfg); - } +/* static */ void ATTR_TCM_SECTION SF_Cfg_Deinit_Ext_Flash_Gpio(uint8_t extFlashPin) { + GLB_GPIO_Cfg_Type cfg; + uint8_t gpiopins[6]; + uint8_t i = 0; + + cfg.gpioMode = GPIO_MODE_INPUT; + cfg.pullType = GPIO_PULL_UP; + cfg.drive = 1; + cfg.smtCtrl = 1; + cfg.gpioFun = GPIO_FUN_GPIO; + + if (extFlashPin == 0) { + gpiopins[0] = BFLB_EXTFLASH_CLK0_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS0_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA00_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA10_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA20_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA30_GPIO; + + } else if (extFlashPin == 1) { + gpiopins[0] = BFLB_EXTFLASH_CLK1_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS1_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA01_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA11_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA21_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA31_GPIO; + } else { + gpiopins[0] = BFLB_EXTFLASH_CLK2_GPIO; + gpiopins[1] = BFLB_EXTFLASH_CS2_GPIO; + gpiopins[2] = BFLB_EXTFLASH_DATA02_GPIO; + gpiopins[3] = BFLB_EXTFLASH_DATA12_GPIO; + gpiopins[4] = BFLB_EXTFLASH_DATA22_GPIO; + gpiopins[5] = BFLB_EXTFLASH_DATA32_GPIO; + } + + for (i = 0; i < sizeof(gpiopins); i++) { + cfg.gpioPin = gpiopins[i]; + GLB_GPIO_Init(&cfg); + } } #endif @@ -2194,206 +2191,202 @@ __WEAK */ /****************************************************************************/ /** - * @brief Get flash config according to flash ID - * - * @param flashID: Flash ID - * @param pFlashCfg: Flash config pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Get flash config according to flash ID + * + * @param flashID: Flash ID + * @param pFlashCfg: Flash config pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) -{ - uint32_t i; - uint8_t buf[sizeof(SPI_Flash_Cfg_Type) + 8]; - uint32_t crc, *pCrc; - uint32_t xipOffset; - - if (flashID == 0) { - xipOffset = SF_Ctrl_Get_Flash_Image_Offset(); - SF_Ctrl_Set_Flash_Image_Offset(0); - XIP_SFlash_Read_Via_Cache_Need_Lock(8 + BL702_FLASH_XIP_BASE, buf, sizeof(SPI_Flash_Cfg_Type) + 8); - SF_Ctrl_Set_Flash_Image_Offset(xipOffset); - - if (BL702_MemCmp(buf, BFLB_FLASH_CFG_MAGIC, 4) == 0) { - crc = BFLB_Soft_CRC32((uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); - pCrc = (uint32_t *)(buf + 4 + sizeof(SPI_Flash_Cfg_Type)); - - if (*pCrc == crc) { - BL702_MemCpy_Fast(pFlashCfg, (uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); - return SUCCESS; - } - } - } else { - for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { - if (flashInfos[i].jedecID == flashID) { - BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); - return SUCCESS; - } - } +BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) { + uint32_t i; + uint8_t buf[sizeof(SPI_Flash_Cfg_Type) + 8]; + uint32_t crc, *pCrc; + uint32_t xipOffset; + + if (flashID == 0) { + xipOffset = SF_Ctrl_Get_Flash_Image_Offset(); + SF_Ctrl_Set_Flash_Image_Offset(0); + XIP_SFlash_Read_Via_Cache_Need_Lock(8 + BL702_FLASH_XIP_BASE, buf, sizeof(SPI_Flash_Cfg_Type) + 8); + SF_Ctrl_Set_Flash_Image_Offset(xipOffset); + + if (BL702_MemCmp(buf, BFLB_FLASH_CFG_MAGIC, 4) == 0) { + crc = BFLB_Soft_CRC32((uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); + pCrc = (uint32_t *)(buf + 4 + sizeof(SPI_Flash_Cfg_Type)); + + if (*pCrc == crc) { + BL702_MemCpy_Fast(pFlashCfg, (uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); + return SUCCESS; + } + } + } else { + for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { + if (flashInfos[i].jedecID == flashID) { + BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); + return SUCCESS; + } } + } - return ERROR; + return ERROR; } #endif /****************************************************************************/ /** - * @brief Init flash GPIO according to flash Pin config - * - * @param flashPinCfg: Specify flash Pin config - * @param restoreDefault: Wether to restore default setting - * - * @return None - * -*******************************************************************************/ + * @brief Init flash GPIO according to flash Pin config + * + * @param flashPinCfg: Specify flash Pin config + * @param restoreDefault: Wether to restore default setting + * + * @return None + * + *******************************************************************************/ __WEAK -void ATTR_TCM_SECTION SF_Cfg_Init_Flash_Gpio(uint8_t flashPinCfg, uint8_t restoreDefault) -{ - uint8_t flashCfg; - uint8_t swapCfg; - uint32_t tmpVal; - - flashCfg = (flashPinCfg >> 2) & 0x03; - swapCfg = flashPinCfg & 0x03; - - if (restoreDefault) { - /* Set Default first */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - - if (BL_GET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO) == 0x00) { - SF_Cfg_Init_Ext_Flash_Gpio(1); - } - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF2); - - /* Default is set, so return */ - if (flashCfg == BFLB_FLASH_CFG_SF2_EXT_23_28 && swapCfg == BFLB_SF2_SWAP_NONE) { - return; - } +void ATTR_TCM_SECTION SF_Cfg_Init_Flash_Gpio(uint8_t flashPinCfg, uint8_t restoreDefault) { + uint8_t flashCfg; + uint8_t swapCfg; + uint32_t tmpVal; + + flashCfg = (flashPinCfg >> 2) & 0x03; + swapCfg = flashPinCfg & 0x03; + + if (restoreDefault) { + /* Set Default first */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); + + if (BL_GET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO) == 0x00) { + SF_Cfg_Init_Ext_Flash_Gpio(1); + } + + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + + SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF2); + + /* Default is set, so return */ + if (flashCfg == BFLB_FLASH_CFG_SF2_EXT_23_28 && swapCfg == BFLB_SF2_SWAP_NONE) { + return; } + } + + if (flashCfg == BFLB_FLASH_CFG_SF1_EXT_17_22) { + SF_Cfg_Init_Ext_Flash_Gpio(0); + SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF1); + } else { + tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - if (flashCfg == BFLB_FLASH_CFG_SF1_EXT_17_22) { - SF_Cfg_Init_Ext_Flash_Gpio(0); - SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF1); + if (BL_GET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO) == 0x00) { + SF_Cfg_Init_Ext_Flash_Gpio(1); + } + + tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); + + if (swapCfg == BFLB_SF2_SWAP_NONE) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); + } else if (swapCfg == BFLB_SF2_SWAP_CS_IO2) { + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); + } else if (swapCfg == BFLB_SF2_SWAP_IO0_IO3) { + tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); } else { - tmpVal = BL_RD_REG(GLB_BASE, GLB_GPIO_USE_PSRAM__IO); - - if (BL_GET_REG_BITS_VAL(tmpVal, GLB_CFG_GPIO_USE_PSRAM_IO) == 0x00) { - SF_Cfg_Init_Ext_Flash_Gpio(1); - } - - tmpVal = BL_RD_REG(GLB_BASE, GLB_PARM); - - if (swapCfg == BFLB_SF2_SWAP_NONE) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - } else if (swapCfg == BFLB_SF2_SWAP_CS_IO2) { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - } else if (swapCfg == BFLB_SF2_SWAP_IO0_IO3) { - tmpVal = BL_CLR_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - } else { - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); - tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); - } - - BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); - - SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_CS_IO2); + tmpVal = BL_SET_REG_BIT(tmpVal, GLB_CFG_SFLASH2_SWAP_IO0_IO3); } + + BL_WR_REG(GLB_BASE, GLB_PARM, tmpVal); + + SF_Ctrl_Select_Pad(SF_CTRL_PAD_SEL_SF2); + } } /****************************************************************************/ /** - * @brief Identify one flash - * - * @param callFromFlash: code run at flash or ram - * @param autoScan: Auto scan all GPIO pin - * @param flashPinCfg: Specify flash GPIO config, not auto scan - * @param restoreDefault: Wether restore default flash GPIO config - * @param pFlashCfg: Flash config pointer - * - * @return Flash ID - * -*******************************************************************************/ + * @brief Identify one flash + * + * @param callFromFlash: code run at flash or ram + * @param autoScan: Auto scan all GPIO pin + * @param flashPinCfg: Specify flash GPIO config, not auto scan + * @param restoreDefault: Wether restore default flash GPIO config + * @param pFlashCfg: Flash config pointer + * + * @return Flash ID + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint32_t ATTR_TCM_SECTION SF_Cfg_Flash_Identify(uint8_t callFromFlash, - uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, SPI_Flash_Cfg_Type *pFlashCfg) -{ - uint32_t jdecId = 0; - uint32_t i = 0; - uint32_t offset; - BL_Err_Type stat; +uint32_t ATTR_TCM_SECTION SF_Cfg_Flash_Identify(uint8_t callFromFlash, uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, SPI_Flash_Cfg_Type *pFlashCfg) { + uint32_t jdecId = 0; + uint32_t i = 0; + uint32_t offset; + BL_Err_Type stat; - BL702_MemCpy_Fast(pFlashCfg, &flashCfg_Gd_Q80E_Q16E, sizeof(SPI_Flash_Cfg_Type)); + BL702_MemCpy_Fast(pFlashCfg, &flashCfg_Gd_Q80E_Q16E, sizeof(SPI_Flash_Cfg_Type)); - if (callFromFlash == 1) { - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + if (callFromFlash == 1) { + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SF_Ctrl_Set_Owner(SF_CTRL_OWNER_IAHB); - return 0; - } + if (stat != SUCCESS) { + SF_Ctrl_Set_Owner(SF_CTRL_OWNER_IAHB); + return 0; } - - if (autoScan) { - flashPinCfg = 0; - - do { - if (flashPinCfg > 0x0f) { - jdecId = 0; - break; - } - - SF_Cfg_Init_Flash_Gpio(flashPinCfg, restoreDefault); - SFlash_Releae_Powerdown(pFlashCfg); - SFlash_Reset_Continue_Read(pFlashCfg); - SFlash_DisableBurstWrap(pFlashCfg); - jdecId = 0; - SFlash_GetJedecId(pFlashCfg, (uint8_t *)&jdecId); - SFlash_DisableBurstWrap(pFlashCfg); - jdecId = jdecId & 0xffffff; - flashPinCfg++; - } while ((jdecId & 0x00ffff) == 0 || (jdecId & 0xffff00) == 0 || (jdecId & 0x00ffff) == 0xffff || (jdecId & 0xffff00) == 0xffff00); - } else { - /* select media gpio */ - SF_Cfg_Init_Flash_Gpio(flashPinCfg, restoreDefault); - SFlash_Releae_Powerdown(pFlashCfg); - SFlash_Reset_Continue_Read(pFlashCfg); - SFlash_DisableBurstWrap(pFlashCfg); - SFlash_GetJedecId(pFlashCfg, (uint8_t *)&jdecId); - SFlash_DisableBurstWrap(pFlashCfg); - jdecId = jdecId & 0xffffff; + } + + if (autoScan) { + flashPinCfg = 0; + + do { + if (flashPinCfg > 0x0f) { + jdecId = 0; + break; + } + + SF_Cfg_Init_Flash_Gpio(flashPinCfg, restoreDefault); + SFlash_Releae_Powerdown(pFlashCfg); + SFlash_Reset_Continue_Read(pFlashCfg); + SFlash_DisableBurstWrap(pFlashCfg); + jdecId = 0; + SFlash_GetJedecId(pFlashCfg, (uint8_t *)&jdecId); + SFlash_DisableBurstWrap(pFlashCfg); + jdecId = jdecId & 0xffffff; + flashPinCfg++; + } while ((jdecId & 0x00ffff) == 0 || (jdecId & 0xffff00) == 0 || (jdecId & 0x00ffff) == 0xffff || (jdecId & 0xffff00) == 0xffff00); + } else { + /* select media gpio */ + SF_Cfg_Init_Flash_Gpio(flashPinCfg, restoreDefault); + SFlash_Releae_Powerdown(pFlashCfg); + SFlash_Reset_Continue_Read(pFlashCfg); + SFlash_DisableBurstWrap(pFlashCfg); + SFlash_GetJedecId(pFlashCfg, (uint8_t *)&jdecId); + SFlash_DisableBurstWrap(pFlashCfg); + jdecId = jdecId & 0xffffff; + } + + for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { + if (flashInfos[i].jedecID == jdecId) { + BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); + break; } + } - for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { - if (flashInfos[i].jedecID == jdecId) { - BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); - break; - } + if (i == sizeof(flashInfos) / sizeof(flashInfos[0])) { + if (callFromFlash == 1) { + XIP_SFlash_State_Restore(pFlashCfg, pFlashCfg->ioMode, offset); } - if (i == sizeof(flashInfos) / sizeof(flashInfos[0])) { - if (callFromFlash == 1) { - XIP_SFlash_State_Restore(pFlashCfg, pFlashCfg->ioMode, offset); - } - - return jdecId; - } else { - if (callFromFlash == 1) { - XIP_SFlash_State_Restore(pFlashCfg, pFlashCfg->ioMode, offset); - } - - return (jdecId | BFLB_FLASH_ID_VALID_FLAG); + return jdecId; + } else { + if (callFromFlash == 1) { + XIP_SFlash_State_Restore(pFlashCfg, pFlashCfg->ioMode, offset); } + + return (jdecId | BFLB_FLASH_ID_VALID_FLAG); + } } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c index d90928c88..e74513200 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_cfg_ext.c @@ -1,44 +1,44 @@ /** - ****************************************************************************** - * @file bl702_sf_cfg_ext.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sf_cfg_ext.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ +#include "bl702_sf_cfg_ext.h" #include "bl702_glb.h" +#include "bl702_romdriver.h" #include "bl702_sf_cfg.h" -#include "bl702_sf_cfg_ext.h" #include "bl702_xip_sflash.h" -#include "bl702_romdriver.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -58,11 +58,10 @@ /** @defgroup SF_CFG_EXT_Private_Types * @{ */ -typedef struct -{ - uint32_t jedecID; - char *name; - const SPI_Flash_Cfg_Type *cfg; +typedef struct { + uint32_t jedecID; + char *name; + const SPI_Flash_Cfg_Type *cfg; } Flash_Info_t; /*@} end of group SF_CFG_EXT_Private_Types */ @@ -71,489 +70,489 @@ typedef struct * @{ */ -static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_Md_40D={ - .resetCreadCmd = 0xff, +static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Gd_Md_40D = { + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0x51, + .mid = 0x51, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16/8, - .cReadSupport = 0, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 0, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, - /*erase*/ - .chipEraseCmd = 0xc7, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, + /*erase*/ + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = 0x11, - .clkDelay = 1, + .ioMode = 0x11, + .clkDelay = 1, .clkInvert = 0x3f, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8/8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8/8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8/8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8/8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16/8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, - /*AC*/ + /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 20*1000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 20 * 1000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_MX_KH25 = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc2, + .mid = 0xc2, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x00, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x00, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x00, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 0, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 0, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = 0x11, - .clkDelay = 1, + .ioMode = 0x11, + .clkDelay = 1, .clkInvert = 0x01, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 33000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 33000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_FM_Q80 = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xc8, + .mid = 0xc8, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x02, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x01, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0xA0, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0xA0, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x01, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 300, - .timeE32k = 1200, - .timeE64k = 1200, + .timeE32k = 1200, + .timeE64k = 1200, .timePagePgm = 5, - .timeCe = 33000, - .pdDelay = 20, - .qeData = 0, + .timeCe = 33000, + .pdDelay = 20, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION SPI_Flash_Cfg_Type flashCfg_Winb_16JV = { - .resetCreadCmd = 0xff, + .resetCreadCmd = 0xff, .resetCreadCmdSize = 3, - .mid = 0xef, + .mid = 0xef, - .deBurstWrapCmd = 0x77, + .deBurstWrapCmd = 0x77, .deBurstWrapCmdDmyClk = 0x3, - .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, - .deBurstWrapData = 0xF0, + .deBurstWrapDataMode = SF_CTRL_DATA_4_LINES, + .deBurstWrapData = 0xF0, /*reg*/ - .writeEnableCmd = 0x06, - .wrEnableIndex = 0x00, - .wrEnableBit = 0x01, + .writeEnableCmd = 0x06, + .wrEnableIndex = 0x00, + .wrEnableBit = 0x01, .wrEnableReadRegLen = 0x01, - .qeIndex = 1, - .qeBit = 0x01, + .qeIndex = 1, + .qeBit = 0x01, .qeWriteRegLen = 0x01, - .qeReadRegLen = 0x1, + .qeReadRegLen = 0x1, - .busyIndex = 0, - .busyBit = 0x00, - .busyReadRegLen = 0x1, + .busyIndex = 0, + .busyBit = 0x00, + .busyReadRegLen = 0x1, .releasePowerDown = 0xab, - .readRegCmd[0] = 0x05, - .readRegCmd[1] = 0x35, + .readRegCmd[0] = 0x05, + .readRegCmd[1] = 0x35, .writeRegCmd[0] = 0x01, .writeRegCmd[1] = 0x31, .fastReadQioCmd = 0xeb, - .frQioDmyClk = 16 / 8, - .cReadSupport = 1, - .cReadMode = 0x20, + .frQioDmyClk = 16 / 8, + .cReadSupport = 1, + .cReadMode = 0x20, - .burstWrapCmd = 0x77, + .burstWrapCmd = 0x77, .burstWrapCmdDmyClk = 0x3, - .burstWrapDataMode = SF_CTRL_DATA_4_LINES, - .burstWrapData = 0x40, + .burstWrapDataMode = SF_CTRL_DATA_4_LINES, + .burstWrapData = 0x40, /*erase*/ - .chipEraseCmd = 0xc7, + .chipEraseCmd = 0xc7, .sectorEraseCmd = 0x20, - .blk32EraseCmd = 0x52, - .blk64EraseCmd = 0xd8, + .blk32EraseCmd = 0x52, + .blk64EraseCmd = 0xd8, /*write*/ - .pageProgramCmd = 0x02, + .pageProgramCmd = 0x02, .qpageProgramCmd = 0x32, - .qppAddrMode = SF_CTRL_ADDR_1_LINE, + .qppAddrMode = SF_CTRL_ADDR_1_LINE, - .ioMode = SF_CTRL_QIO_MODE, - .clkDelay = 1, + .ioMode = SF_CTRL_QIO_MODE, + .clkDelay = 1, .clkInvert = 0x01, - .resetEnCmd = 0x66, - .resetCmd = 0x99, - .cRExit = 0xff, + .resetEnCmd = 0x66, + .resetCmd = 0x99, + .cRExit = 0xff, .wrEnableWriteRegLen = 0x00, /*id*/ - .jedecIdCmd = 0x9f, - .jedecIdCmdDmyClk = 0, - .qpiJedecIdCmd = 0x9f, + .jedecIdCmd = 0x9f, + .jedecIdCmdDmyClk = 0, + .qpiJedecIdCmd = 0x9f, .qpiJedecIdCmdDmyClk = 0x00, - .sectorSize = 4, - .pageSize = 256, + .sectorSize = 4, + .pageSize = 256, /*read*/ - .fastReadCmd = 0x0b, - .frDmyClk = 8 / 8, + .fastReadCmd = 0x0b, + .frDmyClk = 8 / 8, .qpiFastReadCmd = 0x0b, - .qpiFrDmyClk = 8 / 8, - .fastReadDoCmd = 0x3b, - .frDoDmyClk = 8 / 8, + .qpiFrDmyClk = 8 / 8, + .fastReadDoCmd = 0x3b, + .frDoDmyClk = 8 / 8, .fastReadDioCmd = 0xbb, - .frDioDmyClk = 0, - .fastReadQoCmd = 0x6b, - .frQoDmyClk = 8 / 8, + .frDioDmyClk = 0, + .fastReadQoCmd = 0x6b, + .frQoDmyClk = 8 / 8, - .qpiFastReadQioCmd = 0xeb, - .qpiFrQioDmyClk = 16 / 8, - .qpiPageProgramCmd = 0x02, + .qpiFastReadQioCmd = 0xeb, + .qpiFrQioDmyClk = 16 / 8, + .qpiPageProgramCmd = 0x02, .writeVregEnableCmd = 0x50, /* qpi mode */ .enterQpi = 0x38, - .exitQpi = 0xff, + .exitQpi = 0xff, /*AC*/ .timeEsector = 400, - .timeE32k = 1600, - .timeE64k = 2000, + .timeE32k = 1600, + .timeE64k = 2000, .timePagePgm = 5, - .timeCe = 33000, - .pdDelay = 3, - .qeData = 0, + .timeCe = 33000, + .pdDelay = 3, + .qeData = 0, }; static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = { { - .jedecID = 0x134051, - .name = "GD_MD04D_04_33", - .cfg = &flashCfg_Gd_Md_40D, - }, + .jedecID = 0x134051, + .name = "GD_MD04D_04_33", + .cfg = &flashCfg_Gd_Md_40D, + }, { - .jedecID = 0x1320c2, - .name = "MX_KH40_04_33", - .cfg = &flashCfg_MX_KH25, - }, + .jedecID = 0x1320c2, + .name = "MX_KH40_04_33", + .cfg = &flashCfg_MX_KH25, + }, { - .jedecID = 0x1420c2, - .name = "MX_KH80_08_33", - .cfg = &flashCfg_MX_KH25, - }, + .jedecID = 0x1420c2, + .name = "MX_KH80_08_33", + .cfg = &flashCfg_MX_KH25, + }, { - .jedecID = 0x1520c2, - .name = "MX_KH16_16_33", - .cfg = &flashCfg_MX_KH25, - }, + .jedecID = 0x1520c2, + .name = "MX_KH16_16_33", + .cfg = &flashCfg_MX_KH25, + }, { - .jedecID = 0x1440A1, - .name = "FM_25Q80_80_33", - .cfg = &flashCfg_FM_Q80, - }, + .jedecID = 0x1440A1, + .name = "FM_25Q80_80_33", + .cfg = &flashCfg_FM_Q80, + }, { - .jedecID = 0x1570EF, - .name = "Winb_16JV_16_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x1570EF, + .name = "Winb_16JV_16_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x1870EF, - .name = "Winb_128JV_128_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x1870EF, + .name = "Winb_128JV_128_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x15605E, - .name = "ZB_VQ16_16_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x15605E, + .name = "ZB_VQ16_16_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x144020, - .name = "XM_25QH80_80_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x144020, + .name = "XM_25QH80_80_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x154020, - .name = "XM_25QH16_16_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x154020, + .name = "XM_25QH16_16_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x164020, - .name = "XM_25QH32_32_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x164020, + .name = "XM_25QH32_32_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x174020, - .name = "XM_25QH64_64_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x174020, + .name = "XM_25QH64_64_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x13325E, - .name = "ZB_D40B_80_33", - .cfg = &flashCfg_MX_KH25, - }, + .jedecID = 0x13325E, + .name = "ZB_D40B_80_33", + .cfg = &flashCfg_MX_KH25, + }, { - .jedecID = 0x14325E, - .name = "ZB_D80B_80_33", - .cfg = &flashCfg_MX_KH25, - }, + .jedecID = 0x14325E, + .name = "ZB_D80B_80_33", + .cfg = &flashCfg_MX_KH25, + }, { - .jedecID = 0x15405E, - .name = "ZB_25Q16B_15_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x15405E, + .name = "ZB_25Q16B_15_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x16405E, - .name = "ZB_25Q32B_16_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x16405E, + .name = "ZB_25Q32B_16_33", + .cfg = &flashCfg_Winb_16JV, + }, { - .jedecID = 0x1560EB, - .name = "TH_25Q16HB_16_33", - .cfg = &flashCfg_FM_Q80, - }, + .jedecID = 0x1560EB, + .name = "TH_25Q16HB_16_33", + .cfg = &flashCfg_FM_Q80, + }, { - .jedecID = 0x15345E, - .name = "ZB_25Q16A_15_33", - .cfg = &flashCfg_Winb_16JV, - }, + .jedecID = 0x15345E, + .name = "ZB_25Q16A_15_33", + .cfg = &flashCfg_Winb_16JV, + }, }; /*@} end of group SF_CFG_EXT_Private_Variables */ @@ -575,127 +574,123 @@ static const ATTR_TCM_CONST_SECTION Flash_Info_t flashInfos[] = { */ /****************************************************************************/ /** - * @brief Init internal flash GPIO - * - * @param None - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION SF_Cfg_Init_Internal_Flash_Gpio(void) -{ - GLB_GPIO_Cfg_Type gpioCfg = { - .gpioPin = GLB_GPIO_PIN_0, - .gpioFun = GPIO_FUN_GPIO, - .gpioMode = GPIO_MODE_INPUT, - .pullType = GPIO_PULL_NONE, - .drive = 0, - .smtCtrl = 1, - }; - - /* Turn on Flash pad, GPIO23 - GPIO28 */ - for (uint32_t pin = 23; pin < 29; pin++) { - gpioCfg.gpioPin = pin; - - if (pin == 25) { - gpioCfg.pullType = GPIO_PULL_DOWN; - } else { - gpioCfg.pullType = GPIO_PULL_NONE; - } - - GLB_GPIO_Init(&gpioCfg); + * @brief Init internal flash GPIO + * + * @param None + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION SF_Cfg_Init_Internal_Flash_Gpio(void) { + GLB_GPIO_Cfg_Type gpioCfg = { + .gpioPin = GLB_GPIO_PIN_0, + .gpioFun = GPIO_FUN_GPIO, + .gpioMode = GPIO_MODE_INPUT, + .pullType = GPIO_PULL_NONE, + .drive = 0, + .smtCtrl = 1, + }; + + /* Turn on Flash pad, GPIO23 - GPIO28 */ + for (uint32_t pin = 23; pin < 29; pin++) { + gpioCfg.gpioPin = pin; + + if (pin == 25) { + gpioCfg.pullType = GPIO_PULL_DOWN; + } else { + gpioCfg.pullType = GPIO_PULL_NONE; } + + GLB_GPIO_Init(&gpioCfg); + } } /****************************************************************************/ /** - * @brief Get flash config according to flash ID - * - * @param flashID: Flash ID - * @param pFlashCfg: Flash config pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) -{ - uint32_t i; - uint8_t buf[sizeof(SPI_Flash_Cfg_Type) + 8]; - uint32_t crc, *pCrc; - char flashCfgMagic[] = "FCFG"; - - if (flashID == 0) { - XIP_SFlash_Read_Via_Cache_Need_Lock(8 + BL702_FLASH_XIP_BASE, buf, sizeof(SPI_Flash_Cfg_Type) + 8); - - if (BL702_MemCmp(buf, flashCfgMagic, 4) == 0) { - crc = BFLB_Soft_CRC32((uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); - pCrc = (uint32_t *)(buf + 4 + sizeof(SPI_Flash_Cfg_Type)); - - if (*pCrc == crc) { - BL702_MemCpy_Fast(pFlashCfg, (uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); - return SUCCESS; - } - } - } else { - if (SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID, pFlashCfg) == SUCCESS) { - /* 0x134051 flash cfg is wrong in rom, find again */ - if ((flashID&0xFFFFFF) != 0x134051) { - return SUCCESS; - } - } - - for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { - if (flashInfos[i].jedecID == flashID) { - BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); - return SUCCESS; - } - } + * @brief Get flash config according to flash ID + * + * @param flashID: Flash ID + * @param pFlashCfg: Flash config pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock_Ext(uint32_t flashID, SPI_Flash_Cfg_Type *pFlashCfg) { + uint32_t i; + uint8_t buf[sizeof(SPI_Flash_Cfg_Type) + 8]; + uint32_t crc, *pCrc; + char flashCfgMagic[] = "FCFG"; + + if (flashID == 0) { + XIP_SFlash_Read_Via_Cache_Need_Lock(8 + BL702_FLASH_XIP_BASE, buf, sizeof(SPI_Flash_Cfg_Type) + 8); + + if (BL702_MemCmp(buf, flashCfgMagic, 4) == 0) { + crc = BFLB_Soft_CRC32((uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); + pCrc = (uint32_t *)(buf + 4 + sizeof(SPI_Flash_Cfg_Type)); + + if (*pCrc == crc) { + BL702_MemCpy_Fast(pFlashCfg, (uint8_t *)buf + 4, sizeof(SPI_Flash_Cfg_Type)); + return SUCCESS; + } + } + } else { + if (SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID, pFlashCfg) == SUCCESS) { + /* 0x134051 flash cfg is wrong in rom, find again */ + if ((flashID & 0xFFFFFF) != 0x134051) { + return SUCCESS; + } } - return ERROR; + for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { + if (flashInfos[i].jedecID == flashID) { + BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); + return SUCCESS; + } + } + } + + return ERROR; } /****************************************************************************/ /** - * @brief Identify one flash - * - * @param callFromFlash: code run at flash or ram - * @param autoScan: Auto scan all GPIO pin - * @param flashPinCfg: Specify flash GPIO config, not auto scan - * @param restoreDefault: Wether restore default flash GPIO config - * @param pFlashCfg: Flash config pointer - * - * @return Flash ID - * -*******************************************************************************/ -uint32_t ATTR_TCM_SECTION SF_Cfg_Flash_Identify_Ext(uint8_t callFromFlash, - uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, SPI_Flash_Cfg_Type *pFlashCfg) -{ - uint32_t jdecId = 0; - uint32_t i = 0; - uint32_t ret = 0; - - ret = SF_Cfg_Flash_Identify(callFromFlash, autoScan, flashPinCfg, restoreDefault, pFlashCfg); - - if ((ret & BFLB_FLASH_ID_VALID_FLAG) != 0) { - /* 0x134051 flash cfg is wrong in rom, find again */ - if ((ret&0xFFFFFF) != 0x134051) { - return ret; - } + * @brief Identify one flash + * + * @param callFromFlash: code run at flash or ram + * @param autoScan: Auto scan all GPIO pin + * @param flashPinCfg: Specify flash GPIO config, not auto scan + * @param restoreDefault: Wether restore default flash GPIO config + * @param pFlashCfg: Flash config pointer + * + * @return Flash ID + * + *******************************************************************************/ +uint32_t ATTR_TCM_SECTION SF_Cfg_Flash_Identify_Ext(uint8_t callFromFlash, uint32_t autoScan, uint32_t flashPinCfg, uint8_t restoreDefault, SPI_Flash_Cfg_Type *pFlashCfg) { + uint32_t jdecId = 0; + uint32_t i = 0; + uint32_t ret = 0; + + ret = SF_Cfg_Flash_Identify(callFromFlash, autoScan, flashPinCfg, restoreDefault, pFlashCfg); + + if ((ret & BFLB_FLASH_ID_VALID_FLAG) != 0) { + /* 0x134051 flash cfg is wrong in rom, find again */ + if ((ret & 0xFFFFFF) != 0x134051) { + return ret; } + } - jdecId = (ret & 0xffffff); + jdecId = (ret & 0xffffff); - for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { - if (flashInfos[i].jedecID == jdecId) { - BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); - break; - } + for (i = 0; i < sizeof(flashInfos) / sizeof(flashInfos[0]); i++) { + if (flashInfos[i].jedecID == jdecId) { + BL702_MemCpy_Fast(pFlashCfg, flashInfos[i].cfg, sizeof(SPI_Flash_Cfg_Type)); + break; } + } - if (i == sizeof(flashInfos) / sizeof(flashInfos[0])) { - return jdecId; - } else { - return (jdecId | BFLB_FLASH_ID_VALID_FLAG); - } + if (i == sizeof(flashInfos) / sizeof(flashInfos[0])) { + return jdecId; + } else { + return (jdecId | BFLB_FLASH_ID_VALID_FLAG); + } } /*@} end of group SF_CFG_EXT_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c index a67e0e983..93e8c5938 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sf_ctrl.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_sf_ctrl.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sf_ctrl.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_sf_ctrl.h" @@ -60,7 +60,7 @@ * @{ */ #define SF_CTRL_BUSY_STATE_TIMEOUT (5 * 160 * 1000) -#define SF_Ctrl_Get_AES_Region(addr, r) (addr + SF_CTRL_AES_REGION_OFFSET + (r)*0x100) +#define SF_Ctrl_Get_AES_Region(addr, r) (addr + SF_CTRL_AES_REGION_OFFSET + (r) * 0x100) /*@} end of group SF_CTRL_Private_Variables */ @@ -87,1359 +87,1324 @@ */ /****************************************************************************/ /** - * @brief Enable serail flash controller - * - * @param cfg: serial flash controller config - * - * @return None - * -*******************************************************************************/ + * @brief Enable serail flash controller + * + * @param cfg: serial flash controller config + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Enable(const SF_Ctrl_Cfg_Type *cfg) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; - - if (cfg == NULL) { - return; - } - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_OWNER_TYPE(cfg->owner)); +void ATTR_TCM_SECTION SF_Ctrl_Enable(const SF_Ctrl_Cfg_Type *cfg) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + if (cfg == NULL) { + return; + } - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_OWNER_TYPE(cfg->owner)); - if (timeOut == 0) { - return; - } - } + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - if (cfg->clkDelay > 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N, cfg->clkDelay - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); + if (timeOut == 0) { + return; } - - /* Serail out inverted, so sf ctrl send on negative edge */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CLK_OUT_INV_SEL, cfg->clkInvert); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CLK_SF_RX_INV_SEL, cfg->rxClkInvert); - - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); - - /* Set do di and oe delay */ - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_1, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_2, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_3, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_4); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_4, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_1, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_2, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_3, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_4); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_4, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_1, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_2); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_2, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_3); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_3, tmpVal); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_4); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_DO_DLY_SEL, cfg->doDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_DI_DLY_SEL, cfg->diDelay); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_OE_DLY_SEL, cfg->oeDelay); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_4, tmpVal); - - /* Enable AHB access sram buffer and enable sf interface */ - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SRAM_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); - - SF_Ctrl_Set_Owner(cfg->owner); + } + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + + if (cfg->clkDelay > 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N, cfg->clkDelay - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); + } + + /* Serail out inverted, so sf ctrl send on negative edge */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CLK_OUT_INV_SEL, cfg->clkInvert); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CLK_SF_RX_INV_SEL, cfg->rxClkInvert); + + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); + + /* Set do di and oe delay */ + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_0_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_1, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_1_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_2, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_2_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_3, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IO_3_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IO_DLY_4, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_0_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_1, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_1_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_2, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_2_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_3, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IO_3_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF2_IF_IO_DLY_4, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_0_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_1, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_2); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_1_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_2, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_3); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_2_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_3, tmpVal); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_4); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_DO_DLY_SEL, cfg->doDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_DI_DLY_SEL, cfg->diDelay); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF3_IO_3_OE_DLY_SEL, cfg->oeDelay); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF3_IF_IO_DLY_4, tmpVal); + + /* Enable AHB access sram buffer and enable sf interface */ + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SRAM_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); + + SF_Ctrl_Set_Owner(cfg->owner); } #endif /****************************************************************************/ /** - * @brief Enable serail psram controller - * - * @param sfCtrlPsramCfg: serial psram controller config - * - * @return None - * -*******************************************************************************/ -//#ifndef BFLB_USE_ROM_DRIVER + * @brief Enable serail psram controller + * + * @param sfCtrlPsramCfg: serial psram controller config + * + * @return None + * + *******************************************************************************/ +// #ifndef BFLB_USE_ROM_DRIVER //__WEAK -void ATTR_TCM_SECTION SF_Ctrl_Psram_Init(SF_Ctrl_Psram_Cfg *sfCtrlPsramCfg) -{ - uint32_t tmpVal = 0; +void ATTR_TCM_SECTION SF_Ctrl_Psram_Init(SF_Ctrl_Psram_Cfg *sfCtrlPsramCfg) { + uint32_t tmpVal = 0; - SF_Ctrl_Select_Pad(sfCtrlPsramCfg->padSel); - SF_Ctrl_Select_Bank(sfCtrlPsramCfg->bankSel); + SF_Ctrl_Select_Pad(sfCtrlPsramCfg->padSel); + SF_Ctrl_Select_Bank(sfCtrlPsramCfg->bankSel); - /* Select psram clock delay */ - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_12); + /* Select psram clock delay */ + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_12); - if (sfCtrlPsramCfg->psramRxClkInvertSrc) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SRC); + if (sfCtrlPsramCfg->psramRxClkInvertSrc) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SRC); - if (sfCtrlPsramCfg->psramRxClkInvertSel) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SEL); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SEL); - } + if (sfCtrlPsramCfg->psramRxClkInvertSel) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SEL); } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SRC); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SEL); } + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_CLK_SF_RX_INV_SRC); + } - if (sfCtrlPsramCfg->psramDelaySrc) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_SRC); + if (sfCtrlPsramCfg->psramDelaySrc) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_SRC); - if (sfCtrlPsramCfg->psramClkDelay > 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IF_READ_DLY_N, sfCtrlPsramCfg->psramClkDelay - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_EN); - } + if (sfCtrlPsramCfg->psramClkDelay > 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF2_IF_READ_DLY_N, sfCtrlPsramCfg->psramClkDelay - 1); } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_SRC); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_EN); } + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF2_IF_READ_DLY_SRC); + } - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_12, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_12, tmpVal); - /* Enable AHB access sram buffer and enable sf interface */ - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SRAM_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); + /* Enable AHB access sram buffer and enable sf interface */ + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SRAM_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); - SF_Ctrl_Set_Owner(sfCtrlPsramCfg->owner); + SF_Ctrl_Set_Owner(sfCtrlPsramCfg->owner); } -//#endif +// #endif /****************************************************************************/ /** - * @brief Get flash controller clock delay value - * - * @param None - * - * @return Clock delay value - * -*******************************************************************************/ + * @brief Get flash controller clock delay value + * + * @param None + * + * @return Clock delay value + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint8_t ATTR_TCM_SECTION SF_Ctrl_Get_Clock_Delay(void) -{ - uint32_t tmpVal; +uint8_t ATTR_TCM_SECTION SF_Ctrl_Get_Clock_Delay(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); - if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN) == 0) { - return 0; - } else { - return BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N) + 1; - } + if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN) == 0) { + return 0; + } else { + return BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N) + 1; + } } #endif /****************************************************************************/ /** - * @brief Set flash controller clock delay value - * - * @param delay: Clock delay value - * - * @return None - * -*******************************************************************************/ + * @brief Set flash controller clock delay value + * + * @param delay: Clock delay value + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Set_Clock_Delay(uint8_t delay) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_Set_Clock_Delay(uint8_t delay) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); - if (delay > 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N, delay - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); - } + if (delay > 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_READ_DLY_N, delay - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_READ_DLY_EN); + } - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); } #endif /****************************************************************************/ /** - * @brief SF Ctrl set cmds config - * - * @param cmdsCfg: SF Ctrl cmds config - * - * @return None - * -*******************************************************************************/ + * @brief SF Ctrl set cmds config + * + * @param cmdsCfg: SF Ctrl cmds config + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Cmds_Set(SF_Ctrl_Cmds_Cfg *cmdsCfg) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_WRAP_LEN_TYPE(cmdsCfg->wrapLen)); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_3); - - if (cmdsCfg->cmdsEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_EN); - } - - if (cmdsCfg->burstToggleEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_BT_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_BT_EN); - } - - if (cmdsCfg->wrapModeEn) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_WRAP_MODE); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_WRAP_MODE); - } - - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CMDS_WRAP_LEN, cmdsCfg->wrapLen); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_3, tmpVal); +void ATTR_TCM_SECTION SF_Ctrl_Cmds_Set(SF_Ctrl_Cmds_Cfg *cmdsCfg) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_WRAP_LEN_TYPE(cmdsCfg->wrapLen)); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_3); + + if (cmdsCfg->cmdsEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_EN); + } + + if (cmdsCfg->burstToggleEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_BT_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_BT_EN); + } + + if (cmdsCfg->wrapModeEn) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_WRAP_MODE); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CMDS_WRAP_MODE); + } + + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_CMDS_WRAP_LEN, cmdsCfg->wrapLen); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_3, tmpVal); } #endif /****************************************************************************/ /** - * @brief SF Ctrl pad select - * - * @param sel: pad select type - * - * @return None - * -*******************************************************************************/ + * @brief SF Ctrl pad select + * + * @param sel: pad select type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Select_Pad(SF_Ctrl_Pad_Select sel) -{ - /* TODO: sf_if_bk_swap */ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_PAD_SELECT(sel)); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_2); - - if (sel <= SF_CTRL_PAD_SEL_SF3) { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, sel); - } else if (sel >= SF_CTRL_PAD_SEL_DUAL_BANK_SF1_SF2 && sel <= SF_CTRL_PAD_SEL_DUAL_BANK_SF3_SF1) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, sel - SF_CTRL_PAD_SEL_DUAL_BANK_SF1_SF2); - } else if (sel == SF_CTRL_PAD_SEL_DUAL_CS_SF2) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, 1); - } else if (sel == SF_CTRL_PAD_SEL_DUAL_CS_SF3) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, 2); - } - - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_2, tmpVal); +void ATTR_TCM_SECTION SF_Ctrl_Select_Pad(SF_Ctrl_Pad_Select sel) { + /* TODO: sf_if_bk_swap */ + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_PAD_SELECT(sel)); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_2); + + if (sel <= SF_CTRL_PAD_SEL_SF3) { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, sel); + } else if (sel >= SF_CTRL_PAD_SEL_DUAL_BANK_SF1_SF2 && sel <= SF_CTRL_PAD_SEL_DUAL_BANK_SF3_SF1) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, sel - SF_CTRL_PAD_SEL_DUAL_BANK_SF1_SF2); + } else if (sel == SF_CTRL_PAD_SEL_DUAL_CS_SF2) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, 1); + } else if (sel == SF_CTRL_PAD_SEL_DUAL_CS_SF3) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_BK2_MODE); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_PAD_SEL, 2); + } + + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_2, tmpVal); } #endif /****************************************************************************/ /** - * @brief SF Ctrl bank select - * - * @param sel: bank select type - * - * @return None - * -*******************************************************************************/ + * @brief SF Ctrl bank select + * + * @param sel: bank select type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Select_Bank(SF_Ctrl_Select sel) -{ - /* TODO: sf_if_bk_swap */ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_Select_Bank(SF_Ctrl_Select sel) { + /* TODO: sf_if_bk_swap */ + uint32_t tmpVal; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_SELECT(sel)); + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_SELECT(sel)); - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_2); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_2); - if (sel == SF_CTRL_SEL_FLASH) { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_BK_SEL); - } else { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_BK_SEL); - } + if (sel == SF_CTRL_SEL_FLASH) { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_BK_SEL); + } else { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_BK_SEL); + } - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_2, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_2, tmpVal); } #endif /****************************************************************************/ /** - * @brief Set flash controller owner:I/D AHB or system AHB - * - * @param owner: owner type - * - * @return None - * -*******************************************************************************/ + * @brief Set flash controller owner:I/D AHB or system AHB + * + * @param owner: owner type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Set_Owner(SF_Ctrl_Owner_Type owner) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; +void ATTR_TCM_SECTION SF_Ctrl_Set_Owner(SF_Ctrl_Owner_Type owner) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_OWNER_TYPE(owner)); + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_OWNER_TYPE(owner)); - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - if (timeOut == 0) { - return; - } + if (timeOut == 0) { + return; } + } - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - /* Set owner */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL, owner); + /* Set owner */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL, owner); - /* Set iahb to flash interface */ - if (owner == SF_CTRL_OWNER_IAHB) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SIF_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SIF_EN); - } + /* Set iahb to flash interface */ + if (owner == SF_CTRL_OWNER_IAHB) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SIF_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AHB2SIF_EN); + } - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); } #endif /****************************************************************************/ /** - * @brief Disable flash controller - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Disable flash controller + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Disable(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_Disable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_EN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_1, tmpVal); } #endif /****************************************************************************/ /** - * @brief Enable flash controller AES with big indian - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Enable flash controller AES with big indian + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_BE(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_BE(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_KEY_ENDIAN); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_IV_ENDIAN); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_DOUT_ENDIAN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_KEY_ENDIAN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_IV_ENDIAN); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_DOUT_ENDIAN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); } #endif /****************************************************************************/ /** - * @brief Enable flash controller AES with little indian - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Enable flash controller AES with little indian + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_LE(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_LE(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_KEY_ENDIAN); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_IV_ENDIAN); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_DOUT_ENDIAN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_KEY_ENDIAN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_IV_ENDIAN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_DOUT_ENDIAN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); } #endif /****************************************************************************/ /** - * @brief Serial flash controller set AES region - * - * @param region: region number - * @param enable: enable or not - * @param hwKey: hardware key or software key - * @param startAddr: region start address - * @param endAddr: region end address - * @param locked: lock this region or not - * - * @return None - * -*******************************************************************************/ + * @brief Serial flash controller set AES region + * + * @param region: region number + * @param enable: enable or not + * @param hwKey: hardware key or software key + * @param startAddr: region start address + * @param endAddr: region end address + * @param locked: lock this region or not + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Region(uint8_t region, uint8_t enable, - uint8_t hwKey, uint32_t startAddr, uint32_t endAddr, uint8_t locked) -{ - /* Do flash key eco*/ - uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - uint32_t tmpVal; - - if (!hwKey) { - regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - } +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Region(uint8_t region, uint8_t enable, uint8_t hwKey, uint32_t startAddr, uint32_t endAddr, uint8_t locked) { + /* Do flash key eco*/ + uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + uint32_t tmpVal; + + if (!hwKey) { + regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + } - tmpVal = BL_RD_REG(regionRegBase, SF_CTRL_SF_AES_CFG); + tmpVal = BL_RD_REG(regionRegBase, SF_CTRL_SF_AES_CFG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_HW_KEY_EN, hwKey); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_START, startAddr / 1024); - /* sf_aes_end =1 means 1,11,1111,1111 */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_END, endAddr / 1024); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_EN, enable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_LOCK, locked); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_HW_KEY_EN, hwKey); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_START, startAddr / 1024); + /* sf_aes_end =1 means 1,11,1111,1111 */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_END, endAddr / 1024); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_EN, enable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_REGION_LOCK, locked); - BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_CFG, tmpVal); + BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_CFG, tmpVal); } #endif /****************************************************************************/ /** - * @brief Serial flash controller set AES key - * - * @param region: region number - * @param key: key data pointer - * @param keyType: flash controller AES key type:128 bits,192 bits or 256 bits - * - * @return None - * -*******************************************************************************/ + * @brief Serial flash controller set AES key + * + * @param region: region number + * @param key: key data pointer + * @param keyType: flash controller AES key type:128 bits,192 bits or 256 bits + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) -{ - /* Do flash key eco*/ - uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - uint32_t tmpVal, i = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_AES_KEY_TYPE(keyType)); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_MODE, keyType); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); - - if (NULL != key) { - if (keyType == SF_CTRL_AES_128BITS) { - i = 4; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - */ - } else if (keyType == SF_CTRL_AES_256BITS) { - i = 8; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - */ - } else if (keyType == SF_CTRL_AES_192BITS) { - i = 6; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - */ - } - - tmpVal = SF_CTRL_SF_AES_KEY_7_OFFSET; - - while (i--) { - BL_WR_WORD(regionRegBase + tmpVal, __REV(BL_RDWD_FRM_BYTEP(key))); - key += 4; - tmpVal -= 4; - } +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) { + /* Do flash key eco*/ + uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + uint32_t tmpVal, i = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_AES_KEY_TYPE(keyType)); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_MODE, keyType); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); + + if (NULL != key) { + if (keyType == SF_CTRL_AES_128BITS) { + i = 4; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + */ + } else if (keyType == SF_CTRL_AES_256BITS) { + i = 8; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + */ + } else if (keyType == SF_CTRL_AES_192BITS) { + i = 6; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + */ } + + tmpVal = SF_CTRL_SF_AES_KEY_7_OFFSET; + + while (i--) { + BL_WR_WORD(regionRegBase + tmpVal, __REV(BL_RDWD_FRM_BYTEP(key))); + key += 4; + tmpVal -= 4; + } + } } #endif /****************************************************************************/ /** - * @brief Serial flash controller set AES key with big endian - * - * @param region: region number - * @param key: key data pointer - * @param keyType: flash controller AES key type:128 bits,192 bits or 256 bits - * - * @return None - * -*******************************************************************************/ + * @brief Serial flash controller set AES key with big endian + * + * @param region: region number + * @param key: key data pointer + * @param keyType: flash controller AES key type:128 bits,192 bits or 256 bits + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key_BE(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) -{ - /* Do flash key eco*/ - uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - uint32_t tmpVal, i = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_AES_KEY_TYPE(keyType)); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_MODE, keyType); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); - - if (NULL != key) { - if (keyType == SF_CTRL_AES_128BITS) { - i = 4; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); - key+=4; - */ - } else if (keyType == SF_CTRL_AES_256BITS) { - i = 8; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,BL_RDWD_FRM_BYTEP(key)); - key+=4; - */ - } else if (keyType == SF_CTRL_AES_192BITS) { - i = 6; - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,BL_RDWD_FRM_BYTEP(key)); - key+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,BL_RDWD_FRM_BYTEP(key)); - */ - } - - tmpVal = SF_CTRL_SF_AES_KEY_0_OFFSET; - - while (i--) { - BL_WR_WORD(regionRegBase + tmpVal, BL_RDWD_FRM_BYTEP(key)); - key += 4; - tmpVal += 4; - } +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key_BE(uint8_t region, uint8_t *key, SF_Ctrl_AES_Key_Type keyType) { + /* Do flash key eco*/ + uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + uint32_t tmpVal, i = 0; + + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_AES_KEY_TYPE(keyType)); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_AES_MODE, keyType); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); + + if (NULL != key) { + if (keyType == SF_CTRL_AES_128BITS) { + i = 4; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); + key+=4; + */ + } else if (keyType == SF_CTRL_AES_256BITS) { + i = 8; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_6,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_7,BL_RDWD_FRM_BYTEP(key)); + key+=4; + */ + } else if (keyType == SF_CTRL_AES_192BITS) { + i = 6; + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_0,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_1,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_2,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_3,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_4,BL_RDWD_FRM_BYTEP(key)); + key+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_KEY_5,BL_RDWD_FRM_BYTEP(key)); + */ + } + + tmpVal = SF_CTRL_SF_AES_KEY_0_OFFSET; + + while (i--) { + BL_WR_WORD(regionRegBase + tmpVal, BL_RDWD_FRM_BYTEP(key)); + key += 4; + tmpVal += 4; } + } } #endif /****************************************************************************/ /** - * @brief Serial flash controller set AES iv - * - * @param region: region number - * @param iv: iv data pointer - * @param addrOffset: flash address offset - * - * @return None - * -*******************************************************************************/ + * @brief Serial flash controller set AES iv + * + * @param region: region number + * @param iv: iv data pointer + * @param addrOffset: flash address offset + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV(uint8_t region, uint8_t *iv, uint32_t addrOffset) -{ - /* Do flash key eco*/ - uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - uint32_t tmpVal, i = 3; - - if (iv != NULL) { - tmpVal = SF_CTRL_SF_AES_IV_W3_OFFSET; - - while (i--) { - BL_WR_WORD(regionRegBase + tmpVal, __REV(BL_RDWD_FRM_BYTEP(iv))); - iv += 4; - tmpVal -= 4; - } - - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W3,__REV(BL_RDWD_FRM_BYTEP(iv))); - iv+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W2,__REV(BL_RDWD_FRM_BYTEP(iv))); - iv+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W1,__REV(BL_RDWD_FRM_BYTEP(iv))); - iv+=4; - */ - BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_IV_W0, addrOffset); - iv += 4; +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV(uint8_t region, uint8_t *iv, uint32_t addrOffset) { + /* Do flash key eco*/ + uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + uint32_t tmpVal, i = 3; + + if (iv != NULL) { + tmpVal = SF_CTRL_SF_AES_IV_W3_OFFSET; + + while (i--) { + BL_WR_WORD(regionRegBase + tmpVal, __REV(BL_RDWD_FRM_BYTEP(iv))); + iv += 4; + tmpVal -= 4; } + + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W3,__REV(BL_RDWD_FRM_BYTEP(iv))); + iv+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W2,__REV(BL_RDWD_FRM_BYTEP(iv))); + iv+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W1,__REV(BL_RDWD_FRM_BYTEP(iv))); + iv+=4; + */ + BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_IV_W0, addrOffset); + iv += 4; + } } #endif /****************************************************************************/ /** - * @brief Serial flash controller set AES iv with big endian - * - * @param region: region number - * @param iv: iv data pointer - * @param addrOffset: flash address offset - * - * @return None - * -*******************************************************************************/ + * @brief Serial flash controller set AES iv with big endian + * + * @param region: region number + * @param iv: iv data pointer + * @param addrOffset: flash address offset + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV_BE(uint8_t region, uint8_t *iv, uint32_t addrOffset) -{ - /* Do flash key eco*/ - uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); - uint32_t tmpVal, i = 3; - - if (iv != NULL) { - tmpVal = SF_CTRL_SF_AES_IV_W0_OFFSET; - - while (i--) { - BL_WR_WORD(regionRegBase + tmpVal, BL_RDWD_FRM_BYTEP(iv)); - iv += 4; - tmpVal += 4; - } - - /* - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W0,BL_RDWD_FRM_BYTEP(iv)); - iv+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W1,BL_RDWD_FRM_BYTEP(iv)); - iv+=4; - BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W2,BL_RDWD_FRM_BYTEP(iv)); - iv+=4; - */ - BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_IV_W3, __REV(addrOffset)); - iv += 4; +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV_BE(uint8_t region, uint8_t *iv, uint32_t addrOffset) { + /* Do flash key eco*/ + uint32_t regionRegBase = SF_Ctrl_Get_AES_Region(SF_CTRL_BASE, region); + uint32_t tmpVal, i = 3; + + if (iv != NULL) { + tmpVal = SF_CTRL_SF_AES_IV_W0_OFFSET; + + while (i--) { + BL_WR_WORD(regionRegBase + tmpVal, BL_RDWD_FRM_BYTEP(iv)); + iv += 4; + tmpVal += 4; } + + /* + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W0,BL_RDWD_FRM_BYTEP(iv)); + iv+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W1,BL_RDWD_FRM_BYTEP(iv)); + iv+=4; + BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W2,BL_RDWD_FRM_BYTEP(iv)); + iv+=4; + */ + BL_WR_REG(regionRegBase, SF_CTRL_SF_AES_IV_W3, __REV(addrOffset)); + iv += 4; + } } #endif /****************************************************************************/ /** - * @brief Enable serial flash controller AES - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Enable serial flash controller AES + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Enable(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_AES_Enable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_EN); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_AES_EN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); } #endif /****************************************************************************/ /** - * @brief Disable serial flash controller AES - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief Disable serial flash controller AES + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_AES_Disable(void) -{ - uint32_t tmpVal; +void ATTR_TCM_SECTION SF_Ctrl_AES_Disable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_EN); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_AES_EN); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_AES, tmpVal); } #endif /****************************************************************************/ /** - * @brief Check is serial flash controller AES enable - * - * @param None - * - * @return Wether AES is enable - * -*******************************************************************************/ + * @brief Check is serial flash controller AES enable + * + * @param None + * + * @return Wether AES is enable + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint8_t ATTR_TCM_SECTION SF_Ctrl_Is_AES_Enable(void) -{ - uint32_t tmpVal; +uint8_t ATTR_TCM_SECTION SF_Ctrl_Is_AES_Enable(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); - return BL_IS_REG_BIT_SET(tmpVal, SF_CTRL_SF_AES_EN); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_AES); + return BL_IS_REG_BIT_SET(tmpVal, SF_CTRL_SF_AES_EN); } #endif /****************************************************************************/ /** - * @brief Set flash image offset - * - * @param addrOffset: Address offset value - * - * @return None - * -*******************************************************************************/ + * @brief Set flash image offset + * + * @param addrOffset: Address offset value + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Set_Flash_Image_Offset(uint32_t addrOffset) -{ - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, addrOffset); -} +void ATTR_TCM_SECTION SF_Ctrl_Set_Flash_Image_Offset(uint32_t addrOffset) { BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET, addrOffset); } #endif /****************************************************************************/ /** - * @brief Get flash image offset - * - * @param None - * - * @return :Address offset value - * -*******************************************************************************/ + * @brief Get flash image offset + * + * @param None + * + * @return :Address offset value + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -uint32_t ATTR_TCM_SECTION SF_Ctrl_Get_Flash_Image_Offset(void) -{ - return BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET); -} +uint32_t ATTR_TCM_SECTION SF_Ctrl_Get_Flash_Image_Offset(void) { return BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_ID0_OFFSET); } #endif /****************************************************************************/ /** - * @brief SF controller send one command - * - * @param sahbType: Serial flash controller clock sahb sram select - * - * @return None - * -*******************************************************************************/ + * @brief SF controller send one command + * + * @param sahbType: Serial flash controller clock sahb sram select + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Select_Clock(SF_Ctrl_Sahb_Type sahbType) -{ - uint32_t tmpVal = 0; +void ATTR_TCM_SECTION SF_Ctrl_Select_Clock(SF_Ctrl_Sahb_Type sahbType) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_0); - if (sahbType == SF_CTRL_SAHB_CLOCK) { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CLK_SAHB_SRAM_SEL); - } else if (sahbType == SF_CTRL_FLASH_CLOCK) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CLK_SAHB_SRAM_SEL); - } + if (sahbType == SF_CTRL_SAHB_CLOCK) { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_CLK_SAHB_SRAM_SEL); + } else if (sahbType == SF_CTRL_FLASH_CLOCK) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_CLK_SAHB_SRAM_SEL); + } - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_0, tmpVal); } #endif /****************************************************************************/ /** - * @brief SF controller send one command - * - * @param cfg: Serial flash controller command configuration pointer - * - * @return None - * -*******************************************************************************/ + * @brief SF controller send one command + * + * @param cfg: Serial flash controller command configuration pointer + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_SendCmd(SF_Ctrl_Cmd_Cfg_Type *cfg) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; +void ATTR_TCM_SECTION SF_Ctrl_SendCmd(SF_Ctrl_Cmd_Cfg_Type *cfg) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); - CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); - CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); - CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); + CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); + CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); + CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - if (timeOut == 0) { - return; - } + if (timeOut == 0) { + return; } - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - - if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_SAHB) { - return; - } - - /* Clear trigger */ - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0); - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_TRIG); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); - - /* Copy command buffer */ - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_1, cfg->cmdBuf[0]); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_2, cfg->cmdBuf[1]); - - /* Configure SPI and IO mode*/ - if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_QPI_MODE_EN, SF_CTRL_SPI_MODE); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_QPI_MODE_EN, SF_CTRL_QPI_MODE); - } - - if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { - if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_NIO_MODE); - } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_DO_MODE); - } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_QO_MODE); - } - } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_DIO_MODE); - } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_QIO_MODE); - } - - /* Configure cmd */ - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_CMD_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_CMD_BYTE, 0); - - /* Configure address */ - if (cfg->addrSize != 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_ADR_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_ADR_BYTE, cfg->addrSize - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_ADR_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_ADR_BYTE, 0); - } - - /* Configure dummy */ - if (cfg->dummyClks != 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DMY_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DMY_BYTE, cfg->dummyClks - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DMY_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DMY_BYTE, 0); + } + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + + if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_SAHB) { + return; + } + + /* Clear trigger */ + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0); + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_TRIG); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); + + /* Copy command buffer */ + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_1, cfg->cmdBuf[0]); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_2, cfg->cmdBuf[1]); + + /* Configure SPI and IO mode*/ + if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_QPI_MODE_EN, SF_CTRL_SPI_MODE); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_QPI_MODE_EN, SF_CTRL_QPI_MODE); + } + + if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { + if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_NIO_MODE); + } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_DO_MODE); + } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_QO_MODE); } - - /* Configure data */ - if (cfg->nbData != 0) { - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DAT_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_BYTE, cfg->nbData - 1); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DAT_EN); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_BYTE, 0); - } - - /* Set read write flag */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_RW, cfg->rwFlag); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); - - //switch sf_clk_sahb_sram_sel = 1 - SF_Ctrl_Select_Clock(SF_CTRL_FLASH_CLOCK); - /* Trigger */ - tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_TRIG); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); - - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; - - if (timeOut == 0) { - SF_Ctrl_Select_Clock(SF_CTRL_SAHB_CLOCK); - return; - } + } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_DIO_MODE); + } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_SPI_MODE, SF_CTRL_QIO_MODE); + } + + /* Configure cmd */ + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_CMD_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_CMD_BYTE, 0); + + /* Configure address */ + if (cfg->addrSize != 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_ADR_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_ADR_BYTE, cfg->addrSize - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_ADR_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_ADR_BYTE, 0); + } + + /* Configure dummy */ + if (cfg->dummyClks != 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DMY_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DMY_BYTE, cfg->dummyClks - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DMY_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DMY_BYTE, 0); + } + + /* Configure data */ + if (cfg->nbData != 0) { + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DAT_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_BYTE, cfg->nbData - 1); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_DAT_EN); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_BYTE, 0); + } + + /* Set read write flag */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_0_DAT_RW, cfg->rwFlag); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); + + // switch sf_clk_sahb_sram_sel = 1 + SF_Ctrl_Select_Clock(SF_CTRL_FLASH_CLOCK); + /* Trigger */ + tmpVal = BL_SET_REG_BIT(tmpVal, SF_CTRL_SF_IF_0_TRIG); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0, tmpVal); + + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; + + if (timeOut == 0) { + SF_Ctrl_Select_Clock(SF_CTRL_SAHB_CLOCK); + return; } + } - //switch sf_clk_sahb_sram_sel = 0 - SF_Ctrl_Select_Clock(SF_CTRL_SAHB_CLOCK); + // switch sf_clk_sahb_sram_sel = 0 + SF_Ctrl_Select_Clock(SF_CTRL_SAHB_CLOCK); } #endif /****************************************************************************/ /** - * @brief Config SF controller for flash I/D cache read - * - * @param cfg: Serial flash controller command configuration pointer - * @param cmdValid: command valid or not, for continous read, cache may need no command - * - * @return None - * -*******************************************************************************/ + * @brief Config SF controller for flash I/D cache read + * + * @param cfg: Serial flash controller command configuration pointer + * @param cmdValid: command valid or not, for continous read, cache may need no command + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Flash_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; - - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); - CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); - CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); - CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); +void ATTR_TCM_SECTION SF_Ctrl_Flash_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); + CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); + CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); + CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - if (timeOut == 0) { - return; - } - } - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - - if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { - return; - } - - /* Copy command buffer */ - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_1, cfg->cmdBuf[0]); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_2, cfg->cmdBuf[1]); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_0); - - /* Configure SPI and IO mode*/ - if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_SPI_MODE); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_QPI_MODE); - } - - if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { - if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_NIO_MODE); - } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DO_MODE); - } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QO_MODE); - } - } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DIO_MODE); - } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QIO_MODE); - } - - if (cmdValid) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); - } + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - /* Configure address */ - if (cfg->addrSize != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, cfg->addrSize - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, 0); + if (timeOut == 0) { + return; } - - /* configure dummy */ - if (cfg->dummyClks != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, cfg->dummyClks - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, 0); + } + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + + if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { + return; + } + + /* Copy command buffer */ + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_1, cfg->cmdBuf[0]); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_2, cfg->cmdBuf[1]); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_0); + + /* Configure SPI and IO mode*/ + if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_SPI_MODE); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_QPI_MODE); + } + + if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { + if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_NIO_MODE); + } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DO_MODE); + } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QO_MODE); } - - /* Configure data */ - if (cfg->nbData != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 0); - } - - /* Set read write flag */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_RW, cfg->rwFlag); - - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_0, tmpVal); + } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DIO_MODE); + } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QIO_MODE); + } + + if (cmdValid) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); + } + + /* Configure address */ + if (cfg->addrSize != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, cfg->addrSize - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, 0); + } + + /* configure dummy */ + if (cfg->dummyClks != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, cfg->dummyClks - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, 0); + } + + /* Configure data */ + if (cfg->nbData != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 0); + } + + /* Set read write flag */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_RW, cfg->rwFlag); + + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_0, tmpVal); } #endif /****************************************************************************/ /** - * @brief Config psram controller for psram I/D cache write - * - * @param cfg: Serial flash controller command configuration pointer - * @param cmdValid: command valid or not, cache may need no command - * - * @return None - * -*******************************************************************************/ + * @brief Config psram controller for psram I/D cache write + * + * @param cfg: Serial flash controller command configuration pointer + * @param cmdValid: command valid or not, cache may need no command + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Psram_Write_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; +void ATTR_TCM_SECTION SF_Ctrl_Psram_Write_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); - CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); - CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); - CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); + CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); + CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); + CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - if (timeOut == 0) { - return; - } + if (timeOut == 0) { + return; } - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - - if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { - return; + } + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + + if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { + return; + } + + /* Copy command buffer */ + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_4, cfg->cmdBuf[0]); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_5, cfg->cmdBuf[1]); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_3); + + /* Configure SPI and IO mode*/ + if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_QPI_MODE_EN, SF_CTRL_SPI_MODE); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_QPI_MODE_EN, SF_CTRL_QPI_MODE); + } + + if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { + if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_NIO_MODE); + } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_DO_MODE); + } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_QO_MODE); } - - /* Copy command buffer */ - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_4, cfg->cmdBuf[0]); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_5, cfg->cmdBuf[1]); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_3); - - /* Configure SPI and IO mode*/ - if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_QPI_MODE_EN, SF_CTRL_SPI_MODE); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_QPI_MODE_EN, SF_CTRL_QPI_MODE); - } - - if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { - if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_NIO_MODE); - } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_DO_MODE); - } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_QO_MODE); - } - } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_DIO_MODE); - } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_QIO_MODE); - } - - if (cmdValid) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_BYTE, 0); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_BYTE, 0); - } - - /* Configure address */ - if (cfg->addrSize != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_BYTE, cfg->addrSize - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_BYTE, 0); - } - - /* configure dummy */ - if (cfg->dummyClks != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_BYTE, cfg->dummyClks - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_BYTE, 0); - } - - /* Configure data */ - if (cfg->nbData != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_EN, 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_EN, 0); - } - - /* Set read write flag */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_RW, cfg->rwFlag); - - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_3, tmpVal); + } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_DIO_MODE); + } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_SPI_MODE, SF_CTRL_QIO_MODE); + } + + if (cmdValid) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_BYTE, 0); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_CMD_BYTE, 0); + } + + /* Configure address */ + if (cfg->addrSize != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_BYTE, cfg->addrSize - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_ADR_BYTE, 0); + } + + /* configure dummy */ + if (cfg->dummyClks != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_BYTE, cfg->dummyClks - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DMY_BYTE, 0); + } + + /* Configure data */ + if (cfg->nbData != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_EN, 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_EN, 0); + } + + /* Set read write flag */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_2_DAT_RW, cfg->rwFlag); + + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_3, tmpVal); } #endif /****************************************************************************/ /** - * @brief Config psram controller for psram I/D cache read - * - * @param cfg: Serial flash controller command configuration pointer - * @param cmdValid: command valid or not, for continous read, cache may need no command - * - * @return None - * -*******************************************************************************/ + * @brief Config psram controller for psram I/D cache read + * + * @param cfg: Serial flash controller command configuration pointer + * @param cmdValid: command valid or not, for continous read, cache may need no command + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -void ATTR_TCM_SECTION SF_Ctrl_Psram_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) -{ - uint32_t tmpVal = 0; - uint32_t timeOut = 0; +void ATTR_TCM_SECTION SF_Ctrl_Psram_Read_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg, uint8_t cmdValid) { + uint32_t tmpVal = 0; + uint32_t timeOut = 0; - /* Check the parameters */ - CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); - CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); - CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); - CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); + /* Check the parameters */ + CHECK_PARAM(IS_SF_CTRL_CMD_MODE_TYPE(cfg->cmdMode)); + CHECK_PARAM(IS_SF_CTRL_ADDR_MODE_TYPE(cfg->addrMode)); + CHECK_PARAM(IS_SF_CTRL_DMY_MODE_TYPE(cfg->dummyMode)); + CHECK_PARAM(IS_SF_CTRL_DATA_MODE_TYPE(cfg->dataMode)); - timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; + timeOut = SF_CTRL_BUSY_STATE_TIMEOUT; - while (SET == SF_Ctrl_GetBusyState()) { - timeOut--; + while (SET == SF_Ctrl_GetBusyState()) { + timeOut--; - if (timeOut == 0) { - return; - } + if (timeOut == 0) { + return; } - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); - - if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { - return; + } + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_1); + + if (BL_GET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_FN_SEL) != SF_CTRL_OWNER_IAHB) { + return; + } + + /* Copy command buffer */ + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_10, cfg->cmdBuf[0]); + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_11, cfg->cmdBuf[1]); + + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_9); + + /* Configure SPI and IO mode*/ + if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_SPI_MODE); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_QPI_MODE); + } + + if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { + if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_NIO_MODE); + } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DO_MODE); + } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QO_MODE); } - - /* Copy command buffer */ - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_10, cfg->cmdBuf[0]); - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_11, cfg->cmdBuf[1]); - - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_9); - - /* Configure SPI and IO mode*/ - if (SF_CTRL_CMD_1_LINE == cfg->cmdMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_SPI_MODE); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_QPI_MODE_EN, SF_CTRL_QPI_MODE); - } - - if (SF_CTRL_ADDR_1_LINE == cfg->addrMode) { - if (SF_CTRL_DATA_1_LINE == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_NIO_MODE); - } else if (SF_CTRL_DATA_2_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DO_MODE); - } else if (SF_CTRL_DATA_4_LINES == cfg->dataMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QO_MODE); - } - } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DIO_MODE); - } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QIO_MODE); - } - - if (cmdValid) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); - } - - /* Configure address */ - if (cfg->addrSize != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, cfg->addrSize - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, 0); - } - - /* configure dummy */ - if (cfg->dummyClks != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, cfg->dummyClks - 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, 0); - } - - /* Configure data */ - if (cfg->nbData != 0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 1); - } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 0); - } - - /* Set read write flag */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_RW, cfg->rwFlag); - - BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_9, tmpVal); + } else if (SF_CTRL_ADDR_2_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_DIO_MODE); + } else if (SF_CTRL_ADDR_4_LINES == cfg->addrMode) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_SPI_MODE, SF_CTRL_QIO_MODE); + } + + if (cmdValid) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_CMD_BYTE, 0); + } + + /* Configure address */ + if (cfg->addrSize != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, cfg->addrSize - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_ADR_BYTE, 0); + } + + /* configure dummy */ + if (cfg->dummyClks != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, cfg->dummyClks - 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_EN, 0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DMY_BYTE, 0); + } + + /* Configure data */ + if (cfg->nbData != 0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 1); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_EN, 0); + } + + /* Set read write flag */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SF_CTRL_SF_IF_1_DAT_RW, cfg->rwFlag); + + BL_WR_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_IAHB_9, tmpVal); } #endif /****************************************************************************/ /** - * @brief Get SF Ctrl busy state - * - * @param None - * - * @return SET for SF ctrl busy or RESET for SF ctrl not busy - * -*******************************************************************************/ + * @brief Get SF Ctrl busy state + * + * @param None + * + * @return SET for SF ctrl busy or RESET for SF ctrl not busy + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Sts_Type ATTR_TCM_SECTION SF_Ctrl_GetBusyState(void) -{ - uint32_t tmpVal; +BL_Sts_Type ATTR_TCM_SECTION SF_Ctrl_GetBusyState(void) { + uint32_t tmpVal; - tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0); + tmpVal = BL_RD_REG(SF_CTRL_BASE, SF_CTRL_SF_IF_SAHB_0); - if (BL_IS_REG_BIT_SET(tmpVal, SF_CTRL_SF_IF_BUSY)) { - return SET; - } else { - return RESET; - } + if (BL_IS_REG_BIT_SET(tmpVal, SF_CTRL_SF_IF_BUSY)) { + return SET; + } else { + return RESET; + } } #endif /****************************************************************************/ /** - * @brief SF Controller interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief SF Controller interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void SF_Ctrl_IRQHandler(void) -{ - /* TODO: Not implemented */ -} +void SF_Ctrl_IRQHandler(void) { /* TODO: Not implemented */ } #endif /*@} end of group SF_CTRL_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c index 81ec04b31..3b922ce56 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash.c @@ -39,7 +39,6 @@ #include "bl702_sf_ctrl.h" #include "string.h" - /** @addtogroup BL702_Peripheral_Driver * @{ */ @@ -671,8 +670,8 @@ BL_Err_Type ATTR_TCM_SECTION SFlash_Erase(SPI_Flash_Cfg_Type *flashCfg, uint32_t /* 64K margin address,and length > 64K-sector size, erase one first */ ret = SFlash_Blk64_Erase(flashCfg, startaddr / BFLB_SPIFLASH_BLK64K_SIZE); eraseLen = BFLB_SPIFLASH_BLK64K_SIZE; - } else if (flashCfg->blk32EraseCmd != BFLB_SPIFLASH_CMD_INVALID && (startaddr & (BFLB_SPIFLASH_BLK32K_SIZE - 1)) == 0 - && len > (uint32_t)(BFLB_SPIFLASH_BLK32K_SIZE - flashCfg->sectorSize * 1024)) { + } else if (flashCfg->blk32EraseCmd != BFLB_SPIFLASH_CMD_INVALID && (startaddr & (BFLB_SPIFLASH_BLK32K_SIZE - 1)) == 0 && + len > (uint32_t)(BFLB_SPIFLASH_BLK32K_SIZE - flashCfg->sectorSize * 1024)) { /* 32K margin address,and length > 32K-sector size, erase one first */ ret = SFlash_Blk32_Erase(flashCfg, startaddr / BFLB_SPIFLASH_BLK32K_SIZE); eraseLen = BFLB_SPIFLASH_BLK32K_SIZE; diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c index fba509518..24b2bf584 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_sflash_ext.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_sflash_ext.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2019 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_sflash_ext.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2019 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_sflash_ext.h" #include "bl702_sf_ctrl.h" @@ -87,184 +87,179 @@ */ /****************************************************************************/ /** - * @brief KH25V40 flash write protect set - * - * @param flashCfg: Serial flash parameter configuration pointer - * @param protect: protect area - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief KH25V40 flash write protect set + * + * @param flashCfg: Serial flash parameter configuration pointer + * @param protect: protect area + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_TCM_SECTION SFlash_KH25V40_Write_Protect(SPI_Flash_Cfg_Type *flashCfg, SFlash_Protect_Kh25v40_Type protect) -{ - uint32_t stat = 0, ret; +BL_Err_Type ATTR_TCM_SECTION SFlash_KH25V40_Write_Protect(SPI_Flash_Cfg_Type *flashCfg, SFlash_Protect_Kh25v40_Type protect) { + uint32_t stat = 0, ret; - SFlash_Read_Reg(flashCfg, 0, (uint8_t *)&stat, 1); - if (((stat >> 2) & 0xf) == protect) { - return SUCCESS; - } + SFlash_Read_Reg(flashCfg, 0, (uint8_t *)&stat, 1); + if (((stat >> 2) & 0xf) == protect) { + return SUCCESS; + } - stat |= ((protect << 2) & 0xff); + stat |= ((protect << 2) & 0xff); - ret = SFlash_Write_Enable(flashCfg); - if (SUCCESS != ret) { - return ERROR; - } + ret = SFlash_Write_Enable(flashCfg); + if (SUCCESS != ret) { + return ERROR; + } - SFlash_Write_Reg(flashCfg, 0, (uint8_t *)&stat, 1); - SFlash_Read_Reg(flashCfg, 0, (uint8_t *)&stat, 1); - if (((stat >> 2) & 0xf) == protect) { - return SUCCESS; - } + SFlash_Write_Reg(flashCfg, 0, (uint8_t *)&stat, 1); + SFlash_Read_Reg(flashCfg, 0, (uint8_t *)&stat, 1); + if (((stat >> 2) & 0xf) == protect) { + return SUCCESS; + } - return ERROR; + return ERROR; } /****************************************************************************/ /** - * @brief Read flash register with read command - * - * @param flashCfg: Serial flash parameter configuration pointer - * @param readRegCmd: read command - * @param regValue: register value pointer to store data - * @param regLen: register value length - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Read flash register with read command + * + * @param flashCfg: Serial flash parameter configuration pointer + * @param readRegCmd: read command + * @param regValue: register value pointer to store data + * @param regLen: register value length + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_TCM_SECTION SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t readRegCmd, uint8_t *regValue, uint8_t regLen) -{ - uint8_t *const flashCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - SF_Ctrl_Cmd_Cfg_Type flashCmd; - uint32_t cnt = 0; - - if (((uint32_t)&flashCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&flashCmd, 0, sizeof(flashCmd) / 4); - } else { - BL702_MemSet(&flashCmd, 0, sizeof(flashCmd)); - } +BL_Err_Type ATTR_TCM_SECTION SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t readRegCmd, uint8_t *regValue, uint8_t regLen) { + uint8_t *const flashCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + SF_Ctrl_Cmd_Cfg_Type flashCmd; + uint32_t cnt = 0; + + if (((uint32_t)&flashCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&flashCmd, 0, sizeof(flashCmd) / 4); + } else { + BL702_MemSet(&flashCmd, 0, sizeof(flashCmd)); + } - flashCmd.cmdBuf[0] = readRegCmd << 24; - flashCmd.rwFlag = SF_CTRL_READ; - flashCmd.nbData = regLen; + flashCmd.cmdBuf[0] = readRegCmd << 24; + flashCmd.rwFlag = SF_CTRL_READ; + flashCmd.nbData = regLen; - SF_Ctrl_SendCmd(&flashCmd); + SF_Ctrl_SendCmd(&flashCmd); - while (SET == SF_Ctrl_GetBusyState()) { - BL702_Delay_US(1); - cnt++; + while (SET == SF_Ctrl_GetBusyState()) { + BL702_Delay_US(1); + cnt++; - if (cnt > 1000) { - return ERROR; - } + if (cnt > 1000) { + return ERROR; } + } - BL702_MemCpy(regValue, flashCtrlBuf, regLen); - return SUCCESS; + BL702_MemCpy(regValue, flashCtrlBuf, regLen); + return SUCCESS; } /****************************************************************************/ /** - * @brief Write flash register with write command - * - * @param flashCfg: Serial flash parameter configuration pointer - * @param writeRegCmd: write command - * @param regValue: register value pointer storing data - * @param regLen: register value length - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Write flash register with write command + * + * @param flashCfg: Serial flash parameter configuration pointer + * @param writeRegCmd: write command + * @param regValue: register value pointer storing data + * @param regLen: register value length + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t writeRegCmd, uint8_t *regValue, uint8_t regLen) -{ - uint8_t *const flashCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; - uint32_t cnt = 0; - SF_Ctrl_Cmd_Cfg_Type flashCmd; - - if (((uint32_t)&flashCmd) % 4 == 0) { - BL702_MemSet4((uint32_t *)&flashCmd, 0, sizeof(flashCmd) / 4); - } else { - BL702_MemSet(&flashCmd, 0, sizeof(flashCmd)); - } +BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg, uint8_t writeRegCmd, uint8_t *regValue, uint8_t regLen) { + uint8_t *const flashCtrlBuf = (uint8_t *)SF_CTRL_BUF_BASE; + uint32_t cnt = 0; + SF_Ctrl_Cmd_Cfg_Type flashCmd; - BL702_MemCpy(flashCtrlBuf, regValue, regLen); + if (((uint32_t)&flashCmd) % 4 == 0) { + BL702_MemSet4((uint32_t *)&flashCmd, 0, sizeof(flashCmd) / 4); + } else { + BL702_MemSet(&flashCmd, 0, sizeof(flashCmd)); + } - flashCmd.cmdBuf[0] = writeRegCmd << 24; - flashCmd.rwFlag = SF_CTRL_WRITE; - flashCmd.nbData = regLen; + BL702_MemCpy(flashCtrlBuf, regValue, regLen); - SF_Ctrl_SendCmd(&flashCmd); + flashCmd.cmdBuf[0] = writeRegCmd << 24; + flashCmd.rwFlag = SF_CTRL_WRITE; + flashCmd.nbData = regLen; - /* take 40ms for tw(write status register) as default */ - while (SET == SFlash_Busy(flashCfg)) { - BL702_Delay_US(100); - cnt++; + SF_Ctrl_SendCmd(&flashCmd); - if (cnt > 400) { - return ERROR; - } + /* take 40ms for tw(write status register) as default */ + while (SET == SFlash_Busy(flashCfg)) { + BL702_Delay_US(100); + cnt++; + + if (cnt > 400) { + return ERROR; } + } - return SUCCESS; + return SUCCESS; } -/****************************************************************************//** - * @brief Clear flash status register - * - * @param pFlashCfg: Flash configuration pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type ATTR_TCM_SECTION SFlash_Clear_Status_Register(SPI_Flash_Cfg_Type *pFlashCfg) -{ - uint32_t ret = 0; - uint32_t qeValue = 0; - uint32_t regValue = 0; - uint32_t readValue = 0; - uint8_t readRegValue0 = 0; - uint8_t readRegValue1 = 0; - - if((pFlashCfg->ioMode&0xf)==SF_CTRL_QO_MODE || (pFlashCfg->ioMode&0xf)==SF_CTRL_QIO_MODE){ - qeValue = 1; - } +/****************************************************************************/ /** + * @brief Clear flash status register + * + * @param pFlashCfg: Flash configuration pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type ATTR_TCM_SECTION SFlash_Clear_Status_Register(SPI_Flash_Cfg_Type *pFlashCfg) { + uint32_t ret = 0; + uint32_t qeValue = 0; + uint32_t regValue = 0; + uint32_t readValue = 0; + uint8_t readRegValue0 = 0; + uint8_t readRegValue1 = 0; + + if ((pFlashCfg->ioMode & 0xf) == SF_CTRL_QO_MODE || (pFlashCfg->ioMode & 0xf) == SF_CTRL_QIO_MODE) { + qeValue = 1; + } + + SFlash_Read_Reg(pFlashCfg, 0, (uint8_t *)&readRegValue0, 1); + SFlash_Read_Reg(pFlashCfg, 1, (uint8_t *)&readRegValue1, 1); + readValue = (readRegValue0 | (readRegValue1 << 8)); + if ((readValue & (~((1 << (pFlashCfg->qeIndex * 8 + pFlashCfg->qeBit)) | (1 << (pFlashCfg->busyIndex * 8 + pFlashCfg->busyBit)) | (1 << (pFlashCfg->wrEnableIndex * 8 + pFlashCfg->wrEnableBit))))) == + 0) { + return SUCCESS; + } - SFlash_Read_Reg(pFlashCfg, 0, (uint8_t *)&readRegValue0, 1); - SFlash_Read_Reg(pFlashCfg, 1, (uint8_t *)&readRegValue1, 1); - readValue = (readRegValue0|(readRegValue1<<8)); - if ((readValue & (~((1<<(pFlashCfg->qeIndex*8+pFlashCfg->qeBit)) | - (1<<(pFlashCfg->busyIndex*8+pFlashCfg->busyBit)) | - (1<<(pFlashCfg->wrEnableIndex*8+pFlashCfg->wrEnableBit))))) == 0){ - return SUCCESS; + ret = SFlash_Write_Enable(pFlashCfg); + if (SUCCESS != ret) { + return ERROR; + } + if (pFlashCfg->qeWriteRegLen == 2) { + regValue = (qeValue << (pFlashCfg->qeIndex * 8 + pFlashCfg->qeBit)); + SFlash_Write_Reg(pFlashCfg, 0, (uint8_t *)®Value, 2); + } else { + if (pFlashCfg->qeIndex == 0) { + regValue = (qeValue << pFlashCfg->qeBit); + } else { + regValue = 0; } - + SFlash_Write_Reg(pFlashCfg, 0, (uint8_t *)®Value, 1); ret = SFlash_Write_Enable(pFlashCfg); if (SUCCESS != ret) { - return ERROR; + return ERROR; } - if (pFlashCfg->qeWriteRegLen == 2) { - regValue = (qeValue<<(pFlashCfg->qeIndex*8+pFlashCfg->qeBit)); - SFlash_Write_Reg(pFlashCfg, 0, (uint8_t *)®Value, 2); + if (pFlashCfg->qeIndex == 1) { + regValue = (qeValue << pFlashCfg->qeBit); } else { - if (pFlashCfg->qeIndex == 0) { - regValue = (qeValue<qeBit); - } else { - regValue = 0; - } - SFlash_Write_Reg(pFlashCfg, 0, (uint8_t *)®Value, 1); - ret = SFlash_Write_Enable(pFlashCfg); - if (SUCCESS != ret) { - return ERROR; - } - if (pFlashCfg->qeIndex == 1) { - regValue = (qeValue<qeBit); - } else { - regValue = 0; - } - SFlash_Write_Reg(pFlashCfg, 1, (uint8_t *)®Value, 1); + regValue = 0; } - return SUCCESS; + SFlash_Write_Reg(pFlashCfg, 1, (uint8_t *)®Value, 1); + } + return SUCCESS; } /*@} end of group SFLASH_EXT_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_spi.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_spi.c index f831aaeda..69a6e14ec 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_spi.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_spi.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_spi.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_spi.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_spi.h" #include "bl702_glb.h" @@ -62,10 +62,8 @@ /** @defgroup SPI_Private_Variables * @{ */ -static const uint32_t spiAddr[SPI_ID_MAX] = { SPI_BASE }; -static intCallback_Type *spiIntCbfArra[SPI_ID_MAX][SPI_INT_ALL] = { - { NULL } -}; +static const uint32_t spiAddr[SPI_ID_MAX] = {SPI_BASE}; +static intCallback_Type *spiIntCbfArra[SPI_ID_MAX][SPI_INT_ALL] = {{NULL}}; /*@} end of group SPI_Private_Variables */ @@ -89,70 +87,69 @@ static void SPI_IntHandler(SPI_ID_Type spiNo); */ /****************************************************************************/ /** - * @brief SPI interrupt common handler function - * - * @param spiNo: SPI ID type - * - * @return None - * -*******************************************************************************/ + * @brief SPI interrupt common handler function + * + * @param spiNo: SPI ID type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -static void SPI_IntHandler(SPI_ID_Type spiNo) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; +static void SPI_IntHandler(SPI_ID_Type spiNo) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); + tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); - /* Transfer end interrupt,shared by both master and slave mode */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_END_MASK)) { - BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_END_CLR)); + /* Transfer end interrupt,shared by both master and slave mode */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_END_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_END_MASK)) { + BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_END_CLR)); - if (spiIntCbfArra[spiNo][SPI_INT_END] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_END](); - } + if (spiIntCbfArra[spiNo][SPI_INT_END] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_END](); } + } - /* TX fifo ready interrupt(fifo count > fifo threshold) */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_TXF_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_TXF_MASK)) { - if (spiIntCbfArra[spiNo][SPI_INT_TX_FIFO_REQ] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_TX_FIFO_REQ](); - } + /* TX fifo ready interrupt(fifo count > fifo threshold) */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_TXF_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_TXF_MASK)) { + if (spiIntCbfArra[spiNo][SPI_INT_TX_FIFO_REQ] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_TX_FIFO_REQ](); } + } - /* RX fifo ready interrupt(fifo count > fifo threshold) */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_RXF_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_RXF_MASK)) { - if (spiIntCbfArra[spiNo][SPI_INT_RX_FIFO_REQ] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_RX_FIFO_REQ](); - } + /* RX fifo ready interrupt(fifo count > fifo threshold) */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_RXF_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_RXF_MASK)) { + if (spiIntCbfArra[spiNo][SPI_INT_RX_FIFO_REQ] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_RX_FIFO_REQ](); } + } - /* Slave mode transfer time-out interrupt,triggered when bus is idle for the given value */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_STO_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_STO_MASK)) { - BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_STO_CLR)); + /* Slave mode transfer time-out interrupt,triggered when bus is idle for the given value */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_STO_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_STO_MASK)) { + BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_STO_CLR)); - if (spiIntCbfArra[spiNo][SPI_INT_SLAVE_TIMEOUT] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_SLAVE_TIMEOUT](); - } + if (spiIntCbfArra[spiNo][SPI_INT_SLAVE_TIMEOUT] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_SLAVE_TIMEOUT](); } + } - /* Slave mode tx underrun error interrupt,trigged when tx is not ready during transfer */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_TXU_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_TXU_MASK)) { - BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_TXU_CLR)); + /* Slave mode tx underrun error interrupt,trigged when tx is not ready during transfer */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_TXU_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_TXU_MASK)) { + BL_WR_REG(SPIx, SPI_INT_STS, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_TXU_CLR)); - if (spiIntCbfArra[spiNo][SPI_INT_SLAVE_UNDERRUN] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_SLAVE_UNDERRUN](); - } + if (spiIntCbfArra[spiNo][SPI_INT_SLAVE_UNDERRUN] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_SLAVE_UNDERRUN](); } + } - /* TX/RX fifo overflow/underflow interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, SPI_FER_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_FER_MASK)) { - if (spiIntCbfArra[spiNo][SPI_INT_FIFO_ERROR] != NULL) { - spiIntCbfArra[spiNo][SPI_INT_FIFO_ERROR](); - } + /* TX/RX fifo overflow/underflow interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, SPI_FER_INT) && !BL_IS_REG_BIT_SET(tmpVal, SPI_CR_SPI_FER_MASK)) { + if (spiIntCbfArra[spiNo][SPI_INT_FIFO_ERROR] != NULL) { + spiIntCbfArra[spiNo][SPI_INT_FIFO_ERROR](); } + } } #endif @@ -163,1645 +160,1607 @@ static void SPI_IntHandler(SPI_ID_Type spiNo) */ /****************************************************************************/ /** - * @brief SPI initialization function - * - * @param spiNo: SPI ID type - * @param spiCfg: SPI configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Init(SPI_ID_Type spiNo, SPI_CFG_Type *spiCfg) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(spiCfg->mod)); - CHECK_PARAM(IS_SPI_BYTE_INVERSE_TYPE(spiCfg->byteSequence)); - CHECK_PARAM(IS_SPI_BIT_INVERSE_TYPE(spiCfg->bitSequence)); - CHECK_PARAM(IS_SPI_CLK_PHASE_INVERSE_TYPE(spiCfg->clkPhaseInv)); - CHECK_PARAM(IS_SPI_CLK_POLARITY_TYPE(spiCfg->clkPolarity)); - - /* Disable clock gate */ - GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_SPI); - - /* spi config */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_DEG_EN, spiCfg->deglitchEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_M_CONT_EN, spiCfg->continuousEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_BYTE_INV, spiCfg->byteSequence); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_BIT_INV, spiCfg->bitSequence); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_SCLK_PH, (spiCfg->clkPhaseInv + 1) & 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_SCLK_POL, spiCfg->clkPolarity); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, spiCfg->frameSize); - BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); + * @brief SPI initialization function + * + * @param spiNo: SPI ID type + * @param spiCfg: SPI configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Init(SPI_ID_Type spiNo, SPI_CFG_Type *spiCfg) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(spiCfg->mod)); + CHECK_PARAM(IS_SPI_BYTE_INVERSE_TYPE(spiCfg->byteSequence)); + CHECK_PARAM(IS_SPI_BIT_INVERSE_TYPE(spiCfg->bitSequence)); + CHECK_PARAM(IS_SPI_CLK_PHASE_INVERSE_TYPE(spiCfg->clkPhaseInv)); + CHECK_PARAM(IS_SPI_CLK_POLARITY_TYPE(spiCfg->clkPolarity)); + + /* Disable clock gate */ + GLB_AHB_Slave1_Clock_Gate(DISABLE, BL_AHB_SLAVE1_SPI); + + /* spi config */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_DEG_EN, spiCfg->deglitchEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_M_CONT_EN, spiCfg->continuousEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_BYTE_INV, spiCfg->byteSequence); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_BIT_INV, spiCfg->bitSequence); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_SCLK_PH, (spiCfg->clkPhaseInv + 1) & 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_SCLK_POL, spiCfg->clkPolarity); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, spiCfg->frameSize); + BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(SPI_IRQn, SPI_IRQHandler); + Interrupt_Handler_Register(SPI_IRQn, SPI_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI set default value of all registers function - * - * @param spiNo: SPI ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_DeInit(SPI_ID_Type spiNo) -{ - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - if (SPI_ID_0 == spiNo) { - GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_SPI); - } - - return SUCCESS; + * @brief SPI set default value of all registers function + * + * @param spiNo: SPI ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_DeInit(SPI_ID_Type spiNo) { + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + if (SPI_ID_0 == spiNo) { + GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_SPI); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief Length of data phase1/0,start/stop condition and interval between frame initialization - * function - * - * @param spiNo: SPI ID type - * @param clockCfg: Clock configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_ClockConfig(SPI_ID_Type spiNo, SPI_ClockCfg_Type *clockCfg) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Configure length of data phase1/0 and start/stop condition */ - tmpVal = BL_RD_REG(SPIx, SPI_PRD_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_S, clockCfg->startLen - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_P, clockCfg->stopLen - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_0, clockCfg->dataPhase0Len - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_1, clockCfg->dataPhase1Len - 1); - BL_WR_REG(SPIx, SPI_PRD_0, tmpVal); - - /* Configure length of interval between frame */ - tmpVal = BL_RD_REG(SPIx, SPI_PRD_1); - BL_WR_REG(SPIx, SPI_PRD_1, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_I, clockCfg->intervalLen - 1)); - - return SUCCESS; + * @brief Length of data phase1/0,start/stop condition and interval between frame initialization + * function + * + * @param spiNo: SPI ID type + * @param clockCfg: Clock configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_ClockConfig(SPI_ID_Type spiNo, SPI_ClockCfg_Type *clockCfg) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Configure length of data phase1/0 and start/stop condition */ + tmpVal = BL_RD_REG(SPIx, SPI_PRD_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_S, clockCfg->startLen - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_P, clockCfg->stopLen - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_0, clockCfg->dataPhase0Len - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_1, clockCfg->dataPhase1Len - 1); + BL_WR_REG(SPIx, SPI_PRD_0, tmpVal); + + /* Configure length of interval between frame */ + tmpVal = BL_RD_REG(SPIx, SPI_PRD_1); + BL_WR_REG(SPIx, SPI_PRD_1, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_I, clockCfg->intervalLen - 1)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI configure fifo function - * - * @param spiNo: SPI ID type - * @param fifoCfg: FIFO configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_FifoConfig(SPI_ID_Type spiNo, SPI_FifoCfg_Type *fifoCfg) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Set fifo threshold value */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_TX_FIFO_TH, fifoCfg->txFifoThreshold); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_RX_FIFO_TH, fifoCfg->rxFifoThreshold); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_1, tmpVal); - - /* Enable or disable dma function */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_DMA_TX_EN, fifoCfg->txFifoDmaEnable); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_DMA_RX_EN, fifoCfg->rxFifoDmaEnable); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - return SUCCESS; + * @brief SPI configure fifo function + * + * @param spiNo: SPI ID type + * @param fifoCfg: FIFO configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_FifoConfig(SPI_ID_Type spiNo, SPI_FifoCfg_Type *fifoCfg) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Set fifo threshold value */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_TX_FIFO_TH, fifoCfg->txFifoThreshold); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_RX_FIFO_TH, fifoCfg->rxFifoThreshold); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_1, tmpVal); + + /* Enable or disable dma function */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_DMA_TX_EN, fifoCfg->txFifoDmaEnable); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_DMA_RX_EN, fifoCfg->rxFifoDmaEnable); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Set SPI SCK Clcok - * - * @param spiNo: SPI ID type - * @param clk: Clk - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SetClock(SPI_ID_Type spiNo, uint32_t clk) -{ - uint32_t glb_div = 1, spi_div = 1; - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - if(clk > 36000000) { - clk = 36000000; - glb_div = 1; - spi_div = 1; - } else if(clk > 140625) { - glb_div = 1; - spi_div = 36000000 / clk; - } else if(clk > 70312) { - glb_div = 2; - spi_div = 18000000 / clk; - } else if(clk > 35156) { - glb_div = 4; - spi_div = 9000000 / clk; - } else if(clk > 4394) { - glb_div = 32; - spi_div = 1125000 / clk; - } else { - glb_div = 32; - spi_div = 256; - } - - /* Configure length of data phase1/0 and start/stop condition */ - tmpVal = BL_RD_REG(SPIx, SPI_PRD_0); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_S, spi_div - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_P, spi_div - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_0, spi_div - 1); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_1, spi_div - 1); - BL_WR_REG(SPIx, SPI_PRD_0, tmpVal); - - tmpVal = BL_RD_REG(SPIx, SPI_PRD_1); - BL_WR_REG(SPIx, SPI_PRD_1, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_I, spi_div - 1)); - - GLB_Set_SPI_CLK(ENABLE, glb_div - 1); - - return SUCCESS; + * @brief Set SPI SCK Clcok + * + * @param spiNo: SPI ID type + * @param clk: Clk + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SetClock(SPI_ID_Type spiNo, uint32_t clk) { + uint32_t glb_div = 1, spi_div = 1; + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + if (clk > 36000000) { + clk = 36000000; + glb_div = 1; + spi_div = 1; + } else if (clk > 140625) { + glb_div = 1; + spi_div = 36000000 / clk; + } else if (clk > 70312) { + glb_div = 2; + spi_div = 18000000 / clk; + } else if (clk > 35156) { + glb_div = 4; + spi_div = 9000000 / clk; + } else if (clk > 4394) { + glb_div = 32; + spi_div = 1125000 / clk; + } else { + glb_div = 32; + spi_div = 256; + } + + /* Configure length of data phase1/0 and start/stop condition */ + tmpVal = BL_RD_REG(SPIx, SPI_PRD_0); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_S, spi_div - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_P, spi_div - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_0, spi_div - 1); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_D_PH_1, spi_div - 1); + BL_WR_REG(SPIx, SPI_PRD_0, tmpVal); + + tmpVal = BL_RD_REG(SPIx, SPI_PRD_1); + BL_WR_REG(SPIx, SPI_PRD_1, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_PRD_I, spi_div - 1)); + + GLB_Set_SPI_CLK(ENABLE, glb_div - 1); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Enable spi transfer - * - * @param spiNo: SPI ID type - * @param modeType: Master or slave mode select - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Enable(SPI_ID_Type spiNo, SPI_WORK_MODE_Type modeType) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(modeType)); - - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - - if (modeType != SPI_WORK_MODE_SLAVE) { - /* master mode */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); - } else { - /* slave mode */ - tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); - } + * @brief Enable spi transfer + * + * @param spiNo: SPI ID type + * @param modeType: Master or slave mode select + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Enable(SPI_ID_Type spiNo, SPI_WORK_MODE_Type modeType) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(modeType)); + + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + + if (modeType != SPI_WORK_MODE_SLAVE) { + /* master mode */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); + } else { + /* slave mode */ + tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); + } - BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); + BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable spi transfer - * - * @param spiNo: SPI ID type - * @param modeType: Master or slave mode select - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Disable(SPI_ID_Type spiNo, SPI_WORK_MODE_Type modeType) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(modeType)); - - /* close master and slave */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); - tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); - BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); - - return SUCCESS; + * @brief Disable spi transfer + * + * @param spiNo: SPI ID type + * @param modeType: Master or slave mode select + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Disable(SPI_ID_Type spiNo, SPI_WORK_MODE_Type modeType) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_WORK_MODE_TYPE(modeType)); + + /* close master and slave */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_M_EN); + tmpVal = BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_S_EN); + BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Set time-out value to trigger interrupt when spi bus is idle for the given value - * - * @param spiNo: SPI ID type - * @param value: Time value - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SetTimeOutValue(SPI_ID_Type spiNo, uint16_t value) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Set time-out value */ - tmpVal = BL_RD_REG(SPIx, SPI_STO_VALUE); - BL_WR_REG(SPIx, SPI_STO_VALUE, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_STO_VALUE, value - 1)); - - return SUCCESS; + * @brief Set time-out value to trigger interrupt when spi bus is idle for the given value + * + * @param spiNo: SPI ID type + * @param value: Time value + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SetTimeOutValue(SPI_ID_Type spiNo, uint16_t value) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Set time-out value */ + tmpVal = BL_RD_REG(SPIx, SPI_STO_VALUE); + BL_WR_REG(SPIx, SPI_STO_VALUE, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_STO_VALUE, value - 1)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Set de-glitch function cycle count value - * - * @param spiNo: SPI ID type - * @param cnt: De-glitch function cycle count - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SetDeglitchCount(SPI_ID_Type spiNo, uint8_t cnt) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Set count value */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_DEG_CNT, cnt); - BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); - - return SUCCESS; + * @brief Set de-glitch function cycle count value + * + * @param spiNo: SPI ID type + * @param cnt: De-glitch function cycle count + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SetDeglitchCount(SPI_ID_Type spiNo, uint8_t cnt) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Set count value */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_DEG_CNT, cnt); + BL_WR_REG(SPIx, SPI_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Enable rx data ignore function and set start/stop point - * - * @param spiNo: SPI ID type - * @param startPoint: Start point - * @param stopPoint: Stop point - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_RxIgnoreEnable(SPI_ID_Type spiNo, uint8_t startPoint, uint8_t stopPoint) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Enable rx ignore function */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Set start and stop point */ - tmpVal = startPoint << SPI_CR_SPI_RXD_IGNR_S_POS | stopPoint; - BL_WR_REG(SPIx, SPI_RXD_IGNR, tmpVal); - - return SUCCESS; + * @brief Enable rx data ignore function and set start/stop point + * + * @param spiNo: SPI ID type + * @param startPoint: Start point + * @param stopPoint: Stop point + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_RxIgnoreEnable(SPI_ID_Type spiNo, uint8_t startPoint, uint8_t stopPoint) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Enable rx ignore function */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Set start and stop point */ + tmpVal = startPoint << SPI_CR_SPI_RXD_IGNR_S_POS | stopPoint; + BL_WR_REG(SPIx, SPI_RXD_IGNR, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable rx data ignore function - * - * @param spiNo: SPI ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_RxIgnoreDisable(SPI_ID_Type spiNo) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Disable rx ignore function */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - return SUCCESS; + * @brief Disable rx data ignore function + * + * @param spiNo: SPI ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_RxIgnoreDisable(SPI_ID_Type spiNo) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Disable rx ignore function */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Clear tx fifo and tx fifo overflow/underflow status - * - * @param spiNo: SPI ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_ClrTxFifo(SPI_ID_Type spiNo) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Clear tx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR)); - - return SUCCESS; + * @brief Clear tx fifo and tx fifo overflow/underflow status + * + * @param spiNo: SPI ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_ClrTxFifo(SPI_ID_Type spiNo) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Clear tx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Clear rx fifo and rx fifo overflow/underflow status - * - * @param spiNo: SPI ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_ClrRxFifo(SPI_ID_Type spiNo) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Clear rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR)); - - return SUCCESS; + * @brief Clear rx fifo and rx fifo overflow/underflow status + * + * @param spiNo: SPI ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_ClrRxFifo(SPI_ID_Type spiNo) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Clear rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief Clear spi interrupt status - * - * @param spiNo: SPI ID type - * @param intType: SPI interrupt type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_ClrIntStatus(SPI_ID_Type spiNo, SPI_INT_Type intType) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Clear certain or all interrupt */ - tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); - - if (SPI_INT_ALL == intType) { - tmpVal |= 0x1f << SPI_CR_SPI_END_CLR_POS; - } else { - tmpVal |= 1 << (intType + SPI_CR_SPI_END_CLR_POS); - } - - BL_WR_REG(SPIx, SPI_INT_STS, tmpVal); - - return SUCCESS; + * @brief Clear spi interrupt status + * + * @param spiNo: SPI ID type + * @param intType: SPI interrupt type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_ClrIntStatus(SPI_ID_Type spiNo, SPI_INT_Type intType) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Clear certain or all interrupt */ + tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); + + if (SPI_INT_ALL == intType) { + tmpVal |= 0x1f << SPI_CR_SPI_END_CLR_POS; + } else { + tmpVal |= 1 << (intType + SPI_CR_SPI_END_CLR_POS); + } + + BL_WR_REG(SPIx, SPI_INT_STS, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI mask or unmask certain or all interrupt - * - * @param spiNo: SPI ID type - * @param intType: SPI interrupt type - * @param intMask: SPI interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_IntMask(SPI_ID_Type spiNo, SPI_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); - - /* Mask or unmask certain or all interrupt */ - if (SPI_INT_ALL == intType) { - if (MASK == intMask) { - tmpVal |= 0x3f << SPI_CR_SPI_END_MASK_POS; - } else { - tmpVal &= ~(0x3f << SPI_CR_SPI_END_MASK_POS); - } + * @brief SPI mask or unmask certain or all interrupt + * + * @param spiNo: SPI ID type + * @param intType: SPI interrupt type + * @param intMask: SPI interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_IntMask(SPI_ID_Type spiNo, SPI_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); + + /* Mask or unmask certain or all interrupt */ + if (SPI_INT_ALL == intType) { + if (MASK == intMask) { + tmpVal |= 0x3f << SPI_CR_SPI_END_MASK_POS; } else { - if (MASK == intMask) { - tmpVal |= 1 << (intType + SPI_CR_SPI_END_MASK_POS); - } else { - tmpVal &= ~(1 << (intType + SPI_CR_SPI_END_MASK_POS)); - } + tmpVal &= ~(0x3f << SPI_CR_SPI_END_MASK_POS); + } + } else { + if (MASK == intMask) { + tmpVal |= 1 << (intType + SPI_CR_SPI_END_MASK_POS); + } else { + tmpVal &= ~(1 << (intType + SPI_CR_SPI_END_MASK_POS)); } + } - /* Write back */ - BL_WR_REG(SPIx, SPI_INT_STS, tmpVal); + /* Write back */ + BL_WR_REG(SPIx, SPI_INT_STS, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Install spi interrupt callback function - * - * @param spiNo: SPI ID type - * @param intType: SPI interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Int_Callback_Install(SPI_ID_Type spiNo, SPI_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_INT_TYPE(intType)); - - spiIntCbfArra[spiNo][intType] = cbFun; - - return SUCCESS; + * @brief Install spi interrupt callback function + * + * @param spiNo: SPI ID type + * @param intType: SPI interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Int_Callback_Install(SPI_ID_Type spiNo, SPI_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_INT_TYPE(intType)); + + spiIntCbfArra[spiNo][intType] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI write data to tx fifo - * - * @param spiNo: SPI ID type - * @param data: Data to write - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SendData(SPI_ID_Type spiNo, uint32_t data) -{ - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Write tx fifo */ - BL_WR_REG(SPIx, SPI_FIFO_WDATA, data); - - return SUCCESS; + * @brief SPI write data to tx fifo + * + * @param spiNo: SPI ID type + * @param data: Data to write + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SendData(SPI_ID_Type spiNo, uint32_t data) { + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Write tx fifo */ + BL_WR_REG(SPIx, SPI_FIFO_WDATA, data); + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send 8-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Send_8bits(SPI_ID_Type spiNo, uint8_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t rData; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send 8-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Send_8bits(SPI_ID_Type spiNo, uint8_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t rData; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send 16-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Send_16bits(SPI_ID_Type spiNo, uint16_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t rData; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send 16-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Send_16bits(SPI_ID_Type spiNo, uint16_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t rData; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)buff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send 24-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Send_24bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t rData; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send 24-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Send_24bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t rData; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send 32-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Send_32bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t rData; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send 32-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Send_32bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t rData; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_TX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, buff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + rData |= BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI receive 8-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Recv_8bits(SPI_ID_Type spiNo, uint8_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t rxLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo with 0 */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (rxLen = 0; rxLen < tmpVal; rxLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); - } - - /* Wait receive data and send the rest of the data 0 */ - for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI receive 8-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Recv_8bits(SPI_ID_Type spiNo, uint8_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t rxLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo with 0 */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (rxLen = 0; rxLen < tmpVal; rxLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } + + /* Wait receive data and send the rest of the data 0 */ + for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - buff[rxLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } } - /* Wait receive the rest of the data */ - for (; rxLen < length; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + buff[rxLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (; rxLen < length; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - buff[rxLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + buff[rxLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI receive 16-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Recv_16bits(SPI_ID_Type spiNo, uint16_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t rxLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo with 0 */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (rxLen = 0; rxLen < tmpVal; rxLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); - } - - /* Wait receive data and send the rest of the data 0 */ - for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI receive 16-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Recv_16bits(SPI_ID_Type spiNo, uint16_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t rxLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo with 0 */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (rxLen = 0; rxLen < tmpVal; rxLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } + + /* Wait receive data and send the rest of the data 0 */ + for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - buff[rxLen++] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } } - /* Wait receive the rest of the data */ - for (; rxLen < length; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + buff[rxLen++] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (; rxLen < length; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - buff[rxLen++] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + buff[rxLen++] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI receive 24-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Recv_24bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t rxLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo with 0 */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (rxLen = 0; rxLen < tmpVal; rxLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); - } - - /* Wait receive data and send the rest of the data 0 */ - for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI receive 24-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Recv_24bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t rxLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo with 0 */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (rxLen = 0; rxLen < tmpVal; rxLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } + + /* Wait receive data and send the rest of the data 0 */ + for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } } - /* Wait receive the rest of the data */ - for (; rxLen < length; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (; rxLen < length; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI receive 32-bit datas - * - * @param spiNo: SPI ID type - * @param buff: Buffer of datas - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_Recv_32bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t rxLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo with 0 */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (rxLen = 0; rxLen < tmpVal; rxLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); - } - - /* Wait receive data and send the rest of the data 0 */ - for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI receive 32-bit datas + * + * @param spiNo: SPI ID type + * @param buff: Buffer of datas + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_Recv_32bits(SPI_ID_Type spiNo, uint32_t *buff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t rxLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo with 0 */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (rxLen = 0; rxLen < tmpVal; rxLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } + + /* Wait receive data and send the rest of the data 0 */ + for (rxLen = 0; rxLen < length - tmpVal; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } } - /* Wait receive the rest of the data */ - for (; rxLen < length; rxLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, 0); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (; rxLen < length; rxLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + buff[rxLen++] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send and receive 8-bit datas at the same time - * - * @param spiNo: SPI ID type - * @param sendBuff: Buffer of datas to send - * @param recvBuff: Buffer of datas received - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SendRecv_8bits(SPI_ID_Type spiNo, uint8_t *sendBuff, uint8_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send and receive 8-bit datas at the same time + * + * @param spiNo: SPI ID type + * @param sendBuff: Buffer of datas to send + * @param recvBuff: Buffer of datas received + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SendRecv_8bits(SPI_ID_Type spiNo, uint8_t *sendBuff, uint8_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 0)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - recvBuff[txLen - tmpVal] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + recvBuff[txLen - tmpVal] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - recvBuff[length - tmpVal + txLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + recvBuff[length - tmpVal + txLen] = (uint8_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xff); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send and receive 16-bit datas at the same time - * - * @param spiNo: SPI ID type - * @param sendBuff: Buffer of datas to send - * @param recvBuff: Buffer of datas received - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SendRecv_16bits(SPI_ID_Type spiNo, uint16_t *sendBuff, uint16_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send and receive 16-bit datas at the same time + * + * @param spiNo: SPI ID type + * @param sendBuff: Buffer of datas to send + * @param recvBuff: Buffer of datas received + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SendRecv_16bits(SPI_ID_Type spiNo, uint16_t *sendBuff, uint16_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 1)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - recvBuff[txLen - tmpVal] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + recvBuff[txLen - tmpVal] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, (uint32_t)sendBuff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - recvBuff[length - tmpVal + txLen] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + recvBuff[length - tmpVal + txLen] = (uint16_t)(BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffff); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send and receive 24-bit datas at the same time - * - * @param spiNo: SPI ID type - * @param sendBuff: Buffer of datas to send - * @param recvBuff: Buffer of datas received - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SendRecv_24bits(SPI_ID_Type spiNo, uint32_t *sendBuff, uint32_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send and receive 24-bit datas at the same time + * + * @param spiNo: SPI ID type + * @param sendBuff: Buffer of datas to send + * @param recvBuff: Buffer of datas received + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SendRecv_24bits(SPI_ID_Type spiNo, uint32_t *sendBuff, uint32_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 2)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - recvBuff[txLen - tmpVal] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; - BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + recvBuff[txLen - tmpVal] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - recvBuff[length - tmpVal + txLen] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + recvBuff[length - tmpVal + txLen] = BL_RD_REG(SPIx, SPI_FIFO_RDATA) & 0xffffff; + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI send and receive 32-bit datas at the same time - * - * @param spiNo: SPI ID type - * @param sendBuff: Buffer of datas to send - * @param recvBuff: Buffer of datas received - * @param length: Length of buffer - * @param timeoutType: Enable or disable timeout judgment - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type SPI_SendRecv_32bits(SPI_ID_Type spiNo, uint32_t *sendBuff, uint32_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) -{ - uint32_t tmpVal; - uint32_t txLen = 0; - uint32_t SPIx = spiAddr[spiNo]; - uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); - - /* Set valid width for each fifo entry */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); - - /* Disable rx ignore */ - tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); - BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); - - /* Clear tx and rx fifo */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); - tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); - BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); - - /* Fill tx fifo */ - tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; - - for (txLen = 0; txLen < tmpVal; txLen++) { - BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); - } - - /* Wait receive data and send the rest of the data */ - for (; txLen < length; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; - - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } + * @brief SPI send and receive 32-bit datas at the same time + * + * @param spiNo: SPI ID type + * @param sendBuff: Buffer of datas to send + * @param recvBuff: Buffer of datas received + * @param length: Length of buffer + * @param timeoutType: Enable or disable timeout judgment + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type SPI_SendRecv_32bits(SPI_ID_Type spiNo, uint32_t *sendBuff, uint32_t *recvBuff, uint32_t length, SPI_Timeout_Type timeoutType) { + uint32_t tmpVal; + uint32_t txLen = 0; + uint32_t SPIx = spiAddr[spiNo]; + uint32_t timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_TIMEOUT_TYPE(timeoutType)); + + /* Set valid width for each fifo entry */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, SPI_CR_SPI_FRAME_SIZE, 3)); + + /* Disable rx ignore */ + tmpVal = BL_RD_REG(SPIx, SPI_CONFIG); + BL_WR_REG(SPIx, SPI_CONFIG, BL_CLR_REG_BIT(tmpVal, SPI_CR_SPI_RXD_IGNR_EN)); + + /* Clear tx and rx fifo */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_TX_FIFO_CLR); + tmpVal = BL_SET_REG_BIT(tmpVal, SPI_RX_FIFO_CLR); + BL_WR_REG(SPIx, SPI_FIFO_CONFIG_0, tmpVal); + + /* Fill tx fifo */ + tmpVal = length <= (SPI_TX_FIFO_SIZE) ? length : SPI_TX_FIFO_SIZE; + + for (txLen = 0; txLen < tmpVal; txLen++) { + BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } + + /* Wait receive data and send the rest of the data */ + for (; txLen < length; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; + + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; } - - recvBuff[txLen - tmpVal] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); - BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } } - /* Wait receive the rest of the data */ - for (txLen = 0; txLen < tmpVal; txLen++) { - timeoutCnt = SPI_RX_TIMEOUT_COUNT; + recvBuff[txLen - tmpVal] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + BL_WR_REG(SPIx, SPI_FIFO_WDATA, sendBuff[txLen]); + } - while (SPI_GetRxFifoCount(spiNo) == 0) { - if (timeoutType) { - timeoutCnt--; + /* Wait receive the rest of the data */ + for (txLen = 0; txLen < tmpVal; txLen++) { + timeoutCnt = SPI_RX_TIMEOUT_COUNT; - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + while (SPI_GetRxFifoCount(spiNo) == 0) { + if (timeoutType) { + timeoutCnt--; - recvBuff[length - tmpVal + txLen] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + if (timeoutCnt == 0) { + return TIMEOUT; + } + } } - return SUCCESS; + recvBuff[length - tmpVal + txLen] = BL_RD_REG(SPIx, SPI_FIFO_RDATA); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief SPI read data from rx fifo - * - * @param spiNo: SPI ID type - * - * @return Data readed - * -*******************************************************************************/ -uint32_t SPI_ReceiveData(SPI_ID_Type spiNo) -{ - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - return BL_RD_REG(SPIx, SPI_FIFO_RDATA); + * @brief SPI read data from rx fifo + * + * @param spiNo: SPI ID type + * + * @return Data readed + * + *******************************************************************************/ +uint32_t SPI_ReceiveData(SPI_ID_Type spiNo) { + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + return BL_RD_REG(SPIx, SPI_FIFO_RDATA); } /****************************************************************************/ /** - * @brief Get tx fifo available count value function - * - * @param spiNo: SPI ID type - * - * @return Count value - * -*******************************************************************************/ -uint8_t SPI_GetTxFifoCount(SPI_ID_Type spiNo) -{ - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Get count value */ - return BL_GET_REG_BITS_VAL(BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1), SPI_TX_FIFO_CNT); + * @brief Get tx fifo available count value function + * + * @param spiNo: SPI ID type + * + * @return Count value + * + *******************************************************************************/ +uint8_t SPI_GetTxFifoCount(SPI_ID_Type spiNo) { + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Get count value */ + return BL_GET_REG_BITS_VAL(BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1), SPI_TX_FIFO_CNT); } /****************************************************************************/ /** - * @brief Get rx fifo available count value function - * - * @param spiNo: SPI ID type - * - * @return Count value - * -*******************************************************************************/ -uint8_t SPI_GetRxFifoCount(SPI_ID_Type spiNo) -{ - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Get count value */ - return BL_GET_REG_BITS_VAL(BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1), SPI_RX_FIFO_CNT); + * @brief Get rx fifo available count value function + * + * @param spiNo: SPI ID type + * + * @return Count value + * + *******************************************************************************/ +uint8_t SPI_GetRxFifoCount(SPI_ID_Type spiNo) { + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Get count value */ + return BL_GET_REG_BITS_VAL(BL_RD_REG(SPIx, SPI_FIFO_CONFIG_1), SPI_RX_FIFO_CNT); } /****************************************************************************/ /** - * @brief Get spi interrupt status - * - * @param spiNo: SPI ID type - * @param intType: SPI interrupt type - * - * @return Status of interrupt - * -*******************************************************************************/ -BL_Sts_Type SPI_GetIntStatus(SPI_ID_Type spiNo, SPI_INT_Type intType) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_INT_TYPE(intType)); - - /* Get certain or all interrupt status */ - tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); - - if (SPI_INT_ALL == intType) { - if ((tmpVal & 0x3f) != 0) { - return SET; - } else { - return RESET; - } + * @brief Get spi interrupt status + * + * @param spiNo: SPI ID type + * @param intType: SPI interrupt type + * + * @return Status of interrupt + * + *******************************************************************************/ +BL_Sts_Type SPI_GetIntStatus(SPI_ID_Type spiNo, SPI_INT_Type intType) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_INT_TYPE(intType)); + + /* Get certain or all interrupt status */ + tmpVal = BL_RD_REG(SPIx, SPI_INT_STS); + + if (SPI_INT_ALL == intType) { + if ((tmpVal & 0x3f) != 0) { + return SET; } else { - if ((tmpVal & (1U << intType)) != 0) { - return SET; - } else { - return RESET; - } + return RESET; } -} - -/****************************************************************************/ /** - * @brief Get indicator of spi bus busy - * - * @param spiNo: SPI ID type - * - * @return Status of spi bus - * -*******************************************************************************/ -BL_Sts_Type SPI_GetBusyStatus(SPI_ID_Type spiNo) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - - /* Get bus busy status */ - tmpVal = BL_RD_REG(SPIx, SPI_BUS_BUSY); - - if (BL_IS_REG_BIT_SET(tmpVal, SPI_STS_SPI_BUS_BUSY)) { - return SET; + } else { + if ((tmpVal & (1U << intType)) != 0) { + return SET; } else { - return RESET; + return RESET; } + } } /****************************************************************************/ /** - * @brief Get tx/rx fifo overflow or underflow status - * - * @param spiNo: SPI ID type - * @param fifoSts: Select tx/rx overflow or underflow - * - * @return Status of tx/rx fifo - * -*******************************************************************************/ -BL_Sts_Type SPI_GetFifoStatus(SPI_ID_Type spiNo, SPI_FifoStatus_Type fifoSts) -{ - uint32_t tmpVal; - uint32_t SPIx = spiAddr[spiNo]; - - /* Check the parameters */ - CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); - CHECK_PARAM(IS_SPI_FIFOSTATUS_TYPE(fifoSts)); - - /* Get tx/rx fifo overflow or underflow status */ - tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + * @brief Get indicator of spi bus busy + * + * @param spiNo: SPI ID type + * + * @return Status of spi bus + * + *******************************************************************************/ +BL_Sts_Type SPI_GetBusyStatus(SPI_ID_Type spiNo) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + + /* Get bus busy status */ + tmpVal = BL_RD_REG(SPIx, SPI_BUS_BUSY); + + if (BL_IS_REG_BIT_SET(tmpVal, SPI_STS_SPI_BUS_BUSY)) { + return SET; + } else { + return RESET; + } +} - if ((tmpVal & (1U << (fifoSts + SPI_TX_FIFO_OVERFLOW_POS))) != 0) { - return SET; - } else { - return RESET; - } +/****************************************************************************/ /** + * @brief Get tx/rx fifo overflow or underflow status + * + * @param spiNo: SPI ID type + * @param fifoSts: Select tx/rx overflow or underflow + * + * @return Status of tx/rx fifo + * + *******************************************************************************/ +BL_Sts_Type SPI_GetFifoStatus(SPI_ID_Type spiNo, SPI_FifoStatus_Type fifoSts) { + uint32_t tmpVal; + uint32_t SPIx = spiAddr[spiNo]; + + /* Check the parameters */ + CHECK_PARAM(IS_SPI_ID_TYPE(spiNo)); + CHECK_PARAM(IS_SPI_FIFOSTATUS_TYPE(fifoSts)); + + /* Get tx/rx fifo overflow or underflow status */ + tmpVal = BL_RD_REG(SPIx, SPI_FIFO_CONFIG_0); + + if ((tmpVal & (1U << (fifoSts + SPI_TX_FIFO_OVERFLOW_POS))) != 0) { + return SET; + } else { + return RESET; + } } /****************************************************************************/ /** - * @brief SPI interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief SPI interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void SPI_IRQHandler(void) -{ - SPI_IntHandler(SPI_ID_0); -} +void SPI_IRQHandler(void) { SPI_IntHandler(SPI_ID_0); } #endif /*@} end of group SPI_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c index 0dec73f19..934c501e7 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_timer.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_timer.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_timer.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_timer.h" @@ -61,9 +61,9 @@ * @{ */ intCallback_Type *timerIntCbfArra[3][TIMER_INT_ALL] = { - { NULL, NULL, NULL }, - { NULL, NULL, NULL }, - { NULL, NULL, NULL } + {NULL, NULL, NULL}, + {NULL, NULL, NULL}, + {NULL, NULL, NULL} }; /*@} end of group TIMER_Private_Variables */ @@ -88,803 +88,770 @@ static void TIMER_IntHandler(IRQn_Type irqNo, TIMER_Chan_Type timerCh); */ /****************************************************************************/ /** - * @brief TIMER interrupt common handler function - * - * @param irqNo: Interrupt ID type - * @param timerCh: TIMER channel type - * - * @return None - * -*******************************************************************************/ + * @brief TIMER interrupt common handler function + * + * @param irqNo: Interrupt ID type + * @param timerCh: TIMER channel type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void TIMER_IntHandler(IRQn_Type irqNo, TIMER_Chan_Type timerCh) -{ - uint32_t intId; - uint32_t tmpVal; - uint32_t tmpAddr; - - intId = BL_RD_WORD(TIMER_BASE + TIMER_TMSR2_OFFSET + 4 * timerCh); - tmpAddr = TIMER_BASE + TIMER_TICR2_OFFSET + 4 * timerCh; - tmpVal = BL_RD_WORD(tmpAddr); - - /* Comparator 0 match interrupt */ - if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_0)) { - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_0)); - - if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_0] != NULL) { - /* Call the callback function */ - timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_0](); - } +void TIMER_IntHandler(IRQn_Type irqNo, TIMER_Chan_Type timerCh) { + uint32_t intId; + uint32_t tmpVal; + uint32_t tmpAddr; + + intId = BL_RD_WORD(TIMER_BASE + TIMER_TMSR2_OFFSET + 4 * timerCh); + tmpAddr = TIMER_BASE + TIMER_TICR2_OFFSET + 4 * timerCh; + tmpVal = BL_RD_WORD(tmpAddr); + + /* Comparator 0 match interrupt */ + if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_0)) { + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_0)); + + if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_0] != NULL) { + /* Call the callback function */ + timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_0](); } + } - /* Comparator 1 match interrupt */ - if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_1)) { - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_1)); + /* Comparator 1 match interrupt */ + if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_1)) { + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_1)); - if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_1] != NULL) { - /* Call the callback function */ - timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_1](); - } + if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_1] != NULL) { + /* Call the callback function */ + timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_1](); } + } - /* Comparator 2 match interrupt */ - if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_2)) { - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_2)); + /* Comparator 2 match interrupt */ + if (BL_IS_REG_BIT_SET(intId, TIMER_TMSR_2)) { + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TCLR_2)); - if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_2] != NULL) { - /* Call the callback function */ - timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_2](); - } + if (timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_2] != NULL) { + /* Call the callback function */ + timerIntCbfArra[irqNo - TIMER_CH0_IRQn][TIMER_INT_COMP_2](); } + } } #endif /****************************************************************************/ /** - * @brief Get the specified channel and match comparator value - * - * @param timerCh: TIMER channel type - * @param cmpNo: TIMER comparator ID type - * - * @return Match comapre register value - * -*******************************************************************************/ -uint32_t TIMER_GetCompValue(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); - - tmpVal = BL_RD_WORD(TIMER_BASE + TIMER_TMR2_0_OFFSET + 4 * (TIMER_MAX_MATCH * timerCh + cmpNo)); - return tmpVal; + * @brief Get the specified channel and match comparator value + * + * @param timerCh: TIMER channel type + * @param cmpNo: TIMER comparator ID type + * + * @return Match comapre register value + * + *******************************************************************************/ +uint32_t TIMER_GetCompValue(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); + + tmpVal = BL_RD_WORD(TIMER_BASE + TIMER_TMR2_0_OFFSET + 4 * (TIMER_MAX_MATCH * timerCh + cmpNo)); + return tmpVal; } /****************************************************************************/ /** - * @brief TIMER set specified channel and comparator compare value - * - * @param timerCh: TIMER channel type - * @param cmpNo: TIMER comparator ID type - * @param val: TIMER match comapre register value - * - * @return None - * -*******************************************************************************/ -void TIMER_SetCompValue(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo, uint32_t val) -{ - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); - - BL_WR_WORD(TIMER_BASE + TIMER_TMR2_0_OFFSET + 4 * (TIMER_MAX_MATCH * timerCh + cmpNo), val); + * @brief TIMER set specified channel and comparator compare value + * + * @param timerCh: TIMER channel type + * @param cmpNo: TIMER comparator ID type + * @param val: TIMER match comapre register value + * + * @return None + * + *******************************************************************************/ +void TIMER_SetCompValue(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo, uint32_t val) { + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); + + BL_WR_WORD(TIMER_BASE + TIMER_TMR2_0_OFFSET + 4 * (TIMER_MAX_MATCH * timerCh + cmpNo), val); } /****************************************************************************/ /** - * @brief TIMER get the specified channel count value - * - * @param timerCh: TIMER channel type - * - * @return TIMER count register value - * -*******************************************************************************/ -uint32_t TIMER_GetCounterValue(TIMER_Chan_Type timerCh) -{ - uint32_t tmpVal; - uint32_t tmpAddr; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - - /* TO avoid risk of reading, don't read TCVWR directly*/ - /* request for read*/ - tmpAddr = TIMER_BASE + TIMER_TCVWR2_OFFSET + 4 * timerCh; - BL_WR_WORD(tmpAddr, 1); - - /* Need wait */ - tmpVal = BL_RD_WORD(tmpAddr); - tmpVal = BL_RD_WORD(tmpAddr); - tmpVal = BL_RD_WORD(tmpAddr); - - return tmpVal; + * @brief TIMER get the specified channel count value + * + * @param timerCh: TIMER channel type + * + * @return TIMER count register value + * + *******************************************************************************/ +uint32_t TIMER_GetCounterValue(TIMER_Chan_Type timerCh) { + uint32_t tmpVal; + uint32_t tmpAddr; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + + /* TO avoid risk of reading, don't read TCVWR directly*/ + /* request for read*/ + tmpAddr = TIMER_BASE + TIMER_TCVWR2_OFFSET + 4 * timerCh; + BL_WR_WORD(tmpAddr, 1); + + /* Need wait */ + tmpVal = BL_RD_WORD(tmpAddr); + tmpVal = BL_RD_WORD(tmpAddr); + tmpVal = BL_RD_WORD(tmpAddr); + + return tmpVal; } /****************************************************************************/ /** - * @brief TIMER get specified channel and comparator match status - * - * @param timerCh: TIMER channel type - * @param cmpNo: TIMER comparator ID type - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type TIMER_GetMatchStatus(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) -{ - uint32_t tmpVal; - BL_Sts_Type bitStatus = RESET; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); - - tmpVal = BL_RD_WORD(TIMER_BASE + TIMER_TMSR2_OFFSET + 4 * timerCh); - - switch (cmpNo) { - case TIMER_COMP_ID_0: - bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_0) ? SET : RESET; - break; - - case TIMER_COMP_ID_1: - bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_1) ? SET : RESET; - break; - - case TIMER_COMP_ID_2: - bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_2) ? SET : RESET; - break; - - default: - break; - } - - return bitStatus; + * @brief TIMER get specified channel and comparator match status + * + * @param timerCh: TIMER channel type + * @param cmpNo: TIMER comparator ID type + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type TIMER_GetMatchStatus(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) { + uint32_t tmpVal; + BL_Sts_Type bitStatus = RESET; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); + + tmpVal = BL_RD_WORD(TIMER_BASE + TIMER_TMSR2_OFFSET + 4 * timerCh); + + switch (cmpNo) { + case TIMER_COMP_ID_0: + bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_0) ? SET : RESET; + break; + + case TIMER_COMP_ID_1: + bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_1) ? SET : RESET; + break; + + case TIMER_COMP_ID_2: + bitStatus = BL_IS_REG_BIT_SET(tmpVal, TIMER_TMSR_2) ? SET : RESET; + break; + + default: + break; + } + + return bitStatus; } /****************************************************************************/ /** - * @brief TIMER get specified channel preload value - * - * @param timerCh: TIMER channel type - * - * @return Preload register value - * -*******************************************************************************/ -uint32_t TIMER_GetPreloadValue(TIMER_Chan_Type timerCh) -{ - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - - return BL_RD_WORD(TIMER_BASE + TIMER_TPLVR2_OFFSET + 4 * timerCh); + * @brief TIMER get specified channel preload value + * + * @param timerCh: TIMER channel type + * + * @return Preload register value + * + *******************************************************************************/ +uint32_t TIMER_GetPreloadValue(TIMER_Chan_Type timerCh) { + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + + return BL_RD_WORD(TIMER_BASE + TIMER_TPLVR2_OFFSET + 4 * timerCh); } /****************************************************************************/ /** - * @brief TIMER set preload register low 32bits value - * - * @param timerCh: TIMER channel type - * @param val: Preload register low 32bits value - * - * @return None - * -*******************************************************************************/ -void TIMER_SetPreloadValue(TIMER_Chan_Type timerCh, uint32_t val) -{ - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - - BL_WR_WORD(TIMER_BASE + TIMER_TPLVR2_OFFSET + 4 * timerCh, val); + * @brief TIMER set preload register low 32bits value + * + * @param timerCh: TIMER channel type + * @param val: Preload register low 32bits value + * + * @return None + * + *******************************************************************************/ +void TIMER_SetPreloadValue(TIMER_Chan_Type timerCh, uint32_t val) { + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + + BL_WR_WORD(TIMER_BASE + TIMER_TPLVR2_OFFSET + 4 * timerCh, val); } /****************************************************************************/ /** - * @brief TIMER set preload trigger source,COMP0,COMP1,COMP2 or None - * - * @param timerCh: TIMER channel type - * @param plSrc: TIMER preload source type - * - * @return None - * -*******************************************************************************/ -void TIMER_SetPreloadTrigSrc(TIMER_Chan_Type timerCh, TIMER_PreLoad_Trig_Type plSrc) -{ - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_PRELOAD_TRIG_TYPE(plSrc)); - - BL_WR_WORD(TIMER_BASE + TIMER_TPLCR2_OFFSET + 4 * timerCh, plSrc); + * @brief TIMER set preload trigger source,COMP0,COMP1,COMP2 or None + * + * @param timerCh: TIMER channel type + * @param plSrc: TIMER preload source type + * + * @return None + * + *******************************************************************************/ +void TIMER_SetPreloadTrigSrc(TIMER_Chan_Type timerCh, TIMER_PreLoad_Trig_Type plSrc) { + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_PRELOAD_TRIG_TYPE(plSrc)); + + BL_WR_WORD(TIMER_BASE + TIMER_TPLCR2_OFFSET + 4 * timerCh, plSrc); } /****************************************************************************/ /** - * @brief TIMER set count mode:preload or free run - * - * @param timerCh: TIMER channel type - * @param countMode: TIMER count mode: TIMER_COUNT_PRELOAD or TIMER_COUNT_FREERUN - * - * @return None - * -*******************************************************************************/ -void TIMER_SetCountMode(TIMER_Chan_Type timerCh, TIMER_CountMode_Type countMode) -{ - uint32_t tmpval; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_COUNTMODE_TYPE(countMode)); - - tmpval = BL_RD_WORD(TIMER_BASE + TIMER_TCMR_OFFSET); - tmpval &= (~(1 << (timerCh + 1))); - tmpval |= (countMode << (timerCh + 1)); - - BL_WR_WORD(TIMER_BASE + TIMER_TCMR_OFFSET, tmpval); + * @brief TIMER set count mode:preload or free run + * + * @param timerCh: TIMER channel type + * @param countMode: TIMER count mode: TIMER_COUNT_PRELOAD or TIMER_COUNT_FREERUN + * + * @return None + * + *******************************************************************************/ +void TIMER_SetCountMode(TIMER_Chan_Type timerCh, TIMER_CountMode_Type countMode) { + uint32_t tmpval; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_COUNTMODE_TYPE(countMode)); + + tmpval = BL_RD_WORD(TIMER_BASE + TIMER_TCMR_OFFSET); + tmpval &= (~(1 << (timerCh + 1))); + tmpval |= (countMode << (timerCh + 1)); + + BL_WR_WORD(TIMER_BASE + TIMER_TCMR_OFFSET, tmpval); } /****************************************************************************/ /** - * @brief TIMER clear interrupt status - * - * @param timerCh: TIMER channel type - * @param cmpNo: TIMER macth comparator ID type - * - * @return None - * -*******************************************************************************/ -void TIMER_ClearIntStatus(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) -{ - uint32_t tmpAddr; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); - - tmpAddr = TIMER_BASE + TIMER_TICR2_OFFSET + 4 * timerCh; - - tmpVal = BL_RD_WORD(tmpAddr); - tmpVal |= (1 << cmpNo); - - BL_WR_WORD(tmpAddr, tmpVal); + * @brief TIMER clear interrupt status + * + * @param timerCh: TIMER channel type + * @param cmpNo: TIMER macth comparator ID type + * + * @return None + * + *******************************************************************************/ +void TIMER_ClearIntStatus(TIMER_Chan_Type timerCh, TIMER_Comp_ID_Type cmpNo) { + uint32_t tmpAddr; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_COMP_ID_TYPE(cmpNo)); + + tmpAddr = TIMER_BASE + TIMER_TICR2_OFFSET + 4 * timerCh; + + tmpVal = BL_RD_WORD(tmpAddr); + tmpVal |= (1 << cmpNo); + + BL_WR_WORD(tmpAddr, tmpVal); } /****************************************************************************/ /** - * @brief TIMER initialization function - * - * @param timerCfg: TIMER configuration structure pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ -BL_Err_Type TIMER_Init(TIMER_CFG_Type *timerCfg) -{ - TIMER_Chan_Type timerCh = timerCfg->timerCh; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CLKSRC_TYPE(timerCfg->clkSrc)); - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCfg->timerCh)); - CHECK_PARAM(IS_TIMER_PRELOAD_TRIG_TYPE(timerCfg->plTrigSrc)); - CHECK_PARAM(IS_TIMER_COUNTMODE_TYPE(timerCfg->countMode)); - - /* Configure timer clock source */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCCR); - - if (timerCh == TIMER_CH0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_1, timerCfg->clkSrc); + * @brief TIMER initialization function + * + * @param timerCfg: TIMER configuration structure pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ +BL_Err_Type TIMER_Init(TIMER_CFG_Type *timerCfg) { + TIMER_Chan_Type timerCh = timerCfg->timerCh; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CLKSRC_TYPE(timerCfg->clkSrc)); + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCfg->timerCh)); + CHECK_PARAM(IS_TIMER_PRELOAD_TRIG_TYPE(timerCfg->plTrigSrc)); + CHECK_PARAM(IS_TIMER_COUNTMODE_TYPE(timerCfg->countMode)); + + /* Configure timer clock source */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCCR); + + if (timerCh == TIMER_CH0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_1, timerCfg->clkSrc); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_2, timerCfg->clkSrc); + } + + BL_WR_REG(TIMER_BASE, TIMER_TCCR, tmpVal); + + /* Configure timer clock division */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCDR); + + if (timerCh == TIMER_CH0) { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_TCDR2, timerCfg->clockDivision); + } else { + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_TCDR3, timerCfg->clockDivision); + } + + BL_WR_REG(TIMER_BASE, TIMER_TCDR, tmpVal); + + /* Configure timer count mode: preload or free run */ + TIMER_SetCountMode(timerCh, timerCfg->countMode); + + /* Configure timer preload trigger src */ + TIMER_SetPreloadTrigSrc(timerCh, timerCfg->plTrigSrc); + + if (timerCfg->countMode == TIMER_COUNT_PRELOAD) { + /* Configure timer preload value */ + TIMER_SetPreloadValue(timerCh, timerCfg->preLoadVal); + + /* Configure match compare values */ + if (timerCfg->matchVal0 > 1 + timerCfg->preLoadVal) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0 - 2); } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_2, timerCfg->clkSrc); + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0); } - BL_WR_REG(TIMER_BASE, TIMER_TCCR, tmpVal); - - /* Configure timer clock division */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCDR); - - if (timerCh == TIMER_CH0) { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_TCDR2, timerCfg->clockDivision); + if (timerCfg->matchVal1 > 1 + timerCfg->preLoadVal) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1 - 2); } else { - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_TCDR3, timerCfg->clockDivision); + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1); } - BL_WR_REG(TIMER_BASE, TIMER_TCDR, tmpVal); - - /* Configure timer count mode: preload or free run */ - TIMER_SetCountMode(timerCh, timerCfg->countMode); - - /* Configure timer preload trigger src */ - TIMER_SetPreloadTrigSrc(timerCh, timerCfg->plTrigSrc); - - if (timerCfg->countMode == TIMER_COUNT_PRELOAD) { - /* Configure timer preload value */ - TIMER_SetPreloadValue(timerCh, timerCfg->preLoadVal); - - /* Configure match compare values */ - if (timerCfg->matchVal0 > 1 + timerCfg->preLoadVal) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0); - } + if (timerCfg->matchVal2 > 1 + timerCfg->preLoadVal) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2 - 2); + } else { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2); + } + } else { + /* Configure match compare values */ + if (timerCfg->matchVal0 > 1) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0 - 2); + } else { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0); + } - if (timerCfg->matchVal1 > 1 + timerCfg->preLoadVal) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1); - } + if (timerCfg->matchVal1 > 1) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1 - 2); + } else { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1); + } - if (timerCfg->matchVal2 > 1 + timerCfg->preLoadVal) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2); - } + if (timerCfg->matchVal2 > 1) { + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2 - 2); } else { - /* Configure match compare values */ - if (timerCfg->matchVal0 > 1) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_0, timerCfg->matchVal0); - } - - if (timerCfg->matchVal1 > 1) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_1, timerCfg->matchVal1); - } - - if (timerCfg->matchVal2 > 1) { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2 - 2); - } else { - TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2); - } + TIMER_SetCompValue(timerCh, TIMER_COMP_ID_2, timerCfg->matchVal2); } + } #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(TIMER_CH0_IRQn, TIMER_CH0_IRQHandler); - Interrupt_Handler_Register(TIMER_CH1_IRQn, TIMER_CH1_IRQHandler); + Interrupt_Handler_Register(TIMER_CH0_IRQn, TIMER_CH0_IRQHandler); + Interrupt_Handler_Register(TIMER_CH1_IRQn, TIMER_CH1_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief TIMER enable one channel function - * - * @param timerCh: TIMER channel type - * - * @return None - * -*******************************************************************************/ -void TIMER_Enable(TIMER_Chan_Type timerCh) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCER); - tmpVal |= (1 << (timerCh + 1)); + * @brief TIMER enable one channel function + * + * @param timerCh: TIMER channel type + * + * @return None + * + *******************************************************************************/ +void TIMER_Enable(TIMER_Chan_Type timerCh) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCER); + tmpVal |= (1 << (timerCh + 1)); + + BL_WR_REG(TIMER_BASE, TIMER_TCER, tmpVal); +} - BL_WR_REG(TIMER_BASE, TIMER_TCER, tmpVal); +/****************************************************************************/ /** + * @brief TIMER disable one channel function + * + * @param timerCh: TIMER channel type + * + * @return None + * + *******************************************************************************/ +void TIMER_Disable(TIMER_Chan_Type timerCh) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCER); + tmpVal &= (~(1 << (timerCh + 1))); + + BL_WR_REG(TIMER_BASE, TIMER_TCER, tmpVal); } /****************************************************************************/ /** - * @brief TIMER disable one channel function - * - * @param timerCh: TIMER channel type - * - * @return None - * -*******************************************************************************/ -void TIMER_Disable(TIMER_Chan_Type timerCh) -{ - uint32_t tmpVal; + * @brief TIMER mask or unmask certain or all interrupt + * + * @param timerCh: TIMER channel type + * @param intType: TIMER interrupt type + * @param intMask: TIMER interrupt mask value:MASK:disbale interrupt.UNMASK:enable interrupt + * + * @return None + * + *******************************************************************************/ +void TIMER_IntMask(TIMER_Chan_Type timerCh, TIMER_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpAddr; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + CHECK_PARAM(IS_TIMER_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpAddr = TIMER_BASE + TIMER_TIER2_OFFSET + 4 * timerCh; + tmpVal = BL_RD_WORD(tmpAddr); + + switch (intType) { + case TIMER_INT_COMP_0: + if (intMask == UNMASK) { + /* Enable this interrupt */ + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_0)); + } else { + /* Disable this interrupt */ + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_0)); + } - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); + break; - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCER); - tmpVal &= (~(1 << (timerCh + 1))); + case TIMER_INT_COMP_1: + if (intMask == UNMASK) { + /* Enable this interrupt */ + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_1)); + } else { + /* Disable this interrupt */ + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_1)); + } - BL_WR_REG(TIMER_BASE, TIMER_TCER, tmpVal); -} + break; -/****************************************************************************/ /** - * @brief TIMER mask or unmask certain or all interrupt - * - * @param timerCh: TIMER channel type - * @param intType: TIMER interrupt type - * @param intMask: TIMER interrupt mask value:MASK:disbale interrupt.UNMASK:enable interrupt - * - * @return None - * -*******************************************************************************/ -void TIMER_IntMask(TIMER_Chan_Type timerCh, TIMER_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpAddr; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerCh)); - CHECK_PARAM(IS_TIMER_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpAddr = TIMER_BASE + TIMER_TIER2_OFFSET + 4 * timerCh; - tmpVal = BL_RD_WORD(tmpAddr); - - switch (intType) { - case TIMER_INT_COMP_0: - if (intMask == UNMASK) { - /* Enable this interrupt */ - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_0)); - } else { - /* Disable this interrupt */ - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_0)); - } - - break; - - case TIMER_INT_COMP_1: - if (intMask == UNMASK) { - /* Enable this interrupt */ - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_1)); - } else { - /* Disable this interrupt */ - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_1)); - } - - break; - - case TIMER_INT_COMP_2: - if (intMask == UNMASK) { - /* Enable this interrupt */ - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_2)); - } else { - /* Disable this interrupt */ - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_2)); - } - - break; - - case TIMER_INT_ALL: - if (intMask == UNMASK) { - /* Enable this interrupt */ - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_0)); - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_1)); - BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_2)); - } else { - /* Disable this interrupt */ - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_0)); - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_1)); - BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_2)); - } - - break; - - default: - break; + case TIMER_INT_COMP_2: + if (intMask == UNMASK) { + /* Enable this interrupt */ + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_2)); + } else { + /* Disable this interrupt */ + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_2)); } -} - -/****************************************************************************/ /** - * @brief TIMER set watchdog clock source and clock division - * - * @param clkSrc: Watchdog timer clock source type - * @param div: Watchdog timer clock division value - * - * @return None - * -*******************************************************************************/ -void WDT_Set_Clock(TIMER_ClkSrc_Type clkSrc, uint8_t div) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CLKSRC_TYPE(clkSrc)); - - /* Configure watchdog timer clock source */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCCR); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_WDT, clkSrc); - BL_WR_REG(TIMER_BASE, TIMER_TCCR, tmpVal); - - /* Configure watchdog timer clock divison */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCDR); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_WCDR, div); - BL_WR_REG(TIMER_BASE, TIMER_TCDR, tmpVal); -} -/****************************************************************************/ /** - * @brief TIMER get watchdog match compare value - * - * @param None - * - * @return Watchdog match comapre register value - * -*******************************************************************************/ -uint16_t WDT_GetMatchValue(void) -{ - uint32_t tmpVal; + break; - WDT_ENABLE_ACCESS(); + case TIMER_INT_ALL: + if (intMask == UNMASK) { + /* Enable this interrupt */ + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_0)); + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_1)); + BL_WR_WORD(tmpAddr, BL_SET_REG_BIT(tmpVal, TIMER_TIER_2)); + } else { + /* Disable this interrupt */ + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_0)); + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_1)); + BL_WR_WORD(tmpAddr, BL_CLR_REG_BIT(tmpVal, TIMER_TIER_2)); + } - /* Get watchdog timer match register value */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMR); + break; - return tmpVal; + default: + break; + } } /****************************************************************************/ /** - * @brief TIMER set watchdog match compare value - * - * @param val: Watchdog match compare value - * - * @return None - * -*******************************************************************************/ -void WDT_SetCompValue(uint16_t val) -{ - WDT_ENABLE_ACCESS(); - - /* Set watchdog timer match register value */ - BL_WR_REG(TIMER_BASE, TIMER_WMR, val); + * @brief TIMER set watchdog clock source and clock division + * + * @param clkSrc: Watchdog timer clock source type + * @param div: Watchdog timer clock division value + * + * @return None + * + *******************************************************************************/ +void WDT_Set_Clock(TIMER_ClkSrc_Type clkSrc, uint8_t div) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CLKSRC_TYPE(clkSrc)); + + /* Configure watchdog timer clock source */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCCR); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_CS_WDT, clkSrc); + BL_WR_REG(TIMER_BASE, TIMER_TCCR, tmpVal); + + /* Configure watchdog timer clock divison */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_TCDR); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, TIMER_WCDR, div); + BL_WR_REG(TIMER_BASE, TIMER_TCDR, tmpVal); } /****************************************************************************/ /** - * @brief TIMER get watchdog count register value - * - * @param None - * - * @return Watchdog count register value - * -*******************************************************************************/ -uint16_t WDT_GetCounterValue(void) -{ - uint32_t tmpVal; - - WDT_ENABLE_ACCESS(); - - /* Get watchdog timer count register value */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WVR); - - return tmpVal; + * @brief TIMER get watchdog match compare value + * + * @param None + * + * @return Watchdog match comapre register value + * + *******************************************************************************/ +uint16_t WDT_GetMatchValue(void) { + uint32_t tmpVal; + + WDT_ENABLE_ACCESS(); + + /* Get watchdog timer match register value */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMR); + + return tmpVal; } /****************************************************************************/ /** - * @brief TIMER reset watchdog count register value - * - * @param None - * - * @return None - * -*******************************************************************************/ -void WDT_ResetCounterValue(void) -{ - uint32_t tmpVal; - - /* Reset watchdog timer count register value */ - WDT_ENABLE_ACCESS(); - - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WCR); - - /* Set watchdog counter reset register bit0 to 1 */ - BL_WR_REG(TIMER_BASE, TIMER_WCR, BL_SET_REG_BIT(tmpVal, TIMER_WCR)); + * @brief TIMER set watchdog match compare value + * + * @param val: Watchdog match compare value + * + * @return None + * + *******************************************************************************/ +void WDT_SetCompValue(uint16_t val) { + WDT_ENABLE_ACCESS(); + + /* Set watchdog timer match register value */ + BL_WR_REG(TIMER_BASE, TIMER_WMR, val); } /****************************************************************************/ /** - * @brief TIMER get watchdog reset status - * - * @param None - * - * @return SET or RESET - * -*******************************************************************************/ -BL_Sts_Type WDT_GetResetStatus(void) -{ - uint32_t tmpVal; - - WDT_ENABLE_ACCESS(); - - /* Get watchdog status register */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WSR); - - return (BL_IS_REG_BIT_SET(tmpVal, TIMER_WTS)) ? SET : RESET; + * @brief TIMER get watchdog count register value + * + * @param None + * + * @return Watchdog count register value + * + *******************************************************************************/ +uint16_t WDT_GetCounterValue(void) { + uint32_t tmpVal; + + WDT_ENABLE_ACCESS(); + + /* Get watchdog timer count register value */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WVR); + + return tmpVal; } /****************************************************************************/ /** - * @brief TIMER clear watchdog reset status - * - * @param None - * - * @return None - * -*******************************************************************************/ -void WDT_ClearResetStatus(void) -{ - uint32_t tmpVal; - - WDT_ENABLE_ACCESS(); + * @brief TIMER reset watchdog count register value + * + * @param None + * + * @return None + * + *******************************************************************************/ +void WDT_ResetCounterValue(void) { + uint32_t tmpVal; + + /* Reset watchdog timer count register value */ + WDT_ENABLE_ACCESS(); + + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WCR); + + /* Set watchdog counter reset register bit0 to 1 */ + BL_WR_REG(TIMER_BASE, TIMER_WCR, BL_SET_REG_BIT(tmpVal, TIMER_WCR)); +} - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WSR); +/****************************************************************************/ /** + * @brief TIMER get watchdog reset status + * + * @param None + * + * @return SET or RESET + * + *******************************************************************************/ +BL_Sts_Type WDT_GetResetStatus(void) { + uint32_t tmpVal; + + WDT_ENABLE_ACCESS(); + + /* Get watchdog status register */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WSR); + + return (BL_IS_REG_BIT_SET(tmpVal, TIMER_WTS)) ? SET : RESET; +} - /* Set watchdog status register */ - BL_WR_REG(TIMER_BASE, TIMER_WSR, BL_CLR_REG_BIT(tmpVal, TIMER_WTS)); +/****************************************************************************/ /** + * @brief TIMER clear watchdog reset status + * + * @param None + * + * @return None + * + *******************************************************************************/ +void WDT_ClearResetStatus(void) { + uint32_t tmpVal; + + WDT_ENABLE_ACCESS(); + + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WSR); + + /* Set watchdog status register */ + BL_WR_REG(TIMER_BASE, TIMER_WSR, BL_CLR_REG_BIT(tmpVal, TIMER_WTS)); } /****************************************************************************/ /** - * @brief TIMER enable watchdog function - * - * @param None - * - * @return None - * -*******************************************************************************/ -void WDT_Enable(void) -{ - uint32_t tmpVal; + * @brief TIMER enable watchdog function + * + * @param None + * + * @return None + * + *******************************************************************************/ +void WDT_Enable(void) { + uint32_t tmpVal; #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(TIMER_WDT_IRQn, TIMER_WDT_IRQHandler); + Interrupt_Handler_Register(TIMER_WDT_IRQn, TIMER_WDT_IRQHandler); #endif - WDT_ENABLE_ACCESS(); + WDT_ENABLE_ACCESS(); - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); - BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_SET_REG_BIT(tmpVal, TIMER_WE)); + BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_SET_REG_BIT(tmpVal, TIMER_WE)); } /****************************************************************************/ /** - * @brief Watchdog timer disable function - * - * @param None - * - * @return None - * -*******************************************************************************/ -void WDT_Disable(void) -{ - uint32_t tmpVal; + * @brief Watchdog timer disable function + * + * @param None + * + * @return None + * + *******************************************************************************/ +void WDT_Disable(void) { + uint32_t tmpVal; - WDT_ENABLE_ACCESS(); + WDT_ENABLE_ACCESS(); - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); - BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpVal, TIMER_WE)); + BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpVal, TIMER_WE)); } /****************************************************************************/ /** - * @brief Watchdog timer mask or unmask certain or all interrupt - * - * @param intType: Watchdog interrupt type - * @param intMask: Watchdog interrupt mask value:MASK:disbale interrupt.UNMASK:enable interrupt - * - * @return None - * -*******************************************************************************/ -void WDT_IntMask(WDT_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_WDT_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - WDT_ENABLE_ACCESS(); - - /* Deal with watchdog match/interrupt enable register, - WRIE:watchdog reset/interrupt enable */ - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); - - switch (intType) { - case WDT_INT: - if (intMask == UNMASK) { - /* Enable this interrupt */ - /* 0 means generates a watchdog interrupt, - a watchdog timer reset is not generated*/ - BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpVal, TIMER_WRIE)); - } else { - /* Disable this interrupt */ - /* 1 means generates a watchdog timer reset, - a watchdog interrupt is not generated*/ - BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_SET_REG_BIT(tmpVal, TIMER_WRIE)); - } - - break; - - default: - break; + * @brief Watchdog timer mask or unmask certain or all interrupt + * + * @param intType: Watchdog interrupt type + * @param intMask: Watchdog interrupt mask value:MASK:disbale interrupt.UNMASK:enable interrupt + * + * @return None + * + *******************************************************************************/ +void WDT_IntMask(WDT_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_WDT_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + WDT_ENABLE_ACCESS(); + + /* Deal with watchdog match/interrupt enable register, + WRIE:watchdog reset/interrupt enable */ + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WMER); + + switch (intType) { + case WDT_INT: + if (intMask == UNMASK) { + /* Enable this interrupt */ + /* 0 means generates a watchdog interrupt, + a watchdog timer reset is not generated*/ + BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_CLR_REG_BIT(tmpVal, TIMER_WRIE)); + } else { + /* Disable this interrupt */ + /* 1 means generates a watchdog timer reset, + a watchdog interrupt is not generated*/ + BL_WR_REG(TIMER_BASE, TIMER_WMER, BL_SET_REG_BIT(tmpVal, TIMER_WRIE)); } + + break; + + default: + break; + } } /****************************************************************************/ /** - * @brief TIMER channel 0 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief TIMER channel 0 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void TIMER_CH0_IRQHandler(void) -{ - TIMER_IntHandler(TIMER_CH0_IRQn, TIMER_CH0); -} +void TIMER_CH0_IRQHandler(void) { TIMER_IntHandler(TIMER_CH0_IRQn, TIMER_CH0); } #endif /****************************************************************************/ /** - * @brief TIMER channel 1 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief TIMER channel 1 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void TIMER_CH1_IRQHandler(void) -{ - TIMER_IntHandler(TIMER_CH1_IRQn, TIMER_CH1); -} +void TIMER_CH1_IRQHandler(void) { TIMER_IntHandler(TIMER_CH1_IRQn, TIMER_CH1); } #endif /****************************************************************************/ /** - * @brief TIMER watchdog interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief TIMER watchdog interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void TIMER_WDT_IRQHandler(void) -{ - uint32_t tmpVal; +void TIMER_WDT_IRQHandler(void) { + uint32_t tmpVal; - WDT_ENABLE_ACCESS(); + WDT_ENABLE_ACCESS(); - tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WICR); - BL_WR_REG(TIMER_BASE, TIMER_WICR, BL_SET_REG_BIT(tmpVal, TIMER_WICLR)); + tmpVal = BL_RD_REG(TIMER_BASE, TIMER_WICR); + BL_WR_REG(TIMER_BASE, TIMER_WICR, BL_SET_REG_BIT(tmpVal, TIMER_WICLR)); - if (timerIntCbfArra[TIMER_WDT_IRQn - TIMER_CH0_IRQn][WDT_INT] != NULL) { - /* Call the callback function */ - timerIntCbfArra[TIMER_WDT_IRQn - TIMER_CH0_IRQn][WDT_INT](); - } + if (timerIntCbfArra[TIMER_WDT_IRQn - TIMER_CH0_IRQn][WDT_INT] != NULL) { + /* Call the callback function */ + timerIntCbfArra[TIMER_WDT_IRQn - TIMER_CH0_IRQn][WDT_INT](); + } } #endif /****************************************************************************/ /** - * @brief TIMER install interrupt callback - * - * @param timerChan: TIMER channel type - * @param intType: TIMER interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return None - * -*******************************************************************************/ -void Timer_Int_Callback_Install(TIMER_Chan_Type timerChan, TIMER_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerChan)); - CHECK_PARAM(IS_TIMER_INT_TYPE(intType)); - - timerIntCbfArra[timerChan][intType] = cbFun; + * @brief TIMER install interrupt callback + * + * @param timerChan: TIMER channel type + * @param intType: TIMER interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return None + * + *******************************************************************************/ +void Timer_Int_Callback_Install(TIMER_Chan_Type timerChan, TIMER_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_TIMER_CHAN_TYPE(timerChan)); + CHECK_PARAM(IS_TIMER_INT_TYPE(intType)); + + timerIntCbfArra[timerChan][intType] = cbFun; } /****************************************************************************/ /** - * @brief Watchdog install interrupt callback - * - * @param wdtInt: Watchdog interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return None - * -*******************************************************************************/ -void WDT_Int_Callback_Install(WDT_INT_Type wdtInt, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_WDT_INT_TYPE(wdtInt)); - - timerIntCbfArra[2][wdtInt] = cbFun; + * @brief Watchdog install interrupt callback + * + * @param wdtInt: Watchdog interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return None + * + *******************************************************************************/ +void WDT_Int_Callback_Install(WDT_INT_Type wdtInt, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_WDT_INT_TYPE(wdtInt)); + + timerIntCbfArra[2][wdtInt] = cbFun; } /*@} end of group TIMER_Private_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c index 6b8ce8f24..fbc45c9a5 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_uart.c @@ -1,38 +1,38 @@ /** - ****************************************************************************** - * @file bl702_uart.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_uart.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_uart.h" #include "bl702_glb.h" @@ -61,11 +61,8 @@ /** @defgroup UART_Private_Variables * @{ */ -static const uint32_t uartAddr[2] = { UART0_BASE, UART1_BASE }; -static intCallback_Type *uartIntCbfArra[2][UART_INT_ALL] = { - { NULL }, - { NULL } -}; +static const uint32_t uartAddr[2] = {UART0_BASE, UART1_BASE}; +static intCallback_Type *uartIntCbfArra[2][UART_INT_ALL] = {{NULL}, {NULL}}; /*@} end of group UART_Private_Variables */ @@ -89,95 +86,94 @@ static void UART_IntHandler(UART_ID_Type uartId); */ /****************************************************************************/ /** - * @brief UART interrupt common handler function - * - * @param uartId: UART ID type - * - * @return None - * -*******************************************************************************/ + * @brief UART interrupt common handler function + * + * @param uartId: UART ID type + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -static void UART_IntHandler(UART_ID_Type uartId) -{ - uint32_t tmpVal = 0; - uint32_t maskVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - tmpVal = BL_RD_REG(UARTx, UART_INT_STS); - maskVal = BL_RD_REG(UARTx, UART_INT_MASK); - - /* Length of uart tx data transfer arrived interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_END_MASK)) { - BL_WR_REG(UARTx, UART_INT_CLEAR, 0x1); - - if (uartIntCbfArra[uartId][UART_INT_TX_END] != NULL) { - uartIntCbfArra[uartId][UART_INT_TX_END](); - } +static void UART_IntHandler(UART_ID_Type uartId) { + uint32_t tmpVal = 0; + uint32_t maskVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + tmpVal = BL_RD_REG(UARTx, UART_INT_STS); + maskVal = BL_RD_REG(UARTx, UART_INT_MASK); + + /* Length of uart tx data transfer arrived interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_END_MASK)) { + BL_WR_REG(UARTx, UART_INT_CLEAR, 0x1); + + if (uartIntCbfArra[uartId][UART_INT_TX_END] != NULL) { + uartIntCbfArra[uartId][UART_INT_TX_END](); } + } - /* Length of uart rx data transfer arrived interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_END_MASK)) { - BL_WR_REG(UARTx, UART_INT_CLEAR, 0x2); + /* Length of uart rx data transfer arrived interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_END_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_END_MASK)) { + BL_WR_REG(UARTx, UART_INT_CLEAR, 0x2); - if (uartIntCbfArra[uartId][UART_INT_RX_END] != NULL) { - uartIntCbfArra[uartId][UART_INT_RX_END](); - } + if (uartIntCbfArra[uartId][UART_INT_RX_END] != NULL) { + uartIntCbfArra[uartId][UART_INT_RX_END](); } + } - /* Tx fifo ready interrupt,auto-cleared when data is pushed */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FIFO_MASK)) { - if (uartIntCbfArra[uartId][UART_INT_TX_FIFO_REQ] != NULL) { - uartIntCbfArra[uartId][UART_INT_TX_FIFO_REQ](); - } + /* Tx fifo ready interrupt,auto-cleared when data is pushed */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FIFO_MASK)) { + if (uartIntCbfArra[uartId][UART_INT_TX_FIFO_REQ] != NULL) { + uartIntCbfArra[uartId][UART_INT_TX_FIFO_REQ](); } + } - /* Rx fifo ready interrupt,auto-cleared when data is popped */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FIFO_MASK)) { - if (uartIntCbfArra[uartId][UART_INT_RX_FIFO_REQ] != NULL) { - uartIntCbfArra[uartId][UART_INT_RX_FIFO_REQ](); - } + /* Rx fifo ready interrupt,auto-cleared when data is popped */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FIFO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FIFO_MASK)) { + if (uartIntCbfArra[uartId][UART_INT_RX_FIFO_REQ] != NULL) { + uartIntCbfArra[uartId][UART_INT_RX_FIFO_REQ](); } + } - /* Rx time-out interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_RTO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_RTO_MASK)) { - BL_WR_REG(UARTx, UART_INT_CLEAR, 0x10); + /* Rx time-out interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_RTO_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_RTO_MASK)) { + BL_WR_REG(UARTx, UART_INT_CLEAR, 0x10); - if (uartIntCbfArra[uartId][UART_INT_RTO] != NULL) { - uartIntCbfArra[uartId][UART_INT_RTO](); - } + if (uartIntCbfArra[uartId][UART_INT_RTO] != NULL) { + uartIntCbfArra[uartId][UART_INT_RTO](); } + } - /* Rx parity check error interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_PCE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_PCE_MASK)) { - BL_WR_REG(UARTx, UART_INT_CLEAR, 0x20); + /* Rx parity check error interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_PCE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_PCE_MASK)) { + BL_WR_REG(UARTx, UART_INT_CLEAR, 0x20); - if (uartIntCbfArra[uartId][UART_INT_PCE] != NULL) { - uartIntCbfArra[uartId][UART_INT_PCE](); - } + if (uartIntCbfArra[uartId][UART_INT_PCE] != NULL) { + uartIntCbfArra[uartId][UART_INT_PCE](); } + } - /* Tx fifo overflow/underflow error interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FER_MASK)) { - if (uartIntCbfArra[uartId][UART_INT_TX_FER] != NULL) { - uartIntCbfArra[uartId][UART_INT_TX_FER](); - } + /* Tx fifo overflow/underflow error interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_UTX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_UTX_FER_MASK)) { + if (uartIntCbfArra[uartId][UART_INT_TX_FER] != NULL) { + uartIntCbfArra[uartId][UART_INT_TX_FER](); } + } - /* Rx fifo overflow/underflow error interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FER_MASK)) { - if (uartIntCbfArra[uartId][UART_INT_RX_FER] != NULL) { - uartIntCbfArra[uartId][UART_INT_RX_FER](); - } + /* Rx fifo overflow/underflow error interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_FER_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_FER_MASK)) { + if (uartIntCbfArra[uartId][UART_INT_RX_FER] != NULL) { + uartIntCbfArra[uartId][UART_INT_RX_FER](); } + } - /* Rx lin mode sync field error interrupt */ - if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_LSE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_LSE_MASK)) { - BL_WR_REG(UARTx, UART_INT_CLEAR, 0x100); + /* Rx lin mode sync field error interrupt */ + if (BL_IS_REG_BIT_SET(tmpVal, UART_URX_LSE_INT) && !BL_IS_REG_BIT_SET(maskVal, UART_CR_URX_LSE_MASK)) { + BL_WR_REG(UARTx, UART_INT_CLEAR, 0x100); - if (uartIntCbfArra[uartId][UART_INT_LSE] != NULL) { - uartIntCbfArra[uartId][UART_INT_LSE](); - } + if (uartIntCbfArra[uartId][UART_INT_LSE] != NULL) { + uartIntCbfArra[uartId][UART_INT_LSE](); } + } } #endif @@ -188,1035 +184,997 @@ static void UART_IntHandler(UART_ID_Type uartId) */ /****************************************************************************/ /** - * @brief UART initialization function - * - * @param uartId: UART ID type - * @param uartCfg: UART configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_Init(UART_ID_Type uartId, UART_CFG_Type *uartCfg) -{ - uint32_t tmpValTxCfg = 0; - uint32_t tmpValRxCfg = 0; - uint32_t fraction = 0; - uint32_t baudRateDivisor = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_PARITY_TYPE(uartCfg->parity)); - CHECK_PARAM(IS_UART_DATABITS_TYPE(uartCfg->dataBits)); - CHECK_PARAM(IS_UART_STOPBITS_TYPE(uartCfg->stopBits)); - CHECK_PARAM(IS_UART_BYTEBITINVERSE_TYPE(uartCfg->byteBitInverse)); - - /* Cal the baud rate divisor */ - fraction = uartCfg->uartClk * 10 / uartCfg->baudRate % 10; - baudRateDivisor = uartCfg->uartClk / uartCfg->baudRate; - - if (fraction >= 5) { - ++baudRateDivisor; - } - - /* Set the baud rate register value */ - BL_WR_REG(UARTx, UART_BIT_PRD, ((baudRateDivisor - 1) << 0x10) | ((baudRateDivisor - 1) & 0xFFFF)); - - /* Configure parity type */ - tmpValTxCfg = BL_RD_REG(UARTx, UART_UTX_CONFIG); - tmpValRxCfg = BL_RD_REG(UARTx, UART_URX_CONFIG); - - switch (uartCfg->parity) { - case UART_PARITY_NONE: - tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); - tmpValRxCfg = BL_CLR_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); - break; - - case UART_PARITY_ODD: - tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); - tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_SEL); - tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); - tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_SEL); - break; - - case UART_PARITY_EVEN: - tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); - tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_SEL); - tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); - tmpValRxCfg = BL_CLR_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_SEL); - break; - - default: - break; - } - - /* Configure data bits */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_D, (uartCfg->dataBits + 4)); - tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_BIT_CNT_D, (uartCfg->dataBits + 4)); - - /* Configure tx stop bits */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_P, uartCfg->stopBits); - - /* Configure tx cts flow control function */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_CTS_EN, uartCfg->ctsFlowControl); - - /* Configure rx input de-glitch function */ - tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_DEG_EN, uartCfg->rxDeglitch); - - /* Configure tx lin mode function */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_LIN_EN, uartCfg->txLinMode); - - /* Configure rx lin mode function */ - tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_LIN_EN, uartCfg->rxLinMode); - - /* Set tx break bit count for lin protocol */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_B, uartCfg->txBreakBitCnt); - - /* Write back */ - BL_WR_REG(UARTx, UART_UTX_CONFIG, tmpValTxCfg); - BL_WR_REG(UARTx, UART_URX_CONFIG, tmpValRxCfg); - - /* Configure LSB-first or MSB-first */ - tmpValTxCfg = BL_RD_REG(UARTx, UART_DATA_CONFIG); - - if (UART_MSB_FIRST == uartCfg->byteBitInverse) { - tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UART_BIT_INV); - } else { - tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UART_BIT_INV); - } - - BL_WR_REG(UARTx, UART_DATA_CONFIG, tmpValTxCfg); - - tmpValTxCfg = BL_RD_REG(UARTx, UART_SW_MODE); - /* Configure rx rts output SW control mode */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_URX_RTS_SW_MODE, uartCfg->rtsSoftwareControl); - /* Configure tx output SW control mode */ - tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_TXD_SW_MODE, uartCfg->txSoftwareControl); - BL_WR_REG(UARTx, UART_SW_MODE, tmpValTxCfg); + * @brief UART initialization function + * + * @param uartId: UART ID type + * @param uartCfg: UART configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_Init(UART_ID_Type uartId, UART_CFG_Type *uartCfg) { + uint32_t tmpValTxCfg = 0; + uint32_t tmpValRxCfg = 0; + uint32_t fraction = 0; + uint32_t baudRateDivisor = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_PARITY_TYPE(uartCfg->parity)); + CHECK_PARAM(IS_UART_DATABITS_TYPE(uartCfg->dataBits)); + CHECK_PARAM(IS_UART_STOPBITS_TYPE(uartCfg->stopBits)); + CHECK_PARAM(IS_UART_BYTEBITINVERSE_TYPE(uartCfg->byteBitInverse)); + + /* Cal the baud rate divisor */ + fraction = uartCfg->uartClk * 10 / uartCfg->baudRate % 10; + baudRateDivisor = uartCfg->uartClk / uartCfg->baudRate; + + if (fraction >= 5) { + ++baudRateDivisor; + } + + /* Set the baud rate register value */ + BL_WR_REG(UARTx, UART_BIT_PRD, ((baudRateDivisor - 1) << 0x10) | ((baudRateDivisor - 1) & 0xFFFF)); + + /* Configure parity type */ + tmpValTxCfg = BL_RD_REG(UARTx, UART_UTX_CONFIG); + tmpValRxCfg = BL_RD_REG(UARTx, UART_URX_CONFIG); + + switch (uartCfg->parity) { + case UART_PARITY_NONE: + tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); + tmpValRxCfg = BL_CLR_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); + break; + + case UART_PARITY_ODD: + tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); + tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_SEL); + tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); + tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_SEL); + break; + + case UART_PARITY_EVEN: + tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_EN); + tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UTX_PRT_SEL); + tmpValRxCfg = BL_SET_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_EN); + tmpValRxCfg = BL_CLR_REG_BIT(tmpValRxCfg, UART_CR_URX_PRT_SEL); + break; + + default: + break; + } + + /* Configure data bits */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_D, (uartCfg->dataBits + 4)); + tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_BIT_CNT_D, (uartCfg->dataBits + 4)); + + /* Configure tx stop bits */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_P, uartCfg->stopBits); + + /* Configure tx cts flow control function */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_CTS_EN, uartCfg->ctsFlowControl); + + /* Configure rx input de-glitch function */ + tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_DEG_EN, uartCfg->rxDeglitch); + + /* Configure tx lin mode function */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_LIN_EN, uartCfg->txLinMode); + + /* Configure rx lin mode function */ + tmpValRxCfg = BL_SET_REG_BITS_VAL(tmpValRxCfg, UART_CR_URX_LIN_EN, uartCfg->rxLinMode); + + /* Set tx break bit count for lin protocol */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_BIT_CNT_B, uartCfg->txBreakBitCnt); + + /* Write back */ + BL_WR_REG(UARTx, UART_UTX_CONFIG, tmpValTxCfg); + BL_WR_REG(UARTx, UART_URX_CONFIG, tmpValRxCfg); + + /* Configure LSB-first or MSB-first */ + tmpValTxCfg = BL_RD_REG(UARTx, UART_DATA_CONFIG); + + if (UART_MSB_FIRST == uartCfg->byteBitInverse) { + tmpValTxCfg = BL_SET_REG_BIT(tmpValTxCfg, UART_CR_UART_BIT_INV); + } else { + tmpValTxCfg = BL_CLR_REG_BIT(tmpValTxCfg, UART_CR_UART_BIT_INV); + } + + BL_WR_REG(UARTx, UART_DATA_CONFIG, tmpValTxCfg); + + tmpValTxCfg = BL_RD_REG(UARTx, UART_SW_MODE); + /* Configure rx rts output SW control mode */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_URX_RTS_SW_MODE, uartCfg->rtsSoftwareControl); + /* Configure tx output SW control mode */ + tmpValTxCfg = BL_SET_REG_BITS_VAL(tmpValTxCfg, UART_CR_UTX_TXD_SW_MODE, uartCfg->txSoftwareControl); + BL_WR_REG(UARTx, UART_SW_MODE, tmpValTxCfg); #ifndef BFLB_USE_HAL_DRIVER - Interrupt_Handler_Register(UART0_IRQn, UART0_IRQHandler); - Interrupt_Handler_Register(UART1_IRQn, UART1_IRQHandler); + Interrupt_Handler_Register(UART0_IRQn, UART0_IRQHandler); + Interrupt_Handler_Register(UART1_IRQn, UART1_IRQHandler); #endif - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set default value of all registers function - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_DeInit(UART_ID_Type uartId) -{ - if (UART0_ID == uartId) { - GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0); - } else if (UART1_ID == uartId) { - GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1); - } - - return SUCCESS; + * @brief UART set default value of all registers function + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_DeInit(UART_ID_Type uartId) { + if (UART0_ID == uartId) { + GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART0); + } else if (UART1_ID == uartId) { + GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_UART1); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART configure fifo function - * - * @param uartId: UART ID type - * @param fifoCfg: FIFO configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_FifoConfig(UART_ID_Type uartId, UART_FifoCfg_Type *fifoCfg) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Deal with uart fifo configure register */ - tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_1); - /* Configure dma tx fifo threshold */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_TX_FIFO_TH, fifoCfg->txFifoDmaThreshold); - /* Configure dma rx fifo threshold */ - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_RX_FIFO_TH, fifoCfg->rxFifoDmaThreshold); - /* Write back */ - BL_WR_REG(UARTx, UART_FIFO_CONFIG_1, tmpVal); - - /* Enable or disable uart fifo dma function */ - tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); - - if (ENABLE == fifoCfg->txFifoDmaEnable) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_TX_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_TX_EN); - } - - if (ENABLE == fifoCfg->rxFifoDmaEnable) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_RX_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_RX_EN); - } - - BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, tmpVal); - - return SUCCESS; + * @brief UART configure fifo function + * + * @param uartId: UART ID type + * @param fifoCfg: FIFO configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_FifoConfig(UART_ID_Type uartId, UART_FifoCfg_Type *fifoCfg) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Deal with uart fifo configure register */ + tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_1); + /* Configure dma tx fifo threshold */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_TX_FIFO_TH, fifoCfg->txFifoDmaThreshold); + /* Configure dma rx fifo threshold */ + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_RX_FIFO_TH, fifoCfg->rxFifoDmaThreshold); + /* Write back */ + BL_WR_REG(UARTx, UART_FIFO_CONFIG_1, tmpVal); + + /* Enable or disable uart fifo dma function */ + tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); + + if (ENABLE == fifoCfg->txFifoDmaEnable) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_TX_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_TX_EN); + } + + if (ENABLE == fifoCfg->rxFifoDmaEnable) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_DMA_RX_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_DMA_RX_EN); + } + + BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART configure infra function - * - * @param uartId: UART ID type - * @param irCfg: IR configuration structure pointer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_IrConfig(UART_ID_Type uartId, UART_IrCfg_Type *irCfg) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + * @brief UART configure infra function + * + * @param uartId: UART ID type + * @param irCfg: IR configuration structure pointer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_IrConfig(UART_ID_Type uartId, UART_IrCfg_Type *irCfg) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Configure tx ir mode */ + tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); + + if (ENABLE == irCfg->txIrEnable) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_UTX_IR_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_IR_EN); + } + + if (ENABLE == irCfg->txIrInverse) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_UTX_IR_INV); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_IR_INV); + } + + BL_WR_REG(UARTx, UART_UTX_CONFIG, tmpVal); + + /* Configure rx ir mode */ + tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + + if (ENABLE == irCfg->rxIrEnable) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_URX_IR_EN); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_URX_IR_EN); + } + + if (ENABLE == irCfg->rxIrInverse) { + tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_URX_IR_INV); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_URX_IR_INV); + } + + BL_WR_REG(UARTx, UART_URX_CONFIG, tmpVal); + + /* Configure tx ir pulse start and stop position */ + BL_WR_REG(UARTx, UART_UTX_IR_POSITION, irCfg->txIrPulseStop << 0x10 | irCfg->txIrPulseStart); + + /* Configure rx ir pulse start position */ + BL_WR_REG(UARTx, UART_URX_IR_POSITION, irCfg->rxIrPulseStart); + + return SUCCESS; +} - /* Configure tx ir mode */ +/****************************************************************************/ /** + * @brief Enable UART + * + * @param uartId: UART ID type + * @param direct: UART direction type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_Enable(UART_ID_Type uartId, UART_Direction_Type direct) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_DIRECTION_TYPE(direct)); + + if (direct == UART_TX || direct == UART_TXRX) { + /* Enable UART tx unit */ tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); + BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_EN)); + } - if (ENABLE == irCfg->txIrEnable) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_UTX_IR_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_IR_EN); - } - - if (ENABLE == irCfg->txIrInverse) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_UTX_IR_INV); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_IR_INV); - } - - BL_WR_REG(UARTx, UART_UTX_CONFIG, tmpVal); - - /* Configure rx ir mode */ + if (direct == UART_RX || direct == UART_TXRX) { + /* Enable UART rx unit */ tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_URX_EN)); + } - if (ENABLE == irCfg->rxIrEnable) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_URX_IR_EN); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_URX_IR_EN); - } - - if (ENABLE == irCfg->rxIrInverse) { - tmpVal = BL_SET_REG_BIT(tmpVal, UART_CR_URX_IR_INV); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, UART_CR_URX_IR_INV); - } - - BL_WR_REG(UARTx, UART_URX_CONFIG, tmpVal); - - /* Configure tx ir pulse start and stop position */ - BL_WR_REG(UARTx, UART_UTX_IR_POSITION, irCfg->txIrPulseStop << 0x10 | irCfg->txIrPulseStart); - - /* Configure rx ir pulse start position */ - BL_WR_REG(UARTx, UART_URX_IR_POSITION, irCfg->rxIrPulseStart); - - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Enable UART - * - * @param uartId: UART ID type - * @param direct: UART direction type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_Enable(UART_ID_Type uartId, UART_Direction_Type direct) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_DIRECTION_TYPE(direct)); - - if (direct == UART_TX || direct == UART_TXRX) { - /* Enable UART tx unit */ - tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); - BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_EN)); - } + * @brief Disable UART + * + * @param uartId: UART ID type + * @param direct: UART direction type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_Disable(UART_ID_Type uartId, UART_Direction_Type direct) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_DIRECTION_TYPE(direct)); + + if (direct == UART_TX || direct == UART_TXRX) { + /* Disable UART tx unit */ + tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); + BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_EN)); + } - if (direct == UART_RX || direct == UART_TXRX) { - /* Enable UART rx unit */ - tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); - BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_URX_EN)); - } + if (direct == UART_RX || direct == UART_TXRX) { + /* Disable UART rx unit */ + tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + BL_WR_REG(UARTx, UART_URX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_EN)); + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Disable UART - * - * @param uartId: UART ID type - * @param direct: UART direction type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_Disable(UART_ID_Type uartId, UART_Direction_Type direct) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_DIRECTION_TYPE(direct)); - - if (direct == UART_TX || direct == UART_TXRX) { - /* Disable UART tx unit */ - tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); - BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_EN)); - } - - if (direct == UART_RX || direct == UART_TXRX) { - /* Disable UART rx unit */ - tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); - BL_WR_REG(UARTx, UART_URX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_EN)); - } - - return SUCCESS; + * @brief UART set length of tx data transfer,tx end interrupt will assert when this length is + * reached + * + * @param uartId: UART ID type + * @param length: Length of data (unit:character/byte) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetTxDataLength(UART_ID_Type uartId, uint16_t length) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Set length */ + tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); + BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, UART_CR_UTX_LEN, length - 1)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set length of tx data transfer,tx end interrupt will assert when this length is - * reached - * - * @param uartId: UART ID type - * @param length: Length of data (unit:character/byte) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetTxDataLength(UART_ID_Type uartId, uint16_t length) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Set length */ - tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); - BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, UART_CR_UTX_LEN, length - 1)); - - return SUCCESS; + * @brief UART set length of rx data transfer,rx end interrupt will assert when this length is + * reached + * + * @param uartId: UART ID type + * @param length: Length of data (unit:character/byte) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetRxDataLength(UART_ID_Type uartId, uint16_t length) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Set length */ + tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_LEN, length - 1)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set length of rx data transfer,rx end interrupt will assert when this length is - * reached - * - * @param uartId: UART ID type - * @param length: Length of data (unit:character/byte) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetRxDataLength(UART_ID_Type uartId, uint16_t length) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Set length */ - tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); - BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_LEN, length - 1)); - - return SUCCESS; + * @brief UART set rx time-out value for triggering RTO interrupt + * + * @param uartId: UART ID type + * @param time: Time-out value (unit:bit time) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetRxTimeoutValue(UART_ID_Type uartId, uint8_t time) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Set time-out value */ + tmpVal = BL_RD_REG(UARTx, UART_URX_RTO_TIMER); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_RTO_VALUE, time - 1); + BL_WR_REG(UARTx, UART_URX_RTO_TIMER, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set rx time-out value for triggering RTO interrupt - * - * @param uartId: UART ID type - * @param time: Time-out value (unit:bit time) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetRxTimeoutValue(UART_ID_Type uartId, uint8_t time) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Set time-out value */ - tmpVal = BL_RD_REG(UARTx, UART_URX_RTO_TIMER); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_RTO_VALUE, time - 1); - BL_WR_REG(UARTx, UART_URX_RTO_TIMER, tmpVal); - - return SUCCESS; + * @brief UART set de-glitch function cycle count value + * + * @param uartId: UART ID type + * @param deglitchCnt: De-glitch function cycle count + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetDeglitchCount(UART_ID_Type uartId, uint8_t deglitchCnt) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Set count value */ + tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_DEG_CNT, deglitchCnt); + BL_WR_REG(UARTx, UART_URX_CONFIG, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set de-glitch function cycle count value - * - * @param uartId: UART ID type - * @param deglitchCnt: De-glitch function cycle count - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetDeglitchCount(UART_ID_Type uartId, uint8_t deglitchCnt) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Set count value */ - tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, UART_CR_URX_DEG_CNT, deglitchCnt); - BL_WR_REG(UARTx, UART_URX_CONFIG, tmpVal); - - return SUCCESS; + * @brief UART set tx and rx baudrate according to auto baudrate detection value + * + * @param uartId: UART ID type + * @param autoBaudDet: Choose detection value using codeword 0x55 or start bit + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_ApplyAbrResult(UART_ID_Type uartId, UART_AutoBaudDetection_Type autoBaudDet) { + uint32_t UARTx = uartAddr[uartId]; + uint16_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Get detection value */ + tmpVal = UART_GetAutoBaudCount(uartId, autoBaudDet); + + /* Set tx baudrate */ + BL_WR_REG(UARTx, UART_BIT_PRD, tmpVal << 0x10 | tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set tx and rx baudrate according to auto baudrate detection value - * - * @param uartId: UART ID type - * @param autoBaudDet: Choose detection value using codeword 0x55 or start bit - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_ApplyAbrResult(UART_ID_Type uartId, UART_AutoBaudDetection_Type autoBaudDet) -{ - uint32_t UARTx = uartAddr[uartId]; - uint16_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Get detection value */ - tmpVal = UART_GetAutoBaudCount(uartId, autoBaudDet); - - /* Set tx baudrate */ - BL_WR_REG(UARTx, UART_BIT_PRD, tmpVal << 0x10 | tmpVal); - - return SUCCESS; + * @brief UART set rx rts output software control value + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetRtsValue(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Rts set 1*/ + tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); + BL_WR_REG(UARTx, UART_SW_MODE, BL_SET_REG_BIT(tmpVal, UART_CR_URX_RTS_SW_VAL)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set rx rts output software control value - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetRtsValue(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Rts set 1*/ - tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); - BL_WR_REG(UARTx, UART_SW_MODE, BL_SET_REG_BIT(tmpVal, UART_CR_URX_RTS_SW_VAL)); - - return SUCCESS; + * @brief UART clear rx rts output software control value + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_ClrRtsValue(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Rts clear 0 */ + tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); + BL_WR_REG(UARTx, UART_SW_MODE, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_RTS_SW_VAL)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART clear rx rts output software control value - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_ClrRtsValue(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Rts clear 0 */ - tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); - BL_WR_REG(UARTx, UART_SW_MODE, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_RTS_SW_VAL)); - - return SUCCESS; + * @brief UART set tx output software control value + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SetTxValue(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Tx set 1*/ + tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); + BL_WR_REG(UARTx, UART_SW_MODE, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_TXD_SW_VAL)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART set tx output software control value - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SetTxValue(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Tx set 1*/ - tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); - BL_WR_REG(UARTx, UART_SW_MODE, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_TXD_SW_VAL)); - - return SUCCESS; + * @brief UART clear tx output software control value + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_ClrTxValue(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + uint32_t tmpVal; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Rts clear 0 */ + tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); + BL_WR_REG(UARTx, UART_SW_MODE, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_TXD_SW_VAL)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART clear tx output software control value - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_ClrTxValue(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - uint32_t tmpVal; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Rts clear 0 */ - tmpVal = BL_RD_REG(UARTx, UART_SW_MODE); - BL_WR_REG(UARTx, UART_SW_MODE, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_TXD_SW_VAL)); - - return SUCCESS; + * @brief UART configure tx free run mode function + * + * @param uartId: UART ID type + * @param txFreeRun: Enable or disable tx free run mode + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_TxFreeRun(UART_ID_Type uartId, BL_Fun_Type txFreeRun) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Enable or disable tx free run mode */ + tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); + + if (ENABLE == txFreeRun) { + BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_FRM_EN)); + } else { + BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_FRM_EN)); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART configure tx free run mode function - * - * @param uartId: UART ID type - * @param txFreeRun: Enable or disable tx free run mode - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_TxFreeRun(UART_ID_Type uartId, BL_Fun_Type txFreeRun) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Enable or disable tx free run mode */ - tmpVal = BL_RD_REG(UARTx, UART_UTX_CONFIG); - - if (ENABLE == txFreeRun) { - BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_UTX_FRM_EN)); - } else { - BL_WR_REG(UARTx, UART_UTX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_UTX_FRM_EN)); - } - - return SUCCESS; + * @brief UART configure auto baud rate detection function + * + * @param uartId: UART ID type + * @param autoBaud: Enable or disable auto function + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_AutoBaudDetection(UART_ID_Type uartId, BL_Fun_Type autoBaud) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Enable or disable auto baud rate detection function */ + tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); + + if (ENABLE == autoBaud) { + BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_URX_ABR_EN)); + } else { + BL_WR_REG(UARTx, UART_URX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_ABR_EN)); + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART configure auto baud rate detection function - * - * @param uartId: UART ID type - * @param autoBaud: Enable or disable auto function - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_AutoBaudDetection(UART_ID_Type uartId, BL_Fun_Type autoBaud) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Enable or disable auto baud rate detection function */ - tmpVal = BL_RD_REG(UARTx, UART_URX_CONFIG); - - if (ENABLE == autoBaud) { - BL_WR_REG(UARTx, UART_URX_CONFIG, BL_SET_REG_BIT(tmpVal, UART_CR_URX_ABR_EN)); - } else { - BL_WR_REG(UARTx, UART_URX_CONFIG, BL_CLR_REG_BIT(tmpVal, UART_CR_URX_ABR_EN)); - } - - return SUCCESS; + * @brief UART tx fifo clear + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_TxFifoClear(UART_ID_Type uartId) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Clear tx fifo */ + tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); + BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, UART_TX_FIFO_CLR)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART tx fifo clear - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_TxFifoClear(UART_ID_Type uartId) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Clear tx fifo */ - tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); - BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, UART_TX_FIFO_CLR)); - - return SUCCESS; + * @brief UART rx fifo clear + * + * @param uartId: UART ID type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_RxFifoClear(UART_ID_Type uartId) { + uint32_t tmpVal = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Clear rx fifo */ + tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); + BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, UART_RX_FIFO_CLR)); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART rx fifo clear - * - * @param uartId: UART ID type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_RxFifoClear(UART_ID_Type uartId) -{ - uint32_t tmpVal = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Clear rx fifo */ - tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); - BL_WR_REG(UARTx, UART_FIFO_CONFIG_0, BL_SET_REG_BIT(tmpVal, UART_RX_FIFO_CLR)); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief UART mask or unmask certain or all interrupt - * - * @param uartId: UART ID type - * @param intType: UART interrupt type - * @param intMask: UART interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_IntMask(UART_ID_Type uartId, UART_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_INT_TYPE(intType)); - CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); - - tmpVal = BL_RD_REG(UARTx, UART_INT_MASK); - - /* Mask or unmask certain or all interrupt */ - if (UART_INT_ALL == intType) { - if (MASK == intMask) { - tmpVal |= 0x1ff; - } else { - tmpVal &= 0; - } + * @brief UART mask or unmask certain or all interrupt + * + * @param uartId: UART ID type + * @param intType: UART interrupt type + * @param intMask: UART interrupt mask value( MASK:disbale interrupt,UNMASK:enable interrupt ) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_IntMask(UART_ID_Type uartId, UART_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_INT_TYPE(intType)); + CHECK_PARAM(IS_BL_MASK_TYPE(intMask)); + + tmpVal = BL_RD_REG(UARTx, UART_INT_MASK); + + /* Mask or unmask certain or all interrupt */ + if (UART_INT_ALL == intType) { + if (MASK == intMask) { + tmpVal |= 0x1ff; } else { - if (MASK == intMask) { - tmpVal |= 1 << intType; - } else { - tmpVal &= ~(1 << intType); - } + tmpVal &= 0; } - - /* Write back */ - BL_WR_REG(UARTx, UART_INT_MASK, tmpVal); - - return SUCCESS; -} - -/****************************************************************************/ /** - * @brief UART clear certain or all interrupt - * - * @param uartId: UART ID type - * @param intType: UART interrupt type - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_IntClear(UART_ID_Type uartId, UART_INT_Type intType) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_INT_TYPE(intType)); - - tmpVal = BL_RD_REG(UARTx, UART_INT_CLEAR); - - /* Clear certain or all interrupt */ - if (UART_INT_ALL == intType) { - tmpVal |= 0x1ff; + } else { + if (MASK == intMask) { + tmpVal |= 1 << intType; } else { - tmpVal |= 1 << intType; + tmpVal &= ~(1 << intType); } + } - /* Write back */ - BL_WR_REG(UARTx, UART_INT_CLEAR, tmpVal); + /* Write back */ + BL_WR_REG(UARTx, UART_INT_MASK, tmpVal); - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief Install uart interrupt callback function - * - * @param uartId: UART ID type - * @param intType: UART interrupt type - * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_Int_Callback_Install(UART_ID_Type uartId, UART_INT_Type intType, intCallback_Type *cbFun) -{ - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_INT_TYPE(intType)); - - uartIntCbfArra[uartId][intType] = cbFun; - - return SUCCESS; + * @brief UART clear certain or all interrupt + * + * @param uartId: UART ID type + * @param intType: UART interrupt type + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_IntClear(UART_ID_Type uartId, UART_INT_Type intType) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_INT_TYPE(intType)); + + tmpVal = BL_RD_REG(UARTx, UART_INT_CLEAR); + + /* Clear certain or all interrupt */ + if (UART_INT_ALL == intType) { + tmpVal |= 0x1ff; + } else { + tmpVal |= 1 << intType; + } + + /* Write back */ + BL_WR_REG(UARTx, UART_INT_CLEAR, tmpVal); + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART send data to tx fifo - * - * @param uartId: UART ID type - * @param data: The data to be send - * @param len: The length of the send buffer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SendData(UART_ID_Type uartId, uint8_t *data, uint32_t len) -{ - uint32_t txLen = 0; - uint32_t UARTx = uartAddr[uartId]; - uint32_t timeoutCnt = UART_TX_TIMEOUT_COUNT; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Send data */ - while (txLen < len) { - if (UART_GetTxFifoCount(uartId) > 0) { - BL_WR_BYTE(UARTx + UART_FIFO_WDATA_OFFSET, data[txLen++]); - timeoutCnt = UART_TX_TIMEOUT_COUNT; - } else { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } - - return SUCCESS; + * @brief Install uart interrupt callback function + * + * @param uartId: UART ID type + * @param intType: UART interrupt type + * @param cbFun: Pointer to interrupt callback function. The type should be void (*fn)(void) + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_Int_Callback_Install(UART_ID_Type uartId, UART_INT_Type intType, intCallback_Type *cbFun) { + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_INT_TYPE(intType)); + + uartIntCbfArra[uartId][intType] = cbFun; + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART send data to tx fifo in block mode - * - * @param uartId: UART ID type - * @param data: The data to be send - * @param len: The length of the send buffer - * - * @return SUCCESS - * -*******************************************************************************/ -BL_Err_Type UART_SendDataBlock(UART_ID_Type uartId, uint8_t *data, uint32_t len) -{ - uint32_t txLen = 0; - uint32_t UARTx = uartAddr[uartId]; - uint32_t timeoutCnt = UART_TX_TIMEOUT_COUNT; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Send data */ - while (txLen < len) { - if (UART_GetTxFifoCount(uartId) > 0) { - BL_WR_BYTE(UARTx + UART_FIFO_WDATA_OFFSET, data[txLen++]); - timeoutCnt = UART_TX_TIMEOUT_COUNT; - } else { - timeoutCnt--; - - if (timeoutCnt == 0) { - return TIMEOUT; - } - } - } + * @brief UART send data to tx fifo + * + * @param uartId: UART ID type + * @param data: The data to be send + * @param len: The length of the send buffer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SendData(UART_ID_Type uartId, uint8_t *data, uint32_t len) { + uint32_t txLen = 0; + uint32_t UARTx = uartAddr[uartId]; + uint32_t timeoutCnt = UART_TX_TIMEOUT_COUNT; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Send data */ + while (txLen < len) { + if (UART_GetTxFifoCount(uartId) > 0) { + BL_WR_BYTE(UARTx + UART_FIFO_WDATA_OFFSET, data[txLen++]); + timeoutCnt = UART_TX_TIMEOUT_COUNT; + } else { + timeoutCnt--; - while (UART_GetTxBusBusyStatus(uartId) == SET) { + if (timeoutCnt == 0) { + return TIMEOUT; + } } + } - return SUCCESS; + return SUCCESS; } /****************************************************************************/ /** - * @brief UART receive data from rx fifo - * - * @param uartId: UART ID type - * @param data: The receive data buffer - * @param maxLen: The max length of the buffer - * - * @return The length of the received buffer - * -*******************************************************************************/ -uint32_t UART_ReceiveData(UART_ID_Type uartId, uint8_t *data, uint32_t maxLen) -{ - uint32_t rxLen = 0; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Receive data */ - while (rxLen < maxLen && UART_GetRxFifoCount(uartId) > 0) { - data[rxLen++] = BL_RD_BYTE(UARTx + UART_FIFO_RDATA_OFFSET); + * @brief UART send data to tx fifo in block mode + * + * @param uartId: UART ID type + * @param data: The data to be send + * @param len: The length of the send buffer + * + * @return SUCCESS + * + *******************************************************************************/ +BL_Err_Type UART_SendDataBlock(UART_ID_Type uartId, uint8_t *data, uint32_t len) { + uint32_t txLen = 0; + uint32_t UARTx = uartAddr[uartId]; + uint32_t timeoutCnt = UART_TX_TIMEOUT_COUNT; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Send data */ + while (txLen < len) { + if (UART_GetTxFifoCount(uartId) > 0) { + BL_WR_BYTE(UARTx + UART_FIFO_WDATA_OFFSET, data[txLen++]); + timeoutCnt = UART_TX_TIMEOUT_COUNT; + } else { + timeoutCnt--; + + if (timeoutCnt == 0) { + return TIMEOUT; + } } + } - return rxLen; + while (UART_GetTxBusBusyStatus(uartId) == SET) { + } + + return SUCCESS; } /****************************************************************************/ /** - * @brief UART get auto baud count value - * - * @param uartId: UART ID type - * @param autoBaudDet: Detection using codeword 0x55 or start bit - * - * @return Bit period of auto baudrate detection - * -*******************************************************************************/ -uint16_t UART_GetAutoBaudCount(UART_ID_Type uartId, UART_AutoBaudDetection_Type autoBaudDet) -{ - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_AUTOBAUDDETECTION_TYPE(autoBaudDet)); - - /* Select 0x55 or start bit detection value */ - if (UART_AUTOBAUD_0X55 == autoBaudDet) { - return BL_RD_REG(UARTx, UART_STS_URX_ABR_PRD) >> 0x10 & 0xffff; - } else { - return BL_RD_REG(UARTx, UART_STS_URX_ABR_PRD) & 0xffff; - } + * @brief UART receive data from rx fifo + * + * @param uartId: UART ID type + * @param data: The receive data buffer + * @param maxLen: The max length of the buffer + * + * @return The length of the received buffer + * + *******************************************************************************/ +uint32_t UART_ReceiveData(UART_ID_Type uartId, uint8_t *data, uint32_t maxLen) { + uint32_t rxLen = 0; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Receive data */ + while (rxLen < maxLen && UART_GetRxFifoCount(uartId) > 0) { + data[rxLen++] = BL_RD_BYTE(UARTx + UART_FIFO_RDATA_OFFSET); + } + + return rxLen; } /****************************************************************************/ /** - * @brief UART get tx fifo unoccupied count value - * - * @param uartId: UART ID type - * - * @return Tx fifo unoccupied count value - * -*******************************************************************************/ -uint8_t UART_GetTxFifoCount(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - return BL_GET_REG_BITS_VAL(BL_RD_REG(UARTx, UART_FIFO_CONFIG_1), UART_TX_FIFO_CNT); + * @brief UART get auto baud count value + * + * @param uartId: UART ID type + * @param autoBaudDet: Detection using codeword 0x55 or start bit + * + * @return Bit period of auto baudrate detection + * + *******************************************************************************/ +uint16_t UART_GetAutoBaudCount(UART_ID_Type uartId, UART_AutoBaudDetection_Type autoBaudDet) { + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_AUTOBAUDDETECTION_TYPE(autoBaudDet)); + + /* Select 0x55 or start bit detection value */ + if (UART_AUTOBAUD_0X55 == autoBaudDet) { + return BL_RD_REG(UARTx, UART_STS_URX_ABR_PRD) >> 0x10 & 0xffff; + } else { + return BL_RD_REG(UARTx, UART_STS_URX_ABR_PRD) & 0xffff; + } } /****************************************************************************/ /** - * @brief UART get rx fifo occupied count value - * - * @param uartId: UART ID type - * - * @return Rx fifo occupied count value - * -*******************************************************************************/ -uint8_t UART_GetRxFifoCount(UART_ID_Type uartId) -{ - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameter */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - return BL_GET_REG_BITS_VAL(BL_RD_REG(UARTx, UART_FIFO_CONFIG_1), UART_RX_FIFO_CNT); + * @brief UART get tx fifo unoccupied count value + * + * @param uartId: UART ID type + * + * @return Tx fifo unoccupied count value + * + *******************************************************************************/ +uint8_t UART_GetTxFifoCount(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + return BL_GET_REG_BITS_VAL(BL_RD_REG(UARTx, UART_FIFO_CONFIG_1), UART_TX_FIFO_CNT); } /****************************************************************************/ /** - * @brief Get uart interrupt status - * - * @param uartId: UART ID type - * @param intType: UART interrupt type - * - * @return Status of interrupt - * -*******************************************************************************/ -BL_Sts_Type UART_GetIntStatus(UART_ID_Type uartId, UART_INT_Type intType) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_INT_TYPE(intType)); - - /* Get certain or all interrupt status */ - tmpVal = BL_RD_REG(UARTx, UART_INT_STS); - - if (UART_INT_ALL == intType) { - if ((tmpVal & 0x1ff) != 0) { - return SET; - } else { - return RESET; - } - } else { - if ((tmpVal & (1U << intType)) != 0) { - return SET; - } else { - return RESET; - } - } + * @brief UART get rx fifo occupied count value + * + * @param uartId: UART ID type + * + * @return Rx fifo occupied count value + * + *******************************************************************************/ +uint8_t UART_GetRxFifoCount(UART_ID_Type uartId) { + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameter */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + return BL_GET_REG_BITS_VAL(BL_RD_REG(UARTx, UART_FIFO_CONFIG_1), UART_RX_FIFO_CNT); } /****************************************************************************/ /** - * @brief Get indicator of uart tx bus busy - * - * @param uartId: UART ID type - * - * @return Status of tx bus - * -*******************************************************************************/ -BL_Sts_Type UART_GetTxBusBusyStatus(UART_ID_Type uartId) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Get tx bus busy status */ - tmpVal = BL_RD_REG(UARTx, UART_STATUS); - - if (BL_IS_REG_BIT_SET(tmpVal, UART_STS_UTX_BUS_BUSY)) { - return SET; + * @brief Get uart interrupt status + * + * @param uartId: UART ID type + * @param intType: UART interrupt type + * + * @return Status of interrupt + * + *******************************************************************************/ +BL_Sts_Type UART_GetIntStatus(UART_ID_Type uartId, UART_INT_Type intType) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_INT_TYPE(intType)); + + /* Get certain or all interrupt status */ + tmpVal = BL_RD_REG(UARTx, UART_INT_STS); + + if (UART_INT_ALL == intType) { + if ((tmpVal & 0x1ff) != 0) { + return SET; } else { - return RESET; + return RESET; } -} - -/****************************************************************************/ /** - * @brief Get indicator of uart rx bus busy - * - * @param uartId: UART ID type - * - * @return Status of rx bus - * -*******************************************************************************/ -BL_Sts_Type UART_GetRxBusBusyStatus(UART_ID_Type uartId) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - - /* Get rx bus busy status */ - tmpVal = BL_RD_REG(UARTx, UART_STATUS); - - if (BL_IS_REG_BIT_SET(tmpVal, UART_STS_URX_BUS_BUSY)) { - return SET; + } else { + if ((tmpVal & (1U << intType)) != 0) { + return SET; } else { - return RESET; + return RESET; } + } } /****************************************************************************/ /** - * @brief Get tx/rx fifo overflow or underflow status - * - * @param uartId: UART ID type - * @param overflow: Select tx/rx overflow or underflow - * - * @return Status of tx/rx fifo - * -*******************************************************************************/ -BL_Sts_Type UART_GetOverflowStatus(UART_ID_Type uartId, UART_Overflow_Type overflow) -{ - uint32_t tmpVal; - uint32_t UARTx = uartAddr[uartId]; - - /* Check the parameters */ - CHECK_PARAM(IS_UART_ID_TYPE(uartId)); - CHECK_PARAM(IS_UART_OVERFLOW_TYPE(overflow)); + * @brief Get indicator of uart tx bus busy + * + * @param uartId: UART ID type + * + * @return Status of tx bus + * + *******************************************************************************/ +BL_Sts_Type UART_GetTxBusBusyStatus(UART_ID_Type uartId) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Get tx bus busy status */ + tmpVal = BL_RD_REG(UARTx, UART_STATUS); + + if (BL_IS_REG_BIT_SET(tmpVal, UART_STS_UTX_BUS_BUSY)) { + return SET; + } else { + return RESET; + } +} - /* Get tx/rx fifo overflow or underflow status */ - tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); +/****************************************************************************/ /** + * @brief Get indicator of uart rx bus busy + * + * @param uartId: UART ID type + * + * @return Status of rx bus + * + *******************************************************************************/ +BL_Sts_Type UART_GetRxBusBusyStatus(UART_ID_Type uartId) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + + /* Get rx bus busy status */ + tmpVal = BL_RD_REG(UARTx, UART_STATUS); + + if (BL_IS_REG_BIT_SET(tmpVal, UART_STS_URX_BUS_BUSY)) { + return SET; + } else { + return RESET; + } +} - if ((tmpVal & (1U << (overflow + 4))) != 0) { - return SET; - } else { - return RESET; - } +/****************************************************************************/ /** + * @brief Get tx/rx fifo overflow or underflow status + * + * @param uartId: UART ID type + * @param overflow: Select tx/rx overflow or underflow + * + * @return Status of tx/rx fifo + * + *******************************************************************************/ +BL_Sts_Type UART_GetOverflowStatus(UART_ID_Type uartId, UART_Overflow_Type overflow) { + uint32_t tmpVal; + uint32_t UARTx = uartAddr[uartId]; + + /* Check the parameters */ + CHECK_PARAM(IS_UART_ID_TYPE(uartId)); + CHECK_PARAM(IS_UART_OVERFLOW_TYPE(overflow)); + + /* Get tx/rx fifo overflow or underflow status */ + tmpVal = BL_RD_REG(UARTx, UART_FIFO_CONFIG_0); + + if ((tmpVal & (1U << (overflow + 4))) != 0) { + return SET; + } else { + return RESET; + } } /****************************************************************************/ /** - * @brief UART0 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief UART0 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void UART0_IRQHandler(void) -{ - UART_IntHandler(UART0_ID); -} +void UART0_IRQHandler(void) { UART_IntHandler(UART0_ID); } #endif /****************************************************************************/ /** - * @brief UART1 interrupt handler - * - * @param None - * - * @return None - * -*******************************************************************************/ + * @brief UART1 interrupt handler + * + * @param None + * + * @return None + * + *******************************************************************************/ #ifndef BFLB_USE_HAL_DRIVER -void UART1_IRQHandler(void) -{ - UART_IntHandler(UART1_ID); -} +void UART1_IRQHandler(void) { UART_IntHandler(UART1_ID); } #endif /*@} end of group UART_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_usb.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_usb.c index 647662655..3b3b1f00e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_usb.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_usb.c @@ -1,42 +1,42 @@ /** - ****************************************************************************** - * @file bl70x_usb.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2019 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl70x_usb.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2019 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ #include "bl702_usb.h" -#include "bl702_glb.h" #include "bl702_common.h" +#include "bl702_glb.h" /** @addtogroup BL70X_Peripheral_Driver * @{ @@ -86,2402 +86,2347 @@ * @{ */ -BL_Err_Type USB_Enable(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Enable(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EN); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EN); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Disable(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Disable(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EN); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EN); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_Config(BL_Fun_Type enable, USB_Config_Type *usbCfg) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_Config(BL_Fun_Type enable, USB_Config_Type *usbCfg) { + uint32_t tmpVal = 0; - /* disable USB first */ - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EN); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + /* disable USB first */ + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EN); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - /* USB config */ - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + /* USB config */ + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - if (usbCfg->SoftwareCtrl == ENABLE) { - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR, usbCfg->DeviceAddress); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, usbCfg->EnumMaxPacketSize); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_NACK_IN, usbCfg->EnumInEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT, usbCfg->EnumOutEn); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_ROM_DCT_EN, usbCfg->RomBaseDescriptorUsed); - } else { - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_CTRL); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_ROM_DCT_EN, usbCfg->RomBaseDescriptorUsed); - } + if (usbCfg->SoftwareCtrl == ENABLE) { + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR, usbCfg->DeviceAddress); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, usbCfg->EnumMaxPacketSize); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_NACK_IN, usbCfg->EnumInEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT, usbCfg->EnumOutEn); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_ROM_DCT_EN, usbCfg->RomBaseDescriptorUsed); + } else { + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_CTRL); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_ROM_DCT_EN, usbCfg->RomBaseDescriptorUsed); + } - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - /* enable/disable USB */ - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + /* enable/disable USB */ + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - if (enable) { - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EN); - } + if (enable) { + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EN); + } - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_Device_Addr(uint8_t addr) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_Device_Addr(uint8_t addr) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR, addr); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR, addr); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -uint8_t USB_Get_Device_Addr(void) -{ - uint32_t tmpVal = 0; +uint8_t USB_Get_Device_Addr(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - return BL_GET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR); + return BL_GET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_ADDR); } -BL_Err_Type USB_Set_EPx_Xfer_Size(USB_EP_ID epId, uint8_t size) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_Xfer_Size(USB_EP_ID epId, uint8_t size) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, size); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, size); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_IN_Busy(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_IN_Busy(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_IN_Stall(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_IN_Stall(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_OUT_Busy(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_OUT_Busy(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_OUT_Stall(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_OUT_Stall(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_Rdy(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; - - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_RDY); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } +BL_Err_Type USB_Set_EPx_Rdy(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_RDY); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Sts_Type USB_Is_EPx_RDY_Free(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Is_EPx_RDY_Free(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_USB_EP0_SW_RDY); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP1_RDY); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP2_RDY); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP3_RDY); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP4_RDY); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP5_RDY); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP6_RDY); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP7_RDY); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_USB_EP0_SW_RDY); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP1_RDY); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP2_RDY); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP3_RDY); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP4_RDY); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP5_RDY); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP6_RDY); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP7_RDY); + break; + + default: + break; } + } - return tmpVal ? RESET : SET; + return tmpVal ? RESET : SET; } -BL_Err_Type USB_Set_EPx_STALL(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_STALL(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_STALL); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Clr_EPx_STALL(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Clr_EPx_STALL(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - return SUCCESS; - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + return SUCCESS; + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_Busy(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_Busy(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_IN); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_USB_EP0_SW_NACK_OUT); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP1_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP1_STALL); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP2_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP2_STALL); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP3_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP3_STALL); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP4_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP4_STALL); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP5_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP5_STALL); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP6_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP6_STALL); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_EP7_NACK); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_EP7_STALL); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_Status(USB_EP_ID epId, USB_EP_STATUS_Type sts) -{ - switch (sts) { - case USB_EP_STATUS_ACK: - USB_Set_EPx_Rdy(epId); - break; +BL_Err_Type USB_Set_EPx_Status(USB_EP_ID epId, USB_EP_STATUS_Type sts) { + switch (sts) { + case USB_EP_STATUS_ACK: + USB_Set_EPx_Rdy(epId); + break; - case USB_EP_STATUS_NACK: - USB_Set_EPx_Busy(epId); - break; + case USB_EP_STATUS_NACK: + USB_Set_EPx_Busy(epId); + break; - case USB_EP_STATUS_STALL: - USB_Set_EPx_STALL(epId); - break; + case USB_EP_STATUS_STALL: + USB_Set_EPx_STALL(epId); + break; - case USB_EP_STATUS_NSTALL: - USB_Clr_EPx_STALL(epId); - break; + case USB_EP_STATUS_NSTALL: + USB_Clr_EPx_STALL(epId); + break; - default: - break; - } + default: + break; + } - return SUCCESS; + return SUCCESS; } -USB_EP_STATUS_Type USB_Get_EPx_Status(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +USB_EP_STATUS_Type USB_Get_EPx_Status(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + if (epId == EP_ID0) { + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - switch ((tmpVal >> 24) & 0x7) { - case 0: - return USB_EP_STATUS_ACK; + switch ((tmpVal >> 24) & 0x7) { + case 0: + return USB_EP_STATUS_ACK; - case 1: - return USB_EP_STATUS_STALL; + case 1: + return USB_EP_STATUS_STALL; - case 2: - case 4: - case 6: - return USB_EP_STATUS_NACK; + case 2: + case 4: + case 6: + return USB_EP_STATUS_NACK; - default: - break; - } - } else { - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - break; - - default: - tmpVal = 0; - break; - } - - switch ((tmpVal >> 14) & 0x3) { - case 0: - return USB_EP_STATUS_ACK; - - case 1: - return USB_EP_STATUS_STALL; - - case 2: - return USB_EP_STATUS_NACK; - - case 3: - default: - break; - } + default: + break; } + } else { + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + break; - return USB_EP_STATUS_NSTALL; -} + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + break; -BL_Err_Type USB_IntEn(USB_INT_Type intType, uint8_t enable) -{ - uint32_t tmpVal = 0; + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + break; - if (USB_INT_ALL == intType) { - if (enable) { - BL_WR_REG(USB_BASE, USB_INT_EN, USB_INT_TYPE_ALL); - } else { - BL_WR_REG(USB_BASE, USB_INT_EN, ~USB_INT_TYPE_ALL); - } + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + break; - return SUCCESS; - } + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + break; - tmpVal = BL_RD_REG(USB_BASE, USB_INT_EN); + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + break; - if (enable) { - tmpVal |= (1 << intType); - } else { - tmpVal &= ~(1 << intType); - } + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + break; - BL_WR_REG(USB_BASE, USB_INT_EN, tmpVal); + default: + tmpVal = 0; + break; + } - return SUCCESS; -} + switch ((tmpVal >> 14) & 0x3) { + case 0: + return USB_EP_STATUS_ACK; -BL_Err_Type USB_IntMask(USB_INT_Type intType, BL_Mask_Type intMask) -{ - uint32_t tmpVal = 0; + case 1: + return USB_EP_STATUS_STALL; - if (USB_INT_ALL == intType) { - if (intMask != UNMASK) { - BL_WR_REG(USB_BASE, USB_INT_MASK, USB_INT_TYPE_ALL); - } else { - BL_WR_REG(USB_BASE, USB_INT_MASK, ~USB_INT_TYPE_ALL); - } + case 2: + return USB_EP_STATUS_NACK; - return SUCCESS; + case 3: + default: + break; } + } - tmpVal = BL_RD_REG(USB_BASE, USB_INT_MASK); + return USB_EP_STATUS_NSTALL; +} - if (intMask != UNMASK) { - tmpVal |= (1 << intType); +BL_Err_Type USB_IntEn(USB_INT_Type intType, uint8_t enable) { + uint32_t tmpVal = 0; + + if (USB_INT_ALL == intType) { + if (enable) { + BL_WR_REG(USB_BASE, USB_INT_EN, USB_INT_TYPE_ALL); } else { - tmpVal &= ~(1 << intType); + BL_WR_REG(USB_BASE, USB_INT_EN, ~USB_INT_TYPE_ALL); } - BL_WR_REG(USB_BASE, USB_INT_MASK, tmpVal); - return SUCCESS; -} + } -BL_Sts_Type USB_Get_IntStatus(USB_INT_Type intType) -{ - if (USB_INT_ALL == intType) { - return BL_RD_REG(USB_BASE, USB_INT_STS) ? SET : RESET; - } + tmpVal = BL_RD_REG(USB_BASE, USB_INT_EN); - return ((BL_RD_REG(USB_BASE, USB_INT_STS) & (1 << intType))) ? SET : RESET; -} + if (enable) { + tmpVal |= (1 << intType); + } else { + tmpVal &= ~(1 << intType); + } + + BL_WR_REG(USB_BASE, USB_INT_EN, tmpVal); -BL_Err_Type USB_Clr_IntStatus(USB_INT_Type intType) -{ - uint32_t tmpVal = 0; + return SUCCESS; +} - if (USB_INT_ALL == intType) { - BL_WR_REG(USB_BASE, USB_INT_CLEAR, USB_INT_TYPE_ALL); +BL_Err_Type USB_IntMask(USB_INT_Type intType, BL_Mask_Type intMask) { + uint32_t tmpVal = 0; - return SUCCESS; + if (USB_INT_ALL == intType) { + if (intMask != UNMASK) { + BL_WR_REG(USB_BASE, USB_INT_MASK, USB_INT_TYPE_ALL); + } else { + BL_WR_REG(USB_BASE, USB_INT_MASK, ~USB_INT_TYPE_ALL); } - tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); + return SUCCESS; + } + + tmpVal = BL_RD_REG(USB_BASE, USB_INT_MASK); + + if (intMask != UNMASK) { tmpVal |= (1 << intType); - BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); + } else { + tmpVal &= ~(1 << intType); + } - return SUCCESS; + BL_WR_REG(USB_BASE, USB_INT_MASK, tmpVal); + + return SUCCESS; } -BL_Err_Type USB_Clr_EPx_IntStatus(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_IntStatus(USB_INT_Type intType) { + if (USB_INT_ALL == intType) { + return BL_RD_REG(USB_BASE, USB_INT_STS) ? SET : RESET; + } - tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); + return ((BL_RD_REG(USB_BASE, USB_INT_STS) & (1 << intType))) ? SET : RESET; +} - if (epId == EP_ID0) { - tmpVal |= (0x3F << 4); - } else { - tmpVal |= (0x3 << (epId * 2 + 8)); - } +BL_Err_Type USB_Clr_IntStatus(USB_INT_Type intType) { + uint32_t tmpVal = 0; - BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); + if (USB_INT_ALL == intType) { + BL_WR_REG(USB_BASE, USB_INT_CLEAR, USB_INT_TYPE_ALL); return SUCCESS; -} - -uint16_t USB_Get_Frame_Num(void) -{ - uint32_t tmpVal = 0; + } - tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); + tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); + tmpVal |= (1 << intType); + BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); - return tmpVal & 0x7ff; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_Config(USB_EP_ID epId, EP_Config_Type *epCfg) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Clr_EPx_IntStatus(USB_EP_ID epId) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - return ERROR; - } + tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE, epCfg->type); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR, epCfg->dir); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, epCfg->EPMaxPacketSize); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + if (epId == EP_ID0) { + tmpVal |= (0x3F << 4); + } else { + tmpVal |= (0x3 << (epId * 2 + 8)); + } - return SUCCESS; -} + BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); -BL_Err_Type USB_Set_EPx_Type(USB_EP_ID epId, EP_XFER_Type type) -{ - uint32_t tmpVal = 0; + return SUCCESS; +} - if (epId == EP_ID0) { - return ERROR; - } +uint16_t USB_Get_Frame_Num(void) { + uint32_t tmpVal = 0; - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE, type); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } + tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); - return SUCCESS; + return tmpVal & 0x7ff; } -EP_XFER_Type USB_Get_EPx_Type(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; - - if (epId == EP_ID0) { - return EP_CTRL; - } +BL_Err_Type USB_Set_EPx_Config(USB_EP_ID epId, EP_Config_Type *epCfg) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + return ERROR; + } + + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE, epCfg->type); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR, epCfg->dir); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, epCfg->EPMaxPacketSize); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; +} - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE); - break; - - default: - break; - } +BL_Err_Type USB_Set_EPx_Type(USB_EP_ID epId, EP_XFER_Type type) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + return ERROR; + } + + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE, type); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; +} - return (EP_XFER_Type)tmpVal; +EP_XFER_Type USB_Get_EPx_Type(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + return EP_CTRL; + } + + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP1_TYPE); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP2_TYPE); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP3_TYPE); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP4_TYPE); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP5_TYPE); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP6_TYPE); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP7_TYPE); + break; + + default: + break; + } + + return (EP_XFER_Type)tmpVal; } -BL_Err_Type USB_Set_EPx_Dir(USB_EP_ID epId, EP_XFER_DIR dir) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_EPx_Dir(USB_EP_ID epId, EP_XFER_DIR dir) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + return ERROR; + } + + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR, dir); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; +} - if (epId == EP_ID0) { - return ERROR; - } +EP_XFER_DIR USB_Get_EPx_Dir(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + if (epId == EP_ID0) { + return EP_DISABLED; + } + + switch (epId) { + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR); + break; + + default: + break; + } + + return (EP_XFER_DIR)tmpVal; +} - switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR, dir); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; - } +BL_Err_Type USB_Set_EPx_Size(USB_EP_ID epId, uint32_t size) { + uint32_t tmpVal = 0; - return SUCCESS; + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, size); + BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, size); + BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; } -EP_XFER_DIR USB_Get_EPx_Dir(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_EPx_TX_FIFO_Errors(USB_EP_ID epId, USB_FIFO_ERROR_FLAG_Type errFlag) { + uint32_t tmpVal = 0; - if (epId == EP_ID0) { - return EP_DISABLED; + if (errFlag == USB_FIFO_ERROR_OVERFLOW) { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_OVERFLOW); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_OVERFLOW); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_OVERFLOW); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_OVERFLOW); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_OVERFLOW); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_OVERFLOW); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_OVERFLOW); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_OVERFLOW); + break; + + default: + tmpVal = 0; + break; } - + } else { switch (epId) { - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP1_DIR); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP2_DIR); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP3_DIR); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP4_DIR); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP5_DIR); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP6_DIR); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_CR_EP7_DIR); - break; - - default: - break; + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_UNDERFLOW); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_UNDERFLOW); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_UNDERFLOW); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_UNDERFLOW); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_UNDERFLOW); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_UNDERFLOW); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_UNDERFLOW); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_UNDERFLOW); + break; + + default: + tmpVal = 0; + break; } + } - return (EP_XFER_DIR)tmpVal; + return tmpVal ? SET : RESET; } -BL_Err_Type USB_Set_EPx_Size(USB_EP_ID epId, uint32_t size) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_EPx_RX_FIFO_Errors(USB_EP_ID epId, USB_FIFO_ERROR_FLAG_Type errFlag) { + uint32_t tmpVal = 0; + if (errFlag == USB_FIFO_ERROR_OVERFLOW) { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_OVERFLOW); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_OVERFLOW); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_OVERFLOW); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_OVERFLOW); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_OVERFLOW); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_OVERFLOW); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_OVERFLOW); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_OVERFLOW); + break; + + default: + tmpVal = 0; + break; + } + } else { switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_USB_EP0_SW_SIZE, size); - BL_WR_REG(USB_BASE, USB_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP1_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP1_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP2_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP2_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP3_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP3_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP4_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP4_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP5_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP5_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP6_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP6_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_EP7_SIZE, size); - BL_WR_REG(USB_BASE, USB_EP7_CONFIG, tmpVal); - break; - - default: - break; + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_UNDERFLOW); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_UNDERFLOW); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_UNDERFLOW); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_UNDERFLOW); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_UNDERFLOW); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_UNDERFLOW); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_UNDERFLOW); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_UNDERFLOW); + break; + + default: + tmpVal = 0; + break; } + } - return SUCCESS; + return tmpVal ? SET : RESET; } -BL_Sts_Type USB_Get_EPx_TX_FIFO_Errors(USB_EP_ID epId, USB_FIFO_ERROR_FLAG_Type errFlag) -{ - uint32_t tmpVal = 0; - - if (errFlag == USB_FIFO_ERROR_OVERFLOW) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_OVERFLOW); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_OVERFLOW); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_OVERFLOW); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_OVERFLOW); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_OVERFLOW); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_OVERFLOW); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_OVERFLOW); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_OVERFLOW); - break; - - default: - tmpVal = 0; - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_UNDERFLOW); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_UNDERFLOW); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_UNDERFLOW); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_UNDERFLOW); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_UNDERFLOW); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_UNDERFLOW); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_UNDERFLOW); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_UNDERFLOW); - break; - - default: - tmpVal = 0; - break; - } - } +BL_Err_Type USB_Clr_EPx_TX_FIFO_Errors(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_TX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; +} - return tmpVal ? SET : RESET; +BL_Err_Type USB_Clr_EPx_RX_FIFO_Errors(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_RX_FIFO_CLR); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; + } + + return SUCCESS; } -BL_Sts_Type USB_Get_EPx_RX_FIFO_Errors(USB_EP_ID epId, USB_FIFO_ERROR_FLAG_Type errFlag) -{ - uint32_t tmpVal = 0; - - if (errFlag == USB_FIFO_ERROR_OVERFLOW) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_OVERFLOW); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_OVERFLOW); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_OVERFLOW); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_OVERFLOW); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_OVERFLOW); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_OVERFLOW); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_OVERFLOW); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_OVERFLOW); - break; - - default: - tmpVal = 0; - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_UNDERFLOW); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_UNDERFLOW); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_UNDERFLOW); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_UNDERFLOW); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_UNDERFLOW); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_UNDERFLOW); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_UNDERFLOW); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_UNDERFLOW); - break; - - default: - tmpVal = 0; - break; - } - } +BL_Err_Type USB_EPx_Write_Data_To_FIFO(USB_EP_ID epId, uint8_t *pData, uint16_t len) { + uint32_t timeout = 0x00FFFFFF; - return tmpVal ? SET : RESET; -} + while ((!USB_Is_EPx_RDY_Free(epId)) && timeout) { + timeout--; + } + + if (!timeout) { + return ERROR; + } -BL_Err_Type USB_Clr_EPx_TX_FIFO_Errors(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; + if (len == 1) { + USB_Set_EPx_Xfer_Size(EP_ID0, 1); + } else { + USB_Set_EPx_Xfer_Size(EP_ID0, 64); + } + for (uint16_t i = 0; i < len; i++) { switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_TX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } + case EP_ID0: + BL_WR_REG(USB_BASE, USB_EP0_TX_FIFO_WDATA, pData[i]); + break; - return SUCCESS; -} + case EP_ID1: + BL_WR_REG(USB_BASE, USB_EP1_TX_FIFO_WDATA, pData[i]); + break; -BL_Err_Type USB_Clr_EPx_RX_FIFO_Errors(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; + case EP_ID2: + BL_WR_REG(USB_BASE, USB_EP2_TX_FIFO_WDATA, pData[i]); + break; - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_RX_FIFO_CLR); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } + case EP_ID3: + BL_WR_REG(USB_BASE, USB_EP3_TX_FIFO_WDATA, pData[i]); + break; - return SUCCESS; -} + case EP_ID4: + BL_WR_REG(USB_BASE, USB_EP4_TX_FIFO_WDATA, pData[i]); + break; -BL_Err_Type USB_EPx_Write_Data_To_FIFO(USB_EP_ID epId, uint8_t *pData, uint16_t len) -{ - uint32_t timeout = 0x00FFFFFF; + case EP_ID5: + BL_WR_REG(USB_BASE, USB_EP5_TX_FIFO_WDATA, pData[i]); + break; - while ((!USB_Is_EPx_RDY_Free(epId)) && timeout) { - timeout--; - } + case EP_ID6: + BL_WR_REG(USB_BASE, USB_EP6_TX_FIFO_WDATA, pData[i]); + break; - if (!timeout) { - return ERROR; - } + case EP_ID7: + BL_WR_REG(USB_BASE, USB_EP7_TX_FIFO_WDATA, pData[i]); + break; - if (len == 1) { - USB_Set_EPx_Xfer_Size(EP_ID0, 1); - } else { - USB_Set_EPx_Xfer_Size(EP_ID0, 64); + default: + break; } + } + + return SUCCESS; +} - for (uint16_t i = 0; i < len; i++) { - switch (epId) { - case EP_ID0: - BL_WR_REG(USB_BASE, USB_EP0_TX_FIFO_WDATA, pData[i]); - break; +BL_Err_Type USB_EPx_Read_Data_From_FIFO(USB_EP_ID epId, uint8_t *pBuff, uint16_t len) { + for (uint16_t i = 0; i < len; i++) { + switch (epId) { + case EP_ID0: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP0_RX_FIFO_RDATA); + break; - case EP_ID1: - BL_WR_REG(USB_BASE, USB_EP1_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID1: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP1_RX_FIFO_RDATA); + break; - case EP_ID2: - BL_WR_REG(USB_BASE, USB_EP2_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID2: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP2_RX_FIFO_RDATA); + break; - case EP_ID3: - BL_WR_REG(USB_BASE, USB_EP3_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID3: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP3_RX_FIFO_RDATA); + break; - case EP_ID4: - BL_WR_REG(USB_BASE, USB_EP4_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID4: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP4_RX_FIFO_RDATA); + break; - case EP_ID5: - BL_WR_REG(USB_BASE, USB_EP5_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID5: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP5_RX_FIFO_RDATA); + break; - case EP_ID6: - BL_WR_REG(USB_BASE, USB_EP6_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID6: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP6_RX_FIFO_RDATA); + break; - case EP_ID7: - BL_WR_REG(USB_BASE, USB_EP7_TX_FIFO_WDATA, pData[i]); - break; + case EP_ID7: + pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP7_RX_FIFO_RDATA); + break; - default: - break; - } + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_EPx_Read_Data_From_FIFO(USB_EP_ID epId, uint8_t *pBuff, uint16_t len) -{ - for (uint16_t i = 0; i < len; i++) { - switch (epId) { - case EP_ID0: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP0_RX_FIFO_RDATA); - break; - - case EP_ID1: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP1_RX_FIFO_RDATA); - break; - - case EP_ID2: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP2_RX_FIFO_RDATA); - break; - - case EP_ID3: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP3_RX_FIFO_RDATA); - break; - - case EP_ID4: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP4_RX_FIFO_RDATA); - break; - - case EP_ID5: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP5_RX_FIFO_RDATA); - break; - - case EP_ID6: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP6_RX_FIFO_RDATA); - break; - - case EP_ID7: - pBuff[i] = (uint8_t)BL_RD_REG(USB_BASE, USB_EP7_RX_FIFO_RDATA); - break; - - default: - break; - } +BL_Err_Type USB_Set_EPx_TX_DMA_Interface_Config(USB_EP_ID epId, BL_Fun_Type newState) { + uint32_t tmpVal = 0; + + if (newState == ENABLE) { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; + } + } else { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP0_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP1_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP2_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP3_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP4_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP5_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP6_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP7_DMA_TX_EN); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_TX_DMA_Interface_Config(USB_EP_ID epId, BL_Fun_Type newState) -{ - uint32_t tmpVal = 0; - - if (newState == ENABLE) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP0_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP1_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP2_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP3_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP4_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP5_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP6_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP7_DMA_TX_EN); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } +BL_Err_Type USB_Set_EPx_RX_DMA_Interface_Config(USB_EP_ID epId, BL_Fun_Type newState) { + uint32_t tmpVal = 0; + + if (newState == ENABLE) { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; + } + } else { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP0_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP1_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP2_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP3_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP4_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP5_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP6_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP7_DMA_RX_EN); + BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); + break; + + default: + break; } + } - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Set_EPx_RX_DMA_Interface_Config(USB_EP_ID epId, BL_Fun_Type newState) -{ - uint32_t tmpVal = 0; - - if (newState == ENABLE) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP0_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP1_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP2_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP3_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP4_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP5_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP6_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_EP7_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP0_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP0_FIFO_CONFIG, tmpVal); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP1_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP1_FIFO_CONFIG, tmpVal); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP2_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP2_FIFO_CONFIG, tmpVal); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP3_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP3_FIFO_CONFIG, tmpVal); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP4_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP4_FIFO_CONFIG, tmpVal); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP5_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP5_FIFO_CONFIG, tmpVal); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP6_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP6_FIFO_CONFIG, tmpVal); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_EP7_DMA_RX_EN); - BL_WR_REG(USB_BASE, USB_EP7_FIFO_CONFIG, tmpVal); - break; - - default: - break; - } - } +BL_Err_Type USB_EPx_Write_Data_To_FIFO_DMA(USB_EP_ID epId, uint8_t *pData, uint16_t len) { + /* not yet implemented */ - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_EPx_Write_Data_To_FIFO_DMA(USB_EP_ID epId, uint8_t *pData, uint16_t len) -{ - /* not yet implemented */ +BL_Err_Type USB_EPx_Read_Data_From_FIFO_DMA(USB_EP_ID epId, uint8_t *pBuff, uint16_t len) { + /* not yet implemented */ - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_EPx_Read_Data_From_FIFO_DMA(USB_EP_ID epId, uint8_t *pBuff, uint16_t len) -{ - /* not yet implemented */ +uint16_t USB_Get_EPx_TX_FIFO_CNT(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_CNT); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_CNT); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_CNT); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_CNT); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_CNT); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_CNT); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_CNT); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_CNT); + break; + + default: + tmpVal = 0; + break; + } + + return tmpVal; +} - return SUCCESS; +uint16_t USB_Get_EPx_RX_FIFO_CNT(USB_EP_ID epId) { + uint32_t tmpVal = 0; + + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_CNT); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_CNT); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_CNT); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_CNT); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_CNT); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_CNT); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_CNT); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_CNT); + break; + + default: + tmpVal = 0; + break; + } + + return tmpVal; } -uint16_t USB_Get_EPx_TX_FIFO_CNT(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_EPx_TX_FIFO_Status(USB_EP_ID epId, USB_FIFO_STATUS_Type sts) { + uint32_t tmpVal = 0; + if (sts == USB_FIFO_EMPTY) { switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_CNT); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_CNT); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_CNT); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_CNT); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_CNT); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_CNT); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_CNT); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_CNT); - break; - - default: - tmpVal = 0; - break; + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_EMPTY); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_EMPTY); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_EMPTY); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_EMPTY); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_EMPTY); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_EMPTY); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_EMPTY); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_EMPTY); + break; + + default: + tmpVal = 0; + break; } - - return tmpVal; -} - -uint16_t USB_Get_EPx_RX_FIFO_CNT(USB_EP_ID epId) -{ - uint32_t tmpVal = 0; - + } else { switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_CNT); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_CNT); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_CNT); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_CNT); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_CNT); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_CNT); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_CNT); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_CNT); - break; - - default: - tmpVal = 0; - break; + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_FULL); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_FULL); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_FULL); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_FULL); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_FULL); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_FULL); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_FULL); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_FULL); + break; + + default: + tmpVal = 0; + break; } + } - return tmpVal; + return tmpVal ? SET : RESET; } -BL_Sts_Type USB_Get_EPx_TX_FIFO_Status(USB_EP_ID epId, USB_FIFO_STATUS_Type sts) -{ - uint32_t tmpVal = 0; - - if (sts == USB_FIFO_EMPTY) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_EMPTY); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_EMPTY); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_EMPTY); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_EMPTY); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_EMPTY); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_EMPTY); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_EMPTY); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_EMPTY); - break; - - default: - tmpVal = 0; - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_TX_FIFO_FULL); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_TX_FIFO_FULL); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_TX_FIFO_FULL); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_TX_FIFO_FULL); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_TX_FIFO_FULL); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_TX_FIFO_FULL); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_TX_FIFO_FULL); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_TX_FIFO_FULL); - break; - - default: - tmpVal = 0; - break; - } - } - - return tmpVal ? SET : RESET; -} +BL_Sts_Type USB_Get_EPx_RX_FIFO_Status(USB_EP_ID epId, USB_FIFO_STATUS_Type sts) { + uint32_t tmpVal = 0; -BL_Sts_Type USB_Get_EPx_RX_FIFO_Status(USB_EP_ID epId, USB_FIFO_STATUS_Type sts) -{ - uint32_t tmpVal = 0; - - if (sts == USB_FIFO_EMPTY) { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_EMPTY); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_EMPTY); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_EMPTY); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_EMPTY); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_EMPTY); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_EMPTY); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_EMPTY); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_EMPTY); - break; - - default: - tmpVal = 0; - break; - } - } else { - switch (epId) { - case EP_ID0: - tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_FULL); - break; - - case EP_ID1: - tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_FULL); - break; - - case EP_ID2: - tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_FULL); - break; - - case EP_ID3: - tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_FULL); - break; - - case EP_ID4: - tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_FULL); - break; - - case EP_ID5: - tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_FULL); - break; - - case EP_ID6: - tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_FULL); - break; - - case EP_ID7: - tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); - tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_FULL); - break; - - default: - tmpVal = 0; - break; - } + if (sts == USB_FIFO_EMPTY) { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_EMPTY); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_EMPTY); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_EMPTY); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_EMPTY); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_EMPTY); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_EMPTY); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_EMPTY); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_EMPTY); + break; + + default: + tmpVal = 0; + break; } + } else { + switch (epId) { + case EP_ID0: + tmpVal = BL_RD_REG(USB_BASE, USB_EP0_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP0_RX_FIFO_FULL); + break; + + case EP_ID1: + tmpVal = BL_RD_REG(USB_BASE, USB_EP1_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP1_RX_FIFO_FULL); + break; + + case EP_ID2: + tmpVal = BL_RD_REG(USB_BASE, USB_EP2_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP2_RX_FIFO_FULL); + break; + + case EP_ID3: + tmpVal = BL_RD_REG(USB_BASE, USB_EP3_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP3_RX_FIFO_FULL); + break; + + case EP_ID4: + tmpVal = BL_RD_REG(USB_BASE, USB_EP4_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP4_RX_FIFO_FULL); + break; + + case EP_ID5: + tmpVal = BL_RD_REG(USB_BASE, USB_EP5_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP5_RX_FIFO_FULL); + break; + + case EP_ID6: + tmpVal = BL_RD_REG(USB_BASE, USB_EP6_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP6_RX_FIFO_FULL); + break; + + case EP_ID7: + tmpVal = BL_RD_REG(USB_BASE, USB_EP7_FIFO_STATUS); + tmpVal = BL_GET_REG_BITS_VAL(tmpVal, USB_EP7_RX_FIFO_FULL); + break; + + default: + tmpVal = 0; + break; + } + } - return tmpVal ? SET : RESET; + return tmpVal ? SET : RESET; } -BL_Err_Type USB_Set_Internal_PullUp_Config(BL_Fun_Type newState) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_Internal_PullUp_Config(BL_Fun_Type newState) { + uint32_t tmpVal = 0; - /* recommended: fclk<=160MHz, bclk<=80MHz */ - tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, newState); - BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal); + /* recommended: fclk<=160MHz, bclk<=80MHz */ + tmpVal = BL_RD_REG(GLB_BASE, GLB_USB_XCVR); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, GLB_USB_ENUM, newState); + BL_WR_REG(GLB_BASE, GLB_USB_XCVR, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Sts_Type USB_Get_LPM_Status(void) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_LPM_Status(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_LPM) ? SET : RESET; + return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_LPM) ? SET : RESET; } -uint16_t USB_Get_LPM_Packet_Attr(void) -{ - uint32_t tmpVal = 0; +uint16_t USB_Get_LPM_Packet_Attr(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_LPM_ATTR); + return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_LPM_ATTR); } -BL_Err_Type USB_Set_LPM_Default_Response(USB_LPM_DEFAULT_RESP_Type defaultResp) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Set_LPM_Default_Response(USB_LPM_DEFAULT_RESP_Type defaultResp) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_LPM_RESP, defaultResp); - BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_LPM_RESP, defaultResp); + BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_LPM_RESP_UPD); - BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_LPM_RESP_UPD); + BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_LPM_Enable(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_LPM_Enable(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_LPM_EN); - BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_LPM_EN); + BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_LPM_Disable(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_LPM_Disable(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); - tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_LPM_EN); - BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_LPM_CONFIG); + tmpVal = BL_CLR_REG_BIT(tmpVal, USB_CR_LPM_EN); + BL_WR_REG(USB_BASE, USB_LPM_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Device_Output_K_State(uint16_t stateWidth) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Device_Output_K_State(uint16_t stateWidth) { + uint32_t tmpVal = 0; - CHECK_PARAM((stateWidth <= 0x7FF)); + CHECK_PARAM((stateWidth <= 0x7FF)); - tmpVal = BL_RD_REG(USB_BASE, USB_RESUME_CONFIG); - tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_RES_WIDTH, stateWidth); - BL_WR_REG(USB_BASE, USB_RESUME_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_RESUME_CONFIG); + tmpVal = BL_SET_REG_BITS_VAL(tmpVal, USB_CR_RES_WIDTH, stateWidth); + BL_WR_REG(USB_BASE, USB_RESUME_CONFIG, tmpVal); - tmpVal = BL_RD_REG(USB_BASE, USB_RESUME_CONFIG); - tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_RES_TRIG); - BL_WR_REG(USB_BASE, USB_RESUME_CONFIG, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_RESUME_CONFIG); + tmpVal = BL_SET_REG_BIT(tmpVal, USB_CR_RES_TRIG); + BL_WR_REG(USB_BASE, USB_RESUME_CONFIG, tmpVal); - return SUCCESS; + return SUCCESS; } -uint8_t USB_Get_Current_Packet_PID(void) -{ - uint32_t tmpVal = 0; +uint8_t USB_Get_Current_Packet_PID(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); + tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); - return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_PID); + return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_PID); } -uint8_t USB_Get_Current_Packet_EP(void) -{ - uint32_t tmpVal = 0; +uint8_t USB_Get_Current_Packet_EP(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); + tmpVal = BL_RD_REG(USB_BASE, USB_FRAME_NO); - return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP_NO); + return BL_GET_REG_BITS_VAL(tmpVal, USB_STS_EP_NO); } -BL_Sts_Type USB_Get_Error_Status(USB_ERROR_Type err) -{ - uint32_t tmpVal = 0; +BL_Sts_Type USB_Get_Error_Status(USB_ERROR_Type err) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_ERROR); + tmpVal = BL_RD_REG(USB_BASE, USB_ERROR); - return tmpVal & (1 << err) ? SET : RESET; + return tmpVal & (1 << err) ? SET : RESET; } -BL_Err_Type USB_Clr_Error_Status(USB_ERROR_Type err) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Clr_Error_Status(USB_ERROR_Type err) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); - tmpVal |= (1 << USB_INT_ERROR); - BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); + tmpVal |= (1 << USB_INT_ERROR); + BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); - return SUCCESS; + return SUCCESS; } -BL_Err_Type USB_Clr_RstEndIntStatus(void) -{ - uint32_t tmpVal = 0; +BL_Err_Type USB_Clr_RstEndIntStatus(void) { + uint32_t tmpVal = 0; - tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); - tmpVal |= (1 << 27); - BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); + tmpVal = BL_RD_REG(USB_BASE, USB_INT_CLEAR); + tmpVal |= (1 << 27); + BL_WR_REG(USB_BASE, USB_INT_CLEAR, tmpVal); - return SUCCESS; + return SUCCESS; } /*@} end of group USB_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash.c index 23c28a639..a53efa2c4 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_xip_sflash.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_xip_sflash.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "string.h" #include "bl702_xip_sflash.h" +#include "string.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -81,99 +81,95 @@ static uint8_t aesEnable; */ /****************************************************************************/ /** - * @brief XIP SFlash option save - * - * @param None - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION XIP_SFlash_Opt_Enter(void) -{ - aesEnable = SF_Ctrl_Is_AES_Enable(); - - if (aesEnable) { - SF_Ctrl_AES_Disable(); - } + * @brief XIP SFlash option save + * + * @param None + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION XIP_SFlash_Opt_Enter(void) { + aesEnable = SF_Ctrl_Is_AES_Enable(); + + if (aesEnable) { + SF_Ctrl_AES_Disable(); + } } /****************************************************************************/ /** - * @brief XIP SFlash option restore - * - * @param None - * - * @return None - * -*******************************************************************************/ -void ATTR_TCM_SECTION XIP_SFlash_Opt_Exit(void) -{ - if (aesEnable) { - SF_Ctrl_AES_Enable(); - } + * @brief XIP SFlash option restore + * + * @param None + * + * @return None + * + *******************************************************************************/ +void ATTR_TCM_SECTION XIP_SFlash_Opt_Exit(void) { + if (aesEnable) { + SF_Ctrl_AES_Enable(); + } } /****************************************************************************/ /** - * @brief Save flash controller state - * - * @param pFlashCfg: Flash config pointer - * @param offset: CPU XIP flash offset pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Save flash controller state + * + * @param pFlashCfg: Flash config pointer + * @param offset: CPU XIP flash offset pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Save(SPI_Flash_Cfg_Type *pFlashCfg, uint32_t *offset) -{ - /* XIP_SFlash_Delay */ - volatile uint32_t i = 32 * 2; - - while (i--) - ; - - SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); - /* Exit form continous read for accepting command */ - SFlash_Reset_Continue_Read(pFlashCfg); - /* Send software reset command(80bv has no this command)to deburst wrap for ISSI like */ - SFlash_Software_Reset(pFlashCfg); - /* For disable command that is setting register instaed of send command, we need write enable */ - SFlash_DisableBurstWrap(pFlashCfg); - /* Enable QE again in case reset command make it reset */ - SFlash_Qspi_Enable(pFlashCfg); - /* Deburst again to make sure */ - SFlash_DisableBurstWrap(pFlashCfg); - - /* Clear offset setting*/ - *offset = SF_Ctrl_Get_Flash_Image_Offset(); - SF_Ctrl_Set_Flash_Image_Offset(0); - - return SUCCESS; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Save(SPI_Flash_Cfg_Type *pFlashCfg, uint32_t *offset) { + /* XIP_SFlash_Delay */ + volatile uint32_t i = 32 * 2; + + while (i--) + ; + + SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); + /* Exit form continous read for accepting command */ + SFlash_Reset_Continue_Read(pFlashCfg); + /* Send software reset command(80bv has no this command)to deburst wrap for ISSI like */ + SFlash_Software_Reset(pFlashCfg); + /* For disable command that is setting register instaed of send command, we need write enable */ + SFlash_DisableBurstWrap(pFlashCfg); + /* Enable QE again in case reset command make it reset */ + SFlash_Qspi_Enable(pFlashCfg); + /* Deburst again to make sure */ + SFlash_DisableBurstWrap(pFlashCfg); + + /* Clear offset setting*/ + *offset = SF_Ctrl_Get_Flash_Image_Offset(); + SF_Ctrl_Set_Flash_Image_Offset(0); + + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Restore flash controller state - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param offset: CPU XIP flash offset - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Restore flash controller state + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param offset: CPU XIP flash offset + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t offset) -{ - uint32_t tmp[1]; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t offset) { + uint32_t tmp[1]; - SF_Ctrl_Set_Flash_Image_Offset(offset); + SF_Ctrl_Set_Flash_Image_Offset(offset); - SFlash_SetBurstWrap(pFlashCfg); - SFlash_Read(pFlashCfg, ioMode, 1, 0x0, (uint8_t *)tmp, sizeof(tmp)); - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + SFlash_SetBurstWrap(pFlashCfg); + SFlash_Read(pFlashCfg, ioMode, 1, 0x0, (uint8_t *)tmp, sizeof(tmp)); + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - return SUCCESS; + return SUCCESS; } #endif @@ -184,216 +180,209 @@ BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlash */ /****************************************************************************/ /** - * @brief Erase flash one region - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param startaddr: start address to erase - * @param endaddr: end address(include this address) to erase - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Erase flash one region + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param startaddr: start address to erase + * @param endaddr: end address(include this address) to erase + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Erase_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t startaddr, uint32_t endaddr) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Erase_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t startaddr, uint32_t endaddr) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - stat = SFlash_Erase(pFlashCfg, startaddr, endaddr); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + stat = SFlash_Erase(pFlashCfg, startaddr, endaddr); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return stat; + return stat; } #endif /****************************************************************************/ /** - * @brief Program flash one region - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param addr: start address to be programed - * @param data: data pointer to be programed - * @param len: data length to be programed - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Program flash one region + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param addr: start address to be programed + * @param data: data pointer to be programed + * @param len: data length to be programed + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Write_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Write_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - stat = SFlash_Program(pFlashCfg, ioMode, addr, data, len); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + stat = SFlash_Program(pFlashCfg, ioMode, addr, data, len); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return stat; + return stat; } #endif /****************************************************************************/ /** - * @brief Read data from flash - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param addr: flash read start address - * @param data: data pointer to store data read from flash - * @param len: data length to read - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Read data from flash + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param addr: flash read start address + * @param data: data pointer to store data read from flash + * @param len: data length to read + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint32_t addr, uint8_t *data, uint32_t len) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - stat = SFlash_Read(pFlashCfg, ioMode, 0, addr, data, len); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + stat = SFlash_Read(pFlashCfg, ioMode, 0, addr, data, len); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return stat; + return stat; } #endif /****************************************************************************/ /** - * @brief Get Flash Jedec ID - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param data: data pointer to store Jedec ID Read from flash - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Get Flash Jedec ID + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param data: data pointer to store Jedec ID Read from flash + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetJedecId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetJedecId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - SFlash_GetJedecId(pFlashCfg, data); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + SFlash_GetJedecId(pFlashCfg, data); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Get Flash Device ID - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param data: data pointer to store Device ID Read from flash - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Get Flash Device ID + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param data: data pointer to store Device ID Read from flash + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetDeviceId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetDeviceId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - SFlash_GetDeviceId(data); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + SFlash_GetDeviceId(data); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Get Flash Unique ID - * - * @param pFlashCfg: Flash config pointer - * @param ioMode: flash controller interface mode - * @param data: data pointer to store Device ID Read from flash - * @param idLen: Unique id len - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Get Flash Unique ID + * + * @param pFlashCfg: Flash config pointer + * @param ioMode: flash controller interface mode + * @param data: data pointer to store Device ID Read from flash + * @param idLen: Unique id len + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetUniqueId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data, uint8_t idLen) -{ - BL_Err_Type stat; - uint32_t offset; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetUniqueId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SF_Ctrl_IO_Type ioMode, uint8_t *data, uint8_t idLen) { + BL_Err_Type stat; + uint32_t offset; - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - SFlash_GetUniqueId(data, idLen); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + SFlash_GetUniqueId(data, idLen); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } - return SUCCESS; + return SUCCESS; } #endif /****************************************************************************/ /** - * @brief Read data from flash via XIP - * - * @param addr: flash read start address - * @param data: data pointer to store data read from flash - * @param len: data length to read - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ + * @brief Read data from flash via XIP + * + * @param addr: flash read start address + * @param data: data pointer to store data read from flash + * @param len: data length to read + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ #ifndef BFLB_USE_ROM_DRIVER __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Via_Cache_Need_Lock(uint32_t addr, uint8_t *data, uint32_t len) -{ - uint32_t offset; - - if (addr >= BL702_FLASH_XIP_BASE && addr < BL702_FLASH_XIP_END) { - offset = SF_Ctrl_Get_Flash_Image_Offset(); - SF_Ctrl_Set_Flash_Image_Offset(0); - /* Flash read */ - BL702_MemCpy_Fast(data, (void *)(addr - SF_Ctrl_Get_Flash_Image_Offset()), len); - SF_Ctrl_Set_Flash_Image_Offset(offset); - } - - return SUCCESS; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Via_Cache_Need_Lock(uint32_t addr, uint8_t *data, uint32_t len) { + uint32_t offset; + + if (addr >= BL702_FLASH_XIP_BASE && addr < BL702_FLASH_XIP_END) { + offset = SF_Ctrl_Get_Flash_Image_Offset(); + SF_Ctrl_Set_Flash_Image_Offset(0); + /* Flash read */ + BL702_MemCpy_Fast(data, (void *)(addr - SF_Ctrl_Get_Flash_Image_Offset()), len); + SF_Ctrl_Set_Flash_Image_Offset(offset); + } + + return SUCCESS; } #endif diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash_ext.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash_ext.c index 2f75785da..a4065391e 100644 --- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash_ext.c +++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/std_drv/src/bl702_xip_sflash_ext.c @@ -1,41 +1,41 @@ /** - ****************************************************************************** - * @file bl702_xip_sflash_ext.c - * @version V1.0 - * @date - * @brief This file is the standard driver c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2020 Bouffalo Lab

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file bl702_xip_sflash_ext.c + * @version V1.0 + * @date + * @brief This file is the standard driver c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2020 Bouffalo Lab

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include "string.h" #include "bl702_xip_sflash_ext.h" +#include "string.h" /** @addtogroup BL702_Peripheral_Driver * @{ @@ -79,57 +79,55 @@ * @{ */ -/****************************************************************************//** - * @brief XIP KH25V40 flash write protect set - * - * @param pFlashCfg: Flash config pointer - * @param protect: protect area - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ +/****************************************************************************/ /** + * @brief XIP KH25V40 flash write protect set + * + * @param pFlashCfg: Flash config pointer + * @param protect: protect area + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_KH25V40_Write_Protect_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SFlash_Protect_Kh25v40_Type protect) -{ - BL_Err_Type stat; - uint32_t offset; - SF_Ctrl_IO_Type ioMode = (SF_Ctrl_IO_Type)pFlashCfg->ioMode&0xf; - - stat = XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - stat = SFlash_KH25V40_Write_Protect(pFlashCfg, protect); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } - - return stat; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_KH25V40_Write_Protect_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg, SFlash_Protect_Kh25v40_Type protect) { + BL_Err_Type stat; + uint32_t offset; + SF_Ctrl_IO_Type ioMode = (SF_Ctrl_IO_Type)pFlashCfg->ioMode & 0xf; + + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + stat = SFlash_KH25V40_Write_Protect(pFlashCfg, protect); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } + + return stat; } -/****************************************************************************//** - * @brief Clear flash status register need lock - * - * @param pFlashCfg: Flash config pointer - * - * @return SUCCESS or ERROR - * -*******************************************************************************/ +/****************************************************************************/ /** + * @brief Clear flash status register need lock + * + * @param pFlashCfg: Flash config pointer + * + * @return SUCCESS or ERROR + * + *******************************************************************************/ __WEAK -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Clear_Status_Register_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg) -{ - BL_Err_Type stat; - uint32_t offset; - SF_Ctrl_IO_Type ioMode = (SF_Ctrl_IO_Type)pFlashCfg->ioMode&0xf; - - stat=XIP_SFlash_State_Save(pFlashCfg, &offset); - if (stat != SUCCESS) { - SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); - } else { - stat=SFlash_Clear_Status_Register(pFlashCfg); - XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); - } - - return stat; +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Clear_Status_Register_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg) { + BL_Err_Type stat; + uint32_t offset; + SF_Ctrl_IO_Type ioMode = (SF_Ctrl_IO_Type)pFlashCfg->ioMode & 0xf; + + stat = XIP_SFlash_State_Save(pFlashCfg, &offset); + if (stat != SUCCESS) { + SFlash_Set_IDbus_Cfg(pFlashCfg, ioMode, 1, 0, 32); + } else { + stat = SFlash_Clear_Status_Register(pFlashCfg); + XIP_SFlash_State_Restore(pFlashCfg, ioMode, offset); + } + + return stat; } /*@} end of group XIP_SFLASH_EXT_Public_Functions */ diff --git a/source/Core/BSP/Pinecilv2/ble.c b/source/Core/BSP/Pinecilv2/ble.c index 5206d6af4..dd99b83cc 100644 --- a/source/Core/BSP/Pinecilv2/ble.c +++ b/source/Core/BSP/Pinecilv2/ble.c @@ -59,3 +59,12 @@ void vApplicationMallocFailedHook(void) { ; } } + +void user_vAssertCalled(void) { + + MSG("user_vAssertCalled\r\n"); + + while (1) { + ; + } +} diff --git a/source/Core/BSP/Pinecilv2/ble_characteristics.h b/source/Core/BSP/Pinecilv2/ble_characteristics.h index e6e7ab6a6..bacab6bbe 100644 --- a/source/Core/BSP/Pinecilv2/ble_characteristics.h +++ b/source/Core/BSP/Pinecilv2/ble_characteristics.h @@ -90,4 +90,6 @@ #define BT_UUID_CHAR_BLE_SETTINGS_VALUE_36 BT_UUID_DECLARE_128(BT_UUID_128_ENCODE(0xf6d70024, 0x5a10, 0x4eba, 0xAA55, 0x33e27f9bc533)) #define BT_UUID_CHAR_BLE_SETTINGS_VALUE_37 BT_UUID_DECLARE_128(BT_UUID_128_ENCODE(0xf6d70025, 0x5a10, 0x4eba, 0xAA55, 0x33e27f9bc533)) #define BT_UUID_CHAR_BLE_SETTINGS_VALUE_38 BT_UUID_DECLARE_128(BT_UUID_128_ENCODE(0xf6d70026, 0x5a10, 0x4eba, 0xAA55, 0x33e27f9bc533)) +#define BT_UUID_CHAR_BLE_SETTINGS_VALUE_53 BT_UUID_DECLARE_128(BT_UUID_128_ENCODE(0xf6d70035, 0x5a10, 0x4eba, 0xAA55, 0x33e27f9bc533)) +#define BT_UUID_CHAR_BLE_SETTINGS_VALUE_54 BT_UUID_DECLARE_128(BT_UUID_128_ENCODE(0xf6d70036, 0x5a10, 0x4eba, 0xAA55, 0x33e27f9bc533)) #endif diff --git a/source/Core/BSP/Pinecilv2/ble_handlers.cpp b/source/Core/BSP/Pinecilv2/ble_handlers.cpp index b23198191..e4a1f8043 100644 --- a/source/Core/BSP/Pinecilv2/ble_handlers.cpp +++ b/source/Core/BSP/Pinecilv2/ble_handlers.cpp @@ -34,7 +34,7 @@ #endif extern TickType_t lastMovementTime; -extern OperatingMode currentMode; +extern OperatingMode currentOperatingMode; int ble_char_read_status_callback(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset) { if (attr == NULL || attr->uuid == NULL) { @@ -123,7 +123,7 @@ int ble_char_read_status_callback(struct bt_conn *conn, const struct bt_gatt_att break; case 13: // Operating mode - temp = currentMode; + temp = (uint32_t)currentOperatingMode; memcpy(buf, &temp, sizeof(temp)); return sizeof(temp); break; @@ -133,6 +133,8 @@ int ble_char_read_status_callback(struct bt_conn *conn, const struct bt_gatt_att memcpy(buf, &temp, sizeof(temp)); return sizeof(temp); break; + default: + break; } MSG((char *)"Unhandled attr read %d | %d\n", (uint32_t)attr->uuid, uuid_value); return 0; @@ -150,7 +152,7 @@ int ble_char_read_bulk_value_callback(struct bt_conn *conn, const struct bt_gatt // Bulk data { uint32_t bulkData[] = { - TipThermoModel::getTipInC(), // 0 - Current temp + (uint32_t)TipThermoModel::getTipInC(), // 0 - Current temp getSettingValue(SettingsOptions::SolderingTemp), // 1 - Setpoint getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0), // 2 - Input voltage getHandleTemperature(0), // 3 - Handle X10 Temp in C @@ -159,10 +161,10 @@ int ble_char_read_bulk_value_callback(struct bt_conn *conn, const struct bt_gatt getTipResistanceX10(), // 6 - Tip resistance xTaskGetTickCount() / TICKS_100MS, // 7 - uptime in deciseconds lastMovementTime / TICKS_100MS, // 8 - last movement time (deciseconds) - TipThermoModel::getTipMaxInC(), // 9 - max temp + (uint32_t)TipThermoModel::getTipMaxInC(), // 9 - max temp TipThermoModel::convertTipRawADCTouV(getTipRawTemp(0), true), // 10 - Raw tip in μV - abs(getRawHallEffect()), // 11 - hall sensor - currentMode, // 12 - Operating mode + (uint32_t)abs(getRawHallEffect()), // 11 - hall sensor + (uint32_t)currentOperatingMode, // 12 - Operating mode x10WattHistory.average(), // 13 - Estimated Wattage *10 }; int lenToCopy = sizeof(bulkData) - offset; @@ -203,6 +205,8 @@ int ble_char_read_bulk_value_callback(struct bt_conn *conn, const struct bt_gatt memcpy(buf, &id, sizeof(id)); return sizeof(id); } + default: + break; } return 0; } diff --git a/source/Core/BSP/Pinecilv2/ble_peripheral.c b/source/Core/BSP/Pinecilv2/ble_peripheral.c index 1cbf4ba1b..1da059769 100644 --- a/source/Core/BSP/Pinecilv2/ble_peripheral.c +++ b/source/Core/BSP/Pinecilv2/ble_peripheral.c @@ -246,6 +246,12 @@ static struct bt_gatt_attr ble_attrs_declaration[] = { ble_char_read_setting_value_callback, ble_char_write_setting_value_callback, NULL), BT_GATT_CHARACTERISTIC(BT_UUID_CHAR_BLE_SETTINGS_VALUE_38, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, ble_char_read_setting_value_callback, ble_char_write_setting_value_callback, NULL), + BT_GATT_CHARACTERISTIC(BT_UUID_CHAR_BLE_SETTINGS_VALUE_53, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + ble_char_read_setting_value_callback, ble_char_write_setting_value_callback, NULL), + BT_GATT_CHARACTERISTIC(BT_UUID_CHAR_BLE_SETTINGS_VALUE_54, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + ble_char_read_setting_value_callback, ble_char_write_setting_value_callback, NULL), + + /* Save & reset */ BT_GATT_CHARACTERISTIC(BT_UUID_CHAR_BLE_SETTINGS_VALUE_SAVE, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, ble_char_read_setting_value_callback, ble_char_write_setting_value_callback, NULL), @@ -258,9 +264,7 @@ static struct bt_gatt_attr ble_attrs_declaration[] = { NAME get_attr */ -struct bt_gatt_attr *get_attr(u8_t index) { - return &ble_attrs_declaration[index]; -} +struct bt_gatt_attr *get_attr(u8_t index) { return &ble_attrs_declaration[index]; } static struct bt_gatt_service ble_tp_server = BT_GATT_SERVICE(ble_attrs_declaration); diff --git a/source/Core/BSP/Pinecilv2/ble_peripheral.h b/source/Core/BSP/Pinecilv2/ble_peripheral.h index 3d45290db..db8410e38 100644 --- a/source/Core/BSP/Pinecilv2/ble_peripheral.h +++ b/source/Core/BSP/Pinecilv2/ble_peripheral.h @@ -10,7 +10,7 @@ NOTES #ifndef _BLE_TP_SVC_H_ #define _BLE_TP_SVC_H_ -#include "types.h" +#include #include "ble_config.h" // read value handle offset 2 diff --git a/source/Core/BSP/Pinecilv2/board.c b/source/Core/BSP/Pinecilv2/board.c index a1ef0288a..84ae831fb 100644 --- a/source/Core/BSP/Pinecilv2/board.c +++ b/source/Core/BSP/Pinecilv2/board.c @@ -33,34 +33,34 @@ struct pin_mux_cfg { static const struct pin_mux_cfg af_pin_table[] = { #ifdef CONFIG_GPIO0_FUNC - {.pin = GPIO_PIN_0, .func = CONFIG_GPIO0_FUNC}, + { .pin = GPIO_PIN_0, .func = CONFIG_GPIO0_FUNC}, #endif #ifdef CONFIG_GPIO1_FUNC - {.pin = GPIO_PIN_1, .func = CONFIG_GPIO1_FUNC}, + { .pin = GPIO_PIN_1, .func = CONFIG_GPIO1_FUNC}, #endif #ifdef CONFIG_GPIO2_FUNC - {.pin = GPIO_PIN_2, .func = CONFIG_GPIO2_FUNC}, + { .pin = GPIO_PIN_2, .func = CONFIG_GPIO2_FUNC}, #endif #ifdef CONFIG_GPIO3_FUNC - {.pin = GPIO_PIN_3, .func = CONFIG_GPIO3_FUNC}, + { .pin = GPIO_PIN_3, .func = CONFIG_GPIO3_FUNC}, #endif #ifdef CONFIG_GPIO4_FUNC - {.pin = GPIO_PIN_4, .func = CONFIG_GPIO4_FUNC}, + { .pin = GPIO_PIN_4, .func = CONFIG_GPIO4_FUNC}, #endif #ifdef CONFIG_GPIO5_FUNC - {.pin = GPIO_PIN_5, .func = CONFIG_GPIO5_FUNC}, + { .pin = GPIO_PIN_5, .func = CONFIG_GPIO5_FUNC}, #endif #ifdef CONFIG_GPIO6_FUNC - {.pin = GPIO_PIN_6, .func = CONFIG_GPIO6_FUNC}, + { .pin = GPIO_PIN_6, .func = CONFIG_GPIO6_FUNC}, #endif #ifdef CONFIG_GPIO7_FUNC - {.pin = GPIO_PIN_7, .func = CONFIG_GPIO7_FUNC}, + { .pin = GPIO_PIN_7, .func = CONFIG_GPIO7_FUNC}, #endif #ifdef CONFIG_GPIO8_FUNC - {.pin = GPIO_PIN_8, .func = CONFIG_GPIO8_FUNC}, + { .pin = GPIO_PIN_8, .func = CONFIG_GPIO8_FUNC}, #endif #ifdef CONFIG_GPIO9_FUNC - {.pin = GPIO_PIN_9, .func = CONFIG_GPIO9_FUNC}, + { .pin = GPIO_PIN_9, .func = CONFIG_GPIO9_FUNC}, #endif #ifdef CONFIG_GPIO10_FUNC {.pin = GPIO_PIN_10, .func = CONFIG_GPIO10_FUNC}, @@ -133,7 +133,7 @@ static const struct pin_mux_cfg af_pin_table[] = { static void board_pin_mux_init(void) { GLB_GPIO_Cfg_Type gpio_cfg; uint32_t tmpVal; - gpio_cfg.drive = 3; + gpio_cfg.drive = 2; gpio_cfg.smtCtrl = 1; uint8_t hbn_gpio_mask = 0x1f; uint8_t hbn_aon_ie = 0; @@ -146,8 +146,9 @@ static void board_pin_mux_init(void) { /*if using gpio9-gpio12 and func is not analog and output ,should set reg_aon_pad_ie_smt corresponding bit = 1*/ if ((af_pin_table[i].pin > GPIO_PIN_8) && (af_pin_table[i].pin < GPIO_PIN_13)) { - if ((af_pin_table[i].func != 10) && ((af_pin_table[i].func < GPIO_FUN_GPIO_OUTPUT_UP) || (af_pin_table[i].func > GPIO_FUN_GPIO_OUTPUT_NONE))) + if ((af_pin_table[i].func != 10) && ((af_pin_table[i].func < GPIO_FUN_GPIO_OUTPUT_UP) || (af_pin_table[i].func > GPIO_FUN_GPIO_OUTPUT_NONE))) { hbn_aon_ie |= (1 << (af_pin_table[i].pin - 9)); + } } /*if reset state*/ diff --git a/source/Core/BSP/Pinecilv2/configuration.h b/source/Core/BSP/Pinecilv2/configuration.h index 5297f3a4b..e50b7225f 100644 --- a/source/Core/BSP/Pinecilv2/configuration.h +++ b/source/Core/BSP/Pinecilv2/configuration.h @@ -1,6 +1,5 @@ #ifndef CONFIGURATION_H_ #define CONFIGURATION_H_ -#include "Settings.h" #include /** * Configuration.h @@ -57,6 +56,7 @@ * */ #define ORIENTATION_MODE 2 // 0: Right 1:Left 2:Automatic - Default Automatic +#define MAX_ORIENTATION_MODE 2 // Up to auto #define REVERSE_BUTTON_TEMP_CHANGE 0 // 0:Default 1:Reverse - Reverse the plus and minus button assigment for temperature change /** @@ -83,7 +83,7 @@ #define POWER_PULSE_WAIT_MAX 9 // 9*2.5s = 22.5 seconds #define POWER_PULSE_DURATION_MAX 9 // 9*250ms = 2.25 seconds -#ifdef MODEL_Pinecil +#ifdef MODEL_Pinecilv2 #define POWER_PULSE_DEFAULT 0 #else #define POWER_PULSE_DEFAULT 5 @@ -105,7 +105,7 @@ #define DETAILED_IDLE 0 // 0: Disable 1: Enable - Default 0 #define THERMAL_RUNAWAY_TIME_SEC 20 -#define THERMAL_RUNAWAY_TEMP_C 20 +#define THERMAL_RUNAWAY_TEMP_C 3 #define CUT_OUT_SETTING 0 // default to no cut-off voltage #define RECOM_VOL_CELL 33 // Minimum voltage per cell (Recommended 3.3V (33)) @@ -114,7 +114,7 @@ #define ANIMATION_LOOP 1 // 0: off 1: on #define ANIMATION_SPEED settingOffSpeed_t::MEDIUM -#define OP_AMP_Rf_Pinecil 680 * 1000 // 700 Kilo-ohms -> From schematic, R1 +#define OP_AMP_Rf_Pinecil 680 * 1000 // 680 Kilo-ohms -> From schematic, R1 #define OP_AMP_Rin_Pinecil 2370 // 2.37 Kilo-ohms -> From schematic, R2 #define OP_AMP_GAIN_STAGE_PINECIL (1 + (OP_AMP_Rf_Pinecil / OP_AMP_Rin_Pinecil)) @@ -124,10 +124,10 @@ #endif #ifdef MODEL_Pinecilv2 -#define ADC_VDD_MV 3300 // ADC max reading millivolts -#define ADC_MAX_READING (62000 >> 1) // Maximum reading of the adc +#define ADC_VDD_MV 3200 // ADC max reading millivolts +#define ADC_MAX_READING ((1 << 16) >> 1) // Maximum reading of the adc #define SOLDERING_TEMP 320 // Default soldering temp is 320.0 °C -#define VOLTAGE_DIV 600 // 600 - Default divider from schematic +#define VOLTAGE_DIV 630 // 600 - Default divider from schematic #define CALIBRATION_OFFSET 900 // 900 - Default adc offset in uV #define MIN_CALIBRATION_OFFSET 100 // Min value for calibration #define PID_POWER_LIMIT 120 // Sets the max pwm power limit @@ -146,13 +146,19 @@ #define MIN_BOOST_TEMP_F 480 // The min settable temp for boost mode °F #define DEVICE_HAS_VALIDATION_CODE // We have 2 digit validations #define POW_PD 1 // Supported features +#define USB_PD_EPR_WATTAGE 140 // USB PD EPR Wattage #define POW_PD_EXT 0 // Future-proof macro for other models with other PD modes #define POW_QC 1 // Supported features #define POW_DC 1 // Supported features #define POW_QC_20V 1 // Supported features #define POW_EPR 1 #define ENABLE_QC2 1 +#define MAG_SLEEP_SUPPORT 1 +#define TIP_TYPE_SUPPORT 1 // Support for tips of different types, i.e. resistance +#define AUTO_TIP_SELECTION 1 // Can auto-select the tip +#define TIPTYPE_T12 1 // Can manually pick a T12 tip #define DEVICE_HAS_VALIDATION_SUPPORT +#define OLED_96x16 1 #define TEMP_NTC #define ACCEL_BMA #define ACCEL_SC7 @@ -165,8 +171,8 @@ #define NEEDS_VBUS_PROBE 0 // No vbus probe, its not connected in pcb #define CANT_DIRECT_READ_SETTINGS // We cant memcpy settings due to flash cache #define TIP_CONTROL_PID // We use PID rather than integrator -#define TIP_PID_KP 45 // Reasonable compromise for most tips so far -#define TIP_PID_KI 9 // About as high for stability across tips +#define TIP_PID_KP 40 // Reasonable compromise for most tips so far +#define TIP_PID_KI 6 // About as high for stability across tips #define TIP_PID_KD 200 // Helps dampen smaller tips; ~= nothing for larger tips #define FILTER_DISPLAYED_TIP_TEMP 8 // Filtering for GUI display diff --git a/source/Core/BSP/Pinecilv2/peripheral_config.h b/source/Core/BSP/Pinecilv2/peripheral_config.h index 21b56915c..375de426c 100644 --- a/source/Core/BSP/Pinecilv2/peripheral_config.h +++ b/source/Core/BSP/Pinecilv2/peripheral_config.h @@ -123,7 +123,7 @@ #define DMA0_CH0_CONFIG \ { \ .id = 0, .ch = 0, .direction = DMA_MEMORY_TO_MEMORY, .transfer_mode = DMA_LLI_ONCE_MODE, .src_req = DMA_REQUEST_NONE, .dst_req = DMA_REQUEST_NONE, .src_addr_inc = DMA_ADDR_INCREMENT_ENABLE, \ - .dst_addr_inc = DMA_ADDR_INCREMENT_ENABLE, .src_burst_size = DMA_BURST_4BYTE, .dst_burst_size = DMA_BURST_4BYTE, .src_width = DMA_TRANSFER_WIDTH_32BIT, .dst_width = DMA_TRANSFER_WIDTH_32BIT, \ + .dst_addr_inc = DMA_ADDR_INCREMENT_ENABLE, .src_burst_size = DMA_BURST_SIZE_4, .dst_burst_size = DMA_BURST_SIZE_4, .src_width = DMA_TRANSFER_WIDTH_32BIT, .dst_width = DMA_TRANSFER_WIDTH_32BIT, \ } #endif #endif @@ -133,7 +133,7 @@ #define DMA0_CH1_CONFIG \ { \ .id = 0, .ch = 1, .direction = DMA_MEMORY_TO_MEMORY, .transfer_mode = DMA_LLI_ONCE_MODE, .src_req = DMA_REQUEST_NONE, .dst_req = DMA_REQUEST_NONE, .src_addr_inc = DMA_ADDR_INCREMENT_ENABLE, \ - .dst_addr_inc = DMA_ADDR_INCREMENT_ENABLE, .src_burst_size = DMA_BURST_4BYTE, .dst_burst_size = DMA_BURST_4BYTE, .src_width = DMA_TRANSFER_WIDTH_16BIT, .dst_width = DMA_TRANSFER_WIDTH_16BIT, \ + .dst_addr_inc = DMA_ADDR_INCREMENT_ENABLE, .src_burst_size = DMA_BURST_SIZE_4, .dst_burst_size = DMA_BURST_SIZE_4, .src_width = DMA_TRANSFER_WIDTH_16BIT, .dst_width = DMA_TRANSFER_WIDTH_16BIT, \ } #endif #endif @@ -143,7 +143,7 @@ #define DMA0_CH2_CONFIG \ { \ .id = 0, .ch = 2, .direction = DMA_MEMORY_TO_PERIPH, .transfer_mode = DMA_LLI_ONCE_MODE, .src_req = DMA_REQUEST_NONE, .dst_req = DMA_REQUEST_UART1_TX, .src_addr_inc = DMA_ADDR_INCREMENT_ENABLE, \ - .dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE, .src_burst_size = DMA_BURST_1BYTE, .dst_burst_size = DMA_BURST_1BYTE, .src_width = DMA_TRANSFER_WIDTH_8BIT, .dst_width = DMA_TRANSFER_WIDTH_8BIT, \ + .dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE, .src_burst_size = DMA_BURST_SIZE_1, .dst_burst_size = DMA_BURST_SIZE_1, .src_width = DMA_TRANSFER_WIDTH_8BIT, .dst_width = DMA_TRANSFER_WIDTH_8BIT, \ } #endif #endif @@ -153,7 +153,7 @@ #define DMA0_CH3_CONFIG \ { \ .id = 0, .ch = 3, .direction = DMA_MEMORY_TO_PERIPH, .transfer_mode = DMA_LLI_ONCE_MODE, .src_req = DMA_REQUEST_NONE, .dst_req = DMA_REQUEST_SPI0_TX, .src_addr_inc = DMA_ADDR_INCREMENT_ENABLE, \ - .dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE, .src_burst_size = DMA_BURST_1BYTE, .dst_burst_size = DMA_BURST_1BYTE, .src_width = DMA_TRANSFER_WIDTH_8BIT, .dst_width = DMA_TRANSFER_WIDTH_8BIT, \ + .dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE, .src_burst_size = DMA_BURST_SIZE_1, .dst_burst_size = DMA_BURST_SIZE_1, .src_width = DMA_TRANSFER_WIDTH_8BIT, .dst_width = DMA_TRANSFER_WIDTH_8BIT, \ } #endif #endif @@ -163,7 +163,7 @@ #define DMA0_CH4_CONFIG \ { \ .id = 0, .ch = 4, .direction = DMA_PERIPH_TO_MEMORY, .transfer_mode = DMA_LLI_ONCE_MODE, .src_req = DMA_REQUEST_SPI0_RX, .dst_req = DMA_REQUEST_NONE, .src_addr_inc = DMA_ADDR_INCREMENT_DISABLE, \ - .dst_addr_inc = DMA_ADDR_INCREMENT_ENABLE, .src_burst_size = DMA_BURST_1BYTE, .dst_burst_size = DMA_BURST_1BYTE, .src_width = DMA_TRANSFER_WIDTH_8BIT, .dst_width = DMA_TRANSFER_WIDTH_8BIT, \ + .dst_addr_inc = DMA_ADDR_INCREMENT_ENABLE, .src_burst_size = DMA_BURST_SIZE_1, .dst_burst_size = DMA_BURST_SIZE_1, .src_width = DMA_TRANSFER_WIDTH_8BIT, .dst_width = DMA_TRANSFER_WIDTH_8BIT, \ } #endif #endif @@ -173,7 +173,7 @@ #define DMA0_CH5_CONFIG \ { \ .id = 0, .ch = 5, .direction = DMA_MEMORY_TO_PERIPH, .transfer_mode = DMA_LLI_CYCLE_MODE, .src_req = DMA_REQUEST_NONE, .dst_req = DMA_REQUEST_I2S_TX, .src_addr_inc = DMA_ADDR_INCREMENT_ENABLE, \ - .dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE, .src_burst_size = DMA_BURST_1BYTE, .dst_burst_size = DMA_BURST_1BYTE, .src_width = DMA_TRANSFER_WIDTH_16BIT, .dst_width = DMA_TRANSFER_WIDTH_16BIT, \ + .dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE, .src_burst_size = DMA_BURST_SIZE_1, .dst_burst_size = DMA_BURST_SIZE_1, .src_width = DMA_TRANSFER_WIDTH_16BIT, .dst_width = DMA_TRANSFER_WIDTH_16BIT, \ } #endif #endif @@ -183,7 +183,7 @@ #define DMA0_CH6_CONFIG \ { \ .id = 0, .ch = 6, .direction = DMA_MEMORY_TO_PERIPH, .transfer_mode = DMA_LLI_CYCLE_MODE, .src_req = DMA_REQUEST_NONE, .dst_req = DMA_REQUEST_I2S_TX, .src_addr_inc = DMA_ADDR_INCREMENT_ENABLE, \ - .dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE, .src_burst_size = DMA_BURST_1BYTE, .dst_burst_size = DMA_BURST_1BYTE, .src_width = DMA_TRANSFER_WIDTH_16BIT, .dst_width = DMA_TRANSFER_WIDTH_16BIT, \ + .dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE, .src_burst_size = DMA_BURST_SIZE_1, .dst_burst_size = DMA_BURST_SIZE_1, .src_width = DMA_TRANSFER_WIDTH_16BIT, .dst_width = DMA_TRANSFER_WIDTH_16BIT, \ } #endif #endif @@ -193,7 +193,7 @@ #define DMA0_CH7_CONFIG \ { \ .id = 0, .ch = 7, .direction = DMA_MEMORY_TO_MEMORY, .transfer_mode = DMA_LLI_ONCE_MODE, .src_req = DMA_REQUEST_NONE, .dst_req = DMA_REQUEST_NONE, .src_addr_inc = DMA_ADDR_INCREMENT_ENABLE, \ - .dst_addr_inc = DMA_ADDR_INCREMENT_ENABLE, .src_burst_size = DMA_BURST_1BYTE, .dst_burst_size = DMA_BURST_1BYTE, .src_width = DMA_TRANSFER_WIDTH_32BIT, .dst_width = DMA_TRANSFER_WIDTH_32BIT, \ + .dst_addr_inc = DMA_ADDR_INCREMENT_ENABLE, .src_burst_size = DMA_BURST_SIZE_1, .dst_burst_size = DMA_BURST_SIZE_1, .src_width = DMA_TRANSFER_WIDTH_32BIT, .dst_width = DMA_TRANSFER_WIDTH_32BIT, \ } #endif #endif diff --git a/source/Core/BSP/Pinecilv2/preRTOS.cpp b/source/Core/BSP/Pinecilv2/preRTOS.cpp index 1a949881d..944a562fa 100644 --- a/source/Core/BSP/Pinecilv2/preRTOS.cpp +++ b/source/Core/BSP/Pinecilv2/preRTOS.cpp @@ -20,5 +20,6 @@ void preRToSInit() { gpio_write(OLED_RESET_Pin, 0); delay_ms(10); gpio_write(OLED_RESET_Pin, 1); + BSPInit(); FRToSI2C::FRToSInit(); } diff --git a/source/Core/BSP/Sequre_S60/BSP.cpp b/source/Core/BSP/Sequre/BSP.cpp similarity index 81% rename from source/Core/BSP/Sequre_S60/BSP.cpp rename to source/Core/BSP/Sequre/BSP.cpp index f960cd0dd..32daec13f 100644 --- a/source/Core/BSP/Sequre_S60/BSP.cpp +++ b/source/Core/BSP/Sequre/BSP.cpp @@ -2,9 +2,11 @@ #include "BSP.h" #include "BootLogo.h" +#include "FS2711.hpp" #include "HUB238.hpp" #include "I2C_Wrapper.hpp" #include "Pins.h" +#include "Settings.h" #include "Setup.h" #include "TipThermoModel.h" #include "configuration.h" @@ -52,6 +54,7 @@ static const uint16_t NTCHandleLookup[] = { }; uint16_t getHandleTemperature(uint8_t sample) { +#ifdef TMP36_ADC1_CHANNEL int32_t result = getADCHandleTemp(sample); // S60 uses 10k NTC resistor // For now not doing interpolation @@ -61,6 +64,9 @@ uint16_t getHandleTemperature(uint8_t sample) { } } return 45 * 10; +#else + return 0; // Not implemented +#endif } uint16_t getInputVoltageX10(uint16_t divisor, uint8_t sample) { @@ -104,7 +110,7 @@ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { if (PWMSafetyTimer == 0) { htim4.Instance->CCR3 = 0; } else { - htim4.Instance->CCR3 = pendingPWM; + htim4.Instance->CCR3 = pendingPWM / 4; } } else if (htim->Instance == TIM1) { // STM uses this for internal functions as a counter for timeouts @@ -155,8 +161,9 @@ void unstick_I2C() { HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET); timeout_cnt++; - if (timeout_cnt > timeout) + if (timeout_cnt > timeout) { return; + } } // 12. Configure the SCL and SDA I/Os as Alternate function Open-Drain. @@ -209,13 +216,23 @@ bool isTipDisconnected() { void setStatusLED(const enum StatusLED state) {} uint8_t preStartChecks() { +#if POW_PD_EXT == 1 if (!hub238_has_run_selection() && (xTaskGetTickCount() < TICKS_SECOND * 5)) { return 0; } // We check if we are in a "Limited" mode; where we have to run the PWM really fast // Where as if we are on 9V for example, the tip resistance is enough - uint16_t voltage = hub238_source_voltage(); - uint16_t currentx100 = hub238_source_currentX100(); + uint16_t voltage = hub238_source_voltage(); + uint16_t currentx100 = hub238_source_currentX100(); +#endif +#if POW_PD_EXT == 2 + if (!FS2711::has_run_selection() && (xTaskGetTickCount() < TICKS_SECOND * 5)) { + return 0; + } + uint16_t voltage = FS2711::source_voltage(); + uint16_t currentx100 = FS2711::source_currentx100(); +#endif + uint16_t thresholdResistancex10 = ((voltage * 1000) / currentx100) + 5; if (getTipResistanceX10() <= thresholdResistancex10) { @@ -230,7 +247,29 @@ uint64_t getDeviceID() { return HAL_GetUIDw0() | ((uint64_t)HAL_GetUIDw1() << 32); } -uint8_t getTipResistanceX10() { return TIP_RESISTANCE; } +uint8_t getTipResistanceX10() { +#ifdef COPPER_HEATER_COIL + + // TODO + //! Warning, must never return 0. + TemperatureType_t measuredTemperature = TipThermoModel::getTipInC(false); + if (measuredTemperature < 25) { + return 50; // Start assuming under spec to soft-start + } + + // Assuming a temperature rise of 0.00393 per deg c over 20C + + uint32_t scaler = 393 * (measuredTemperature - 20); + + return TIP_RESISTANCE + ((TIP_RESISTANCE * scaler) / 100000); +#else + uint8_t user_selected_tip = getUserSelectedTipResistance(); + if (user_selected_tip == 0) { + return TIP_RESISTANCE; // Auto mode + } + return user_selected_tip; +#endif +} bool isTipShorted() { return false; } uint8_t preStartChecksDone() { return 1; } @@ -240,3 +279,7 @@ uint16_t getTipInertia() { return TIP_THERMAL_INERTIA; } void setBuzzer(bool on) {} void showBootLogo(void) { BootLogo::handleShowingLogo((uint8_t *)FLASH_LOGOADDR); } + +#ifdef CUSTOM_MAX_TEMP_C +TemperatureType_t getCustomTipMaxInC() { return MAX_TEMP_C; } +#endif diff --git a/source/Core/BSP/Sequre_S60/FreeRTOSConfig.h b/source/Core/BSP/Sequre/FreeRTOSConfig.h similarity index 85% rename from source/Core/BSP/Sequre_S60/FreeRTOSConfig.h rename to source/Core/BSP/Sequre/FreeRTOSConfig.h index ef0451ef4..a9b8bb91e 100644 --- a/source/Core/BSP/Sequre_S60/FreeRTOSConfig.h +++ b/source/Core/BSP/Sequre/FreeRTOSConfig.h @@ -101,16 +101,16 @@ extern uint32_t SystemCoreClock; #define configUSE_TICK_HOOK 0 #define configCPU_CLOCK_HZ (SystemCoreClock) #define configTICK_RATE_HZ (1000) -#define configMAX_PRIORITIES (6) +#define configMAX_PRIORITIES (7) #define configMINIMAL_STACK_SIZE ((uint16_t)256) #define configTOTAL_HEAP_SIZE ((size_t)1024 * 14) /*Currently use about 9000*/ #define configMAX_TASK_NAME_LEN (32) -#define configUSE_16_BIT_TICKS 0 #define configUSE_MUTEXES 1 #define configQUEUE_REGISTRY_SIZE 8 #define configUSE_TIMERS 0 #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #define configCHECK_FOR_STACK_OVERFLOW 2 /*Bump this to 2 during development and bug hunting*/ +#define configTICK_TYPE_WIDTH_IN_BITS TICK_TYPE_WIDTH_32_BITS /* Co-routine definitions. */ #define configUSE_CO_ROUTINES 0 @@ -156,11 +156,11 @@ extern uint32_t SystemCoreClock; /* Normal assert() semantics without relying on the provision of an assert.h header file. */ /* USER CODE BEGIN 1 */ -#define configASSERT(x) \ - if ((x) == 0) { \ - taskDISABLE_INTERRUPTS(); \ - for (;;) \ - ; \ +#define configASSERT(x) \ + if ((x) == 0) { \ + taskDISABLE_INTERRUPTS(); \ + for (;;) \ + ; \ } /* USER CODE END 1 */ diff --git a/source/Core/BSP/Sequre_S60/IRQ.cpp b/source/Core/BSP/Sequre/IRQ.cpp similarity index 66% rename from source/Core/BSP/Sequre_S60/IRQ.cpp rename to source/Core/BSP/Sequre/IRQ.cpp index 196cc4378..f20acc13d 100644 --- a/source/Core/BSP/Sequre_S60/IRQ.cpp +++ b/source/Core/BSP/Sequre/IRQ.cpp @@ -23,12 +23,6 @@ void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc) { } } } -void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } -void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); } extern osThreadId POWTaskHandle; diff --git a/source/Core/BSP/Sequre_S60/IRQ.h b/source/Core/BSP/Sequre/IRQ.h similarity index 54% rename from source/Core/BSP/Sequre_S60/IRQ.h rename to source/Core/BSP/Sequre/IRQ.h index 27a3b13db..b3024636d 100644 --- a/source/Core/BSP/Sequre_S60/IRQ.h +++ b/source/Core/BSP/Sequre/IRQ.h @@ -18,12 +18,6 @@ extern "C" { #endif void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc); -void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); -void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); void HAL_GPIO_EXTI_Callback(uint16_t); #ifdef __cplusplus diff --git a/source/Core/BSP/Sequre/Pins.h b/source/Core/BSP/Sequre/Pins.h new file mode 100644 index 000000000..f00be339f --- /dev/null +++ b/source/Core/BSP/Sequre/Pins.h @@ -0,0 +1,101 @@ +/* + * Pins.h + * + * Created on: 29 May 2020 + * Author: Ralim + */ + +#ifndef BSP_MINIWARE_PINS_H_ +#define BSP_MINIWARE_PINS_H_ +#include "configuration.h" + +#ifdef MODEL_S60 + +#define KEY_B_Pin GPIO_PIN_1 +#define KEY_B_GPIO_Port GPIOB +#define TMP36_INPUT_Pin GPIO_PIN_5 +#define TMP36_INPUT_GPIO_Port GPIOA +#define TMP36_ADC1_CHANNEL ADC_CHANNEL_5 +#define TMP36_ADC2_CHANNEL ADC_CHANNEL_5 +#define TIP_TEMP_Pin GPIO_PIN_0 +#define TIP_TEMP_GPIO_Port GPIOA +#define TIP_TEMP_ADC1_CHANNEL ADC_CHANNEL_0 +#define TIP_TEMP_ADC2_CHANNEL ADC_CHANNEL_0 +#define VIN_Pin GPIO_PIN_4 +#define VIN_GPIO_Port GPIOA +#define VIN_ADC1_CHANNEL ADC_CHANNEL_4 +#define VIN_ADC2_CHANNEL ADC_CHANNEL_4 +#define KEY_A_Pin GPIO_PIN_0 +#define KEY_A_GPIO_Port GPIOB +#define PWM_Out_Pin GPIO_PIN_8 +#define PWM_Out_GPIO_Port GPIOB +#define PWM_Out_CHANNEL TIM_CHANNEL_3 // Timer 4; channel 3 +#define SCL2_Pin GPIO_PIN_6 +#define SCL2_GPIO_Port GPIOB +#define SDA2_Pin GPIO_PIN_7 +#define SDA2_GPIO_Port GPIOB +// Pin gets pulled high on movement +#define MOVEMENT_Pin GPIO_PIN_3 +#define MOVEMENT_GPIO_Port GPIOA + +#endif + +#ifdef MODEL_S60P + +#define KEY_B_Pin GPIO_PIN_1 +#define KEY_B_GPIO_Port GPIOB +#define TMP36_INPUT_Pin GPIO_PIN_5 +#define TMP36_INPUT_GPIO_Port GPIOA +#define TMP36_ADC1_CHANNEL ADC_CHANNEL_5 +#define TMP36_ADC2_CHANNEL ADC_CHANNEL_5 +#define TIP_TEMP_Pin GPIO_PIN_0 +#define TIP_TEMP_GPIO_Port GPIOA +#define TIP_TEMP_ADC1_CHANNEL ADC_CHANNEL_0 +#define TIP_TEMP_ADC2_CHANNEL ADC_CHANNEL_0 +#define VIN_Pin GPIO_PIN_4 +#define VIN_GPIO_Port GPIOA +#define VIN_ADC1_CHANNEL ADC_CHANNEL_4 +#define VIN_ADC2_CHANNEL ADC_CHANNEL_4 +#define KEY_A_Pin GPIO_PIN_0 +#define KEY_A_GPIO_Port GPIOB +#define PWM_Out_Pin GPIO_PIN_8 +#define PWM_Out_GPIO_Port GPIOB +#define PWM_Out_CHANNEL TIM_CHANNEL_3 // Timer 4; channel 3 +#define SCL2_Pin GPIO_PIN_6 +#define SCL2_GPIO_Port GPIOB +#define SDA2_Pin GPIO_PIN_7 +#define SDA2_GPIO_Port GPIOB +// Pin gets pulled high on movement +#define MOVEMENT_Pin GPIO_PIN_3 +#define MOVEMENT_GPIO_Port GPIOA + +#endif // MODEL_S60P + +#ifdef MODEL_T55 + +#define KEY_A_Pin GPIO_PIN_1 +#define KEY_A_GPIO_Port GPIOB +// No cold junction compensation as its a PT1000 +#define TIP_TEMP_Pin GPIO_PIN_5 +#define TIP_TEMP_GPIO_Port GPIOA +#define TIP_TEMP_ADC1_CHANNEL ADC_CHANNEL_5 +#define TIP_TEMP_ADC2_CHANNEL ADC_CHANNEL_5 + +#define VIN_Pin GPIO_PIN_4 +#define VIN_GPIO_Port GPIOA +#define VIN_ADC1_CHANNEL ADC_CHANNEL_4 +#define VIN_ADC2_CHANNEL ADC_CHANNEL_4 +#define KEY_B_Pin GPIO_PIN_0 +#define KEY_B_GPIO_Port GPIOB + +#define PWM_Out_Pin GPIO_PIN_8 +#define PWM_Out_GPIO_Port GPIOB +#define PWM_Out_CHANNEL TIM_CHANNEL_3 // Timer 4; channel 3 +#define SCL2_Pin GPIO_PIN_6 +#define SCL2_GPIO_Port GPIOB +#define SDA2_Pin GPIO_PIN_7 +#define SDA2_GPIO_Port GPIOB + +#endif // MODEL_T55 + +#endif /* BSP_MINIWARE_PINS_H_ */ diff --git a/source/Core/BSP/Sequre_S60/Power.cpp b/source/Core/BSP/Sequre/Power.cpp similarity index 100% rename from source/Core/BSP/Sequre_S60/Power.cpp rename to source/Core/BSP/Sequre/Power.cpp diff --git a/source/Core/BSP/Sequre_S60/README.md b/source/Core/BSP/Sequre/README.md similarity index 100% rename from source/Core/BSP/Sequre_S60/README.md rename to source/Core/BSP/Sequre/README.md diff --git a/source/Core/BSP/Sequre_S60/Setup.cpp b/source/Core/BSP/Sequre/Setup.cpp similarity index 89% rename from source/Core/BSP/Sequre_S60/Setup.cpp rename to source/Core/BSP/Sequre/Setup.cpp index 562ee2237..ee261a308 100644 --- a/source/Core/BSP/Sequre_S60/Setup.cpp +++ b/source/Core/BSP/Sequre/Setup.cpp @@ -14,10 +14,6 @@ ADC_HandleTypeDef hadc1; ADC_HandleTypeDef hadc2; DMA_HandleTypeDef hdma_adc1; -I2C_HandleTypeDef hi2c1; -DMA_HandleTypeDef hdma_i2c1_rx; -DMA_HandleTypeDef hdma_i2c1_tx; - IWDG_HandleTypeDef hiwdg; TIM_HandleTypeDef htim4; // Tip control TIM_HandleTypeDef htim2; // ADC Scheduling @@ -28,7 +24,6 @@ uint16_t ADCReadings[ADC_SAMPLES]; // Used to store the adc readings for the han // Functions static void SystemClock_Config(void); static void MX_ADC1_Init(void); -static void MX_I2C1_Init(void); static void MX_IWDG_Init(void); static void MX_TIM4_Init(void); // Tip control static void MX_TIM2_Init(void); // ADC Scheduling @@ -44,9 +39,6 @@ void Setup_HAL() { // These are not shared so no harm enabling __HAL_AFIO_REMAP_SWJ_NOJTAG(); -#ifdef SCL_Pin - MX_I2C1_Init(); -#endif MX_GPIO_Init(); MX_DMA_Init(); MX_ADC1_Init(); @@ -59,18 +51,21 @@ void Setup_HAL() { HAL_ADCEx_InjectedStart(&hadc1); // enable injected readings HAL_ADCEx_InjectedStart(&hadc2); // enable injected readings - // Setup movement pin +// Setup movement pin +#ifdef MOVEMENT_Pin { GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = MOVEMENT_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLDOWN; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; // We would like sharp rising edges + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(MOVEMENT_GPIO_Port, &GPIO_InitStruct); } +#endif } uint16_t getADCHandleTemp(uint8_t sample) { +#ifdef TMP36_ADC1_CHANNEL static history filter = {{0}, 0, 0}; if (sample) { uint32_t sum = 0; @@ -80,6 +75,9 @@ uint16_t getADCHandleTemp(uint8_t sample) { filter.update(sum); } return filter.average() >> 1; +#else + return 0; +#endif } uint16_t getADCVin(uint8_t sample) { @@ -173,13 +171,19 @@ static void MX_ADC1_Init(void) { hadc1.Init.NbrOfConversion = 1; HAL_ADC_Init(&hadc1); - /**Configure Regular Channel - */ +/**Configure Regular Channel + */ +#ifdef TMP36_ADC1_CHANNEL sConfig.Channel = TMP36_ADC1_CHANNEL; sConfig.Rank = ADC_REGULAR_RANK_1; sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5; HAL_ADC_ConfigChannel(&hadc1, &sConfig); - +#else + sConfig.Channel = VIN_ADC1_CHANNEL; // Filler + sConfig.Rank = ADC_REGULAR_RANK_1; + sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5; + HAL_ADC_ConfigChannel(&hadc1, &sConfig); +#endif /**Configure Injected Channel */ // F in = 10.66 MHz @@ -249,33 +253,6 @@ static void MX_ADC2_Init(void) { ; } } -/* I2C1 init function */ -static void MX_I2C1_Init(void) { - hi2c1.Instance = I2C1; - hi2c1.Init.ClockSpeed = 200000; - // OLED doesnt handle >100k when its asleep (off). - hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_16_9; - hi2c1.Init.OwnAddress1 = 0; - hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; - hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; - hi2c1.Init.OwnAddress2 = 0; - hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; - hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; - __HAL_I2C_DISABLE(&hi2c1); - - __HAL_RCC_I2C1_CLK_ENABLE(); - - // 13. Set SWRST bit in I2Cx_CR1 register. - hi2c1.Instance->CR1 |= 0x8000; - - asm("nop"); - - // 14. Clear SWRST bit in I2Cx_CR1 register. - hi2c1.Instance->CR1 &= ~0x8000; - - HAL_I2C_Init(&hi2c1); - unstick_I2C(); -} /* IWDG init function */ static void MX_IWDG_Init(void) { @@ -289,23 +266,20 @@ static void MX_IWDG_Init(void) { static void MX_TIM4_Init(void) { /* - * We use the channel 1 to trigger the ADC at end of PWM period - * And we use the channel 4 as the PWM modulation source using Interrupts + * On Sequre devies we run the output PWM as fast as possible due to the low tip resistance + no inductor for filtering. + * So we run it as fast as we can and hope that the caps filter out the current spikes. * */ TIM_ClockConfigTypeDef sClockSourceConfig; TIM_MasterConfigTypeDef sMasterConfig; TIM_OC_InitTypeDef sConfigOC; memset(&sConfigOC, 0, sizeof(sConfigOC)); - // Timer 2 is fairly slow as its being used to run the PWM and trigger the ADC - // in the PWM off time. + htim4.Instance = TIM4; // dummy value, will be reconfigured by BSPInit() - htim4.Init.Prescaler = 10; // 2 MHz timer clock/1000 = 2 kHz tick rate + htim4.Init.Prescaler = 10; // 2 MHz timer clock/10 = 200 kHz tick rate - // pwm out is 10k from tim3, we want to run our PWM at around 10hz or slower on the output stage - // These values give a rate of around 3.5 Hz for "fast" mode and 1.84 Hz for "slow" htim4.Init.CounterMode = TIM_COUNTERMODE_UP; - htim4.Init.Period = 255; + htim4.Init.Period = 64; htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; // 8 MHz (x2 APB1) before divide htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; @@ -345,6 +319,9 @@ static void MX_TIM2_Init(void) { TIM_ClockConfigTypeDef sClockSourceConfig; TIM_MasterConfigTypeDef sMasterConfig; TIM_OC_InitTypeDef sConfigOC; + memset(&sConfigOC, 0, sizeof(sConfigOC)); + memset(&sClockSourceConfig, 0, sizeof(sClockSourceConfig)); + memset(&sMasterConfig, 0, sizeof(sMasterConfig)); // Timer 2 is fairly slow as its being used to run the PWM and trigger the ADC // in the PWM off time. @@ -445,8 +422,8 @@ static void MX_GPIO_Init(void) { GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_15; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 - | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15; + GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 | + GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pins : KEY_B_Pin KEY_A_Pin */ diff --git a/source/Core/BSP/Sequre_S60/Setup.h b/source/Core/BSP/Sequre/Setup.h similarity index 82% rename from source/Core/BSP/Sequre_S60/Setup.h rename to source/Core/BSP/Sequre/Setup.h index 654dfb3c2..4ebcd24dd 100644 --- a/source/Core/BSP/Sequre_S60/Setup.h +++ b/source/Core/BSP/Sequre/Setup.h @@ -18,10 +18,6 @@ extern ADC_HandleTypeDef hadc1; extern ADC_HandleTypeDef hadc2; extern DMA_HandleTypeDef hdma_adc1; -extern DMA_HandleTypeDef hdma_i2c1_rx; -extern DMA_HandleTypeDef hdma_i2c1_tx; -extern I2C_HandleTypeDef hi2c1; - extern IWDG_HandleTypeDef hiwdg; extern TIM_HandleTypeDef htim4; diff --git a/source/Core/BSP/Sequre_S60/Software_I2C.h b/source/Core/BSP/Sequre/Software_I2C.h similarity index 93% rename from source/Core/BSP/Sequre_S60/Software_I2C.h rename to source/Core/BSP/Sequre/Software_I2C.h index 65a51fad2..d80bbfcb4 100644 --- a/source/Core/BSP/Sequre_S60/Software_I2C.h +++ b/source/Core/BSP/Sequre/Software_I2C.h @@ -18,12 +18,14 @@ #define SOFT_SDA2_LOW() HAL_GPIO_WritePin(SDA2_GPIO_Port, SDA2_Pin, GPIO_PIN_RESET) #define SOFT_SDA2_READ() (HAL_GPIO_ReadPin(SDA2_GPIO_Port, SDA2_Pin) == GPIO_PIN_SET ? 1 : 0) #define SOFT_SCL2_READ() (HAL_GPIO_ReadPin(SCL2_GPIO_Port, SCL2_Pin) == GPIO_PIN_SET ? 1 : 0) +// clang-format off #define SOFT_I2C_DELAY() \ { \ for (int xx = 0; xx < 12; xx++) { \ asm("nop"); \ } \ } +// clang-format on #endif // 40 ~= 100kHz; 15 gives around 250kHz or so which is fast _and_ stable diff --git a/source/Core/BSP/Sequre/Startup/startup_stm32f103t8ux.S b/source/Core/BSP/Sequre/Startup/startup_stm32f103t8ux.S new file mode 100644 index 000000000..f8d1c8ed7 --- /dev/null +++ b/source/Core/BSP/Sequre/Startup/startup_stm32f103t8ux.S @@ -0,0 +1,344 @@ +/** + ****************************************************************************** + * @file startup_stm32.s + * @author Ac6 + * @version V1.0.0 + * @date 12-June-2014 + ****************************************************************************** + */ + + .syntax unified + .cpu cortex-m3 + .thumb + +.global g_pfnVectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _sidata +/* start address for the .data section. defined in linker script */ +.word _sdata +/* end address for the .data section. defined in linker script */ +.word _edata +/* start address for the .bss section. defined in linker script */ +.word _sbss +/* end address for the .bss section. defined in linker script */ +.word _ebss + +.equ BootRAM, 0xF1E0F85F +/** + * @brief This is the code that gets called when the processor first + * starts execution following a reset event. Only the absolutely + * necessary set is performed, after which the application + * supplied main() routine is called. + * @param None + * @retval : None +*/ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +Reset_Handler: + +/* Copy the data segment initializers from flash to SRAM */ + movs r1, #0 + b LoopCopyDataInit + +CopyDataInit: + ldr r3, =_sidata + ldr r3, [r3, r1] + str r3, [r0, r1] + adds r1, r1, #4 + +LoopCopyDataInit: + ldr r0, =_sdata + ldr r3, =_edata + adds r2, r0, r1 + cmp r2, r3 + bcc CopyDataInit + ldr r2, =_sbss + b LoopFillZerobss +/* Zero fill the bss segment. */ +FillZerobss: + movs r3, #0 + str r3, [r2] + adds r2, r2, #4 + +LoopFillZerobss: + ldr r3, = _ebss + cmp r2, r3 + bcc FillZerobss + +/* Call the clock system intitialization function.*/ + bl SystemInit +/* Call static constructors */ + bl __libc_init_array +/* Call the application's entry point.*/ + bl main + +LoopForever: + b LoopForever + +.size Reset_Handler, .-Reset_Handler + +/** + * @brief This is the code that gets called when the processor receives an + * unexpected interrupt. This simply enters an infinite loop, preserving + * the system state for examination by a debugger. + * + * @param None + * @retval : None +*/ + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +/****************************************************************************** +* +* The minimal vector table for a Cortex-M. Note that the proper constructs +* must be placed on this to ensure that it ends up at physical address +* 0x0000.0000. +* +******************************************************************************/ + .section .isr_vector,"a",%progbits + .type g_pfnVectors, %object + .size g_pfnVectors, .-g_pfnVectors + +g_pfnVectors: + .word _estack + .word Reset_Handler + .word NMI_Handler + .word HardFault_Handler + .word MemManage_Handler + .word BusFault_Handler + .word UsageFault_Handler + .word 0 + .word 0 + .word 0 + .word 0 + .word SVC_Handler + .word DebugMon_Handler + .word 0 + .word PendSV_Handler + .word SysTick_Handler + .word WWDG_IRQHandler + .word PVD_IRQHandler + .word TAMPER_IRQHandler + .word RTC_IRQHandler + .word FLASH_IRQHandler + .word RCC_IRQHandler + .word EXTI0_IRQHandler + .word EXTI1_IRQHandler + .word EXTI2_IRQHandler + .word EXTI3_IRQHandler + .word EXTI4_IRQHandler + .word DMA1_Channel1_IRQHandler + .word DMA1_Channel2_IRQHandler + .word DMA1_Channel3_IRQHandler + .word DMA1_Channel4_IRQHandler + .word DMA1_Channel5_IRQHandler + .word DMA1_Channel6_IRQHandler + .word DMA1_Channel7_IRQHandler + .word ADC1_2_IRQHandler + .word USB_HP_CAN1_TX_IRQHandler + .word USB_LP_CAN1_RX0_IRQHandler + .word CAN1_RX1_IRQHandler + .word CAN1_SCE_IRQHandler + .word EXTI9_5_IRQHandler + .word TIM1_BRK_IRQHandler + .word TIM1_UP_IRQHandler + .word TIM1_TRG_COM_IRQHandler + .word TIM1_CC_IRQHandler + .word TIM2_IRQHandler + .word TIM3_IRQHandler + .word TIM4_IRQHandler + .word I2C1_EV_IRQHandler + .word I2C1_ER_IRQHandler + .word I2C2_EV_IRQHandler + .word I2C2_ER_IRQHandler + .word SPI1_IRQHandler + .word SPI2_IRQHandler + .word USART1_IRQHandler + .word USART2_IRQHandler + .word USART3_IRQHandler + .word EXTI15_10_IRQHandler + .word RTC_Alarm_IRQHandler + .word USBWakeUp_IRQHandler + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word BootRAM /* @0x108. This is for boot in RAM mode for + STM32F10x Medium Density devices. */ + +/******************************************************************************* +* +* Provide weak aliases for each Exception handler to the Default_Handler. +* As they are weak aliases, any function with the same name will override +* this definition. +* +*******************************************************************************/ + + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDG_IRQHandler + .thumb_set WWDG_IRQHandler,Default_Handler + + .weak PVD_IRQHandler + .thumb_set PVD_IRQHandler,Default_Handler + + .weak TAMPER_IRQHandler + .thumb_set TAMPER_IRQHandler,Default_Handler + + .weak RTC_IRQHandler + .thumb_set RTC_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCC_IRQHandler + .thumb_set RCC_IRQHandler,Default_Handler + + .weak EXTI0_IRQHandler + .thumb_set EXTI0_IRQHandler,Default_Handler + + .weak EXTI1_IRQHandler + .thumb_set EXTI1_IRQHandler,Default_Handler + + .weak EXTI2_IRQHandler + .thumb_set EXTI2_IRQHandler,Default_Handler + + .weak EXTI3_IRQHandler + .thumb_set EXTI3_IRQHandler,Default_Handler + + .weak EXTI4_IRQHandler + .thumb_set EXTI4_IRQHandler,Default_Handler + + .weak DMA1_Channel1_IRQHandler + .thumb_set DMA1_Channel1_IRQHandler,Default_Handler + + .weak DMA1_Channel2_IRQHandler + .thumb_set DMA1_Channel2_IRQHandler,Default_Handler + + .weak DMA1_Channel3_IRQHandler + .thumb_set DMA1_Channel3_IRQHandler,Default_Handler + + .weak DMA1_Channel4_IRQHandler + .thumb_set DMA1_Channel4_IRQHandler,Default_Handler + + .weak DMA1_Channel5_IRQHandler + .thumb_set DMA1_Channel5_IRQHandler,Default_Handler + + .weak DMA1_Channel6_IRQHandler + .thumb_set DMA1_Channel6_IRQHandler,Default_Handler + + .weak DMA1_Channel7_IRQHandler + .thumb_set DMA1_Channel7_IRQHandler,Default_Handler + + .weak ADC1_2_IRQHandler + .thumb_set ADC1_2_IRQHandler,Default_Handler + + .weak USB_HP_CAN1_TX_IRQHandler + .thumb_set USB_HP_CAN1_TX_IRQHandler,Default_Handler + + .weak USB_LP_CAN1_RX0_IRQHandler + .thumb_set USB_LP_CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EXTI9_5_IRQHandler + .thumb_set EXTI9_5_IRQHandler,Default_Handler + + .weak TIM1_BRK_IRQHandler + .thumb_set TIM1_BRK_IRQHandler,Default_Handler + + .weak TIM1_UP_IRQHandler + .thumb_set TIM1_UP_IRQHandler,Default_Handler + + .weak TIM1_TRG_COM_IRQHandler + .thumb_set TIM1_TRG_COM_IRQHandler,Default_Handler + + .weak TIM1_CC_IRQHandler + .thumb_set TIM1_CC_IRQHandler,Default_Handler + + .weak TIM2_IRQHandler + .thumb_set TIM2_IRQHandler,Default_Handler + + .weak TIM3_IRQHandler + .thumb_set TIM3_IRQHandler,Default_Handler + + .weak TIM4_IRQHandler + .thumb_set TIM4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EXTI15_10_IRQHandler + .thumb_set EXTI15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak USBWakeUp_IRQHandler + .thumb_set USBWakeUp_IRQHandler,Default_Handler + + +/************************ (C) COPYRIGHT Ac6 *****END OF FILE****/ diff --git a/source/Core/BSP/Sequre/ThermoModel.cpp b/source/Core/BSP/Sequre/ThermoModel.cpp new file mode 100644 index 000000000..8e49b9856 --- /dev/null +++ b/source/Core/BSP/Sequre/ThermoModel.cpp @@ -0,0 +1,85 @@ +/* + * ThermoModel.cpp + * + * Created on: 1 May 2021 + * Author: Ralim + */ +#include "TipThermoModel.h" +#include "Utils.hpp" +#include "configuration.h" + +#ifdef TEMP_uV_LOOKUP_PT1000 +// Use https://br.flukecal.com/pt100-table-generator to make table for resistance to temp +const int32_t ohmsToDegC[] = { + // + // Resistance (ohms x10) Temperature (Celsius) + + 10000, 0, // + 10390, 10, // + 10779, 20, // + 11167, 30, // + 11554, 40, // + 11940, 50, // + 12324, 60, // + 12708, 70, // + 13090, 80, // + 13471, 90, // + 13851, 100, // + 14229, 110, // + 14607, 120, // + 14983, 130, // + 15358, 140, // + 15733, 150, // + 16105, 160, // + 16477, 170, // + 16848, 180, // + 17217, 190, // + 17586, 200, // + 17953, 210, // + 18319, 220, // + 18684, 230, // + 19047, 240, // + 19410, 250, // + 19771, 260, // + 20131, 270, // + 20490, 280, // + 20848, 290, // + 21205, 300, // + 21561, 310, // + 21915, 320, // + 22268, 330, // + 22621, 340, // + 22972, 350, // + 23321, 360, // + 23670, 370, // + 24018, 380, // + 24364, 390, // + 24709, 400, // + 25053, 410, // + 25396, 420, // + 25738, 430, // + 26078, 440, // + 26418, 450, // + 26756, 460, // + 27093, 470, // + 27429, 480, // + 27764, 490, // + 28098, 500, // + +}; + +TemperatureType_t TipThermoModel::convertuVToDegC(uint32_t tipuVDelta) { + + // 3.3V -> 1K ->(ADC) <- PT1000 <- GND + // PT100 = (adc*r1)/(3.3V-adc) + uint32_t reading_mv = tipuVDelta / 1000; + uint32_t resistance_x10 = (reading_mv * 10000) / (3300 - reading_mv); + + return Utils::InterpolateLookupTable(ohmsToDegC, sizeof(ohmsToDegC) / (2 * sizeof(int32_t)), resistance_x10); +} + +#endif // TEMP_uV_LOOKUP_PT1000 + +#ifdef TEMP_uV_LOOKUP_S60 +TemperatureType_t TipThermoModel::convertuVToDegC(uint32_t tipuVDelta) { return (tipuVDelta * 50) / 485; } +#endif // TEMP_uV_LOOKUP_S60 diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Device/ST/STM32F1xx/Include/stm32f103xb.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Device/ST/STM32F1xx/Include/stm32f103xb.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Device/ST/STM32F1xx/Include/stm32f103xb.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Device/ST/STM32F1xx/Include/stm32f103xb.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Device/ST/STM32F1xx/Include/stm32f1xx.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Device/ST/STM32F1xx/Include/stm32f1xx.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Device/ST/STM32F1xx/Include/stm32f1xx.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Device/ST/STM32F1xx/Include/stm32f1xx.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Device/ST/STM32F1xx/Include/system_stm32f1xx.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Device/ST/STM32F1xx/Include/system_stm32f1xx.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Device/ST/STM32F1xx/Include/system_stm32f1xx.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Device/ST/STM32F1xx/Include/system_stm32f1xx.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/arm_common_tables.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/arm_common_tables.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/arm_common_tables.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/arm_common_tables.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/arm_const_structs.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/arm_const_structs.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/arm_const_structs.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/arm_const_structs.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/arm_math.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/arm_math.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/arm_math.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/arm_math.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/cmsis_armcc.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/cmsis_armcc.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/cmsis_armcc.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/cmsis_armcc.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/cmsis_armcc_V6.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/cmsis_armcc_V6.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/cmsis_armcc_V6.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/cmsis_armcc_V6.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/cmsis_gcc.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/cmsis_gcc.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/cmsis_gcc.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/cmsis_gcc.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cm0.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cm0.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cm0.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cm0.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cm0plus.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cm0plus.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cm0plus.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cm0plus.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cm3.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cm3.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cm3.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cm3.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cm4.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cm4.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cm4.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cm4.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cm7.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cm7.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cm7.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cm7.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cmFunc.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cmFunc.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cmFunc.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cmFunc.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cmInstr.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cmInstr.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cmInstr.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cmInstr.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cmSimd.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cmSimd.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_cmSimd.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_cmSimd.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_sc000.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_sc000.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_sc000.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_sc000.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_sc300.h b/source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_sc300.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/CMSIS/Include/core_sc300.h rename to source/Core/BSP/Sequre/Vendor/CMSIS/Include/core_sc300.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/Legacy/stm32_hal_legacy.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/Legacy/stm32_hal_legacy.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/Legacy/stm32_hal_legacy.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/Legacy/stm32_hal_legacy.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_adc.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_adc.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_adc.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_adc.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_adc_ex.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_adc_ex.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_adc_ex.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_adc_ex.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_cortex.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_cortex.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_cortex.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_cortex.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_def.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_def.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_def.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_def.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_dma.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_dma.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_dma.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_dma.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_dma_ex.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_dma_ex.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_dma_ex.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_dma_ex.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_flash.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_flash.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_flash.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_flash.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_flash_ex.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_flash_ex.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_flash_ex.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_flash_ex.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_gpio.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_gpio.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_gpio.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_gpio.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_gpio_ex.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_gpio_ex.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_gpio_ex.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_gpio_ex.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_i2c.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_iwdg.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_iwdg.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_iwdg.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_iwdg.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_pwr.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_pwr.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_pwr.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_pwr.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_rcc.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_rcc.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_rcc.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_rcc.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_rcc_ex.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_rcc_ex.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_rcc_ex.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_rcc_ex.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_tim.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_tim.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_tim.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_tim.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_tim_ex.h b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_tim_ex.h similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_tim_ex.h rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_tim_ex.h diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c similarity index 96% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c index cb32ffdf1..8725243aa 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c +++ b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c @@ -155,8 +155,8 @@ HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT; /* 1KHz */ HAL_StatusTypeDef HAL_Init(void) { /* Configure Flash prefetch */ #if (PREFETCH_ENABLE != 0) -#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) \ - || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) +#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) || \ + defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) /* Prefetch buffer is not available on value line devices */ __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); @@ -352,7 +352,8 @@ __weak void HAL_Delay(uint32_t Delay) { wait += (uint32_t)(uwTickFreq); } - while ((HAL_GetTick() - tickstart) < wait) {} + while ((HAL_GetTick() - tickstart) < wait) { + } } /** diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c similarity index 97% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c index f29ea6c51..19ac9e7db 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c +++ b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c @@ -555,12 +555,12 @@ HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_JEOC | ADC_FLAG_EOC | ADC_FLAG_JSTRT | ADC_FLAG_STRT)); /* Reset register CR1 */ - CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | ADC_CR1_AWDIE - | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); + CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | + ADC_CR1_AWDIE | ADC_CR1_EOCIE | ADC_CR1_AWDCH)); /* Reset register CR2 */ - CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA - | ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); + CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA | + ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON)); /* Reset register SMPR1 */ CLEAR_BIT(hadc->Instance->SMPR1, (ADC_SMPR1_SMP17 | ADC_SMPR1_SMP16 | ADC_SMPR1_SMP15 | ADC_SMPR1_SMP14 | ADC_SMPR1_SMP13 | ADC_SMPR1_SMP12 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP10)); @@ -1194,7 +1194,6 @@ HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, ui /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; - /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ /* start (in case of SW start): */ @@ -1352,7 +1351,6 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { } } - /* Clear regular group conversion flag */ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_STRT | ADC_FLAG_EOC); } @@ -1393,12 +1391,8 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JSTRT | ADC_FLAG_JEOC)); } } - - } - - /** * @} */ @@ -1438,7 +1432,7 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) { * @retval HAL status */ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConfTypeDef *sConfig) { - HAL_StatusTypeDef tmp_hal_status = HAL_OK; + HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -1472,8 +1466,6 @@ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConf MODIFY_REG(hadc->Instance->SMPR2, ADC_SMPR2(ADC_SMPR2_SMP0, sConfig->Channel), ADC_SMPR2(sConfig->SamplingTime, sConfig->Channel)); } - - /* Process unlocked */ __HAL_UNLOCK(hadc); @@ -1503,8 +1495,8 @@ HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDG assert_param(IS_ADC_RANGE(AnalogWDGConfig->HighThreshold)); assert_param(IS_ADC_RANGE(AnalogWDGConfig->LowThreshold)); - if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) - || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { + if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) || + (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) { assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel)); } @@ -1712,11 +1704,6 @@ void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma) { } } - - - - - /** * @} */ diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c similarity index 97% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c index dc2e20e8a..03c947f34 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c +++ b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c @@ -661,7 +661,6 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef *hadc, uint32_t /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; - /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ /* start (in case of SW start): */ @@ -899,7 +898,7 @@ __weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc) { * @retval None */ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_InjectionConfTypeDef *sConfigInjected) { - HAL_StatusTypeDef tmp_hal_status = HAL_OK; + HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -964,8 +963,8 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I ADC_JSQR_JL | ADC_JSQR_RK_JL(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion), - ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) - | ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); + ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) | + ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion)); } else { /* Clear the old SQx bits for the selected rank */ MODIFY_REG(hadc->Instance->JSQR, @@ -1028,9 +1027,6 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I MODIFY_REG(hadc->Instance->SMPR2, ADC_SMPR2(ADC_SMPR2_SMP0, sConfigInjected->InjectedChannel), ADC_SMPR2(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel)); } - - - /* Configure the offset: offset enable/disable, InjectedChannel, offset value */ switch (sConfigInjected->InjectedRank) { case 1: @@ -1051,7 +1047,6 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_I break; } - /* Process unlocked */ __HAL_UNLOCK(hadc); diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c similarity index 95% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c index e1f9b4e4a..b973ec025 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c +++ b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c @@ -321,9 +321,9 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) { assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); MPU->RBAR = MPU_Init->BaseAddress; - MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) - | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) - | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); + MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | + ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | + ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } else { MPU->RBAR = 0x00U; MPU->RASR = 0x00U; diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c similarity index 96% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c index 5d46145df..d21cfac8d 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c +++ b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c @@ -198,7 +198,7 @@ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) { tmp = hdma->Instance->CCR; /* Clear PL, MSIZE, PSIZE, MINC, PINC, CIRC and DIR bits */ - tmp &= ((uint32_t) ~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | DMA_CCR_DIR)); + tmp &= ((uint32_t)~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | DMA_CCR_DIR)); /* Prepare the DMA Channel configuration */ tmp |= hdma->Init.Direction | hdma->Init.PeriphInc | hdma->Init.MemInc | hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment | hdma->Init.Mode | hdma->Init.Priority; diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash.c similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash.c diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash_ex.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash_ex.c similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash_ex.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash_ex.c diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio.c similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio.c diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio_ex.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio_ex.c similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio_ex.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio_ex.c diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c similarity index 97% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c index 5dd8b7c77..2c38ddb99 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c +++ b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c @@ -956,8 +956,6 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData /* Clear ADDR flag */ __HAL_I2C_CLEAR_ADDRFLAG(hi2c); - - while (hi2c->XferSize > 0U) { /* Wait until TXE flag is set */ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) { @@ -3183,8 +3181,8 @@ void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) { tmp2 = hi2c->XferCount; tmp3 = hi2c->State; tmp4 = hi2c->PreviousState; - if ((tmp1 == HAL_I2C_MODE_SLAVE) && (tmp2 == 0U) - && ((tmp3 == HAL_I2C_STATE_BUSY_TX) || (tmp3 == HAL_I2C_STATE_BUSY_TX_LISTEN) || ((tmp3 == HAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX)))) { + if ((tmp1 == HAL_I2C_MODE_SLAVE) && (tmp2 == 0U) && + ((tmp3 == HAL_I2C_STATE_BUSY_TX) || (tmp3 == HAL_I2C_STATE_BUSY_TX_LISTEN) || ((tmp3 == HAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX)))) { } else { hi2c->ErrorCode |= HAL_I2C_ERROR_AF; @@ -3717,7 +3715,6 @@ static HAL_StatusTypeDef I2C_Master_SB(I2C_HandleTypeDef *hi2c) { return HAL_OK; } - /** * @brief Handle ADDR flag for Master * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains @@ -3963,7 +3960,6 @@ static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_ /* Send slave address */ hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress); } - /* Wait until ADDR flag is set */ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { @@ -4012,7 +4008,6 @@ static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t /* Send slave address */ hi2c->Instance->DR = I2C_7BIT_ADD_READ(DevAddress); } - /* Wait until ADDR flag is set */ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) { diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_iwdg.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_iwdg.c similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_iwdg.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_iwdg.c diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_pwr.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_pwr.c similarity index 100% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_pwr.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_pwr.c diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c similarity index 97% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c index e56f9cbd0..56515b0b9 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c +++ b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c @@ -360,8 +360,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue)); /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */ - if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) - || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { + if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) || + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) { /* When HSI is used as system clock it will not disabled */ if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) { return HAL_ERROR; @@ -416,8 +416,8 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { if ((RCC_OscInitStruct->PLL2.PLL2State) != RCC_PLL2_NONE) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { if ((RCC_OscInitStruct->PLL2.PLL2State) == RCC_PLL2_ON) { diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c similarity index 95% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c index d700f0cab..25e902fa0 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c +++ b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c @@ -470,8 +470,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -490,8 +490,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* Check if PLLI2S is enabled */ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -670,8 +670,8 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Check the parameters */ @@ -730,8 +730,8 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void) { /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ - if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) - && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { + if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && + ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) { return HAL_ERROR; } else { /* Disable the main PLL2. */ diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c similarity index 96% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c index 2fc30fd6f..31a02a5cf 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c +++ b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c @@ -2450,8 +2450,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t Outpu UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2541,8 +2541,8 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t Ou UNUSED(OutputChannel); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -2874,8 +2874,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channe TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -2997,8 +2997,8 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Cha TIM_CHANNEL_N_STATE_SET(htim, TIM_CHANNEL_2, HAL_TIM_CHANNEL_STATE_BUSY); } } else { - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } else { TIM_CHANNEL_STATE_SET(htim, TIM_CHANNEL_1, HAL_TIM_CHANNEL_STATE_BUSY); @@ -3142,11 +3142,11 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Ch return HAL_ERROR; } } else { - if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) - || (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { + if ((channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || (channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY) || (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_BUSY) || + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_BUSY)) { return HAL_BUSY; - } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) - && (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { + } else if ((channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && (channel_2_state == HAL_TIM_CHANNEL_STATE_READY) && (complementary_channel_1_state == HAL_TIM_CHANNEL_STATE_READY) && + (complementary_channel_2_state == HAL_TIM_CHANNEL_STATE_READY)) { if ((((pData1 == NULL) || (pData2 == NULL))) && (Length > 0U)) { return HAL_ERROR; } else { diff --git a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c similarity index 96% rename from source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c rename to source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c index 9d6123bf2..87f66c3fd 100644 --- a/source/Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c +++ b/source/Core/BSP/Sequre/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c @@ -311,8 +311,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } @@ -382,8 +382,8 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) { assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(htim->Instance)); /* Check the TIM channels state */ - if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) - || (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { + if ((channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || (channel_2_state != HAL_TIM_CHANNEL_STATE_READY) || (complementary_channel_1_state != HAL_TIM_CHANNEL_STATE_READY) || + (complementary_channel_2_state != HAL_TIM_CHANNEL_STATE_READY)) { return HAL_ERROR; } diff --git a/source/Core/BSP/Sequre/configuration.h b/source/Core/BSP/Sequre/configuration.h new file mode 100644 index 000000000..df06f68ef --- /dev/null +++ b/source/Core/BSP/Sequre/configuration.h @@ -0,0 +1,275 @@ +#ifndef CONFIGURATION_H_ +#define CONFIGURATION_H_ +#include +/** + * Configuration.h + * Define here your default pre settings for S60 + * + */ + +//=========================================================================== +//============================= Default Settings ============================ +//=========================================================================== +/** + * Default soldering temp is 320.0 C + * Temperature the iron sleeps at - default 150.0 C + */ + +#define SLEEP_TEMP 150 // Default sleep temperature +#define BOOST_TEMP 420 // Default boost temp. +#define BOOST_MODE_ENABLED 1 // 0: Disable 1: Enable + +/** + * OLED Brightness + * + */ +#define MIN_BRIGHTNESS 1 // Min OLED brightness selectable +#define MAX_BRIGHTNESS 101 // Max OLED brightness selectable +#define BRIGHTNESS_STEP 25 // OLED brightness increment +#define DEFAULT_BRIGHTNESS 25 // default OLED brightness + +/** + * Blink the temperature on the cooling screen when its > 50C + */ +#define COOLING_TEMP_BLINK 0 // 0: Disable 1: Enable + +/** + * How many seconds/minutes we wait until going to sleep/shutdown. + * Values -> SLEEP_TIME * 10; i.e. 5*10 = 50 Seconds! + */ +#define SLEEP_TIME 5 // x10 Seconds +#define SHUTDOWN_TIME 10 // Minutes + +/** + * Auto start off for safety. + * Pissible values are: + * 0 - none + * 1 - Soldering Temperature + * 2 - Sleep Temperature + * 3 - Sleep Off Temperature + */ +#define AUTO_START_MODE 0 // Default to none + +/** + * Locking Mode + * When in soldering mode a long press on both keys toggle the lock of the buttons + * Possible values are: + * 0 - Desactivated + * 1 - Lock except boost + * 2 - Full lock + */ +#define LOCKING_MODE 0 // Default to desactivated for safety + +/** + * OLED Orientation + * + */ +#define ORIENTATION_MODE 0 // 0: Right 1:Left (2:Automatic N/A) +#define MAX_ORIENTATION_MODE 1 // Disable auto mode +#define REVERSE_BUTTON_TEMP_CHANGE 0 // 0:Default 1:Reverse - Reverse the plus and minus button assigment for temperature change + +/** + * Temp change settings + */ +#define TEMP_CHANGE_SHORT_STEP 1 // Default temp change short step +1 +#define TEMP_CHANGE_LONG_STEP 10 // Default temp change long step +10 +#define TEMP_CHANGE_SHORT_STEP_MAX 50 // Temp change short step MAX value +#define TEMP_CHANGE_LONG_STEP_MAX 90 // Temp change long step MAX value + +/* Power pulse for keeping power banks awake*/ +#define POWER_PULSE_INCREMENT 1 +#define POWER_PULSE_MAX 100 // x10 max watts +#define POWER_PULSE_WAIT_MAX 9 // 9*2.5s = 22.5 seconds +#define POWER_PULSE_DURATION_MAX 9 // 9*250ms = 2.25 seconds + +#define POWER_PULSE_DEFAULT 0 +#define POWER_PULSE_WAIT_DEFAULT 4 // Default rate of the power pulse: 4*2500 = 10000 ms = 10 s +#define POWER_PULSE_DURATION_DEFAULT 1 // Default duration of the power pulse: 1*250 = 250 ms + +/** + * OLED Orientation Sensitivity on Automatic mode! + * Motion Sensitivity <0=Off 1=Least Sensitive 9=Most Sensitive> + */ +#define SENSITIVITY 7 // Default 7 + +/** + * Detailed soldering screen + * Detailed idle screen (off for first time users) + */ +#define DETAILED_SOLDERING 0 // 0: Disable 1: Enable - Default 0 +#define DETAILED_IDLE 0 // 0: Disable 1: Enable - Default 0 + +#define CUT_OUT_SETTING 0 // default to no cut-off voltage +#define RECOM_VOL_CELL 33 // Minimum voltage per cell (Recommended 3.3V (33)) +#define TEMPERATURE_INF 0 // default to 0 +#define DESCRIPTION_SCROLL_SPEED 0 // 0: Slow 1: Fast - default to slow +#define ANIMATION_LOOP 1 // 0: off 1: on +#define ANIMATION_SPEED settingOffSpeed_t::MEDIUM + +// Op-amp gain +// First stage has a gain of 10.31, followed by gain of 52; so total gain is 536 + +#define ADC_MAX_READING (4096 * 8) // Maximum reading of the adc +#define ADC_VDD_MV 3300 // ADC max reading millivolts + +// Deriving the Voltage div: +// Vin_max = (3.3*(r1+r2))/(r2) +// vdiv = (32768*4)/(vin_max*10) + +#if defined(MODEL_S60) + defined(MODEL_S60P) + defined(MODEL_T55) == 0 +#error "No model defined!" +#endif + +#define NEEDS_VBUS_PROBE 0 + +#ifdef MODEL_S60 +#define VOLTAGE_DIV 460 // Default divider scaler +#define CALIBRATION_OFFSET 200 // Default adc offset in uV +#define PID_POWER_LIMIT 70 // Sets the max pwm power limit +#define POWER_LIMIT 0 // 0 watts default limit +#define MAX_POWER_LIMIT 70 +#define POWER_LIMIT_STEPS 5 +#define OP_AMP_GAIN_STAGE 536 +#define TEMP_uV_LOOKUP_S60 +#define USB_PD_VMAX 12 // Maximum voltage for PD to negotiate +#define THERMAL_RUNAWAY_TIME_SEC 20 +#define THERMAL_RUNAWAY_TEMP_C 3 + +#define HARDWARE_MAX_WATTAGE_X10 600 + +#define TIP_THERMAL_MASS 10 // X10 watts to raise 1 deg C in 1 second +#define TIP_THERMAL_INERTIA 128 // We use a large inertia value to smooth out the drive to the tip since its stupidly sensitive + +#define TIP_RESISTANCE 20 //(actually 2.5 ish but we need to be more conservative on pwm'ing watt limit) x10 ohms + +#define OLED_128x32 +#define GPIO_VIBRATION +#define POW_PD_EXT 1 +#define USB_PD_EPR_WATTAGE 0 /*No EPR*/ +#define DEBUG_POWER_MENU_BUTTON_B 1 +#define HAS_POWER_DEBUG_MENU +#define TEMP_NTC +#define I2C_SOFT_BUS_2 // For now we are doing software I2C to get around hardware chip issues +#define OLED_I2CBB2 +#define FILTER_DISPLAYED_TIP_TEMP 4 // Filtering for GUI display + +#define MODEL_HAS_DCDC // We dont have DC/DC but have reallly fast PWM that gets us roughly the same place +#endif /* S60 */ + +#ifdef MODEL_S60P +#define VOLTAGE_DIV 460 // Default divider scaler +#define CALIBRATION_OFFSET 200 // Default adc offset in uV +#define PID_POWER_LIMIT 70 // Sets the max pwm power limit +#define POWER_LIMIT 0 // 0 watts default limit +#define MAX_POWER_LIMIT 70 +#define POWER_LIMIT_STEPS 5 +#define OP_AMP_GAIN_STAGE 536 +#define TEMP_uV_LOOKUP_S60 +#define USB_PD_VMAX 20 // Maximum voltage for PD to negotiate +#define THERMAL_RUNAWAY_TIME_SEC 20 +#define THERMAL_RUNAWAY_TEMP_C 3 + +#define HARDWARE_MAX_WATTAGE_X10 600 + +#define TIP_THERMAL_MASS 10 // X10 watts to raise 1 deg C in 1 second +#define TIP_THERMAL_INERTIA 128 // We use a large inertia value to smooth out the drive to the tip since its stupidly sensitive + +#define TIP_RESISTANCE 20 //(actually 2.5 ish but we need to be more conservative on pwm'ing watt limit) x10 ohms + +#define OLED_128x32 +#define GPIO_VIBRATION +#define POW_PD_EXT 2 +#define USB_PD_EPR_WATTAGE 0 /*No EPR*/ +#define DEBUG_POWER_MENU_BUTTON_B 1 +#define HAS_POWER_DEBUG_MENU +#define TEMP_NTC +#define I2C_SOFT_BUS_2 // For now we are doing software I2C to get around hardware chip issues +#define OLED_I2CBB2 +#define FILTER_DISPLAYED_TIP_TEMP 4 // Filtering for GUI display + +#define MODEL_HAS_DCDC // We dont have DC/DC but have reallly fast PWM that gets us roughly the same place +#endif /* S60P */ + +#ifdef MODEL_T55 +// T55 Hotplate is similar to Project-Argon, PCB heater + PT100 sensor but no current rolloff compensation +// Uses a HUB238 for PD negotiation like the S60, also has a buzzer. Feels like designed to share with S60 +// Hold back left button for "DFU" + +#define SOLDERING_TEMP 200 // Default soldering temp is 200.0 °C +#define VOLTAGE_DIV 460 // Default divider scaler +#define MIN_CALIBRATION_OFFSET 0 // Should be 0 +#define CALIBRATION_OFFSET 0 // Default adc offset in uV +#define PID_POWER_LIMIT 70 // Sets the max pwm power limit +#define POWER_LIMIT 0 // 0 watts default limit +#define MAX_POWER_LIMIT 70 +#define POWER_LIMIT_STEPS 5 +#define OP_AMP_GAIN_STAGE 1 +#define TEMP_uV_LOOKUP_PT1000 +#define USB_PD_VMAX 20 // Maximum voltage for PD to negotiate +#define NO_DISPLAY_ROTATE // Disable OLED rotation by accel +#define MAX_TEMP_C 350 // Max soldering temp selectable °C +#define MAX_TEMP_F 660 // Max soldering temp selectable °F +#define MIN_TEMP_C 10 // Min soldering temp selectable °C +#define MIN_TEMP_F 50 // Min soldering temp selectable °F +#define MIN_BOOST_TEMP_C 150 // The min settable temp for boost mode °C +#define MIN_BOOST_TEMP_F 300 // The min settable temp for boost mode °F +#define NO_SLEEP_MODE +#define HARDWARE_MAX_WATTAGE_X10 850 + +#define TIP_THERMAL_MASS 30 // X10 watts to raise 1 deg C in 1 second +#define TIP_THERMAL_INERTIA 10 // We use a large inertia value to smooth out the drive to the tip since its stupidly sensitive +#define THERMAL_RUNAWAY_TIME_SEC 30 +#define THERMAL_RUNAWAY_TEMP_C 2 + +#define COPPER_HEATER_COIL 1 // Have a heater coil that changes resistance on us +#define TIP_RESISTANCE 52 // PCB heater, measured at ~19C. Will shift by temp a decent amount +#define CUSTOM_MAX_TEMP_C +#define PROFILE_SUPPORT 1 // Soldering Profiles +#define OLED_128x32 1 // Larger OLED +#define OLED_FLIP 1 // Mounted upside down +#define POW_PD_EXT 1 // Older HUB238 +#define USB_PD_EPR_WATTAGE 0 /*No EPR*/ +#define DEBUG_POWER_MENU_BUTTON_B 1 +#define HAS_POWER_DEBUG_MENU +#define NO_ACCEL 1 +#define I2C_SOFT_BUS_2 // For now we are doing software I2C to get around hardware chip issues +#define OLED_I2CBB2 +#define FILTER_DISPLAYED_TIP_TEMP 16 // Filtering for GUI display + +#define MODEL_HAS_DCDC // We dont have DC/DC but have reallly fast PWM that gets us roughly the same place +#endif /* T55 */ + +#define FLASH_LOGOADDR (0x08000000 + (62 * 1024)) +#define SETTINGS_START_PAGE (0x08000000 + (63 * 1024)) + +// Defaults + +#ifndef MIN_CALIBRATION_OFFSET +#define MIN_CALIBRATION_OFFSET 100 // Min value for calibration +#endif +#ifndef SOLDERING_TEMP +#define SOLDERING_TEMP 320 // Default soldering temp is 320.0 °C +#endif +#ifndef PID_TIM_HZ +#define PID_TIM_HZ (8) // Tick rate of the PID loop +#endif +#ifndef MAX_TEMP_C +#define MAX_TEMP_C 450 // Max soldering temp selectable °C +#endif +#ifndef MAX_TEMP_F +#define MAX_TEMP_F 850 // Max soldering temp selectable °F +#endif +#ifndef MIN_TEMP_C +#define MIN_TEMP_C 10 // Min soldering temp selectable °C +#endif +#ifndef MIN_TEMP_F +#define MIN_TEMP_F 60 // Min soldering temp selectable °F +#endif +#ifndef MIN_BOOST_TEMP_C +#define MIN_BOOST_TEMP_C 250 // The min settable temp for boost mode °C +#endif +#ifndef MIN_BOOST_TEMP_F +#define MIN_BOOST_TEMP_F 480 // The min settable temp for boost mode °F +#endif + +#endif /* CONFIGURATION_H_ */ diff --git a/source/Core/BSP/Sequre_S60/flash.c b/source/Core/BSP/Sequre/flash.c similarity index 100% rename from source/Core/BSP/Sequre_S60/flash.c rename to source/Core/BSP/Sequre/flash.c diff --git a/source/Core/BSP/Sequre_S60/port.c b/source/Core/BSP/Sequre/port.c similarity index 97% rename from source/Core/BSP/Sequre_S60/port.c rename to source/Core/BSP/Sequre/port.c index 1b6417781..02d09c0e1 100644 --- a/source/Core/BSP/Sequre_S60/port.c +++ b/source/Core/BSP/Sequre/port.c @@ -208,7 +208,8 @@ static void prvTaskExitError(void) { // therefore not output an 'unreachable code' warning for code that appears // after it. */ // } - for (;;) {} + for (;;) { + } } /*-----------------------------------------------------------*/ diff --git a/source/Core/BSP/Sequre_S60/portmacro.h b/source/Core/BSP/Sequre/portmacro.h similarity index 100% rename from source/Core/BSP/Sequre_S60/portmacro.h rename to source/Core/BSP/Sequre/portmacro.h diff --git a/source/Core/BSP/Sequre_S60/postRTOS.cpp b/source/Core/BSP/Sequre/postRTOS.cpp similarity index 100% rename from source/Core/BSP/Sequre_S60/postRTOS.cpp rename to source/Core/BSP/Sequre/postRTOS.cpp diff --git a/source/Core/BSP/Sequre_S60/preRTOS.cpp b/source/Core/BSP/Sequre/preRTOS.cpp similarity index 83% rename from source/Core/BSP/Sequre_S60/preRTOS.cpp rename to source/Core/BSP/Sequre/preRTOS.cpp index 24bc7707d..3a8fa4f46 100644 --- a/source/Core/BSP/Sequre_S60/preRTOS.cpp +++ b/source/Core/BSP/Sequre/preRTOS.cpp @@ -20,6 +20,4 @@ void preRToSInit() { #ifdef I2C_SOFT_BUS_2 I2CBB2::init(); #endif - /* Init the IPC objects */ - FRToSI2C::FRToSInit(); } diff --git a/source/Core/BSP/Sequre_S60/stm32f103.ld b/source/Core/BSP/Sequre/stm32f103.ld similarity index 100% rename from source/Core/BSP/Sequre_S60/stm32f103.ld rename to source/Core/BSP/Sequre/stm32f103.ld diff --git a/source/Core/BSP/Sequre_S60/stm32f1xx_hal_msp.c b/source/Core/BSP/Sequre/stm32f1xx_hal_msp.c similarity index 58% rename from source/Core/BSP/Sequre_S60/stm32f1xx_hal_msp.c rename to source/Core/BSP/Sequre/stm32f1xx_hal_msp.c index 89243eab4..9a19a7c58 100644 --- a/source/Core/BSP/Sequre_S60/stm32f1xx_hal_msp.c +++ b/source/Core/BSP/Sequre/stm32f1xx_hal_msp.c @@ -56,12 +56,15 @@ void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { PB0 ------> ADC2_IN8 PB1 ------> ADC2_IN9 */ + GPIO_InitStruct.Pin = TIP_TEMP_Pin; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; HAL_GPIO_Init(TIP_TEMP_GPIO_Port, &GPIO_InitStruct); +#ifdef TMP36_INPUT_Pin GPIO_InitStruct.Pin = TMP36_INPUT_Pin; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; HAL_GPIO_Init(TMP36_INPUT_GPIO_Port, &GPIO_InitStruct); +#endif GPIO_InitStruct.Pin = VIN_Pin; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; HAL_GPIO_Init(VIN_GPIO_Port, &GPIO_InitStruct); @@ -72,54 +75,6 @@ void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { } } -void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) { -#ifdef SCL_Pin - GPIO_InitTypeDef GPIO_InitStruct; - /**I2C1 GPIO Configuration - PB6 ------> I2C1_SCL - PB7 ------> I2C1_SDA - */ - GPIO_InitStruct.Pin = SCL_Pin | SDA_Pin; - GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; - GPIO_InitStruct.Pull = GPIO_PULLUP; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM; - HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); - - /* I2C1 DMA Init */ - /* I2C1_RX Init */ - hdma_i2c1_rx.Instance = DMA1_Channel7; - hdma_i2c1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; - hdma_i2c1_rx.Init.PeriphInc = DMA_PINC_DISABLE; - hdma_i2c1_rx.Init.MemInc = DMA_MINC_ENABLE; - hdma_i2c1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; - hdma_i2c1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; - hdma_i2c1_rx.Init.Mode = DMA_NORMAL; - hdma_i2c1_rx.Init.Priority = DMA_PRIORITY_LOW; - HAL_DMA_Init(&hdma_i2c1_rx); - - __HAL_LINKDMA(hi2c, hdmarx, hdma_i2c1_rx); - - /* I2C1_TX Init */ - hdma_i2c1_tx.Instance = DMA1_Channel6; - hdma_i2c1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; - hdma_i2c1_tx.Init.PeriphInc = DMA_PINC_DISABLE; - hdma_i2c1_tx.Init.MemInc = DMA_MINC_ENABLE; - hdma_i2c1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; - hdma_i2c1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; - hdma_i2c1_tx.Init.Mode = DMA_NORMAL; - hdma_i2c1_tx.Init.Priority = DMA_PRIORITY_MEDIUM; - HAL_DMA_Init(&hdma_i2c1_tx); - - __HAL_LINKDMA(hi2c, hdmatx, hdma_i2c1_tx); - - /* I2C1 interrupt Init */ - HAL_NVIC_SetPriority(I2C1_EV_IRQn, 15, 0); - HAL_NVIC_EnableIRQ(I2C1_EV_IRQn); - HAL_NVIC_SetPriority(I2C1_ER_IRQn, 15, 0); - HAL_NVIC_EnableIRQ(I2C1_ER_IRQn); -#endif -} - void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim_base) { if (htim_base->Instance == TIM4) { /* Peripheral clock enable */ diff --git a/source/Core/BSP/Sequre_S60/stm32f1xx_hal_timebase_TIM.c b/source/Core/BSP/Sequre/stm32f1xx_hal_timebase_TIM.c similarity index 100% rename from source/Core/BSP/Sequre_S60/stm32f1xx_hal_timebase_TIM.c rename to source/Core/BSP/Sequre/stm32f1xx_hal_timebase_TIM.c diff --git a/source/Core/BSP/Sequre_S60/stm32f1xx_it.c b/source/Core/BSP/Sequre/stm32f1xx_it.c similarity index 83% rename from source/Core/BSP/Sequre_S60/stm32f1xx_it.c rename to source/Core/BSP/Sequre/stm32f1xx_it.c index e68c484f4..fed18b55a 100644 --- a/source/Core/BSP/Sequre_S60/stm32f1xx_it.c +++ b/source/Core/BSP/Sequre/stm32f1xx_it.c @@ -33,10 +33,4 @@ void TIM1_UP_IRQHandler(void) { HAL_TIM_IRQHandler(&htim1); } void TIM4_IRQHandler(void) { HAL_TIM_IRQHandler(&htim4); } void TIM2_IRQHandler(void) { HAL_TIM_IRQHandler(&htim2); } -void I2C1_EV_IRQHandler(void) { HAL_I2C_EV_IRQHandler(&hi2c1); } -void I2C1_ER_IRQHandler(void) { HAL_I2C_ER_IRQHandler(&hi2c1); } - -void DMA1_Channel6_IRQHandler(void) { HAL_DMA_IRQHandler(&hdma_i2c1_tx); } - -void DMA1_Channel7_IRQHandler(void) { HAL_DMA_IRQHandler(&hdma_i2c1_rx); } void EXTI9_5_IRQHandler(void) { HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_9); } diff --git a/source/Core/BSP/Sequre_S60/system_stm32f1xx.c b/source/Core/BSP/Sequre/system_stm32f1xx.c similarity index 93% rename from source/Core/BSP/Sequre_S60/system_stm32f1xx.c rename to source/Core/BSP/Sequre/system_stm32f1xx.c index 5be70b6f3..32d5b6744 100644 --- a/source/Core/BSP/Sequre_S60/system_stm32f1xx.c +++ b/source/Core/BSP/Sequre/system_stm32f1xx.c @@ -3,8 +3,8 @@ #include "stm32f1xx.h" #if !defined(HSI_VALUE) -#define HSI_VALUE \ - 8000000U /*!< Default value of the Internal oscillator in Hz. \ +#define HSI_VALUE \ + 8000000U /*!< Default value of the Internal oscillator in Hz. \ This value can be provided and adapted by the user application. */ #endif /* HSI_VALUE */ @@ -85,7 +85,7 @@ void SystemInit(void) { #ifdef VECT_TAB_SRAM SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */ #else - SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */ + SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */ #endif } diff --git a/source/Core/BSP/Sequre_S60/I2C_Wrapper.cpp b/source/Core/BSP/Sequre_S60/I2C_Wrapper.cpp deleted file mode 100644 index 47150ab5b..000000000 --- a/source/Core/BSP/Sequre_S60/I2C_Wrapper.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * FRToSI2C.cpp - * - * Created on: 14Apr.,2018 - * Author: Ralim - */ -#include "BSP.h" -#include "Setup.h" -#include -SemaphoreHandle_t FRToSI2C::I2CSemaphore = nullptr; -StaticSemaphore_t FRToSI2C::xSemaphoreBuffer; - -void FRToSI2C::CpltCallback() { - hi2c1.State = HAL_I2C_STATE_READY; // Force state reset (even if tx error) - if (I2CSemaphore) { - xSemaphoreGiveFromISR(I2CSemaphore, NULL); - } -} - -bool FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) { - - if (!lock()) - return false; - if (HAL_I2C_Mem_Read(&hi2c1, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 500) != HAL_OK) { - - I2C_Unstick(); - unlock(); - return false; - } - - unlock(); - return true; -} -bool FRToSI2C::I2C_RegisterWrite(uint8_t address, uint8_t reg, uint8_t data) { return Mem_Write(address, reg, &data, 1); } - -uint8_t FRToSI2C::I2C_RegisterRead(uint8_t add, uint8_t reg) { - uint8_t tx_data[1]; - Mem_Read(add, reg, tx_data, 1); - return tx_data[0]; -} -bool FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) { - - if (!lock()) - return false; - if (HAL_I2C_Mem_Write(&hi2c1, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 500) != HAL_OK) { - - I2C_Unstick(); - unlock(); - return false; - } - - unlock(); - return true; -} - -bool FRToSI2C::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) - return false; - if (HAL_I2C_Master_Transmit_IT(&hi2c1, DevAddress, pData, Size) != HAL_OK) { - I2C_Unstick(); - unlock(); - return false; - } - return true; -} - -bool FRToSI2C::probe(uint16_t DevAddress) { - if (!lock()) - return false; - uint8_t buffer[1]; - bool worked = HAL_I2C_Mem_Read(&hi2c1, DevAddress, 0x0F, I2C_MEMADD_SIZE_8BIT, buffer, 1, 1000) == HAL_OK; - unlock(); - return worked; -} - -void FRToSI2C::I2C_Unstick() { unstick_I2C(); } - -void FRToSI2C::unlock() { xSemaphoreGive(I2CSemaphore); } - -bool FRToSI2C::lock() { return xSemaphoreTake(I2CSemaphore, (TickType_t)50) == pdTRUE; } - -bool FRToSI2C::writeRegistersBulk(const uint8_t address, const I2C_REG *registers, const uint8_t registersLength) { - for (int index = 0; index < registersLength; index++) { - if (!I2C_RegisterWrite(address, registers[index].reg, registers[index].val)) { - return false; - } - if (registers[index].pause_ms) - delay_ms(registers[index].pause_ms); - } - return true; -} diff --git a/source/Core/BSP/Sequre_S60/Pins.h b/source/Core/BSP/Sequre_S60/Pins.h deleted file mode 100644 index b818878fb..000000000 --- a/source/Core/BSP/Sequre_S60/Pins.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Pins.h - * - * Created on: 29 May 2020 - * Author: Ralim - */ - -#ifndef BSP_MINIWARE_PINS_H_ -#define BSP_MINIWARE_PINS_H_ -#include "configuration.h" - -#ifdef MODEL_S60 - -#define KEY_B_Pin GPIO_PIN_1 -#define KEY_B_GPIO_Port GPIOB -#define TMP36_INPUT_Pin GPIO_PIN_5 -#define TMP36_INPUT_GPIO_Port GPIOA -#define TMP36_ADC1_CHANNEL ADC_CHANNEL_5 -#define TMP36_ADC2_CHANNEL ADC_CHANNEL_5 -#define TIP_TEMP_Pin GPIO_PIN_0 -#define TIP_TEMP_GPIO_Port GPIOA -#define TIP_TEMP_ADC1_CHANNEL ADC_CHANNEL_0 -#define TIP_TEMP_ADC2_CHANNEL ADC_CHANNEL_0 -#define VIN_Pin GPIO_PIN_4 -#define VIN_GPIO_Port GPIOA -#define VIN_ADC1_CHANNEL ADC_CHANNEL_4 -#define VIN_ADC2_CHANNEL ADC_CHANNEL_4 -#define KEY_A_Pin GPIO_PIN_0 -#define KEY_A_GPIO_Port GPIOB -#define PWM_Out_Pin GPIO_PIN_8 -#define PWM_Out_GPIO_Port GPIOB -#define PWM_Out_CHANNEL TIM_CHANNEL_3 // Timer 4; channel 3 -#define SCL2_Pin GPIO_PIN_6 -#define SCL2_GPIO_Port GPIOB -#define SDA2_Pin GPIO_PIN_7 -#define SDA2_GPIO_Port GPIOB -// Pin gets pulled high on movement -#define MOVEMENT_Pin GPIO_PIN_3 -#define MOVEMENT_GPIO_Port GPIOA - -#endif - -#endif /* BSP_MINIWARE_PINS_H_ */ diff --git a/source/Core/BSP/Sequre_S60/ThermoModel.cpp b/source/Core/BSP/Sequre_S60/ThermoModel.cpp deleted file mode 100644 index 90c12ab10..000000000 --- a/source/Core/BSP/Sequre_S60/ThermoModel.cpp +++ /dev/null @@ -1,11 +0,0 @@ -/* - * ThermoModel.cpp - * - * Created on: 1 May 2021 - * Author: Ralim - */ -#include "TipThermoModel.h" -#include "Utils.h" -#include "configuration.h" - -TemperatureType_t TipThermoModel::convertuVToDegC(uint32_t tipuVDelta) { return (tipuVDelta * 50) / 485; } diff --git a/source/Core/BSP/Sequre_S60/configuration.h b/source/Core/BSP/Sequre_S60/configuration.h deleted file mode 100644 index fd84162e5..000000000 --- a/source/Core/BSP/Sequre_S60/configuration.h +++ /dev/null @@ -1,171 +0,0 @@ -#ifndef CONFIGURATION_H_ -#define CONFIGURATION_H_ -#include "Settings.h" -#include -/** - * Configuration.h - * Define here your default pre settings for S60 - * - */ - -//=========================================================================== -//============================= Default Settings ============================ -//=========================================================================== -/** - * Default soldering temp is 320.0 C - * Temperature the iron sleeps at - default 150.0 C - */ - -#define SLEEP_TEMP 150 // Default sleep temperature -#define BOOST_TEMP 420 // Default boost temp. -#define BOOST_MODE_ENABLED 1 // 0: Disable 1: Enable - -/** - * OLED Brightness - * - */ -#define MIN_BRIGHTNESS 0 // Min OLED brightness selectable -#define MAX_BRIGHTNESS 100 // Max OLED brightness selectable -#define BRIGHTNESS_STEP 25 // OLED brightness increment -#define DEFAULT_BRIGHTNESS 25 // default OLED brightness - -/** - * Blink the temperature on the cooling screen when its > 50C - */ -#define COOLING_TEMP_BLINK 0 // 0: Disable 1: Enable - -/** - * How many seconds/minutes we wait until going to sleep/shutdown. - * Values -> SLEEP_TIME * 10; i.e. 5*10 = 50 Seconds! - */ -#define SLEEP_TIME 5 // x10 Seconds -#define SHUTDOWN_TIME 10 // Minutes - -/** - * Auto start off for safety. - * Pissible values are: - * 0 - none - * 1 - Soldering Temperature - * 2 - Sleep Temperature - * 3 - Sleep Off Temperature - */ -#define AUTO_START_MODE 0 // Default to none - -/** - * Locking Mode - * When in soldering mode a long press on both keys toggle the lock of the buttons - * Possible values are: - * 0 - Desactivated - * 1 - Lock except boost - * 2 - Full lock - */ -#define LOCKING_MODE 0 // Default to desactivated for safety - -/** - * OLED Orientation - * - */ -#define ORIENTATION_MODE 0 // 0: Right 1:Left 2:Automatic - Default Automatic -#define REVERSE_BUTTON_TEMP_CHANGE 0 // 0:Default 1:Reverse - Reverse the plus and minus button assigment for temperature change - -/** - * Temp change settings - */ -#define TEMP_CHANGE_SHORT_STEP 1 // Default temp change short step +1 -#define TEMP_CHANGE_LONG_STEP 10 // Default temp change long step +10 -#define TEMP_CHANGE_SHORT_STEP_MAX 50 // Temp change short step MAX value -#define TEMP_CHANGE_LONG_STEP_MAX 90 // Temp change long step MAX value - -/* Power pulse for keeping power banks awake*/ -#define POWER_PULSE_INCREMENT 1 -#define POWER_PULSE_MAX 100 // x10 max watts -#define POWER_PULSE_WAIT_MAX 9 // 9*2.5s = 22.5 seconds -#define POWER_PULSE_DURATION_MAX 9 // 9*250ms = 2.25 seconds - -#define POWER_PULSE_DEFAULT 0 -#define POWER_PULSE_WAIT_DEFAULT 4 // Default rate of the power pulse: 4*2500 = 10000 ms = 10 s -#define POWER_PULSE_DURATION_DEFAULT 1 // Default duration of the power pulse: 1*250 = 250 ms - -/** - * OLED Orientation Sensitivity on Automatic mode! - * Motion Sensitivity <0=Off 1=Least Sensitive 9=Most Sensitive> - */ -#define SENSITIVITY 7 // Default 7 - -/** - * Detailed soldering screen - * Detailed idle screen (off for first time users) - */ -#define DETAILED_SOLDERING 0 // 0: Disable 1: Enable - Default 0 -#define DETAILED_IDLE 0 // 0: Disable 1: Enable - Default 0 - -#define THERMAL_RUNAWAY_TIME_SEC 20 -#define THERMAL_RUNAWAY_TEMP_C 10 - -#define CUT_OUT_SETTING 0 // default to no cut-off voltage -#define RECOM_VOL_CELL 33 // Minimum voltage per cell (Recommended 3.3V (33)) -#define TEMPERATURE_INF 0 // default to 0 -#define DESCRIPTION_SCROLL_SPEED 0 // 0: Slow 1: Fast - default to slow -#define ANIMATION_LOOP 1 // 0: off 1: on -#define ANIMATION_SPEED settingOffSpeed_t::MEDIUM - -// Op-amp gain -// First stage has a gain of 10.31, followed by gain of 52; so total gain is 536 - -#define ADC_MAX_READING (4096 * 8) // Maximum reading of the adc -#define ADC_VDD_MV 3300 // ADC max reading millivolts - -// Deriving the Voltage div: -// Vin_max = (3.3*(r1+r2))/(r2) -// vdiv = (32768*4)/(vin_max*10) - -#if defined(MODEL_S60) == 0 -#error "No model defined!" -#endif - -#define NEEDS_VBUS_PROBE 0 - -#define MIN_CALIBRATION_OFFSET 100 // Min value for calibration -#define SOLDERING_TEMP 320 // Default soldering temp is 320.0 °C -#define PID_TIM_HZ (8) // Tick rate of the PID loop -#define MAX_TEMP_C 450 // Max soldering temp selectable °C -#define MAX_TEMP_F 850 // Max soldering temp selectable °F -#define MIN_TEMP_C 10 // Min soldering temp selectable °C -#define MIN_TEMP_F 60 // Min soldering temp selectable °F -#define MIN_BOOST_TEMP_C 250 // The min settable temp for boost mode °C -#define MIN_BOOST_TEMP_F 480 // The min settable temp for boost mode °F - -#ifdef MODEL_S60 -#define VOLTAGE_DIV 460 // Default divider scaler -#define CALIBRATION_OFFSET 200 // Default adc offset in uV -#define PID_POWER_LIMIT 70 // Sets the max pwm power limit -#define POWER_LIMIT 0 // 0 watts default limit -#define MAX_POWER_LIMIT 70 -#define POWER_LIMIT_STEPS 5 -#define OP_AMP_GAIN_STAGE 536 -#define TEMP_uV_LOOKUP_S60 -#define USB_PD_VMAX 12 // Maximum voltage for PD to negotiate - -#define HARDWARE_MAX_WATTAGE_X10 600 - -#define TIP_THERMAL_MASS 8 // X10 watts to raise 1 deg C in 1 second -#define TIP_THERMAL_INERTIA 128 // We use a large inertia value to smooth out the drive to the tip since its stupidly sensitive - -#define TIP_RESISTANCE 20 //(actually 2.5 ish but we need to be more conservative on pwm'ing watt limit) x10 ohms - -#define OLED_128x32 -#define GPIO_VIBRATION -#define POW_PD_EXT 1 -#define DEBUG_POWER_MENU_BUTTON_B 1 -#define HAS_POWER_DEBUG_MENU -#define TEMP_NTC -#define I2C_SOFT_BUS_2 // For now we are doing software I2C to get around hardware chip issues -#define OLED_I2CBB2 - -#define MODEL_HAS_DCDC // We dont have DC/DC but have reallly fast PWM that gets us roughly the same place -#endif /* S60 */ - -#define FLASH_LOGOADDR (0x08000000 + (62 * 1024)) -#define SETTINGS_START_PAGE (0x08000000 + (63 * 1024)) - -#endif /* CONFIGURATION_H_ */ diff --git a/source/Core/Drivers/BMA223.cpp b/source/Core/Drivers/BMA223.cpp index cffe109d9..b5844cfbb 100644 --- a/source/Core/Drivers/BMA223.cpp +++ b/source/Core/Drivers/BMA223.cpp @@ -5,14 +5,15 @@ * Author: Ralim */ +#include "accelerometers_common.h" #include #include bool BMA223::detect() { - if (FRToSI2C::probe(BMA223_ADDRESS)) { + if (ACCEL_I2C_CLASS::probe(BMA223_ADDRESS)) { // Read chip id to ensure its not an address collision uint8_t id = 0; - if (FRToSI2C::Mem_Read(BMA223_ADDRESS, BMA223_BGW_CHIPID, &id, 1)) { + if (ACCEL_I2C_CLASS::Mem_Read(BMA223_ADDRESS, BMA223_BGW_CHIPID, &id, 1)) { return id == 0b11111000; } } @@ -20,17 +21,17 @@ bool BMA223::detect() { return false; } -static const FRToSI2C::I2C_REG i2c_registers[] = { +static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = { // // - {BMA223_PMU_RANGE, 0b00000011, 0}, // 2G range - {BMA223_PMU_BW, 0b00001101, 0}, // 250Hz filter - {BMA223_PMU_LPW, 0b00000000, 0}, // Full power - {BMA223_ACCD_HBW, 0b00000000, 0}, // filtered data out - {BMA223_INT_OUT_CTRL, 0b00001010, 0}, // interrupt active low and OD to get it hi-z + { BMA223_PMU_RANGE, 0b00000011, 0}, // 2G range + { BMA223_PMU_BW, 0b00001101, 0}, // 250Hz filter + { BMA223_PMU_LPW, 0b00000000, 0}, // Full power + { BMA223_ACCD_HBW, 0b00000000, 0}, // filtered data out + { BMA223_INT_OUT_CTRL, 0b00001010, 0}, // interrupt active low and OD to get it hi-z {BMA223_INT_RST_LATCH, 0b10000000, 0}, // interrupt active low and OD to get it hi-z - {BMA223_INT_EN_0, 0b01000000, 0}, // Enable orientation - {BMA223_INT_A, 0b00100111, 0}, // Setup orientation detection + { BMA223_INT_EN_0, 0b01000000, 0}, // Enable orientation + { BMA223_INT_A, 0b00100111, 0}, // Setup orientation detection // }; @@ -44,7 +45,7 @@ bool BMA223::initalize() { // Hysteresis is set to ~ 16 counts // Theta blocking is set to 0b10 - return FRToSI2C::writeRegistersBulk(BMA223_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); + return ACCEL_I2C_CLASS::writeRegistersBulk(BMA223_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); } void BMA223::getAxisReadings(int16_t &x, int16_t &y, int16_t &z) { @@ -52,7 +53,7 @@ void BMA223::getAxisReadings(int16_t &x, int16_t &y, int16_t &z) { // And yet there are MSB and LSB registers _sigh_. uint8_t sensorData[6] = {0, 0, 0, 0, 0, 0}; - if (FRToSI2C::Mem_Read(BMA223_ADDRESS, BMA223_ACCD_X_LSB, sensorData, 6) == false) { + if (ACCEL_I2C_CLASS::Mem_Read(BMA223_ADDRESS, BMA223_ACCD_X_LSB, sensorData, 6) == false) { x = y = z = 0; return; } diff --git a/source/Core/Drivers/BMA223.hpp b/source/Core/Drivers/BMA223.hpp index 5e033784d..54c0db517 100644 --- a/source/Core/Drivers/BMA223.hpp +++ b/source/Core/Drivers/BMA223.hpp @@ -9,7 +9,10 @@ #define CORE_DRIVERS_BMA223_HPP_ #include "BMA223_defines.h" #include "BSP.h" +#include "accelerometers_common.h" #include "I2C_Wrapper.hpp" +#include "accelerometers_common.h" + class BMA223 { public: @@ -17,7 +20,7 @@ class BMA223 { static bool initalize(); // 1 = rh, 2,=lh, 8=flat static Orientation getOrientation() { - uint8_t val = FRToSI2C::I2C_RegisterRead(BMA223_ADDRESS, BMA223_INT_STATUS_3); + uint8_t val = ACCEL_I2C_CLASS::I2C_RegisterRead(BMA223_ADDRESS, BMA223_INT_STATUS_3); val >>= 4; // we dont need high values val &= 0b11; if (val & 0b10) { diff --git a/source/Core/Drivers/BootLogo.cpp b/source/Core/Drivers/BootLogo.cpp index f21b8993c..af43fee43 100644 --- a/source/Core/Drivers/BootLogo.cpp +++ b/source/Core/Drivers/BootLogo.cpp @@ -2,11 +2,13 @@ #include "BSP.h" #include "Buttons.hpp" #include "OLED.hpp" +#include "Settings.h" #include "cmsis_os.h" + #define LOGO_PAGE_LENGTH 1024 void delay() { - if (getSettingValue(SettingsOptions::LOGOTime) == 5) { + if (getSettingValue(SettingsOptions::LOGOTime) >= logoMode_t::ONETIME) { waitForButtonPress(); } else { waitForButtonPressOrTimeout(TICKS_SECOND * getSettingValue(SettingsOptions::LOGOTime)); @@ -14,72 +16,102 @@ void delay() { } void BootLogo::handleShowingLogo(const uint8_t *ptrLogoArea) { + OLED::clearScreen(); // Read the first few bytes and figure out what format we are looking at if (OLD_LOGO_HEADER_VALUE == *(reinterpret_cast(ptrLogoArea))) { showOldFormat(ptrLogoArea); } else if (ptrLogoArea[0] == 0xAA) { showNewFormat(ptrLogoArea + 1); } + OLED::clearScreen(); - OLED::refresh(); } void BootLogo::showOldFormat(const uint8_t *ptrLogoArea) { +#ifdef OLED_128x32 + // Draw in middle + OLED::drawAreaSwapped(16, 8, 96, 16, (uint8_t *)(ptrLogoArea + 4)); +#else OLED::drawAreaSwapped(0, 0, 96, 16, (uint8_t *)(ptrLogoArea + 4)); - OLED::refresh(); - // Delay here until button is pressed or its been the amount of seconds set by the user +#endif + OLED::refresh(); + // Delay here with static logo until a button is pressed or its been the amount of seconds set by the user delay(); } void BootLogo::showNewFormat(const uint8_t *ptrLogoArea) { - if (getSettingValue(SettingsOptions::LOGOTime) == 0) { + if (getSettingValue(SettingsOptions::LOGOTime) == logoMode_t::SKIP) { return; } + // New logo format (a) fixes long standing byte swap quirk and (b) supports animation uint8_t interFrameDelay = ptrLogoArea[0]; OLED::clearScreen(); - ButtonState buttons = getButtonState(); // Now draw in the frames int position = 1; - do { - + while (getButtonState() == BUTTON_NONE) { int len = (showNewFrame(ptrLogoArea + position)); OLED::refresh(); position += len; - buttons = getButtonState(); if (interFrameDelay) { osDelay(interFrameDelay * 4); } + // 1024 less the header type byte and the inter-frame-delay - if (getSettingValue(SettingsOptions::LOGOTime) > 0 && (position >= 1022 || len == 0)) { - // Delay here until button is pressed or its been the amount of seconds set by the user - delay(); - return; + if (getSettingValue(SettingsOptions::LOGOTime) && (position >= 1022 || len == 0)) { + // Animated logo stops here ... + if (getSettingValue(SettingsOptions::LOGOTime) == logoMode_t::INFINITY) { + // ... but if it's infinite logo setting then keep it rolling over again until a button is pressed + osDelay(4 * TICKS_100MS); + OLED::clearScreen(); + position = 1; + continue; + } + } else { + // Animation in progress so jumping to the next frame + continue; } - } while (buttons == BUTTON_NONE); + + // Static logo case ends up right here, so delay until a button is pressed or its been the amount of seconds set by the user + delay(); + return; + } } + int BootLogo::showNewFrame(const uint8_t *ptrLogoArea) { uint8_t length = ptrLogoArea[0]; - - if (length == 0xFF) { - // Full frame update + switch (length) { + case 0: + // End + return 0; + break; + case 0xFE: + return 1; + break; + case 0xFF: +// Full frame update +#ifdef OLED_128x32 + OLED::drawArea(16, 8, 96, 16, ptrLogoArea + 1); +#else OLED::drawArea(0, 0, 96, 16, ptrLogoArea + 1); +#endif length = 96; - } else if (length == 0xFE) { - return 1; - } else if (length == 0) { - return 0; // end - } else { + break; + default: length /= 2; // Draw length patches for (int p = 0; p < length; p++) { uint8_t index = ptrLogoArea[1 + (p * 2)]; uint8_t value = ptrLogoArea[2 + (p * 2)]; +#ifdef OLED_128x32 + OLED::drawArea(16 + (index % 96), index >= 96 ? 16 : 8, 1, 8, &value); +#else OLED::drawArea(index % 96, index >= 96 ? 8 : 0, 1, 8, &value); +#endif } } diff --git a/source/Core/Drivers/Buttons.cpp b/source/Core/Drivers/Buttons.cpp index 4ab8718fb..826374271 100644 --- a/source/Core/Drivers/Buttons.cpp +++ b/source/Core/Drivers/Buttons.cpp @@ -31,23 +31,27 @@ ButtonState getButtonState() { currentState = (getButtonA()) << 0; currentState |= (getButtonB()) << 1; - if (currentState) + if (currentState) { lastButtonTime = xTaskGetTickCount(); + } if (currentState == previousState) { - if (currentState == 0) + if (currentState == 0) { return BUTTON_NONE; + } if ((xTaskGetTickCount() - previousStateChange) >= timeout) { // User has been holding the button down // We want to send a button is held message longPressed = true; - if (currentState == 0x01) + if (currentState == 0x01) { return BUTTON_F_LONG; - else if (currentState == 0x02) + } else if (currentState == 0x02) { return BUTTON_B_LONG; - else + } else { return BUTTON_BOTH_LONG; // Both being held case - } else + } + } else { return BUTTON_NONE; + } } else { // A change in button state has occurred ButtonState retVal = BUTTON_NONE; @@ -65,12 +69,13 @@ ButtonState getButtonState() { // The user didn't hold the button for long // So we send button press - if (previousState == 0x01) + if (previousState == 0x01) { retVal = BUTTON_F_SHORT; - else if (previousState == 0x02) + } else if (previousState == 0x02) { retVal = BUTTON_B_SHORT; - else + } else { retVal = BUTTON_BOTH; // Both being held case + } } previousState = 0; longPressed = false; @@ -103,13 +108,15 @@ void waitForButtonPressOrTimeout(TickType_t timeout) { while (buttons) { buttons = getButtonState(); GUIDelay(); - if (xTaskGetTickCount() > timeout) + if (xTaskGetTickCount() > timeout) { return; + } } while (!buttons) { buttons = getButtonState(); GUIDelay(); - if (xTaskGetTickCount() > timeout) + if (xTaskGetTickCount() > timeout) { return; + } } } diff --git a/source/Core/Drivers/FS2711.cpp b/source/Core/Drivers/FS2711.cpp new file mode 100644 index 000000000..e6624b306 --- /dev/null +++ b/source/Core/Drivers/FS2711.cpp @@ -0,0 +1,244 @@ +#include "configuration.h" + +#if POW_PD_EXT == 2 +#include "BSP.h" +#include "FS2711.hpp" +#include "FS2711_defines.h" +#include "I2CBB2.hpp" +#include "Settings.h" +#include "cmsis_os.h" +#include +#include +#include + +#ifndef USB_PD_VMAX +#error Max PD Voltage must be defined +#endif + +#define PROTOCOL_TIMEOUT 100 // ms + +extern int32_t powerSupplyWattageLimit; + +fs2711_state_t FS2711::state; + +inline void i2c_write(uint8_t addr, uint8_t data) { I2CBB2::Mem_Write(FS2711_ADDR, addr, &data, 1); } + +inline uint8_t i2c_read(uint8_t addr) { + uint8_t data = 0; + I2CBB2::Mem_Read(FS2711_ADDR, addr, &data, 1); + return data; +} + +inline bool i2c_probe(uint8_t addr) { return I2CBB2::probe(addr); } + +void FS2711::start() { + memset(&state, 0, sizeof(fs2711_state_t)); + state.req_pdo_num = 0xFF; + + enable_protocol(false); + osDelay(PROTOCOL_TIMEOUT); + select_protocol(FS2711_PROTOCOL_PD); + enable_protocol(true); + osDelay(PROTOCOL_TIMEOUT); +} + +uint8_t FS2711::selected_protocol() { return i2c_read(FS2711_REG_SELECT_PROTOCOL); } + +void FS2711::enable_protocol(bool enable) { i2c_write(FS2711_REG_ENABLE_PROTOCOL, enable ? FS2711_ENABLE : FS2711_DISABLE); } + +void FS2711::select_protocol(uint8_t protocol) { i2c_write(FS2711_REG_SELECT_PROTOCOL, protocol); } + +void FS2711::enable_voltage() { i2c_write(FS2711_REG_ENABLE_VOLTAGE, FS2711_ENABLE); } + +bool FS2711::probe() { return i2c_probe(FS2711_ADDR); } + +void FS2711::pdo_update() { + uint8_t pdo_b0 = 0, pdo_b1 = 0, pdo_b2 = 0, pdo_b3 = 0; + + state.pdo_num = 0; + memset(state.pdo_type, 0, 7); + memset(state.pdo_min_volt, 0, 7); + memset(state.pdo_max_volt, 0, 7); + memset(state.pdo_max_curr, 0, 7); + + for (uint8_t i = 0; i < 7; i++) { + pdo_b0 = i2c_read(FS2711_REG_PDO_B0 + i * 4); + pdo_b1 = i2c_read(FS2711_REG_PDO_B1 + i * 4); + pdo_b2 = i2c_read(FS2711_REG_PDO_B2 + i * 4); + pdo_b3 = i2c_read(FS2711_REG_PDO_B3 + i * 4); + + if (pdo_b0) { + if ((pdo_b3 & FS2711_REG_PDO_B0) == FS2711_REG_PDO_B0) { + state.pdo_type[i] = FS2711_PDO_PPS; + state.pdo_min_volt[i] = pdo_b1 * 100; + state.pdo_max_volt[i] = ((pdo_b2 >> 1) + ((pdo_b3 & 0x1) << 7)) * 100; + state.pdo_max_curr[i] = (pdo_b0 & 0x7F) * 50; + } else { + state.pdo_type[i] = FS2711_PDO_FIX; + state.pdo_min_volt[i] = ((pdo_b1 >> 2) + ((pdo_b2 & 0xF) << 6)) * 50; + state.pdo_max_volt[i] = state.pdo_min_volt[i]; + state.pdo_max_curr[i] = (pdo_b0 + ((pdo_b1 & 0x3) << 8)) * 10; + } + state.pdo_num++; + } + } +} + +bool FS2711::open_pps(uint8_t pdoid, uint16_t volt, uint16_t max_curr) { + uint16_t wr; + + if (pdoid > state.pdo_num) + return false; + if ((volt > state.pdo_max_volt[pdoid]) || (volt < state.pdo_min_volt[pdoid])) + return false; + if ((volt > state.pdo_max_volt[pdoid]) || (volt < state.pdo_min_volt[pdoid])) + return false; + if (max_curr > state.pdo_max_curr[pdoid]) + return false; + if (state.pdo_type[pdoid] != FS2711_PDO_PPS) + return false; + + if (FS2711::selected_protocol() == FS2711_PROTOCOL_PD) { + select_protocol(FS2711_PROTOCOL_PPS); + enable_protocol(true); + } + + if (FS2711::selected_protocol() != FS2711_PROTOCOL_PPS) { + return false; + } + + i2c_write(FS2711_REG_PDO_IDX, pdoid + (pdoid << 4)); + wr = (volt - state.pdo_min_volt[pdoid]) / 20; + i2c_write(FS2711_PROTOCOL_PPS_CURRENT, max_curr / 50); + + i2c_write(FS2711_REG_VOLT_CFG_B0, wr & 0xFF); + i2c_write(FS2711_REG_VOLT_CFG_B1, (wr >> 8) & 0xFF); + i2c_write(FS2711_REG_VOLT_CFG_B2, wr & 0xFF); + i2c_write(FS2711_REG_VOLT_CFG_B3, (wr >> 8) & 0xFF); + + enable_voltage(); + + state.source_voltage = volt; + state.source_current = max_curr; + state.req_pdo_num = pdoid; + powerSupplyWattageLimit = ((volt * max_curr) / 1000000) - 2; + return true; +} + +bool FS2711::open_pd(uint8_t pdoid) { + if (pdoid >= state.pdo_num) { + return false; + } + if (state.pdo_type[pdoid] != FS2711_PDO_FIX) { + return false; + } + + if (FS2711::selected_protocol() != FS2711_PROTOCOL_PD) { + return false; + } + + i2c_write(FS2711_REG_PDO_IDX, pdoid + (pdoid << 4)); + + enable_voltage(); + + state.source_voltage = state.pdo_max_volt[pdoid]; + state.source_current = state.pdo_max_curr[pdoid]; + state.req_pdo_num = pdoid; + + powerSupplyWattageLimit = ((state.source_voltage * state.source_current) / 1000000) - 2; + return true; +} + +void FS2711::negotiate() { + uint16_t best_voltage = 0; + uint16_t best_current = 0; + uint8_t best_pdoid = 0xFF; + bool pps = false; + + int min_resistance_omhsx10 = 0; + + // FS2711 uses mV instead of V + const uint16_t vmax = USB_PD_VMAX * 1000; + uint8_t tip_resistance = getTipResistanceX10(); + if (getSettingValue(SettingsOptions::USBPDMode) == usbpdMode_t::DEFAULT) { + tip_resistance += 5; + } + + uint16_t pdo_min_mv = 0, pdo_max_mv = 0, pdo_max_curr = 0, pdo_type = 0; + + FS2711::pdo_update(); + + for (int i = 0; state.pdo_num > i; i++) { + pdo_min_mv = state.pdo_min_volt[i]; + pdo_max_mv = state.pdo_max_volt[i]; + pdo_max_curr = state.pdo_max_curr[i]; + pdo_type = state.pdo_type[i]; + + min_resistance_omhsx10 = (pdo_max_mv / pdo_max_curr) * 10; + + switch (pdo_type) { + case FS2711_PDO_FIX: + if (pdo_max_mv > 0 && vmax >= pdo_max_mv) { + if (min_resistance_omhsx10 <= tip_resistance) { + if (pdo_max_mv > best_voltage) { + pps = false; + best_pdoid = i; + best_voltage = pdo_max_mv; + best_current = pdo_max_curr; + } + } + } + break; + + case FS2711_PDO_PPS: { + int ideal_mv = tip_resistance * (pdo_max_curr / 10); + if (ideal_mv > pdo_max_mv) { + ideal_mv = pdo_max_mv; + } + + if (ideal_mv > vmax) { + ideal_mv = vmax; + } + + if (ideal_mv > best_voltage) { + best_pdoid = i; + best_voltage = ideal_mv; + best_current = pdo_max_curr; + pps = true; + } + } + + break; + + default: + break; + } + } + + if (best_pdoid != 0xFF && best_pdoid != state.req_pdo_num) { + if (pps) { + FS2711::open_pps(best_pdoid, best_voltage, best_current); + } else { + FS2711::open_pd(best_pdoid); + } + } +} + +bool FS2711::has_run_selection() { return state.req_pdo_num != 0xFF; } + +uint16_t FS2711::source_voltage() { return state.source_voltage / 1000; } + +// FS2711 does current in mV so it needs to be converted to x100 intead of x1000 +uint16_t FS2711::source_currentx100() { return state.source_current / 10; } + +uint16_t FS2711::debug_pdo_max_voltage(uint8_t pdoid) { return state.pdo_max_volt[pdoid]; } + +uint16_t FS2711::debug_pdo_min_voltage(uint8_t pdoid) { return state.pdo_min_volt[pdoid]; } + +uint16_t FS2711::debug_pdo_source_current(uint8_t pdoid) { return state.pdo_max_curr[pdoid]; } + +uint16_t FS2711::debug_pdo_type(uint8_t pdoid) { return state.pdo_type[pdoid]; } + +fs2711_state_t FS2711::debug_get_state() { return state; } + +#endif diff --git a/source/Core/Drivers/FS2711.hpp b/source/Core/Drivers/FS2711.hpp new file mode 100644 index 000000000..9fb2ae83c --- /dev/null +++ b/source/Core/Drivers/FS2711.hpp @@ -0,0 +1,61 @@ +#include "configuration.h" +#ifndef _DRIVERS_FS2711_HPP_ +#define _DRIVERS_FS2711_HPP_ +// #define POW_PD_EXT 2 +#if POW_PD_EXT == 2 +#include +#include + +typedef struct { + uint8_t pdo_num; // Nums of USB-PD Objects max of 7 + uint16_t source_current; + uint16_t source_voltage; + uint16_t req_pdo_num; + uint16_t pdo_type[7]; + uint16_t pdo_min_volt[7]; + uint16_t pdo_max_volt[7]; + uint16_t pdo_max_curr[7]; +} fs2711_state_t; + +class FS2711 { +public: + static bool probe(); + + static void start(); + + static bool open_pps(uint8_t PDOID, uint16_t volt, uint16_t max_curr); + + static bool open_pd(uint8_t PDOID); + + static void negotiate(); + + static bool has_run_selection(); + + static uint16_t source_voltage(); + + static uint16_t source_currentx100(); + + static uint8_t selected_protocol(); + + static void pdo_update(); + + static uint8_t debug_protocol(); + static uint16_t debug_pdo_max_voltage(uint8_t pdoid); + static uint16_t debug_pdo_min_voltage(uint8_t pdoid); + static uint16_t debug_pdo_source_current(uint8_t pdoid); + static uint16_t debug_pdo_type(uint8_t pdoid); + static fs2711_state_t debug_get_state(); + +private: + // Internal state of IC + static fs2711_state_t state; + + static void enable_protocol(bool enable); + + static void select_protocol(uint8_t protocol); + + static void enable_voltage(); +}; + +#endif +#endif diff --git a/source/Core/Drivers/FS2711_defines.h b/source/Core/Drivers/FS2711_defines.h new file mode 100644 index 000000000..d7594b750 --- /dev/null +++ b/source/Core/Drivers/FS2711_defines.h @@ -0,0 +1,73 @@ +#ifndef _FS2711_DEFINE_HPP_ +#define _FS2711_DEFINE_HPP_ + +#define FS2711_WRITE_ADDR 0x5A +#define FS2711_READ_ADDR 0x5B + +#define FS2711_ADDR 0x5A + +#define FS2711_PDO_FIX 0 +#define FS2711_PDO_PPS 1 + +#define FS2711_MAX_5V 1 +#define FS2711_MAX_9V 3 +#define FS2711_MAX_12V 7 +#define FS2711_MAX_20V 15 + +#define FS2711_ENABLE 0x1 +#define FS2711_DISABLE 0x2 + +// Protocol Selection +#define FS2711_PROTOCOL_QC2A 4 +#define FS2711_PROTOCOL_QC2B 5 +#define FS2711_PROTOCOL_QC3A 6 +#define FS2711_PROTOCOL_QC3B 7 +#define FS2711_PROTOCOL_PPS 20 +#define FS2711_PROTOCOL_PD 21 + +#define FS2711_PROTOCOL_PPS_CURRENT 0xDE + +#define FS2711_PROTOCOL_QC_MAX_VOLT 0xC0 + +#define FS2711_REG_SCAN_START 0x40 // Protocol Scan +#define FS2711_REG_ENABLE_PROTOCOL 0x41 // Enable Protocol +#define FS2711_REG_SELECT_PROTOCOL 0x42 // Select Protocol +#define FS2711_REG_ENABLE_VOLTAGE 0x43 // Enable Voltage +#define FS2711_REG_PDO_IDX 0x46 // Requests Protocol Index +#define FS2711_REG_SWEEP 0x47 // Requests a voltage sweep? +#define FS2711_REG_PORT_RESET 0x49 // Port Reset +#define FS2711_REG_SYSTEM_RESET 0x4A // System Reset +#define FS2711_REG_DPDM 0x51 // DPDM +#define FS2711_REG_MODE_SET 0xA0 // Mode set +#define FS2711_REG_STATE0 0xB1 // PD:A_SNK PD:A_SRC (PD:pe_ready POM:crc_success) (PD:soft_reset POM:crc_fail) (PD:hard_rest POM:resp_fail) PD:hardreset_found VIVO +#define FS2711_REG_STATE1 0xB2 // scan_done pdo_updated vooc_recv_cmd vivo_pom_tx_finish vivo_pom_rx_finish huawei_comm_fail huawei_op_finish + +// Used to calculate PDO Objects +#define FS2711_REG_PDO_B0 0xC0 +#define FS2711_REG_PDO_B1 0xC1 +#define FS2711_REG_PDO_B2 0xC2 +#define FS2711_REG_PDO_B3 0xC3 + +#define FS2711_REG_VOLT_CFG_B0 0xF4 +#define FS2711_REG_VOLT_CFG_B1 0xF5 +#define FS2711_REG_VOLT_CFG_B2 0xF6 +#define FS2711_REG_VOLT_CFG_B3 0xF7 + +// 0xF0 ~ 0xF1 16 bits +#define FS2711_REG_MASK 0xF0 +// 0xF4 ~ 0xF7 32 bits +#define FS2711_REG_PROTOCOL_VOLT 0xF4 +// 0xF8 ~ 0xFB 24 bits +#define FS2711_REG_PROTOCOL_EXISTS 0xF8 + +#define FS2711_SWEEP_SAW 0 +#define FS2711_SWEEP_TRI 1 +#define FS2711_SWEEP_STEP 2 + +#define FS2711_STATE_SCAN_DONE 0x01 +#define FS2711_STATE_PDO_UPDATE 0x02 +#define FS2711_STATE_PD_SNK 0x40 +#define FS2711_STATE_PD_SRC 0x80 +#define FS2711_STATE_PD_PE_READY 0x100 +#define FS2711_STATE_DISABLE 0x800 +#endif diff --git a/source/Core/Drivers/Font.h b/source/Core/Drivers/Font.h index 0bd08c82a..0d0943ff3 100644 --- a/source/Core/Drivers/Font.h +++ b/source/Core/Drivers/Font.h @@ -14,851 +14,572 @@ #define FONT_12_WIDTH 12 // THE MAIN FONTS ARE NO LONGER HERE, MOVED TO PYTHON AUTO GEN // THESE ARE ONLY THE SYMBOL FONTS - -const uint8_t ExtraFontChars[] = { - // width = 12 - // height = 16 - 0x00, 0x18, 0x24, 0x24, 0x18, 0xC0, 0x40, 0x40, 0x40, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, // Degrees F - 0x00, 0x18, 0x24, 0x24, 0x18, 0x80, 0x40, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x08, 0x10, 0x10, 0x10, 0x00, 0x00, // Degrees C - 0x00, 0x00, 0x20, 0x30, 0x38, 0xFC, 0xFE, 0xFC, 0x38, 0x30, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, // UP arrow - - 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x3F, 0x00, // Battery Empty - 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x40, 0x3F, 0x00, // Battery 1*/ - 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x40, 0x3F, 0x00, // Battery 2*/ - 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x40, 0x3F, 0x00, // Battery 3*/ - 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5E, 0x5E, 0x5E, 0x5E, 0x5E, 0x5E, 0x40, 0x3F, 0x00, // Battery 4*/ - 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 5*/ - 0x00, 0xF0, 0x08, 0x8E, 0x82, 0x82, 0x82, 0x82, 0x8E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 6*/ - 0x00, 0xF0, 0x08, 0xCE, 0xC2, 0xC2, 0xC2, 0xC2, 0xCE, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 7*/ - 0x00, 0xF0, 0x08, 0xEE, 0xE2, 0xE2, 0xE2, 0xE2, 0xEE, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 8*/ - 0x00, 0xF0, 0x08, 0xEE, 0xE2, 0xF2, 0xF2, 0xE2, 0xEE, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 9*/ - 0x00, 0xF0, 0x08, 0xEE, 0xE2, 0xFA, 0xFA, 0xE2, 0xEE, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 10*/ - - 0x00, 0x00, 0x38, 0xC4, 0x00, 0x38, 0xC4, 0x00, 0x38, 0xC4, 0x00, 0x00, 0x00, 0x38, 0x3A, 0x39, 0x38, 0x3A, 0x39, 0x38, 0x3A, 0x39, 0x10, 0x10, // heating - 0x00, 0x60, 0xE0, 0xFE, 0xE0, 0xE0, 0xE0, 0xE0, 0xFE, 0xE0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0xFF, 0xFF, 0x03, 0x01, 0x00, 0x00, 0x00, // AC - - 0xFC, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x82, 0x62, 0x1A, 0x02, 0xFC, 0x3F, 0x40, 0x42, 0x46, 0x4C, 0x58, 0x46, 0x41, 0x40, 0x40, 0x40, 0x3F, // ☑ (check box on, menu true) - 0xFC, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0xFC, 0x3F, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x3F, // ☐ (check box off, menu false) - +// clang-format off + const uint8_t ExtraFontChars[] = { + // width = 12 + // height = 16 + 0x00, 0x18, 0x24, 0x24, 0x18, 0xC0, 0x40, 0x40, 0x40, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, // Degrees F + 0x00, 0x18, 0x24, 0x24, 0x18, 0x80, 0x40, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x08, 0x10, 0x10, 0x10, 0x00, 0x00, // Degrees C + 0x00, 0x00, 0x20, 0x30, 0x38, 0xFC, 0xFE, 0xFC, 0x38, 0x30, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, // UP arrow + + 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x3F, 0x00, // Battery Empty + 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x40, 0x3F, 0x00, // Battery 1*/ + 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x40, 0x3F, 0x00, // Battery 2*/ + 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x40, 0x3F, 0x00, // Battery 3*/ + 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5E, 0x5E, 0x5E, 0x5E, 0x5E, 0x5E, 0x40, 0x3F, 0x00, // Battery 4*/ + 0x00, 0xF0, 0x08, 0x0E, 0x02, 0x02, 0x02, 0x02, 0x0E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 5*/ + 0x00, 0xF0, 0x08, 0x8E, 0x82, 0x82, 0x82, 0x82, 0x8E, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 6*/ + 0x00, 0xF0, 0x08, 0xCE, 0xC2, 0xC2, 0xC2, 0xC2, 0xCE, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 7*/ + 0x00, 0xF0, 0x08, 0xEE, 0xE2, 0xE2, 0xE2, 0xE2, 0xEE, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 8*/ + 0x00, 0xF0, 0x08, 0xEE, 0xE2, 0xF2, 0xF2, 0xE2, 0xEE, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 9*/ + 0x00, 0xF0, 0x08, 0xEE, 0xE2, 0xFA, 0xFA, 0xE2, 0xEE, 0x08, 0xF0, 0x00, 0x00, 0x3F, 0x40, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x5F, 0x40, 0x3F, 0x00, // Battery 10*/ + + 0x00, 0x00, 0x38, 0xC4, 0x00, 0x38, 0xC4, 0x00, 0x38, 0xC4, 0x00, 0x00, 0x00, 0x38, 0x3A, 0x39, 0x38, 0x3A, 0x39, 0x38, 0x3A, 0x39, 0x10, 0x10, // heating + 0x00, 0x60, 0xE0, 0xFE, 0xE0, 0xE0, 0xE0, 0xE0, 0xFE, 0xE0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0xFF, 0xFF, 0x03, 0x01, 0x00, 0x00, 0x00, // AC + + 0xFC, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x82, 0x62, 0x1A, 0x02, 0xFC, 0x3F, 0x40, 0x42, 0x46, 0x4C, 0x58, 0x46, 0x41, 0x40, 0x40, 0x40, 0x3F, // ☑ (check box on, menu true) + 0xFC, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0xFC, 0x3F, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x3F, // ☐ (check box off, menu false) + + /* + 0x00,0x00,0x00,0x80,0x80,0xFE,0xFF,0x83,0x87,0x06,0x00,0x00,0x00,0x00,0x30,0x70,0x60,0x7F,0x3F,0x00,0x00,0x00,0x00,0x00, // Function? + 0x00,0x70,0xFA,0xDB,0xDB,0xDB,0xDB,0xDB,0xDB,0xFF,0xFE,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x00,0x00, // a_ + 0x00,0x3C,0x7E,0xE7,0xC3,0xC3,0xC3,0xC3,0xE7,0x7E,0x3C,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x00,0x00, // 0_ + 0x55,0x00,0xAA,0x00,0x55,0x00,0xAA,0x00,0x55,0x00,0xAA,0x00,0x55,0x00,0xAA,0x00,0x55,0x00,0xAA,0x00,0x55,0x00,0xAA,0x00, // 25% block + 0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55, // 50% pipe + 0xAA,0xFF,0x55,0xFF,0xAA,0xFF,0x55,0xFF,0xAA,0xFF,0x55,0xFF,0xAA,0xFF,0x55,0xFF,0xAA,0xFF,0x55,0xFF,0xAA,0xFF,0x55,0xFF, // 75% block + 0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // | pipe + 0x80,0x80,0x80,0x80,0x80,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // T pipe ,| + 0xC0,0xC0,0xFF,0xFF,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0xFE,0xFE,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // ,| double pipe + 0x00,0x00,0xFF,0xFF,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // || double pipe + 0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0xFE,0xFE,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // #NAME?//#NAME? + 0xC0,0xC0,0xFF,0xFF,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x07,0x07,0x00,0x00,0x00,0x00,0x00, // ,^ double pupe + 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // #NAME?//#NAME? + 0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01, // ,> pipe + 0x80,0x80,0x80,0x80,0x80,0xFF,0xFF,0x80,0x80,0x80,0x80,0x80,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, // _|_ pipe + 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x01,0x01,0x01,0x01,0x01,0xFF,0xFF,0x01,0x01,0x01,0x01,0x01, // ,|, pipe + 0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x01,0x01,0x01,0x01,0x01, // |, pipe + 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, // #NAME?//#NAME? + 0x80,0x80,0x80,0x80,0x80,0xFF,0xFF,0x80,0x80,0x80,0x80,0x80,0x01,0x01,0x01,0x01,0x01,0xFF,0xFF,0x01,0x01,0x01,0x01,0x01, // #NAME?//#NAME? + 0x00,0x00,0xFF,0xFF,0x00,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0x07,0x07,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06, // ,> double pipe + 0x00,0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0xFF,0xFF,0x00,0xFE,0xFE,0x06,0x06,0x06,0x06,0x06, // ^, double pipe + 0xC0,0xC0,0xFF,0xFF,0x00,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xC0,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06, // _|_ double pipe + 0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x06,0x06,0xFE,0xFE,0x00,0xFE,0xFE,0x06,0x06,0x06,0x06,0x06, // ,|, double pipe + 0x00,0x00,0xFF,0xFF,0x00,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0xFF,0xFF,0x00,0xFE,0xFE,0x06,0x06,0x06,0x06,0x06, // |, double pipe + 0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06, // == double pipe + 0xC0,0xC0,0xFF,0xFF,0x00,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xC0,0x06,0x06,0xFE,0xFE,0x00,0xFE,0xFE,0x06,0x06,0x06,0x06,0x06, // #NAME?//#NAME? + 0x00,0x00,0x00,0x78,0xFC,0xCC,0x8C,0x0C,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x1C,0x3E,0x33,0x33,0x3F,0x1E,0x00,0x00,0x00, // Delta lowercase + 0x00,0x00,0x00,0x00,0x00,0x7E,0x7E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // 27 (') + 0x80,0x80,0x80,0x80,0x80,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00, // ,^ pipe + 0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x01,0x01,0x01,0x01,0x01, // | , pipe + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, // solid block + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, // half block bottom + 0x00,0x00,0x00,0x00,0x00,0xBF,0xBF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3F,0x3F,0x00,0x00,0x00,0x00,0x00, // 7C (|) + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // top half solid block + 0x00,0x00,0x0C,0xFC,0xFC,0x6C,0x60,0x60,0xE0,0xC0,0x00,0x00,0x00,0x00,0x30,0x3F,0x3F,0x36,0x06,0x06,0x07,0x03,0x00,0x00, // DE small + 0x00,0x00,0x03,0xFF,0xFF,0x1B,0x18,0x18,0xF8,0xF0,0x00,0x00,0x00,0x00,0x30,0x3F,0x3F,0x36,0x06,0x06,0x07,0x03,0x00,0x00, // DE large + 0x00,0x00,0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // ? (,) + 0x00,0x00,0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x06,0x00,0x00,0x00, // = + 0x00,0x00,0x00,0x40,0x80,0x80,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // sideways comma + 0x00,0x00,0x80,0xC0,0x80,0x00,0x00,0x80,0xC0,0x80,0x00,0x00,0x00,0x00,0x01,0x03,0x01,0x00,0x00,0x01,0x03,0x01,0x00,0x00, // .. + 0x00,0x00,0x00,0x00,0x00,0x80,0xC0,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x03,0x01,0x00,0x00,0x00,0x00, // . + 0x00,0x00,0x02,0x1F,0x1F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // tiny 1 + 0x00,0x00,0x00,0x00,0xF0,0xF0,0xF0,0xF0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x03,0x03,0x03,0x00,0x00,0x00,0x00, // small block + */ + }; + + const uint8_t WarningBlock24[] = { + // width = 24 + // height = 16 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x30, 0x0C, 0x02, 0xF1, 0xF1, 0xF1, 0x02, 0x0C, 0x30, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xC0, 0xB0, 0x8C, 0x83, 0x80, 0x80, 0x80, 0x80, 0xB3, 0xB3, 0xB3, 0x80, 0x80, 0x80, 0x80, 0x83, 0x8C, 0xB0, 0xC0, 0x00, 0x00}; + + #if defined(MODEL_S60) || defined(MODEL_S60P) || defined(MODEL_TS101) || defined(MODEL_T55) + #if defined(MODEL_S60) || defined(MODEL_S60P) + const uint8_t buttonA[] = { + // width = 56 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x04, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x04, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xf0, 0x0e, 0x01, 0x00, 0x00, 0x00, 0x00, 0x10, 0xe0, 0x00, 0x00, 0x88, 0x70, 0x00, 0x00, 0x88, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x0e, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0f, 0x70, 0x80, 0x00, 0x00, 0x00, 0x0e, 0x51, 0x40, 0x40, 0x47, 0x48, 0xa0, 0x60, 0xa7, 0x60, 0xa0, 0x60, 0xa0, 0x40, 0x00, 0x40, 0x40, 0x40, + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x00, 0xfc, 0x08, 0xbc, 0x08, 0xbc, 0x00, 0xfc, 0xfc, 0x3c, 0x84, 0x70, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x20, 0x40, 0x40, 0x40, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x47, 0x40, 0x44, 0x21, 0x20, 0x18, 0x09, 0x04, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + + const uint8_t disconnectedTip[] = { + // width = 56 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xe0, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x40, 0xc0, 0x40, 0xc0, 0x40, 0xc0, 0x40, 0x80, 0x00, 0x80, 0x80, 0x80, 0x80, 0x81, 0x83, 0x87, 0x8e, 0x9c, 0x38, 0x70, 0xe0, 0xc0, + 0x80, 0x20, 0x70, 0x38, 0x9c, 0x8e, 0x87, 0x83, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0x70, 0x38, 0x1c, 0x0e, 0x04, 0x01, + 0x03, 0x07, 0x0e, 0x1c, 0x38, 0x70, 0xe0, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + + #elif defined(MODEL_TS101) + const uint8_t buttonA[] = { + // width = 56 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x04, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x04, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xf0, 0x0e, 0x01, 0x00, 0x00, 0x00, 0x00, 0x10, 0xe0, 0x00, 0x00, 0x88, 0x70, 0x00, 0x00, 0x88, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x0e, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0f, 0x70, 0x80, 0x00, 0x00, 0x40, 0x5e, 0x41, 0xa0, 0x60, 0xa7, 0x70, 0x00, 0xf0, 0x37, 0x70, 0x30, 0x70, 0x30, 0x70, 0x30, 0x70, 0x30, 0x50, + 0x30, 0x50, 0x30, 0x50, 0x30, 0x50, 0xe0, 0x00, 0xa0, 0x60, 0xa0, 0x60, 0xa0, 0x60, 0xa0, 0x60, 0xa0, 0x50, 0xb8, 0x38, 0x80, 0x70, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x20, 0x40, 0x40, 0x41, 0x80, 0x81, 0x81, 0x80, 0x81, 0x80, 0x81, 0x80, 0x81, 0x80, 0x81, 0x80, + 0x81, 0x80, 0x81, 0x80, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x40, 0x40, 0x40, 0x20, 0x20, 0x18, 0x09, 0x04, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + + const uint8_t disconnectedTip[] = { + // width = 56 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xe0, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x40, 0xc0, 0x40, 0xe0, 0x00, 0xe0, 0x60, 0xe0, 0x61, 0xe3, 0x67, 0xce, 0x1c, 0x38, 0x70, 0xe0, 0xc0, + 0x80, 0x20, 0x70, 0x38, 0x9c, 0xce, 0x07, 0x43, 0xc1, 0x40, 0xc0, 0x40, 0xc0, 0x40, 0xc0, 0x40, 0xa0, 0x70, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x02, 0x00, 0x03, 0x02, 0x00, 0x82, 0xc0, 0xe2, 0x70, 0x38, 0x1c, 0x0e, 0x04, 0x01, + 0x03, 0x07, 0x0e, 0x1c, 0x38, 0x71, 0xe0, 0xc1, 0x80, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x02, 0x04, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + + #elif defined(MODEL_T55) + const uint8_t buttonA[] = { + // width = 56 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x04, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x04, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xf0, 0x0e, 0x01, 0x00, 0x00, 0x00, 0x00, 0x10, 0xe0, 0x00, 0x00, 0x88, 0x70, 0x00, 0x00, 0x88, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x0e, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0f, 0x70, 0x80, 0x00, 0x00, 0x00, 0x0e, 0x51, 0x40, 0x40, 0x47, 0x48, 0xa0, 0x60, 0xa7, 0x60, 0xa0, 0x60, 0xa0, 0x40, 0x00, 0x40, 0x40, 0x40, + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x00, 0xfc, 0x08, 0xbc, 0x08, 0xbc, 0x00, 0xfc, 0xfc, 0x3c, 0x84, 0x70, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x20, 0x40, 0x40, 0x40, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x47, 0x40, 0x44, 0x21, 0x20, 0x18, 0x09, 0x04, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + + const uint8_t disconnectedTip[] = { + // width = 56 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xe0, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x40, 0xc0, 0x40, 0xc0, 0x40, 0xc0, 0x40, 0x80, 0x00, 0x80, 0x80, 0x80, 0x80, 0x81, 0x83, 0x87, 0x8e, 0x9c, 0x38, 0x70, 0xe0, 0xc0, + 0x80, 0x20, 0x70, 0x38, 0x9c, 0x8e, 0x87, 0x83, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0x70, 0x38, 0x1c, 0x0e, 0x04, 0x01, + 0x03, 0x07, 0x0e, 0x1c, 0x38, 0x70, 0xe0, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + #endif + + const uint8_t buttonB[] = { + // width = 56 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x04, 0x02, 0x02, 0x02, 0x01, 0x01, 0x71, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xf1, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xf1, 0x01, 0x01, 0x02, 0x02, 0x02, 0x04, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xf0, 0x0e, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x1f, 0xd7, 0x13, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xdf, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x0e, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0f, 0x70, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x7c, 0x5d, + 0x4c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x03, 0x07, 0xf5, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x70, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x20, 0x40, 0x40, 0x40, 0x80, 0x80, 0x8f, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x8f, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x8f, 0x80, 0x80, 0x40, 0x40, 0x40, 0x20, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + + const uint8_t RepeatOnce[] = { + // width = 32 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0x70, 0x78, 0x38, 0x38, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x38, 0x38, 0x78, 0xf0, 0xf0, 0xe0, 0xf0, + 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xfc, 0xff, 0x1f, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, + 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0xe0, 0xe0, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x07, 0x20, 0x30, 0x38, 0xfc, 0xfc, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xe0, 0xf8, 0xff, 0x3f, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x3f, 0x3f, 0x00, 0x00, 0x00, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x1c, 0x1c, 0x1e, 0x0e, 0x0f, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}; + + const uint8_t RepeatInf[] = { + // width = 32 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0x70, 0x78, 0x38, 0x38, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x38, 0x38, 0x78, 0xf0, 0xf0, 0xe0, 0xf0, + 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xfc, 0xff, 0x1f, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, + 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0xe0, 0xe0, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x07, 0x1f, 0x9f, 0x98, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xe0, 0xf8, 0xff, 0x3f, 0x07, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x11, 0x20, 0x20, 0x20, 0x11, + 0x0a, 0x04, 0x0a, 0x11, 0x20, 0x20, 0x20, 0x11, 0x0e, 0x00, 0x00, 0x1c, 0x1c, 0x1e, 0x0e, 0x0f, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}; + + const uint8_t UnavailableIcon[] = { + // width = 32 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0x70, 0x78, 0x38, 0x38, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x1c, 0x38, 0x38, 0x78, 0x70, 0xf0, 0xe0, 0xc0, + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xfc, 0xff, 0x1f, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0x7c, + 0x3e, 0x1e, 0x0c, 0x00, 0x01, 0x07, 0x1f, 0xff, 0xfc, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x07, 0x3f, 0xff, 0xf8, 0xe0, 0x80, 0x00, 0x30, 0x78, 0x7c, 0x3e, 0x1f, + 0x0f, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xe0, 0xf8, 0xff, 0x3f, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, + 0x0f, 0x0e, 0x1e, 0x1c, 0x1c, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x1c, 0x1c, 0x1e, 0x0e, 0x0f, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}; + + #define SETTINGS_ICON_WIDTH 21 + #define SETTINGS_ICON_HEIGHT 32 /* - 0x00,0x00,0x00,0x80,0x80,0xFE,0xFF,0x83,0x87,0x06,0x00,0x00,0x00,0x00,0x30,0x70,0x60,0x7F,0x3F,0x00,0x00,0x00,0x00,0x00, // Function? - 0x00,0x70,0xFA,0xDB,0xDB,0xDB,0xDB,0xDB,0xDB,0xFF,0xFE,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x00,0x00, // a_ - 0x00,0x3C,0x7E,0xE7,0xC3,0xC3,0xC3,0xC3,0xE7,0x7E,0x3C,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x00,0x00, // 0_ - 0x55,0x00,0xAA,0x00,0x55,0x00,0xAA,0x00,0x55,0x00,0xAA,0x00,0x55,0x00,0xAA,0x00,0x55,0x00,0xAA,0x00,0x55,0x00,0xAA,0x00, // 25% block - 0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55,0xAA,0x55, // 50% pipe - 0xAA,0xFF,0x55,0xFF,0xAA,0xFF,0x55,0xFF,0xAA,0xFF,0x55,0xFF,0xAA,0xFF,0x55,0xFF,0xAA,0xFF,0x55,0xFF,0xAA,0xFF,0x55,0xFF, // 75% block - 0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // | pipe - 0x80,0x80,0x80,0x80,0x80,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // T pipe ,| - 0xC0,0xC0,0xFF,0xFF,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0xFE,0xFE,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // ,| double pipe - 0x00,0x00,0xFF,0xFF,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // || double pipe - 0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0xFE,0xFE,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // #NAME?//#NAME? - 0xC0,0xC0,0xFF,0xFF,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x07,0x07,0x00,0x00,0x00,0x00,0x00, // ,^ double pupe - 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00, // #NAME?//#NAME? - 0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01, // ,> pipe - 0x80,0x80,0x80,0x80,0x80,0xFF,0xFF,0x80,0x80,0x80,0x80,0x80,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, // _|_ pipe - 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x01,0x01,0x01,0x01,0x01,0xFF,0xFF,0x01,0x01,0x01,0x01,0x01, // ,|, pipe - 0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x01,0x01,0x01,0x01,0x01, // |, pipe - 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, // #NAME?//#NAME? - 0x80,0x80,0x80,0x80,0x80,0xFF,0xFF,0x80,0x80,0x80,0x80,0x80,0x01,0x01,0x01,0x01,0x01,0xFF,0xFF,0x01,0x01,0x01,0x01,0x01, // #NAME?//#NAME? - 0x00,0x00,0xFF,0xFF,0x00,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0x07,0x07,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06, // ,> double pipe - 0x00,0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0xFF,0xFF,0x00,0xFE,0xFE,0x06,0x06,0x06,0x06,0x06, // ^, double pipe - 0xC0,0xC0,0xFF,0xFF,0x00,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xC0,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06, // _|_ double pipe - 0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x06,0x06,0xFE,0xFE,0x00,0xFE,0xFE,0x06,0x06,0x06,0x06,0x06, // ,|, double pipe - 0x00,0x00,0xFF,0xFF,0x00,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0xFF,0xFF,0x00,0xFE,0xFE,0x06,0x06,0x06,0x06,0x06, // |, double pipe - 0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06, // == double pipe - 0xC0,0xC0,0xFF,0xFF,0x00,0xFF,0xFF,0xC0,0xC0,0xC0,0xC0,0xC0,0x06,0x06,0xFE,0xFE,0x00,0xFE,0xFE,0x06,0x06,0x06,0x06,0x06, // #NAME?//#NAME? - 0x00,0x00,0x00,0x78,0xFC,0xCC,0x8C,0x0C,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x1C,0x3E,0x33,0x33,0x3F,0x1E,0x00,0x00,0x00, // Delta lowercase - 0x00,0x00,0x00,0x00,0x00,0x7E,0x7E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // 27 (') - 0x80,0x80,0x80,0x80,0x80,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00, // ,^ pipe - 0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x01,0x01,0x01,0x01,0x01, // | , pipe - 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, // solid block - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, // half block bottom - 0x00,0x00,0x00,0x00,0x00,0xBF,0xBF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3F,0x3F,0x00,0x00,0x00,0x00,0x00, // 7C (|) - 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // top half solid block - 0x00,0x00,0x0C,0xFC,0xFC,0x6C,0x60,0x60,0xE0,0xC0,0x00,0x00,0x00,0x00,0x30,0x3F,0x3F,0x36,0x06,0x06,0x07,0x03,0x00,0x00, // DE small - 0x00,0x00,0x03,0xFF,0xFF,0x1B,0x18,0x18,0xF8,0xF0,0x00,0x00,0x00,0x00,0x30,0x3F,0x3F,0x36,0x06,0x06,0x07,0x03,0x00,0x00, // DE large - 0x00,0x00,0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // ? (,) - 0x00,0x00,0x00,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x06,0x06,0x00,0x00,0x00, // = - 0x00,0x00,0x00,0x40,0x80,0x80,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // sideways comma - 0x00,0x00,0x80,0xC0,0x80,0x00,0x00,0x80,0xC0,0x80,0x00,0x00,0x00,0x00,0x01,0x03,0x01,0x00,0x00,0x01,0x03,0x01,0x00,0x00, // .. - 0x00,0x00,0x00,0x00,0x00,0x80,0xC0,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x03,0x01,0x00,0x00,0x00,0x00, // . - 0x00,0x00,0x02,0x1F,0x1F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // tiny 1 - 0x00,0x00,0x00,0x00,0xF0,0xF0,0xF0,0xF0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x03,0x03,0x03,0x00,0x00,0x00,0x00, // small block - */ -}; - -const uint8_t WarningBlock24[] = { - // width = 24 - // height = 16 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x30, 0x0C, 0x02, 0xF1, 0xF1, 0xF1, 0x02, 0x0C, 0x30, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0xC0, 0xB0, 0x8C, 0x83, 0x80, 0x80, 0x80, 0x80, 0xB3, 0xB3, 0xB3, 0x80, 0x80, 0x80, 0x80, 0x83, 0x8C, 0xB0, 0xC0, 0x00, 0x00}; - -#if defined(MODEL_TS100) + defined(MODEL_Pinecil) + defined(MODEL_Pinecilv2) +defined(MODEL_TS101) > 0 -const uint8_t buttonA[] = { - // width = 42 - // height = 16 - 0x00, 0x00, 0x00, 0x00, 0xe0, 0x18, 0x04, 0x02, 0x02, 0x01, 0x81, 0x49, 0x31, 0x01, 0xc1, 0x25, 0x19, 0x01, 0xc1, 0x25, 0x19, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x04, 0x18, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x18, 0x20, 0x40, 0x40, 0x80, 0x89, 0x8a, 0x88, 0x94, - 0x8c, 0x94, 0xae, 0x80, 0xbe, 0x8e, 0xa6, 0x8e, 0xa6, 0x8e, 0xa6, 0x8e, 0xa6, 0x8a, 0xa6, 0x8a, 0xa6, 0x8a, 0xa6, 0x8a, 0x46, 0x4a, 0x22, 0x18, 0x07, 0x00, 0x00, 0x00}; - -const uint8_t disconnectedTip[] = { - // width = 42 - // height = 16 - 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0xc0, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xcc, 0x9c, 0x38, 0x70, 0xe0, 0xc0, 0x80, 0x20, 0x70, 0x38, 0x1c, 0xcc, 0x40, - 0x80, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xc0, 0x60, 0xe0, 0x00, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x05, 0x00, 0x07, 0x01, 0x04, 0x01, 0x04, 0x01, - 0x04, 0x31, 0x38, 0x1c, 0x0e, 0x04, 0x01, 0x03, 0x07, 0x0e, 0x1c, 0x39, 0x30, 0x01, 0x03, 0x00, 0x02, 0x01, 0x02, 0x01, 0x02, 0x01, 0x02, 0x01, 0x04, 0x09, 0x0f, 0x00}; -#endif - -#if defined(MODEL_TS80) + defined(MODEL_TS80P) > 0 -const uint8_t buttonA[] = { - // width = 42 - // height = 16 - 0x00, 0x00, 0x00, 0x00, 0xe0, 0x18, 0x04, 0x02, 0x02, 0x01, 0x81, 0x49, 0x31, 0x01, 0xc1, 0x25, 0x19, 0x01, 0xc1, 0x25, 0x19, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x04, 0x18, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x18, 0x20, 0x40, 0x40, 0x80, 0x81, 0x8a, 0x88, 0x88, - 0x8c, 0x95, 0x80, 0x9c, 0xa6, 0x8e, 0xa6, 0x8c, 0x80, 0x94, 0x8c, 0x94, 0x8c, 0x94, 0x8c, 0x94, 0x80, 0x88, 0x88, 0x88, 0x48, 0x48, 0x20, 0x18, 0x07, 0x00, 0x00, 0x00}; - -const uint8_t disconnectedTip[] = { - // width = 42 - // height = 16 - 0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0xc0, 0xc0, 0xc0, 0x80, 0x00, 0x80, 0x80, 0x80, 0x8c, 0x9c, 0x38, 0x70, 0xe0, 0xc0, 0x80, 0x20, 0x70, 0x38, 0x1c, 0x0c, 0x00, - 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0xc0, 0xc0, 0xc0, 0xc0, 0xe0, 0xa0, 0xe0, 0x00, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00, 0x03, 0x04, 0x01, 0x04, 0x01, 0x00, 0x02, 0x01, - 0x02, 0x31, 0x38, 0x1c, 0x0e, 0x04, 0x01, 0x03, 0x07, 0x0e, 0x1c, 0x39, 0x31, 0x01, 0x01, 0x00, 0x02, 0x01, 0x02, 0x01, 0x04, 0x01, 0x04, 0x01, 0x0a, 0x01, 0x0f, 0x00}; -#endif - -#ifdef MODEL_MHP30 -const uint8_t buttonA[] = { - // width = 42 - // height = 16 - 0x00, 0x00, 0x00, 0x00, 0xe0, 0x18, 0x04, 0x02, 0x02, 0x81, 0x81, 0x41, 0x41, 0x41, 0x41, 0x21, 0x01, 0xc1, 0x25, 0x19, 0x01, 0x81, 0x49, 0x31, 0x01, 0xc1, 0x25, 0x19, - 0x01, 0xa1, 0xa1, 0x41, 0x41, 0x01, 0x02, 0x02, 0x04, 0x18, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x18, 0x20, 0x40, 0x40, 0x83, 0x87, 0x83, 0xab, 0x86, - 0x96, 0x8e, 0xa6, 0x9c, 0xad, 0x8c, 0xb8, 0x89, 0xa4, 0x84, 0x84, 0x92, 0x82, 0x81, 0xa9, 0x80, 0x84, 0x80, 0x81, 0x80, 0x40, 0x40, 0x20, 0x18, 0x07, 0x00, 0x00, 0x00}; - -const uint8_t disconnectedTip[] = { - // width = 42 - // height = 16 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x40, 0x40, 0x40, 0x40, 0x20, 0x20, 0x20, 0x20, 0x10, 0x10, 0xd0, 0xc8, 0x08, 0x10, 0x10, 0x10, 0x10, - 0x20, 0x20, 0x20, 0x40, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x04, 0x04, 0x38, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x04, 0x04, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; -#endif - -#if defined(MODEL_S60) > 0 -const uint8_t buttonA[] = { - // width = 42 - // height = 16 - 0x00, 0x00, 0x00, 0x00, 0xe0, 0x18, 0x04, 0x02, 0x02, 0x01, 0x81, 0x49, 0x31, 0x01, 0xc1, 0x25, 0x19, 0x01, 0xc1, 0x25, 0x19, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x04, 0x18, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x18, 0x20, 0x40, 0x40, 0x80, 0x89, 0x8a, 0x88, 0x94, - 0x8c, 0x94, 0xae, 0x80, 0xbe, 0x8e, 0xa6, 0x8e, 0xa6, 0x8e, 0xa6, 0x8e, 0xa6, 0x8a, 0xa6, 0x8a, 0xa6, 0x8a, 0xa6, 0x8a, 0x46, 0x4a, 0x22, 0x18, 0x07, 0x00, 0x00, 0x00}; - -const uint8_t disconnectedTip[] = { - // width = 42 - // height = 16 - 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0xc0, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xcc, 0x9c, 0x38, 0x70, 0xe0, 0xc0, 0x80, 0x20, 0x70, 0x38, 0x1c, 0xcc, 0x40, - 0x80, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xc0, 0x60, 0xe0, 0x00, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x05, 0x00, 0x07, 0x01, 0x04, 0x01, 0x04, 0x01, - 0x04, 0x31, 0x38, 0x1c, 0x0e, 0x04, 0x01, 0x03, 0x07, 0x0e, 0x1c, 0x39, 0x30, 0x01, 0x03, 0x00, 0x02, 0x01, 0x02, 0x01, 0x02, 0x01, 0x02, 0x01, 0x04, 0x09, 0x0f, 0x00}; -#endif - -const uint8_t buttonB[] = { - // width = 42 - // height = 16 - 0x00, 0x00, 0x00, 0xe0, 0x18, 0x04, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x71, 0x55, 0x71, 0x01, 0x01, 0xfd, 0x01, 0x01, 0x81, 0xbd, 0x81, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x04, 0x18, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x18, 0x20, 0x40, 0x40, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0xbf, 0x80, 0x80, 0x8e, 0xaa, 0x8e, 0x80, 0x83, 0xba, 0x83, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x40, 0x40, 0x20, 0x18, 0x07, 0x00, 0x00, 0x00, 0x00}; - -// const uint8_t brightnessIcon[] = { -// // width = 16 -// // height = 16 -// 0x80, 0x86, 0x8E, 0x9C, 0x18, 0xC0, 0xE0, 0xEF, 0xEF, 0xE0, 0xC0, 0x18, 0x9C, 0x8E, 0x86, 0x80, 0x01, 0x61, 0x71, 0x39, 0x18, 0x03, 0x07, 0xF7, 0xF7, 0x07, 0x03, 0x18, 0x39, 0x71, 0x61, 0x01}; - -// const uint8_t invertDisplayIcon[] = { -// // width = 24 -// // height = 16 -// 0xFE, 0x01, 0x79, 0x25, 0x79, 0x01, 0xFE, 0x00, 0x20, 0x20, 0x20, 0x20, 0xDF, 0x07, 0x8F, 0xDF, 0xFF, 0x01, 0xFE, 0x86, 0xDA, 0x86, 0xFE, 0x01, -// 0x7F, 0x80, 0xA4, 0xBE, 0xA0, 0x80, 0x7F, 0x00, 0x04, 0x0E, 0x1F, 0x04, 0xFB, 0xFB, 0xFB, 0xFB, 0xFF, 0x80, 0x7F, 0x5B, 0x41, 0x5F, 0x7F, 0x80}; - -const uint8_t infinityIcon[] = { - // width = 24 - // height = 16 - 0x00, 0xc0, 0x70, 0x18, 0x0c, 0x0c, 0x0c, 0x0c, 0x18, 0x10, 0x20, 0x80, 0xc0, 0x60, 0x30, 0x18, 0x0c, 0x0c, 0x0c, 0x0c, 0x18, 0x70, 0xc0, 0x00, - 0x00, 0x01, 0x07, 0x0c, 0x18, 0x18, 0x18, 0x18, 0x0c, 0x06, 0x03, 0x01, 0x00, 0x02, 0x04, 0x0c, 0x18, 0x18, 0x18, 0x18, 0x0c, 0x07, 0x01, 0x00}; - -/* - * 16x16 icons - * 32 * 3 = Frame size * Frame count - * */ -const uint8_t SettingsMenuIcons[][32 * 3] = { - // Power - // 3 frames - { - // Power 1st frame - // width = 16 - // height = 16 - 0x00, - 0x00, - 0xfe, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x04, - 0x17, - 0x0f, - 0x05, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x1c, - 0x55, - 0x1c, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - // Power 2nd frame - // width = 16 - // height = 16 - 0x00, - 0x00, - 0x7e, - 0x00, - 0x00, - 0x00, - 0x00, - 0x10, - 0x1c, - 0xdf, - 0x77, - 0x33, - 0x11, - 0x00, - 0x00, - 0x00, - 0x00, - 0x07, - 0x75, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - // Power final frame - // width = 16 - // height = 16 - 0x00, - 0x38, - 0xaa, - 0x38, - 0x00, - 0x20, - 0x30, - 0x3c, - 0xff, - 0xff, - 0xff, - 0x77, - 0x33, - 0x13, - 0x01, - 0x00, - 0x00, - 0x00, - 0x7f, - 0x00, - 0x00, - 0x00, - 0x42, - 0x33, - 0x1f, - 0x0f, - 0x06, - 0x02, - 0x00, - 0x00, - 0x00, - 0x00, - }, - - // Soldering - // 3 frames - { - // Soldering 1st frame - // width = 16 - // height = 16 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x80, - 0x40, - 0xE0, - 0x50, - 0x28, - 0x14, - 0x0A, - 0x06, - 0x00, - 0x00, - 0x40, - 0x20, - 0x10, - 0x08, - 0x04, - 0x03, - 0x02, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - // Soldering 2nd frame - // width = 16 + * 21x32 icons + * 84 * 3 = Frame size * Frame count + * */ + const uint8_t SettingsMenuIcons[][84 * 3] = { + // Power + // 3 frames + { + // Power 1st frame + // width = 21 + // height = 32 + 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xdc, 0x37, 0x13, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x80, 0xc0, 0xdf, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x03, 0x07, 0x35, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + + // Power 2nd frame + // width = 21 + // height = 32 + 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xe0, 0xfc, 0x7f, 0x1f, 0x0f, 0x07, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x83, 0x73, 0x3f, 0x0f, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x0e, 0x1f, 0xd7, 0x13, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + + // Power final frame + // width = 21 + // height = 32 + 0x00, 0xc0, 0xe0, 0xec, 0x60, 0xc0, 0x00, 0x00, 0x00, 0x80, 0xf0, 0xfc, 0xff, 0xff, 0x7f, 0x3f, 0x1f, 0x07, 0x03, 0x01, 0x00, + 0x00, 0x01, 0x03, 0xfa, 0x02, 0x01, 0x00, 0x08, 0x0e, 0x0f, 0x8f, 0xef, 0xff, 0x7f, 0x3f, 0x1f, 0x07, 0x03, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x08, 0x0e, 0x0f, 0xcf, 0xfd, 0x3c, 0x1c, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0c, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }, + + // Soldering + // 3 frames + { + // Soldering 1st frame + // width = 21 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x60, 0xf8, 0xfc, 0xfc, 0x7c, 0x18, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x60, 0xe8, 0xe2, 0xf8, 0x7e, 0x1f, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x66, 0x15, 0x07, 0x0f, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x20, 0x18, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + + // Soldering 2nd frame + // width = 21 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x60, 0xf8, 0xfc, 0xfc, 0x7c, 0x18, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x60, 0xe8, 0xe2, 0xf8, 0x7e, 0x1f, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x66, 0x15, 0x07, 0x0f, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x03, 0x0c, 0x20, 0x18, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + + // Soldering final frame + // width = 21 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x60, 0xf8, 0xfc, 0xfc, 0x7c, 0x18, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x60, 0xe8, 0xe2, 0xf8, 0x7e, 0x1f, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x80, 0xc8, 0xf0, 0x00, 0x00, 0x80, 0x66, 0x15, 0x07, 0x0f, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x03, 0x0d, 0x20, 0x18, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }, + + // Sleep + // 3 frames + { + // Sleep 1st frame + // width = 21 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x60, 0x60, 0xe0, 0xe0, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x1e, 0x1f, 0x1b, 0x19, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + + // Sleep 2nd frame + // width = 21 + // height = 32 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x1c, 0x1c, 0x9c, 0xdc, 0xfc, 0xfc, 0x38, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x60, 0x60, 0xe0, 0xe0, 0xc0, 0x00, 0x18, 0x3e, 0x3f, 0x3f, 0x3b, 0x39, 0x38, 0x10, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x1e, 0x1f, 0x1b, 0x19, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + + // Sleep final frame + // width = 21 + // height = 32 + 0x00, 0x18, 0x3c, 0x3c, 0x3c, 0x3c, 0xbc, 0xfc, 0xfc, 0xfc, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xe0, 0xf8, 0xfc, 0xfe, 0xdf, 0xcf, 0xc7, 0xc3, 0xc1, 0x80, 0x00, 0x08, 0x1c, 0x1c, 0x9c, 0xdc, 0xfc, 0xfc, 0x38, 0x00, + 0x00, 0x01, 0x03, 0x03, 0x03, 0x63, 0x63, 0x63, 0xe3, 0xe3, 0xc1, 0x00, 0x18, 0x3e, 0x3f, 0x3f, 0x3b, 0x39, 0x38, 0x10, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x1e, 0x1f, 0x1b, 0x19, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }, + + // UI + // 3 frames + { + // UI 1st frame + // width = 21 + // height = 32 + 0x00, 0x18, 0x74, 0x08, 0x44, 0x7c, 0x10, 0x7c, 0x10, 0x78, 0x44, 0x08, 0x48, 0x3c, 0x68, 0x08, 0x74, 0x10, 0x7c, 0x08, 0x00, + 0x00, 0x60, 0xc0, 0x60, 0x80, 0xe0, 0x40, 0xe0, 0x20, 0xe0, 0x00, 0x00, 0xf8, 0x04, 0x84, 0x04, 0x04, 0x04, 0x04, 0xf8, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x24, 0x24, 0x24, 0x24, 0x24, 0x24, 0xc3, 0x00, + 0x00, 0x04, 0x03, 0x04, 0x07, 0x05, 0x00, 0x07, 0x02, 0x04, 0x00, 0x00, 0x1f, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x1f, 0x00, + + // UI 2nd frame + // width = 21 + // height = 32 + 0x00, 0x18, 0x74, 0x08, 0x44, 0x7c, 0x10, 0x7c, 0x10, 0x78, 0x44, 0x08, 0x48, 0x3c, 0x68, 0x08, 0x74, 0x10, 0x7c, 0x08, 0x00, + 0x00, 0x60, 0xc0, 0x60, 0x80, 0xe0, 0x40, 0xe0, 0x20, 0xe0, 0x00, 0x00, 0xf8, 0x04, 0x84, 0x04, 0x04, 0x04, 0x04, 0xf8, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x24, 0x24, 0x25, 0x24, 0x24, 0x24, 0xc3, 0x00, + 0x00, 0x04, 0x03, 0x04, 0x07, 0x05, 0x00, 0x07, 0x02, 0x04, 0x00, 0x00, 0x1f, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x1f, 0x00, + + // UI final frame + // width = 21 + // height = 32 + 0x00, 0x18, 0x74, 0x08, 0x44, 0x7c, 0x10, 0x7c, 0x10, 0x78, 0x44, 0x08, 0x48, 0x3c, 0x68, 0x08, 0x74, 0x10, 0x7c, 0x08, 0x00, + 0x00, 0x60, 0xc0, 0x60, 0x80, 0xe0, 0x40, 0xe0, 0x20, 0xe0, 0x00, 0x00, 0xf8, 0x04, 0x84, 0x04, 0xc4, 0x34, 0x04, 0xf8, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x24, 0x24, 0x25, 0x24, 0x24, 0x24, 0xc3, 0x00, + 0x00, 0x04, 0x03, 0x04, 0x07, 0x05, 0x00, 0x07, 0x02, 0x04, 0x00, 0x00, 0x1f, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x1f, 0x00, + }, + + // Advanced + // 3 frames + { + // Advanced 1st frame + // width = 21 + // height = 32 + 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0xe0, 0xf0, 0x74, 0x30, 0xe0, 0x00, 0x00, 0x10, 0x00, 0xf0, 0x00, 0x00, 0x00, 0xf0, 0x00, + 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, + 0x00, 0x80, 0xbf, 0x80, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xf0, 0x08, 0x04, 0x04, 0x44, 0x44, 0x44, 0x48, 0x50, + 0x07, 0x0f, 0x2b, 0x09, 0x07, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x01, 0x02, 0x04, 0x04, 0x04, 0x04, 0x04, 0x02, 0x01, + + // Advanced 2nd frame + // width = 21 + // height = 32 + 0xe0, 0xf0, 0x74, 0x30, 0xe0, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x10, 0x00, 0xc0, 0x00, 0x30, 0x00, + 0x00, 0x01, 0xfd, 0x01, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, + 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x0e, 0x1f, 0xd7, 0x13, 0x0e, 0x00, 0xf0, 0x08, 0x04, 0x04, 0xc4, 0x04, 0x04, 0x08, 0xf0, + 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x01, 0x02, 0x04, 0x00, 0x07, 0x00, 0x04, 0x02, 0x01, + + // Advanced final frame + // width = 21 + // height = 32 + 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x10, 0x00, 0xf0, 0x00, 0xc0, 0x00, + 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x70, 0xf8, 0xbb, 0x98, 0x70, 0x00, 0x00, 0x80, 0xbf, 0x80, 0x00, 0x00, 0xf0, 0x08, 0x04, 0x04, 0x44, 0x24, 0x10, 0x08, 0xe0, + 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x07, 0x0f, 0x2b, 0x09, 0x07, 0x00, 0x01, 0x02, 0x04, 0x04, 0x04, 0x04, 0x04, 0x02, 0x01, + } + }; + #else + #if defined(MODEL_TS100) || defined(MODEL_Pinecil) || defined(MODEL_Pinecilv2) + const uint8_t buttonA[] = { + // width = 42 // height = 16 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x80, - 0x40, - 0xE0, - 0x50, - 0x28, - 0x14, - 0x0A, - 0x06, - 0x00, - 0x00, - 0x48, - 0x26, - 0x10, - 0x08, - 0x04, - 0x03, - 0x02, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - // Soldering final frame - // width = 16 + 0x00, 0x00, 0x00, 0x00, 0xe0, 0x18, 0x04, 0x02, 0x02, 0x01, 0x81, 0x49, 0x31, 0x01, 0xc1, 0x25, 0x19, 0x01, 0xc1, 0x25, 0x19, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x04, 0x18, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x18, 0x20, 0x40, 0x40, 0x80, 0x89, 0x8a, 0x88, 0x94, + 0x8c, 0x94, 0xae, 0x80, 0xbe, 0x8e, 0xa6, 0x8e, 0xa6, 0x8e, 0xa6, 0x8e, 0xa6, 0x8a, 0xa6, 0x8a, 0xa6, 0x8a, 0xa6, 0x8a, 0x46, 0x4a, 0x22, 0x18, 0x07, 0x00, 0x00, 0x00}; + + const uint8_t disconnectedTip[] = { + // width = 42 // height = 16 - 0x00, - 0x80, - 0x40, - 0x00, - 0x00, - 0x00, - 0x00, - 0x80, - 0x40, - 0xE0, - 0x50, - 0x28, - 0x14, - 0x0A, - 0x06, - 0x00, - 0x00, - 0x49, - 0x26, - 0x10, - 0x08, - 0x04, - 0x03, - 0x02, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - }, - - // Sleep - // 3 frames - { - // Sleep 1st frame - // width = 16 + 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0xc0, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xcc, 0x9c, 0x38, 0x70, 0xe0, 0xc0, 0x80, 0x20, 0x70, 0x38, 0x1c, 0xcc, 0x40, + 0x80, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xc0, 0x60, 0xe0, 0x00, 0x01, 0x01, 0x01, 0x02, 0x01, 0x02, 0x05, 0x00, 0x07, 0x01, 0x04, 0x01, 0x04, 0x01, + 0x04, 0x31, 0x38, 0x1c, 0x0e, 0x04, 0x01, 0x03, 0x07, 0x0e, 0x1c, 0x39, 0x30, 0x01, 0x03, 0x00, 0x02, 0x01, 0x02, 0x01, 0x02, 0x01, 0x02, 0x01, 0x04, 0x09, 0x0f, 0x00}; + + #elif defined(MODEL_TS80) || defined(MODEL_TS80P) + const uint8_t buttonA[] = { + // width = 42 // height = 16 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x44, - 0x64, - 0x74, - 0x5C, - 0x4C, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - // Sleep 2nd frame - // width = 16 + 0x00, 0x00, 0x00, 0x00, 0xe0, 0x18, 0x04, 0x02, 0x02, 0x01, 0x81, 0x49, 0x31, 0x01, 0xc1, 0x25, 0x19, 0x01, 0xc1, 0x25, 0x19, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x04, 0x18, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x18, 0x20, 0x40, 0x40, 0x80, 0x81, 0x8a, 0x88, 0x88, + 0x8c, 0x95, 0x80, 0x9c, 0xa6, 0x8e, 0xa6, 0x8c, 0x80, 0x94, 0x8c, 0x94, 0x8c, 0x94, 0x8c, 0x94, 0x80, 0x88, 0x88, 0x88, 0x48, 0x48, 0x20, 0x18, 0x07, 0x00, 0x00, 0x00}; + + const uint8_t disconnectedTip[] = { + // width = 42 // height = 16 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x40, - 0x40, - 0xC0, - 0xC0, - 0xC0, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x44, - 0x64, - 0x74, - 0x5C, - 0x4C, - 0x00, - 0x06, - 0x07, - 0x07, - 0x05, - 0x04, - 0x00, - - // Sleep final frame - // width = 16 + 0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0xc0, 0xc0, 0xc0, 0x80, 0x00, 0x80, 0x80, 0x80, 0x8c, 0x9c, 0x38, 0x70, 0xe0, 0xc0, 0x80, 0x20, 0x70, 0x38, 0x1c, 0x0c, 0x00, + 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0xc0, 0xc0, 0xc0, 0xc0, 0xe0, 0xa0, 0xe0, 0x00, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00, 0x03, 0x04, 0x01, 0x04, 0x01, 0x00, 0x02, 0x01, + 0x02, 0x31, 0x38, 0x1c, 0x0e, 0x04, 0x01, 0x03, 0x07, 0x0e, 0x1c, 0x39, 0x31, 0x01, 0x01, 0x00, 0x02, 0x01, 0x02, 0x01, 0x04, 0x01, 0x04, 0x01, 0x0a, 0x01, 0x0f, 0x00}; + + #elif defined(MODEL_MHP30) + const uint8_t buttonA[] = { + // width = 42 // height = 16 - 0x00, - 0xC6, - 0xE6, - 0xF6, - 0xBE, - 0x9E, - 0x8E, - 0x86, - 0x00, - 0x00, - 0x40, - 0x40, - 0xC0, - 0xC0, - 0xC0, - 0x00, - 0x00, - 0x01, - 0x01, - 0x01, - 0x45, - 0x65, - 0x75, - 0x5D, - 0x4C, - 0x00, - 0x06, - 0x07, - 0x07, - 0x05, - 0x04, - 0x00, - }, - - // UI - // 3 frames - { - // UI 1st frame - // width = 16 - // height = 16 - 0x00, - 0x80, - 0x06, - 0x06, - 0x06, - 0x06, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x00, - 0x00, - 0x00, - 0x60, - 0x60, - 0x00, - 0x00, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x00, - - // UI 2nd frame - // width = 16 + 0x00, 0x00, 0x00, 0x00, 0xe0, 0x18, 0x04, 0x02, 0x02, 0x81, 0x81, 0x41, 0x41, 0x41, 0x41, 0x21, 0x01, 0xc1, 0x25, 0x19, 0x01, 0x81, 0x49, 0x31, 0x01, 0xc1, 0x25, 0x19, + 0x01, 0xa1, 0xa1, 0x41, 0x41, 0x01, 0x02, 0x02, 0x04, 0x18, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x18, 0x20, 0x40, 0x40, 0x83, 0x87, 0x83, 0xab, 0x86, + 0x96, 0x8e, 0xa6, 0x9c, 0xad, 0x8c, 0xb8, 0x89, 0xa4, 0x84, 0x84, 0x92, 0x82, 0x81, 0xa9, 0x80, 0x84, 0x80, 0x81, 0x80, 0x40, 0x40, 0x20, 0x18, 0x07, 0x00, 0x00, 0x00}; + + const uint8_t disconnectedTip[] = { + // width = 42 // height = 16 - 0x00, - 0x80, - 0x06, - 0x06, - 0x06, - 0x06, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x00, - 0x00, - 0x00, - 0x61, - 0x60, - 0x00, - 0x00, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x00, - - // UI final frame - // width = 16 - // height = 16 - 0x00, - 0x80, - 0x06, - 0x86, - 0x46, - 0x06, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x86, - 0x00, - 0x00, - 0x00, - 0x61, - 0x60, - 0x00, - 0x00, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x61, - 0x00, - }, - - // Advanced - // 3 frames - { - // Advanced 1st frame + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x40, 0x40, 0x40, 0x40, 0x20, 0x20, 0x20, 0x20, 0x10, 0x10, 0xd0, 0xc8, 0x08, 0x10, 0x10, 0x10, 0x10, + 0x20, 0x20, 0x20, 0x40, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x04, 0x04, 0x38, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x04, 0x04, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + #endif + + const uint8_t buttonB[] = { + // width = 42 + // height = 16 + 0x00, 0x00, 0x00, 0xe0, 0x18, 0x04, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x71, 0x55, 0x71, 0x01, 0x01, 0xfd, 0x01, 0x01, 0x81, 0xbd, 0x81, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x04, 0x18, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x18, 0x20, 0x40, 0x40, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0xbf, 0x80, 0x80, 0x8e, 0xaa, 0x8e, 0x80, 0x83, 0xba, 0x83, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x40, 0x40, 0x20, 0x18, 0x07, 0x00, 0x00, 0x00, 0x00}; + + // const uint8_t brightnessIcon[] = { + // // width = 16 + // // height = 16 + // 0x80, 0x86, 0x8E, 0x9C, 0x18, 0xC0, 0xE0, 0xEF, 0xEF, 0xE0, 0xC0, 0x18, 0x9C, 0x8E, 0x86, 0x80, 0x01, 0x61, 0x71, 0x39, 0x18, 0x03, 0x07, 0xF7, 0xF7, 0x07, 0x03, 0x18, 0x39, 0x71, 0x61, 0x01}; + + // const uint8_t invertDisplayIcon[] = { + // // width = 24 + // // height = 16 + // 0xFE, 0x01, 0x79, 0x25, 0x79, 0x01, 0xFE, 0x00, 0x20, 0x20, 0x20, 0x20, 0xDF, 0x07, 0x8F, 0xDF, 0xFF, 0x01, 0xFE, 0x86, 0xDA, 0x86, 0xFE, 0x01, + // 0x7F, 0x80, 0xA4, 0xBE, 0xA0, 0x80, 0x7F, 0x00, 0x04, 0x0E, 0x1F, 0x04, 0xFB, 0xFB, 0xFB, 0xFB, 0xFF, 0x80, 0x7F, 0x5B, 0x41, 0x5F, 0x7F, 0x80}; + + const uint8_t RepeatOnce[] = { + // width = 16 + // height = 16 + 0x00, 0xc0, 0xf0, 0x78, 0x1c, 0x0c, 0x0e, 0x06, 0x06, 0x0e, 0x2c, 0x3c, 0x38, 0x3c, 0x00, 0x00, + 0x00, 0x01, 0x08, 0x04, 0x7e, 0x00, 0x00, 0x60, 0x60, 0x70, 0x30, 0x38, 0x1e, 0x0f, 0x03, 0x00}; + + const uint8_t RepeatInf[] = { + // width = 16 + // height = 16 + 0x00, 0xc0, 0xf0, 0x78, 0x1c, 0x0c, 0x0e, 0x06, 0x06, 0x0e, 0x2c, 0x3c, 0x38, 0x3c, 0x00, 0x00, + 0x00, 0x31, 0x49, 0x48, 0x30, 0x48, 0x48, 0x30, 0x00, 0x00, 0x30, 0x38, 0x1e, 0x0f, 0x03, 0x00}; + + const uint8_t UnavailableIcon[] = { // width = 16 // height = 16 - 0x00, - 0xfe, - 0x00, - 0x00, - 0x00, - 0xfe, - 0x00, - 0x00, - 0x0c, - 0x00, - 0x14, - 0x00, - 0x18, - 0x00, - 0x14, - 0x00, - 0x1c, - 0x55, - 0x1c, - 0x00, - 0x1c, - 0x55, - 0x1c, - 0x00, - 0x00, - 0x1c, - 0x22, - 0x41, - 0x49, - 0x11, - 0x22, - 0x0c, + 0x00, 0xc0, 0x30, 0x08, 0x04, 0x04, 0x02, 0x82, 0xc2, 0xe2, 0x74, 0x24, 0x08, 0x30, 0xc0, 0x00, + 0x00, 0x03, 0x0c, 0x10, 0x24, 0x2e, 0x47, 0x43, 0x41, 0x40, 0x20, 0x20, 0x10, 0x0c, 0x03, 0x00}; - // Advanced 2nd frame - // width = 16 - // height = 16 - 0xe0, - 0xae, - 0xe0, - 0x00, - 0x80, - 0xbe, - 0x80, - 0x00, - 0x08, - 0x00, - 0x04, - 0x00, - 0x1c, - 0x00, - 0x08, - 0x00, - 0x00, - 0x7e, - 0x00, - 0x00, - 0x03, - 0x7a, - 0x03, - 0x00, - 0x00, - 0x1c, - 0x22, - 0x01, - 0x79, - 0x01, - 0x22, - 0x1c, - - // Advanced final frame - // width = 16 - // height = 16 - 0x00, - 0x7e, - 0x00, - 0x00, - 0x38, - 0xaa, - 0x38, - 0x00, - 0x04, - 0x00, - 0x0c, - 0x00, - 0x10, - 0x00, - 0x1c, - 0x00, - 0x07, - 0x75, - 0x07, - 0x00, - 0x00, - 0x7f, - 0x00, - 0x00, - 0x00, - 0x0c, - 0x22, - 0x11, - 0x49, - 0x41, - 0x22, - 0x1c, - }, -#ifdef NOTUSED - - // Calibration (Not used, kept for future menu layouts) - // 3 frames - { - // Calibration 1st frame (Not used, kept for future menu layouts) - // width = 16 - // height = 16 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x80, - 0xC0, - 0xE0, - 0x70, - 0x3A, - 0x1E, - 0x0E, - 0x1C, - 0x30, - 0x00, - 0x00, - 0x10, - 0x3A, - 0x1C, - 0x1E, - 0x17, - 0x23, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - // Calibration 2nd frame (Not used, kept for future menu layouts) - // width = 16 - // height = 16 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x40, - 0x80, - 0xC0, - 0xE0, - 0x70, - 0x3A, - 0x1E, - 0x0E, - 0x1C, - 0x30, - 0x00, - 0x00, - 0x10, - 0x38, - 0x1C, - 0x0E, - 0x07, - 0x03, - 0x03, - 0x02, - 0x04, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - // Calibration final frame (Not used, kept for future menu layouts) - // width = 16 - // height = 16 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x80, - 0xC0, - 0xE8, - 0x70, - 0x7A, - 0x5E, - 0x8E, - 0x1C, - 0x30, - 0x00, - 0x00, - 0x10, - 0x38, - 0x1C, - 0x0E, - 0x07, - 0x03, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - } -#endif -}; - -#endif /* FONT_H_ */ + #define SETTINGS_ICON_WIDTH 16 + #define SETTINGS_ICON_HEIGHT 16 + /* + * 16x16 icons + * 32 * 3 = Frame size * Frame count + * */ + const uint8_t SettingsMenuIcons[][32 * 3] = { + // Power + // 3 frames + { + // Power 1st frame + // width = 16 + // height = 16 + 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x17, 0x0f, 0x05, 0x00, 0x00, 0x00, 0x00, // + 0x00, 0x1c, 0x55, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // + + // Power 2nd frame + // width = 16 + // height = 16 + 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x10, 0x1c, 0xdf, 0x77, 0x33, 0x11, 0x00, 0x00, 0x00, // + 0x00, 0x07, 0x75, 0x07, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // + + // Power final frame + // width = 16 + // height = 16 + 0x00, 0x38, 0xaa, 0x38, 0x00, 0x20, 0x30, 0x3c, 0xff, 0xff, 0xff, 0x77, 0x33, 0x13, 0x01, 0x00, // + 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x42, 0x33, 0x1f, 0x0f, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00, // + }, + + // Soldering + // 3 frames + { + // Soldering 1st frame + // width = 16 + // height = 16 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0xE0, 0x50, 0x28, 0x14, 0x0A, 0x06, 0x00, // + 0x00, 0x40, 0x20, 0x10, 0x08, 0x04, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // + + // Soldering 2nd frame + // width = 16 + // height = 16 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0xE0, 0x50, 0x28, 0x14, 0x0A, 0x06, 0x00, // + 0x00, 0x48, 0x26, 0x10, 0x08, 0x04, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // + + // Soldering final frame + // width = 16 + // height = 16 + 0x00, 0x80, 0x40, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0xE0, 0x50, 0x28, 0x14, 0x0A, 0x06, 0x00, // + 0x00, 0x49, 0x26, 0x10, 0x08, 0x04, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // + }, + + // Sleep + // 3 frames + { + // Sleep 1st frame + // width = 16 + // height = 16 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // + 0x00, 0x00, 0x00, 0x00, 0x44, 0x64, 0x74, 0x5C, 0x4C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // + + // Sleep 2nd frame + // width = 16 + // height = 16 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x40, 0xC0, 0xC0, 0xC0, 0x00, // + 0x00, 0x00, 0x00, 0x00, 0x44, 0x64, 0x74, 0x5C, 0x4C, 0x00, 0x06, 0x07, 0x07, 0x05, 0x04, 0x00, // + + // Sleep final frame + // width = 16 + // height = 16 + 0x00, 0xC6, 0xE6, 0xF6, 0xBE, 0x9E, 0x8E, 0x86, 0x00, 0x00, 0x40, 0x40, 0xC0, 0xC0, 0xC0, 0x00, // + 0x00, 0x01, 0x01, 0x01, 0x45, 0x65, 0x75, 0x5D, 0x4C, 0x00, 0x06, 0x07, 0x07, 0x05, 0x04, 0x00, // + }, + + // UI + // 3 frames + { + // UI 1st frame + // width = 16 + // height = 16 + 0x00, 0x80, 0x06, 0x06, 0x06, 0x06, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x00, // + 0x00, 0x00, 0x60, 0x60, 0x00, 0x00, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x00, // + + // UI 2nd frame + // width = 16 + // height = 16 + 0x00, 0x80, 0x06, 0x06, 0x06, 0x06, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x00, // + 0x00, 0x00, 0x61, 0x60, 0x00, 0x00, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x00, // + + // UI final frame + // width = 16 + // height = 16 + 0x00, 0x80, 0x06, 0x86, 0x46, 0x06, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x00, // + 0x00, 0x00, 0x61, 0x60, 0x00, 0x00, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x00, // + }, + + // Advanced + // 3 frames + { + // Advanced 1st frame + // width = 16 + // height = 16 + 0x00, 0xfe, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x0c, 0x00, 0x14, 0x00, 0x18, 0x00, 0x14, 0x00, // + 0x1c, 0x55, 0x1c, 0x00, 0x1c, 0x55, 0x1c, 0x00, 0x00, 0x1c, 0x22, 0x41, 0x49, 0x11, 0x22, 0x0c, // + + // Advanced 2nd frame + // width = 16 + // height = 16 + 0xe0, 0xae, 0xe0, 0x00, 0x80, 0xbe, 0x80, 0x00, 0x08, 0x00, 0x04, 0x00, 0x1c, 0x00, 0x08, 0x00, // + 0x00, 0x7e, 0x00, 0x00, 0x03, 0x7a, 0x03, 0x00, 0x00, 0x1c, 0x22, 0x01, 0x79, 0x01, 0x22, 0x1c, // + + // Advanced final frame + // width = 16 + // height = 16 + 0x00, 0x7e, 0x00, 0x00, 0x38, 0xaa, 0x38, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x1c, 0x00,// + 0x07, 0x75, 0x07, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x0c, 0x22, 0x11, 0x49, 0x41, 0x22, 0x1c,// + }, + #ifdef NOTUSED + + // Calibration (Not used, kept for future menu layouts) + // 3 frames + { + // Calibration 1st frame (Not used, kept for future menu layouts) + // width = 16 + // height = 16 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x3A, 0x1E, 0x0E, 0x1C, 0x30, 0x00,// + 0x00, 0x10, 0x3A, 0x1C, 0x1E, 0x17, 0x23, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,// + + // Calibration 2nd frame (Not used, kept for future menu layouts) + // width = 16 + // height = 16 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x80, 0xC0, 0xE0, 0x70, 0x3A, 0x1E, 0x0E, 0x1C, 0x30, 0x00, // + 0x00, 0x10, 0x38, 0x1C, 0x0E, 0x07, 0x03, 0x03, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // + + // Calibration final frame (Not used, kept for future menu layouts) + // width = 16 + // height = 16 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE8, 0x70, 0x7A, 0x5E, 0x8E, 0x1C, 0x30, 0x00, // + 0x00, 0x10, 0x38, 0x1C, 0x0E, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // + + #endif + }; + #endif +// clang-format on +#endif /* FONT_H_ */ \ No newline at end of file diff --git a/source/Core/Drivers/HUB238.cpp b/source/Core/Drivers/HUB238.cpp index 6d2940b00..2dfd37da9 100644 --- a/source/Core/Drivers/HUB238.cpp +++ b/source/Core/Drivers/HUB238.cpp @@ -1,6 +1,6 @@ #include "HUB238.hpp" #include "I2CBB2.hpp" -#include "Utils.h" +#include "Utils.hpp" #include "configuration.h" #if POW_PD_EXT == 1 diff --git a/source/Core/Drivers/I2CBB1.cpp b/source/Core/Drivers/I2CBB1.cpp index bda0da18e..bc250b358 100644 --- a/source/Core/Drivers/I2CBB1.cpp +++ b/source/Core/Drivers/I2CBB1.cpp @@ -45,8 +45,9 @@ void I2CBB1::init() { } bool I2CBB1::probe(uint8_t address) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(address); stop(); @@ -55,8 +56,9 @@ bool I2CBB1::probe(uint8_t address) { } bool I2CBB1::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -91,8 +93,9 @@ bool I2CBB1::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, } bool I2CBB1::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, const uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -123,8 +126,9 @@ bool I2CBB1::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, const uint8_t * } void I2CBB1::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -147,8 +151,9 @@ void I2CBB1::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { } void I2CBB1::Receive(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return; + } start(); bool ack = send(DevAddress | 1); if (!ack) { @@ -166,10 +171,12 @@ void I2CBB1::Receive(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { } void I2CBB1::TransmitReceive(uint16_t DevAddress, uint8_t *pData_tx, uint16_t Size_tx, uint8_t *pData_rx, uint16_t Size_rx) { - if (Size_tx == 0 && Size_rx == 0) + if (Size_tx == 0 && Size_rx == 0) { return; - if (lock() == false) + } + if (lock() == false) { return; + } if (Size_tx) { start(); bool ack = send(DevAddress); @@ -251,10 +258,11 @@ uint8_t I2CBB1::read(bool ack) { } SOFT_SDA1_HIGH(); - if (ack) + if (ack) { write_bit(0); - else + } else { write_bit(1); + } return B; } @@ -266,10 +274,11 @@ uint8_t I2CBB1::read_bit() { SOFT_SCL1_HIGH(); SOFT_I2C_DELAY(); - if (SOFT_SDA1_READ()) + if (SOFT_SDA1_READ()) { b = 1; - else + } else { b = 0; + } SOFT_SCL1_LOW(); return b; @@ -278,7 +287,8 @@ uint8_t I2CBB1::read_bit() { void I2CBB1::unlock() { xSemaphoreGive(I2CSemaphore); } bool I2CBB1::lock() { - if (I2CSemaphore == NULL) {} + if (I2CSemaphore == NULL) { + } bool a = xSemaphoreTake(I2CSemaphore, (TickType_t)100) == pdTRUE; return a; } @@ -309,9 +319,22 @@ bool I2CBB1::writeRegistersBulk(const uint8_t address, const I2C_REG *registers, if (!I2C_RegisterWrite(address, registers[index].reg, registers[index].val)) { return false; } - if (registers[index].pause_ms) + if (registers[index].pause_ms) { delay_ms(registers[index].pause_ms); + } } return true; } + +bool I2CBB1::wakePart(uint16_t DevAddress) { + // wakepart is a special case where only the device address is sent + if (!lock()) { + return false; + } + start(); + bool ack = send(DevAddress); + stop(); + unlock(); + return ack; +} #endif diff --git a/source/Core/Drivers/I2CBB1.hpp b/source/Core/Drivers/I2CBB1.hpp index 406560518..45863e7e3 100644 --- a/source/Core/Drivers/I2CBB1.hpp +++ b/source/Core/Drivers/I2CBB1.hpp @@ -36,6 +36,7 @@ class I2CBB1 { const uint8_t pause_ms; // How many ms to pause _after_ writing this reg } I2C_REG; static bool writeRegistersBulk(const uint8_t address, const I2C_REG *registers, const uint8_t registersLength); + static bool wakePart(uint16_t DevAddress); private: static SemaphoreHandle_t I2CSemaphore; diff --git a/source/Core/Drivers/I2CBB2.cpp b/source/Core/Drivers/I2CBB2.cpp index 2d268b495..fee68bd16 100644 --- a/source/Core/Drivers/I2CBB2.cpp +++ b/source/Core/Drivers/I2CBB2.cpp @@ -44,8 +44,9 @@ void I2CBB2::init() { } bool I2CBB2::probe(uint8_t address) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(address); stop(); @@ -54,8 +55,9 @@ bool I2CBB2::probe(uint8_t address) { } bool I2CBB2::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -90,8 +92,9 @@ bool I2CBB2::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, } bool I2CBB2::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, const uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return false; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -122,8 +125,9 @@ bool I2CBB2::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, const uint8_t * } void I2CBB2::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return; + } start(); bool ack = send(DevAddress); if (!ack) { @@ -146,8 +150,9 @@ void I2CBB2::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { } void I2CBB2::Receive(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { - if (!lock()) + if (!lock()) { return; + } start(); bool ack = send(DevAddress | 1); if (!ack) { @@ -165,10 +170,12 @@ void I2CBB2::Receive(uint16_t DevAddress, uint8_t *pData, uint16_t Size) { } void I2CBB2::TransmitReceive(uint16_t DevAddress, uint8_t *pData_tx, uint16_t Size_tx, uint8_t *pData_rx, uint16_t Size_rx) { - if (Size_tx == 0 && Size_rx == 0) + if (Size_tx == 0 && Size_rx == 0) { return; - if (lock() == false) + } + if (lock() == false) { return; + } if (Size_tx) { start(); bool ack = send(DevAddress); @@ -250,10 +257,11 @@ uint8_t I2CBB2::read(bool ack) { } SOFT_SDA2_HIGH(); - if (ack) + if (ack) { write_bit(0); - else + } else { write_bit(1); + } return B; } @@ -265,10 +273,11 @@ uint8_t I2CBB2::read_bit() { SOFT_SCL2_HIGH(); SOFT_I2C_DELAY(); - if (SOFT_SDA2_READ()) + if (SOFT_SDA2_READ()) { b = 1; - else + } else { b = 0; + } SOFT_SCL2_LOW(); return b; @@ -277,7 +286,8 @@ uint8_t I2CBB2::read_bit() { void I2CBB2::unlock() { xSemaphoreGive(I2CSemaphore); } bool I2CBB2::lock() { - if (I2CSemaphore == NULL) {} + if (I2CSemaphore == NULL) { + } bool a = xSemaphoreTake(I2CSemaphore, (TickType_t)100) == pdTRUE; return a; } @@ -308,9 +318,22 @@ bool I2CBB2::writeRegistersBulk(const uint8_t address, const I2C_REG *registers, if (!I2C_RegisterWrite(address, registers[index].reg, registers[index].val)) { return false; } - if (registers[index].pause_ms) + if (registers[index].pause_ms) { delay_ms(registers[index].pause_ms); + } } return true; } + +bool I2CBB2::wakePart(uint16_t DevAddress) { + // wakepart is a special case where only the device address is sent + if (!lock()) { + return false; + } + start(); + bool ack = send(DevAddress); + stop(); + unlock(); + return ack; +} #endif diff --git a/source/Core/Drivers/I2CBB2.hpp b/source/Core/Drivers/I2CBB2.hpp index 389a6a63d..09202180e 100644 --- a/source/Core/Drivers/I2CBB2.hpp +++ b/source/Core/Drivers/I2CBB2.hpp @@ -36,6 +36,7 @@ class I2CBB2 { const uint8_t pause_ms; // How many ms to pause _after_ writing this reg } I2C_REG; static bool writeRegistersBulk(const uint8_t address, const I2C_REG *registers, const uint8_t registersLength); + static bool wakePart(uint16_t DevAddress); private: static SemaphoreHandle_t I2CSemaphore; diff --git a/source/Core/Drivers/LIS2DH12.cpp b/source/Core/Drivers/LIS2DH12.cpp index 2abb0216e..86c146d93 100644 --- a/source/Core/Drivers/LIS2DH12.cpp +++ b/source/Core/Drivers/LIS2DH12.cpp @@ -5,24 +5,26 @@ * Author: Ralim */ -#include - #include "LIS2DH12.hpp" #include "cmsis_os.h" +#include "configuration.h" +#include -static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = {{LIS_CTRL_REG1, 0x17, 0}, // 25Hz - {LIS_CTRL_REG2, 0b00001000, 0}, // Highpass filter off - {LIS_CTRL_REG3, 0b01100000, 0}, // Setup interrupt pins - {LIS_CTRL_REG4, 0b00001000, 0}, // Block update mode off, HR on - {LIS_CTRL_REG5, 0b00000010, 0}, // - {LIS_CTRL_REG6, 0b01100010, 0}, - // Basically setup the unit to run, and enable 4D orientation detection - {LIS_INT2_CFG, 0b01111110, 0}, // setup for movement detection - {LIS_INT2_THS, 0x28, 0}, // - {LIS_INT2_DURATION, 64, 0}, // - {LIS_INT1_CFG, 0b01111110, 0}, // - {LIS_INT1_THS, 0x28, 0}, // - {LIS_INT1_DURATION, 64, 0}}; +static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = { + { LIS_CTRL_REG1, 0x17, 0}, // 25Hz + { LIS_CTRL_REG2, 0b00001000, 0}, // Highpass filter off + { LIS_CTRL_REG3, 0b01100000, 0}, // Setup interrupt pins + { LIS_CTRL_REG4, 0b00001000, 0}, // Block update mode off, HR on + { LIS_CTRL_REG5, 0b00000010, 0}, // + { LIS_CTRL_REG6, 0b01100010, 0}, + // Basically setup the unit to run, and enable 4D orientation detection + { LIS_INT2_CFG, 0b01111110, 0}, // setup for movement detection + { LIS_INT2_THS, 0x28, 0}, // + {LIS_INT2_DURATION, 64, 0}, // + { LIS_INT1_CFG, 0b01111110, 0}, // + { LIS_INT1_THS, 0x28, 0}, // + {LIS_INT1_DURATION, 64, 0} +}; bool LIS2DH12::initalize() { return ACCEL_I2C_CLASS::writeRegistersBulk(LIS2DH_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); } @@ -43,15 +45,21 @@ bool LIS2DH12::detect() { // Read chip id to ensure its not an address collision uint8_t id = 0; if (ACCEL_I2C_CLASS::Mem_Read(LIS2DH_I2C_ADDRESS, LIS2DH_WHOAMI_REG, &id, 1)) { +#ifdef ACCEL_LIS_CLONE return (id == LIS2DH_WHOAMI_ID) || (id == LIS2DH_CLONE_WHOAMI_ID); +#else + return (id == LIS2DH_WHOAMI_ID); +#endif } return false; // cant read ID } bool LIS2DH12::isClone() { +#ifdef ACCEL_LIS_CLONE uint8_t id = 0; if (ACCEL_I2C_CLASS::Mem_Read(LIS2DH_I2C_ADDRESS, LIS2DH_WHOAMI_REG, &id, 1)) { return (id == LIS2DH_CLONE_WHOAMI_ID); } +#endif return false; } \ No newline at end of file diff --git a/source/Core/Drivers/MMA8652FC.cpp b/source/Core/Drivers/MMA8652FC.cpp index 3d0fa0d77..d56f14eb0 100644 --- a/source/Core/Drivers/MMA8652FC.cpp +++ b/source/Core/Drivers/MMA8652FC.cpp @@ -5,32 +5,36 @@ * Author: Ben V. Brown */ +#include "MMA8652FC.hpp" +#include "accelerometers_common.h" +#include "cmsis_os.h" #include #include "MMA8652FC.hpp" +#include "accelerometers_common.h" #include "cmsis_os.h" -static const FRToSI2C::I2C_REG i2c_registers[] = { - {CTRL_REG2, 0, 0}, // Normal mode - {CTRL_REG2, 0x40, 2}, // Reset all registers to POR values - {FF_MT_CFG_REG, 0x78, 0}, // Enable motion detection for X, Y, Z axis, latch disabled - {PL_CFG_REG, 0x40, 0}, // Enable the orientation detection - {PL_COUNT_REG, 200, 0}, // 200 count debounce - {PL_BF_ZCOMP_REG, 0b01000111, 0}, // Set the threshold to 42 degrees - {P_L_THS_REG, 0b10011100, 0}, // Up the trip angles - {CTRL_REG4, 0x01 | (1 << 4), 0}, // Enable dataready interrupt & orientation interrupt - {CTRL_REG5, 0x01, 0}, // Route data ready interrupts to INT1 ->PB5 ->EXTI5, leaving orientation routed to INT2 - {CTRL_REG2, 0x12, 0}, // Set maximum resolution oversampling - {XYZ_DATA_CFG_REG, (1 << 4), 0}, // select high pass filtered data - {HP_FILTER_CUTOFF_REG, 0x03, 0}, // select high pass filtered data - {CTRL_REG1, 0x19, 0} // ODR=12 Hz, Active mode +static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = { + { CTRL_REG2, 0, 0}, // Normal mode + { CTRL_REG2, 0x40, 2}, // Reset all registers to POR values + { FF_MT_CFG_REG, 0x78, 0}, // Enable motion detection for X, Y, Z axis, latch disabled + { PL_CFG_REG, 0x40, 0}, // Enable the orientation detection + { PL_COUNT_REG, 200, 0}, // 200 count debounce + { PL_BF_ZCOMP_REG, 0b01000111, 0}, // Set the threshold to 42 degrees + { P_L_THS_REG, 0b10011100, 0}, // Up the trip angles + { CTRL_REG4, 0x01 | (1 << 4), 0}, // Enable dataready interrupt & orientation interrupt + { CTRL_REG5, 0x01, 0}, // Route data ready interrupts to INT1 ->PB5 ->EXTI5, leaving orientation routed to INT2 + { CTRL_REG2, 0x12, 0}, // Set maximum resolution oversampling + { XYZ_DATA_CFG_REG, (1 << 4), 0}, // select high pass filtered data + {HP_FILTER_CUTOFF_REG, 0x03, 0}, // select high pass filtered data + { CTRL_REG1, 0x19, 0} // ODR=12 Hz, Active mode }; -bool MMA8652FC::initalize() { return FRToSI2C::writeRegistersBulk(MMA8652FC_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); } +bool MMA8652FC::initalize() { return ACCEL_I2C_CLASS::writeRegistersBulk(MMA8652FC_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); } Orientation MMA8652FC::getOrientation() { // First read the PL_STATUS register - uint8_t plStatus = FRToSI2C::I2C_RegisterRead(MMA8652FC_I2C_ADDRESS, PL_STATUS_REG); + uint8_t plStatus = ACCEL_I2C_CLASS::I2C_RegisterRead(MMA8652FC_I2C_ADDRESS, PL_STATUS_REG); if ((plStatus & 0b10000000) == 0b10000000) { plStatus >>= 1; // We don't need the up/down bit plStatus &= 0x03; // mask to the two lower bits @@ -47,11 +51,11 @@ Orientation MMA8652FC::getOrientation() { void MMA8652FC::getAxisReadings(int16_t &x, int16_t &y, int16_t &z) { std::array sensorData; - FRToSI2C::Mem_Read(MMA8652FC_I2C_ADDRESS, OUT_X_MSB_REG, reinterpret_cast(sensorData.begin()), sensorData.size() * sizeof(int16_t)); + ACCEL_I2C_CLASS::Mem_Read(MMA8652FC_I2C_ADDRESS, OUT_X_MSB_REG, reinterpret_cast(sensorData.begin()), sensorData.size() * sizeof(int16_t)); x = static_cast(__builtin_bswap16(*reinterpret_cast(&sensorData[0]))); y = static_cast(__builtin_bswap16(*reinterpret_cast(&sensorData[1]))); z = static_cast(__builtin_bswap16(*reinterpret_cast(&sensorData[2]))); } -bool MMA8652FC::detect() { return FRToSI2C::probe(MMA8652FC_I2C_ADDRESS); } +bool MMA8652FC::detect() { return ACCEL_I2C_CLASS::probe(MMA8652FC_I2C_ADDRESS); } diff --git a/source/Core/Drivers/MSA301.cpp b/source/Core/Drivers/MSA301.cpp index 3e1b9e460..d439d1c48 100644 --- a/source/Core/Drivers/MSA301.cpp +++ b/source/Core/Drivers/MSA301.cpp @@ -6,26 +6,27 @@ */ #include "MSA301_defines.h" +#include "accelerometers_common.h" #include + #define MSA301_I2C_ADDRESS 0x26 << 1 -bool MSA301::detect() { return FRToSI2C::probe(MSA301_I2C_ADDRESS); } +bool MSA301::detect() { return ACCEL_I2C_CLASS::probe(MSA301_I2C_ADDRESS); } -static const FRToSI2C::I2C_REG i2c_registers[] = { +static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = { // // - {MSA301_REG_ODR, 0b00001000, 1}, // X/Y/Z enabled @ 250Hz - {MSA301_REG_POWERMODE, 0b0001001, 1}, // Normal mode - {MSA301_REG_RESRANGE, 0b00000001, 0}, // 14bit resolution @ 4G range + { MSA301_REG_ODR, 0b00001000, 1}, // X/Y/Z enabled @ 250Hz + {MSA301_REG_POWERMODE, 0b0001001, 1}, // Normal mode + { MSA301_REG_RESRANGE, 0b00000001, 0}, // 14bit resolution @ 4G range {MSA301_REG_ORIENT_HY, 0b01000000, 0}, // 4*62.5mg hyst, no blocking, symmetrical - {MSA301_REG_INTSET0, 1 << 6, 0}, // Turn on orientation detection (by enabling its interrupt) - + { MSA301_REG_INTSET0, 1 << 6, 0}, // Turn on orientation detection (by enabling its interrupt) }; -bool MSA301::initalize() { return FRToSI2C::writeRegistersBulk(MSA301_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); } +bool MSA301::initalize() { return ACCEL_I2C_CLASS::writeRegistersBulk(MSA301_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); } Orientation MSA301::getOrientation() { uint8_t temp = 0; - FRToSI2C::Mem_Read(MSA301_I2C_ADDRESS, MSA301_REG_ORIENT_STATUS, &temp, 1); + ACCEL_I2C_CLASS::Mem_Read(MSA301_I2C_ADDRESS, MSA301_REG_ORIENT_STATUS, &temp, 1); switch (temp) { case 112: return Orientation::ORIENTATION_LEFT_HAND; @@ -39,7 +40,7 @@ Orientation MSA301::getOrientation() { void MSA301::getAxisReadings(int16_t &x, int16_t &y, int16_t &z) { uint8_t temp[6]; // Bulk read all 6 regs - FRToSI2C::Mem_Read(MSA301_I2C_ADDRESS, MSA301_REG_OUT_X_L, temp, 6); + ACCEL_I2C_CLASS::Mem_Read(MSA301_I2C_ADDRESS, MSA301_REG_OUT_X_L, temp, 6); x = int16_t(((int16_t)temp[1]) << 8 | temp[0]) >> 2; y = int16_t(((int16_t)temp[3]) << 8 | temp[2]) >> 2; z = int16_t(((int16_t)temp[5]) << 8 | temp[4]) >> 2; diff --git a/source/Core/Drivers/OLED.cpp b/source/Core/Drivers/OLED.cpp index 27f103fc5..fc699bef0 100644 --- a/source/Core/Drivers/OLED.cpp +++ b/source/Core/Drivers/OLED.cpp @@ -6,10 +6,12 @@ */ #include "Buttons.hpp" +#include "Settings.h" #include "Translation.h" #include "cmsis_os.h" #include "configuration.h" #include +#include #include #include @@ -22,9 +24,9 @@ OLED::DisplayState OLED::displayState; int16_t OLED::cursor_x, OLED::cursor_y; bool OLED::initDone = false; uint8_t OLED::displayOffset; -uint8_t OLED::screenBuffer[16 + (OLED_WIDTH * (OLED_HEIGHT / 8)) + 10]; // The data buffer -uint8_t OLED::secondFrameBuffer[16 + (OLED_WIDTH * (OLED_HEIGHT / 8)) + 10]; -uint32_t OLED::displayChecksum; +alignas(uint32_t) uint8_t OLED::screenBuffer[16 + (OLED_WIDTH * (OLED_HEIGHT / 8)) + 10]; // The data buffer +alignas(uint32_t) uint8_t OLED::secondFrameBuffer[16 + (OLED_WIDTH * (OLED_HEIGHT / 8)) + 10]; +uint32_t OLED::displayChecksum; /* * Setup params for the OLED screen * http://www.displayfuture.com/Display/datasheet/controller/SSD1307.pdf @@ -33,35 +35,35 @@ uint32_t OLED::displayChecksum; */ I2C_CLASS::I2C_REG OLED_Setup_Array[] = { /**/ - {0x80, OLED_OFF, 0}, /* Display off */ - {0x80, OLED_DIVIDER, 0}, /* Set display clock divide ratio / osc freq */ - {0x80, 0x52, 0}, /* Divide ratios */ - {0x80, 0xA8, 0}, /* Set Multiplex Ratio */ - {0x80, OLED_HEIGHT - 1, 0}, /* Multiplex ratio adjusts how far down the matrix it scans */ - {0x80, 0xC0, 0}, /* Set COM Scan direction */ - {0x80, 0xD3, 0}, /* Set vertical Display offset */ - {0x80, 0x00, 0}, /* 0 Offset */ - {0x80, 0x40, 0}, /* Set Display start line to 0 */ + {0x80, OLED_OFF, 0}, /* Display off */ + {0x80, OLED_DIVIDER, 0}, /* Set display clock divide ratio / osc freq */ + {0x80, 0x52, 0}, /* Divide ratios */ + {0x80, 0xA8, 0}, /* Set Multiplex Ratio */ + {0x80, OLED_HEIGHT - 1, 0}, /* Multiplex ratio adjusts how far down the matrix it scans */ + {0x80, 0xC0, 0}, /* Set COM Scan direction */ + {0x80, 0xD3, 0}, /* Set vertical Display offset */ + {0x80, 0x00, 0}, /* 0 Offset */ + {0x80, 0x40, 0}, /* Set Display start line to 0 */ #ifdef OLED_SEGMENT_MAP_REVERSED - {0x80, 0xA1, 0}, /* Set Segment remap to normal */ + {0x80, 0xA1, 0}, /* Set Segment remap to normal */ #else {0x80, 0xA0, 0}, /* Set Segment remap to normal */ #endif - {0x80, 0x8D, 0}, /* Charge Pump */ - {0x80, 0x14, 0}, /* Charge Pump settings */ - {0x80, 0xDA, 0}, /* Set VCOM Pins hardware config */ + {0x80, 0x8D, 0}, /* Charge Pump */ + {0x80, 0x14, 0}, /* Charge Pump settings */ + {0x80, 0xDA, 0}, /* Set VCOM Pins hardware config */ {0x80, OLED_VCOM_LAYOUT, 0}, /* Combination 0x2 or 0x12 depending on OLED model */ - {0x80, 0x81, 0}, /* Brightness */ - {0x80, 0x00, 0}, /* ^0 */ - {0x80, 0xD9, 0}, /* Set pre-charge period */ - {0x80, 0xF1, 0}, /* Pre charge period */ - {0x80, 0xDB, 0}, /* Adjust VCOMH regulator ouput */ - {0x80, 0x30, 0}, /* VCOM level */ - {0x80, 0xA4, 0}, /* Enable the display GDDR */ - {0x80, 0xA6, 0}, /* Normal display */ - {0x80, 0x20, 0}, /* Memory Mode */ - {0x80, 0x00, 0}, /* Wrap memory */ - {0x80, OLED_ON, 0}, /* Display on */ + {0x80, 0x81, 0}, /* Brightness */ + {0x80, 0x00, 0}, /* ^0 */ + {0x80, 0xD9, 0}, /* Set pre-charge period */ + {0x80, 0xF1, 0}, /* Pre charge period */ + {0x80, 0xDB, 0}, /* Adjust VCOMH regulator ouput */ + {0x80, 0x30, 0}, /* VCOM level */ + {0x80, 0xA4, 0}, /* Enable the display GDDR */ + {0x80, 0xA6, 0}, /* Normal display */ + {0x80, 0x20, 0}, /* Memory Mode */ + {0x80, 0x00, 0}, /* Wrap memory */ + {0x80, OLED_ON, 0}, /* Display on */ }; // Setup based on the SSD1307 and modified for the SSD1306 @@ -160,7 +162,7 @@ void OLED::setFramebuffer(uint8_t *buffer) { * UTF font handling is done using the two input chars. * Precursor is the command char that is used to select the table. */ -void OLED::drawChar(const uint16_t charCode, const FontStyle fontStyle) { +void OLED::drawChar(const uint16_t charCode, const FontStyle fontStyle, const uint8_t soft_x_limit) { const uint8_t *currentFont; static uint8_t fontWidth, fontHeight; uint16_t index; @@ -174,12 +176,6 @@ void OLED::drawChar(const uint16_t charCode, const FontStyle fontStyle) { case FontStyle::SMALL: case FontStyle::LARGE: default: - if (charCode == '\x01' && cursor_y == 0) { // 0x01 is used as new line char - setCursor(0, 8); - return; - } else if (charCode <= 0x01) { - return; - } currentFont = nullptr; index = 0; switch (fontStyle) { @@ -193,6 +189,12 @@ void OLED::drawChar(const uint16_t charCode, const FontStyle fontStyle) { fontWidth = 12; break; } + if (charCode == '\x01' && cursor_y == 0) { // 0x01 is used as new line char + setCursor(soft_x_limit, fontHeight); + return; + } else if (charCode <= 0x01) { + return; + } currentFont = fontStyle == FontStyle::SMALL ? FontSectionInfo.font06_start_ptr : FontSectionInfo.font12_start_ptr; index = charCode - 2; @@ -208,18 +210,20 @@ void OLED::drawChar(const uint16_t charCode, const FontStyle fontStyle) { * of the indicator in pixels (0..<16). */ void OLED::drawScrollIndicator(uint8_t y, uint8_t height) { - union u_type { - uint16_t whole; - uint8_t strips[2]; - } column; - - column.whole = (1 << height) - 1; - column.whole <<= y; + const uint32_t whole = ((1 << height) - 1) << y; // preload a set of set bits of height + // Shift down by the y value + const uint8_t strips[4] = {static_cast(whole & 0xff), static_cast((whole & 0xff00) >> 8 * 1), static_cast((whole & 0xff0000) >> 8 * 2), + static_cast((whole & 0xff000000) >> 8 * 3)}; // Draw a one pixel wide bar to the left with a single pixel as // the scroll indicator. - fillArea(OLED_WIDTH - 1, 0, 1, 8, column.strips[0]); - fillArea(OLED_WIDTH - 1, 8, 1, 8, column.strips[1]); + fillArea(OLED_WIDTH - 1, 0, 1, 8, strips[0]); + fillArea(OLED_WIDTH - 1, 8, 1, 8, strips[1]); +#if OLED_HEIGHT == 32 + fillArea(OLED_WIDTH - 1, 16, 1, 8, strips[2]); + fillArea(OLED_WIDTH - 1, 24, 1, 8, strips[3]); + +#endif } /** @@ -262,22 +266,25 @@ void OLED::maskScrollIndicatorOnOLED() { * If forward is true, this displays a forward navigation to the second framebuffer contents. * Otherwise a rewinding navigation animation is shown to the second framebuffer contents. */ -void OLED::transitionSecondaryFramebuffer(bool forwardNavigation) { +void OLED::transitionSecondaryFramebuffer(const bool forwardNavigation, const TickType_t viewEnterTime) { + bool buttonsReleased = getButtonState() == BUTTON_NONE; uint8_t *stripBackPointers[4]; stripBackPointers[0] = &secondFrameBuffer[FRAMEBUFFER_START + 0]; stripBackPointers[1] = &secondFrameBuffer[FRAMEBUFFER_START + OLED_WIDTH]; #ifdef OLED_128x32 - stripBackPointers[2] = &secondFrameBuffer[OLED_WIDTH * 2]; - stripBackPointers[3] = &secondFrameBuffer[OLED_WIDTH * 3]; + stripBackPointers[2] = &secondFrameBuffer[FRAMEBUFFER_START + (OLED_WIDTH * 2)]; + stripBackPointers[3] = &secondFrameBuffer[FRAMEBUFFER_START + (OLED_WIDTH * 3)]; #endif /* OLED_128x32 */ TickType_t totalDuration = TICKS_100MS * 5; // 500ms TickType_t duration = 0; TickType_t start = xTaskGetTickCount(); uint8_t offset = 0; + uint32_t loopCounter = 0; TickType_t startDraw = xTaskGetTickCount(); while (duration <= totalDuration) { + loopCounter++; duration = xTaskGetTickCount() - start; uint16_t progress = ((duration * 100) / totalDuration); // Percentage of the period we are through for animation progress = easeInOutTiming(progress); @@ -315,12 +322,23 @@ void OLED::transitionSecondaryFramebuffer(bool forwardNavigation) { memmove(&stripPointers[3][newStart], &stripBackPointers[3][newEnd], progress); #endif /* OLED_128x32 */ +#ifdef OLED_128x32 + if (loopCounter % 2 == 0) { + refresh(); + } +#else refresh(); // Now refresh to write out the contents to the new page +#endif /* OLED_128x32 */ + vTaskDelayUntil(&startDraw, TICKS_100MS / 7); - if (getButtonState() != BUTTON_NONE) { + buttonsReleased |= getButtonState() == BUTTON_NONE; + if (getButtonState() != BUTTON_NONE && buttonsReleased) { + memcpy(screenBuffer + FRAMEBUFFER_START, secondFrameBuffer + FRAMEBUFFER_START, sizeof(screenBuffer) - FRAMEBUFFER_START); + refresh(); // Now refresh to write out the contents to the new page return; } } + refresh(); // redraw at the end if required } void OLED::useSecondaryFramebuffer(bool useSecondary) { @@ -330,6 +348,7 @@ void OLED::useSecondaryFramebuffer(bool useSecondary) { setFramebuffer(screenBuffer); } } + /** * This assumes that the current display output buffer has the current on screen contents * Then the secondary buffer has the "new" contents to be slid up onto the screen @@ -337,8 +356,9 @@ void OLED::useSecondaryFramebuffer(bool useSecondary) { * * **This function blocks until the transition has completed or user presses button** */ -void OLED::transitionScrollDown() { - TickType_t startDraw = xTaskGetTickCount(); +void OLED::transitionScrollDown(const TickType_t viewEnterTime) { + TickType_t startDraw = xTaskGetTickCount(); + bool buttonsReleased = getButtonState() == BUTTON_NONE; for (uint8_t heightPos = 0; heightPos < OLED_HEIGHT; heightPos++) { // For each line, we shuffle all bits up a row @@ -365,9 +385,9 @@ void OLED::transitionScrollDown() { // Finally on the bottom row; we shuffle it up ready secondFrameBuffer[fourthStripPos] >>= 1; #else - // Move the MSB off the first strip, and pop MSB from second strip onto the first strip + // Move the LSB off the first strip, and pop MSB from second strip onto the first strip screenBuffer[firstStripPos] = (screenBuffer[firstStripPos] >> 1) | ((screenBuffer[secondStripPos] & 0x01) << 7); - // Now shuffle off the second strip MSB, and replace it with the MSB of the secondary buffer + // Now shuffle off the second strip MSB, and replace it with the LSB of the secondary buffer screenBuffer[secondStripPos] = (screenBuffer[secondStripPos] >> 1) | ((secondFrameBuffer[firstStripPos] & 0x01) << 7); // Finally, do the shuffle on the second frame buffer secondFrameBuffer[firstStripPos] = (secondFrameBuffer[firstStripPos] >> 1) | ((secondFrameBuffer[secondStripPos] & 0x01) << 7); @@ -375,13 +395,83 @@ void OLED::transitionScrollDown() { secondFrameBuffer[secondStripPos] >>= 1; #endif /* OLED_128x32 */ } - if (getButtonState() != BUTTON_NONE) { + buttonsReleased |= getButtonState() == BUTTON_NONE; + if (getButtonState() != BUTTON_NONE && buttonsReleased) { + // Exit early, but have to transition whole buffer + memcpy(screenBuffer + FRAMEBUFFER_START, secondFrameBuffer + FRAMEBUFFER_START, sizeof(screenBuffer) - FRAMEBUFFER_START); + refresh(); // Now refresh to write out the contents to the new page + return; + } +#ifdef OLED_128x32 + // To keep things faster, only redraw every second line + if (heightPos % 2 == 0) { + refresh(); // Now refresh to write out the contents to the new page + } +#else + refresh(); // Now refresh to write out the contents to the new page +#endif + vTaskDelayUntil(&startDraw, TICKS_100MS / 7); + } +} +/** + * This assumes that the current display output buffer has the current on screen contents + * Then the secondary buffer has the "new" contents to be slid down onto the screen + * Sadly we cant use the hardware scroll as some devices with the 128x32 screens dont have the GRAM for holding both screens at once + * + * **This function blocks until the transition has completed or user presses button** + */ +void OLED::transitionScrollUp(const TickType_t viewEnterTime) { + TickType_t startDraw = xTaskGetTickCount(); + bool buttonsReleased = getButtonState() == BUTTON_NONE; + + for (uint8_t heightPos = 0; heightPos < OLED_HEIGHT; heightPos++) { + // For each line, we shuffle all bits down a row + for (uint8_t xPos = 0; xPos < OLED_WIDTH; xPos++) { + const uint16_t firstStripPos = FRAMEBUFFER_START + xPos; + const uint16_t secondStripPos = firstStripPos + OLED_WIDTH; +#ifdef OLED_128x32 + // For 32 pixel high OLED's we have four strips to tailchain + const uint16_t thirdStripPos = secondStripPos + OLED_WIDTH; + const uint16_t fourthStripPos = thirdStripPos + OLED_WIDTH; + // We are shffling LSB's off the end and pushing bits down + screenBuffer[fourthStripPos] = (screenBuffer[fourthStripPos] << 1) | ((screenBuffer[thirdStripPos] & 0x80) >> 7); + screenBuffer[thirdStripPos] = (screenBuffer[thirdStripPos] << 1) | ((screenBuffer[secondStripPos] & 0x80) >> 7); + screenBuffer[secondStripPos] = (screenBuffer[secondStripPos] << 1) | ((screenBuffer[firstStripPos] & 0x80) >> 7); + screenBuffer[firstStripPos] = (screenBuffer[firstStripPos] << 1) | ((secondFrameBuffer[fourthStripPos] & 0x80) >> 7); + + secondFrameBuffer[fourthStripPos] = (secondFrameBuffer[fourthStripPos] << 1) | ((secondFrameBuffer[thirdStripPos] & 0x80) >> 7); + secondFrameBuffer[thirdStripPos] = (secondFrameBuffer[thirdStripPos] << 1) | ((secondFrameBuffer[secondStripPos] & 0x80) >> 7); + secondFrameBuffer[secondStripPos] = (secondFrameBuffer[secondStripPos] << 1) | ((secondFrameBuffer[firstStripPos] & 0x80) >> 7); + // Finally on the bottom row; we shuffle it up ready + secondFrameBuffer[firstStripPos] <<= 1; +#else + // We pop the LSB off the bottom row, and replace the MSB in that byte with the LSB of the row above + screenBuffer[secondStripPos] = (screenBuffer[secondStripPos] << 1) | ((screenBuffer[firstStripPos] & 0x80) >> 7); + // Move the LSB off the first strip, and pop MSB from second strip onto the first strip + screenBuffer[firstStripPos] = (screenBuffer[firstStripPos] << 1) | ((secondFrameBuffer[secondStripPos] & 0x80) >> 7); + + // Finally, do the shuffle on the second frame buffer + secondFrameBuffer[secondStripPos] = (secondFrameBuffer[secondStripPos] << 1) | ((secondFrameBuffer[firstStripPos] & 0x80) >> 7); + // Finally on the bottom row; we shuffle it up ready + secondFrameBuffer[firstStripPos] <<= 1; +#endif /* OLED_128x32 */ + } + buttonsReleased |= getButtonState() == BUTTON_NONE; + if (getButtonState() != BUTTON_NONE && buttonsReleased) { // Exit early, but have to transition whole buffer memcpy(screenBuffer + FRAMEBUFFER_START, secondFrameBuffer + FRAMEBUFFER_START, sizeof(screenBuffer) - FRAMEBUFFER_START); refresh(); // Now refresh to write out the contents to the new page return; } + +#ifdef OLED_128x32 + // To keep things faster, only redraw every second line + if (heightPos % 2 == 0) { + refresh(); // Now refresh to write out the contents to the new page + } +#else refresh(); // Now refresh to write out the contents to the new page +#endif vTaskDelayUntil(&startDraw, TICKS_100MS / 7); } } @@ -428,18 +518,22 @@ void OLED::setRotation(bool leftHanded) { } void OLED::setBrightness(uint8_t contrast) { - OLED_Setup_Array[15].val = contrast; - I2C_CLASS::writeRegistersBulk(DEVICEADDR_OLED, &OLED_Setup_Array[14], 2); + if (OLED_Setup_Array[15].val != contrast) { + OLED_Setup_Array[15].val = contrast; + I2C_CLASS::writeRegistersBulk(DEVICEADDR_OLED, &OLED_Setup_Array[14], 2); + } } void OLED::setInverseDisplay(bool inverse) { uint8_t normalInverseCmd = inverse ? 0xA7 : 0xA6; - OLED_Setup_Array[21].val = normalInverseCmd; - I2C_CLASS::I2C_RegisterWrite(DEVICEADDR_OLED, 0x80, normalInverseCmd); + if (OLED_Setup_Array[21].val != normalInverseCmd) { + OLED_Setup_Array[21].val = normalInverseCmd; + I2C_CLASS::I2C_RegisterWrite(DEVICEADDR_OLED, 0x80, normalInverseCmd); + } } // print a string to the current cursor location, len chars MAX -void OLED::print(const char *const str, FontStyle fontStyle, uint8_t len) { +void OLED::print(const char *const str, FontStyle fontStyle, uint8_t len, const uint8_t soft_x_limit) { const uint8_t *next = reinterpret_cast(str); if (next[0] == 0x01) { fontStyle = FontStyle::LARGE; @@ -457,7 +551,7 @@ void OLED::print(const char *const str, FontStyle fontStyle, uint8_t len) { index = (next[0] - 0xF0) * 0xFF - 15 + next[1]; next += 2; } - drawChar(index, fontStyle); + drawChar(index, fontStyle, soft_x_limit); } } @@ -514,7 +608,7 @@ void OLED::drawHex(uint32_t x, FontStyle fontStyle, uint8_t digits) { // print number to hex for (uint_fast8_t i = 0; i < digits; i++) { uint16_t value = (x >> (4 * (7 - i))) & 0b1111; - drawChar(value + 2, fontStyle); + drawChar(value + 2, fontStyle, 0); } } @@ -569,80 +663,69 @@ void OLED::debugNumber(int32_t val, FontStyle fontStyle) { void OLED::drawSymbol(uint8_t symbolID) { // draw a symbol to the current cursor location - drawChar(symbolID, FontStyle::EXTRAS); + drawChar(symbolID, FontStyle::EXTRAS, 0); } // Draw an area, but y must be aligned on 0/8 offset -void OLED::drawArea(int16_t x, int8_t y, uint8_t wide, uint8_t height, const uint8_t *ptr) { - // Splat this from x->x+wide in two strides - if (x <= -wide) { +void OLED::drawArea(int16_t x, int8_t y, uint8_t width, uint8_t height, const uint8_t *ptr) { + // Splat this from x->x+width in two strides + if (x <= -width) { return; // cutoffleft } - if (x > 96) { + if (x > OLED_WIDTH) { return; // cutoff right } uint8_t visibleStart = 0; - uint8_t visibleEnd = wide; + uint8_t visibleEnd = width; // trimming to draw partials if (x < 0) { visibleStart -= x; // subtract negative value == add absolute value } - if (x + wide > 96) { - visibleEnd = 96 - x; - } - - if (y == 0) { - // Splat first line of data - for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) { - stripPointers[0][xx + x] = ptr[xx]; - } + if (x + width > OLED_WIDTH) { + visibleEnd = OLED_WIDTH - x; } - if (y == 8 || height >= 16) { - // Splat the second line + uint8_t rowsDrawn = 0; + while (height > 0) { for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) { - stripPointers[1][x + xx] = ptr[xx + (height == 16 ? wide : 0)]; + stripPointers[(y / 8) + rowsDrawn][x + xx] = ptr[xx + (rowsDrawn * width)]; } + height -= 8; + rowsDrawn++; } - // TODO NEEDS HEIGHT HANDLERS for 24/32 } // Draw an area, but y must be aligned on 0/8 offset // For data which has octets swapped in a 16-bit word. -void OLED::drawAreaSwapped(int16_t x, int8_t y, uint8_t wide, uint8_t height, const uint8_t *ptr) { - // Splat this from x->x+wide in two strides - if (x <= -wide) { +void OLED::drawAreaSwapped(int16_t x, int8_t y, uint8_t width, uint8_t height, const uint8_t *ptr) { + // Splat this from x->x+width in two strides + if (x <= -width) { return; // cutoffleft } - if (x > 96) { + if (x > OLED_WIDTH) { return; // cutoff right } uint8_t visibleStart = 0; - uint8_t visibleEnd = wide; + uint8_t visibleEnd = width; // trimming to draw partials if (x < 0) { visibleStart -= x; // subtract negative value == add absolute value } - if (x + wide > 96) { - visibleEnd = 96 - x; + if (x + width > OLED_WIDTH) { + visibleEnd = OLED_WIDTH - x; } - if (y == 0) { - // Splat first line of data - for (uint8_t xx = visibleStart; xx < visibleEnd; xx += 2) { - stripPointers[0][xx + x] = ptr[xx + 1]; - stripPointers[0][xx + x + 1] = ptr[xx]; - } - } - if (y == 8 || height == 16) { - // Splat the second line + uint8_t rowsDrawn = 0; + while (height > 0) { for (uint8_t xx = visibleStart; xx < visibleEnd; xx += 2) { - stripPointers[1][x + xx] = ptr[xx + 1 + (height == 16 ? wide : 0)]; - stripPointers[1][x + xx + 1] = ptr[xx + (height == 16 ? wide : 0)]; + stripPointers[(y / 8) + rowsDrawn][x + xx] = ptr[xx + 1 + (rowsDrawn * width)]; + stripPointers[(y / 8) + rowsDrawn][x + xx + 1] = ptr[xx + (rowsDrawn * width)]; } + height -= 8; + rowsDrawn++; } } @@ -651,7 +734,7 @@ void OLED::fillArea(int16_t x, int8_t y, uint8_t wide, uint8_t height, const uin if (x <= -wide) { return; // cutoffleft } - if (x > 96) { + if (x > OLED_WIDTH) { return; // cutoff right } @@ -662,62 +745,47 @@ void OLED::fillArea(int16_t x, int8_t y, uint8_t wide, uint8_t height, const uin if (x < 0) { visibleStart -= x; // subtract negative value == add absolute value } - if (x + wide > 96) { - visibleEnd = 96 - x; + if (x + wide > OLED_WIDTH) { + visibleEnd = OLED_WIDTH - x; } - if (y == 0) { - // Splat first line of data - for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) { - stripPointers[0][xx + x] = value; - } - } - if (y == 8 || height == 16) { - // Splat the second line + uint8_t rowsDrawn = 0; + while (height > 0) { for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) { - stripPointers[1][x + xx] = value; + stripPointers[(y / 8) + rowsDrawn][x + xx] = value; } + height -= 8; + rowsDrawn++; } } void OLED::drawFilledRect(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1, bool clear) { - // Draw this in 3 sections - // This is basically a N wide version of vertical line - - // Step 1 : Draw in the top few pixels that are not /8 aligned - // LSB is at the top of the screen - uint8_t mask = 0xFF; - if (y0) { - mask = mask << (y0 % 8); - for (uint8_t col = x0; col < x1; col++) { - if (clear) { - stripPointers[0][(y0 / 8) * 96 + col] &= ~mask; - } else { - stripPointers[0][(y0 / 8) * 96 + col] |= mask; - } - } + // Ensure coordinates are within bounds + if (x0 >= OLED_WIDTH || y0 >= OLED_HEIGHT || x1 >= OLED_WIDTH || y1 >= OLED_HEIGHT) { + return; } - // Next loop down the line the total number of solids - if (y0 / 8 != y1 / 8) { - for (uint8_t col = x0; col < x1; col++) { - for (uint8_t r = (y0 / 8); r < (y1 / 8); r++) { - // This gives us the row index r - if (clear) { - stripPointers[0][(r * 96) + col] = 0; - } else { - stripPointers[0][(r * 96) + col] = 0xFF; - } - } + + // Calculate the height in rows + uint8_t startRow = y0 / 8; + uint8_t endRow = y1 / 8; + uint8_t startMask = 0xFF << (y0 % 8); + uint8_t endMask = 0xFF >> (7 - (y1 % 8)); + + for (uint8_t row = startRow; row <= endRow; row++) { + uint8_t mask = 0xFF; + if (row == startRow) { + mask &= startMask; + } + if (row == endRow) { + mask &= endMask; } - } - // Finally draw the tail - mask = ~(mask << (y1 % 8)); - for (uint8_t col = x0; col < x1; col++) { - if (clear) { - stripPointers[0][(y1 / 8) * 96 + col] &= ~mask; - } else { - stripPointers[0][(y1 / 8) * 96 + col] |= mask; + for (uint8_t x = x0; x <= x1; x++) { + if (clear) { + stripPointers[row][x] &= ~mask; + } else { + stripPointers[row][x] |= mask; + } } } } @@ -728,8 +796,20 @@ void OLED::drawHeatSymbol(uint8_t state) { // the levels masks the symbol nicely state /= 31; // 0-> 8 range // Then we want to draw down (16-(5+state) - uint8_t cursor_x_temp = cursor_x; + uint16_t cursor_x_temp = cursor_x; drawSymbol(14); + /* + / / / / / + / / / / / + +---------+ + | | + +---------+ + + + <- 14 px -> + What we are doing is aiming to clear a section of the screen, down to the base depending on how much PWM we are using. + Larger numbers mean more heat, so we clear less of the screen. + */ drawFilledRect(cursor_x_temp, 0, cursor_x_temp + 12, 2 + (8 - state), true); } diff --git a/source/Core/Drivers/OLED.hpp b/source/Core/Drivers/OLED.hpp index 622ef9089..2f0f714bc 100644 --- a/source/Core/Drivers/OLED.hpp +++ b/source/Core/Drivers/OLED.hpp @@ -46,9 +46,9 @@ extern "C" { #define OLED_GRAM_START_FLIP 0 #define OLED_GRAM_END_FLIP 0x7F -#define OLED_VCOM_LAYOUT 0x12 +#define OLED_VCOM_LAYOUT 0x12 #define OLED_SEGMENT_MAP_REVERSED -#define OLED_DIVIDER 0xD3 +#define OLED_DIVIDER 0xD3 #else @@ -59,14 +59,14 @@ extern "C" { #define OLED_GRAM_START_FLIP 0 #define OLED_GRAM_END_FLIP 95 -#define OLED_VCOM_LAYOUT 0x02 -#define OLED_SEGMENT_MAP 0xA0 -#define OLED_DIVIDER 0xD5 +#define OLED_VCOM_LAYOUT 0x02 +#define OLED_SEGMENT_MAP 0xA0 +#define OLED_DIVIDER 0xD5 #endif /* OLED_128x32 */ -#define OLED_ON 0xAF -#define OLED_OFF 0xAE +#define OLED_ON 0xAF +#define OLED_OFF 0xAE #define FRAMEBUFFER_START 17 @@ -117,10 +117,10 @@ class OLED { static void setInverseDisplay(bool inverted); static int16_t getCursorX() { return cursor_x; } // Draw a string to the current location, with selected font; optionally - with MAX length only - static void print(const char *string, FontStyle fontStyle, uint8_t length = 255); - static void printWholeScreen(const char *string); + static void print(const char *string, FontStyle fontStyle, uint8_t length = 255, const uint8_t soft_x_limit = 0); + static void printWholeScreen(const char *string); // Print *F or *C - in font style of Small, Large (by default) or Extra based on input arg - static void printSymbolDeg(FontStyle fontStyle = FontStyle::LARGE); + static void printSymbolDeg(FontStyle fontStyle = FontStyle::LARGE); // Set the cursor location by pixels static void setCursor(int16_t x, int16_t y) { cursor_x = x; @@ -136,6 +136,7 @@ class OLED { static void drawBattery(uint8_t state) { drawSymbol(3 + (state > 10 ? 10 : state)); } // Draws a checkbox static void drawCheckbox(bool state) { drawSymbol((state) ? 16 : 17); } + inline static void drawUnavailableIcon() { drawArea(OLED_WIDTH - OLED_HEIGHT - 2, 0, OLED_HEIGHT, OLED_HEIGHT, UnavailableIcon); } static void debugNumber(int32_t val, FontStyle fontStyle); static void drawHex(uint32_t x, FontStyle fontStyle, uint8_t digits); static void drawSymbol(uint8_t symbolID); // Used for drawing symbols of a predictable width @@ -146,9 +147,10 @@ class OLED { static void drawHeatSymbol(uint8_t state); static void drawScrollIndicator(uint8_t p, uint8_t h); // Draws a scrolling position indicator static void maskScrollIndicatorOnOLED(); - static void transitionSecondaryFramebuffer(bool forwardNavigation); + static void transitionSecondaryFramebuffer(const bool forwardNavigation, const TickType_t viewEnterTime); static void useSecondaryFramebuffer(bool useSecondary); - static void transitionScrollDown(); + static void transitionScrollDown(const TickType_t viewEnterTime); + static void transitionScrollUp(const TickType_t viewEnterTime); private: static bool checkDisplayBufferChecksum() { @@ -162,7 +164,7 @@ class OLED { displayChecksum = hash; return result; } - static void drawChar(uint16_t charCode, FontStyle fontStyle); // Draw a character to the current cursor location + static void drawChar(uint16_t charCode, FontStyle fontStyle, const uint8_t soft_x_limit); // Draw a character to the current cursor location static void setFramebuffer(uint8_t *buffer); static uint8_t *stripPointers[4]; // Pointers to the strips to allow for buffer having extra content static bool inLeftHandedMode; // Whether the screen is in left or not (used for offsets in GRAM) diff --git a/source/Core/Drivers/SC7A20.cpp b/source/Core/Drivers/SC7A20.cpp index 81c8d1c26..9b9fda61a 100644 --- a/source/Core/Drivers/SC7A20.cpp +++ b/source/Core/Drivers/SC7A20.cpp @@ -6,6 +6,7 @@ */ #include "LIS2DH12_defines.hpp" +#include "accelerometers_common.h" #include #include #include @@ -17,20 +18,20 @@ bool SC7A20::isInImitationMode; */ bool SC7A20::detect() { - if (FRToSI2C::probe(SC7A20_ADDRESS)) { + if (ACCEL_I2C_CLASS::probe(SC7A20_ADDRESS)) { // Read chip id to ensure its not an address collision uint8_t id = 0; - if (FRToSI2C::Mem_Read(SC7A20_ADDRESS, SC7A20_WHO_AMI_I, &id, 1)) { + if (ACCEL_I2C_CLASS::Mem_Read(SC7A20_ADDRESS, SC7A20_WHO_AMI_I, &id, 1)) { if (id == SC7A20_WHO_AM_I_VALUE) { isInImitationMode = false; return true; } } } - if (FRToSI2C::probe(SC7A20_ADDRESS2)) { + if (ACCEL_I2C_CLASS::probe(SC7A20_ADDRESS2)) { // Read chip id to ensure its not an address collision uint8_t id = 0; - if (FRToSI2C::Mem_Read(SC7A20_ADDRESS2, SC7A20_WHO_AMI_I, &id, 1)) { + if (ACCEL_I2C_CLASS::Mem_Read(SC7A20_ADDRESS2, SC7A20_WHO_AMI_I, &id, 1)) { if (id == SC7A20_WHO_AM_I_VALUE) { isInImitationMode = true; return true; @@ -40,38 +41,40 @@ bool SC7A20::detect() { return false; } -static const FRToSI2C::I2C_REG i2c_registers[] = { +static const ACCEL_I2C_CLASS::I2C_REG i2c_registers[] = { // // - {SC7A20_CTRL_REG1, 0b01100111, 0}, // 200Hz, XYZ enabled - {SC7A20_CTRL_REG2, 0b00000000, 0}, // Setup filter to 0x00 ?? - {SC7A20_CTRL_REG3, 0b00000000, 0}, // int1 off - {SC7A20_CTRL_REG4, 0b01001000, 0}, // Block mode off,little-endian,2G,High-pres,self test off - {SC7A20_CTRL_REG5, 0b00000100, 0}, // fifo off, D4D on int1 - {SC7A20_CTRL_REG6, 0x00, 0}, // INT2 off - // Basically setup the unit to run, and enable 4D orientation detection - {SC7A20_INT2_CFG, 0b01111110, 0}, // setup for movement detection - {SC7A20_INT2_THS, 0x28, 0}, // - {SC7A20_INT2_DURATION, 64, 0}, // - {SC7A20_INT1_CFG, 0b01111110, 0}, // - {SC7A20_INT1_THS, 0x28, 0}, // - {SC7A20_INT1_DURATION, 64, 0} + { SC7A20_CTRL_REG1, 0b01100111, 0}, // 200Hz, XYZ enabled + { SC7A20_CTRL_REG2, 0b00000000, 0}, // Setup filter to 0x00 ?? + { SC7A20_CTRL_REG3, 0b00000000, 0}, // int1 off + { SC7A20_CTRL_REG4, 0b01001000, 0}, // Block mode off,little-endian,2G,High-pres,self test off + { SC7A20_CTRL_REG5, 0b00000100, 0}, // fifo off, D4D on int1 + { SC7A20_CTRL_REG6, 0x00, 0}, // INT2 off + // Basically setup the unit to run, and enable 4D orientation detection + { SC7A20_INT2_CFG, 0b01111110, 0}, // setup for movement detection + { SC7A20_INT2_THS, 0x28, 0}, // + {SC7A20_INT2_DURATION, 64, 0}, // + { SC7A20_INT1_CFG, 0b01111110, 0}, // + { SC7A20_INT1_THS, 0x28, 0}, // + {SC7A20_INT1_DURATION, 64, 0} // }; -static const FRToSI2C::I2C_REG i2c_registers_alt[] = {{LIS_CTRL_REG1, 0b00110111, 0}, // 200Hz XYZ - {LIS_CTRL_REG2, 0b00000000, 0}, // - {LIS_CTRL_REG3, 0b01100000, 0}, // Setup interrupt pins - {LIS_CTRL_REG4, 0b00001000, 0}, // Block update mode off, HR on - {LIS_CTRL_REG5, 0b00000010, 0}, // - {LIS_CTRL_REG6, 0b01100010, 0}, - // Basically setup the unit to run, and enable 4D orientation detection - {LIS_INT2_CFG, 0b01111110, 0}, // setup for movement detection - {LIS_INT2_THS, 0x28, 0}, // - {LIS_INT2_DURATION, 64, 0}, // - {LIS_INT1_CFG, 0b01111110, 0}, // - {LIS_INT1_THS, 0x28, 0}, // - {LIS_INT1_DURATION, 64, 0}}; +static const ACCEL_I2C_CLASS::I2C_REG i2c_registers_alt[] = { + { LIS_CTRL_REG1, 0b00110111, 0}, // 200Hz XYZ + { LIS_CTRL_REG2, 0b00000000, 0}, // + { LIS_CTRL_REG3, 0b01100000, 0}, // Setup interrupt pins + { LIS_CTRL_REG4, 0b00001000, 0}, // Block update mode off, HR on + { LIS_CTRL_REG5, 0b00000010, 0}, // + { LIS_CTRL_REG6, 0b01100010, 0}, + // Basically setup the unit to run, and enable 4D orientation detection + { LIS_INT2_CFG, 0b01111110, 0}, // setup for movement detection + { LIS_INT2_THS, 0x28, 0}, // + {LIS_INT2_DURATION, 64, 0}, // + { LIS_INT1_CFG, 0b01111110, 0}, // + { LIS_INT1_THS, 0x28, 0}, // + {LIS_INT1_DURATION, 64, 0} +}; bool SC7A20::initalize() { // Setup acceleration readings @@ -83,9 +86,9 @@ bool SC7A20::initalize() { // Hysteresis is set to ~ 16 counts // Theta blocking is set to 0b10 if (isInImitationMode) { - return FRToSI2C::writeRegistersBulk(SC7A20_ADDRESS2, i2c_registers_alt, sizeof(i2c_registers_alt) / sizeof(i2c_registers_alt[0])); + return ACCEL_I2C_CLASS::writeRegistersBulk(SC7A20_ADDRESS2, i2c_registers_alt, sizeof(i2c_registers_alt) / sizeof(i2c_registers_alt[0])); } else { - return FRToSI2C::writeRegistersBulk(SC7A20_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); + return ACCEL_I2C_CLASS::writeRegistersBulk(SC7A20_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); } } @@ -93,7 +96,7 @@ void SC7A20::getAxisReadings(int16_t &x, int16_t &y, int16_t &z) { // We can tell the accelerometer to output in LE mode which makes this simple uint16_t sensorData[3] = {0, 0, 0}; - if (FRToSI2C::Mem_Read(isInImitationMode ? SC7A20_ADDRESS2 : SC7A20_ADDRESS, isInImitationMode ? SC7A20_OUT_X_L_ALT : SC7A20_OUT_X_L, (uint8_t *)sensorData, 6) == false) { + if (ACCEL_I2C_CLASS::Mem_Read(isInImitationMode ? SC7A20_ADDRESS2 : SC7A20_ADDRESS, isInImitationMode ? SC7A20_OUT_X_L_ALT : SC7A20_OUT_X_L, (uint8_t *)sensorData, 6) == false) { x = y = z = 0; return; } diff --git a/source/Core/Drivers/SC7A20.hpp b/source/Core/Drivers/SC7A20.hpp index ea65f8242..c9e75f2cd 100644 --- a/source/Core/Drivers/SC7A20.hpp +++ b/source/Core/Drivers/SC7A20.hpp @@ -10,6 +10,7 @@ #include "BSP.h" #include "I2C_Wrapper.hpp" #include "SC7A20_defines.h" +#include "accelerometers_common.h" class SC7A20 { public: @@ -17,7 +18,7 @@ class SC7A20 { static bool initalize(); // 1 = rh, 2,=lh, 8=flat static Orientation getOrientation() { - uint8_t val = ((FRToSI2C::I2C_RegisterRead(isInImitationMode ? SC7A20_ADDRESS2 : SC7A20_ADDRESS, SC7A20_INT2_SOURCE) >> 2) - 1); + uint8_t val = ((ACCEL_I2C_CLASS::I2C_RegisterRead(isInImitationMode ? SC7A20_ADDRESS2 : SC7A20_ADDRESS, SC7A20_INT2_SOURCE) >> 2) - 1); if (val == 1) { #ifdef SC7_ORI_FLIP return Orientation::ORIENTATION_RIGHT_HAND; diff --git a/source/Core/Drivers/Si7210.cpp b/source/Core/Drivers/Si7210.cpp index 642e481c1..8683672f0 100644 --- a/source/Core/Drivers/Si7210.cpp +++ b/source/Core/Drivers/Si7210.cpp @@ -10,9 +10,10 @@ * This class is licensed as MIT to match this code base */ -#include "I2C_Wrapper.hpp" #include "Si7210_defines.h" +#include "accelerometers_common.h" #include +#ifdef MAG_SLEEP_SUPPORT bool Si7210::detect() { return FRToSI2C::wakePart(SI7210_ADDRESS); } bool Si7210::init() { @@ -20,7 +21,7 @@ bool Si7210::init() { // Load OTP cal uint8_t temp; - if (FRToSI2C::Mem_Read(SI7210_ADDRESS, SI7210_REG_ID, &temp, 1)) { + if (ACCEL_I2C_CLASS::Mem_Read(SI7210_ADDRESS, SI7210_REG_ID, &temp, 1)) { // We don't really care what model it is etc, just probing to check its probably this iC if (temp != 0x00 && temp != 0xFF) { temp = 0x00; @@ -31,27 +32,33 @@ bool Si7210::init() { } /* Disable periodic auto-wakeup by device, and tamper detect. */ - if ((!write_reg(SI7210_CTRL3, (uint8_t)~SL_TIMEENA_MASK, 0))) + if ((!write_reg(SI7210_CTRL3, (uint8_t)~SL_TIMEENA_MASK, 0))) { return false; + } /* Disable tamper detection by setting sw_tamper to 63 */ - if (!write_reg(SI7210_CTRL3, SL_FAST_MASK | SL_TIMEENA_MASK, 63 << 2)) + if (!write_reg(SI7210_CTRL3, SL_FAST_MASK | SL_TIMEENA_MASK, 63 << 2)) { return false; + } - if (!set_high_range()) + if (!set_high_range()) { return false; + } /* Stop the control loop by setting stop bit */ - if (!write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK)) /* WARNING: Removed USE_STORE MASK */ + if (!write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK)) { /* WARNING: Removed USE_STORE MASK */ return false; + } /* Use a burst size of 128/4096 samples in FIR and IIR modes */ - if (!write_reg(SI7210_CTRL4, 0, DF_BURSTSIZE_128 | DF_BW_4096)) + if (!write_reg(SI7210_CTRL4, 0, DF_BURSTSIZE_128 | DF_BW_4096)) { return false; + } /* Select field strength measurement */ - if (!write_reg(SI7210_DSPSIGSEL, 0, DSP_SIGSEL_FIELD_MASK)) + if (!write_reg(SI7210_DSPSIGSEL, 0, DSP_SIGSEL_FIELD_MASK)) { return false; + } return true; // start_periodic_measurement(); } @@ -77,15 +84,16 @@ bool Si7210::write_reg(const uint8_t reg, const uint8_t mask, const uint8_t val) temp &= mask; } temp |= val; - return FRToSI2C::Mem_Write(SI7210_ADDRESS, reg, &temp, 1); + return ACCEL_I2C_CLASS::Mem_Write(SI7210_ADDRESS, reg, &temp, 1); } -bool Si7210::read_reg(const uint8_t reg, uint8_t *val) { return FRToSI2C::Mem_Read(SI7210_ADDRESS, reg, val, 1); } +bool Si7210::read_reg(const uint8_t reg, uint8_t *val) { return ACCEL_I2C_CLASS::Mem_Read(SI7210_ADDRESS, reg, val, 1); } bool Si7210::start_periodic_measurement() { /* Enable periodic wakeup */ - if (!write_reg(SI7210_CTRL3, (uint8_t)~SL_TIMEENA_MASK, SL_TIMEENA_MASK)) + if (!write_reg(SI7210_CTRL3, (uint8_t)~SL_TIMEENA_MASK, SL_TIMEENA_MASK)) { return false; + } /* Start measurement */ /* Change to ~STOP_MASK with STOP_MASK */ @@ -95,19 +103,22 @@ bool Si7210::start_periodic_measurement() { bool Si7210::get_field_strength(int16_t *field) { *field = 0; uint8_t val = 0; - FRToSI2C::wakePart(SI7210_ADDRESS); + ACCEL_I2C_CLASS::wakePart(SI7210_ADDRESS); - if (!write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK)) + if (!write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK)) { return false; + } /* Read most-significant byte */ - if (!read_reg(SI7210_DSPSIGM, &val)) + if (!read_reg(SI7210_DSPSIGM, &val)) { return false; + } *field = (val & DSP_SIGM_DATA_MASK) << 8; /* Read least-significant byte of data */ - if (!read_reg(SI7210_DSPSIGL, &val)) + if (!read_reg(SI7210_DSPSIGL, &val)) { return false; + } *field += val; *field -= 16384U; @@ -175,3 +186,4 @@ bool Si7210::set_high_range() { worked &= write_reg(SI7210_A5, 0, val); return worked; } +#endif // MAG_SLEEP_SUPPORT \ No newline at end of file diff --git a/source/Core/Drivers/Si7210.h b/source/Core/Drivers/Si7210.h index 305c91ea0..2bbc46bea 100644 --- a/source/Core/Drivers/Si7210.h +++ b/source/Core/Drivers/Si7210.h @@ -7,7 +7,10 @@ #ifndef CORE_DRIVERS_SI7210_H_ #define CORE_DRIVERS_SI7210_H_ +#include "configuration.h" #include + +#ifdef MAG_SLEEP_SUPPORT class Si7210 { public: // Return true if present @@ -23,5 +26,5 @@ class Si7210 { static bool get_field_strength(int16_t *field); static bool set_high_range(); }; - +#endif // MAG_SLEEP_SUPPORT #endif /* CORE_DRIVERS_SI7210_H_ */ diff --git a/source/Core/Drivers/TipThermoModel.cpp b/source/Core/Drivers/TipThermoModel.cpp index 29edc08df..e1bee830d 100644 --- a/source/Core/Drivers/TipThermoModel.cpp +++ b/source/Core/Drivers/TipThermoModel.cpp @@ -9,7 +9,7 @@ #include "BSP.h" #include "Settings.h" #include "Types.h" -#include "Utils.h" +#include "Utils.hpp" #include "configuration.h" #include "main.hpp" #include "power.hpp" @@ -89,7 +89,11 @@ TemperatureType_t TipThermoModel::getTipInF(bool sampleNow) { } TemperatureType_t TipThermoModel::getTipMaxInC() { +#ifdef CUSTOM_MAX_TEMP_C + return getCustomTipMaxInC(); +#else TemperatureType_t maximumTipTemp = TipThermoModel::convertTipRawADCToDegC(ADC_MAX_READING - 1); maximumTipTemp += getHandleTemperature(0) / 10; // Add handle offset return maximumTipTemp - 1; +#endif } diff --git a/source/Core/Drivers/TipThermoModel.h b/source/Core/Drivers/TipThermoModel.h index 03a10ff0f..b437b0268 100644 --- a/source/Core/Drivers/TipThermoModel.h +++ b/source/Core/Drivers/TipThermoModel.h @@ -5,11 +5,11 @@ * Author: ralim */ -#ifndef SRC_TIPTHERMOMODEL_H_ -#define SRC_TIPTHERMOMODEL_H_ #include "BSP.h" #include "Types.h" #include "stdint.h" +#ifndef SRC_TIPTHERMOMODEL_H_ +#define SRC_TIPTHERMOMODEL_H_ class TipThermoModel { public: // These are the main two functions diff --git a/source/Core/Drivers/USBPD.cpp b/source/Core/Drivers/USBPD.cpp index 7bdd4113d..9c7b2b436 100644 --- a/source/Core/Drivers/USBPD.cpp +++ b/source/Core/Drivers/USBPD.cpp @@ -1,9 +1,9 @@ #include "USBPD.h" #include "configuration.h" #ifdef POW_PD - #include "BSP_PD.h" #include "FreeRTOS.h" +#include "Settings.h" #include "fusb302b.h" #include "main.hpp" #include "pd.h" @@ -27,8 +27,9 @@ bool pdbs_dpm_evaluate_capability(const pd_msg *capabilities, pd_msg *re void pdbs_dpm_get_sink_capability(pd_msg *cap, const bool isPD3); bool EPREvaluateCapabilityFunc(const epr_pd_msg *capabilities, pd_msg *request); FUSB302 fusb((0x22 << 1), fusb_read_buf, fusb_write_buf, ms_delay); // Create FUSB driver -PolicyEngine pe(fusb, get_ms_timestamp, ms_delay, pdbs_dpm_get_sink_capability, pdbs_dpm_evaluate_capability, EPREvaluateCapabilityFunc, 140); +PolicyEngine pe(fusb, get_ms_timestamp, ms_delay, pdbs_dpm_get_sink_capability, pdbs_dpm_evaluate_capability, EPREvaluateCapabilityFunc, USB_PD_EPR_WATTAGE); int USBPowerDelivery::detectionState = 0; +bool haveSeenCapabilityOffer = false; uint16_t requested_voltage_mv = 0; /* The current draw when the output is disabled */ @@ -46,10 +47,20 @@ void USBPowerDelivery::IRQOccured() { pe.IRQOccured(); } bool USBPowerDelivery::negotiationHasWorked() { return pe.pdHasNegotiated(); } uint8_t USBPowerDelivery::getStateNumber() { return pe.currentStateCode(true); } void USBPowerDelivery::step() { - while (pe.thread()) {} + while (pe.thread()) { + } } void USBPowerDelivery::PPSTimerCallback() { pe.TimersCallback(); } +bool USBPowerDelivery::negotiationInProgress() { + if (USBPowerDelivery::negotiationComplete()) { + return false; + } + if (haveSeenCapabilityOffer) { + return false; + } + return true; +} bool USBPowerDelivery::negotiationComplete() { if (!fusbPresent()) { return true; @@ -124,7 +135,11 @@ bool parseCapabilitiesArray(const uint8_t numCaps, uint8_t *bestIndex, uint16_t *bestVoltage = 5000; // Default 5V // Fudge of 0.5 ohms to round up a little to account for us always having off periods in PWM - uint8_t tipResistance = getTipResistanceX10() + 5; + uint8_t tipResistance = getTipResistanceX10(); + usbpdMode_t pd_mode = (usbpdMode_t)getSettingValue(SettingsOptions::USBPDMode); + if (pd_mode == usbpdMode_t::DEFAULT) { + tipResistance += 5; + } #ifdef MODEL_HAS_DCDC // If this device has step down DC/DC inductor to smooth out current spikes // We can instead ignore resistance and go for max voltage we can accept; and rely on the DC/DC regulation to keep under current limit @@ -142,70 +157,84 @@ bool parseCapabilitiesArray(const uint8_t numCaps, uint8_t *bestIndex, uint16_t int min_resistance_ohmsx10 = voltage_mv / current_a_x100; if (voltage_mv > 0) { if (voltage_mv <= (USB_PD_VMAX * 1000)) { - if (min_resistance_ohmsx10 <= tipResistance) { - // This is a valid power source we can select as - if (voltage_mv > *bestVoltage) { - - // Higher voltage and valid, select this instead - *bestIndex = i; - *bestVoltage = voltage_mv; - *bestCurrent = current_a_x100; - *bestIsPPS = false; - *bestIsAVS = false; + if (voltage_mv <= 20000 || (pd_mode != usbpdMode_t::NO_DYNAMIC)) { + if (min_resistance_ohmsx10 <= tipResistance) { + // This is a valid power source we can select as + if (voltage_mv > *bestVoltage) { + + // Higher voltage and valid, select this instead + *bestIndex = i; + *bestVoltage = voltage_mv; + *bestCurrent = current_a_x100; + *bestIsPPS = false; + *bestIsAVS = false; + } } } } } - } else if ((lastCapabilities[i] & PD_PDO_TYPE) == PD_PDO_TYPE_AUGMENTED && (((lastCapabilities[i] & PD_APDO_TYPE) == PD_APDO_TYPE_PPS)) && getSettingValue(SettingsOptions::PDVpdo)) { - // If this is a PPS slot, calculate the max voltage in the PPS range that can we be used and maintain - uint16_t max_voltage = PD_PAV2MV(PD_APDO_PPS_MAX_VOLTAGE_GET(lastCapabilities[i])); - // uint16_t min_voltage = PD_PAV2MV(PD_APDO_PPS_MIN_VOLTAGE_GET(lastCapabilities[i])); - uint16_t max_current = PD_PAI2CA(PD_APDO_PPS_CURRENT_GET(lastCapabilities[i])); // max current in 10mA units - // Using the current and tip resistance, calculate the ideal max voltage - // if this is range, then we will work with this voltage - // if this is not in range; then max_voltage can be safely selected - int ideal_voltage_mv = (tipResistance * max_current); - if (ideal_voltage_mv > max_voltage) { - ideal_voltage_mv = max_voltage; // constrain to what this PDO offers - } - if (ideal_voltage_mv > 20000) { - ideal_voltage_mv = 20000; // Limit to 20V as some advertise 21 but are not stable at 21 + } else if (((lastCapabilities[i] & PD_PDO_TYPE) == PD_PDO_TYPE_AUGMENTED) && (pd_mode != usbpdMode_t::NO_DYNAMIC)) { + bool sourceIsEPRCapable = lastCapabilities[0] & PD_PDO_SRC_FIXED_EPR_CAPABLE; + bool isPPS = false; + bool isAVS = false; + if (sourceIsEPRCapable) { + isPPS = (lastCapabilities[i] & PD_APDO_TYPE) == PD_APDO_TYPE_PPS; + isAVS = (lastCapabilities[i] & PD_APDO_TYPE) == PD_APDO_TYPE_AVS; + } else { + isPPS = true; // Assume PPS if no EPR support } - if (ideal_voltage_mv > (USB_PD_VMAX * 1000)) { - ideal_voltage_mv = (USB_PD_VMAX * 1000); // constrain to model max voltage safe to select - } - if (ideal_voltage_mv > *bestVoltage) { - *bestIndex = i; - *bestVoltage = ideal_voltage_mv; - *bestCurrent = max_current; - *bestIsPPS = true; - *bestIsAVS = false; + if (isPPS) { + // If this is a PPS slot, calculate the max voltage in the PPS range that can we be used and maintain + uint16_t max_voltage = PD_PAV2MV(PD_APDO_PPS_MAX_VOLTAGE_GET(lastCapabilities[i])); + // uint16_t min_voltage = PD_PAV2MV(PD_APDO_PPS_MIN_VOLTAGE_GET(lastCapabilities[i])); + uint16_t max_current = PD_PAI2CA(PD_APDO_PPS_CURRENT_GET(lastCapabilities[i])); // max current in 10mA units + // Using the current and tip resistance, calculate the ideal max voltage + // if this is range, then we will work with this voltage + // if this is not in range; then max_voltage can be safely selected + int ideal_voltage_mv = (tipResistance * max_current); + if (ideal_voltage_mv > max_voltage) { + ideal_voltage_mv = max_voltage; // constrain to what this PDO offers + } + if (ideal_voltage_mv > 20000) { + ideal_voltage_mv = 20000; // Limit to 20V as some advertise 21 but are not stable at 21 + } + if (ideal_voltage_mv > (USB_PD_VMAX * 1000)) { + ideal_voltage_mv = (USB_PD_VMAX * 1000); // constrain to model max voltage safe to select + } + if (ideal_voltage_mv > *bestVoltage) { + *bestIndex = i; + *bestVoltage = ideal_voltage_mv; + *bestCurrent = max_current; + *bestIsPPS = true; + *bestIsAVS = false; + } } - } #ifdef POW_EPR - else if ((lastCapabilities[i] & PD_PDO_TYPE) == PD_PDO_TYPE_AUGMENTED && (((lastCapabilities[i] & PD_APDO_TYPE) == PD_APDO_TYPE_AVS)) && getSettingValue(SettingsOptions::PDVpdo)) { - uint16_t max_voltage = PD_PAV2MV(PD_APDO_AVS_MAX_VOLTAGE_GET(lastCapabilities[i])); - uint8_t max_wattage = PD_APDO_AVS_MAX_POWER_GET(lastCapabilities[i]); - - // W = v^2/tip_resistance => Wattage*tip_resistance == Max_voltage^2 - auto ideal_max_voltage = sqrtI((max_wattage * tipResistance) / 10) * 1000; - if (ideal_max_voltage > (USB_PD_VMAX * 1000)) { - ideal_max_voltage = (USB_PD_VMAX * 1000); // constrain to model max voltage safe to select - } - if (ideal_max_voltage > (max_voltage)) { - ideal_max_voltage = (max_voltage); // constrain to model max voltage safe to select - } - auto operating_current = (ideal_max_voltage / tipResistance); // Current in centiamps - - if (ideal_max_voltage > *bestVoltage) { - *bestIndex = i; - *bestVoltage = ideal_max_voltage; - *bestCurrent = operating_current; - *bestIsAVS = true; - *bestIsPPS = false; + else if (isAVS) { + uint16_t max_voltage = PD_PAV2MV(PD_APDO_AVS_MAX_VOLTAGE_GET(lastCapabilities[i])); + uint8_t max_wattage = PD_APDO_AVS_MAX_POWER_GET(lastCapabilities[i]); + tipResistance = getTipResistanceX10(); // Dont use fudge factor for EPR + + // W = v^2/tip_resistance => Wattage*tip_resistance == Max_voltage^2 + auto ideal_max_voltage = sqrtI((max_wattage * tipResistance) / 10) * 1000; + if (ideal_max_voltage > (USB_PD_VMAX * 1000)) { + ideal_max_voltage = (USB_PD_VMAX * 1000); // constrain to model max voltage safe to select + } + if (ideal_max_voltage > (max_voltage)) { + ideal_max_voltage = (max_voltage); // constrain to model max voltage safe to select + } + auto operating_current = (ideal_max_voltage / tipResistance); // Current in centiamps + + if (ideal_max_voltage > *bestVoltage) { + *bestIndex = i; + *bestVoltage = ideal_max_voltage; + *bestCurrent = operating_current; + *bestIsAVS = true; + *bestIsPPS = false; + } } - } #endif + } } // Now that the best index is known, set the current values return *bestIndex != 0xFF; // have we selected one @@ -267,6 +296,7 @@ bool EPREvaluateCapabilityFunc(const epr_pd_msg *capabilities, pd_msg *request) bool pdbs_dpm_evaluate_capability(const pd_msg *capabilities, pd_msg *request) { memset(lastCapabilities, 0, sizeof(lastCapabilities)); memcpy(lastCapabilities, capabilities->obj, sizeof(uint32_t) * 7); + haveSeenCapabilityOffer = true; /* Get the number of PDOs */ uint8_t numobj = PD_NUMOBJ_GET(capabilities); @@ -311,68 +341,51 @@ bool pdbs_dpm_evaluate_capability(const pd_msg *capabilities, pd_msg *request) { return true; } +void add_v_record(pd_msg *cap, uint16_t voltage_mv, int numobj) { + + uint16_t current = (voltage_mv) / getTipResistanceX10(); // In centi-amps + + /* Add a PDO for the desired power. */ + cap->obj[numobj] = PD_PDO_TYPE_FIXED | PD_PDO_SNK_FIXED_VOLTAGE_SET(PD_MV2PDV(voltage_mv)) | PD_PDO_SNK_FIXED_CURRENT_SET(current); +} void pdbs_dpm_get_sink_capability(pd_msg *cap, const bool isPD3) { /* Keep track of how many PDOs we've added */ - // int numobj = 0; - - // /* If we have no configuration or want something other than 5 V, add a PDO - // * for vSafe5V */ - // /* Minimum current, 5 V, and higher capability. */ - // cap->obj[numobj++] = PD_PDO_TYPE_FIXED | PD_PDO_SNK_FIXED_VOLTAGE_SET(PD_MV2PDV(5000)) | PD_PDO_SNK_FIXED_CURRENT_SET(DPM_MIN_CURRENT); - - // /* Get the current we want */ - // uint16_t voltage = USB_PD_VMAX * 1000; // in mv - // if (requested_voltage_mv != 5000) { - // voltage = requested_voltage_mv; - // } - // uint16_t current = (voltage) / getTipResistanceX10(); // In centi-amps - - // /* Add a PDO for the desired power. */ - // cap->obj[numobj++] = PD_PDO_TYPE_FIXED | PD_PDO_SNK_FIXED_VOLTAGE_SET(PD_MV2PDV(voltage)) | PD_PDO_SNK_FIXED_CURRENT_SET(current); - - // /* Get the PDO from the voltage range */ - // int8_t i = dpm_get_range_fixed_pdo_index(cap); - - // /* If it's vSafe5V, set our vSafe5V's current to what we want */ - // if (i == 0) { - // cap->obj[0] &= ~PD_PDO_SNK_FIXED_CURRENT; - // cap->obj[0] |= PD_PDO_SNK_FIXED_CURRENT_SET(current); - // } else { - // /* If we want more than 5 V, set the Higher Capability flag */ - // if (PD_MV2PDV(voltage) != PD_MV2PDV(5000)) { - // cap->obj[0] |= PD_PDO_SNK_FIXED_HIGHER_CAP; - // } - - // /* If the range PDO is a different voltage than the preferred - // * voltage, add it to the array. */ - // if (i > 0 && PD_PDO_SRC_FIXED_VOLTAGE_GET(cap->obj[i]) != PD_MV2PDV(voltage)) { - // cap->obj[numobj++] = PD_PDO_TYPE_FIXED | PD_PDO_SNK_FIXED_VOLTAGE_SET(PD_PDO_SRC_FIXED_VOLTAGE_GET(cap->obj[i])) | PD_PDO_SNK_FIXED_CURRENT_SET(PD_PDO_SRC_FIXED_CURRENT_GET(cap->obj[i])); - // } - - // /* If we have three PDOs at this point, make sure the last two are - // * sorted by voltage. */ - // if (numobj == 3 && (cap->obj[1] & PD_PDO_SNK_FIXED_VOLTAGE) > (cap->obj[2] & PD_PDO_SNK_FIXED_VOLTAGE)) { - // cap->obj[1] ^= cap->obj[2]; - // cap->obj[2] ^= cap->obj[1]; - // cap->obj[1] ^= cap->obj[2]; - // } - // /* If we're using PD 3.0, add a PPS APDO for our desired voltage */ - // if ((hdr_template & PD_HDR_SPECREV) >= PD_SPECREV_3_0) { - // cap->obj[numobj++] - // = PD_PDO_TYPE_AUGMENTED | PD_APDO_TYPE_PPS | PD_APDO_PPS_MAX_VOLTAGE_SET(PD_MV2PAV(voltage)) | PD_APDO_PPS_MIN_VOLTAGE_SET(PD_MV2PAV(voltage)) | - // PD_APDO_PPS_CURRENT_SET(PD_CA2PAI(current)); - // } - // } - - // /* Set the unconstrained power flag. */ - // if (_unconstrained_power) { - // cap->obj[0] |= PD_PDO_SNK_FIXED_UNCONSTRAINED; - // } - // /* Set the USB communications capable flag. */ - // cap->obj[0] |= PD_PDO_SNK_FIXED_USB_COMMS; - - // /* Set the Sink_Capabilities message header */ - // cap->hdr = hdr_template | PD_MSGTYPE_SINK_CAPABILITIES | PD_NUMOBJ(numobj); + int numobj = 0; + + /* If we have no configuration or want something other than 5 V, add a PDO + * for vSafe5V */ + /* Minimum current, 5 V, and higher capability. */ + cap->obj[numobj++] = PD_PDO_TYPE_FIXED | PD_PDO_SNK_FIXED_VOLTAGE_SET(PD_MV2PDV(5000)) | PD_PDO_SNK_FIXED_CURRENT_SET(DPM_MIN_CURRENT); + // Voltages must be in order of lowest -> highest +#if USB_PD_VMAX >= 20 + add_v_record(cap, 9000, numobj); + numobj++; + add_v_record(cap, 15000, numobj); + numobj++; + add_v_record(cap, 20000, numobj); + numobj++; +#elif USB_PD_VMAX >= 15 + add_v_record(cap, 9000, numobj); + numobj++; + add_v_record(cap, 12000, numobj); + numobj++; + add_v_record(cap, 15000, numobj); + numobj++; +#elif USB_PD_VMAX >= 12 + add_v_record(cap, 9000, numobj); + numobj++; + add_v_record(cap, 12000, numobj); + numobj++; +#elif USB_PD_VMAX >= 9 + add_v_record(cap, 9000, numobj); + numobj++; +#endif + + /* Set the USB communications capable flag. */ + cap->obj[0] |= PD_PDO_SNK_FIXED_USB_COMMS; + + /* Set the Sink_Capabilities message header */ + cap->hdr = PD_DATAROLE_UFP | PD_SPECREV_3_0 | PD_POWERROLE_SINK | PD_MSGTYPE_SINK_CAPABILITIES | PD_NUMOBJ(numobj); } #endif diff --git a/source/Core/Drivers/Utils.cpp b/source/Core/Drivers/Utils.cpp index b65922f3c..b40918548 100644 --- a/source/Core/Drivers/Utils.cpp +++ b/source/Core/Drivers/Utils.cpp @@ -6,8 +6,9 @@ */ #include "BSP_Power.h" +#include "Settings.h" #include "configuration.h" -#include +#include int32_t Utils::InterpolateLookupTable(const int32_t *lookupTable, const int noItems, const int32_t value) { for (int i = 1; i < (noItems - 1); i++) { @@ -22,7 +23,10 @@ int32_t Utils::InterpolateLookupTable(const int32_t *lookupTable, const int noIt int32_t Utils::LinearInterpolate(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x) { return y1 + (((((x - x1) * 1000) / (x2 - x1)) * (y2 - y1))) / 1000; } uint16_t Utils::RequiredCurrentForTipAtVoltage(uint16_t voltageX10) { - uint8_t tipResistancex10 = getTipResistanceX10() + 5; + uint8_t tipResistancex10 = getTipResistanceX10(); + if (getSettingValue(SettingsOptions::USBPDMode) == usbpdMode_t::DEFAULT) { + tipResistancex10 += 5; + } #ifdef MODEL_HAS_DCDC // If this device has step down DC/DC inductor to smooth out current spikes // We can instead ignore resistance and go for max voltage we can accept; and rely on the DC/DC regulation to keep under current limit @@ -31,4 +35,4 @@ uint16_t Utils::RequiredCurrentForTipAtVoltage(uint16_t voltageX10) { // V/R = I uint16_t currentX10 = (voltageX10 * 10) / tipResistancex10; return currentX10; -} \ No newline at end of file +} diff --git a/source/Core/Drivers/Utils.h b/source/Core/Drivers/Utils.hpp similarity index 76% rename from source/Core/Drivers/Utils.h rename to source/Core/Drivers/Utils.hpp index ede29124e..f4bad5c6f 100644 --- a/source/Core/Drivers/Utils.h +++ b/source/Core/Drivers/Utils.hpp @@ -1,12 +1,12 @@ /* - * Utils.h + * Utils.hpp * * Created on: 28 Apr 2021 * Author: Ralim */ -#ifndef CORE_DRIVERS_UTILS_H_ -#define CORE_DRIVERS_UTILS_H_ +#ifndef CORE_DRIVERS_UTILS_HPP_ +#define CORE_DRIVERS_UTILS_HPP_ #include class Utils { public: @@ -18,4 +18,4 @@ class Utils { }; -#endif /* CORE_DRIVERS_UTILS_H_ */ +#endif /* CORE_DRIVERS_UTILS_HPP_ */ diff --git a/source/Core/Drivers/WS2812B.h b/source/Core/Drivers/WS2812B.h new file mode 100644 index 000000000..d2292af21 --- /dev/null +++ b/source/Core/Drivers/WS2812B.h @@ -0,0 +1,81 @@ +/* + * WS2812B.h + * + * Created on: 9 July 2023 + * Author: Doegox + * Currently for RISC-V architecture only + * Based on WS2812.h by Ralim for STM32 + */ +#include "Pins.h" +#include "Setup.h" +#include +#include +#include + +#ifndef CORE_DRIVERS_WS2812B_H_ +#define CORE_DRIVERS_WS2812B_H_ + +#ifndef WS2812B_LED_CHANNEL_COUNT +#define WS2812B_LED_CHANNEL_COUNT 3 +#endif + +#define WS2812B_RAW_BYTES_PER_LED (WS2812B_LED_CHANNEL_COUNT * 8) + +template class WS2812B { +private: + uint8_t leds_colors[WS2812B_LED_CHANNEL_COUNT * LED_COUNT]; + +public: + void led_update() { + __disable_irq(); + // Bitbang it out as our cpu irq latency is too high + for (unsigned int i = 0; i < sizeof(leds_colors); i++) { + // Shove out MSB first + for (int x = 0; x < 8; x++) { + if ((leds_colors[i] & (1 << (7 - x))) == (1 << (7 - x))) { + gpio_write(LED_PIN, 1); + for (int k = 0; k < 27; k++) { + __ASM volatile("nop"); + } + gpio_write(LED_PIN, 0); + for (int k = 0; k < 10; k++) { + __ASM volatile("nop"); + } + } else { + gpio_write(LED_PIN, 1); + for (int k = 0; k < 10; k++) { + __ASM volatile("nop"); + } + gpio_write(LED_PIN, 0); + for (int k = 0; k < 27; k++) { + __ASM volatile("nop"); + } + } + } + } + __enable_irq(); + } + + void init(void) { memset(leds_colors, 0, sizeof(leds_colors)); + gpio_set_mode(LED_PIN, GPIO_OUTPUT_MODE); + gpio_write(LED_PIN, 1); + led_set_color(0, 0, 0xFF, 0); // green + led_update(); +} + + void led_set_color(size_t index, uint8_t r, uint8_t g, uint8_t b) { + leds_colors[index * WS2812B_LED_CHANNEL_COUNT + 0] = g; + leds_colors[index * WS2812B_LED_CHANNEL_COUNT + 1] = r; + leds_colors[index * WS2812B_LED_CHANNEL_COUNT + 2] = b; + } + + void led_set_color_all(uint8_t r, uint8_t g, uint8_t b) { + for (int index = 0; index < LED_COUNT; index++) { + leds_colors[index * WS2812B_LED_CHANNEL_COUNT + 0] = g; + leds_colors[index * WS2812B_LED_CHANNEL_COUNT + 1] = r; + leds_colors[index * WS2812B_LED_CHANNEL_COUNT + 2] = b; + } + } +}; + +#endif /* CORE_DRIVERS_WS2812B_H_ */ diff --git a/source/Core/Drivers/accelerometers_common.h b/source/Core/Drivers/accelerometers_common.h index 8c0f1aa92..b4f9c3a72 100644 --- a/source/Core/Drivers/accelerometers_common.h +++ b/source/Core/Drivers/accelerometers_common.h @@ -1,6 +1,6 @@ #ifndef CORE_DRIVERS_ACCELEROMTERS_COMMON_H_ #define CORE_DRIVERS_ACCELEROMTERS_COMMON_H_ - +#include "configuration.h" #if defined(ACCEL_I2CBB2) #include "I2CBB2.hpp" #define ACCEL_I2C_CLASS I2CBB2 diff --git a/source/Core/Drivers/usb-pd b/source/Core/Drivers/usb-pd index feef71016..53d12057f 160000 --- a/source/Core/Drivers/usb-pd +++ b/source/Core/Drivers/usb-pd @@ -1 +1 @@ -Subproject commit feef71016cb3f3d5731f926c0d09b692aaaa9b7e +Subproject commit 53d12057fb1a0eac896aab1acfc9cc078c5ca546 diff --git a/source/Core/Inc/ScrollMessage.hpp b/source/Core/Inc/ScrollMessage.hpp index 3f97fdb99..9352ad4e5 100644 --- a/source/Core/Inc/ScrollMessage.hpp +++ b/source/Core/Inc/ScrollMessage.hpp @@ -4,50 +4,21 @@ #include "portmacro.h" #include /** - * A helper class for showing a full-screen scrolling message. + * A helper for showing a full-screen scrolling message. */ -class ScrollMessage { - TickType_t messageStart = 0; - int16_t lastOffset = -1; - /** - * Calcualte the width in pixels of the message string, in the large - * font and taking into account multi-byte chars. - * - * @param message The null-terminated message string. - */ - static uint16_t messageWidth(const char *message); - -public: - ScrollMessage() {} - - /** - * Resets this `ScrollMessage` instance to its initial state. - */ - void reset() { - messageStart = 0; - lastOffset = -1; - } - - /** - * Gets whether this `ScrollMessage` instance is in its initial state. - */ - bool isReset() const { return messageStart == 0; } - - /** - * Draw and update the scroll message if needed. - * - * This function does not call `OLED::refresh()`. If this function - * returns `true`, the caller shall call `OLED::refresh()` to draw the - * modified framebuffer to the OLED screen. - * - * @param message The null-terminated message string. This must be the - * same string as the previous call, unless this `ScrollMessage` instance - * is in its initial state or `reset()` has been called. - * @param currentTick The current tick as returned by `xTaskGetTickCount()`. - * @return Whether the OLED framebuffer has been modified. - */ - bool drawUpdate(const char *message, TickType_t currentTick); -}; +/** + * Draw and update the scroll message if needed. + * + * This function does not call `OLED::refresh()`. If this function + * returns `true`, the caller shall call `OLED::refresh()` to draw the + * modified framebuffer to the OLED screen. + * + * @param message The null-terminated message string. This must be the + * same string as the previous call, unless this `ScrollMessage` instance + * is in its initial state or `reset()` has been called. + * @param currentTick The current tick as returned by `xTaskGetTickCount()` offset to 0 at start of scrolling. + */ +void drawScrollingText(const char *message, TickType_t currentTickOffset); #endif /* SCROLL_MESSAGE_HPP_ */ diff --git a/source/Core/Inc/Settings.h b/source/Core/Inc/Settings.h index c1eef1280..623d3db9e 100644 --- a/source/Core/Inc/Settings.h +++ b/source/Core/Inc/Settings.h @@ -7,11 +7,18 @@ * Houses the system settings and allows saving / restoring from flash */ -#ifndef SETTINGS_H_ -#define SETTINGS_H_ +#include "configuration.h" + +#ifndef CORE_SETTINGS_H_ +#define CORE_SETTINGS_H_ #include #include -#define SETTINGSVERSION (0x2A) // This number is frozen, do not edit +#ifdef MODEL_Pinecilv2 +// Required settings reset for PR #1916 +#define SETTINGSVERSION (0x55AB) // This number is frozen, do not edit +#else +#define SETTINGSVERSION (0x55AA) // This number is frozen, do not edit +#endif enum SettingsOptions { SolderingTemp = 0, // current set point for the iron @@ -52,7 +59,7 @@ enum SettingsOptions { LOGOTime = 35, // Duration the logo will be displayed for CalibrateCJC = 36, // Toggle calibrate CJC at next boot BluetoothLE = 37, // Toggle BLE if present - PDVpdo = 38, // Toggle PPS & EPR + USBPDMode = 38, // Toggle PPS & EPR ProfilePhases = 39, // Number of profile mode phases ProfilePreheatTemp = 40, // Temperature to preheat to before the first phase ProfilePreheatSpeed = 41, // Maximum allowed preheat speed in degrees per second @@ -67,8 +74,11 @@ enum SettingsOptions { ProfilePhase5Temp = 50, // Temperature to target for the end of phase 5 ProfilePhase5Duration = 51, // Target duration for phase 5 ProfileCooldownSpeed = 52, // Maximum allowed cooldown speed in degrees per second + HallEffectSleepTime = 53, // Seconds (/5) timeout to sleep when hall effect over threshold + SolderingTipType = 54, // Selecting the type of soldering tip fitted + ReverseButtonSettings = 55, // Change the A and B button assigment in Settings menu // - SettingsOptionsLength = 53, // + SettingsOptionsLength = 56, // End marker }; typedef enum { @@ -92,6 +102,58 @@ typedef enum { AUTO = 2, // Automatic screen orientation based on accel.data if presented } orientationMode_t; +typedef enum { + SKIP = 0, // Skip boot logo + ONETIME = 5, // Show boot logo once (if animated) and stall until a button toggled + INFINITY = 6, // Show boot logo on repeat (if animated) until a button toggled +} logoMode_t; + +typedef enum { + DEFAULT = 1, // PPS + EPR + more power request through increasing resistance by 0.5 Ohm to compensate power loss over cable/PCB/etc. + SAFE = 2, // PPS + EPR, without requesting more power + NO_DYNAMIC = 0, // PPS + EPR disabled, fixed PDO only +} usbpdMode_t; + +typedef enum { + DISABLED = 0, // Locking buttons is disabled + BOOST = 1, // Locking buttons for Boost mode only + FULL = 2, // Locking buttons for Boost mode AND for Soldering mode +} lockingMode_t; + +/* Selection of the soldering tip + * Some devices allow multiple types of tips to be fitted, this allows selecting them or overriding the logic + * The first type will be the default (gets value of 0) + */ +#ifdef TIP_TYPE_SUPPORT +typedef enum { +#ifdef AUTO_TIP_SELECTION + TIP_TYPE_AUTO, // If the hardware supports automatic detection +#endif + +#ifdef TIPTYPE_T12 + T12_8_OHM, // TS100 style tips or Hakko T12 tips with adaptors + T12_6_2_OHM, // Short Tips manufactured by Pine64 + T12_4_OHM, // Longer tip but low resistance for PTS200 +#endif + // #ifdef TIPTYPE_TS80 + // TS80_4_5_OHM, // TS80(P) default tips + // // We do not know of other tuning tips (?yet?) + // #endif + // #ifdef TIPTYPE_JBC + // JBC_210_2_5_OHM, // Small JBC tips as used in the S60/S60P + // #endif + TIP_TYPE_MAX, // Max value marker +} tipType_t; +#else +typedef enum { + TIP_TYPE_AUTO = 0, // value for the default case + TIP_TYPE_MAX = 0, // marker for settings when not supported +} tipType_t; +#endif /* TIP_TYPE_SUPPORT */ + +// returns the resistance matching the selected tip type or 0 for auto and when not supported +uint8_t getUserSelectedTipResistance(); + // Settings wide operations void saveSettings(); bool loadSettings(); @@ -101,13 +163,16 @@ void resetSettings(); uint16_t getSettingValue(const enum SettingsOptions option); // Returns true if setting is now on the last value (next iteration will wrap) -bool nextSettingValue(const enum SettingsOptions option); -bool prevSettingValue(const enum SettingsOptions option); - +void nextSettingValue(const enum SettingsOptions option); +void prevSettingValue(const enum SettingsOptions option); +bool isLastSettingValue(const enum SettingsOptions option); +// For setting values to settings void setSettingValue(const enum SettingsOptions option, const uint16_t newValue); -// Special access -uint8_t lookupVoltageLevel(); -uint16_t lookupHallEffectThreshold(); - -#endif /* SETTINGS_H_ */ +// Special access helpers, to reduce logic duplication +uint8_t lookupVoltageLevel(); +uint16_t lookupHallEffectThreshold(); +#ifdef TIP_TYPE_SUPPORT +const char *lookupTipName(); // Get the name string for the current soldering tip +#endif /* TIP_TYPE_SUPPORT */ +#endif /* SETTINGS_H_ */ diff --git a/source/Core/Inc/Translation.h b/source/Core/Inc/Translation.h index f2b84ffa0..c67913d56 100644 --- a/source/Core/Inc/Translation.h +++ b/source/Core/Inc/Translation.h @@ -48,6 +48,8 @@ extern const char *SmallSymbolState; extern const char *SmallSymbolNoVBus; extern const char *SmallSymbolVBus; +extern const char *LargeSymbolSleep; + extern const char *DebugMenu[]; extern const char *AccelTypeNames[]; extern const char *PowerSourceNames[]; @@ -57,7 +59,7 @@ enum class SettingsItemIndex : uint8_t { MinVolCell, QCMaxVoltage, PDNegTimeout, - PDVpdo, + USBPDMode, BoostTemperature, AutoStart, TempChangeShortStep, @@ -82,11 +84,13 @@ enum class SettingsItemIndex : uint8_t { SleepTimeout, ShutdownTimeout, HallEffSensitivity, + HallEffSleepTimeout, TemperatureUnit, DisplayRotation, CooldownBlink, ScrollingSpeed, ReverseButtonTempChange, + ReverseButtonSettings, AnimSpeed, AnimLoop, Brightness, @@ -103,6 +107,7 @@ enum class SettingsItemIndex : uint8_t { PowerPulseDuration, SettingsReset, LanguageSwitch, + SolderingTipType, NUM_ITEMS, }; @@ -127,27 +132,31 @@ struct TranslationIndexTable { uint16_t ProfilePreheatString; uint16_t ProfileCooldownString; - uint16_t SleepingSimpleString; uint16_t SleepingAdvancedString; uint16_t SleepingTipAdvancedString; - uint16_t OffString; uint16_t DeviceFailedValidationWarning; uint16_t TooHotToStartProfileWarning; uint16_t SettingRightChar; uint16_t SettingLeftChar; uint16_t SettingAutoChar; - uint16_t SettingOffChar; uint16_t SettingSlowChar; uint16_t SettingMediumChar; uint16_t SettingFastChar; - uint16_t SettingStartNoneChar; uint16_t SettingStartSolderingChar; uint16_t SettingStartSleepChar; uint16_t SettingStartSleepOffChar; - uint16_t SettingLockDisableChar; uint16_t SettingLockBoostChar; uint16_t SettingLockFullChar; + uint16_t USBPDModeDefault; + uint16_t USBPDModeNoDynamic; + uint16_t USBPDModeSafe; + uint16_t TipTypeAuto; + uint16_t TipTypeT12Long; + uint16_t TipTypeT12Short; + uint16_t TipTypeT12PTS; + uint16_t TipTypeTS80; + uint16_t TipTypeJBCC210; uint16_t SettingsDescriptions[static_cast(SettingsItemIndex::NUM_ITEMS)]; uint16_t SettingsShortNames[static_cast(SettingsItemIndex::NUM_ITEMS)]; @@ -187,6 +196,7 @@ const char *translatedString(uint16_t index); void prepareTranslations(); void settings_displayLanguageSwitch(void); bool settings_showLanguageSwitch(void); -bool settings_setLanguageSwitch(void); +void settings_setLanguageSwitch(void); +bool isLastLanguageOption(void); #endif /* TRANSLATION_H_ */ diff --git a/source/Core/Inc/Types.h b/source/Core/Inc/Types.h index 145cd6beb..ad215994b 100644 --- a/source/Core/Inc/Types.h +++ b/source/Core/Inc/Types.h @@ -1,10 +1,10 @@ #ifndef TYPES_H_ #define TYPES_H_ -#include +#include // Used for temperature represented in C or x10C. // typedef int32_t TemperatureType_t; -#endif \ No newline at end of file +#endif diff --git a/source/Core/Inc/settingsGUI.hpp b/source/Core/Inc/settingsGUI.hpp index f1d908525..4575ce981 100644 --- a/source/Core/Inc/settingsGUI.hpp +++ b/source/Core/Inc/settingsGUI.hpp @@ -8,11 +8,11 @@ #ifndef GUI_HPP_ #define GUI_HPP_ #include "BSP.h" +#include "Buttons.hpp" #include "FreeRTOS.h" #include "Settings.h" #include "Translation.h" - #define PRESS_ACCEL_STEP (TICKS_100MS / 3) #define PRESS_ACCEL_INTERVAL_MIN TICKS_100MS #define PRESS_ACCEL_INTERVAL_MAX (TICKS_100MS * 3) @@ -26,9 +26,8 @@ typedef struct { // The settings description index, please use the `SETTINGS_DESC` macro with // the `SettingsItemIndex` enum. Use 0 for no description. uint8_t description; - // return true if increment reached the maximum value - bool (*const incrementHandler)(void); - void (*const draw)(void); + void (*const incrementHandler)(void); + void (*const draw)(void); // Must not be nullptr, as that marks end of menu bool (*const isVisible)(void); // If this is set, we will automatically use the settings increment handler instead, set >= num settings to disable SettingsOptions autoSettingOption; @@ -36,8 +35,8 @@ typedef struct { uint8_t shortDescriptionSize; } menuitem; -void enterSettingsMenu(); -void warnUser(const char *warning, const TickType_t timeout); -extern const menuitem rootSettingsMenu[]; +void enterSettingsMenu(); +extern const menuitem rootSettingsMenu[]; +extern const menuitem *subSettingsMenus[]; #endif /* GUI_HPP_ */ diff --git a/source/Core/Inc/stm32f1xx_hal_conf.h b/source/Core/Inc/stm32f1xx_hal_conf.h index 0ba2ae22d..ad6ef04bf 100644 --- a/source/Core/Inc/stm32f1xx_hal_conf.h +++ b/source/Core/Inc/stm32f1xx_hal_conf.h @@ -60,7 +60,7 @@ extern "C" { /*#define HAL_ETH_MODULE_ENABLED */ /*#define HAL_FLASH_MODULE_ENABLED */ #define HAL_GPIO_MODULE_ENABLED -#define HAL_I2C_MODULE_ENABLED +/* #define HAL_I2C_MODULE_ENABLED */ /*#define HAL_I2S_MODULE_ENABLED */ /*#define HAL_IRDA_MODULE_ENABLED */ #define HAL_IWDG_MODULE_ENABLED diff --git a/source/Core/LangSupport/lang_multi.cpp b/source/Core/LangSupport/lang_multi.cpp index 44e28ad20..8ce45f964 100644 --- a/source/Core/LangSupport/lang_multi.cpp +++ b/source/Core/LangSupport/lang_multi.cpp @@ -63,12 +63,13 @@ void prepareTranslations() { } } -bool settings_setLanguageSwitch(void) { +void settings_setLanguageSwitch(void) { selectedLangIndex = (selectedLangIndex + 1) % LanguageCount; writeSelectedLanguageToSettings(); prepareTranslations(); - return selectedLangIndex == (LanguageCount - 1); } bool settings_showLanguageSwitch(void) { return true; } void settings_displayLanguageSwitch(void) { OLED::printWholeScreen(translatedString(Tr->SettingsShortNames[static_cast(SettingsItemIndex::LanguageSwitch)])); } + +bool isLastLanguageOption(void) { return selectedLangIndex == (LanguageCount - 1); } \ No newline at end of file diff --git a/source/Core/LangSupport/lang_single.cpp b/source/Core/LangSupport/lang_single.cpp index 019c0938c..48d6c8d55 100644 --- a/source/Core/LangSupport/lang_single.cpp +++ b/source/Core/LangSupport/lang_single.cpp @@ -1,6 +1,7 @@ #include "Translation.h" -bool settings_setLanguageSwitch(void) { return false; } +void settings_setLanguageSwitch(void) {} void settings_displayLanguageSwitch(void) {} bool settings_showLanguageSwitch(void) { return false; } +bool isLastLanguageOption(void) { return true; } \ No newline at end of file diff --git a/source/Core/Src/ScrollMessage.cpp b/source/Core/Src/ScrollMessage.cpp index d63cede37..c56b593bd 100644 --- a/source/Core/Src/ScrollMessage.cpp +++ b/source/Core/Src/ScrollMessage.cpp @@ -1,6 +1,6 @@ #include "ScrollMessage.hpp" - #include "OLED.hpp" +#include "Settings.h" #include "configuration.h" /** @@ -28,19 +28,20 @@ static uint16_t str_display_len(const char *const str) { return count; } -uint16_t ScrollMessage::messageWidth(const char *message) { return FONT_12_WIDTH * str_display_len(message); } - -bool ScrollMessage::drawUpdate(const char *message, TickType_t currentTick) { - bool lcdRefresh = false; +/** + * Calculate the width in pixels of the message string, in the large + * font and taking into account multi-byte chars. + * + * @param message The null-terminated message string. + */ +uint16_t messageWidth(const char *message) { return FONT_12_WIDTH * str_display_len(message); } - if (messageStart == 0) { - messageStart = currentTick; - lcdRefresh = true; - } +void drawScrollingText(const char *message, TickType_t currentTickOffset) { + OLED::clearScreen(); int16_t messageOffset; uint16_t msgWidth = messageWidth(message); if (msgWidth > OLED_WIDTH) { - messageOffset = ((currentTick - messageStart) / (getSettingValue(SettingsOptions::DescriptionScrollSpeed) == 1 ? TICKS_100MS / 10 : (TICKS_100MS / 5))); + messageOffset = (currentTickOffset / (getSettingValue(SettingsOptions::DescriptionScrollSpeed) == 1 ? TICKS_100MS / 10 : (TICKS_100MS / 5))); messageOffset %= msgWidth + OLED_WIDTH; // Roll around at the end if (messageOffset < OLED_WIDTH) { // Snap the message to the left edge. @@ -54,15 +55,7 @@ bool ScrollMessage::drawUpdate(const char *message, TickType_t currentTick) { messageOffset = (OLED_WIDTH - msgWidth) / 2 + msgWidth; } - if (lastOffset != messageOffset) { - OLED::clearScreen(); - - //^ Rolling offset based on time - OLED::setCursor((OLED_WIDTH - messageOffset), 0); - OLED::print(message, FontStyle::LARGE); - lastOffset = messageOffset; - lcdRefresh = true; - } - - return lcdRefresh; + //^ Rolling offset based on time + OLED::setCursor((OLED_WIDTH - messageOffset), 0); + OLED::print(message, FontStyle::LARGE); } diff --git a/source/Core/Src/Settings.cpp b/source/Core/Src/Settings.cpp index 5196f4a48..89adc406c 100644 --- a/source/Core/Src/Settings.cpp +++ b/source/Core/Src/Settings.cpp @@ -16,6 +16,10 @@ #include // for memset bool sanitiseSettings(); +/* + * Used to constrain the QC 3.0 Voltage selection to suit hardware. + * We allow a little overvoltage for users who want to push it + */ #ifdef POW_QC_20V #define QC_VOLTAGE_MAX 220 #else @@ -50,60 +54,63 @@ typedef struct { } SettingConstants; static const SettingConstants settingsConstants[(int)SettingsOptions::SettingsOptionsLength] = { - //{min,max,increment,default} - {MIN_TEMP_C, MAX_TEMP_F, 5, 320}, // SolderingTemp - {MIN_TEMP_C, MAX_TEMP_F, 5, 150}, // SleepTemp - {0, 15, 1, SLEEP_TIME}, // SleepTime - {0, 4, 1, CUT_OUT_SETTING}, // MinDCVoltageCells - {24, 38, 1, RECOM_VOL_CELL}, // MinVoltageCells - {90, QC_VOLTAGE_MAX, 2, 90}, // QCIdealVoltage - {0, 2, 1, ORIENTATION_MODE}, // OrientationMode - {0, 9, 1, SENSITIVITY}, // Sensitivity - {0, 1, 1, ANIMATION_LOOP}, // AnimationLoop - {0, settingOffSpeed_t::MAX_VALUE - 1, 1, ANIMATION_SPEED}, // AnimationSpeed - {0, 3, 1, AUTO_START_MODE}, // AutoStartMode - {0, 60, 1, SHUTDOWN_TIME}, // ShutdownTime - {0, 1, 1, COOLING_TEMP_BLINK}, // CoolingTempBlink - {0, 1, 1, DETAILED_IDLE}, // DetailedIDLE - {0, 1, 1, DETAILED_SOLDERING}, // DetailedSoldering - {0, (uint16_t)(HasFahrenheit ? 1 : 0), 1, TEMPERATURE_INF}, // TemperatureInF - {0, 1, 1, DESCRIPTION_SCROLL_SPEED}, // DescriptionScrollSpeed - {0, 2, 1, LOCKING_MODE}, // LockingMode - {0, 99, 1, POWER_PULSE_DEFAULT}, // KeepAwakePulse - {1, POWER_PULSE_WAIT_MAX, 1, POWER_PULSE_WAIT_DEFAULT}, // KeepAwakePulseWait - {1, POWER_PULSE_DURATION_MAX, 1, POWER_PULSE_DURATION_DEFAULT}, // KeepAwakePulseDuration - {360, 900, 1, VOLTAGE_DIV}, // VoltageDiv - {0, MAX_TEMP_F, 10, BOOST_TEMP}, // BoostTemp - {MIN_CALIBRATION_OFFSET, 2500, 1, CALIBRATION_OFFSET}, // CalibrationOffset - {0, MAX_POWER_LIMIT, POWER_LIMIT_STEPS, POWER_LIMIT}, // PowerLimit - {0, 1, 1, REVERSE_BUTTON_TEMP_CHANGE}, // ReverseButtonTempChangeEnabled - {5, TEMP_CHANGE_LONG_STEP_MAX, 5, TEMP_CHANGE_LONG_STEP}, // TempChangeLongStep - {1, TEMP_CHANGE_SHORT_STEP_MAX, 1, TEMP_CHANGE_SHORT_STEP}, // TempChangeShortStep - {0, 9, 1, 7}, // HallEffectSensitivity - {0, 9, 1, 0}, // AccelMissingWarningCounter - {0, 9, 1, 0}, // PDMissingWarningCounter - {0, 0xFFFF, 0, 41431 /*EN*/}, // UILanguage - {0, 50, 1, 20}, // PDNegTimeout - {0, 1, 1, 0}, // OLEDInversion - {MIN_BRIGHTNESS, MAX_BRIGHTNESS, BRIGHTNESS_STEP, DEFAULT_BRIGHTNESS}, // OLEDBrightness - {0, 5, 1, 1}, // LOGOTime - {0, 1, 1, 0}, // CalibrateCJC - {0, 1, 1, 1}, // BluetoothLE - {0, 1, 1, 1}, // PDVpdo - {1, 5, 1, 4}, // ProfilePhases - {MIN_TEMP_C, MAX_TEMP_F, 5, 90}, // ProfilePreheatTemp - {1, 10, 1, 1}, // ProfilePreheatSpeed - {MIN_TEMP_C, MAX_TEMP_F, 5, 130}, // ProfilePhase1Temp - {10, 180, 5, 90}, // ProfilePhase1Duration - {MIN_TEMP_C, MAX_TEMP_F, 5, 140}, // ProfilePhase2Temp - {10, 180, 5, 30}, // ProfilePhase2Duration - {MIN_TEMP_C, MAX_TEMP_F, 5, 165}, // ProfilePhase3Temp - {10, 180, 5, 30}, // ProfilePhase3Duration - {MIN_TEMP_C, MAX_TEMP_F, 5, 140}, // ProfilePhase4Temp - {10, 180, 5, 30}, // ProfilePhase4Duration - {MIN_TEMP_C, MAX_TEMP_F, 5, 90}, // ProfilePhase5Temp - {10, 180, 5, 30}, // ProfilePhase5Duration - {1, 10, 1, 2}, // ProfileCooldownSpeed + //{ min, max, increment, default} + { MIN_TEMP_C, MAX_TEMP_F, 5, SOLDERING_TEMP}, // SolderingTemp + { MIN_TEMP_C, MAX_TEMP_F, 5, 150}, // SleepTemp + { 0, 15, 1, SLEEP_TIME}, // SleepTime + { 0, 4, 1, CUT_OUT_SETTING}, // MinDCVoltageCells + { 24, 38, 1, RECOM_VOL_CELL}, // MinVoltageCells + { 90, QC_VOLTAGE_MAX, 2, 90}, // QCIdealVoltage + { 0, MAX_ORIENTATION_MODE, 1, ORIENTATION_MODE}, // OrientationMode + { 0, 9, 1, SENSITIVITY}, // Sensitivity + { 0, 1, 1, ANIMATION_LOOP}, // AnimationLoop + { 0, settingOffSpeed_t::MAX_VALUE - 1, 1, ANIMATION_SPEED}, // AnimationSpeed + { 0, 3, 1, AUTO_START_MODE}, // AutoStartMode + { 0, 60, 1, SHUTDOWN_TIME}, // ShutdownTime + { 0, 1, 1, COOLING_TEMP_BLINK}, // CoolingTempBlink + { 0, 1, 1, DETAILED_IDLE}, // DetailedIDLE + { 0, 1, 1, DETAILED_SOLDERING}, // DetailedSoldering + { 0, (uint16_t)(HasFahrenheit ? 1 : 0), 1, TEMPERATURE_INF}, // TemperatureInF + { 0, 1, 1, DESCRIPTION_SCROLL_SPEED}, // DescriptionScrollSpeed + { 0, 2, 1, LOCKING_MODE}, // LockingMode + { 0, 99, 1, POWER_PULSE_DEFAULT}, // KeepAwakePulse + { 1, POWER_PULSE_WAIT_MAX, 1, POWER_PULSE_WAIT_DEFAULT}, // KeepAwakePulseWait + { 1, POWER_PULSE_DURATION_MAX, 1, POWER_PULSE_DURATION_DEFAULT}, // KeepAwakePulseDuration + { 360, 900, 1, VOLTAGE_DIV}, // VoltageDiv + { 0, MAX_TEMP_F, 10, BOOST_TEMP}, // BoostTemp + {MIN_CALIBRATION_OFFSET, 2500, 1, CALIBRATION_OFFSET}, // CalibrationOffset + { 0, MAX_POWER_LIMIT, POWER_LIMIT_STEPS, POWER_LIMIT}, // PowerLimit + { 0, 1, 1, REVERSE_BUTTON_TEMP_CHANGE}, // ReverseButtonTempChangeEnabled + { 5, TEMP_CHANGE_LONG_STEP_MAX, 5, TEMP_CHANGE_LONG_STEP}, // TempChangeLongStep + { 1, TEMP_CHANGE_SHORT_STEP_MAX, 1, TEMP_CHANGE_SHORT_STEP}, // TempChangeShortStep + { 0, 9, 1, 7}, // HallEffectSensitivity + { 0, 9, 1, 0}, // AccelMissingWarningCounter + { 0, 9, 1, 0}, // PDMissingWarningCounter + { 0, 0xFFFF, 0, 41431 /*EN*/}, // UILanguage + { 0, 50, 1, 20}, // PDNegTimeout + { 0, 1, 1, 0}, // OLEDInversion + { MIN_BRIGHTNESS, MAX_BRIGHTNESS, BRIGHTNESS_STEP, DEFAULT_BRIGHTNESS}, // OLEDBrightness + { 0, 6, 1, 1}, // LOGOTime + { 0, 1, 1, 0}, // CalibrateCJC + { 0, 1, 1, 0}, // BluetoothLE + { 0, 2, 1, 0}, // USBPDMode + { 1, 5, 1, 4}, // ProfilePhases + { MIN_TEMP_C, MAX_TEMP_F, 5, 90}, // ProfilePreheatTemp + { 1, 10, 1, 1}, // ProfilePreheatSpeed + { MIN_TEMP_C, MAX_TEMP_F, 5, 130}, // ProfilePhase1Temp + { 10, 180, 5, 90}, // ProfilePhase1Duration + { MIN_TEMP_C, MAX_TEMP_F, 5, 140}, // ProfilePhase2Temp + { 10, 180, 5, 30}, // ProfilePhase2Duration + { MIN_TEMP_C, MAX_TEMP_F, 5, 165}, // ProfilePhase3Temp + { 10, 180, 5, 30}, // ProfilePhase3Duration + { MIN_TEMP_C, MAX_TEMP_F, 5, 140}, // ProfilePhase4Temp + { 10, 180, 5, 30}, // ProfilePhase4Duration + { MIN_TEMP_C, MAX_TEMP_F, 5, 90}, // ProfilePhase5Temp + { 10, 180, 5, 30}, // ProfilePhase5Duration + { 1, 10, 1, 2}, // ProfileCooldownSpeed + { 0, 12, 1, 0}, // HallEffectSleepTime + { 0, (tipType_t::TIP_TYPE_MAX - 1) > 0 ? (tipType_t::TIP_TYPE_MAX - 1) : 0, 1, 0}, // SolderingTipType + { 0, 1, 1, 0}, // ReverseButtonSettings }; static_assert((sizeof(settingsConstants) / sizeof(SettingConstants)) == ((int)SettingsOptions::SettingsOptionsLength)); @@ -135,9 +142,9 @@ bool sanitiseSettings() { // For all settings, need to ensure settings are in a valid range // First for any not know about due to array growth, reset them and update the length value bool dirty = false; - if (systemSettings.versionMarker != 0x55AA) { + if (systemSettings.versionMarker != SETTINGSVERSION) { memset((void *)&systemSettings, 0xFF, sizeof(systemSettings)); - systemSettings.versionMarker = 0x55AA; + systemSettings.versionMarker = SETTINGSVERSION; dirty = true; } if (systemSettings.padding != 0xFFFFFFFF) { @@ -188,7 +195,7 @@ uint16_t getSettingValue(const enum SettingsOptions option) { return systemSetti // Increment by the step size to the next value. If past the end wrap to the minimum // Returns true if we are on the _last_ value -bool nextSettingValue(const enum SettingsOptions option) { +void nextSettingValue(const enum SettingsOptions option) { const auto constants = settingsConstants[(int)option]; if (systemSettings.settingsValues[(int)option] == (constants.max)) { // Already at max, wrap to the start @@ -200,13 +207,38 @@ bool nextSettingValue(const enum SettingsOptions option) { // Otherwise increment systemSettings.settingsValues[(int)option] += constants.increment; } - // Return if we are at the max - return constants.max == systemSettings.settingsValues[(int)option]; } +bool isLastSettingValue(const enum SettingsOptions option) { + const auto constants = settingsConstants[(int)option]; + uint16_t max = constants.max; + // handle temp unit limitations + if (option == SettingsOptions::SolderingTemp) { + if (getSettingValue(SettingsOptions::TemperatureInF)) { + max = MAX_TEMP_F; + } else { + max = MAX_TEMP_C; + } + } else if (option == SettingsOptions::BoostTemp) { + if (getSettingValue(SettingsOptions::TemperatureInF)) { + max = MAX_TEMP_F; + } else { + max = MAX_TEMP_C; + } + } else if (option == SettingsOptions::SleepTemp) { + if (getSettingValue(SettingsOptions::TemperatureInF)) { + max = 580; + } else { + max = 300; + } + } else if (option == SettingsOptions::UILanguage) { + return isLastLanguageOption(); + } + return systemSettings.settingsValues[(int)option] > (max - constants.increment); +} // Step backwards on the settings item // Return true if we are at the end (min) -bool prevSettingValue(const enum SettingsOptions option) { +void prevSettingValue(const enum SettingsOptions option) { const auto constants = settingsConstants[(int)option]; if (systemSettings.settingsValues[(int)option] == (constants.min)) { // Already at min, wrap to the max @@ -218,8 +250,6 @@ bool prevSettingValue(const enum SettingsOptions option) { // Otherwise decrement systemSettings.settingsValues[(int)option] -= constants.increment; } - // Return if we are at the min - return constants.min == systemSettings.settingsValues[(int)option]; } uint16_t lookupHallEffectThreshold() { @@ -268,3 +298,81 @@ uint8_t lookupVoltageLevel() { return (minVoltageOnCell * minVoltageCellCount) + (minVoltageCellCount * 2); } } + +#ifdef TIP_TYPE_SUPPORT +const char *lookupTipName() { + // Get the name string for the current soldering tip + tipType_t value = (tipType_t)getSettingValue(SettingsOptions::SolderingTipType); + + switch (value) { +#ifdef TIPTYPE_T12 + case tipType_t::T12_8_OHM: + return translatedString(Tr->TipTypeT12Long); + break; + case tipType_t::T12_6_2_OHM: + return translatedString(Tr->TipTypeT12Short); + break; + case tipType_t::T12_4_OHM: + return translatedString(Tr->TipTypeT12PTS); + break; +#endif +#ifdef TIPTYPE_TS80 + case tipType_t::TS80_4_5_OHM: + return translatedString(Tr->TipTypeTS80); + break; +#endif +#ifdef TIPTYPE_JBC + case tipType_t::JBC_210_2_5_OHM: + return translatedString(Tr->TipTypeJBCC210); + break; +#endif +#ifdef AUTO_TIP_SELECTION + case tipType_t::TIP_TYPE_AUTO: +#endif + default: + return translatedString(Tr->TipTypeAuto); + break; + } +} +#endif /* TIP_TYPE_SUPPORT */ + +// Returns the resistance for the current tip selected by the user or 0 for auto +#ifdef TIP_TYPE_SUPPORT +uint8_t getUserSelectedTipResistance() { + tipType_t value = (tipType_t)getSettingValue(SettingsOptions::SolderingTipType); + + switch (value) { +#ifdef AUTO_TIP_SELECTION + case tipType_t::TIP_TYPE_AUTO: + return 0; + break; +#endif +#ifdef TIPTYPE_T12 + case tipType_t::T12_8_OHM: + return 80; + break; + case tipType_t::T12_6_2_OHM: + return 62; + break; + case tipType_t::T12_4_OHM: + return 40; + break; +#endif +#ifdef TIPTYE_TS80 + case tipType_t::TS80_4_5_OHM: + return 45; + break; +#endif +#ifdef TIPTYPE_JBC + case tipType_t::JBC_210_2_5_OHM: + return 25; + break; +#endif + default: + return 0; + break; + } +} +#else +uint8_t getUserSelectedTipResistance() { return tipType_t::TIP_TYPE_AUTO; } +#endif /* TIP_TYPE_SUPPORT */ diff --git a/source/Core/Src/main.cpp b/source/Core/Src/main.cpp index 7b92316b8..503fce530 100644 --- a/source/Core/Src/main.cpp +++ b/source/Core/Src/main.cpp @@ -68,5 +68,6 @@ int main(void) { /* Start scheduler */ osKernelStart(); /* We should never get here as control is now taken by the scheduler */ - for (;;) {} + for (;;) { + } } diff --git a/source/Core/Src/settingsGUI.cpp b/source/Core/Src/settingsGUI.cpp index 9542b08c9..1163758d6 100644 --- a/source/Core/Src/settingsGUI.cpp +++ b/source/Core/Src/settingsGUI.cpp @@ -7,14 +7,14 @@ #include "settingsGUI.hpp" #include "Buttons.hpp" +#include "Font.h" #include "ScrollMessage.hpp" #include "TipThermoModel.h" #include "Translation.h" #include "cmsis_os.h" #include "configuration.h" #include "main.hpp" - -void gui_Menu(const menuitem *menu); +#include "ui_drawing.hpp" #ifdef POW_DC static void displayInputVRange(void); @@ -28,7 +28,7 @@ static void displayQCInputV(void); #ifdef POW_PD static void displayPDNegTimeout(void); -static void displayPDVpdo(void); +static void displayUSBPDMode(void); #endif /* POW_PD */ static void displaySensitivity(void); @@ -36,16 +36,18 @@ static void displayShutdownTime(void); static bool showSleepOptions(void); #ifndef NO_SLEEP_MODE -static bool setSleepTemp(void); +static void setSleepTemp(void); static void displaySleepTemp(void); static void displaySleepTime(void); #endif /* *not* NO_SLEEP_MODE */ -static bool setTempF(void); +static void setTempF(void); static void displayTempF(void); static void displayAdvancedSolderingScreens(void); static void displayAdvancedIDLEScreens(void); static void displayScrollSpeed(void); +static void displayReverseButtonTempChangeEnabled(void); +static void displayReverseButtonSettings(void); static void displayPowerLimit(void); #ifdef BLE_ENABLED @@ -53,20 +55,20 @@ static void displayBluetoothLE(void); #endif /* BLE_ENABLED */ #ifndef NO_DISPLAY_ROTATE -static bool setDisplayRotation(void); +static void setDisplayRotation(void); static void displayDisplayRotation(void); #endif /* *not* NO_DISPLAY_ROTATE */ -static bool setBoostTemp(void); +static void setBoostTemp(void); static void displayBoostTemp(void); #ifdef PROFILE_SUPPORT -static bool setProfilePreheatTemp(); -static bool setProfilePhase1Temp(); -static bool setProfilePhase2Temp(); -static bool setProfilePhase3Temp(); -static bool setProfilePhase4Temp(); -static bool setProfilePhase5Temp(); +static void setProfilePreheatTemp(); +static void setProfilePhase1Temp(); +static void setProfilePhase2Temp(); +static void setProfilePhase3Temp(); +static void setProfilePhase4Temp(); +static void setProfilePhase5Temp(); static void displayProfilePhases(void); static void displayProfilePreheatTemp(void); static void displayProfilePreheatSpeed(void); @@ -91,13 +93,10 @@ static bool showProfilePhase5Options(void); static void displayAutomaticStartMode(void); static void displayLockingMode(void); static void displayCoolingBlinkEnabled(void); -static bool setResetSettings(void); -static void displayResetSettings(void); -static bool setCalibrate(void); +static void setResetSettings(void); +static void setCalibrate(void); static void displayCalibrate(void); -static bool setCalibrateVIN(void); -static void displayCalibrateVIN(void); -static void displayReverseButtonTempChangeEnabled(void); +static void setCalibrateVIN(void); static void displayTempChangeShortStep(void); static void displayTempChangeLongStep(void); static void displayPowerPulse(void); @@ -113,24 +112,26 @@ static void displayLogoTime(void); #ifdef HALL_SENSOR static void displayHallEffect(void); +static void displayHallEffectSleepTime(void); static bool showHallEffect(void); #endif /* HALL_SENSOR */ +// Tip type selection +#ifdef TIP_TYPE_SUPPORT +static void displaySolderingTipType(void); +static bool showSolderingTipType(void); +#endif /* TIP_TYPE_SUPPORT */ + // Menu functions -#if defined(POW_DC) || defined(POW_QC) +#if defined(POW_DC) || defined(POW_QC) || defined(POW_PD) static void displayPowerMenu(void); -static bool enterPowerMenu(void); #endif /* POW_DC or POW_QC */ static void displaySolderingMenu(void); -static bool enterSolderingMenu(void); static void displayPowerSavingMenu(void); -static bool enterPowerSavingMenu(void); static void displayUIMenu(void); -static bool enterUIMenu(void); static void displayAdvancedMenu(void); -static bool enterAdvancedMenu(void); /* * Root Settings Menu @@ -140,9 +141,10 @@ static bool enterAdvancedMenu(void); * -Minimum Voltage * QC Voltage * PD Timeout - * PDVpdo + * USBPDMode * * Soldering + * Tip Type selection * Boost Mode Temp * Auto Start * Temp Change Short Step @@ -169,6 +171,7 @@ static bool enterAdvancedMenu(void); * -Sleep Time * -Shutdown Time * Hall Sensor Sensitivity + * Hall Sensor Sleep Time * * UI * Temperature Unit @@ -196,6 +199,7 @@ static bool enterAdvancedMenu(void); * */ +void noOpDisplay() {} /* vvv !!!DISABLE CLANG-FORMAT for menuitems initialization!!! vvv */ /* clang-format off */ @@ -214,18 +218,18 @@ const menuitem rootSettingsMenu[] { * // Language * Exit */ -#if defined(POW_DC) || defined(POW_QC) +#if defined(POW_DC) || defined(POW_QC) || defined(POW_PD) /* Power */ - {0, enterPowerMenu, displayPowerMenu, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, + {0, nullptr, displayPowerMenu, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, #endif /* Soldering */ - {0, enterSolderingMenu, displaySolderingMenu, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, + {0, nullptr, displaySolderingMenu, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, /* Sleep Options Menu */ - {0, enterPowerSavingMenu, displayPowerSavingMenu, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, + {0, nullptr, displayPowerSavingMenu, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, /* UI Menu */ - {0, enterUIMenu, displayUIMenu, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, + {0, nullptr, displayUIMenu, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, /* Advanced Menu */ - {0, enterAdvancedMenu, displayAdvancedMenu, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, + {0, nullptr, displayAdvancedMenu, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, /* Language Switch */ {0, settings_setLanguageSwitch, settings_displayLanguageSwitch, settings_showLanguageSwitch, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0}, /* vvvv end of menu marker. DO NOT REMOVE vvvv */ @@ -240,7 +244,7 @@ const menuitem powerMenu[] = { * -Minimum Voltage * QC Voltage * PD Timeout - * PDVpdo + * USBPDMode */ #ifdef POW_DC /* Voltage input */ @@ -254,9 +258,9 @@ const menuitem powerMenu[] = { #endif #ifdef POW_PD /* PD timeout setup */ - {SETTINGS_DESC(SettingsItemIndex::PDNegTimeout), nullptr, displayPDNegTimeout, nullptr, SettingsOptions::PDNegTimeout, SettingsItemIndex::PDNegTimeout, 5}, + {SETTINGS_DESC(SettingsItemIndex::PDNegTimeout), nullptr, displayPDNegTimeout, nullptr, SettingsOptions::PDNegTimeout, SettingsItemIndex::PDNegTimeout, 6}, /* Toggle PPS & EPR */ - {SETTINGS_DESC(SettingsItemIndex::PDVpdo), nullptr, displayPDVpdo, nullptr, SettingsOptions::PDVpdo, SettingsItemIndex::PDVpdo, 7}, + {SETTINGS_DESC(SettingsItemIndex::USBPDMode), nullptr, displayUSBPDMode, nullptr, SettingsOptions::USBPDMode, SettingsItemIndex::USBPDMode, 4}, #endif /* vvvv end of menu marker. DO NOT REMOVE vvvv */ {0, nullptr, nullptr, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0} @@ -271,6 +275,7 @@ const menuitem solderingMenu[] = { * Temp Change Short Step * Temp Change Long Step * Locking Mode + * Tip Type * Profile Phases * Profile Preheat Temperature * Profile Preheat Max Temperature Change Per Second @@ -287,7 +292,7 @@ const menuitem solderingMenu[] = { * Profile Cooldown Max Temperature Change Per Second */ /* Boost Temp */ - {SETTINGS_DESC(SettingsItemIndex::BoostTemperature), setBoostTemp, displayBoostTemp, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::BoostTemperature, 5}, + {SETTINGS_DESC(SettingsItemIndex::BoostTemperature), setBoostTemp, displayBoostTemp, nullptr, SettingsOptions::BoostTemp, SettingsItemIndex::BoostTemperature, 5}, /* Auto start */ {SETTINGS_DESC(SettingsItemIndex::AutoStart), nullptr, displayAutomaticStartMode, nullptr, SettingsOptions::AutoStartMode, SettingsItemIndex::AutoStart, 7}, /* Temp change short step */ @@ -296,31 +301,35 @@ const menuitem solderingMenu[] = { {SETTINGS_DESC(SettingsItemIndex::TempChangeLongStep), nullptr, displayTempChangeLongStep, nullptr, SettingsOptions::TempChangeLongStep, SettingsItemIndex::TempChangeLongStep, 6}, /* Locking Mode */ {SETTINGS_DESC(SettingsItemIndex::LockingMode), nullptr, displayLockingMode, nullptr, SettingsOptions::LockingMode, SettingsItemIndex::LockingMode, 7}, +#ifdef TIP_TYPE_SUPPORT + /* Tip Type */ + {SETTINGS_DESC(SettingsItemIndex::SolderingTipType), nullptr, displaySolderingTipType, showSolderingTipType, SettingsOptions::SolderingTipType, SettingsItemIndex::SolderingTipType, 5}, +#endif /* TIP_TYPE_SUPPORT */ #ifdef PROFILE_SUPPORT /* Profile Phases */ {SETTINGS_DESC(SettingsItemIndex::ProfilePhases), nullptr, displayProfilePhases, nullptr, SettingsOptions::ProfilePhases, SettingsItemIndex::ProfilePhases, 7}, /* Profile Preheat Temp */ - {SETTINGS_DESC(SettingsItemIndex::ProfilePreheatTemp), setProfilePreheatTemp, displayProfilePreheatTemp, showProfileOptions, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::ProfilePreheatTemp, 5}, + {SETTINGS_DESC(SettingsItemIndex::ProfilePreheatTemp), setProfilePreheatTemp, displayProfilePreheatTemp, showProfileOptions, SettingsOptions::ProfilePreheatTemp, SettingsItemIndex::ProfilePreheatTemp, 5}, /* Profile Preheat Speed */ {SETTINGS_DESC(SettingsItemIndex::ProfilePreheatSpeed), nullptr, displayProfilePreheatSpeed, showProfileOptions, SettingsOptions::ProfilePreheatSpeed, SettingsItemIndex::ProfilePreheatSpeed, 5}, /* Phase 1 Temp */ - {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Temp), setProfilePhase1Temp, displayProfilePhase1Temp, showProfileOptions, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::ProfilePhase1Temp, 5}, + {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Temp), setProfilePhase1Temp, displayProfilePhase1Temp, showProfileOptions, SettingsOptions::ProfilePhase1Temp, SettingsItemIndex::ProfilePhase1Temp, 5}, /* Phase 1 Duration */ {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Duration), nullptr, displayProfilePhase1Duration, showProfileOptions, SettingsOptions::ProfilePhase1Duration, SettingsItemIndex::ProfilePhase1Duration, 5}, /* Phase 2 Temp */ - {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Temp), setProfilePhase2Temp, displayProfilePhase2Temp, showProfilePhase2Options, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::ProfilePhase2Temp, 5}, + {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Temp), setProfilePhase2Temp, displayProfilePhase2Temp, showProfilePhase2Options, SettingsOptions::ProfilePhase1Temp, SettingsItemIndex::ProfilePhase2Temp, 5}, /* Phase 2 Duration */ {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Duration), nullptr, displayProfilePhase2Duration, showProfilePhase2Options, SettingsOptions::ProfilePhase2Duration, SettingsItemIndex::ProfilePhase2Duration, 5}, /* Phase 3 Temp */ - {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Temp), setProfilePhase3Temp, displayProfilePhase3Temp, showProfilePhase3Options, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::ProfilePhase3Temp, 5}, + {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Temp), setProfilePhase3Temp, displayProfilePhase3Temp, showProfilePhase3Options, SettingsOptions::ProfilePhase1Temp, SettingsItemIndex::ProfilePhase3Temp, 5}, /* Phase 3 Duration */ {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Duration), nullptr, displayProfilePhase3Duration, showProfilePhase3Options, SettingsOptions::ProfilePhase3Duration, SettingsItemIndex::ProfilePhase3Duration, 5}, /* Phase 4 Temp */ - {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Temp), setProfilePhase4Temp, displayProfilePhase4Temp, showProfilePhase4Options, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::ProfilePhase4Temp, 5}, + {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Temp), setProfilePhase4Temp, displayProfilePhase4Temp, showProfilePhase4Options, SettingsOptions::ProfilePhase1Temp, SettingsItemIndex::ProfilePhase4Temp, 5}, /* Phase 4 Duration */ {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Duration), nullptr, displayProfilePhase4Duration, showProfilePhase4Options, SettingsOptions::ProfilePhase4Duration, SettingsItemIndex::ProfilePhase4Duration, 5}, /* Phase 5 Temp */ - {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Temp), setProfilePhase5Temp, displayProfilePhase5Temp, showProfilePhase5Options, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::ProfilePhase5Temp, 5}, + {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Temp), setProfilePhase5Temp, displayProfilePhase5Temp, showProfilePhase5Options, SettingsOptions::ProfilePhase1Temp, SettingsItemIndex::ProfilePhase5Temp, 5}, /* Phase 5 Duration */ {SETTINGS_DESC(SettingsItemIndex::ProfilePhase1Duration), nullptr, displayProfilePhase5Duration, showProfilePhase5Options, SettingsOptions::ProfilePhase5Duration, SettingsItemIndex::ProfilePhase5Duration, 5}, /* Profile Cooldown Speed */ @@ -343,7 +352,7 @@ const menuitem PowerSavingMenu[] = { {SETTINGS_DESC(SettingsItemIndex::MotionSensitivity), nullptr, displaySensitivity, nullptr, SettingsOptions::Sensitivity, SettingsItemIndex::MotionSensitivity, 7}, #ifndef NO_SLEEP_MODE /* Sleep Temp */ - {SETTINGS_DESC(SettingsItemIndex::SleepTemperature), setSleepTemp, displaySleepTemp, showSleepOptions, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::SleepTemperature, 5}, + {SETTINGS_DESC(SettingsItemIndex::SleepTemperature), setSleepTemp, displaySleepTemp, showSleepOptions, SettingsOptions::SleepTemp, SettingsItemIndex::SleepTemperature, 5}, /* Sleep Time */ {SETTINGS_DESC(SettingsItemIndex::SleepTimeout), nullptr, displaySleepTime, showSleepOptions, SettingsOptions::SleepTime, SettingsItemIndex::SleepTimeout, 5}, #endif /* *not* NO_SLEEP_MODE */ @@ -352,6 +361,8 @@ const menuitem PowerSavingMenu[] = { #ifdef HALL_SENSOR /* Hall Effect Sensitivity */ {SETTINGS_DESC(SettingsItemIndex::HallEffSensitivity), nullptr, displayHallEffect, showHallEffect, SettingsOptions::HallEffectSensitivity, SettingsItemIndex::HallEffSensitivity, 7}, + /* Hall Effect Sleep Time */ + {SETTINGS_DESC(SettingsItemIndex::HallEffSleepTimeout), nullptr, displayHallEffectSleepTime, showHallEffect, SettingsOptions::HallEffectSleepTime, SettingsItemIndex::HallEffSleepTimeout, 5}, #endif /* HALL_SENSOR */ /* vvvv end of menu marker. DO NOT REMOVE vvvv */ {0, nullptr, nullptr, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0} @@ -374,10 +385,10 @@ const menuitem UIMenu[] = { * Detailed Soldering */ /* Temperature units, this has to be the first element in the array to work with the logic in enterUIMenu() */ - {SETTINGS_DESC(SettingsItemIndex::TemperatureUnit), setTempF, displayTempF, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::TemperatureUnit, 7}, + {SETTINGS_DESC(SettingsItemIndex::TemperatureUnit), setTempF, displayTempF, nullptr, SettingsOptions::TemperatureInF, SettingsItemIndex::TemperatureUnit, 7}, #ifndef NO_DISPLAY_ROTATE /* Display Rotation */ - {SETTINGS_DESC(SettingsItemIndex::DisplayRotation), setDisplayRotation, displayDisplayRotation, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::DisplayRotation, 7}, + {SETTINGS_DESC(SettingsItemIndex::DisplayRotation), setDisplayRotation, displayDisplayRotation, nullptr, SettingsOptions::OrientationMode, SettingsItemIndex::DisplayRotation, 7}, #endif /* *not* NO_DISPLAY_ROTATE */ /* Cooling blink warning */ {SETTINGS_DESC(SettingsItemIndex::CooldownBlink), nullptr, displayCoolingBlinkEnabled, nullptr, SettingsOptions::CoolingTempBlink, SettingsItemIndex::CooldownBlink, 7}, @@ -385,6 +396,8 @@ const menuitem UIMenu[] = { {SETTINGS_DESC(SettingsItemIndex::ScrollingSpeed), nullptr, displayScrollSpeed, nullptr, SettingsOptions::DescriptionScrollSpeed, SettingsItemIndex::ScrollingSpeed, 7}, /* Reverse Temp change buttons +/- */ {SETTINGS_DESC(SettingsItemIndex::ReverseButtonTempChange), nullptr, displayReverseButtonTempChangeEnabled, nullptr, SettingsOptions::ReverseButtonTempChangeEnabled, SettingsItemIndex::ReverseButtonTempChange, 7}, + /* Reverse Settings menu buttons A/B */ + {SETTINGS_DESC(SettingsItemIndex::ReverseButtonSettings), nullptr, displayReverseButtonSettings, nullptr, SettingsOptions::ReverseButtonSettings, SettingsItemIndex::ReverseButtonSettings, 7}, /* Animation Speed adjustment */ {SETTINGS_DESC(SettingsItemIndex::AnimSpeed), nullptr, displayAnimationSpeed, nullptr, SettingsOptions::AnimationSpeed, SettingsItemIndex::AnimSpeed, 7}, /* Animation Loop switch */ @@ -394,7 +407,7 @@ const menuitem UIMenu[] = { /* Invert screen colour */ {SETTINGS_DESC(SettingsItemIndex::ColourInversion), nullptr, displayInvertColor, nullptr, SettingsOptions::OLEDInversion, SettingsItemIndex::ColourInversion, 7}, /* Set logo duration */ - {SETTINGS_DESC(SettingsItemIndex::LOGOTime), nullptr, displayLogoTime, nullptr, SettingsOptions::LOGOTime, SettingsItemIndex::LOGOTime, 5}, + {SETTINGS_DESC(SettingsItemIndex::LOGOTime), nullptr, displayLogoTime, nullptr, SettingsOptions::LOGOTime, SettingsItemIndex::LOGOTime, 6}, /* Advanced idle screen */ {SETTINGS_DESC(SettingsItemIndex::AdvancedIdle), nullptr, displayAdvancedIDLEScreens, nullptr, SettingsOptions::DetailedIDLE, SettingsItemIndex::AdvancedIdle, 7}, /* Advanced soldering screen */ @@ -422,9 +435,9 @@ const menuitem advancedMenu[] = { /* Power limit */ {SETTINGS_DESC(SettingsItemIndex::PowerLimit), nullptr, displayPowerLimit, nullptr, SettingsOptions::PowerLimit, SettingsItemIndex::PowerLimit, 4}, /* Calibrate Cold Junktion Compensation at next boot */ - {SETTINGS_DESC(SettingsItemIndex::CalibrateCJC), setCalibrate, displayCalibrate, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::CalibrateCJC, 7}, + {SETTINGS_DESC(SettingsItemIndex::CalibrateCJC), setCalibrate, displayCalibrate, nullptr, SettingsOptions::CalibrateCJC, SettingsItemIndex::CalibrateCJC, 7}, /* Voltage input cal */ - {SETTINGS_DESC(SettingsItemIndex::VoltageCalibration), setCalibrateVIN, displayCalibrateVIN, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::VoltageCalibration, 5}, + {SETTINGS_DESC(SettingsItemIndex::VoltageCalibration), setCalibrateVIN, noOpDisplay, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::VoltageCalibration, 5}, /* Power Pulse adjustment */ {SETTINGS_DESC(SettingsItemIndex::PowerPulsePower), nullptr, displayPowerPulse, nullptr, SettingsOptions::KeepAwakePulse, SettingsItemIndex::PowerPulsePower, 5}, /* Power Pulse Wait adjustment */ @@ -432,7 +445,7 @@ const menuitem advancedMenu[] = { /* Power Pulse Duration adjustment */ {SETTINGS_DESC(SettingsItemIndex::PowerPulseDuration), nullptr, displayPowerPulseDuration, showPowerPulseOptions, SettingsOptions::KeepAwakePulseDuration, SettingsItemIndex::PowerPulseDuration, 7}, /* Resets settings */ - {SETTINGS_DESC(SettingsItemIndex::SettingsReset), setResetSettings, displayResetSettings, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::SettingsReset, 7}, + {SETTINGS_DESC(SettingsItemIndex::SettingsReset), setResetSettings, noOpDisplay, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::SettingsReset, 7}, /* vvvv end of menu marker. DO NOT REMOVE vvvv */ {0, nullptr, nullptr, nullptr, SettingsOptions::SettingsOptionsLength, SettingsItemIndex::NUM_ITEMS, 0} /* ^^^^ end of menu marker. DO NOT REMOVE ^^^^ */ @@ -440,6 +453,12 @@ const menuitem advancedMenu[] = { /* clang-format on */ +const menuitem *subSettingsMenus[]{ +#if defined(POW_DC) || defined(POW_QC) || defined(POW_PD) + powerMenu, +#endif + solderingMenu, PowerSavingMenu, UIMenu, advancedMenu, +}; /* ^^^ !!!ENABLE CLANG-FORMAT back!!! ^^^ */ /** @@ -460,10 +479,9 @@ static void printShortDescription(SettingsItemIndex settingsItemIndex, uint16_t } static int userConfirmation(const char *message) { - ScrollMessage scrollMessage; - + TickType_t tickStart = xTaskGetTickCount(); for (;;) { - bool lcdRefresh = scrollMessage.drawUpdate(message, xTaskGetTickCount()); + drawScrollingText(message, xTaskGetTickCount() - tickStart); ButtonState buttons = getButtonState(); switch (buttons) { @@ -481,10 +499,8 @@ static int userConfirmation(const char *message) { return 0; } - if (lcdRefresh) { - OLED::refresh(); - osDelay(40); - } + OLED::refresh(); + osDelay(40); } return 0; } @@ -527,18 +543,34 @@ static void displayQCInputV(void) { static void displayPDNegTimeout(void) { auto value = getSettingValue(SettingsOptions::PDNegTimeout); - if (value == 0) { - OLED::print(translatedString(Tr->OffString), FontStyle::LARGE); - } else { - OLED::printNumber(value, 3, FontStyle::LARGE); - } + value ? OLED::printNumber(value, 2, FontStyle::LARGE) : OLED::drawUnavailableIcon(); } -static void displayPDVpdo(void) { OLED::drawCheckbox(getSettingValue(SettingsOptions::PDVpdo)); } +static void displayUSBPDMode(void) { + /* + * Supported PD modes: + * DEFAULT, 1 = PPS + EPR + more power request through increasing resistance by 0.5 Ohm to compensate power loss over cable/PCB/etc. + * SAFE, 2 = PPS + EPR, without requesting more power + * NO_DYNAMIC, 0 = PPS + EPR disabled, fixed PDO only + */ + + switch (getSettingValue(SettingsOptions::USBPDMode)) { + case usbpdMode_t::DEFAULT: + OLED::print(translatedString(Tr->USBPDModeDefault), FontStyle::SMALL, 255, OLED::getCursorX()); + break; + case usbpdMode_t::SAFE: + OLED::print(translatedString(Tr->USBPDModeSafe), FontStyle::SMALL, 255, OLED::getCursorX()); + break; + case usbpdMode_t::NO_DYNAMIC: + default: + OLED::print(translatedString(Tr->USBPDModeNoDynamic), FontStyle::SMALL, 255, OLED::getCursorX()); + break; + } +} #endif /* POW_PD */ -static bool setBoostTemp(void) { +static void setBoostTemp(void) { uint16_t value = getSettingValue(SettingsOptions::BoostTemp); if (getSettingValue(SettingsOptions::TemperatureInF)) { if (value == 0) { @@ -550,33 +582,31 @@ static bool setBoostTemp(void) { if (value >= MAX_TEMP_F) { value = 0; // jump to off } - setSettingValue(SettingsOptions::BoostTemp, value); - return value >= (MAX_TEMP_F - 10); - } - if (value == 0) { - value = MIN_BOOST_TEMP_C; // loop back at 250 } else { - value += 10; // Go up 10C at a time - } - if (value > MAX_TEMP_C) { - value = 0; // Go to off state + if (value == 0) { + value = MIN_BOOST_TEMP_C; // loop back at 250 + } else { + value += 10; // Go up 10C at a time + } + if (value > MAX_TEMP_C) { + value = 0; // Go to off state + } } setSettingValue(SettingsOptions::BoostTemp, value); - return value >= MAX_TEMP_C; } static void displayBoostTemp(void) { if (getSettingValue(SettingsOptions::BoostTemp)) { OLED::printNumber(getSettingValue(SettingsOptions::BoostTemp), 3, FontStyle::LARGE); } else { - OLED::print(translatedString(Tr->OffString), FontStyle::LARGE); + OLED::drawUnavailableIcon(); } } static void displayAutomaticStartMode(void) { switch (getSettingValue(SettingsOptions::AutoStartMode)) { case autoStartMode_t::NO: - OLED::print(translatedString(Tr->SettingStartNoneChar), FontStyle::LARGE); + OLED::drawUnavailableIcon(); break; case autoStartMode_t::SOLDER: OLED::print(translatedString(Tr->SettingStartSolderingChar), FontStyle::LARGE); @@ -588,7 +618,7 @@ static void displayAutomaticStartMode(void) { OLED::print(translatedString(Tr->SettingStartSleepOffChar), FontStyle::LARGE); break; default: - OLED::print(translatedString(Tr->SettingStartNoneChar), FontStyle::LARGE); + OLED::drawUnavailableIcon(); break; } } @@ -599,17 +629,17 @@ static void displayTempChangeLongStep(void) { OLED::printNumber(getSettingValue( static void displayLockingMode(void) { switch (getSettingValue(SettingsOptions::LockingMode)) { - case 0: - OLED::print(translatedString(Tr->SettingLockDisableChar), FontStyle::LARGE); + case lockingMode_t::DISABLED: + OLED::drawUnavailableIcon(); break; - case 1: + case lockingMode_t::BOOST: OLED::print(translatedString(Tr->SettingLockBoostChar), FontStyle::LARGE); break; - case 2: + case lockingMode_t::FULL: OLED::print(translatedString(Tr->SettingLockFullChar), FontStyle::LARGE); break; default: - OLED::print(translatedString(Tr->SettingLockDisableChar), FontStyle::LARGE); + OLED::drawUnavailableIcon(); break; } } @@ -618,7 +648,7 @@ static void displayLockingMode(void) { static void displayProfilePhases(void) { OLED::printNumber(getSettingValue(SettingsOptions::ProfilePhases), 1, FontStyle::LARGE); } -static bool setProfileTemp(const enum SettingsOptions option) { +static void setProfileTemp(const enum SettingsOptions option) { // If in C, 5 deg, if in F 10 deg uint16_t temp = getSettingValue(option); if (getSettingValue(SettingsOptions::TemperatureInF)) { @@ -626,24 +656,21 @@ static bool setProfileTemp(const enum SettingsOptions option) { if (temp > MAX_TEMP_F) { temp = MIN_TEMP_F; } - setSettingValue(option, temp); - return temp == MAX_TEMP_F; } else { temp += 5; if (temp > MAX_TEMP_C) { temp = MIN_TEMP_C; } - setSettingValue(option, temp); - return temp == MAX_TEMP_C; } + setSettingValue(option, temp); } -static bool setProfilePreheatTemp(void) { return setProfileTemp(SettingsOptions::ProfilePreheatTemp); } -static bool setProfilePhase1Temp(void) { return setProfileTemp(SettingsOptions::ProfilePhase1Temp); } -static bool setProfilePhase2Temp(void) { return setProfileTemp(SettingsOptions::ProfilePhase2Temp); } -static bool setProfilePhase3Temp(void) { return setProfileTemp(SettingsOptions::ProfilePhase3Temp); } -static bool setProfilePhase4Temp(void) { return setProfileTemp(SettingsOptions::ProfilePhase4Temp); } -static bool setProfilePhase5Temp(void) { return setProfileTemp(SettingsOptions::ProfilePhase5Temp); } +static void setProfilePreheatTemp(void) { return setProfileTemp(SettingsOptions::ProfilePreheatTemp); } +static void setProfilePhase1Temp(void) { return setProfileTemp(SettingsOptions::ProfilePhase1Temp); } +static void setProfilePhase2Temp(void) { return setProfileTemp(SettingsOptions::ProfilePhase2Temp); } +static void setProfilePhase3Temp(void) { return setProfileTemp(SettingsOptions::ProfilePhase3Temp); } +static void setProfilePhase4Temp(void) { return setProfileTemp(SettingsOptions::ProfilePhase4Temp); } +static void setProfilePhase5Temp(void) { return setProfileTemp(SettingsOptions::ProfilePhase5Temp); } static void displayProfilePreheatTemp(void) { OLED::printNumber(getSettingValue(SettingsOptions::ProfilePreheatTemp), 3, FontStyle::LARGE); } static void displayProfilePhase1Temp(void) { OLED::printNumber(getSettingValue(SettingsOptions::ProfilePhase1Temp), 3, FontStyle::LARGE); } @@ -667,12 +694,18 @@ static bool showProfilePhase5Options(void) { return getSettingValue(SettingsOpti #endif /* PROFILE_SUPPORT */ -static void displaySensitivity(void) { OLED::printNumber(getSettingValue(SettingsOptions::Sensitivity), 1, FontStyle::LARGE, false); } +static void displaySensitivity(void) { + if (getSettingValue(SettingsOptions::Sensitivity)) { + OLED::printNumber(getSettingValue(SettingsOptions::Sensitivity), 1, FontStyle::LARGE, false); + } else { + OLED::drawUnavailableIcon(); + } +} static bool showSleepOptions(void) { return getSettingValue(SettingsOptions::Sensitivity) > 0; } #ifndef NO_SLEEP_MODE -static bool setSleepTemp(void) { +static void setSleepTemp(void) { // If in C, 10 deg, if in F 20 deg uint16_t temp = getSettingValue(SettingsOptions::SleepTemp); if (getSettingValue(SettingsOptions::TemperatureInF)) { @@ -680,23 +713,20 @@ static bool setSleepTemp(void) { if (temp > 580) { temp = 60; } - setSettingValue(SettingsOptions::SleepTemp, temp); - return temp == 580; } else { temp += 10; if (temp > 300) { temp = 10; } - setSettingValue(SettingsOptions::SleepTemp, temp); - return temp == 300; } + setSettingValue(SettingsOptions::SleepTemp, temp); } static void displaySleepTemp(void) { OLED::printNumber(getSettingValue(SettingsOptions::SleepTemp), 3, FontStyle::LARGE); } static void displaySleepTime(void) { if (getSettingValue(SettingsOptions::SleepTime) == 0) { - OLED::print(translatedString(Tr->OffString), FontStyle::LARGE); + OLED::drawUnavailableIcon(); } else if (getSettingValue(SettingsOptions::SleepTime) < 6) { OLED::printNumber(getSettingValue(SettingsOptions::SleepTime) * 10, 2, FontStyle::LARGE); OLED::print(LargeSymbolSeconds, FontStyle::LARGE); @@ -710,7 +740,7 @@ static void displaySleepTime(void) { static void displayShutdownTime(void) { if (getSettingValue(SettingsOptions::ShutdownTime) == 0) { - OLED::print(translatedString(Tr->OffString), FontStyle::LARGE); + OLED::drawUnavailableIcon(); } else { OLED::printNumber(getSettingValue(SettingsOptions::ShutdownTime), 2, FontStyle::LARGE); OLED::print(LargeSymbolMinutes, FontStyle::LARGE); @@ -718,10 +748,34 @@ static void displayShutdownTime(void) { } #ifdef HALL_SENSOR -static void displayHallEffect(void) { OLED::printNumber(getSettingValue(SettingsOptions::HallEffectSensitivity), 1, FontStyle::LARGE, false); } +static void displayHallEffect(void) { + if (getSettingValue(SettingsOptions::HallEffectSensitivity)) { + OLED::printNumber(getSettingValue(SettingsOptions::HallEffectSensitivity), 1, FontStyle::LARGE, false); + } else { + OLED::drawUnavailableIcon(); + } +} static bool showHallEffect(void) { return getHallSensorFitted(); } +static void displayHallEffectSleepTime(void) { + if (getSettingValue(SettingsOptions::HallEffectSleepTime)) { + OLED::printNumber(getSettingValue(SettingsOptions::HallEffectSleepTime) * 5, 2, FontStyle::LARGE, false); + } else { + // When sleep time is set to zero, we sleep for 1 second anyways. This is the default. + OLED::printNumber(1, 2, FontStyle::LARGE, false); + } + OLED::print(LargeSymbolSeconds, FontStyle::LARGE); +} #endif /* HALL_SENSOR */ +#ifdef TIP_TYPE_SUPPORT +static void displaySolderingTipType(void) { + // TODO wrapping X value + OLED::print(lookupTipName(), FontStyle::SMALL, 255, OLED::getCursorX()); +} +// If there is no detection, and no options, max is 0 +static bool showSolderingTipType(void) { return tipType_t::TIP_TYPE_MAX != 0; } +#endif /* TIP_TYPE_SUPPORT */ + static void setTempF(const enum SettingsOptions option) { uint16_t Temp = getSettingValue(option); if (getSettingValue(SettingsOptions::TemperatureInF)) { @@ -739,8 +793,8 @@ static void setTempF(const enum SettingsOptions option) { setSettingValue(option, Temp); } -static bool setTempF(void) { - bool res = nextSettingValue(SettingsOptions::TemperatureInF); +static void setTempF(void) { + nextSettingValue(SettingsOptions::TemperatureInF); setTempF(SettingsOptions::BoostTemp); setTempF(SettingsOptions::SolderingTemp); #ifndef NO_SLEEP_MODE @@ -754,15 +808,14 @@ static bool setTempF(void) { setTempF(SettingsOptions::ProfilePhase4Temp); setTempF(SettingsOptions::ProfilePhase5Temp); #endif /* PROFILE_SUPPORT */ - return res; } static void displayTempF(void) { OLED::printSymbolDeg(FontStyle::LARGE); } #ifndef NO_DISPLAY_ROTATE -static bool setDisplayRotation(void) { - bool res = nextSettingValue(SettingsOptions::OrientationMode); +static void setDisplayRotation(void) { + nextSettingValue(SettingsOptions::OrientationMode); switch (getSettingValue(SettingsOptions::OrientationMode)) { case orientationMode_t::RIGHT: OLED::setRotation(false); @@ -776,7 +829,6 @@ static bool setDisplayRotation(void) { default: break; } - return res; } static void displayDisplayRotation(void) { @@ -804,6 +856,8 @@ static void displayScrollSpeed(void) { OLED::print(translatedString((getSettingV static void displayReverseButtonTempChangeEnabled(void) { OLED::drawCheckbox(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled)); } +static void displayReverseButtonSettings(void) { OLED::drawCheckbox(getSettingValue(SettingsOptions::ReverseButtonSettings)); } + static void displayAnimationSpeed(void) { switch (getSettingValue(SettingsOptions::AnimationSpeed)) { case settingOffSpeed_t::SLOW: @@ -816,7 +870,7 @@ static void displayAnimationSpeed(void) { OLED::print(translatedString(Tr->SettingFastChar), FontStyle::LARGE); break; default: - OLED::print(translatedString(Tr->SettingOffChar), FontStyle::LARGE); + OLED::drawUnavailableIcon(); break; } } @@ -826,24 +880,31 @@ static void displayAnimationLoop(void) { OLED::drawCheckbox(getSettingValue(Sett static void displayBrightnessLevel(void) { OLED::printNumber((getSettingValue(SettingsOptions::OLEDBrightness) / BRIGHTNESS_STEP + 1), 1, FontStyle::LARGE); - // While not optimal to apply this here, it is _very_ convienient + // While not optimal to apply this here, it is _very_ convenient OLED::setBrightness(getSettingValue(SettingsOptions::OLEDBrightness)); } static void displayInvertColor(void) { OLED::drawCheckbox(getSettingValue(SettingsOptions::OLEDInversion)); - // While not optimal to apply this here, it is _very_ convienient + // While not optimal to apply this here, it is _very_ convenient OLED::setInverseDisplay(getSettingValue(SettingsOptions::OLEDInversion)); } static void displayLogoTime(void) { - if (getSettingValue(SettingsOptions::LOGOTime) == 0) { - OLED::print(translatedString(Tr->OffString), FontStyle::LARGE); - } else if (getSettingValue(SettingsOptions::LOGOTime) == 5) { - OLED::drawArea(OLED_WIDTH - 24 - 2, 0, 24, 16, infinityIcon); - } else { - OLED::printNumber(getSettingValue(SettingsOptions::LOGOTime), 2, FontStyle::LARGE); + switch (getSettingValue(SettingsOptions::LOGOTime)) { + case logoMode_t::SKIP: + OLED::drawUnavailableIcon(); + break; + case logoMode_t::ONETIME: + OLED::drawArea(OLED_WIDTH - OLED_HEIGHT - 2, 0, OLED_HEIGHT, OLED_HEIGHT, RepeatOnce); + break; + case logoMode_t::INFINITY: + OLED::drawArea(OLED_WIDTH - OLED_HEIGHT - 2, 0, OLED_HEIGHT, OLED_HEIGHT, RepeatInf); + break; + default: + OLED::printNumber(getSettingValue(SettingsOptions::LOGOTime), 1, FontStyle::LARGE); OLED::print(LargeSymbolSeconds, FontStyle::LARGE); + break; } } @@ -857,14 +918,14 @@ static void displayBluetoothLE(void) { OLED::drawCheckbox(getSettingValue(Settin static void displayPowerLimit(void) { if (getSettingValue(SettingsOptions::PowerLimit) == 0) { - OLED::print(translatedString(Tr->OffString), FontStyle::LARGE); + OLED::drawUnavailableIcon(); } else { OLED::printNumber(getSettingValue(SettingsOptions::PowerLimit), 3, FontStyle::LARGE); OLED::print(LargeSymbolWatts, FontStyle::LARGE); } } -static bool setCalibrate(void) { +static void setCalibrate(void) { if (getSettingValue(SettingsOptions::CalibrateCJC) < 1) { if (userConfirmation(translatedString(Tr->SettingsCalibrationWarning))) { // User confirmed @@ -874,12 +935,11 @@ static bool setCalibrate(void) { } else { setSettingValue(SettingsOptions::CalibrateCJC, 0); } - return false; } static void displayCalibrate(void) { OLED::drawCheckbox(getSettingValue(SettingsOptions::CalibrateCJC)); } -static bool setCalibrateVIN(void) { +static void setCalibrateVIN(void) { // Jump to the voltage calibration subscreen OLED::clearScreen(); @@ -906,10 +966,10 @@ static bool setCalibrateVIN(void) { saveSettings(); OLED::clearScreen(); OLED::setCursor(0, 0); - warnUser(translatedString(Tr->CalibrationDone), 3 * TICKS_SECOND); + warnUser(translatedString(Tr->CalibrationDone), getButtonState()); OLED::refresh(); waitForButtonPressOrTimeout(0.5 * TICKS_SECOND); - return false; + return; case BUTTON_NONE: default: break; @@ -918,18 +978,15 @@ static bool setCalibrateVIN(void) { OLED::refresh(); osDelay(40); } - return false; } -static void displayCalibrateVIN(void) {} - static void displayPowerPulse(void) { if (getSettingValue(SettingsOptions::KeepAwakePulse)) { OLED::printNumber(getSettingValue(SettingsOptions::KeepAwakePulse) / 10, 1, FontStyle::LARGE); OLED::print(LargeSymbolDot, FontStyle::LARGE); OLED::printNumber(getSettingValue(SettingsOptions::KeepAwakePulse) % 10, 1, FontStyle::LARGE); } else { - OLED::print(translatedString(Tr->OffString), FontStyle::LARGE); + OLED::drawUnavailableIcon(); } } @@ -939,17 +996,19 @@ static void displayPowerPulseWait(void) { OLED::printNumber(getSettingValue(Sett static void displayPowerPulseDuration(void) { OLED::printNumber(getSettingValue(SettingsOptions::KeepAwakePulseDuration), 1, FontStyle::LARGE); } -static bool setResetSettings(void) { +static void setResetSettings(void) { if (userConfirmation(translatedString(Tr->SettingsResetWarning))) { resetSettings(); - warnUser(translatedString(Tr->ResetOKMessage), 3 * TICKS_SECOND); + OLED::clearScreen(); + while (!warnUser(translatedString(Tr->ResetOKMessage), getButtonState())) { + OLED::refresh(); + vTaskDelay(TICKS_100MS); + OLED::clearScreen(); + } reboot(); } - return false; } -static void displayResetSettings(void) {} - // Indicates whether a menu transition is in progress, so that the menu icon // animation is paused during the transition. static bool animOpenState = false; @@ -992,248 +1051,19 @@ static void displayMenu(size_t index) { // Draw symbol // 16 pixel wide image // less 2 pixel wide scrolling indicator - OLED::drawArea(OLED_WIDTH - 16 - 2, 0, 16, 16, (&SettingsMenuIcons[index][(16 * 2) * currentFrame])); + + OLED::drawArea(OLED_WIDTH - SETTINGS_ICON_WIDTH - 2, 0, SETTINGS_ICON_WIDTH, SETTINGS_ICON_HEIGHT, (&SettingsMenuIcons[index][(SETTINGS_ICON_WIDTH * (SETTINGS_ICON_HEIGHT / 8)) * currentFrame])); } -#if defined(POW_DC) || defined(POW_QC) +#if defined(POW_DC) || defined(POW_QC) || defined(POW_PD) static void displayPowerMenu(void) { displayMenu(0); } -static bool enterPowerMenu(void) { - gui_Menu(powerMenu); - return false; -} + #endif /* POW_DC or POW_QC */ static void displaySolderingMenu(void) { displayMenu(1); } -static bool enterSolderingMenu(void) { - gui_Menu(solderingMenu); - return false; -} static void displayPowerSavingMenu(void) { displayMenu(2); } -static bool enterPowerSavingMenu(void) { - gui_Menu(PowerSavingMenu); - return false; -} static void displayUIMenu(void) { displayMenu(3); } -static bool enterUIMenu(void) { - gui_Menu(HasFahrenheit ? UIMenu : UIMenu + 1); - return false; -} static void displayAdvancedMenu(void) { displayMenu(4); } -static bool enterAdvancedMenu(void) { - gui_Menu(advancedMenu); - return false; -} - -uint8_t gui_getMenuLength(const menuitem *menu) { - uint8_t scrollContentSize = 0; - for (uint8_t i = 0; menu[i].draw != nullptr; i++) { - if (menu[i].isVisible == nullptr) { - scrollContentSize += 1; // Always visible - } else if (menu[i].isVisible()) { - scrollContentSize += 1; // Selectively visible and chosen to show - } - } - return scrollContentSize; -} - -void gui_Menu(const menuitem *menu) { - // Draw the settings menu and provide iteration support etc - - // This is used to detect whether a menu-exit transition should be played. - static bool wasInGuiMenu; - wasInGuiMenu = true; - - enum class NavState { - Idle, - Entering, - ScrollingDown, - Exiting, - }; - - uint8_t currentScreen = 0; // Current screen index in the menu struct - uint8_t screensSkipped = 0; // Number of screens skipped due to being disabled - TickType_t autoRepeatTimer = 0; - TickType_t autoRepeatAcceleration = 0; - bool earlyExit = false; - bool lcdRefresh = true; - - ButtonState lastButtonState = BUTTON_NONE; - uint8_t scrollContentSize = gui_getMenuLength(menu); - - bool scrollBlink = false; - bool lastValue = false; - NavState navState = NavState::Entering; - - ScrollMessage scrollMessage; - - while ((menu[currentScreen].draw != nullptr) && earlyExit == false) { - bool valueChanged = false; - // Handle menu transition: - if (navState != NavState::Idle) { - // Check if this menu item shall be skipped. If it shall be skipped, - // `draw()` returns true. Draw on the secondary framebuffer as we want - // to keep the primary framebuffer intact for the upcoming transition - // animation. - OLED::useSecondaryFramebuffer(true); - if (menu[currentScreen].isVisible != nullptr) { - if (!menu[currentScreen].isVisible()) { - currentScreen++; - screensSkipped++; - OLED::useSecondaryFramebuffer(false); - continue; - } - } - - animOpenState = true; - // The menu entering/exiting transition uses the secondary framebuffer, - // but the scroll down transition does not. - OLED::setCursor(0, 0); - OLED::clearScreen(); - if (menu[currentScreen].shortDescriptionSize > 0) { - printShortDescription(menu[currentScreen].shortDescriptionIndex, menu[currentScreen].shortDescriptionSize); - } - menu[currentScreen].draw(); - if (navState == NavState::ScrollingDown) { - // Play the scroll down animation. - OLED::maskScrollIndicatorOnOLED(); - OLED::transitionScrollDown(); - OLED::useSecondaryFramebuffer(false); - } else { - // The menu was drawn in a secondary framebuffer. - // Now we play a transition from the pre-drawn primary - // framebuffer to the new buffer. - // The extra buffer is discarded at the end of the transition. - OLED::useSecondaryFramebuffer(false); - OLED::transitionSecondaryFramebuffer(navState == NavState::Entering); - } - animOpenState = false; - navState = NavState::Idle; - } - - // If the user has hesitated for >=3 seconds, show the long text - // Otherwise "draw" the option - if ((xTaskGetTickCount() - lastButtonTime < (TICKS_SECOND * 3)) || menu[currentScreen].description == 0) { - lcdRefresh = true; - OLED::setCursor(0, 0); - OLED::clearScreen(); - if (menu[currentScreen].shortDescriptionSize > 0) { - printShortDescription(menu[currentScreen].shortDescriptionIndex, menu[currentScreen].shortDescriptionSize); - } - menu[currentScreen].draw(); - uint8_t indicatorHeight = OLED_HEIGHT / scrollContentSize; - uint8_t position = OLED_HEIGHT * (currentScreen - screensSkipped) / scrollContentSize; - if (lastValue) { - scrollBlink = !scrollBlink; - } - if (!lastValue || !scrollBlink) { - OLED::drawScrollIndicator(position, indicatorHeight); - } - } else { - // Draw description - const char *description = translatedString(Tr->SettingsDescriptions[menu[currentScreen].description - 1]); - lcdRefresh |= scrollMessage.drawUpdate(description, xTaskGetTickCount()); - } - - if (lcdRefresh) { - OLED::refresh(); // update the LCD - osDelay(40); - lcdRefresh = false; - } - - ButtonState buttons = getButtonState(); - - if (buttons != lastButtonState) { - autoRepeatAcceleration = 0; - lastButtonState = buttons; - } - - auto callIncrementHandler = [&]() { - wasInGuiMenu = false; - valueChanged = true; - bool res = false; - if ((int)menu[currentScreen].autoSettingOption < (int)SettingsOptions::SettingsOptionsLength) { - res = nextSettingValue(menu[currentScreen].autoSettingOption); - } else if (menu[currentScreen].incrementHandler != nullptr) { - res = menu[currentScreen].incrementHandler(); - } else { - earlyExit = true; - } - if (wasInGuiMenu) { - navState = NavState::Exiting; - } - wasInGuiMenu = true; - return res; - }; - - switch (buttons) { - case BUTTON_BOTH: - earlyExit = true; // will make us exit next loop - scrollMessage.reset(); - break; - case BUTTON_F_SHORT: - // increment - if (scrollMessage.isReset()) { - lastValue = callIncrementHandler(); - } else { - scrollMessage.reset(); - } - break; - case BUTTON_B_SHORT: - if (scrollMessage.isReset()) { - currentScreen++; - navState = NavState::ScrollingDown; - lastValue = false; - } else { - scrollMessage.reset(); - } - break; - case BUTTON_F_LONG: - if (xTaskGetTickCount() + autoRepeatAcceleration > autoRepeatTimer + PRESS_ACCEL_INTERVAL_MAX) { - if ((lastValue = callIncrementHandler())) { - autoRepeatTimer = 1000; - } else { - autoRepeatTimer = 0; - } - autoRepeatTimer += xTaskGetTickCount(); - scrollMessage.reset(); - autoRepeatAcceleration += PRESS_ACCEL_STEP; - } - break; - case BUTTON_B_LONG: - if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration > PRESS_ACCEL_INTERVAL_MAX) { - currentScreen++; - navState = NavState::ScrollingDown; - autoRepeatTimer = xTaskGetTickCount(); - scrollMessage.reset(); - autoRepeatAcceleration += PRESS_ACCEL_STEP; - } - break; - case BUTTON_NONE: - default: - break; - } - - if ((PRESS_ACCEL_INTERVAL_MAX - autoRepeatAcceleration) < PRESS_ACCEL_INTERVAL_MIN) { - autoRepeatAcceleration = PRESS_ACCEL_INTERVAL_MAX - PRESS_ACCEL_INTERVAL_MIN; - } - - if ((xTaskGetTickCount() - lastButtonTime) > (TICKS_SECOND * 2 * 60)) { - // If user has not pressed any buttons in 30 seconds, exit back a menu layer - // This will trickle the user back to the main screen eventually - earlyExit = true; - scrollMessage.reset(); - } - if (valueChanged) { - // If user changed value, update the scroll content size - scrollContentSize = gui_getMenuLength(menu); - } - } -} - -void enterSettingsMenu() { - gui_Menu(rootSettingsMenu); // Call the root menu - saveSettings(); -} diff --git a/source/Core/Src/syscalls.c b/source/Core/Src/syscalls.c index b1cefd18e..8d8557ca1 100644 --- a/source/Core/Src/syscalls.c +++ b/source/Core/Src/syscalls.c @@ -11,4 +11,14 @@ /* Functions */ void initialise_monitor_handles() {} +/* Syscalls (stub implementations to avoid compile warnings and possibe future problems) */ int _getpid(void) { return 1; } + +#if defined(MODEL_Pinecil) || defined(MODEL_Pinecilv2) +// do nothing here because some stubs and real implementations added for Pinecils already +#else +off_t _lseek(int fd, off_t ptr, int dir) { return -1; } +ssize_t _read(int fd, void *ptr, size_t len) { return -1; } +ssize_t _write(int fd, const void *ptr, size_t len) { return -1; } +int _close(int fd) { return -1; } +#endif diff --git a/source/Core/Threads/GUIRendering.md b/source/Core/Threads/GUIRendering.md new file mode 100644 index 000000000..8f6fcee18 --- /dev/null +++ b/source/Core/Threads/GUIRendering.md @@ -0,0 +1,40 @@ +# GUI Rendering + +The GUI aims to be somewhat similar to immediate mode rendering, where the screen is re-rendered each sweep. +This is due to a few aims: + +1. Functions should try and contain their state to the context struct (helps keep state usage flatter) +2. Allows external events to change the state +3. Means state can be read/write over BLE or other external control interfaces + +## Transitions + +When changing the view to a new view it can be preferable to transition using an animation. +The tooling provides for left, right and down animations at this point. +The use of these gives a notion of "direction" when navigating the menu. + +``` + ┌───────────┐ + │ Debug Menu│ + └─────┬─────┘ + │ + │ + │ +┌──────────────┐ ┌────┴─────┐ ┌──────────────────┐ ┌─────────────────┐ +│Soldering Mode│ │ │ │ │ │ │ +│ OR ├───────────┤Home Menu ├───────────┤Settings Main Menu├───────────┤Settings sub menu│ +│Reflow Mode│ │ │ │ │ │ │ +└──────────────┘ └──────────┘ └──────────────────┘ └─────────┬───────┘ + │ + ┌─────────┴───────┐ + │ │ + │Settings sub menu│ + │ │ + └─────────────────┘ +``` + +The downside of supporting transitions is that for these to work, the code should render the screen _first_ then return the new state. +This ensures there is a good working copy in the buffer before the transition changes the view. + +The code that handles the dispatch will run a new render pass again to get the new buffer contents and then transition between the two for you. +At the moment scrolling "Up" isn't implemented but the enumeration is there so that its implementation can follow. diff --git a/source/Core/Threads/GUIThread.cpp b/source/Core/Threads/GUIThread.cpp index 56dc6574c..d3d225e53 100644 --- a/source/Core/Threads/GUIThread.cpp +++ b/source/Core/Threads/GUIThread.cpp @@ -26,13 +26,190 @@ extern "C" { #include "settingsGUI.hpp" #include "stdlib.h" #include "string.h" +#include "ui_drawing.hpp" #ifdef POW_PD #include "USBPD.h" #include "pd.h" #endif + // File local variables +#define MOVEMENT_INACTIVITY_TIME (60 * configTICK_RATE_HZ) +#define BUTTON_INACTIVITY_TIME (60 * configTICK_RATE_HZ) + +ButtonState buttonsAtDeviceBoot; // We record button state at startup, incase of jumping to debug modes +OperatingMode currentOperatingMode = OperatingMode::InitialisationDone; // Current mode we are rendering +guiContext context; // Context passed to functions to aid in state during render passes + +OperatingMode handle_post_init_state(); +OperatingMode guiHandleDraw(void) { + OLED::clearScreen(); // Clear ready for render pass + // Read button state + ButtonState buttons = getButtonState(); + // Enforce screen on if buttons pressed, movement, hot tip etc + if (buttons != BUTTON_NONE) { + OLED::setDisplayState(OLED::DisplayState::ON); + } else { + // Buttons are none; check if we can sleep display + uint32_t tipTemp = TipThermoModel::getTipInC(); + if ((tipTemp < 50) && getSettingValue(SettingsOptions::Sensitivity) && + (((xTaskGetTickCount() - lastMovementTime) > MOVEMENT_INACTIVITY_TIME) && ((xTaskGetTickCount() - lastButtonTime) > BUTTON_INACTIVITY_TIME))) { + OLED::setDisplayState(OLED::DisplayState::OFF); + setStatusLED(LED_OFF); + } else { + OLED::setDisplayState(OLED::DisplayState::ON); + } + if (currentOperatingMode != OperatingMode::Soldering && currentOperatingMode != OperatingMode::SolderingProfile) { + // Not in soldering mode, so set this based on temp + if (tipTemp > 55) { + setStatusLED(LED_COOLING_STILL_HOT); + } else { + setStatusLED(LED_STANDBY); + } + } + } + // Dispatch button state to gui mode + OperatingMode newMode = currentOperatingMode; + switch (currentOperatingMode) { + case OperatingMode::StartupWarnings: + newMode = showWarnings(buttons, &context); + break; + case OperatingMode::UsbPDDebug: +#ifdef HAS_POWER_DEBUG_MENU + newMode = showPDDebug(buttons, &context); + break; +#else + newMode = OperatingMode::InitialisationDone; +#endif + case OperatingMode::StartupLogo: + showBootLogo(); + + if (getSettingValue(SettingsOptions::AutoStartMode) == autoStartMode_t::SLEEP) { + lastMovementTime = lastButtonTime = 0; // We mask the values so that sleep goes until user moves again or presses a button + newMode = OperatingMode::Sleeping; + } else if (getSettingValue(SettingsOptions::AutoStartMode) == autoStartMode_t::SOLDER) { + lastMovementTime = lastButtonTime = xTaskGetTickCount(); // Move forward so we dont go to sleep + newMode = OperatingMode::Soldering; + } else if (getSettingValue(SettingsOptions::AutoStartMode) == autoStartMode_t::ZERO) { + lastMovementTime = lastButtonTime = 0; // We mask the values so that sleep goes until user moves again or presses a button + newMode = OperatingMode::Hibernating; + } else { + newMode = OperatingMode::HomeScreen; + } + + break; + default: + /* Fallthrough */ + case OperatingMode::HomeScreen: + newMode = drawHomeScreen(buttons, &context); + break; + case OperatingMode::Soldering: + context.scratch_state.state4 = 0; + newMode = gui_solderingMode(buttons, &context); + break; + case OperatingMode::SolderingProfile: + newMode = gui_solderingProfileMode(buttons, &context); + break; + case OperatingMode::Sleeping: + newMode = gui_SolderingSleepingMode(buttons, &context); + break; + case OperatingMode::TemperatureAdjust: + newMode = gui_solderingTempAdjust(buttons, &context); + break; + case OperatingMode::DebugMenuReadout: + newMode = showDebugMenu(buttons, &context); + break; + case OperatingMode::CJCCalibration: + newMode = performCJCC(buttons, &context); + break; + case OperatingMode::SettingsMenu: + newMode = gui_SettingsMenu(buttons, &context); + break; + case OperatingMode::InitialisationDone: + newMode = handle_post_init_state(); + break; + case OperatingMode::Hibernating: + context.scratch_state.state4 = 1; + gui_SolderingSleepingMode(buttons, &context); + if (lastButtonTime > 0 || lastMovementTime > 0) { + newMode = OperatingMode::Soldering; + } + break; + case OperatingMode::ThermalRunaway: + /*TODO*/ + newMode = OperatingMode::HomeScreen; + break; + }; + return newMode; +} +void guiRenderLoop(void) { + OperatingMode newMode = guiHandleDraw(); // This does the screen drawing + + // Post draw we handle any state transitions + + if (newMode != currentOperatingMode) { + context.viewEnterTime = xTaskGetTickCount(); + context.previousMode = currentOperatingMode; + // If the previous mode is the startup logo; we dont want to return to it, but instead dispatch out to either home or soldering + if (currentOperatingMode == OperatingMode::StartupLogo) { + if (getSettingValue(SettingsOptions::AutoStartMode)) { + context.previousMode = OperatingMode::Soldering; + } else { + newMode = OperatingMode::HomeScreen; + } + } + memset(&context.scratch_state, 0, sizeof(context.scratch_state)); + currentOperatingMode = newMode; + } + + // If the transition marker is set, we need to make the next draw occur to the secondary buffer so we have something to transition to + if (context.transitionMode != TransitionAnimation::None) { + OLED::useSecondaryFramebuffer(true); + // Now we need to fill the secondary buffer with the _next_ frame to transistion to + guiHandleDraw(); + OLED::useSecondaryFramebuffer(false); + // Now dispatch the transition + switch (context.transitionMode) { + case TransitionAnimation::Down: + OLED::transitionScrollDown(context.viewEnterTime); + break; + case TransitionAnimation::Left: + OLED::transitionSecondaryFramebuffer(false, context.viewEnterTime); + break; + case TransitionAnimation::Right: + OLED::transitionSecondaryFramebuffer(true, context.viewEnterTime); + break; + case TransitionAnimation::Up: + OLED::transitionScrollUp(context.viewEnterTime); + + case TransitionAnimation::None: + default: + break; // Do nothing on unknown + } + + context.transitionMode = TransitionAnimation::None; // Clear transition flag + } + // Render done, draw it out + OLED::refresh(); +} -extern bool heaterThermalRunaway; +OperatingMode handle_post_init_state() { +#ifdef HAS_POWER_DEBUG_MENU +#ifdef DEBUG_POWER_MENU_BUTTON_B + if (buttonsAtDeviceBoot == BUTTON_B_LONG || buttonsAtDeviceBoot == BUTTON_B_SHORT) { +#else + if (buttonsAtDeviceBoot == BUTTON_F_LONG || buttonsAtDeviceBoot == BUTTON_F_SHORT) { +#endif + buttonsAtDeviceBoot = BUTTON_NONE; + return OperatingMode::UsbPDDebug; + } +#endif + + if (getSettingValue(SettingsOptions::CalibrateCJC) > 0) { + return OperatingMode::CJCCalibration; + } + + return OperatingMode::StartupWarnings; +} /* StartGUITask function */ void startGUITask(void const *argument) { @@ -44,45 +221,24 @@ void startGUITask(void const *argument) { OLED::setInverseDisplay(getSettingValue(SettingsOptions::OLEDInversion)); bool buttonLockout = false; - renderHomeScreenAssets(); + ui_pre_render_assets(); getTipRawTemp(1); // reset filter + memset(&context, 0, sizeof(context)); OLED::setRotation(getSettingValue(SettingsOptions::OrientationMode) & 1); - // If the front button is held down, on supported devices, show PD debugging metrics -#ifdef HAS_POWER_DEBUG_MENU -#ifdef DEBUG_POWER_MENU_BUTTON_B - if (getButtonB()) { -#else - if (getButtonA()) { -#endif - showPDDebug(); - } -#endif - if (getSettingValue(SettingsOptions::CalibrateCJC) > 0) { - performCJCC(); + // Read boot button state + if (getButtonA()) { + buttonsAtDeviceBoot = BUTTON_F_LONG; } - - // If the boot logo is enabled (but it times out) and the autostart mode is enabled (but not set to sleep w/o heat), start heating during boot logo - if (getSettingValue(SettingsOptions::LOGOTime) > 0 && getSettingValue(SettingsOptions::LOGOTime) < 5 && getSettingValue(SettingsOptions::AutoStartMode) > 0 - && getSettingValue(SettingsOptions::AutoStartMode) < 3) { - uint16_t sleepTempDegC; - if (getSettingValue(SettingsOptions::TemperatureInF)) { - sleepTempDegC = TipThermoModel::convertFtoC(getSettingValue(SettingsOptions::SleepTemp)); - } else { - sleepTempDegC = getSettingValue(SettingsOptions::SleepTemp); - } - // Only heat to sleep temperature (but no higher than 75°C for safety) - currentTempTargetDegC = min(sleepTempDegC, 75); + if (getButtonB()) { + buttonsAtDeviceBoot = BUTTON_B_LONG; } - showBootLogo(); - showWarnings(); - if (getSettingValue(SettingsOptions::AutoStartMode)) { - // jump directly to the autostart mode - gui_solderingMode(getSettingValue(SettingsOptions::AutoStartMode) - 1); - buttonLockout = true; + TickType_t startRender = xTaskGetTickCount(); + for (;;) { + guiRenderLoop(); + resetWatchdog(); + vTaskDelayUntil(&startRender, TICKS_100MS * 4 / 10); // Try and maintain 20-25fps ish update rate, way to fast but if we can its nice } - - drawHomeScreen(buttonLockout); } diff --git a/source/Core/Threads/MOVThread.cpp b/source/Core/Threads/MOVThread.cpp index 2b0188376..9739cd467 100644 --- a/source/Core/Threads/MOVThread.cpp +++ b/source/Core/Threads/MOVThread.cpp @@ -30,8 +30,6 @@ uint8_t accelInit = 0; TickType_t lastMovementTime = 0; // Order matters for probe order, some Acceleromters do NOT like bad reads; and we have a bunch of overlap of addresses void detectAccelerometerVersion() { - DetectedAccelerometerVersion = AccelType::Scanning; - #ifdef ACCEL_MMA if (MMA8652FC::detect()) { if (MMA8652FC::initalize()) { @@ -141,6 +139,12 @@ inline void readAccelerometer(int16_t &tx, int16_t &ty, int16_t &tz, Orientation } } void startMOVTask(void const *argument __unused) { +#ifdef NO_ACCEL + DetectedAccelerometerVersion = AccelType::None; + for (;;) { + osDelay(2 * TICKS_SECOND); + } +#endif osDelay(TICKS_100MS / 5); // This is here as the BMA doesnt start up instantly and can wedge the I2C bus if probed too fast after boot detectAccelerometerVersion(); diff --git a/source/Core/Threads/OperatingModes/CJC.cpp b/source/Core/Threads/OperatingModes/CJC.cpp deleted file mode 100644 index 4da688f96..000000000 --- a/source/Core/Threads/OperatingModes/CJC.cpp +++ /dev/null @@ -1,39 +0,0 @@ - - -#include "OperatingModes.h" -void performCJCC(void) { - // Calibrate Cold Junction Compensation directly at boot, before internal components get warm. - OLED::refresh(); - osDelay(50); - if (!isTipDisconnected() && abs(int(TipThermoModel::getTipInC() - getHandleTemperature(0) / 10)) < 10) { - uint16_t setoffset = 0; - // If the thermo-couple at the end of the tip, and the handle are at - // equilibrium, then the output should be zero, as there is no temperature - // differential. - while (setoffset == 0) { - uint32_t offset = 0; - for (uint8_t i = 0; i < 16; i++) { - offset += getTipRawTemp(1); - // cycle through the filter a fair bit to ensure we're stable. - OLED::clearScreen(); - OLED::setCursor(0, 0); - OLED::print(translatedString(Tr->CJCCalibrating), FontStyle::SMALL); - OLED::setCursor(0, 8); - OLED::print(SmallSymbolDot, FontStyle::SMALL); - for (uint8_t x = 0; x < (i / 4); x++) { - OLED::print(SmallSymbolDot, FontStyle::SMALL); - } - OLED::refresh(); - osDelay(100); - } - setoffset = TipThermoModel::convertTipRawADCTouV(offset / 16, true); - } - setSettingValue(SettingsOptions::CalibrationOffset, setoffset); - OLED::clearScreen(); - warnUser(translatedString(Tr->CalibrationDone), 3 * TICKS_SECOND); - OLED::refresh(); - // Preventing to repeat calibration at boot automatically (only one shot). - setSettingValue(SettingsOptions::CalibrateCJC, 0); - saveSettings(); - } -} diff --git a/source/Core/Threads/OperatingModes/DebugMenu.cpp b/source/Core/Threads/OperatingModes/DebugMenu.cpp deleted file mode 100644 index adf03ddde..000000000 --- a/source/Core/Threads/OperatingModes/DebugMenu.cpp +++ /dev/null @@ -1,111 +0,0 @@ -#include "OperatingModes.h" -extern osThreadId GUITaskHandle; -extern osThreadId MOVTaskHandle; -extern osThreadId PIDTaskHandle; -extern OperatingMode currentMode; - -void showDebugMenu(void) { - currentMode = OperatingMode::debug; - uint8_t screen = 0; - ButtonState b; - for (;;) { - OLED::clearScreen(); // Ensure the buffer starts clean - OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) - OLED::print(SmallSymbolVersionNumber, FontStyle::SMALL); // Print version number - OLED::setCursor(0, 8); // second line - OLED::print(DebugMenu[screen], FontStyle::SMALL); - switch (screen) { - case 0: // Build Date - break; - case 1: // Device ID - { - uint64_t id = getDeviceID(); -#ifdef DEVICE_HAS_VALIDATION_CODE - // If device has validation code; then we want to take over both lines of the screen - OLED::clearScreen(); // Ensure the buffer starts clean - OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) - OLED::print(DebugMenu[screen], FontStyle::SMALL); - OLED::drawHex(getDeviceValidation(), FontStyle::SMALL, 8); - OLED::setCursor(0, 8); // second line -#endif - OLED::drawHex((uint32_t)(id >> 32), FontStyle::SMALL, 8); - OLED::drawHex((uint32_t)(id & 0xFFFFFFFF), FontStyle::SMALL, 8); - } break; - case 2: // ACC Type - OLED::print(AccelTypeNames[(int)DetectedAccelerometerVersion], FontStyle::SMALL); - break; - case 3: // Power Negotiation Status - OLED::print(PowerSourceNames[getPowerSourceNumber()], FontStyle::SMALL); - break; - case 4: // Input Voltage - printVoltage(); - break; - case 5: // Temp in °C - OLED::printNumber(TipThermoModel::getTipInC(), 6, FontStyle::SMALL); - break; - case 6: // Handle Temp in °C - OLED::printNumber(getHandleTemperature(0) / 10, 6, FontStyle::SMALL); - OLED::print(SmallSymbolDot, FontStyle::SMALL); - OLED::printNumber(getHandleTemperature(0) % 10, 1, FontStyle::SMALL); - break; - case 7: // Max Temp Limit in °C - OLED::printNumber(TipThermoModel::getTipMaxInC(), 6, FontStyle::SMALL); - break; - case 8: // System Uptime - OLED::printNumber(xTaskGetTickCount() / TICKS_100MS, 8, FontStyle::SMALL); - break; - case 9: // Movement Timestamp - OLED::printNumber(lastMovementTime / TICKS_100MS, 8, FontStyle::SMALL); - break; - case 10: // Tip Resistance in Ω large to pad over so that we cover ID left overs - OLED::printNumber(getTipResistanceX10() / 10, 6, FontStyle::SMALL); - OLED::print(SmallSymbolDot, FontStyle::SMALL); - OLED::printNumber(getTipResistanceX10() % 10, 1, FontStyle::SMALL); - break; - case 11: // Raw Tip in µV - OLED::printNumber(TipThermoModel::convertTipRawADCTouV(getTipRawTemp(0), true), 8, FontStyle::SMALL); - break; - case 12: // Tip Cold Junction Compensation Offset in µV - OLED::printNumber(getSettingValue(SettingsOptions::CalibrationOffset), 8, FontStyle::SMALL); - break; - case 13: // High Water Mark for GUI - OLED::printNumber(uxTaskGetStackHighWaterMark(GUITaskHandle), 8, FontStyle::SMALL); - break; - case 14: // High Water Mark for Movement Task - OLED::printNumber(uxTaskGetStackHighWaterMark(MOVTaskHandle), 8, FontStyle::SMALL); - break; - case 15: // High Water Mark for PID Task - OLED::printNumber(uxTaskGetStackHighWaterMark(PIDTaskHandle), 8, FontStyle::SMALL); - break; - break; -#ifdef HALL_SENSOR - case 16: // Raw Hall Effect Value - { - int16_t hallEffectStrength = getRawHallEffect(); - if (hallEffectStrength < 0) { - hallEffectStrength = -hallEffectStrength; - } - OLED::printNumber(hallEffectStrength, 6, FontStyle::SMALL); - } break; -#endif - - default: - break; - } - - OLED::refresh(); - b = getButtonState(); - if (b == BUTTON_B_SHORT) { - return; - } else if (b == BUTTON_F_SHORT) { - screen++; -#ifdef HALL_SENSOR - screen = screen % 17; -#else - screen = screen % 16; -#endif - } - - GUIDelay(); - } -} diff --git a/source/Core/Threads/OperatingModes/HomeScreen.cpp b/source/Core/Threads/OperatingModes/HomeScreen.cpp deleted file mode 100644 index 7ac03e9eb..000000000 --- a/source/Core/Threads/OperatingModes/HomeScreen.cpp +++ /dev/null @@ -1,235 +0,0 @@ - -#include "Buttons.hpp" -#include "OperatingModes.h" - -#define MOVEMENT_INACTIVITY_TIME (60 * configTICK_RATE_HZ) -#define BUTTON_INACTIVITY_TIME (60 * configTICK_RATE_HZ) - -uint8_t buttonAF[sizeof(buttonA)]; -uint8_t buttonBF[sizeof(buttonB)]; -uint8_t disconnectedTipF[sizeof(disconnectedTip)]; -extern OperatingMode currentMode; -bool showExitMenuTransition = false; - -void renderHomeScreenAssets(void) { - - // Generate the flipped screen into ram for later use - // flipped is generated by flipping each row - for (int row = 0; row < 2; row++) { - for (int x = 0; x < 42; x++) { - buttonAF[(row * 42) + x] = buttonA[(row * 42) + (41 - x)]; - buttonBF[(row * 42) + x] = buttonB[(row * 42) + (41 - x)]; - disconnectedTipF[(row * 42) + x] = disconnectedTip[(row * 42) + (41 - x)]; - } - } -} - -void handleButtons(bool *buttonLockout) { - ButtonState buttons = getButtonState(); - if (buttons != BUTTON_NONE) { - OLED::setDisplayState(OLED::DisplayState::ON); - } - if (buttons != BUTTON_NONE && *buttonLockout) { - buttons = BUTTON_NONE; - } else { - *buttonLockout = false; - } - switch (buttons) { - case BUTTON_NONE: - // Do nothing - break; - case BUTTON_BOTH: - // Not used yet - // In multi-language this might be used to reset language on a long hold - // or some such - break; - - case BUTTON_B_LONG: - // Show the version information - showDebugMenu(); - break; - case BUTTON_F_LONG: -#ifdef PROFILE_SUPPORT - if (!isTipDisconnected()) { - gui_solderingProfileMode(); // enter profile mode - *buttonLockout = true; - } -#else - gui_solderingTempAdjust(); - saveSettings(); -#endif - break; - case BUTTON_F_SHORT: - if (!isTipDisconnected()) { - gui_solderingMode(0); // enter soldering mode - *buttonLockout = true; - } - break; - case BUTTON_B_SHORT: - currentMode = OperatingMode::settings; - enterSettingsMenu(); // enter the settings menu - { - OLED::useSecondaryFramebuffer(true); - showExitMenuTransition = true; - } - *buttonLockout = true; - break; - default: - break; - } -} - -void drawDetailedHomeScreen(uint32_t tipTemp) { - if (isTipDisconnected()) { - if (OLED::getRotation()) { - // in right handed mode we want to draw over the first part - OLED::drawArea(54, 0, 42, 16, disconnectedTipF); - } else { - OLED::drawArea(0, 0, 42, 16, disconnectedTip); - } - if (OLED::getRotation()) { - OLED::setCursor(-1, 0); - } else { - OLED::setCursor(42, 0); - } - uint32_t Vlt = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0); - OLED::printNumber(Vlt / 10, 2, FontStyle::LARGE); - OLED::print(LargeSymbolDot, FontStyle::LARGE); - OLED::printNumber(Vlt % 10, 1, FontStyle::LARGE); - if (OLED::getRotation()) { - OLED::setCursor(48, 8); - } else { - OLED::setCursor(91, 8); - } - OLED::print(SmallSymbolVolts, FontStyle::SMALL); - } else { - if (!(getSettingValue(SettingsOptions::CoolingTempBlink) && (tipTemp > 55) && (xTaskGetTickCount() % 1000 < 300))) { - // Blink temp if setting enable and temp < 55° - // 1000 tick/sec - // OFF 300ms ON 700ms - gui_drawTipTemp(true, FontStyle::LARGE); // draw in the temp - } - if (OLED::getRotation()) { - OLED::setCursor(6, 0); - } else { - OLED::setCursor(73, 0); // top right - } - // draw set temp - OLED::printNumber(getSettingValue(SettingsOptions::SolderingTemp), 3, FontStyle::SMALL); - - OLED::printSymbolDeg(FontStyle::SMALL); - - if (OLED::getRotation()) { - OLED::setCursor(0, 8); - } else { - OLED::setCursor(67, 8); // bottom right - } - printVoltage(); // draw voltage then symbol (v) - OLED::print(SmallSymbolVolts, FontStyle::SMALL); - } -} -void drawSimplifiedHomeScreen(uint32_t tipTemp) { - bool tempOnDisplay = false; - bool tipDisconnectedDisplay = false; - if (OLED::getRotation()) { - OLED::drawArea(54, 0, 42, 16, buttonAF); - OLED::drawArea(12, 0, 42, 16, buttonBF); - OLED::setCursor(0, 0); - gui_drawBatteryIcon(); - } else { - OLED::drawArea(0, 0, 42, 16, buttonA); // Needs to be flipped so button ends up - OLED::drawArea(42, 0, 42, 16, buttonB); // on right side of screen - OLED::setCursor(84, 0); - gui_drawBatteryIcon(); - } - tipDisconnectedDisplay = false; - if (tipTemp > 55) { - tempOnDisplay = true; - } else if (tipTemp < 45) { - tempOnDisplay = false; - } - if (isTipDisconnected()) { - tempOnDisplay = false; - tipDisconnectedDisplay = true; - } - if (tempOnDisplay || tipDisconnectedDisplay) { - // draw temp over the start soldering button - // Location changes on screen rotation - if (OLED::getRotation()) { - // in right handed mode we want to draw over the first part - OLED::fillArea(55, 0, 41, 16, 0); // clear the area for the temp - OLED::setCursor(56, 0); - } else { - OLED::fillArea(0, 0, 41, 16, 0); // clear the area - OLED::setCursor(0, 0); - } - // If we have a tip connected draw the temp, if not we leave it blank - if (!tipDisconnectedDisplay) { - // draw in the temp - if (!(getSettingValue(SettingsOptions::CoolingTempBlink) && (xTaskGetTickCount() % 1000 < 300))) { - gui_drawTipTemp(false, FontStyle::LARGE); // draw in the temp - } - } else { - // Draw in missing tip symbol - - if (OLED::getRotation()) { - // in right handed mode we want to draw over the first part - OLED::drawArea(54, 0, 42, 16, disconnectedTipF); - } else { - OLED::drawArea(0, 0, 42, 16, disconnectedTip); - } - } - } -} -void drawHomeScreen(bool buttonLockout) { - - for (;;) { - currentMode = OperatingMode::idle; - handleButtons(&buttonLockout); - - currentTempTargetDegC = 0; // ensure tip is off - getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0); - uint32_t tipTemp = TipThermoModel::getTipInC(); - // Preemptively turn the display on. Turn it off if and only if - // the tip temperature is below 50 degrees C *and* motion sleep - // detection is enabled *and* there has been no activity (movement or - // button presses) in a while. - // This is zero cost really as state is only changed on display updates - OLED::setDisplayState(OLED::DisplayState::ON); - - if ((tipTemp < 50) && getSettingValue(SettingsOptions::Sensitivity) - && (((xTaskGetTickCount() - lastMovementTime) > MOVEMENT_INACTIVITY_TIME) && ((xTaskGetTickCount() - lastButtonTime) > BUTTON_INACTIVITY_TIME))) { - OLED::setDisplayState(OLED::DisplayState::OFF); - setStatusLED(LED_OFF); - } else { - OLED::setDisplayState(OLED::DisplayState::ON); - if (tipTemp > 55) { - setStatusLED(LED_COOLING_STILL_HOT); - } else { - setStatusLED(LED_STANDBY); - } - } - - // Clear the lcd buffer - OLED::clearScreen(); - if (OLED::getRotation()) { - OLED::setCursor(50, 0); - } else { - OLED::setCursor(-1, 0); - } - if (getSettingValue(SettingsOptions::DetailedIDLE)) { - drawDetailedHomeScreen(tipTemp); - } else { - drawSimplifiedHomeScreen(tipTemp); - } - - if (showExitMenuTransition) { - OLED::useSecondaryFramebuffer(false); - OLED::transitionSecondaryFramebuffer(false); - showExitMenuTransition = false; - } else { - OLED::refresh(); - GUIDelay(); - } - } -} diff --git a/source/Core/Threads/OperatingModes/OperatingModes.h b/source/Core/Threads/OperatingModes/OperatingModes.h deleted file mode 100644 index c552e327c..000000000 --- a/source/Core/Threads/OperatingModes/OperatingModes.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef OPERATING_MODES_H_ -#define OPERATING_MODES_H_ - -extern "C" { -#include "FreeRTOSConfig.h" -} -#include "Buttons.hpp" -#include "OLED.hpp" -#include "OperatingModeUtilities.h" -#include "Settings.h" -#include "TipThermoModel.h" -#include "Translation.h" -#include "Types.h" -#include "cmsis_os.h" -#include "configuration.h" -#include "history.hpp" -#include "main.hpp" -#include "power.hpp" -#include "settingsGUI.hpp" -#include "stdlib.h" -#include "string.h" -#ifdef POW_PD -#include "USBPD.h" -#include "pd.h" -#endif - -// Exposed modes -enum OperatingMode { - idle = 0, - soldering = 1, - boost = 2, - sleeping = 3, - settings = 4, - debug = 5 -}; - -// Main functions -void performCJCC(void); // Used to calibrate the Cold Junction offset -void gui_solderingTempAdjust(void); // For adjusting the setpoint temperature of the iron -int gui_SolderingSleepingMode(bool stayOff, bool autoStarted); // Sleep mode -void gui_solderingMode(uint8_t jumpToSleep); // Main mode for hot pointy tool -void gui_solderingProfileMode(); // Profile mode for hot likely-not-so-pointy tool -void showDebugMenu(void); // Debugging values -void showPDDebug(void); // Debugging menu that shows PD adaptor info -void showWarnings(void); // Shows user warnings if required -void drawHomeScreen(bool buttonLockout) __attribute__((noreturn)); // IDLE / Home screen -void renderHomeScreenAssets(void); // Called to act as start delay and used to render out flipped images for home screen graphics - -// Common helpers -int8_t getPowerSourceNumber(void); // Returns number ID of power source -TemperatureType_t getTipTemp(void); // Returns temperature of the tip in *C/*F (based on user settings) -#endif diff --git a/source/Core/Threads/OperatingModes/ShowStartupWarnings.cpp b/source/Core/Threads/OperatingModes/ShowStartupWarnings.cpp deleted file mode 100644 index 62ed5d0e8..000000000 --- a/source/Core/Threads/OperatingModes/ShowStartupWarnings.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "HUB238.hpp" -#include "OperatingModes.h" -void showWarnings(void) { - // Display alert if settings were reset - if (settingsWereReset) { - warnUser(translatedString(Tr->SettingsResetMessage), 10 * TICKS_SECOND); - } -#ifdef DEVICE_HAS_VALIDATION_SUPPORT - if (getDeviceValidationStatus()) { - // Warn user this device might be counterfeit - warnUser(translatedString(Tr->DeviceFailedValidationWarning), 10 * TICKS_SECOND); - } -#endif - -#ifndef NO_WARN_MISSING - // We also want to alert if accel or pd is not detected / not responding - // In this case though, we dont want to nag the user _too_ much - // So only show first 2 times - while (DetectedAccelerometerVersion == AccelType::Scanning) { - osDelay(5); - resetWatchdog(); - } - // Display alert if accelerometer is not detected - if (DetectedAccelerometerVersion == AccelType::None) { - if (getSettingValue(SettingsOptions::AccelMissingWarningCounter) < 2) { - nextSettingValue(SettingsOptions::AccelMissingWarningCounter); - saveSettings(); - warnUser(translatedString(Tr->NoAccelerometerMessage), 10 * TICKS_SECOND); - } - } -#ifdef POW_PD - // We expect pd to be present - resetWatchdog(); - if (!USBPowerDelivery::fusbPresent()) { - if (getSettingValue(SettingsOptions::PDMissingWarningCounter) < 2) { - nextSettingValue(SettingsOptions::PDMissingWarningCounter); - saveSettings(); - warnUser(translatedString(Tr->NoPowerDeliveryMessage), 10 * TICKS_SECOND); - } - } -#endif /*POW_PD*/ -#if POW_PD_EXT == 1 - if (!hub238_probe()) { - if (getSettingValue(SettingsOptions::PDMissingWarningCounter) < 2) { - nextSettingValue(SettingsOptions::PDMissingWarningCounter); - saveSettings(); - warnUser(translatedString(Tr->NoPowerDeliveryMessage), 10 * TICKS_SECOND); - } - } -#endif /*POW_PD_EXT==1*/ - // If tip looks to be shorted, yell at user and dont auto dismiss - if (isTipShorted()) { - warnUser(translatedString(Tr->WarningTipShorted), portMAX_DELAY); - } -#endif /*NO_WARN_MISSING*/ -} diff --git a/source/Core/Threads/OperatingModes/Sleep.cpp b/source/Core/Threads/OperatingModes/Sleep.cpp deleted file mode 100644 index 5c3c47e76..000000000 --- a/source/Core/Threads/OperatingModes/Sleep.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "OperatingModes.h" - -extern OperatingMode currentMode; - -int gui_SolderingSleepingMode(bool stayOff, bool autoStarted) { -#ifndef NO_SLEEP_MODE - // Drop to sleep temperature and display until movement or button press - currentMode = OperatingMode::sleeping; - - for (;;) { - // user moved or pressed a button, go back to soldering - // If in the first two seconds we disable this to let accelerometer warm up - -#ifdef POW_DC - if (checkForUnderVoltage()) { - // return non-zero on error - return 1; - } -#endif - - if (getSettingValue(SettingsOptions::TemperatureInF)) { - currentTempTargetDegC = stayOff ? 0 : TipThermoModel::convertFtoC(min(getSettingValue(SettingsOptions::SleepTemp), getSettingValue(SettingsOptions::SolderingTemp))); - } else { - currentTempTargetDegC = stayOff ? 0 : min(getSettingValue(SettingsOptions::SleepTemp), getSettingValue(SettingsOptions::SolderingTemp)); - } - - // draw the lcd - TemperatureType_t tipTemp = getTipTemp(); - - OLED::clearScreen(); - OLED::setCursor(0, 0); - if (getSettingValue(SettingsOptions::DetailedSoldering)) { - OLED::print(translatedString(Tr->SleepingAdvancedString), FontStyle::SMALL); - OLED::setCursor(0, 8); - OLED::print(translatedString(Tr->SleepingTipAdvancedString), FontStyle::SMALL); - OLED::printNumber(tipTemp, 3, FontStyle::SMALL); - OLED::printSymbolDeg(FontStyle::SMALL); - OLED::print(SmallSymbolSpace, FontStyle::SMALL); - printVoltage(); - OLED::print(SmallSymbolVolts, FontStyle::SMALL); - } else { - OLED::print(translatedString(Tr->SleepingSimpleString), FontStyle::LARGE); - OLED::printNumber(tipTemp, 3, FontStyle::LARGE); - OLED::printSymbolDeg(FontStyle::EXTRAS); - } - - OLED::refresh(); - GUIDelay(); - - if (!shouldBeSleeping(autoStarted)) { - return 0; - } - - if (shouldShutdown()) { - // shutdown - currentTempTargetDegC = 0; - // we want to exit soldering mode - return 1; - } - } -#endif - - return 0; -} diff --git a/source/Core/Threads/OperatingModes/Soldering.cpp b/source/Core/Threads/OperatingModes/Soldering.cpp deleted file mode 100644 index d923871ea..000000000 --- a/source/Core/Threads/OperatingModes/Soldering.cpp +++ /dev/null @@ -1,189 +0,0 @@ - -#include "OperatingModes.h" -#include "SolderingCommon.h" - -extern OperatingMode currentMode; - -void gui_solderingMode(uint8_t jumpToSleep) { - /* - * * Soldering (gui_solderingMode) - * -> Main loop where we draw temp, and animations - * --> User presses buttons and they goto the temperature adjust screen - * ---> Display the current setpoint temperature - * ---> Use buttons to change forward and back on temperature - * ---> Both buttons or timeout for exiting - * --> Long hold front button to enter boost mode - * ---> Just temporarily sets the system into the alternate temperature for - * PID control - * --> Long hold back button to exit - * --> Double button to exit - * --> Long hold double button to toggle key lock - */ - bool boostModeOn = false; - bool buttonsLocked = false; - bool converged = false; - currentMode = OperatingMode::soldering; - - TickType_t buzzerEnd = 0; - - if (jumpToSleep) { - if (gui_SolderingSleepingMode(jumpToSleep == 2, true) == 1) { - lastButtonTime = xTaskGetTickCount(); - return; // If the function returns non-0 then exit - } - } - for (;;) { - ButtonState buttons = getButtonState(); - if (buttonsLocked && (getSettingValue(SettingsOptions::LockingMode) != 0)) { // If buttons locked - switch (buttons) { - case BUTTON_NONE: - boostModeOn = false; - break; - case BUTTON_BOTH_LONG: - // Unlock buttons - buttonsLocked = false; - warnUser(translatedString(Tr->UnlockingKeysString), TICKS_SECOND); - break; - case BUTTON_F_LONG: - // if boost mode is enabled turn it on - if (getSettingValue(SettingsOptions::BoostTemp) && (getSettingValue(SettingsOptions::LockingMode) == 1)) { - boostModeOn = true; - currentMode = OperatingMode::boost; - } - break; - // fall through - case BUTTON_BOTH: - case BUTTON_B_LONG: - case BUTTON_F_SHORT: - case BUTTON_B_SHORT: - // Do nothing and display a lock warning - warnUser(translatedString(Tr->WarningKeysLockedString), TICKS_SECOND / 2); - break; - default: - break; - } - } else { // Button not locked - switch (buttons) { - case BUTTON_NONE: - // stay - boostModeOn = false; - currentMode = OperatingMode::soldering; - break; - case BUTTON_BOTH: - case BUTTON_B_LONG: - return; // exit on back long hold - case BUTTON_F_LONG: - // if boost mode is enabled turn it on - if (getSettingValue(SettingsOptions::BoostTemp)) { - boostModeOn = true; - currentMode = OperatingMode::boost; - } - break; - case BUTTON_F_SHORT: - case BUTTON_B_SHORT: { - uint16_t oldTemp = getSettingValue(SettingsOptions::SolderingTemp); - gui_solderingTempAdjust(); // goto adjust temp mode - if (oldTemp != getSettingValue(SettingsOptions::SolderingTemp)) { - saveSettings(); // only save on change - } - } break; - case BUTTON_BOTH_LONG: - if (getSettingValue(SettingsOptions::LockingMode) != 0) { - // Lock buttons - buttonsLocked = true; - warnUser(translatedString(Tr->LockingKeysString), TICKS_SECOND); - } - break; - default: - break; - } - } - // else we update the screen information - - OLED::clearScreen(); - // Draw in the screen details - if (getSettingValue(SettingsOptions::DetailedSoldering)) { - if (OLED::getRotation()) { - OLED::setCursor(50, 0); - } else { - OLED::setCursor(-1, 0); - } - - gui_drawTipTemp(true, FontStyle::LARGE); - -#ifndef NO_SLEEP_MODE - if (getSettingValue(SettingsOptions::Sensitivity) && getSettingValue(SettingsOptions::SleepTime)) { - if (OLED::getRotation()) { - OLED::setCursor(32, 0); - } else { - OLED::setCursor(47, 0); - } - printCountdownUntilSleep(getSleepTimeout()); - } -#endif - - if (boostModeOn) { - if (OLED::getRotation()) { - OLED::setCursor(38, 8); - } else { - OLED::setCursor(55, 8); - } - OLED::print(SmallSymbolPlus, FontStyle::SMALL); - } else { - if (OLED::getRotation()) { - OLED::setCursor(32, 8); - } else { - OLED::setCursor(47, 8); - } - OLED::print(PowerSourceNames[getPowerSourceNumber()], FontStyle::SMALL, 2); - } - - detailedPowerStatus(); - - } else { - basicSolderingStatus(boostModeOn); - } - - OLED::refresh(); - // Update the setpoints for the temperature - if (boostModeOn) { - if (getSettingValue(SettingsOptions::TemperatureInF)) { - currentTempTargetDegC = TipThermoModel::convertFtoC(getSettingValue(SettingsOptions::BoostTemp)); - } else { - currentTempTargetDegC = (getSettingValue(SettingsOptions::BoostTemp)); - } - } else { - if (getSettingValue(SettingsOptions::TemperatureInF)) { - currentTempTargetDegC = TipThermoModel::convertFtoC(getSettingValue(SettingsOptions::SolderingTemp)); - } else { - currentTempTargetDegC = (getSettingValue(SettingsOptions::SolderingTemp)); - } - } - - if (checkExitSoldering()) { - setBuzzer(false); - return; - } - - // Update status - int error = currentTempTargetDegC - TipThermoModel::getTipInC(); - if (error >= -10 && error <= 10) { - // converged - if (!converged) { - setBuzzer(true); - buzzerEnd = xTaskGetTickCount() + TICKS_SECOND / 3; - converged = true; - } - setStatusLED(LED_HOT); - } else { - setStatusLED(LED_HEATING); - converged = false; - } - if (buzzerEnd != 0 && xTaskGetTickCount() >= buzzerEnd) { - setBuzzer(false); - } - - // slow down ui update rate - GUIDelay(); - } -} diff --git a/source/Core/Threads/OperatingModes/SolderingProfile.cpp b/source/Core/Threads/OperatingModes/SolderingProfile.cpp deleted file mode 100644 index df6b58056..000000000 --- a/source/Core/Threads/OperatingModes/SolderingProfile.cpp +++ /dev/null @@ -1,223 +0,0 @@ - -#include "OperatingModes.h" -#include "SolderingCommon.h" - -extern OperatingMode currentMode; - -void gui_solderingProfileMode() { - /* - * * Soldering (gui_solderingMode) - * -> Main loop where we draw temp, and animations - * PID control - * --> Long hold back button to exit - * --> Double button to exit - */ - currentMode = OperatingMode::soldering; - - TickType_t buzzerEnd = 0; - - bool waitForRelease = true; - TickType_t phaseStartTime = xTaskGetTickCount(); - - uint16_t tipTemp = 0; - uint8_t profilePhase = 0; - - uint16_t phaseElapsedSeconds = 0; - uint16_t phaseTotalSeconds = 0; - uint16_t phaseStartTemp = 0; - uint16_t phaseEndTemp = getSettingValue(SettingsOptions::ProfilePreheatTemp); - uint16_t phaseTicksPerDegree = TICKS_SECOND / getSettingValue(SettingsOptions::ProfilePreheatSpeed); - uint16_t profileCurrentTargetTemp = 0; - - for (;;) { - ButtonState buttons = getButtonState(); - if (buttons) { - if (waitForRelease) { - buttons = BUTTON_NONE; - } - } else { - waitForRelease = false; - } - - switch (buttons) { - case BUTTON_NONE: - break; - case BUTTON_BOTH: - case BUTTON_B_LONG: - return; // exit on back long hold - case BUTTON_F_LONG: - case BUTTON_F_SHORT: - case BUTTON_B_SHORT: - // Not used yet - break; - default: - break; - } - - tipTemp = getTipTemp(); - - // if start temp is unknown (preheat), we're setting it now - if (phaseStartTemp == 0) { - phaseStartTemp = tipTemp; - // if this is hotter than the preheat temperature, we should fail - if (phaseStartTemp >= 55) { - warnUser(translatedString(Tr->TooHotToStartProfileWarning), 10 * TICKS_SECOND); - return; - } - } - - phaseElapsedSeconds = (xTaskGetTickCount() - phaseStartTime) / TICKS_SECOND; - - // have we finished this phase? - if (phaseElapsedSeconds >= phaseTotalSeconds && tipTemp == phaseEndTemp) { - profilePhase++; - - phaseStartTemp = phaseEndTemp; - phaseStartTime = xTaskGetTickCount(); - phaseElapsedSeconds = 0; - - if (profilePhase > getSettingValue(SettingsOptions::ProfilePhases)) { - // done with all phases, lets go to cooldown - phaseTotalSeconds = 0; - phaseEndTemp = 0; - phaseTicksPerDegree = TICKS_SECOND / getSettingValue(SettingsOptions::ProfileCooldownSpeed); - } else { - // set up next phase - switch (profilePhase) { - case 1: - phaseTotalSeconds = getSettingValue(SettingsOptions::ProfilePhase1Duration); - phaseEndTemp = getSettingValue(SettingsOptions::ProfilePhase1Temp); - break; - case 2: - phaseTotalSeconds = getSettingValue(SettingsOptions::ProfilePhase2Duration); - phaseEndTemp = getSettingValue(SettingsOptions::ProfilePhase2Temp); - break; - case 3: - phaseTotalSeconds = getSettingValue(SettingsOptions::ProfilePhase3Duration); - phaseEndTemp = getSettingValue(SettingsOptions::ProfilePhase3Temp); - break; - case 4: - phaseTotalSeconds = getSettingValue(SettingsOptions::ProfilePhase4Duration); - phaseEndTemp = getSettingValue(SettingsOptions::ProfilePhase4Temp); - break; - case 5: - phaseTotalSeconds = getSettingValue(SettingsOptions::ProfilePhase5Duration); - phaseEndTemp = getSettingValue(SettingsOptions::ProfilePhase5Temp); - break; - default: - break; - } - if (phaseStartTemp < phaseEndTemp) { - phaseTicksPerDegree = (phaseTotalSeconds * TICKS_SECOND) / (phaseEndTemp - phaseStartTemp); - } else { - phaseTicksPerDegree = (phaseTotalSeconds * TICKS_SECOND) / (phaseStartTemp - phaseEndTemp); - } - } - } - - // cooldown phase done? - if (profilePhase > getSettingValue(SettingsOptions::ProfilePhases)) { - if (TipThermoModel::getTipInC() < 55) { - // we're done, let the buzzer beep too - setStatusLED(LED_STANDBY); - if (buzzerEnd == 0) { - setBuzzer(true); - buzzerEnd = xTaskGetTickCount() + TICKS_SECOND / 3; - } - } - } - - // determine current target temp - if (phaseStartTemp < phaseEndTemp) { - if (profileCurrentTargetTemp < phaseEndTemp) { - profileCurrentTargetTemp = phaseStartTemp + ((xTaskGetTickCount() - phaseStartTime) / phaseTicksPerDegree); - } - } else { - if (profileCurrentTargetTemp > phaseEndTemp) { - profileCurrentTargetTemp = phaseStartTemp - ((xTaskGetTickCount() - phaseStartTime) / phaseTicksPerDegree); - } - } - - OLED::clearScreen(); - // Draw in the screen details - if (getSettingValue(SettingsOptions::DetailedSoldering)) { - // print temperature - if (OLED::getRotation()) { - OLED::setCursor(48, 0); - } else { - OLED::setCursor(0, 0); - } - - OLED::printNumber(tipTemp, 3, FontStyle::SMALL); - OLED::print(SmallSymbolSlash, FontStyle::SMALL); - OLED::printNumber(profileCurrentTargetTemp, 3, FontStyle::SMALL); - OLED::printSymbolDeg(FontStyle::SMALL); - - // print phase - if (profilePhase > 0 && profilePhase <= getSettingValue(SettingsOptions::ProfilePhases)) { - if (OLED::getRotation()) { - OLED::setCursor(36, 0); - } else { - OLED::setCursor(55, 0); - } - OLED::printNumber(profilePhase, 1, FontStyle::SMALL); - } - - // print time progress / preheat / cooldown - if (OLED::getRotation()) { - OLED::setCursor(42, 8); - } else { - OLED::setCursor(0, 8); - } - - if (profilePhase == 0) { - OLED::print(translatedString(Tr->ProfilePreheatString), FontStyle::SMALL); - } else if (profilePhase > getSettingValue(SettingsOptions::ProfilePhases)) { - OLED::print(translatedString(Tr->ProfileCooldownString), FontStyle::SMALL); - } else { - OLED::printNumber(phaseElapsedSeconds / 60, 1, FontStyle::SMALL); - OLED::print(SmallSymbolColon, FontStyle::SMALL); - OLED::printNumber(phaseElapsedSeconds % 60, 2, FontStyle::SMALL, false); - - OLED::print(SmallSymbolSlash, FontStyle::SMALL); - - // blink if we can't keep up with the time goal - if (phaseElapsedSeconds < phaseTotalSeconds + 2 || (xTaskGetTickCount() / TICKS_SECOND) % 2 == 0) { - OLED::printNumber(phaseTotalSeconds / 60, 1, FontStyle::SMALL); - OLED::print(SmallSymbolColon, FontStyle::SMALL); - OLED::printNumber(phaseTotalSeconds % 60, 2, FontStyle::SMALL, false); - } - } - - detailedPowerStatus(); - - } else { - basicSolderingStatus(false); - } - - OLED::refresh(); - // Update the setpoints for the temperature - if (getSettingValue(SettingsOptions::TemperatureInF)) { - currentTempTargetDegC = TipThermoModel::convertFtoC(profileCurrentTargetTemp); - } else { - currentTempTargetDegC = profileCurrentTargetTemp; - } - - if (checkExitSoldering() || (buzzerEnd != 0 && xTaskGetTickCount() >= buzzerEnd)) { - setBuzzer(false); - return; - } - - // Update LED status - if (profilePhase == 0) { - setStatusLED(LED_HEATING); - } else if (profilePhase > getSettingValue(SettingsOptions::ProfilePhases)) { - setStatusLED(LED_COOLING_STILL_HOT); - } else { - setStatusLED(LED_HOT); - } - - // slow down ui update rate - GUIDelay(); - } -} diff --git a/source/Core/Threads/OperatingModes/TemperatureAdjust.cpp b/source/Core/Threads/OperatingModes/TemperatureAdjust.cpp deleted file mode 100644 index ce06e83ba..000000000 --- a/source/Core/Threads/OperatingModes/TemperatureAdjust.cpp +++ /dev/null @@ -1,120 +0,0 @@ -#include "OperatingModes.h" -void gui_solderingTempAdjust(void) { - TickType_t lastChange = xTaskGetTickCount(); - currentTempTargetDegC = 0; // Turn off heater while adjusting temp - TickType_t autoRepeatTimer = 0; - uint8_t autoRepeatAcceleration = 0; -#ifndef PROFILE_SUPPORT - bool waitForRelease = false; - ButtonState buttons = getButtonState(); - - if (buttons != BUTTON_NONE) { - // Temp adjust entered by long-pressing F button. - waitForRelease = true; - } -#else - ButtonState buttons; -#endif - - for (;;) { - OLED::setCursor(0, 0); - OLED::clearScreen(); - buttons = getButtonState(); - if (buttons) { - lastChange = xTaskGetTickCount(); -#ifndef PROFILE_SUPPORT - if (waitForRelease) { - buttons = BUTTON_NONE; - } - } else { - waitForRelease = false; -#endif - } - int16_t delta = 0; - switch (buttons) { - case BUTTON_NONE: - // stay - autoRepeatAcceleration = 0; - break; - case BUTTON_BOTH: - // exit - return; - break; - case BUTTON_B_LONG: - if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration > PRESS_ACCEL_INTERVAL_MAX) { - delta = -getSettingValue(SettingsOptions::TempChangeLongStep); - autoRepeatTimer = xTaskGetTickCount(); - autoRepeatAcceleration += PRESS_ACCEL_STEP; - } - break; - case BUTTON_B_SHORT: - delta = -getSettingValue(SettingsOptions::TempChangeShortStep); - break; - case BUTTON_F_LONG: - if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration > PRESS_ACCEL_INTERVAL_MAX) { - delta = getSettingValue(SettingsOptions::TempChangeLongStep); - autoRepeatTimer = xTaskGetTickCount(); - autoRepeatAcceleration += PRESS_ACCEL_STEP; - } - break; - case BUTTON_F_SHORT: - delta = getSettingValue(SettingsOptions::TempChangeShortStep); - break; - default: - break; - } - if ((PRESS_ACCEL_INTERVAL_MAX - autoRepeatAcceleration) < PRESS_ACCEL_INTERVAL_MIN) { - autoRepeatAcceleration = PRESS_ACCEL_INTERVAL_MAX - PRESS_ACCEL_INTERVAL_MIN; - } - // If buttons are flipped; flip the delta - if (getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled)) { - delta = -delta; - } - if (delta != 0) { - // constrain between the set temp limits, i.e. 10-450 C - int16_t newTemp = getSettingValue(SettingsOptions::SolderingTemp); - newTemp += delta; - // Round to nearest increment of delta - delta = abs(delta); - newTemp = (newTemp / delta) * delta; - - if (getSettingValue(SettingsOptions::TemperatureInF)) { - if (newTemp > MAX_TEMP_F) { - newTemp = MAX_TEMP_F; - } - if (newTemp < MIN_TEMP_F) { - newTemp = MIN_TEMP_F; - } - } else { - if (newTemp > MAX_TEMP_C) { - newTemp = MAX_TEMP_C; - } - if (newTemp < MIN_TEMP_C) { - newTemp = MIN_TEMP_C; - } - } - setSettingValue(SettingsOptions::SolderingTemp, (uint16_t)newTemp); - } - if (xTaskGetTickCount() - lastChange > (TICKS_SECOND * 2)) { - return; // exit if user just doesn't press anything for a bit - } - - if (OLED::getRotation()) { - OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolPlus : LargeSymbolMinus, FontStyle::LARGE); - } else { - OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolMinus : LargeSymbolPlus, FontStyle::LARGE); - } - - OLED::print(LargeSymbolSpace, FontStyle::LARGE); - OLED::printNumber(getSettingValue(SettingsOptions::SolderingTemp), 3, FontStyle::LARGE); - OLED::printSymbolDeg(FontStyle::EXTRAS); - OLED::print(LargeSymbolSpace, FontStyle::LARGE); - if (OLED::getRotation()) { - OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolMinus : LargeSymbolPlus, FontStyle::LARGE); - } else { - OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolPlus : LargeSymbolMinus, FontStyle::LARGE); - } - OLED::refresh(); - GUIDelay(); - } -} diff --git a/source/Core/Threads/OperatingModes/USBPDDebug_FUSB.cpp b/source/Core/Threads/OperatingModes/USBPDDebug_FUSB.cpp deleted file mode 100644 index 65776970f..000000000 --- a/source/Core/Threads/OperatingModes/USBPDDebug_FUSB.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "OperatingModes.h" - -#ifdef POW_PD -#ifdef HAS_POWER_DEBUG_MENU -void showPDDebug(void) { - // Print out the USB-PD state - // Basically this is like the Debug menu, but instead we want to print out the PD status - uint8_t screen = 0; - ButtonState b; - for (;;) { - OLED::clearScreen(); // Ensure the buffer starts clean - OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) - OLED::print(SmallSymbolPDDebug, FontStyle::SMALL); // Print Title - OLED::setCursor(0, 8); // second line - if (screen == 0) { - // Print the PD state machine - OLED::print(SmallSymbolState, FontStyle::SMALL); - OLED::print(SmallSymbolSpace, FontStyle::SMALL); - OLED::printNumber(USBPowerDelivery::getStateNumber(), 2, FontStyle::SMALL, true); - OLED::print(SmallSymbolSpace, FontStyle::SMALL); - // Also print vbus mod status - if (USBPowerDelivery::fusbPresent()) { - if (USBPowerDelivery::negotiationComplete() || (xTaskGetTickCount() > (TICKS_SECOND * 10))) { - if (!USBPowerDelivery::isVBUSConnected()) { - OLED::print(SmallSymbolNoVBus, FontStyle::SMALL); - } else { - OLED::print(SmallSymbolVBus, FontStyle::SMALL); - } - } - } - } else { - // Print out the Proposed power options one by one - auto lastCaps = USBPowerDelivery::getLastSeenCapabilities(); - if ((screen - 1) < 11) { - int voltage_mv = 0; - int min_voltage = 0; - int current_a_x100 = 0; - int wattage = 0; - - if ((lastCaps[screen - 1] & PD_PDO_TYPE) == PD_PDO_TYPE_FIXED) { - voltage_mv = PD_PDV2MV(PD_PDO_SRC_FIXED_VOLTAGE_GET(lastCaps[screen - 1])); // voltage in mV units - current_a_x100 = PD_PDO_SRC_FIXED_CURRENT_GET(lastCaps[screen - 1]); // current in 10mA units - } else if (((lastCaps[screen - 1] & PD_PDO_TYPE) == PD_PDO_TYPE_AUGMENTED) && ((lastCaps[screen - 1] & PD_APDO_TYPE) == PD_APDO_TYPE_AVS)) { - voltage_mv = PD_PAV2MV(PD_APDO_AVS_MAX_VOLTAGE_GET(lastCaps[screen - 1])); - min_voltage = PD_PAV2MV(PD_APDO_PPS_MIN_VOLTAGE_GET(lastCaps[screen - 1])); - // Last value is wattage - wattage = PD_APDO_AVS_MAX_POWER_GET(lastCaps[screen - 1]); - } else if (((lastCaps[screen - 1] & PD_PDO_TYPE) == PD_PDO_TYPE_AUGMENTED) && ((lastCaps[screen - 1] & PD_APDO_TYPE) == PD_APDO_TYPE_PPS)) { - voltage_mv = PD_PAV2MV(PD_APDO_PPS_MAX_VOLTAGE_GET(lastCaps[screen - 1])); - min_voltage = PD_PAV2MV(PD_APDO_PPS_MIN_VOLTAGE_GET(lastCaps[screen - 1])); - current_a_x100 = PD_PAI2CA(PD_APDO_PPS_CURRENT_GET(lastCaps[screen - 1])); // max current in 10mA units - } - // Skip not used entries - if (voltage_mv == 0) { - screen++; - } else { - // print out this entry of the proposal - OLED::printNumber(screen, 2, FontStyle::SMALL, true); // print the entry number - OLED::print(SmallSymbolSpace, FontStyle::SMALL); - if (min_voltage > 0) { - OLED::printNumber(min_voltage / 1000, 2, FontStyle::SMALL, true); // print the voltage - OLED::print(SmallSymbolMinus, FontStyle::SMALL); - } - OLED::printNumber(voltage_mv / 1000, 2, FontStyle::SMALL, true); // print the voltage - OLED::print(SmallSymbolVolts, FontStyle::SMALL); - OLED::print(SmallSymbolSpace, FontStyle::SMALL); - if (wattage) { - OLED::printNumber(wattage, 3, FontStyle::SMALL, true); // print the current in 0.1A res - OLED::print(SmallSymbolWatts, FontStyle::SMALL); - } else { - OLED::printNumber(current_a_x100 / 100, 2, FontStyle::SMALL, true); // print the current in 0.1A res - OLED::print(SmallSymbolDot, FontStyle::SMALL); - OLED::printNumber(current_a_x100 % 100, 2, FontStyle::SMALL, false); // print the current in 0.1A res - OLED::print(SmallSymbolAmps, FontStyle::SMALL); - } - } - } else { - screen = 0; - } - } - - OLED::refresh(); - b = getButtonState(); - if (b == BUTTON_B_SHORT) { - return; - } else if (b == BUTTON_F_SHORT) { - screen++; - } - - GUIDelay(); - } -} -#endif -#endif diff --git a/source/Core/Threads/OperatingModes/USBPDDebug_HUSB238.cpp b/source/Core/Threads/OperatingModes/USBPDDebug_HUSB238.cpp deleted file mode 100644 index 5841e47ce..000000000 --- a/source/Core/Threads/OperatingModes/USBPDDebug_HUSB238.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "HUB238.hpp" -#include "OperatingModes.h" -#if POW_PD_EXT == 1 -#ifdef HAS_POWER_DEBUG_MENU -void showPDDebug(void) { - // Print out the USB-PD state - // Basically this is like the Debug menu, but instead we want to print out the PD status - uint8_t screen = 0; - ButtonState b; - for (;;) { - OLED::clearScreen(); // Ensure the buffer starts clean - OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) - OLED::print(SmallSymbolPDDebug, FontStyle::SMALL); // Print Title - OLED::setCursor(0, 8); // second line - if (screen > 6) { - screen = 0; - } - if (screen == 0) { - // Print the PD Debug state - OLED::print(SmallSymbolState, FontStyle::SMALL); - OLED::print(SmallSymbolSpace, FontStyle::SMALL); - uint16_t temp = hub238_debug_state(); - OLED::drawHex(temp, FontStyle::SMALL, 4); - OLED::print(SmallSymbolSpace, FontStyle::SMALL); - // Print current selected specs - temp = hub238_source_voltage(); - OLED::printNumber(temp, 2, FontStyle::SMALL, true); - OLED::print(SmallSymbolSpace, FontStyle::SMALL); - - } else { - - // Print out the Proposed power options one by one - const uint8_t voltages[] = {5, 9, 12, 15, 18, 20}; - uint16_t voltage = voltages[screen - 1]; - uint16_t currentx100 = hub238_getVoltagePDOCurrent(voltage); - OLED::printNumber(voltage, 2, FontStyle::SMALL, true); - OLED::print(SmallSymbolSpace, FontStyle::SMALL); - - OLED::printNumber(currentx100 / 100, 1, FontStyle::SMALL, true); - OLED::print(SmallSymbolDot, FontStyle::SMALL); - OLED::printNumber(currentx100 % 100, 2, FontStyle::SMALL, true); - } - - OLED::refresh(); - b = getButtonState(); - if (b == BUTTON_B_SHORT) { - return; - } else if (b == BUTTON_F_SHORT) { - screen++; - } - - GUIDelay(); - } -} -#endif -#endif diff --git a/source/Core/Threads/OperatingModes/utils/OperatingModeUtilities.h b/source/Core/Threads/OperatingModes/utils/OperatingModeUtilities.h deleted file mode 100644 index ab3f36f99..000000000 --- a/source/Core/Threads/OperatingModes/utils/OperatingModeUtilities.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef OPERATING_MODE_UTILITIES_H_ -#define OPERATING_MODE_UTILITIES_H_ -#include "OLED.hpp" -#include - -void GUIDelay(); // -bool checkForUnderVoltage(void); // -uint32_t getSleepTimeout(void); // -bool shouldBeSleeping(bool inAutoStart); // -bool shouldShutdown(void); // -void gui_drawTipTemp(bool symbol, const FontStyle font); // -void printVoltage(void); // -void warnUser(const char *warning, const TickType_t timeout); // -void gui_drawBatteryIcon(void); // -bool checkForUnderVoltage(void); // -uint16_t min(uint16_t a, uint16_t b); // -void printCountdownUntilSleep(int sleepThres); // -#endif \ No newline at end of file diff --git a/source/Core/Threads/OperatingModes/utils/ShowWarning.cpp b/source/Core/Threads/OperatingModes/utils/ShowWarning.cpp deleted file mode 100644 index fcd2972e2..000000000 --- a/source/Core/Threads/OperatingModes/utils/ShowWarning.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include "Buttons.hpp" -#include "OperatingModeUtilities.h" -void warnUser(const char *warning, const TickType_t timeout) { - OLED::clearScreen(); - OLED::printWholeScreen(warning); - OLED::refresh(); - waitForButtonPressOrTimeout(timeout); -} diff --git a/source/Core/Threads/OperatingModes/utils/SolderingCommon.cpp b/source/Core/Threads/OperatingModes/utils/SolderingCommon.cpp deleted file mode 100644 index 0f1bbd2a3..000000000 --- a/source/Core/Threads/OperatingModes/utils/SolderingCommon.cpp +++ /dev/null @@ -1,181 +0,0 @@ -// -// Created by laura on 24.04.23. -// - -#include "SolderingCommon.h" -#include "OperatingModes.h" -#include "configuration.h" -#include "history.hpp" - -extern bool heaterThermalRunaway; - -void detailedPowerStatus() { - if (OLED::getRotation()) { - OLED::setCursor(0, 0); - } else { - OLED::setCursor(67, 0); - } - // Print wattage - { - uint32_t x10Watt = x10WattHistory.average(); - if (x10Watt > 999) { - // If we exceed 99.9W we drop the decimal place to keep it all fitting - OLED::print(SmallSymbolSpace, FontStyle::SMALL); - OLED::printNumber(x10WattHistory.average() / 10, 3, FontStyle::SMALL); - } else { - OLED::printNumber(x10WattHistory.average() / 10, 2, FontStyle::SMALL); - OLED::print(SmallSymbolDot, FontStyle::SMALL); - OLED::printNumber(x10WattHistory.average() % 10, 1, FontStyle::SMALL); - } - OLED::print(SmallSymbolWatts, FontStyle::SMALL); - } - - if (OLED::getRotation()) { - OLED::setCursor(0, 8); - } else { - OLED::setCursor(67, 8); - } - printVoltage(); - OLED::print(SmallSymbolVolts, FontStyle::SMALL); -} - -void basicSolderingStatus(bool boostModeOn) { - OLED::setCursor(0, 0); - // We switch the layout direction depending on the orientation of the oled - if (OLED::getRotation()) { - // battery - gui_drawBatteryIcon(); - // Space out gap between battery <-> temp - OLED::print(LargeSymbolSpace, FontStyle::LARGE); - // Draw current tip temp - gui_drawTipTemp(true, FontStyle::LARGE); - - // We draw boost arrow if boosting, - // or else gap temp <-> heat indicator - if (boostModeOn) { - OLED::drawSymbol(2); - } else { - OLED::print(LargeSymbolSpace, FontStyle::LARGE); - } - - // Draw heating/cooling symbols - OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average())); - } else { - // Draw heating/cooling symbols - OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average())); - // We draw boost arrow if boosting, - // or else gap temp <-> heat indicator - if (boostModeOn) { - OLED::drawSymbol(2); - } else { - OLED::print(LargeSymbolSpace, FontStyle::LARGE); - } - // Draw current tip temp - gui_drawTipTemp(true, FontStyle::LARGE); - // Space out gap between battery <-> temp - OLED::print(LargeSymbolSpace, FontStyle::LARGE); - - gui_drawBatteryIcon(); - } -} - -bool checkExitSoldering(void) { -#ifdef POW_DC - // Undervoltage test - if (checkForUnderVoltage()) { - lastButtonTime = xTaskGetTickCount(); - return true; - } -#endif - -#ifdef ACCEL_EXITS_ON_MOVEMENT - // If the accel works in reverse where movement will cause exiting the soldering mode - if (getSettingValue(Sensitivity)) { - if (lastMovementTime) { - if (lastMovementTime > TICKS_SECOND * 10) { - // If we have moved recently; in the last second - // Then exit soldering mode - - // Movement occurred in last update - if (((TickType_t)(xTaskGetTickCount() - lastMovementTime)) < (TickType_t)(TICKS_SECOND / 5)) { - currentTempTargetDegC = 0; - lastMovementTime = 0; - return true; - } - } - } - } -#endif -#ifdef NO_SLEEP_MODE - // No sleep mode, but still want shutdown timeout - - if (shouldShutdown()) { - // shutdown - currentTempTargetDegC = 0; - lastMovementTime = xTaskGetTickCount(); // We manually move the movement time to now such that shutdown timer is reset - - return true; // we want to exit soldering mode - } -#endif - if (shouldBeSleeping(false)) { - if (gui_SolderingSleepingMode(false, false)) { - return true; // If the function returns non-0 then exit - } - } - - // If we have tripped thermal runaway, turn off heater and show warning - if (heaterThermalRunaway) { - currentTempTargetDegC = 0; // heater control off - warnUser(translatedString(Tr->WarningThermalRunaway), 10 * TICKS_SECOND); - heaterThermalRunaway = false; - return true; - } - - return false; -} - -int8_t getPowerSourceNumber(void) { - int8_t sourceNumber = 0; - if (getIsPoweredByDCIN()) { - sourceNumber = 0; - } else { - // We are not powered via DC, so want to display the appropriate state for PD or QC - bool poweredbyPD = false; - bool pdHasVBUSConnected = false; -#ifdef POW_PD - if (USBPowerDelivery::fusbPresent()) { - // We are PD capable - if (USBPowerDelivery::negotiationComplete()) { - // We are powered via PD - poweredbyPD = true; -#ifdef VBUS_MOD_TEST - pdHasVBUSConnected = USBPowerDelivery::isVBUSConnected(); -#endif - } - } -#endif - if (poweredbyPD) { - if (pdHasVBUSConnected) { - sourceNumber = 2; - } else { - sourceNumber = 3; - } - } else { - sourceNumber = 1; - } - } - return sourceNumber; -} - -// Returns temperature of the tip in *C/*F (based on user settings) -TemperatureType_t getTipTemp(void) { -#ifdef FILTER_DISPLAYED_TIP_TEMP - static history Filter_Temp; - TemperatureType_t reading = getSettingValue(SettingsOptions::TemperatureInF) ? TipThermoModel::getTipInF() : TipThermoModel::getTipInC(); - Filter_Temp.update(reading); - return Filter_Temp.average(); - -#else - return getSettingValue(SettingsOptions::TemperatureInF) ? TipThermoModel::getTipInF() : TipThermoModel::getTipInC(); -#endif -} diff --git a/source/Core/Threads/OperatingModes/utils/SolderingCommon.h b/source/Core/Threads/OperatingModes/utils/SolderingCommon.h deleted file mode 100644 index 13443e6cc..000000000 --- a/source/Core/Threads/OperatingModes/utils/SolderingCommon.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef SOLDERING_COMMON_H -#define SOLDERING_COMMON_H - -void detailedPowerStatus(); -void basicSolderingStatus(bool boostModeOn); -bool checkExitSoldering(); - -#endif //SOLDERING_COMMON_H diff --git a/source/Core/Threads/PIDThread.cpp b/source/Core/Threads/PIDThread.cpp index 615a966df..e7183248a 100644 --- a/source/Core/Threads/PIDThread.cpp +++ b/source/Core/Threads/PIDThread.cpp @@ -16,15 +16,21 @@ #include "power.hpp" #include "task.h" -static TickType_t powerPulseWaitUnit = 25 * TICKS_100MS; // 2.5 s -static TickType_t powerPulseDurationUnit = (5 * TICKS_100MS) / 2; // 250 ms -TaskHandle_t pidTaskNotification = NULL; -volatile TemperatureType_t currentTempTargetDegC = 0; // Current temperature target in C -int32_t powerSupplyWattageLimit = 0; -bool heaterThermalRunaway = false; +#ifdef POW_PD +#if POW_PD == 1 +#include "USBPD.h" +#endif +#endif + +static TickType_t powerPulseWaitUnit = 25 * TICKS_100MS; // 2.5 s +static TickType_t powerPulseDurationUnit = (5 * TICKS_100MS) / 2; // 250 ms +TaskHandle_t pidTaskNotification = NULL; +volatile TemperatureType_t currentTempTargetDegC = 0; // Current temperature target in C +int32_t powerSupplyWattageLimit = 0; +uint8_t heaterThermalRunawayCounter = 0; static int32_t getPIDResultX10Watts(TemperatureType_t set_point, TemperatureType_t current_value); -static void detectThermalRunaway(const TemperatureType_t currentTipTempInC, const TemperatureType_t tError); +static void detectThermalRunaway(const TemperatureType_t currentTipTempInC, const uint32_t x10WattsOut); static void setOutputx10WattsViaFilters(int32_t x10Watts); static int32_t getX10WattageLimits(); @@ -38,7 +44,9 @@ void startPIDTask(void const *argument __unused) { currentTempTargetDegC = 0; // Force start with no output (off). If in sleep / soldering this will // be over-ridden rapidly - pidTaskNotification = xTaskGetCurrentTaskHandle(); + + pidTaskNotification = xTaskGetCurrentTaskHandle(); + TemperatureType_t PIDTempTarget = 0; // Pre-seed the adc filters for (int i = 0; i < 32; i++) { @@ -51,8 +59,20 @@ void startPIDTask(void const *argument __unused) { resetWatchdog(); ulTaskNotifyTake(pdTRUE, 2000); } +// Wait for PD if its in the middle of negotiation +#ifdef POW_PD +#if POW_PD == 1 + // This is an FUSB based PD capable device + // Wait up to 3 seconds for USB-PD to settle + while (USBPowerDelivery::negotiationInProgress() && xTaskGetTickCount() < (TICKS_SECOND * 3)) { + resetWatchdog(); + ulTaskNotifyTake(pdTRUE, TICKS_100MS); + } +#endif +#endif - int32_t x10WattsOut = 0; + int32_t x10WattsOut = 0; + TickType_t lastThermalRunawayDecay = xTaskGetTickCount(); for (;;) { x10WattsOut = 0; @@ -73,8 +93,8 @@ void startPIDTask(void const *argument __unused) { PIDTempTarget = TipThermoModel::getTipMaxInC(); } - detectThermalRunaway(currentTipTempInC, PIDTempTarget - currentTipTempInC); x10WattsOut = getPIDResultX10Watts(PIDTempTarget, currentTipTempInC); + detectThermalRunaway(currentTipTempInC, x10WattsOut); } else { detectThermalRunaway(currentTipTempInC, 0); } @@ -86,6 +106,12 @@ void startPIDTask(void const *argument __unused) { #ifdef DEBUG_UART_OUTPUT log_system_state(x10WattsOut); #endif + if (xTaskGetTickCount() - lastThermalRunawayDecay > TICKS_SECOND) { + lastThermalRunawayDecay = xTaskGetTickCount(); + if (heaterThermalRunawayCounter > 0) { + heaterThermalRunawayCounter--; + } + } } } @@ -124,10 +150,11 @@ template struct PID { T output = kp_result + ki_result + kd_result; // Restrict to max / 0 - if (output > max_output) + if (output > max_output) { output = max_output; - else if (output < 0) + } else if (output < 0) { output = 0; + } // Save target_delta to previous target_delta previous_error_term = target_delta; @@ -208,31 +235,59 @@ int32_t getPIDResultX10Watts(TemperatureType_t set_point, TemperatureType_t curr #endif } -void detectThermalRunaway(const TemperatureType_t currentTipTempInC, const TemperatureType_t tError) { - static TemperatureType_t tipTempCRunawayTemp = 0; - static TickType_t runawaylastChangeTime = 0; +/* + * Detection of thermal runaway + * The goal of this is to handle cases where something has gone wrong + * 1. The tip MOSFET is broken, so power is being constantly applied to the tip + * a. This can show as temp being stuck at max + * b. Or temp rising when the heater is off + * 2. Broken temperature sense + * a. Temp is stuck at a value + * These boil down to either a constantly rising temperature or a temperature that is stuck at a value + * These are both covered; but looking at the eye/delta between min and max temp seen + */ +void detectThermalRunaway(const TemperatureType_t currentTipTempInC, const uint32_t x10WattsOut) { + + static TemperatureType_t tiptempMin = 0xFFFF; // Min tip temp seen + static TemperatureType_t tipTempMax = 0; // Max tip temp seen while heater is on + bool thisCycleIsHeating = x10WattsOut > 0; + static TickType_t heatCycleStart = 0; - // Check for thermal runaway, where it has been x seconds with negligible (y) temp rise - // While trying to actively heat + static bool haveSeenDelta = false; - // If we are more than 20C below the setpoint - if ((tError > THERMAL_RUNAWAY_TEMP_C)) { + // Check for readings being pegged at the top of the ADC while the heater is off + if (!thisCycleIsHeating && (getTipRawTemp(0) > (ADC_MAX_READING - 8)) && heaterThermalRunawayCounter < 255) { + heaterThermalRunawayCounter++; + } - // If we have heated up by more than 20C since last sample point, snapshot time and tip temp - TemperatureType_t delta = currentTipTempInC - tipTempCRunawayTemp; - if (delta > THERMAL_RUNAWAY_TEMP_C) { - // We have heated up more than the threshold, reset the timer - tipTempCRunawayTemp = currentTipTempInC; - runawaylastChangeTime = xTaskGetTickCount(); - } else { - if ((xTaskGetTickCount() - runawaylastChangeTime) > (THERMAL_RUNAWAY_TIME_SEC * TICKS_SECOND)) { - // It has taken too long to rise - heaterThermalRunaway = true; - } + if (haveSeenDelta) { + return; + } + + if (currentTipTempInC < tiptempMin) { + tiptempMin = currentTipTempInC; + } + if (thisCycleIsHeating && currentTipTempInC > tipTempMax) { + tipTempMax = currentTipTempInC; + } + if (thisCycleIsHeating) { + if (heatCycleStart == 0) { + heatCycleStart = xTaskGetTickCount(); } } else { - tipTempCRunawayTemp = currentTipTempInC; - runawaylastChangeTime = xTaskGetTickCount(); + heatCycleStart = 0; + } + + if ((xTaskGetTickCount() - heatCycleStart) > (THERMAL_RUNAWAY_TIME_SEC * TICKS_SECOND)) { + if (tipTempMax > tiptempMin) { + // Have been heating for min seconds, check if the delta is large enough + TemperatureType_t delta = tipTempMax - tiptempMin; + haveSeenDelta = true; + + if (delta < THERMAL_RUNAWAY_TEMP_C && heaterThermalRunawayCounter < 255) { + heaterThermalRunawayCounter++; + } + } } } @@ -274,7 +329,7 @@ void setOutputx10WattsViaFilters(int32_t x10WattsOut) { if (getTipRawTemp(0) > (0x7FFF - 32)) { x10WattsOut = 0; } - if (heaterThermalRunaway) { + if (heaterThermalRunawayCounter > 8) { x10WattsOut = 0; } #ifdef SLEW_LIMIT @@ -288,4 +343,4 @@ void setOutputx10WattsViaFilters(int32_t x10WattsOut) { #endif setTipX10Watts(x10WattsOut); resetWatchdog(); -} \ No newline at end of file +} diff --git a/source/Core/Threads/POWThread.cpp b/source/Core/Threads/POWThread.cpp index bb816ad72..27b1719be 100644 --- a/source/Core/Threads/POWThread.cpp +++ b/source/Core/Threads/POWThread.cpp @@ -6,6 +6,7 @@ */ #include "BSP.h" +#include "FS2711.hpp" #include "FreeRTOS.h" #include "HUB238.hpp" #include "QC3.h" @@ -14,6 +15,7 @@ #include "cmsis_os.h" #include "configuration.h" #include "main.hpp" +#include "stdbool.h" #include "stdlib.h" #include "task.h" @@ -32,8 +34,12 @@ void startPOWTask(void const *argument __unused) { USBPowerDelivery::start(); // Crank the handle at boot until we are stable and waiting for IRQ USBPowerDelivery::step(); - #endif +#if POW_PD_EXT == 2 + FS2711::start(); + FS2711::negotiate(); +#endif + BaseType_t res; for (;;) { res = pdFALSE; @@ -60,6 +66,9 @@ void startPOWTask(void const *argument __unused) { #endif #if POW_PD_EXT == 1 hub238_check_negotiation(); +#endif +#if POW_PD_EXT == 2 + FS2711::negotiate(); #endif power_check(); } diff --git a/source/Core/Threads/UI/README.md b/source/Core/Threads/UI/README.md new file mode 100644 index 000000000..8805fa20d --- /dev/null +++ b/source/Core/Threads/UI/README.md @@ -0,0 +1,5 @@ +# UI + +The User interface for IronOS is split into two halves in these folders. +The `logic` folder contains the `.cpp` files that implement the logic of each mode, this should handle button events and any logic. +The `drawing` folder contains the `.cpp` files that implement just the screen drawing for each mode. These are further subdivided by the screen _types_. diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_cjc_sampling.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_cjc_sampling.cpp new file mode 100644 index 000000000..efcd03a5b --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_cjc_sampling.cpp @@ -0,0 +1,12 @@ +#include "ui_drawing.hpp" +#ifdef OLED_128x32 +void ui_draw_cjc_sampling(const uint8_t num_dots) { + OLED::setCursor(0, 0); + OLED::print(translatedString(Tr->CJCCalibrating), FontStyle::SMALL); + OLED::setCursor(0, 8); + OLED::print(SmallSymbolDot, FontStyle::SMALL); + for (uint8_t x = 0; x < num_dots; x++) { + OLED::print(SmallSymbolDot, FontStyle::SMALL); + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_debug_menu.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_debug_menu.cpp new file mode 100644 index 000000000..5629e81dd --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_debug_menu.cpp @@ -0,0 +1,95 @@ +#include "OperatingModes.h" +#include "TipThermoModel.h" +#include "main.hpp" +#include "ui_drawing.hpp" + +#ifdef OLED_128x32 +extern osThreadId GUITaskHandle; +extern osThreadId MOVTaskHandle; +extern osThreadId PIDTaskHandle; + +void ui_draw_debug_menu(const uint8_t item_number) { + OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) + OLED::print(SmallSymbolVersionNumber, FontStyle::SMALL); // Print version number + OLED::setCursor(0, 8); // second line + OLED::print(DebugMenu[item_number], FontStyle::SMALL); + switch (item_number) { + case 0: // Build Date + break; + case 1: // Device ID + { + uint64_t id = getDeviceID(); +#ifdef DEVICE_HAS_VALIDATION_CODE + // If device has validation code; then we want to take over both lines of the screen + OLED::clearScreen(); // Ensure the buffer starts clean + OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) + OLED::print(DebugMenu[item_number], FontStyle::SMALL); + OLED::drawHex(getDeviceValidation(), FontStyle::SMALL, 8); + OLED::setCursor(0, 8); // second line +#endif + OLED::drawHex((uint32_t)(id >> 32), FontStyle::SMALL, 8); + OLED::drawHex((uint32_t)(id & 0xFFFFFFFF), FontStyle::SMALL, 8); + } break; + case 2: // ACC Type + OLED::print(AccelTypeNames[(int)DetectedAccelerometerVersion], FontStyle::SMALL); + break; + case 3: // Power Negotiation Status + OLED::print(PowerSourceNames[getPowerSourceNumber()], FontStyle::SMALL); + break; + case 4: // Input Voltage + printVoltage(); + break; + case 5: // Temp in °C + OLED::printNumber(TipThermoModel::getTipInC(), 6, FontStyle::SMALL); + break; + case 6: // Handle Temp in °C + OLED::printNumber(getHandleTemperature(0) / 10, 6, FontStyle::SMALL); + OLED::print(SmallSymbolDot, FontStyle::SMALL); + OLED::printNumber(getHandleTemperature(0) % 10, 1, FontStyle::SMALL); + break; + case 7: // Max Temp Limit in °C + OLED::printNumber(TipThermoModel::getTipMaxInC(), 6, FontStyle::SMALL); + break; + case 8: // System Uptime + OLED::printNumber(xTaskGetTickCount() / TICKS_100MS, 8, FontStyle::SMALL); + break; + case 9: // Movement Timestamp + OLED::printNumber(lastMovementTime / TICKS_100MS, 8, FontStyle::SMALL); + break; + case 10: // Tip Resistance in Ω + OLED::printNumber(getTipResistanceX10() / 10, 6, FontStyle::SMALL); // large to pad over so that we cover ID left overs + OLED::print(SmallSymbolDot, FontStyle::SMALL); + OLED::printNumber(getTipResistanceX10() % 10, 1, FontStyle::SMALL); + break; + case 11: // Raw Tip in µV + OLED::printNumber(TipThermoModel::convertTipRawADCTouV(getTipRawTemp(0), true), 8, FontStyle::SMALL); + break; + case 12: // Tip Cold Junction Compensation Offset in µV + OLED::printNumber(getSettingValue(SettingsOptions::CalibrationOffset), 8, FontStyle::SMALL); + break; + case 13: // High Water Mark for GUI + OLED::printNumber(uxTaskGetStackHighWaterMark(GUITaskHandle), 8, FontStyle::SMALL); + break; + case 14: // High Water Mark for Movement Task + OLED::printNumber(uxTaskGetStackHighWaterMark(MOVTaskHandle), 8, FontStyle::SMALL); + break; + case 15: // High Water Mark for PID Task + OLED::printNumber(uxTaskGetStackHighWaterMark(PIDTaskHandle), 8, FontStyle::SMALL); + break; + break; +#ifdef HALL_SENSOR + case 16: // Raw Hall Effect Value + { + int16_t hallEffectStrength = getRawHallEffect(); + if (hallEffectStrength < 0) { + hallEffectStrength = -hallEffectStrength; + } + OLED::printNumber(hallEffectStrength, 6, FontStyle::SMALL); + } break; +#endif + + default: + break; + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_homescreen_detailed.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_homescreen_detailed.cpp new file mode 100644 index 000000000..29beba17a --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_homescreen_detailed.cpp @@ -0,0 +1,57 @@ +#include "ui_drawing.hpp" +#ifdef OLED_128x32 + +extern uint8_t buttonAF[sizeof(buttonA)]; +extern uint8_t buttonBF[sizeof(buttonB)]; +extern uint8_t disconnectedTipF[sizeof(disconnectedTip)]; + +void ui_draw_homescreen_detailed(TemperatureType_t tipTemp) { + if (isTipDisconnected()) { + if (OLED::getRotation()) { + // in right handed mode we want to draw over the first part + OLED::drawArea(54, 0, 56, 32, disconnectedTipF); + } else { + OLED::drawArea(0, 0, 56, 32, disconnectedTip); + } + if (OLED::getRotation()) { + OLED::setCursor(-1, 0); + } else { + OLED::setCursor(56, 0); + } + uint32_t Vlt = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0); + OLED::printNumber(Vlt / 10, 2, FontStyle::LARGE); + OLED::print(LargeSymbolDot, FontStyle::LARGE); + OLED::printNumber(Vlt % 10, 1, FontStyle::LARGE); + if (OLED::getRotation()) { + OLED::setCursor(48, 8); + } else { + OLED::setCursor(91, 8); + } + OLED::print(SmallSymbolVolts, FontStyle::SMALL); + } else { + if (!(getSettingValue(SettingsOptions::CoolingTempBlink) && (tipTemp > 55) && (xTaskGetTickCount() % 1000 < 300))) { + // Blink temp if setting enable and temp < 55° + // 1000 tick/sec + // OFF 300ms ON 700ms + ui_draw_tip_temperature(true, FontStyle::LARGE); // draw in the temp + } + if (OLED::getRotation()) { + OLED::setCursor(6, 0); + } else { + OLED::setCursor(73, 0); // top right + } + // draw set temp + OLED::printNumber(getSettingValue(SettingsOptions::SolderingTemp), 3, FontStyle::SMALL); + + OLED::printSymbolDeg(FontStyle::SMALL); + + if (OLED::getRotation()) { + OLED::setCursor(0, 8); + } else { + OLED::setCursor(67, 8); // bottom right + } + printVoltage(); // draw voltage then symbol (v) + OLED::print(SmallSymbolVolts, FontStyle::SMALL); + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_homescreen_simplified.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_homescreen_simplified.cpp new file mode 100644 index 000000000..3c8c1816e --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_homescreen_simplified.cpp @@ -0,0 +1,62 @@ +#include "ui_drawing.hpp" + +#ifdef OLED_128x32 + +extern uint8_t buttonAF[sizeof(buttonA)]; +extern uint8_t buttonBF[sizeof(buttonB)]; +extern uint8_t disconnectedTipF[sizeof(disconnectedTip)]; + +void ui_draw_homescreen_simplified(TemperatureType_t tipTemp) { + bool tempOnDisplay = false; + bool tipDisconnectedDisplay = false; + if (OLED::getRotation()) { + OLED::drawArea(68, 0, 56, 32, buttonAF); + OLED::drawArea(12, 0, 56, 32, buttonBF); + OLED::setCursor(0, 0); + ui_draw_power_source_icon(); + } else { + OLED::drawArea(0, 0, 56, 32, buttonA); // Needs to be flipped so button ends up + OLED::drawArea(58, 0, 56, 32, buttonB); // on right side of screen + OLED::setCursor(116, 0); + ui_draw_power_source_icon(); + } + tipDisconnectedDisplay = false; + if (tipTemp > 55) { + tempOnDisplay = true; + } else if (tipTemp < 45) { + tempOnDisplay = false; + } + if (isTipDisconnected()) { + tempOnDisplay = false; + tipDisconnectedDisplay = true; + } + if (tempOnDisplay || tipDisconnectedDisplay) { + // draw temp over the start soldering button + // Location changes on screen rotation + if (OLED::getRotation()) { + // in right handed mode we want to draw over the first part + OLED::fillArea(68, 0, 56, 32, 0); // clear the area for the temp + OLED::setCursor(56, 0); + } else { + OLED::fillArea(0, 0, 56, 32, 0); // clear the area + OLED::setCursor(0, 0); + } + // If we have a tip connected draw the temp, if not we leave it blank + if (!tipDisconnectedDisplay) { + // draw in the temp + if (!(getSettingValue(SettingsOptions::CoolingTempBlink) && (xTaskGetTickCount() % 1000 < 300))) { + ui_draw_tip_temperature(false, FontStyle::LARGE); // draw in the temp + } + } else { + // Draw in missing tip symbol + if (OLED::getRotation()) { + // in right handed mode we want to draw over the first part + OLED::drawArea(54, 0, 56, 32, disconnectedTipF); + } else { + OLED::drawArea(0, 0, 56, 32, disconnectedTip); + } + } + } +} + +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_power_source_icon.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_power_source_icon.cpp new file mode 100644 index 000000000..a2fbec524 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_power_source_icon.cpp @@ -0,0 +1,43 @@ +#include "ui_drawing.hpp" +#ifdef OLED_128x32 +void ui_draw_power_source_icon(void) { +#if defined(POW_PD) || defined(POW_QC) || defined(POW_PD_EXT) + if (!getIsPoweredByDCIN()) { + // On non-DC inputs we replace this symbol with the voltage we are operating on + // If <9V then show single digit, if not show dual small ones vertically stacked + uint16_t V = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0); + if (V % 10 >= 5) { + V = (V / 10) + 1; // round up + } else { + V = V / 10; + } + int16_t xPos = OLED::getCursorX(); + OLED::printNumber(V / 10, 1, FontStyle::LARGE); + OLED::setCursor(xPos, 16); + OLED::printNumber(V % 10, 1, FontStyle::LARGE); + return; + } +#endif +#ifdef POW_DC + if (getSettingValue(SettingsOptions::MinDCVoltageCells)) { + // User is on a lithium battery + // we need to calculate which of the 10 levels they are on + uint8_t cellCount = getSettingValue(SettingsOptions::MinDCVoltageCells) + 2; + uint32_t cellV = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0) / cellCount; + // Should give us approx cell voltage X10 + // Range is 42 -> Minimum voltage setting (systemSettings.minVoltageCells) = 9 steps therefore we will use battery 0-9 + if (cellV < getSettingValue(SettingsOptions::MinVoltageCells)) { + cellV = getSettingValue(SettingsOptions::MinVoltageCells); + } + cellV -= getSettingValue(SettingsOptions::MinVoltageCells); // Should leave us a number of 0-9 + if (cellV > 9) { + cellV = 9; + } + OLED::drawBattery(cellV + 1); + } else { + OLED::drawSymbol(15); // Draw the DC Logo + } +#endif +} + +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_profile_advanced.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_profile_advanced.cpp new file mode 100644 index 000000000..cc8c99464 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_profile_advanced.cpp @@ -0,0 +1,59 @@ +#include "ui_drawing.hpp" + +#ifdef OLED_128x32 +void ui_draw_soldering_profile_advanced(TemperatureType_t tipTemp, TemperatureType_t profileCurrentTargetTemp, uint32_t phaseElapsedSeconds, uint32_t phase, const uint32_t phaseTimeGoal) { + // print temperature + if (OLED::getRotation()) { + OLED::setCursor(48, 0); + } else { + OLED::setCursor(0, 0); + } + + OLED::printNumber(tipTemp, 3, FontStyle::SMALL); + OLED::print(SmallSymbolSlash, FontStyle::SMALL); + OLED::printNumber(profileCurrentTargetTemp, 3, FontStyle::SMALL); + + if (getSettingValue(SettingsOptions::TemperatureInF)) { + OLED::print(SmallSymbolDegF, FontStyle::SMALL); + } else { + OLED::print(SmallSymbolDegC, FontStyle::SMALL); + } + + // print phase + if (phase > 0 && phase <= getSettingValue(SettingsOptions::ProfilePhases)) { + if (OLED::getRotation()) { + OLED::setCursor(36, 0); + } else { + OLED::setCursor(55, 0); + } + OLED::printNumber(phase, 1, FontStyle::SMALL); + } + + // print time progress / preheat / cooldown + if (OLED::getRotation()) { + OLED::setCursor(42, 16); + } else { + OLED::setCursor(0, 16); + } + + if (phase == 0) { + OLED::print(translatedString(Tr->ProfilePreheatString), FontStyle::SMALL); + } else if (phase > getSettingValue(SettingsOptions::ProfilePhases)) { + OLED::print(translatedString(Tr->ProfileCooldownString), FontStyle::SMALL); + } else { + OLED::printNumber(phaseElapsedSeconds / 60, 1, FontStyle::SMALL); + OLED::print(SmallSymbolColon, FontStyle::SMALL); + OLED::printNumber(phaseElapsedSeconds % 60, 2, FontStyle::SMALL, false); + + OLED::print(SmallSymbolSlash, FontStyle::SMALL); + + // blink if we can't keep up with the time goal + if (phaseElapsedSeconds < phaseTimeGoal + 2 || (xTaskGetTickCount() / TICKS_SECOND) % 2 == 0) { + OLED::printNumber(phaseTimeGoal / 60, 1, FontStyle::SMALL); + OLED::print(SmallSymbolColon, FontStyle::SMALL); + OLED::printNumber(phaseTimeGoal % 60, 2, FontStyle::SMALL, false); + } + } +} + +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_soldering_basic_status.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_soldering_basic_status.cpp new file mode 100644 index 000000000..d01dcac43 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_soldering_basic_status.cpp @@ -0,0 +1,45 @@ +#include "power.hpp" +#include "ui_drawing.hpp" +#ifdef OLED_128x32 + +void ui_draw_soldering_basic_status(bool boostModeOn) { + OLED::setCursor(0, 0); + // We switch the layout direction depending on the orientation of the oled + if (OLED::getRotation()) { + // battery + ui_draw_power_source_icon(); + // Space out gap between battery <-> temp + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + // Draw current tip temp + ui_draw_tip_temperature(true, FontStyle::LARGE); + + // We draw boost arrow if boosting, + // or else gap temp <-> heat indicator + if (boostModeOn) { + OLED::drawSymbol(2); + } else { + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + } + + // Draw heating/cooling symbols + OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average())); + } else { + // Draw heating/cooling symbols + OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average())); + // We draw boost arrow if boosting, + // or else gap temp <-> heat indicator + if (boostModeOn) { + OLED::drawSymbol(2); + } else { + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + } + // Draw current tip temp + ui_draw_tip_temperature(true, FontStyle::LARGE); + // Space out gap between battery <-> temp + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + + ui_draw_power_source_icon(); + } +} + +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_soldering_power_status.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_soldering_power_status.cpp new file mode 100644 index 000000000..0b86a5976 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_soldering_power_status.cpp @@ -0,0 +1,69 @@ +#include "power.hpp" +#include "ui_drawing.hpp" +#include +#ifdef OLED_128x32 + +void ui_draw_soldering_power_status(bool boost_mode_on) { + if (OLED::getRotation()) { + OLED::setCursor(50, 0); + } else { + OLED::setCursor(-1, 0); + } + + ui_draw_tip_temperature(true, FontStyle::LARGE); + + if (boost_mode_on) { // Boost mode is on + if (OLED::getRotation()) { + OLED::setCursor(34, 0); + } else { + OLED::setCursor(50, 0); + } + OLED::print(LargeSymbolPlus, FontStyle::LARGE); + } else { +#ifndef NO_SLEEP_MODE + if (getSettingValue(SettingsOptions::Sensitivity) && getSettingValue(SettingsOptions::SleepTime)) { + if (OLED::getRotation()) { + OLED::setCursor(32, 0); + } else { + OLED::setCursor(47, 0); + } + printCountdownUntilSleep(getSleepTimeout()); + } +#endif + if (OLED::getRotation()) { + OLED::setCursor(32, 8); + } else { + OLED::setCursor(47, 8); + } + OLED::print(PowerSourceNames[getPowerSourceNumber()], FontStyle::SMALL, 2); + } + + if (OLED::getRotation()) { + OLED::setCursor(0, 0); + } else { + OLED::setCursor(67, 0); + } + // Print wattage + { + uint32_t x10Watt = x10WattHistory.average(); + if (x10Watt > 999) { + // If we exceed 99.9W we drop the decimal place to keep it all fitting + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + OLED::printNumber(x10WattHistory.average() / 10, 3, FontStyle::SMALL); + } else { + OLED::printNumber(x10WattHistory.average() / 10, 2, FontStyle::SMALL); + OLED::print(SmallSymbolDot, FontStyle::SMALL); + OLED::printNumber(x10WattHistory.average() % 10, 1, FontStyle::SMALL); + } + OLED::print(SmallSymbolWatts, FontStyle::SMALL); + } + + if (OLED::getRotation()) { + OLED::setCursor(0, 8); + } else { + OLED::setCursor(67, 8); + } + printVoltage(); + OLED::print(SmallSymbolVolts, FontStyle::SMALL); +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_soldering_sleep_mode.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_soldering_sleep_mode.cpp new file mode 100644 index 000000000..c483a26b4 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_soldering_sleep_mode.cpp @@ -0,0 +1,36 @@ +#include "ui_drawing.hpp" + +#ifdef OLED_128x32 +void ui_draw_soldering_detailed_sleep(TemperatureType_t tipTemp) { + + OLED::clearScreen(); + OLED::setCursor(0, 0); + OLED::print(translatedString(Tr->SleepingAdvancedString), FontStyle::SMALL); + OLED::setCursor(0, 8); + OLED::print(translatedString(Tr->SleepingTipAdvancedString), FontStyle::SMALL); + OLED::printNumber(tipTemp, 3, FontStyle::SMALL); + if (getSettingValue(SettingsOptions::TemperatureInF)) { + OLED::print(SmallSymbolDegF, FontStyle::SMALL); + } else { + OLED::print(SmallSymbolDegC, FontStyle::SMALL); + } + + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + printVoltage(); + OLED::print(SmallSymbolVolts, FontStyle::SMALL); + + OLED::refresh(); +} + +void ui_draw_soldering_basic_sleep(TemperatureType_t tipTemp) { + + OLED::clearScreen(); + OLED::setCursor(0, 0); + + OLED::print(LargeSymbolSleep, FontStyle::LARGE); + OLED::printNumber(tipTemp, 3, FontStyle::LARGE); + OLED::printSymbolDeg(FontStyle::EXTRAS); + + OLED::refresh(); +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_temperature_change.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_temperature_change.cpp new file mode 100644 index 000000000..f0f5f9229 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_temperature_change.cpp @@ -0,0 +1,23 @@ +#include "ui_drawing.hpp" + +#ifdef OLED_128x32 +void ui_draw_temperature_change(void) { + + OLED::setCursor(8, 8); + if (OLED::getRotation()) { + OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolPlus : LargeSymbolMinus, FontStyle::LARGE); + } else { + OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolMinus : LargeSymbolPlus, FontStyle::LARGE); + } + + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + OLED::printNumber(getSettingValue(SettingsOptions::SolderingTemp), 3, FontStyle::LARGE); + OLED::printSymbolDeg(FontStyle::EXTRAS); + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + if (OLED::getRotation()) { + OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolMinus : LargeSymbolPlus, FontStyle::LARGE); + } else { + OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolPlus : LargeSymbolMinus, FontStyle::LARGE); + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_tip_temperature.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_tip_temperature.cpp new file mode 100644 index 000000000..35058e0d0 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_tip_temperature.cpp @@ -0,0 +1,17 @@ +#include "OperatingModeUtilities.h" +#include "OperatingModes.h" +#include "SolderingCommon.h" +#include "TipThermoModel.h" +#ifdef OLED_128x32 + +void ui_draw_tip_temperature(bool symbol, const FontStyle font) { + // Draw tip temp handling unit conversion & tolerance near setpoint + TemperatureType_t Temp = getTipTemp(); + + OLED::printNumber(Temp, 3, font); // Draw the tip temp out + if (symbol) { + // For big font, can draw nice symbols, otherwise fall back to chars + OLED::printSymbolDeg(font == FontStyle::LARGE ? FontStyle::EXTRAS : font); + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_usb_pd_debug.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_usb_pd_debug.cpp new file mode 100644 index 000000000..e7a3a5a57 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_usb_pd_debug.cpp @@ -0,0 +1,45 @@ +#include "ui_drawing.hpp" +#ifdef OLED_128x32 + +void ui_draw_usb_pd_debug_state(const uint16_t vbus_sense_state, const uint8_t stateNumber) { + OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) + OLED::print(SmallSymbolPDDebug, FontStyle::SMALL); // Print Title + OLED::setCursor(0, 8); // second line + // Print the PD state machine + OLED::print(SmallSymbolState, FontStyle::SMALL); + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + OLED::printNumber(stateNumber, 2, FontStyle::SMALL, true); + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + + if (vbus_sense_state == 2) { + OLED::print(SmallSymbolNoVBus, FontStyle::SMALL); + } else if (vbus_sense_state == 1) { + OLED::print(SmallSymbolVBus, FontStyle::SMALL); + } +} + +void ui_draw_usb_pd_debug_pdo(const uint8_t entry_num, const uint16_t min_voltage, const uint16_t max_voltage, const uint16_t current_a_x100, const uint16_t wattage) { + + OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) + OLED::print(SmallSymbolPDDebug, FontStyle::SMALL); // Print Title + OLED::setCursor(0, 8); // second line + OLED::printNumber(entry_num, 2, FontStyle::SMALL, true); // print the entry number + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + if (min_voltage > 0) { + OLED::printNumber(min_voltage, 2, FontStyle::SMALL, true); // print the voltage + OLED::print(SmallSymbolMinus, FontStyle::SMALL); + } + OLED::printNumber(max_voltage, 2, FontStyle::SMALL, true); // print the voltage + OLED::print(SmallSymbolVolts, FontStyle::SMALL); + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + if (wattage) { + OLED::printNumber(wattage, 3, FontStyle::SMALL, true); // print the current in 0.1A res + OLED::print(SmallSymbolWatts, FontStyle::SMALL); + } else { + OLED::printNumber(current_a_x100 / 100, 2, FontStyle::SMALL, true); // print the current in 0.1A res + OLED::print(SmallSymbolDot, FontStyle::SMALL); + OLED::printNumber(current_a_x100 % 100, 2, FontStyle::SMALL, false); // print the current in 0.1A res + OLED::print(SmallSymbolAmps, FontStyle::SMALL); + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/draw_warning_undervoltage.cpp b/source/Core/Threads/UI/drawing/mono_128x32/draw_warning_undervoltage.cpp new file mode 100644 index 000000000..99d44b612 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/draw_warning_undervoltage.cpp @@ -0,0 +1,21 @@ +#include "ui_drawing.hpp" +#ifdef OLED_128x32 + +void ui_draw_warning_undervoltage(void) { + OLED::clearScreen(); + OLED::setCursor(0, 0); + if (getSettingValue(SettingsOptions::DetailedSoldering)) { + OLED::print(translatedString(Tr->UndervoltageString), FontStyle::SMALL); + OLED::setCursor(0, 8); + OLED::print(translatedString(Tr->InputVoltageString), FontStyle::SMALL); + printVoltage(); + OLED::print(SmallSymbolVolts, FontStyle::SMALL); + } else { + OLED::print(translatedString(Tr->UVLOWarningString), FontStyle::LARGE); + } + + OLED::refresh(); + GUIDelay(); + waitForButtonPress(); +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/pre_render_assets.cpp b/source/Core/Threads/UI/drawing/mono_128x32/pre_render_assets.cpp new file mode 100644 index 000000000..dcdf8ad94 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/pre_render_assets.cpp @@ -0,0 +1,19 @@ +#include "ui_drawing.hpp" +#ifdef OLED_128x32 + +uint8_t buttonAF[sizeof(buttonA)]; +uint8_t buttonBF[sizeof(buttonB)]; +uint8_t disconnectedTipF[sizeof(disconnectedTip)]; + +void ui_pre_render_assets(void) { + // Generate the flipped screen into ram for later use + // flipped is generated by flipping each row + for (int row = 0; row < 4; row++) { + for (int x = 0; x < 56; x++) { + buttonAF[(row * 56) + x] = buttonA[(row * 56) + (41 - x)]; + buttonBF[(row * 56) + x] = buttonB[(row * 56) + (41 - x)]; + disconnectedTipF[(row * 56) + x] = disconnectedTip[(row * 56) + (41 - x)]; + } + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/printSleepCountdown.cpp b/source/Core/Threads/UI/drawing/mono_128x32/printSleepCountdown.cpp new file mode 100644 index 000000000..09386e68d --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/printSleepCountdown.cpp @@ -0,0 +1,22 @@ +#include "Buttons.hpp" +#include "OperatingModeUtilities.h" +#ifdef OLED_128x32 +extern TickType_t lastMovementTime; +#ifndef NO_SLEEP_MODE +void printCountdownUntilSleep(int sleepThres) { + /* + * Print seconds or minutes (if > 99 seconds) until sleep + * mode is triggered. + */ + TickType_t lastEventTime = lastButtonTime < lastMovementTime ? lastMovementTime : lastButtonTime; + TickType_t downCount = sleepThres - xTaskGetTickCount() + lastEventTime; + if (downCount > (99 * TICKS_SECOND)) { + OLED::printNumber(downCount / 60000 + 1, 2, FontStyle::SMALL); + OLED::print(SmallSymbolMinutes, FontStyle::SMALL); + } else { + OLED::printNumber(downCount / 1000 + 1, 2, FontStyle::SMALL); + OLED::print(SmallSymbolSeconds, FontStyle::SMALL); + } +} +#endif +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/print_voltage.cpp b/source/Core/Threads/UI/drawing/mono_128x32/print_voltage.cpp new file mode 100644 index 000000000..dad7b62a4 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/print_voltage.cpp @@ -0,0 +1,10 @@ +#include "ui_drawing.hpp" +#ifdef OLED_128x32 + +void printVoltage(void) { + uint32_t volt = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0); + OLED::printNumber(volt / 10, 2, FontStyle::SMALL); + OLED::print(SmallSymbolDot, FontStyle::SMALL); + OLED::printNumber(volt % 10, 1, FontStyle::SMALL); +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_128x32/show_warning.cpp b/source/Core/Threads/UI/drawing/mono_128x32/show_warning.cpp new file mode 100644 index 000000000..22ae2674d --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_128x32/show_warning.cpp @@ -0,0 +1,14 @@ +#include "Buttons.hpp" +#include "OperatingModeUtilities.h" +#include "OperatingModes.h" +#ifdef OLED_128x32 +bool warnUser(const char *warning, const ButtonState buttons) { + OLED::clearScreen(); + OLED::printWholeScreen(warning); + // Also timeout after 5 seconds + if ((xTaskGetTickCount() - lastButtonTime) > TICKS_SECOND * 5) { + return true; + } + return buttons != BUTTON_NONE; +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_cjc_sampling.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_cjc_sampling.cpp new file mode 100644 index 000000000..f795945a4 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_cjc_sampling.cpp @@ -0,0 +1,13 @@ +#include "ui_drawing.hpp" + +#ifdef OLED_96x16 +void ui_draw_cjc_sampling(const uint8_t num_dots) { + OLED::setCursor(0, 0); + OLED::print(translatedString(Tr->CJCCalibrating), FontStyle::SMALL); + OLED::setCursor(0, 8); + OLED::print(SmallSymbolDot, FontStyle::SMALL); + for (uint8_t x = 0; x < num_dots; x++) { + OLED::print(SmallSymbolDot, FontStyle::SMALL); + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_debug_menu.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_debug_menu.cpp new file mode 100644 index 000000000..3b5ec3229 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_debug_menu.cpp @@ -0,0 +1,94 @@ +#include "OperatingModes.h" +#include "TipThermoModel.h" +#include "main.hpp" +#include "ui_drawing.hpp" +#ifdef OLED_96x16 +extern osThreadId GUITaskHandle; +extern osThreadId MOVTaskHandle; +extern osThreadId PIDTaskHandle; + +void ui_draw_debug_menu(const uint8_t item_number) { + OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) + OLED::print(SmallSymbolVersionNumber, FontStyle::SMALL); // Print version number + OLED::setCursor(0, 8); // second line + OLED::print(DebugMenu[item_number], FontStyle::SMALL); + switch (item_number) { + case 0: // Build Date + break; + case 1: // Device ID + { + uint64_t id = getDeviceID(); +#ifdef DEVICE_HAS_VALIDATION_CODE + // If device has validation code; then we want to take over both lines of the screen + OLED::clearScreen(); // Ensure the buffer starts clean + OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) + OLED::print(DebugMenu[item_number], FontStyle::SMALL); + OLED::drawHex(getDeviceValidation(), FontStyle::SMALL, 8); + OLED::setCursor(0, 8); // second line +#endif + OLED::drawHex((uint32_t)(id >> 32), FontStyle::SMALL, 8); + OLED::drawHex((uint32_t)(id & 0xFFFFFFFF), FontStyle::SMALL, 8); + } break; + case 2: // ACC Type + OLED::print(AccelTypeNames[(int)DetectedAccelerometerVersion], FontStyle::SMALL); + break; + case 3: // Power Negotiation Status + OLED::print(PowerSourceNames[getPowerSourceNumber()], FontStyle::SMALL); + break; + case 4: // Input Voltage + printVoltage(); + break; + case 5: // Temp in °C + OLED::printNumber(TipThermoModel::getTipInC(), 6, FontStyle::SMALL); + break; + case 6: // Handle Temp in °C + OLED::printNumber(getHandleTemperature(0) / 10, 6, FontStyle::SMALL); + OLED::print(SmallSymbolDot, FontStyle::SMALL); + OLED::printNumber(getHandleTemperature(0) % 10, 1, FontStyle::SMALL); + break; + case 7: // Max Temp Limit in °C + OLED::printNumber(TipThermoModel::getTipMaxInC(), 6, FontStyle::SMALL); + break; + case 8: // System Uptime + OLED::printNumber(xTaskGetTickCount() / TICKS_100MS, 8, FontStyle::SMALL); + break; + case 9: // Movement Timestamp + OLED::printNumber(lastMovementTime / TICKS_100MS, 8, FontStyle::SMALL); + break; + case 10: // Tip Resistance in Ω + OLED::printNumber(getTipResistanceX10() / 10, 6, FontStyle::SMALL); // large to pad over so that we cover ID left overs + OLED::print(SmallSymbolDot, FontStyle::SMALL); + OLED::printNumber(getTipResistanceX10() % 10, 1, FontStyle::SMALL); + break; + case 11: // Raw Tip in µV + OLED::printNumber(TipThermoModel::convertTipRawADCTouV(getTipRawTemp(0), true), 8, FontStyle::SMALL); + break; + case 12: // Tip Cold Junction Compensation Offset in µV + OLED::printNumber(getSettingValue(SettingsOptions::CalibrationOffset), 8, FontStyle::SMALL); + break; + case 13: // High Water Mark for GUI + OLED::printNumber(uxTaskGetStackHighWaterMark(GUITaskHandle), 8, FontStyle::SMALL); + break; + case 14: // High Water Mark for Movement Task + OLED::printNumber(uxTaskGetStackHighWaterMark(MOVTaskHandle), 8, FontStyle::SMALL); + break; + case 15: // High Water Mark for PID Task + OLED::printNumber(uxTaskGetStackHighWaterMark(PIDTaskHandle), 8, FontStyle::SMALL); + break; + break; +#ifdef HALL_SENSOR + case 16: // Raw Hall Effect Value + { + int16_t hallEffectStrength = getRawHallEffect(); + if (hallEffectStrength < 0) { + hallEffectStrength = -hallEffectStrength; + } + OLED::printNumber(hallEffectStrength, 6, FontStyle::SMALL); + } break; +#endif + + default: + break; + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_homescreen_detailed.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_homescreen_detailed.cpp new file mode 100644 index 000000000..62c4a40f8 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_homescreen_detailed.cpp @@ -0,0 +1,57 @@ +#include "ui_drawing.hpp" +#ifdef OLED_96x16 + +extern uint8_t buttonAF[sizeof(buttonA)]; +extern uint8_t buttonBF[sizeof(buttonB)]; +extern uint8_t disconnectedTipF[sizeof(disconnectedTip)]; + +void ui_draw_homescreen_detailed(TemperatureType_t tipTemp) { + if (isTipDisconnected()) { + if (OLED::getRotation()) { + // in right handed mode we want to draw over the first part + OLED::drawArea(54, 0, 42, 16, disconnectedTipF); + } else { + OLED::drawArea(0, 0, 42, 16, disconnectedTip); + } + if (OLED::getRotation()) { + OLED::setCursor(-1, 0); + } else { + OLED::setCursor(42, 0); + } + uint32_t Vlt = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0); + OLED::printNumber(Vlt / 10, 2, FontStyle::LARGE); + OLED::print(LargeSymbolDot, FontStyle::LARGE); + OLED::printNumber(Vlt % 10, 1, FontStyle::LARGE); + if (OLED::getRotation()) { + OLED::setCursor(48, 8); + } else { + OLED::setCursor(91, 8); + } + OLED::print(SmallSymbolVolts, FontStyle::SMALL); + } else { + if (!(getSettingValue(SettingsOptions::CoolingTempBlink) && (tipTemp > 55) && (xTaskGetTickCount() % 1000 < 300))) { + // Blink temp if setting enable and temp < 55° + // 1000 tick/sec + // OFF 300ms ON 700ms + ui_draw_tip_temperature(true, FontStyle::LARGE); // draw in the temp + } + if (OLED::getRotation()) { + OLED::setCursor(6, 0); + } else { + OLED::setCursor(73, 0); // top right + } + // draw set temp + OLED::printNumber(getSettingValue(SettingsOptions::SolderingTemp), 3, FontStyle::SMALL); + + OLED::printSymbolDeg(FontStyle::SMALL); + + if (OLED::getRotation()) { + OLED::setCursor(0, 8); + } else { + OLED::setCursor(67, 8); // bottom right + } + printVoltage(); // draw voltage then symbol (v) + OLED::print(SmallSymbolVolts, FontStyle::SMALL); + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_homescreen_simplified.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_homescreen_simplified.cpp new file mode 100644 index 000000000..0376c1313 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_homescreen_simplified.cpp @@ -0,0 +1,62 @@ +#include "ui_drawing.hpp" + +#ifdef OLED_96x16 +extern uint8_t buttonAF[sizeof(buttonA)]; +extern uint8_t buttonBF[sizeof(buttonB)]; +extern uint8_t disconnectedTipF[sizeof(disconnectedTip)]; + +void ui_draw_homescreen_simplified(TemperatureType_t tipTemp) { + bool tempOnDisplay = false; + bool tipDisconnectedDisplay = false; + if (OLED::getRotation()) { + OLED::drawArea(54, 0, 42, 16, buttonAF); + OLED::drawArea(12, 0, 42, 16, buttonBF); + OLED::setCursor(0, 0); + ui_draw_power_source_icon(); + } else { + OLED::drawArea(0, 0, 42, 16, buttonA); // Needs to be flipped so button ends up + OLED::drawArea(42, 0, 42, 16, buttonB); // on right side of screen + OLED::setCursor(84, 0); + ui_draw_power_source_icon(); + } + tipDisconnectedDisplay = false; + if (tipTemp > 55) { + tempOnDisplay = true; + } else if (tipTemp < 45) { + tempOnDisplay = false; + } + if (isTipDisconnected()) { + tempOnDisplay = false; + tipDisconnectedDisplay = true; + } + if (tempOnDisplay || tipDisconnectedDisplay) { + // draw temp over the start soldering button + // Location changes on screen rotation + if (OLED::getRotation()) { + // in right handed mode we want to draw over the first part + OLED::fillArea(55, 0, 41, 16, 0); // clear the area for the temp + OLED::setCursor(56, 0); + } else { + OLED::fillArea(0, 0, 41, 16, 0); // clear the area + OLED::setCursor(0, 0); + } + // If we have a tip connected draw the temp, if not we leave it blank + if (!tipDisconnectedDisplay) { + // draw in the temp + if (!(getSettingValue(SettingsOptions::CoolingTempBlink) && (xTaskGetTickCount() % 1000 < 300))) { + ui_draw_tip_temperature(false, FontStyle::LARGE); // draw in the temp + } + } else { + // Draw in missing tip symbol + + if (OLED::getRotation()) { + // in right handed mode we want to draw over the first part + OLED::drawArea(54, 0, 42, 16, disconnectedTipF); + } else { + OLED::drawArea(0, 0, 42, 16, disconnectedTip); + } + } + } +} + +#endif \ No newline at end of file diff --git a/source/Core/Threads/OperatingModes/utils/drawPowerSourceIcon.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_power_source_icon.cpp similarity index 95% rename from source/Core/Threads/OperatingModes/utils/drawPowerSourceIcon.cpp rename to source/Core/Threads/UI/drawing/mono_96x16/draw_power_source_icon.cpp index c296b5336..427dd58c0 100644 --- a/source/Core/Threads/OperatingModes/utils/drawPowerSourceIcon.cpp +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_power_source_icon.cpp @@ -1,6 +1,7 @@ -#include "OperatingModeUtilities.h" +#include "ui_drawing.hpp" +#ifdef OLED_96x16 -void gui_drawBatteryIcon(void) { +void ui_draw_power_source_icon(void) { #if defined(POW_PD) || defined(POW_QC) || defined(POW_PD_EXT) if (!getIsPoweredByDCIN()) { // On non-DC inputs we replace this symbol with the voltage we are operating on @@ -44,3 +45,5 @@ void gui_drawBatteryIcon(void) { } #endif } + +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_profile_advanced.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_profile_advanced.cpp new file mode 100644 index 000000000..f3f3e53fd --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_profile_advanced.cpp @@ -0,0 +1,59 @@ +#include "ui_drawing.hpp" +#ifdef OLED_96x16 + +void ui_draw_soldering_profile_advanced(TemperatureType_t tipTemp, TemperatureType_t profileCurrentTargetTemp, uint32_t phaseElapsedSeconds, uint32_t phase, const uint32_t phaseTimeGoal) { + // print temperature + if (OLED::getRotation()) { + OLED::setCursor(48, 0); + } else { + OLED::setCursor(0, 0); + } + + OLED::printNumber(tipTemp, 3, FontStyle::SMALL); + OLED::print(SmallSymbolSlash, FontStyle::SMALL); + OLED::printNumber(profileCurrentTargetTemp, 3, FontStyle::SMALL); + + if (getSettingValue(SettingsOptions::TemperatureInF)) { + OLED::print(SmallSymbolDegF, FontStyle::SMALL); + } else { + OLED::print(SmallSymbolDegC, FontStyle::SMALL); + } + + // print phase + if (phase > 0 && phase <= getSettingValue(SettingsOptions::ProfilePhases)) { + if (OLED::getRotation()) { + OLED::setCursor(36, 0); + } else { + OLED::setCursor(55, 0); + } + OLED::printNumber(phase, 1, FontStyle::SMALL); + } + + // print time progress / preheat / cooldown + if (OLED::getRotation()) { + OLED::setCursor(42, 8); + } else { + OLED::setCursor(0, 8); + } + + if (phase == 0) { + OLED::print(translatedString(Tr->ProfilePreheatString), FontStyle::SMALL); + } else if (phase > getSettingValue(SettingsOptions::ProfilePhases)) { + OLED::print(translatedString(Tr->ProfileCooldownString), FontStyle::SMALL); + } else { + OLED::printNumber(phaseElapsedSeconds / 60, 1, FontStyle::SMALL); + OLED::print(SmallSymbolColon, FontStyle::SMALL); + OLED::printNumber(phaseElapsedSeconds % 60, 2, FontStyle::SMALL, false); + + OLED::print(SmallSymbolSlash, FontStyle::SMALL); + + // blink if we can't keep up with the time goal + if (phaseElapsedSeconds < phaseTimeGoal + 2 || (xTaskGetTickCount() / TICKS_SECOND) % 2 == 0) { + OLED::printNumber(phaseTimeGoal / 60, 1, FontStyle::SMALL); + OLED::print(SmallSymbolColon, FontStyle::SMALL); + OLED::printNumber(phaseTimeGoal % 60, 2, FontStyle::SMALL, false); + } + } +} + +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_soldering_basic_status.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_soldering_basic_status.cpp new file mode 100644 index 000000000..1482bf7d8 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_soldering_basic_status.cpp @@ -0,0 +1,44 @@ +#include "power.hpp" +#include "ui_drawing.hpp" +#ifdef OLED_96x16 + +void ui_draw_soldering_basic_status(bool boostModeOn) { + OLED::setCursor(0, 0); + // We switch the layout direction depending on the orientation of the oled + if (OLED::getRotation()) { + // battery + ui_draw_power_source_icon(); + // Space out gap between battery <-> temp + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + // Draw current tip temp + ui_draw_tip_temperature(true, FontStyle::LARGE); + + // We draw boost arrow if boosting, + // or else gap temp <-> heat indicator + if (boostModeOn) { + OLED::drawSymbol(2); + } else { + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + } + + // Draw heating/cooling symbols + OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average())); + } else { + // Draw heating/cooling symbols + OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average())); + // We draw boost arrow if boosting, + // or else gap temp <-> heat indicator + if (boostModeOn) { + OLED::drawSymbol(2); + } else { + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + } + // Draw current tip temp + ui_draw_tip_temperature(true, FontStyle::LARGE); + // Space out gap between battery <-> temp + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + + ui_draw_power_source_icon(); + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_soldering_power_status.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_soldering_power_status.cpp new file mode 100644 index 000000000..f225d37dd --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_soldering_power_status.cpp @@ -0,0 +1,69 @@ +#include "power.hpp" +#include "ui_drawing.hpp" +#include +#ifdef OLED_96x16 + +void ui_draw_soldering_power_status(bool boost_mode_on) { + if (OLED::getRotation()) { + OLED::setCursor(50, 0); + } else { + OLED::setCursor(-1, 0); + } + + ui_draw_tip_temperature(true, FontStyle::LARGE); + + if (boost_mode_on) { // Boost mode is on + if (OLED::getRotation()) { + OLED::setCursor(34, 0); + } else { + OLED::setCursor(50, 0); + } + OLED::print(LargeSymbolPlus, FontStyle::LARGE); + } else { +#ifndef NO_SLEEP_MODE + if (getSettingValue(SettingsOptions::Sensitivity) && getSettingValue(SettingsOptions::SleepTime)) { + if (OLED::getRotation()) { + OLED::setCursor(32, 0); + } else { + OLED::setCursor(47, 0); + } + printCountdownUntilSleep(getSleepTimeout()); + } +#endif + if (OLED::getRotation()) { + OLED::setCursor(32, 8); + } else { + OLED::setCursor(47, 8); + } + OLED::print(PowerSourceNames[getPowerSourceNumber()], FontStyle::SMALL, 2); + } + + if (OLED::getRotation()) { + OLED::setCursor(0, 0); + } else { + OLED::setCursor(67, 0); + } + // Print wattage + { + uint32_t x10Watt = x10WattHistory.average(); + if (x10Watt > 999) { + // If we exceed 99.9W we drop the decimal place to keep it all fitting + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + OLED::printNumber(x10WattHistory.average() / 10, 3, FontStyle::SMALL); + } else { + OLED::printNumber(x10WattHistory.average() / 10, 2, FontStyle::SMALL); + OLED::print(SmallSymbolDot, FontStyle::SMALL); + OLED::printNumber(x10WattHistory.average() % 10, 1, FontStyle::SMALL); + } + OLED::print(SmallSymbolWatts, FontStyle::SMALL); + } + + if (OLED::getRotation()) { + OLED::setCursor(0, 8); + } else { + OLED::setCursor(67, 8); + } + printVoltage(); + OLED::print(SmallSymbolVolts, FontStyle::SMALL); +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_soldering_sleep_mode.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_soldering_sleep_mode.cpp new file mode 100644 index 000000000..04b5a5bb0 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_soldering_sleep_mode.cpp @@ -0,0 +1,36 @@ +#include "ui_drawing.hpp" +#ifdef OLED_96x16 + +void ui_draw_soldering_detailed_sleep(TemperatureType_t tipTemp) { + + OLED::clearScreen(); + OLED::setCursor(0, 0); + OLED::print(translatedString(Tr->SleepingAdvancedString), FontStyle::SMALL); + OLED::setCursor(0, 8); + OLED::print(translatedString(Tr->SleepingTipAdvancedString), FontStyle::SMALL); + OLED::printNumber(tipTemp, 3, FontStyle::SMALL); + if (getSettingValue(SettingsOptions::TemperatureInF)) { + OLED::print(SmallSymbolDegF, FontStyle::SMALL); + } else { + OLED::print(SmallSymbolDegC, FontStyle::SMALL); + } + + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + printVoltage(); + OLED::print(SmallSymbolVolts, FontStyle::SMALL); + + OLED::refresh(); +} + +void ui_draw_soldering_basic_sleep(TemperatureType_t tipTemp) { + + OLED::clearScreen(); + OLED::setCursor(0, 0); + + OLED::print(LargeSymbolSleep, FontStyle::LARGE); + OLED::printNumber(tipTemp, 3, FontStyle::LARGE); + OLED::printSymbolDeg(FontStyle::EXTRAS); + + OLED::refresh(); +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_temperature_change.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_temperature_change.cpp new file mode 100644 index 000000000..48475bc1d --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_temperature_change.cpp @@ -0,0 +1,23 @@ +#include "ui_drawing.hpp" +#ifdef OLED_96x16 + +void ui_draw_temperature_change(void) { + + OLED::setCursor(0, 0); + if (OLED::getRotation()) { + OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolPlus : LargeSymbolMinus, FontStyle::LARGE); + } else { + OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolMinus : LargeSymbolPlus, FontStyle::LARGE); + } + + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + OLED::printNumber(getSettingValue(SettingsOptions::SolderingTemp), 3, FontStyle::LARGE); + OLED::printSymbolDeg(FontStyle::EXTRAS); + OLED::print(LargeSymbolSpace, FontStyle::LARGE); + if (OLED::getRotation()) { + OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolMinus : LargeSymbolPlus, FontStyle::LARGE); + } else { + OLED::print(getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled) ? LargeSymbolPlus : LargeSymbolMinus, FontStyle::LARGE); + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/OperatingModes/utils/DrawTipTemperature.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_tip_temperature.cpp similarity index 78% rename from source/Core/Threads/OperatingModes/utils/DrawTipTemperature.cpp rename to source/Core/Threads/UI/drawing/mono_96x16/draw_tip_temperature.cpp index 7e5cff175..2f2de83d0 100644 --- a/source/Core/Threads/OperatingModes/utils/DrawTipTemperature.cpp +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_tip_temperature.cpp @@ -1,8 +1,10 @@ #include "OperatingModeUtilities.h" #include "OperatingModes.h" +#include "SolderingCommon.h" #include "TipThermoModel.h" +#ifdef OLED_96x16 -void gui_drawTipTemp(bool symbol, const FontStyle font) { +void ui_draw_tip_temperature(bool symbol, const FontStyle font) { // Draw tip temp handling unit conversion & tolerance near setpoint TemperatureType_t Temp = getTipTemp(); @@ -12,3 +14,4 @@ void gui_drawTipTemp(bool symbol, const FontStyle font) { OLED::printSymbolDeg(font == FontStyle::LARGE ? FontStyle::EXTRAS : font); } } +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_usb_pd_debug.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_usb_pd_debug.cpp new file mode 100644 index 000000000..d6bb24c4b --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_usb_pd_debug.cpp @@ -0,0 +1,45 @@ +#include "ui_drawing.hpp" +#ifdef OLED_96x16 + +void ui_draw_usb_pd_debug_state(const uint16_t vbus_sense_state, const uint8_t stateNumber) { + OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) + OLED::print(SmallSymbolPDDebug, FontStyle::SMALL); // Print Title + OLED::setCursor(0, 8); // second line + // Print the PD state machine + OLED::print(SmallSymbolState, FontStyle::SMALL); + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + OLED::printNumber(stateNumber, 2, FontStyle::SMALL, true); + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + + if (vbus_sense_state == 2) { + OLED::print(SmallSymbolNoVBus, FontStyle::SMALL); + } else if (vbus_sense_state == 1) { + OLED::print(SmallSymbolVBus, FontStyle::SMALL); + } +} + +void ui_draw_usb_pd_debug_pdo(const uint8_t entry_num, const uint16_t min_voltage, const uint16_t max_voltage, const uint16_t current_a_x100, const uint16_t wattage) { + + OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left) + OLED::print(SmallSymbolPDDebug, FontStyle::SMALL); // Print Title + OLED::setCursor(0, 8); // second line + OLED::printNumber(entry_num, 2, FontStyle::SMALL, true); // print the entry number + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + if (min_voltage > 0) { + OLED::printNumber(min_voltage, 2, FontStyle::SMALL, true); // print the voltage + OLED::print(SmallSymbolMinus, FontStyle::SMALL); + } + OLED::printNumber(max_voltage, 2, FontStyle::SMALL, true); // print the voltage + OLED::print(SmallSymbolVolts, FontStyle::SMALL); + OLED::print(SmallSymbolSpace, FontStyle::SMALL); + if (wattage) { + OLED::printNumber(wattage, 3, FontStyle::SMALL, true); // print the current in 0.1A res + OLED::print(SmallSymbolWatts, FontStyle::SMALL); + } else { + OLED::printNumber(current_a_x100 / 100, 2, FontStyle::SMALL, true); // print the current in 0.1A res + OLED::print(SmallSymbolDot, FontStyle::SMALL); + OLED::printNumber(current_a_x100 % 100, 2, FontStyle::SMALL, false); // print the current in 0.1A res + OLED::print(SmallSymbolAmps, FontStyle::SMALL); + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/draw_warning_undervoltage.cpp b/source/Core/Threads/UI/drawing/mono_96x16/draw_warning_undervoltage.cpp new file mode 100644 index 000000000..aaeb3858f --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/draw_warning_undervoltage.cpp @@ -0,0 +1,21 @@ +#include "ui_drawing.hpp" +#ifdef OLED_96x16 + +void ui_draw_warning_undervoltage(void) { + OLED::clearScreen(); + OLED::setCursor(0, 0); + if (getSettingValue(SettingsOptions::DetailedSoldering)) { + OLED::print(translatedString(Tr->UndervoltageString), FontStyle::SMALL); + OLED::setCursor(0, 8); + OLED::print(translatedString(Tr->InputVoltageString), FontStyle::SMALL); + printVoltage(); + OLED::print(SmallSymbolVolts, FontStyle::SMALL); + } else { + OLED::print(translatedString(Tr->UVLOWarningString), FontStyle::LARGE); + } + + OLED::refresh(); + GUIDelay(); + waitForButtonPress(); +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/pre_render_assets.cpp b/source/Core/Threads/UI/drawing/mono_96x16/pre_render_assets.cpp new file mode 100644 index 000000000..8e630b6f7 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/pre_render_assets.cpp @@ -0,0 +1,19 @@ +#include "ui_drawing.hpp" + +#ifdef OLED_96x16 +uint8_t buttonAF[sizeof(buttonA)]; +uint8_t buttonBF[sizeof(buttonB)]; +uint8_t disconnectedTipF[sizeof(disconnectedTip)]; + +void ui_pre_render_assets(void) { + // Generate the flipped screen into ram for later use + // flipped is generated by flipping each row + for (int row = 0; row < 2; row++) { + for (int x = 0; x < 42; x++) { + buttonAF[(row * 42) + x] = buttonA[(row * 42) + (41 - x)]; + buttonBF[(row * 42) + x] = buttonB[(row * 42) + (41 - x)]; + disconnectedTipF[(row * 42) + x] = disconnectedTip[(row * 42) + (41 - x)]; + } + } +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/OperatingModes/utils/printSleepCountdown.cpp b/source/Core/Threads/UI/drawing/mono_96x16/printSleepCountdown.cpp similarity index 96% rename from source/Core/Threads/OperatingModes/utils/printSleepCountdown.cpp rename to source/Core/Threads/UI/drawing/mono_96x16/printSleepCountdown.cpp index ea53c5c8a..ee9dd4fd0 100644 --- a/source/Core/Threads/OperatingModes/utils/printSleepCountdown.cpp +++ b/source/Core/Threads/UI/drawing/mono_96x16/printSleepCountdown.cpp @@ -1,5 +1,6 @@ #include "Buttons.hpp" #include "OperatingModeUtilities.h" +#ifdef OLED_96x16 extern TickType_t lastMovementTime; #ifndef NO_SLEEP_MODE void printCountdownUntilSleep(int sleepThres) { @@ -17,4 +18,5 @@ void printCountdownUntilSleep(int sleepThres) { OLED::print(SmallSymbolSeconds, FontStyle::SMALL); } } +#endif #endif \ No newline at end of file diff --git a/source/Core/Threads/OperatingModes/utils/PrintVoltage.cpp b/source/Core/Threads/UI/drawing/mono_96x16/print_voltage.cpp similarity index 84% rename from source/Core/Threads/OperatingModes/utils/PrintVoltage.cpp rename to source/Core/Threads/UI/drawing/mono_96x16/print_voltage.cpp index ea7b8911c..5609feaf0 100644 --- a/source/Core/Threads/OperatingModes/utils/PrintVoltage.cpp +++ b/source/Core/Threads/UI/drawing/mono_96x16/print_voltage.cpp @@ -1,8 +1,10 @@ -#include "OperatingModeUtilities.h" +#include "ui_drawing.hpp" +#ifdef OLED_96x16 void printVoltage(void) { uint32_t volt = getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0); OLED::printNumber(volt / 10, 2, FontStyle::SMALL); OLED::print(SmallSymbolDot, FontStyle::SMALL); OLED::printNumber(volt % 10, 1, FontStyle::SMALL); } +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/mono_96x16/show_warning.cpp b/source/Core/Threads/UI/drawing/mono_96x16/show_warning.cpp new file mode 100644 index 000000000..6f91b9057 --- /dev/null +++ b/source/Core/Threads/UI/drawing/mono_96x16/show_warning.cpp @@ -0,0 +1,14 @@ +#include "Buttons.hpp" +#include "OperatingModeUtilities.h" +#include "OperatingModes.h" +#ifdef OLED_96x16 +bool warnUser(const char *warning, const ButtonState buttons) { + OLED::clearScreen(); + OLED::printWholeScreen(warning); + // Also timeout after 5 seconds + if ((xTaskGetTickCount() - lastButtonTime) > TICKS_SECOND * 5) { + return true; + } + return buttons != BUTTON_NONE; +} +#endif \ No newline at end of file diff --git a/source/Core/Threads/UI/drawing/ui_drawing.hpp b/source/Core/Threads/UI/drawing/ui_drawing.hpp new file mode 100644 index 000000000..4f88aa7d7 --- /dev/null +++ b/source/Core/Threads/UI/drawing/ui_drawing.hpp @@ -0,0 +1,34 @@ +#ifndef UI_DRAWING_UI_DRAWING_HPP_ +#define UI_DRAWING_UI_DRAWING_HPP_ +#include "Buttons.hpp" +#include "OLED.hpp" +#include "OperatingModeUtilities.h" +#include "Settings.h" +#include "configuration.h" +#include +#include +#include +void ui_draw_warning_undervoltage(void); +void ui_draw_power_source_icon(void); // Draw a single character wide power source icon +void ui_draw_tip_temperature(bool symbol, const FontStyle font); // Draw tip temp, aware of conversions +bool warnUser(const char *warning, const ButtonState buttons); // Print a full screen warning to the user +void ui_draw_cjc_sampling(const uint8_t num_dots); // Draws the CJC info text and progress dots +void ui_draw_debug_menu(const uint8_t item_number); // Draws the debug menu state +void ui_draw_homescreen_detailed(TemperatureType_t tipTemp); // Drawing the home screen -- Detailed mode +void ui_draw_homescreen_simplified(TemperatureType_t tipTemp); // Drawing the home screen -- Simple mode +void ui_pre_render_assets(void); // If any assets need to be pre-rendered into ram +// Soldering mode +void ui_draw_soldering_power_status(bool boost_mode_on); +void ui_draw_soldering_basic_status(bool boostModeOn); +void ui_draw_soldering_detailed_sleep(TemperatureType_t tipTemp); +void ui_draw_soldering_basic_sleep(TemperatureType_t tipTemp); +void ui_draw_soldering_profile_advanced(TemperatureType_t tipTemp, TemperatureType_t profileCurrentTargetTemp, uint32_t phaseElapsedSeconds, uint32_t phase, const uint32_t phaseTimeGoal); + +// Temp change +void ui_draw_temperature_change(void); +// USB-PD debug +void ui_draw_usb_pd_debug_state(const uint16_t vbus_sense_state, const uint8_t stateNumber); +void ui_draw_usb_pd_debug_pdo(const uint8_t entry_num, const uint16_t min_voltage, const uint16_t max_voltage, const uint16_t current_a_x100, const uint16_t wattage); +// Utils +void printVoltage(void); +#endif // UI_DRAWING_UI_DRAWING_HPP_ diff --git a/source/Core/Threads/UI/logic/CJC.cpp b/source/Core/Threads/UI/logic/CJC.cpp new file mode 100644 index 000000000..5c0c883b8 --- /dev/null +++ b/source/Core/Threads/UI/logic/CJC.cpp @@ -0,0 +1,42 @@ +#include "OperatingModes.h" +#include "ui_drawing.hpp" + +OperatingMode performCJCC(const ButtonState buttons, guiContext *cxt) { + // Calibrate Cold Junction Compensation directly at boot, before internal components get warm. + + // While we wait for the pre-start checks to finish, we cant run CJC (as the pre-start checks control the tip) + if (preStartChecks() == 0) { + OLED::setCursor(0, 0); + OLED::print(translatedString(Tr->CJCCalibrating), FontStyle::SMALL); + return OperatingMode::CJCCalibration; + } + + if (!isTipDisconnected() && abs(int(TipThermoModel::getTipInC() - getHandleTemperature(0) / 10)) < 10) { + // Take 16 samples, only sample + if (cxt->scratch_state.state1 < 16) { + if ((xTaskGetTickCount() - cxt->scratch_state.state4) > TICKS_100MS) { + cxt->scratch_state.state3 += getTipRawTemp(1); + cxt->scratch_state.state1++; + cxt->scratch_state.state4 = xTaskGetTickCount(); + } + ui_draw_cjc_sampling(cxt->scratch_state.state1 / 4); + return OperatingMode::CJCCalibration; + } + + // If the thermo-couple at the end of the tip, and the handle are at + // equilibrium, then the output should be zero, as there is no temperature + // differential. + + uint16_t setOffset = TipThermoModel::convertTipRawADCTouV(cxt->scratch_state.state3 / 16, true); + setSettingValue(SettingsOptions::CalibrationOffset, setOffset); + if (warnUser(translatedString(Tr->CalibrationDone), buttons)) { + // Preventing to repeat calibration at boot automatically (only one shot). + setSettingValue(SettingsOptions::CalibrateCJC, 0); + saveSettings(); + return OperatingMode::InitialisationDone; + } + return OperatingMode::CJCCalibration; + } + // Cant run calibration without the tip and for temps to be close + return OperatingMode::StartupWarnings; +} diff --git a/source/Core/Threads/UI/logic/DebugMenu.cpp b/source/Core/Threads/UI/logic/DebugMenu.cpp new file mode 100644 index 000000000..df8284cb6 --- /dev/null +++ b/source/Core/Threads/UI/logic/DebugMenu.cpp @@ -0,0 +1,20 @@ +#include "OperatingModes.h" +#include "ui_drawing.hpp" + +OperatingMode showDebugMenu(const ButtonState buttons, guiContext *cxt) { + + ui_draw_debug_menu(cxt->scratch_state.state1); + + if (buttons == BUTTON_B_SHORT) { + cxt->transitionMode = TransitionAnimation::Up; + return OperatingMode::HomeScreen; + } else if (buttons == BUTTON_F_SHORT) { + cxt->scratch_state.state1++; +#ifdef HALL_SENSOR + cxt->scratch_state.state1 = cxt->scratch_state.state1 % 17; +#else + cxt->scratch_state.state1 = cxt->scratch_state.state1 % 16; +#endif + } + return OperatingMode::DebugMenuReadout; // Stay in debug menu +} diff --git a/source/Core/Threads/UI/logic/HomeScreen.cpp b/source/Core/Threads/UI/logic/HomeScreen.cpp new file mode 100644 index 000000000..c4328697f --- /dev/null +++ b/source/Core/Threads/UI/logic/HomeScreen.cpp @@ -0,0 +1,73 @@ + +#include "Buttons.hpp" +#include "OperatingModes.h" +#include "ui_drawing.hpp" + +bool showExitMenuTransition = false; + +OperatingMode handleHomeButtons(const ButtonState buttons, guiContext *cxt) { + if (buttons != BUTTON_NONE && cxt->scratch_state.state1 == 0) { + return OperatingMode::HomeScreen; // Ignore button press + } else { + cxt->scratch_state.state1 = 1; + } + switch (buttons) { + case BUTTON_NONE: + // Do nothing + break; + case BUTTON_BOTH: + break; + + case BUTTON_B_LONG: + cxt->transitionMode = TransitionAnimation::Down; + return OperatingMode::DebugMenuReadout; + break; + case BUTTON_F_LONG: +#ifdef PROFILE_SUPPORT + if (!isTipDisconnected()) { + cxt->transitionMode = TransitionAnimation::Left; + return OperatingMode::SolderingProfile; + } else { + return OperatingMode::HomeScreen; + } +#else + cxt->transitionMode = TransitionAnimation::Left; + return OperatingMode::TemperatureAdjust; +#endif + break; + case BUTTON_F_SHORT: + if (!isTipDisconnected()) { + bool detailedView = getSettingValue(SettingsOptions::DetailedIDLE) && getSettingValue(SettingsOptions::DetailedSoldering); + cxt->transitionMode = detailedView ? TransitionAnimation::None : TransitionAnimation::Left; + return OperatingMode::Soldering; + } + break; + case BUTTON_B_SHORT: + cxt->transitionMode = TransitionAnimation::Right; + return OperatingMode::SettingsMenu; + break; + default: + break; + } + return OperatingMode::HomeScreen; +} + +OperatingMode drawHomeScreen(const ButtonState buttons, guiContext *cxt) { + + currentTempTargetDegC = 0; // ensure tip is off + getInputVoltageX10(getSettingValue(SettingsOptions::VoltageDiv), 0); + uint32_t tipTemp = TipThermoModel::getTipInC(); + + // Setup LCD Cursor location + if (OLED::getRotation()) { + OLED::setCursor(50, 0); + } else { + OLED::setCursor(-1, 0); + } + if (getSettingValue(SettingsOptions::DetailedIDLE)) { + ui_draw_homescreen_detailed(tipTemp); + } else { + ui_draw_homescreen_simplified(tipTemp); + } + return handleHomeButtons(buttons, cxt); +} diff --git a/source/Core/Threads/OperatingModes/OperatingModes.cpp b/source/Core/Threads/UI/logic/OperatingModes.cpp similarity index 50% rename from source/Core/Threads/OperatingModes/OperatingModes.cpp rename to source/Core/Threads/UI/logic/OperatingModes.cpp index c09e71d0a..d334d13b4 100644 --- a/source/Core/Threads/OperatingModes/OperatingModes.cpp +++ b/source/Core/Threads/UI/logic/OperatingModes.cpp @@ -3,6 +3,3 @@ // #include "OperatingModes.h" - -// Global variables -OperatingMode currentMode = OperatingMode::idle; \ No newline at end of file diff --git a/source/Core/Threads/UI/logic/OperatingModes.h b/source/Core/Threads/UI/logic/OperatingModes.h new file mode 100644 index 000000000..3b38bb92a --- /dev/null +++ b/source/Core/Threads/UI/logic/OperatingModes.h @@ -0,0 +1,87 @@ +#ifndef OPERATING_MODES_H_ +#define OPERATING_MODES_H_ + +extern "C" { +#include "FreeRTOSConfig.h" +} +#include "Buttons.hpp" +#include "OLED.hpp" +#include "OperatingModeUtilities.h" +#include "Settings.h" +#include "TipThermoModel.h" +#include "Translation.h" +#include "Types.h" +#include "cmsis_os.h" +#include "configuration.h" +#include "history.hpp" +#include "main.hpp" +#include "power.hpp" +#include "settingsGUI.hpp" +#include "stdlib.h" +#include "string.h" +#ifdef POW_PD +#include "USBPD.h" +#include "pd.h" +#endif + +enum class OperatingMode { + StartupLogo=10, // Showing the startup logo + CJCCalibration=11, // Cold Junction Calibration + StartupWarnings=12, // Startup checks and warnings + InitialisationDone=13, // Special state we use just before we to home screen at first startup. Allows jumping to extra startup states + HomeScreen=0, // Home/Idle screen that is the main launchpad to other modes + Soldering=1, // Main soldering operating mode + SolderingProfile=6, // Soldering by following a profile, used for reflow for example + Sleeping=3, // Sleep state holds iron at lower sleep temp + Hibernating=14, // Like sleeping but keeps heater fully off until woken + SettingsMenu=4, // Settings Menu + DebugMenuReadout=5, // Debug metrics + TemperatureAdjust=7, // Set point temperature adjustment + UsbPDDebug=8, // USB PD debugging information + ThermalRunaway=9, // Thermal Runaway warning state. +}; + +enum class TransitionAnimation { + None = 0, + Right = 1, + Left = 2, + Down = 3, + Up = 4, +}; + +// Generic context struct used for gui functions to be able to retain state +struct guiContext { + TickType_t viewEnterTime; // Set to ticks when this view state was first entered + OperatingMode previousMode; + TransitionAnimation transitionMode; + // Below is scratch state, this is retained over re-draws but blown away on state change + struct scratch { + uint16_t state1; // 16 bit state scratch + uint16_t state2; // 16 bit state scratch + uint32_t state3; // 32 bit state scratch + uint32_t state4; // 32 bit state scratch + uint16_t state5; // 16 bit state scratch + uint16_t state6; // 16 bit state scratch + uint32_t state7; // 32 bit state scratch + + } scratch_state; +}; + +// Main functions +OperatingMode gui_SolderingSleepingMode(const ButtonState buttons, guiContext *cxt); // Sleep mode +OperatingMode gui_solderingMode(const ButtonState buttons, guiContext *cxt); // Main mode for hot pointy tool +OperatingMode gui_solderingTempAdjust(const ButtonState buttons, guiContext *cxt); // For adjusting the setpoint temperature of the iron +OperatingMode drawHomeScreen(const ButtonState buttons, guiContext *cxt); // IDLE / Home screen +OperatingMode gui_SettingsMenu(const ButtonState buttons, guiContext *cxt); // + +OperatingMode gui_solderingProfileMode(const ButtonState buttons, guiContext *cxt); // Profile mode for hot likely-not-so-pointy tool +OperatingMode performCJCC(const ButtonState buttons, guiContext *cxt); // Used to calibrate the Cold Junction offset +OperatingMode showDebugMenu(const ButtonState buttons, guiContext *cxt); // Debugging values +OperatingMode showPDDebug(const ButtonState buttons, guiContext *cxt); // Debugging menu that shows PD adaptor info +OperatingMode showWarnings(const ButtonState buttons, guiContext *cxt); // Shows user warnings if required + +// Common helpers +int8_t getPowerSourceNumber(void); // Returns number ID of power source + +extern uint8_t heaterThermalRunawayCounter; +#endif diff --git a/source/Core/Threads/UI/logic/SettingsMenu.cpp b/source/Core/Threads/UI/logic/SettingsMenu.cpp new file mode 100644 index 000000000..371ecde8e --- /dev/null +++ b/source/Core/Threads/UI/logic/SettingsMenu.cpp @@ -0,0 +1,293 @@ +#include "OperatingModes.h" +#include "ScrollMessage.hpp" + +#define HELP_TEXT_TIMEOUT_TICKS (TICKS_SECOND * 3) +/* + * The settings menu is the most complex bit of GUI code we have + * The menu consists of a two tier menu + * Main menu -> Categories + * Secondary menu -> Settings + * + * For each entry in the menu + */ + +/** + * Prints two small lines (or one line for CJK) of short description for + * setting items and prepares cursor after it. + * @param settingsItemIndex Index of the setting item. + * @param cursorCharPosition Custom cursor char position to set after printing + * description. + */ +static void printShortDescription(SettingsItemIndex settingsItemIndex, uint16_t cursorCharPosition) { + // print short description (default single line, explicit double line) + uint8_t shortDescIndex = static_cast(settingsItemIndex); + OLED::printWholeScreen(translatedString(Tr->SettingsShortNames[shortDescIndex])); + + // prepare cursor for value + // make room for scroll indicator + OLED::setCursor(cursorCharPosition * FONT_12_WIDTH - 2, 0); +} + +// Render a menu, based on the position given +// This will either draw the menu item, or the help text depending on how long its been since button press +void render_menu(const menuitem *item, guiContext *cxt) { + // If recent interaction or not help text draw the entry + if ((xTaskGetTickCount() - lastButtonTime < HELP_TEXT_TIMEOUT_TICKS) || item->description == 0) { + + if (item->shortDescriptionSize > 0) { + printShortDescription(item->shortDescriptionIndex, item->shortDescriptionSize); + } + item->draw(); + } else { + + uint16_t *isRenderingHelp = &(cxt->scratch_state.state6); + *isRenderingHelp = 1; + // Draw description + const char *description = translatedString(Tr->SettingsDescriptions[item->description - 1]); + drawScrollingText(description, (xTaskGetTickCount() - lastButtonTime) - HELP_TEXT_TIMEOUT_TICKS); + } +} + +uint16_t getMenuLength(const menuitem *menu, const uint16_t stop) { + // walk this menu to find the length + uint16_t counter = 0; + for (uint16_t pos = 0; pos < stop; pos++) { + // End of list + if (menu[pos].draw == nullptr) { + return counter; + } + // Otherwise increment for each visible item (null == always, or if not check function) + if (menu[pos].isVisible == nullptr || menu[pos].isVisible()) { + counter++; + } + } + return counter; +} + +OperatingMode moveToNextEntry(guiContext *cxt) { + uint16_t *mainEntry = &(cxt->scratch_state.state1); + uint16_t *subEntry = &(cxt->scratch_state.state2); + uint16_t *currentMenuLength = &(cxt->scratch_state.state5); + uint16_t *isRenderingHelp = &(cxt->scratch_state.state6); + + if (*isRenderingHelp) { + *isRenderingHelp = 0; + } else { + *currentMenuLength = 0; // Reset menu length + // Scroll down + // We can increment freely _once_ + cxt->transitionMode = TransitionAnimation::Down; + if (*subEntry == 0) { + (*mainEntry) += 1; + + if (rootSettingsMenu[*mainEntry].draw == nullptr) { + // We are off the end of the menu now + saveSettings(); + cxt->transitionMode = TransitionAnimation::Left; + return OperatingMode::HomeScreen; + } + // Check if visible + if (rootSettingsMenu[*mainEntry].isVisible != nullptr && !rootSettingsMenu[*mainEntry].isVisible()) { + // We need to move on as this one isn't visible + return moveToNextEntry(cxt); + } + } else { + (*subEntry) += 1; + + // If the new entry is null, we need to exit + if (subSettingsMenus[*mainEntry][(*subEntry) - 1].draw == nullptr) { + (*subEntry) = 0; // Reset back to the main menu + cxt->transitionMode = TransitionAnimation::Left; + // Have to break early to avoid the below check underflowing + return OperatingMode::SettingsMenu; + } + // Check if visible + if (subSettingsMenus[*mainEntry][(*subEntry) - 1].isVisible != nullptr && !subSettingsMenus[*mainEntry][(*subEntry) - 1].isVisible()) { + // We need to move on as this one isn't visible + return moveToNextEntry(cxt); + } + } + } + return OperatingMode::SettingsMenu; +} + +OperatingMode gui_SettingsMenu(const ButtonState buttons, guiContext *cxt) { + // Render out the current settings menu + // State 1 -> Root menu + // State 2 -> Sub entry + // Draw main entry if sub-entry is 0, otherwise draw sub-entry + + uint16_t *mainEntry = &(cxt->scratch_state.state1); + uint16_t *subEntry = &(cxt->scratch_state.state2); + uint32_t *autoRepeatAcceleration = &(cxt->scratch_state.state3); + uint32_t *autoRepeatTimer = &(cxt->scratch_state.state4); + uint16_t *currentMenuLength = &(cxt->scratch_state.state5); + uint16_t *isRenderingHelp = &(cxt->scratch_state.state6); + + const menuitem *currentMenu; + // Draw the currently on screen item + uint16_t currentScreen; + if (*subEntry == 0) { + // Drawing main menu + currentMenu = rootSettingsMenu; + currentScreen = *mainEntry; + } else { + // Drawing sub menu + currentMenu = subSettingsMenus[*mainEntry]; + currentScreen = (*subEntry) - 1; + } + render_menu(&(currentMenu[currentScreen]), cxt); + + // Update the cached menu length if unknown + if (*currentMenuLength == 0) { + // We walk the current menu to find the length + *currentMenuLength = getMenuLength(currentMenu, 128 /* Max length of any menu*/); + } + + if (*isRenderingHelp == 0) { + // Draw scroll + + // Get virtual pos by counting entries from start to _here_ + uint16_t currentVirtualPosition = getMenuLength(currentMenu, currentScreen + 1); + if (currentVirtualPosition > 0) { + currentVirtualPosition--; + } + + // The height of the indicator is screen res height / total menu entries + uint8_t indicatorHeight = OLED_HEIGHT / *currentMenuLength; + if (indicatorHeight == 0) { + indicatorHeight = 1; // always at least 1 pixel + } + + uint16_t position = (OLED_HEIGHT * (uint16_t)currentVirtualPosition) / *currentMenuLength; + + bool showScrollbar = true; + + // Store if its the last option for this setting + bool isLastOptionForSetting = false; + if ((int)currentMenu[currentScreen].autoSettingOption < (int)SettingsOptions::SettingsOptionsLength) { + isLastOptionForSetting = isLastSettingValue(currentMenu[currentScreen].autoSettingOption); + } + + // Last settings menu entry, reset scroll show back so it flashes + if (isLastOptionForSetting) { + showScrollbar = false; + } + + // Or Flash it + showScrollbar |= (xTaskGetTickCount() % (TICKS_SECOND / 4) < (TICKS_SECOND / 8)); + + if (showScrollbar) { + OLED::drawScrollIndicator((uint8_t)position, indicatorHeight); + } + } + + // Now handle user button input + auto callIncrementHandler = [&]() { + if (currentMenu[currentScreen].incrementHandler != nullptr) { + currentMenu[currentScreen].incrementHandler(); + } else if ((int)currentMenu[currentScreen].autoSettingOption < (int)SettingsOptions::SettingsOptionsLength) { + nextSettingValue(currentMenu[currentScreen].autoSettingOption); + } + return false; + }; + + // Modify a button value before processing a key press if setting to swap buttons is enabled + bool swapButtonSettings = getSettingValue(SettingsOptions::ReverseButtonSettings); + uint8_t buttonPress; + switch (buttons) { + case BUTTON_F_LONG: + buttonPress = swapButtonSettings ? BUTTON_B_LONG : BUTTON_F_LONG; + break; + case BUTTON_F_SHORT: + buttonPress = swapButtonSettings ? BUTTON_B_SHORT : BUTTON_F_SHORT; + break; + case BUTTON_B_LONG: + buttonPress = swapButtonSettings ? BUTTON_F_LONG : BUTTON_B_LONG; + break; + case BUTTON_B_SHORT: + buttonPress = swapButtonSettings ? BUTTON_F_SHORT : BUTTON_B_SHORT; + break; + default: + buttonPress = buttons; + break; + } + + OperatingMode newMode = OperatingMode::SettingsMenu; + switch (buttonPress) { + case BUTTON_NONE: + (*autoRepeatAcceleration) = 0; // reset acceleration + (*autoRepeatTimer) = 0; // reset acceleration + break; + case BUTTON_BOTH: + if (*subEntry == 0) { + saveSettings(); + cxt->transitionMode = TransitionAnimation::Left; + return OperatingMode::HomeScreen; + } else { + cxt->transitionMode = TransitionAnimation::Left; + *subEntry = 0; + return OperatingMode::SettingsMenu; + } + break; + case BUTTON_F_LONG: + if (xTaskGetTickCount() + (*autoRepeatAcceleration) > (*autoRepeatTimer) + PRESS_ACCEL_INTERVAL_MAX) { + callIncrementHandler(); + // Update the check for if its the last version + bool isLastOptionForSetting = false; + if ((int)currentMenu[currentScreen].autoSettingOption < (int)SettingsOptions::SettingsOptionsLength) { + isLastOptionForSetting = isLastSettingValue(currentMenu[currentScreen].autoSettingOption); + } + + if (isLastOptionForSetting) { + (*autoRepeatTimer) = TICKS_SECOND * 2; + } else { + (*autoRepeatTimer) = 0; + } + (*autoRepeatTimer) += xTaskGetTickCount(); + (*autoRepeatAcceleration) += PRESS_ACCEL_STEP; + *currentMenuLength = 0; // Reset incase menu visible changes + } + break; + case BUTTON_F_SHORT: + // Increment setting + if (*isRenderingHelp) { + *isRenderingHelp = 0; + } else { + *currentMenuLength = 0; // Reset incase menu visible changes + if (*subEntry == 0) { + // In a root menu, if its null handler we enter the menu + if (currentMenu[currentScreen].incrementHandler != nullptr) { + currentMenu[currentScreen].incrementHandler(); + } else { + (*subEntry) += 1; + cxt->transitionMode = TransitionAnimation::Right; + } + } else { + callIncrementHandler(); + } + } + break; + case BUTTON_B_LONG: + if (xTaskGetTickCount() + (*autoRepeatAcceleration) > (*autoRepeatTimer) + PRESS_ACCEL_INTERVAL_MAX) { + (*autoRepeatTimer) = xTaskGetTickCount(); + (*autoRepeatAcceleration) += PRESS_ACCEL_STEP; + } else { + break; + } + /* Fall through*/ + case BUTTON_B_SHORT: + // Increment menu item + newMode = moveToNextEntry(cxt); + break; + default: + break; + } + + if ((PRESS_ACCEL_INTERVAL_MAX - (*autoRepeatAcceleration)) < PRESS_ACCEL_INTERVAL_MIN) { + (*autoRepeatAcceleration) = PRESS_ACCEL_INTERVAL_MAX - PRESS_ACCEL_INTERVAL_MIN; + } + + // Otherwise we stay put for next render iteration + return newMode; +} diff --git a/source/Core/Threads/UI/logic/ShowStartupWarnings.cpp b/source/Core/Threads/UI/logic/ShowStartupWarnings.cpp new file mode 100644 index 000000000..433eb7b0e --- /dev/null +++ b/source/Core/Threads/UI/logic/ShowStartupWarnings.cpp @@ -0,0 +1,118 @@ +#include "FS2711.hpp" +#include "HUB238.hpp" +#include "OperatingModes.h" +#include "ui_drawing.hpp" +OperatingMode showWarnings(const ButtonState buttons, guiContext *cxt) { + // Display alert if settings were reset + + switch (cxt->scratch_state.state1) { + case 0: // Settings reset warning + if (settingsWereReset) { + if (warnUser(translatedString(Tr->SettingsResetMessage), buttons)) { + settingsWereReset = false; + cxt->scratch_state.state1 = 1; + } + } else { + cxt->scratch_state.state1 = 1; + } + break; + case 1: // Device validations +#ifdef DEVICE_HAS_VALIDATION_SUPPORT + if (getDeviceValidationStatus()) { + // Warn user this device might be counterfeit + if (warnUser(translatedString(Tr->DeviceFailedValidationWarning), buttons)) { + cxt->scratch_state.state1 = 2; + } + } else { + cxt->scratch_state.state1 = 2; + } +#else + cxt->scratch_state.state1 = 2; +#endif + break; + case 2: // Accelerometer detection +#ifdef NO_ACCEL + cxt->scratch_state.state1 = 3; +#else + if (DetectedAccelerometerVersion == AccelType::Scanning) { + break; + } + // Display alert if accelerometer is not detected + if (DetectedAccelerometerVersion == AccelType::None) { + if (getSettingValue(SettingsOptions::AccelMissingWarningCounter) < 2) { + + if (warnUser(translatedString(Tr->NoAccelerometerMessage), buttons)) { + cxt->scratch_state.state1 = 3; + nextSettingValue(SettingsOptions::AccelMissingWarningCounter); + saveSettings(); + } + } else { + cxt->scratch_state.state1 = 3; + } + } else { + cxt->scratch_state.state1 = 3; + } +#endif + + break; + case 3: + +#ifdef POW_PD + // We expect pd to be present + if (!USBPowerDelivery::fusbPresent()) { + if (getSettingValue(SettingsOptions::PDMissingWarningCounter) < 2) { + if (warnUser(translatedString(Tr->NoPowerDeliveryMessage), buttons)) { + nextSettingValue(SettingsOptions::PDMissingWarningCounter); + saveSettings(); + cxt->scratch_state.state1 = 4; + } + } else { + cxt->scratch_state.state1 = 4; + } + } else { + cxt->scratch_state.state1 = 4; + } +#else +#if POW_PD_EXT == 1 + if (!hub238_probe()) { + if (getSettingValue(SettingsOptions::PDMissingWarningCounter) < 2) { + if (warnUser(translatedString(Tr->NoPowerDeliveryMessage), buttons)) { + cxt->scratch_state.state1 = 4; + nextSettingValue(SettingsOptions::PDMissingWarningCounter); + saveSettings(); + } + } else { + cxt->scratch_state.state1 = 4; + } + } else { + cxt->scratch_state.state1 = 4; + } +#else +#if POW_PD_EXT == 2 + if (!FS2711::probe()) { + if (getSettingValue(SettingsOptions::PDMissingWarningCounter) < 2) { + if (warnUser(translatedString(Tr->NoPowerDeliveryMessage), buttons)) { + cxt->scratch_state.state1 = 4; + nextSettingValue(SettingsOptions::PDMissingWarningCounter); + saveSettings(); + } + } else { + cxt->scratch_state.state1 = 4; + } + } else { + cxt->scratch_state.state1 = 4; + } +#else + cxt->scratch_state.state1 = 4; +#endif /*POW_PD_EXT==1*/ +#endif /*POW_PD_EXT==2*/ +#endif /*POW_PD*/ + + break; + default: + // We are off the end, warnings done + return OperatingMode::StartupLogo; + } + + return OperatingMode::StartupWarnings; // Stay in warnings +} diff --git a/source/Core/Threads/UI/logic/Sleep.cpp b/source/Core/Threads/UI/logic/Sleep.cpp new file mode 100644 index 000000000..dad421ffd --- /dev/null +++ b/source/Core/Threads/UI/logic/Sleep.cpp @@ -0,0 +1,51 @@ +#include "OperatingModes.h" +#include "ui_drawing.hpp" +OperatingMode gui_SolderingSleepingMode(const ButtonState buttons, guiContext *cxt) { +#ifdef NO_SLEEP_MODE + return OperatingMode::Soldering; +#endif + // Drop to sleep temperature and display until movement or button press + + // user moved or pressed a button, go back to soldering + // If in the first two seconds we disable this to let accelerometer warm up + +#ifdef POW_DC + if (checkForUnderVoltage()) { + return OperatingMode::HomeScreen; // return non-zero on error + } +#endif + + if (cxt->scratch_state.state4) { + // Hibernating mode + currentTempTargetDegC = 0; + } else { + if (getSettingValue(SettingsOptions::TemperatureInF)) { + currentTempTargetDegC = TipThermoModel::convertFtoC(min(getSettingValue(SettingsOptions::SleepTemp), getSettingValue(SettingsOptions::SolderingTemp))); + } else { + currentTempTargetDegC = min(getSettingValue(SettingsOptions::SleepTemp), getSettingValue(SettingsOptions::SolderingTemp)); + } + } + // draw the lcd + uint16_t tipTemp = getSettingValue(SettingsOptions::TemperatureInF) ? TipThermoModel::getTipInF() : TipThermoModel::getTipInC(); + + if (getSettingValue(SettingsOptions::DetailedSoldering)) { + ui_draw_soldering_detailed_sleep(tipTemp); + } else { + ui_draw_soldering_basic_sleep(tipTemp); + } + + if (!shouldBeSleeping()) { + return cxt->previousMode; + } + + if (shouldShutdown()) { + // shutdown + currentTempTargetDegC = 0; + return OperatingMode::HomeScreen; + } + if (cxt->scratch_state.state4) { + return OperatingMode::Hibernating; + } else { + return OperatingMode::Sleeping; + } +} diff --git a/source/Core/Threads/UI/logic/Soldering.cpp b/source/Core/Threads/UI/logic/Soldering.cpp new file mode 100644 index 000000000..e0d078f3a --- /dev/null +++ b/source/Core/Threads/UI/logic/Soldering.cpp @@ -0,0 +1,176 @@ + +#include "OperatingModes.h" +#include "SolderingCommon.h" +#include "ui_drawing.hpp" +// State 1 = button locking (0:unlocked+released, 1:unlocked, 2:locked, 3:locked+released) +// State 2 = boost mode +// State 3 = buzzer timer + +OperatingMode handleSolderingButtons(const ButtonState buttons, guiContext *cxt) { + if (cxt->scratch_state.state1 >= 2) { + // Buttons are currently locked + if (buttons == BUTTON_BOTH_LONG) { + if (cxt->scratch_state.state1 == 3) { + // Unlocking + if (warnUser(translatedString(Tr->UnlockingKeysString), buttons)) { + cxt->scratch_state.state1 = 1; + cxt->scratch_state.state7 = 0; + } + } else { + warnUser(translatedString(Tr->LockingKeysString), buttons); + } + return OperatingMode::Soldering; + } + if (cxt->scratch_state.state7 != 0) { + // show locked until timer is up + if (xTaskGetTickCount() >= cxt->scratch_state.state7) { + cxt->scratch_state.state7 = 0; + } else { + warnUser(translatedString(Tr->WarningKeysLockedString), buttons); + return OperatingMode::Soldering; + } + } + switch (buttons) { + case BUTTON_NONE: + cxt->scratch_state.state1 = 3; + cxt->scratch_state.state2 = 0; + break; + case BUTTON_F_LONG: + if (getSettingValue(SettingsOptions::BoostTemp) && (getSettingValue(SettingsOptions::LockingMode) == lockingMode_t::BOOST)) { + cxt->scratch_state.state2 = 1; + break; + } + /*Fall through*/ + default: // Set timer for and display a lock warning + cxt->scratch_state.state7 = xTaskGetTickCount() + TICKS_SECOND; + warnUser(translatedString(Tr->WarningKeysLockedString), buttons); + break; + } + return OperatingMode::Soldering; + } + + bool detailedView = getSettingValue(SettingsOptions::DetailedIDLE) && getSettingValue(SettingsOptions::DetailedSoldering); + // otherwise we are unlocked + switch (buttons) { + case BUTTON_NONE: + cxt->scratch_state.state2 = 0; + cxt->scratch_state.state1 = 0; + break; + case BUTTON_BOTH: + /*Fall through*/ + case BUTTON_B_LONG: + cxt->transitionMode = detailedView ? TransitionAnimation::None : TransitionAnimation::Right; + return OperatingMode::HomeScreen; + case BUTTON_F_LONG: + // if boost mode is enabled turn it on + if (getSettingValue(SettingsOptions::BoostTemp)) { + cxt->scratch_state.state2 = 1; + } + break; + case BUTTON_F_SHORT: + case BUTTON_B_SHORT: + cxt->transitionMode = TransitionAnimation::Left; + return OperatingMode::TemperatureAdjust; + case BUTTON_BOTH_LONG: + if (getSettingValue(SettingsOptions::LockingMode)) { + // Lock buttons + if (cxt->scratch_state.state1 == 0) { + if (warnUser(translatedString(Tr->LockingKeysString), buttons)) { + cxt->scratch_state.state1 = 2; + } + } else { + // FIXME should be WarningKeysUnlockedString + warnUser(translatedString(Tr->UnlockingKeysString), buttons); + } + } + break; + default: + break; + } + return OperatingMode::Soldering; +} + +OperatingMode gui_solderingMode(const ButtonState buttons, guiContext *cxt) { + /* + * * Soldering (gui_solderingMode) + * -> Main loop where we draw temp, and animations + * --> User presses buttons and they goto the temperature adjust screen + * ---> Display the current setpoint temperature + * ---> Use buttons to change forward and back on temperature + * ---> Both buttons or timeout for exiting + * --> Long hold front button to enter boost mode + * ---> Just temporarily sets the system into the alternate temperature for + * PID control + * --> Long hold back button to exit + * --> Double button to exit + * --> Long hold double button to toggle key lock + */ + + // Update the setpoints for the temperature + if (cxt->scratch_state.state2) { + if (getSettingValue(SettingsOptions::TemperatureInF)) { + currentTempTargetDegC = TipThermoModel::convertFtoC(getSettingValue(SettingsOptions::BoostTemp)); + } else { + currentTempTargetDegC = (getSettingValue(SettingsOptions::BoostTemp)); + } + } else { + if (getSettingValue(SettingsOptions::TemperatureInF)) { + currentTempTargetDegC = TipThermoModel::convertFtoC(getSettingValue(SettingsOptions::SolderingTemp)); + } else { + currentTempTargetDegC = (getSettingValue(SettingsOptions::SolderingTemp)); + } + } + + // Update status + int error = currentTempTargetDegC - TipThermoModel::getTipInC(); + if (error >= -10 && error <= 10) { + // converged + if (!cxt->scratch_state.state5) { + setBuzzer(true); + cxt->scratch_state.state3 = xTaskGetTickCount() + TICKS_SECOND / 3; + cxt->scratch_state.state5 = true; + } + setStatusLED(LED_HOT); + } else { + setStatusLED(LED_HEATING); + cxt->scratch_state.state5 = false; + } + if (cxt->scratch_state.state3 != 0 && xTaskGetTickCount() >= cxt->scratch_state.state3) { + setBuzzer(false); + } + + // Draw in the screen details + if (getSettingValue(SettingsOptions::DetailedSoldering)) { + ui_draw_soldering_power_status(cxt->scratch_state.state2); + } else { + ui_draw_soldering_basic_status(cxt->scratch_state.state2); + } + + bool detailedView = getSettingValue(SettingsOptions::DetailedIDLE) && getSettingValue(SettingsOptions::DetailedSoldering); + // Check if we should bail due to undervoltage for example + if (checkExitSoldering()) { + setBuzzer(false); + cxt->transitionMode = detailedView ? TransitionAnimation::None : TransitionAnimation::Right; + return OperatingMode::HomeScreen; + } +#ifdef NO_SLEEP_MODE + + if (shouldShutdown()) { + // shutdown + currentTempTargetDegC = 0; + cxt->transitionMode = detailedView ? TransitionAnimation::None : TransitionAnimation::Right; + return OperatingMode::HomeScreen; + } +#endif + if (shouldBeSleeping()) { + return OperatingMode::Sleeping; + } + + if (heaterThermalRunawayCounter > 8) { + currentTempTargetDegC = 0; // heater control off + heaterThermalRunawayCounter = 0; + cxt->transitionMode = TransitionAnimation::Right; + return OperatingMode::ThermalRunaway; + } + return handleSolderingButtons(buttons, cxt); +} diff --git a/source/Core/Threads/UI/logic/SolderingProfile.cpp b/source/Core/Threads/UI/logic/SolderingProfile.cpp new file mode 100644 index 000000000..606175cf8 --- /dev/null +++ b/source/Core/Threads/UI/logic/SolderingProfile.cpp @@ -0,0 +1,177 @@ + +#include "OperatingModes.h" +#include "SolderingCommon.h" +#include "ui_drawing.hpp" + +OperatingMode gui_solderingProfileMode(const ButtonState buttons, guiContext *cxt) { + /* + * * Soldering + * -> Main loop where we draw temp, and animations + * --> Long hold back button to exit + * --> Double button to exit + */ + + uint16_t tipTemp = 0; + + // If this is during init, start at preheat + if (cxt->scratch_state.state1 == 0) { + cxt->scratch_state.state5 = getSettingValue(SettingsOptions::ProfilePreheatTemp); + } + uint16_t phaseTicksPerDegree = TICKS_SECOND / getSettingValue(SettingsOptions::ProfilePreheatSpeed); + uint16_t profileCurrentTargetTemp = 0; + + switch (buttons) { + case BUTTON_BOTH: + case BUTTON_B_LONG: + cxt->transitionMode = TransitionAnimation::Right; + return OperatingMode::HomeScreen; // exit on back long hold + case BUTTON_F_LONG: + case BUTTON_F_SHORT: + case BUTTON_B_SHORT: + case BUTTON_NONE: + // Not used yet + break; + default: + break; + } + + if (getSettingValue(SettingsOptions::TemperatureInF)) { + tipTemp = TipThermoModel::getTipInF(); + } else { + tipTemp = TipThermoModel::getTipInC(); + } + // If time of entering is unknown; then we start now + if (cxt->scratch_state.state3 == 0) { + cxt->scratch_state.state3 = xTaskGetTickCount(); + } + + // if start temp is unknown (preheat), we're setting it now + if (cxt->scratch_state.state6 == 0) { + cxt->scratch_state.state6 = tipTemp; + // if this is hotter than the preheat temperature, we should fail + if (cxt->scratch_state.state6 >= cxt->scratch_state.state5) { + warnUser(translatedString(Tr->TooHotToStartProfileWarning), buttons); + return OperatingMode::HomeScreen; + } + } + uint16_t phaseElapsedSeconds = (xTaskGetTickCount() - cxt->scratch_state.state3) / TICKS_SECOND; + + // Have we finished this phase? + // Check if we have hit our temperature target in either direction. + bool phaseTargetReached = false; + if (cxt->scratch_state.state6 < cxt->scratch_state.state5 && tipTemp >= cxt->scratch_state.state5) { + phaseTargetReached = true; + } else if (cxt->scratch_state.state6 > cxt->scratch_state.state5 && tipTemp <= cxt->scratch_state.state5) { + phaseTargetReached = true; + } else if (tipTemp == cxt->scratch_state.state5) { + phaseTargetReached = true; + } + + // If we both hit the temperature target and enough time has passed, phase complete. + if (phaseElapsedSeconds >= cxt->scratch_state.state2 && phaseTargetReached) { + cxt->scratch_state.state1++; + cxt->scratch_state.state6 = cxt->scratch_state.state5; + cxt->scratch_state.state3 = xTaskGetTickCount(); + phaseElapsedSeconds = 0; + if (cxt->scratch_state.state1 > getSettingValue(SettingsOptions::ProfilePhases)) { + // done with all phases, lets go to cooldown + cxt->scratch_state.state2 = 0; + cxt->scratch_state.state5 = 0; + phaseTicksPerDegree = TICKS_SECOND / getSettingValue(SettingsOptions::ProfileCooldownSpeed); + } else { + // set up next phase + switch (cxt->scratch_state.state1) { + case 1: + cxt->scratch_state.state2 = getSettingValue(SettingsOptions::ProfilePhase1Duration); + cxt->scratch_state.state5 = getSettingValue(SettingsOptions::ProfilePhase1Temp); + break; + case 2: + cxt->scratch_state.state2 = getSettingValue(SettingsOptions::ProfilePhase2Duration); + cxt->scratch_state.state5 = getSettingValue(SettingsOptions::ProfilePhase2Temp); + break; + case 3: + cxt->scratch_state.state2 = getSettingValue(SettingsOptions::ProfilePhase3Duration); + cxt->scratch_state.state5 = getSettingValue(SettingsOptions::ProfilePhase3Temp); + break; + case 4: + cxt->scratch_state.state2 = getSettingValue(SettingsOptions::ProfilePhase4Duration); + cxt->scratch_state.state5 = getSettingValue(SettingsOptions::ProfilePhase4Temp); + break; + case 5: + cxt->scratch_state.state2 = getSettingValue(SettingsOptions::ProfilePhase5Duration); + cxt->scratch_state.state5 = getSettingValue(SettingsOptions::ProfilePhase5Temp); + break; + default: + break; + } + if (cxt->scratch_state.state6 < cxt->scratch_state.state5) { + phaseTicksPerDegree = (cxt->scratch_state.state2 * TICKS_SECOND) / (cxt->scratch_state.state5 - cxt->scratch_state.state6); + } else { + phaseTicksPerDegree = (cxt->scratch_state.state2 * TICKS_SECOND) / (cxt->scratch_state.state6 - cxt->scratch_state.state5); + } + } + } + + // cooldown phase done? + if (cxt->scratch_state.state1 > getSettingValue(SettingsOptions::ProfilePhases)) { + if (TipThermoModel::getTipInC() < 55) { + // we're done, let the buzzer beep too + setStatusLED(LED_STANDBY); + if (cxt->scratch_state.state4 == 0) { + setBuzzer(true); + cxt->scratch_state.state4 = xTaskGetTickCount() + TICKS_SECOND / 3; + } + } + } + + // determine current target temp + if (cxt->scratch_state.state6 < cxt->scratch_state.state5) { + profileCurrentTargetTemp = cxt->scratch_state.state6 + ((xTaskGetTickCount() - cxt->viewEnterTime) / phaseTicksPerDegree); + if (profileCurrentTargetTemp > cxt->scratch_state.state5) { + profileCurrentTargetTemp = cxt->scratch_state.state5; + } + } else if (cxt->scratch_state.state6 > cxt->scratch_state.state5) { + profileCurrentTargetTemp = cxt->scratch_state.state6 - ((xTaskGetTickCount() - cxt->viewEnterTime) / phaseTicksPerDegree); + // Chance of an overflow when ramping up is basically zero, but chance of an underflow here is quite high. If the target underflowed, snap it back. + if (profileCurrentTargetTemp < cxt->scratch_state.state5 || profileCurrentTargetTemp > cxt->scratch_state.state6) { + profileCurrentTargetTemp = cxt->scratch_state.state5; + } + } else { + profileCurrentTargetTemp = cxt->scratch_state.state5; + } + + // Draw in the screen details + if (getSettingValue(SettingsOptions::DetailedSoldering)) { + ui_draw_soldering_profile_advanced(tipTemp, profileCurrentTargetTemp, phaseElapsedSeconds, cxt->scratch_state.state1, cxt->scratch_state.state2); + ui_draw_soldering_power_status(false); + } else { + ui_draw_soldering_basic_status(false); + } + + // Update the setpoints for the temperature + if (getSettingValue(SettingsOptions::TemperatureInF)) { + currentTempTargetDegC = TipThermoModel::convertFtoC(profileCurrentTargetTemp); + } else { + currentTempTargetDegC = profileCurrentTargetTemp; + } + + if (checkExitSoldering() || (cxt->scratch_state.state4 != 0 && xTaskGetTickCount() >= cxt->scratch_state.state4)) { + setBuzzer(false); + return OperatingMode::HomeScreen; + } + if (heaterThermalRunawayCounter > 8) { + currentTempTargetDegC = 0; // heater control off + heaterThermalRunawayCounter = 0; + return OperatingMode::ThermalRunaway; + } + + // Update LED status + if (cxt->scratch_state.state1 == 0) { + setStatusLED(LED_HEATING); + } else if (cxt->scratch_state.state1 > getSettingValue(SettingsOptions::ProfilePhases)) { + setStatusLED(LED_COOLING_STILL_HOT); + } else { + setStatusLED(LED_HOT); + } + return OperatingMode::SolderingProfile; +} diff --git a/source/Core/Threads/UI/logic/TemperatureAdjust.cpp b/source/Core/Threads/UI/logic/TemperatureAdjust.cpp new file mode 100644 index 000000000..34a896c34 --- /dev/null +++ b/source/Core/Threads/UI/logic/TemperatureAdjust.cpp @@ -0,0 +1,92 @@ +#include "OperatingModes.h" +#include "ui_drawing.hpp" + +OperatingMode gui_solderingTempAdjust(const ButtonState buttonIn, guiContext *cxt) { + + currentTempTargetDegC = 0; // Turn off heater while adjusting temp + uint16_t *waitForRelease = &(cxt->scratch_state.state1); + uint32_t *autoRepeatTimer = &(cxt->scratch_state.state3); + uint16_t *autoRepeatAcceleration = &(cxt->scratch_state.state2); + ButtonState buttons = buttonIn; + if (*waitForRelease == 0) { + // When we first enter we wait for the user to release buttons before enabling changes + if (buttons != BUTTON_NONE) { + buttons = BUTTON_NONE; + } else { + (*waitForRelease)++; + } + } + + int16_t delta = 0; + switch (buttons) { + case BUTTON_NONE: + // stay + (*autoRepeatAcceleration) = 0; + break; + case BUTTON_BOTH: + // exit + saveSettings(); + cxt->transitionMode = TransitionAnimation::Right; + return cxt->previousMode; + case BUTTON_B_LONG: + if (xTaskGetTickCount() - (*autoRepeatTimer) + (*autoRepeatAcceleration) > PRESS_ACCEL_INTERVAL_MAX) { + delta = -getSettingValue(SettingsOptions::TempChangeLongStep); + (*autoRepeatTimer) = xTaskGetTickCount(); + (*autoRepeatAcceleration) += PRESS_ACCEL_STEP; + } + break; + case BUTTON_B_SHORT: + delta = -getSettingValue(SettingsOptions::TempChangeShortStep); + break; + case BUTTON_F_LONG: + if (xTaskGetTickCount() - (*autoRepeatTimer) + (*autoRepeatAcceleration) > PRESS_ACCEL_INTERVAL_MAX) { + delta = getSettingValue(SettingsOptions::TempChangeLongStep); + (*autoRepeatTimer) = xTaskGetTickCount(); + (*autoRepeatAcceleration) += PRESS_ACCEL_STEP; + } + break; + case BUTTON_F_SHORT: + delta = getSettingValue(SettingsOptions::TempChangeShortStep); + break; + default: + break; + } + if ((PRESS_ACCEL_INTERVAL_MAX - (*autoRepeatAcceleration)) < PRESS_ACCEL_INTERVAL_MIN) { + (*autoRepeatAcceleration) = PRESS_ACCEL_INTERVAL_MAX - PRESS_ACCEL_INTERVAL_MIN; + } + // If buttons are flipped; flip the delta + if (getSettingValue(SettingsOptions::ReverseButtonTempChangeEnabled)) { + delta = -delta; + } + if (delta != 0) { + // constrain between the set temp limits, i.e. 10-450 C + int16_t newTemp = getSettingValue(SettingsOptions::SolderingTemp); + newTemp += delta; + // Round to nearest increment of delta + delta = abs(delta); + newTemp = (newTemp / delta) * delta; + + if (getSettingValue(SettingsOptions::TemperatureInF)) { + if (newTemp > MAX_TEMP_F) { + newTemp = MAX_TEMP_F; + } else if (newTemp < MIN_TEMP_F) { + newTemp = MIN_TEMP_F; + } + } else { + if (newTemp > MAX_TEMP_C) { + newTemp = MAX_TEMP_C; + } else if (newTemp < MIN_TEMP_C) { + newTemp = MIN_TEMP_C; + } + } + setSettingValue(SettingsOptions::SolderingTemp, (uint16_t)newTemp); + } + ui_draw_temperature_change(); + + if (xTaskGetTickCount() - lastButtonTime > (TICKS_SECOND * 3)) { + saveSettings(); + cxt->transitionMode = TransitionAnimation::Right; + return cxt->previousMode; // exit if user just doesn't press anything for a bit + } + return OperatingMode::TemperatureAdjust; // Stay in temp adjust +} diff --git a/source/Core/Threads/UI/logic/USBPDDebug_FS2711.cpp b/source/Core/Threads/UI/logic/USBPDDebug_FS2711.cpp new file mode 100644 index 000000000..8ee9440ef --- /dev/null +++ b/source/Core/Threads/UI/logic/USBPDDebug_FS2711.cpp @@ -0,0 +1,50 @@ +#include "FS2711.hpp" +#include "OperatingModes.h" +#include "stdbool.h" +#include "ui_drawing.hpp" +#if POW_PD_EXT == 2 +#ifdef HAS_POWER_DEBUG_MENU + +OperatingMode showPDDebug(const ButtonState buttons, guiContext *cxt) { + // Print out the USB-PD state + // Basically this is like the Debug menu, but instead we want to print out the PD status + uint16_t *screen = &(cxt->scratch_state.state1); + + if (*screen > 7) { + *screen = 0; + } + if (*screen == 0) { + // Print the PD Debug state + fs2711_state_t state = FS2711::debug_get_state(); + + ui_draw_usb_pd_debug_state(0, state.pdo_num); + } else { + + // Print out the Proposed power options one by one + uint16_t max_voltage = FS2711::debug_pdo_max_voltage(*screen - 1); + if (max_voltage == 0) { + *screen += 1; + } else { + uint16_t min_voltage = FS2711::debug_pdo_min_voltage(*screen - 1); + uint16_t current = FS2711::debug_pdo_source_current(*screen - 1); + uint16_t pdo_type = FS2711::debug_pdo_type(*screen - 1); + if (pdo_type != 1) { + min_voltage = 0; + } + + ui_draw_usb_pd_debug_pdo(*screen, min_voltage / 1000, max_voltage / 1000, current * 1, 0); + } + } + + OLED::refresh(); + + if (buttons == BUTTON_B_SHORT) { + return OperatingMode::InitialisationDone; + } else if (buttons == BUTTON_F_SHORT) { + *screen++; + } + + return OperatingMode::UsbPDDebug; +} +#endif +#endif diff --git a/source/Core/Threads/UI/logic/USBPDDebug_FUSB.cpp b/source/Core/Threads/UI/logic/USBPDDebug_FUSB.cpp new file mode 100644 index 000000000..763f375ff --- /dev/null +++ b/source/Core/Threads/UI/logic/USBPDDebug_FUSB.cpp @@ -0,0 +1,75 @@ +#include "OperatingModes.h" +#include "ui_drawing.hpp" +#ifdef POW_PD +#include "pd.h" +#ifdef HAS_POWER_DEBUG_MENU +OperatingMode showPDDebug(const ButtonState buttons, guiContext *cxt) { + // Print out the USB-PD state + // Basically this is like the Debug menu, but instead we want to print out the PD status + uint16_t *screen = &(cxt->scratch_state.state1); + + if ((*screen) == 0) { + // Print the PD state machine + uint8_t vbusState = 0; + if (USBPowerDelivery::fusbPresent()) { + if (USBPowerDelivery::negotiationComplete() || (xTaskGetTickCount() > (TICKS_SECOND * 10))) { + if (!USBPowerDelivery::isVBUSConnected()) { + vbusState = 2; + } else { + vbusState = 1; + } + } + } + ui_draw_usb_pd_debug_state(vbusState, USBPowerDelivery::getStateNumber()); + } else { + // Print out the Proposed power options one by one + auto lastCaps = USBPowerDelivery::getLastSeenCapabilities(); + bool sourceIsEPRCapable = lastCaps[0] & PD_PDO_SRC_FIXED_EPR_CAPABLE; + if (((*screen) - 1) < 11) { + int voltage_mv = 0; + int min_voltage = 0; + int current_a_x100 = 0; + int wattage = 0; + + if ((lastCaps[(*screen) - 1] & PD_PDO_TYPE) == PD_PDO_TYPE_FIXED) { + voltage_mv = PD_PDV2MV(PD_PDO_SRC_FIXED_VOLTAGE_GET(lastCaps[(*screen) - 1])); // voltage in mV units + current_a_x100 = PD_PDO_SRC_FIXED_CURRENT_GET(lastCaps[(*screen) - 1]); // current in 10mA units + } else if ((lastCaps[(*screen) - 1] & PD_PDO_TYPE) == PD_PDO_TYPE_AUGMENTED) { + if (sourceIsEPRCapable) { + if ((lastCaps[(*screen) - 1] & PD_APDO_TYPE) == PD_APDO_TYPE_AVS) { + voltage_mv = PD_PAV2MV(PD_APDO_AVS_MAX_VOLTAGE_GET(lastCaps[(*screen) - 1])); + min_voltage = PD_PAV2MV(PD_APDO_PPS_MIN_VOLTAGE_GET(lastCaps[(*screen) - 1])); + // Last value is wattage + wattage = PD_APDO_AVS_MAX_POWER_GET(lastCaps[(*screen) - 1]); + } else if (((lastCaps[(*screen) - 1] & PD_APDO_TYPE) == PD_APDO_TYPE_PPS)) { + voltage_mv = PD_PAV2MV(PD_APDO_PPS_MAX_VOLTAGE_GET(lastCaps[(*screen) - 1])); + min_voltage = PD_PAV2MV(PD_APDO_PPS_MIN_VOLTAGE_GET(lastCaps[(*screen) - 1])); + current_a_x100 = PD_PAI2CA(PD_APDO_PPS_CURRENT_GET(lastCaps[(*screen) - 1])); // max current in 10mA units + } + } else { + // Doesn't have EPR support. So treat as PPS + // https://github.com/Ralim/IronOS/issues/1906 + voltage_mv = PD_PAV2MV(PD_APDO_PPS_MAX_VOLTAGE_GET(lastCaps[(*screen) - 1])); + min_voltage = PD_PAV2MV(PD_APDO_PPS_MIN_VOLTAGE_GET(lastCaps[(*screen) - 1])); + current_a_x100 = PD_PAI2CA(PD_APDO_PPS_CURRENT_GET(lastCaps[(*screen) - 1])); // max current in 10mA units + } + } + // Skip not used entries + if (voltage_mv == 0) { + (*screen) += 1; + } else { + ui_draw_usb_pd_debug_pdo(*screen, min_voltage / 1000, voltage_mv / 1000, current_a_x100, wattage); + } + } else { + (*screen) = 0; + } + } + if (buttons == BUTTON_B_SHORT) { + return OperatingMode::InitialisationDone; + } else if (buttons == BUTTON_F_SHORT) { + (*screen) += 1; + } + return OperatingMode::UsbPDDebug; +} +#endif +#endif diff --git a/source/Core/Threads/UI/logic/USBPDDebug_HUSB238.cpp b/source/Core/Threads/UI/logic/USBPDDebug_HUSB238.cpp new file mode 100644 index 000000000..41b739f85 --- /dev/null +++ b/source/Core/Threads/UI/logic/USBPDDebug_HUSB238.cpp @@ -0,0 +1,37 @@ +#include "HUB238.hpp" +#include "OperatingModes.h" +#include "ui_drawing.hpp" +#if POW_PD_EXT == 1 +#ifdef HAS_POWER_DEBUG_MENU +OperatingMode showPDDebug(const ButtonState buttons, guiContext *cxt) { + // Print out the USB-PD state + // Basically this is like the Debug menu, but instead we want to print out the PD status + uint16_t *screen = &(cxt->scratch_state.state1); + + if (*screen > 6) { + *screen = 0; + } + if (*screen == 0) { + // Print the PD Debug state + uint16_t temp = hub238_debug_state(); + ui_draw_usb_pd_debug_state(0, temp); + } else { + + // Print out the Proposed power options one by one + const uint8_t voltages[] = {5, 9, 12, 15, 18, 20}; + uint16_t voltage = voltages[*screen - 1]; + uint16_t currentx100 = hub238_getVoltagePDOCurrent(voltage); + + ui_draw_usb_pd_debug_pdo(*screen, 0, voltage, currentx100, 0); + } + + if (buttons == BUTTON_B_SHORT) { + return OperatingMode::InitialisationDone; + } else if (buttons == BUTTON_F_SHORT) { + *screen++; + } + + return OperatingMode::UsbPDDebug; +} +#endif +#endif diff --git a/source/Core/Threads/OperatingModes/utils/GUIDelay.cpp b/source/Core/Threads/UI/logic/utils/GUIDelay.cpp similarity index 100% rename from source/Core/Threads/OperatingModes/utils/GUIDelay.cpp rename to source/Core/Threads/UI/logic/utils/GUIDelay.cpp diff --git a/source/Core/Threads/UI/logic/utils/OperatingModeUtilities.h b/source/Core/Threads/UI/logic/utils/OperatingModeUtilities.h new file mode 100644 index 000000000..519bdad36 --- /dev/null +++ b/source/Core/Threads/UI/logic/utils/OperatingModeUtilities.h @@ -0,0 +1,18 @@ +#ifndef OPERATING_MODE_UTILITIES_H_ +#define OPERATING_MODE_UTILITIES_H_ +#include "Buttons.hpp" +#include "OLED.hpp" +#include "Settings.h" +#include + +void GUIDelay(); // +bool checkForUnderVoltage(void); // +uint32_t getSleepTimeout(void); // +uint32_t getHallEffectSleepTimeout(void); // +bool shouldBeSleeping(); // +bool shouldShutdown(void); // +void printVoltage(void); // +bool checkForUnderVoltage(void); // +uint16_t min(uint16_t a, uint16_t b); // +void printCountdownUntilSleep(int sleepThres); // +#endif diff --git a/source/Core/Threads/UI/logic/utils/SolderingCommon.cpp b/source/Core/Threads/UI/logic/utils/SolderingCommon.cpp new file mode 100644 index 000000000..e10df25c7 --- /dev/null +++ b/source/Core/Threads/UI/logic/utils/SolderingCommon.cpp @@ -0,0 +1,91 @@ +// +// Created by laura on 24.04.23. +// + +#include "SolderingCommon.h" +#include "OperatingModes.h" +#include "Types.h" +#include "configuration.h" +#include "history.hpp" +#include "ui_drawing.hpp" + +extern uint8_t heaterThermalRunawayCounter; + +bool checkExitSoldering(void) { +#ifdef POW_DC + // Undervoltage test + if (checkForUnderVoltage()) { + lastButtonTime = xTaskGetTickCount(); + return true; + } +#endif + +#ifdef ACCEL_EXITS_ON_MOVEMENT + // If the accel works in reverse where movement will cause exiting the soldering mode + if (getSettingValue(Sensitivity)) { + if (lastMovementTime) { + if (lastMovementTime > TICKS_SECOND * 10) { + // If we have moved recently; in the last second + // Then exit soldering mode + + // Movement occurred in last update + if (((TickType_t)(xTaskGetTickCount() - lastMovementTime)) < (TickType_t)(TICKS_SECOND / 5)) { + currentTempTargetDegC = 0; + lastMovementTime = 0; + return true; + } + } + } + } +#endif + + // If we have tripped thermal runaway, turn off heater and show warning + + return false; +} + +int8_t getPowerSourceNumber(void) { + int8_t sourceNumber = 0; + if (getIsPoweredByDCIN()) { + sourceNumber = 0; + } else { + // We are not powered via DC, so want to display the appropriate state for PD or QC + bool poweredbyPD = false; + bool pdHasVBUSConnected = false; +#ifdef POW_PD + if (USBPowerDelivery::fusbPresent()) { + // We are PD capable + if (USBPowerDelivery::negotiationComplete()) { + // We are powered via PD + poweredbyPD = true; +#ifdef VBUS_MOD_TEST + pdHasVBUSConnected = USBPowerDelivery::isVBUSConnected(); +#endif + } + } +#endif + if (poweredbyPD) { + if (pdHasVBUSConnected) { + sourceNumber = 2; + } else { + sourceNumber = 3; + } + } else { + sourceNumber = 1; + } + } + return sourceNumber; +} + +// Returns temperature of the tip in *C/*F (based on user settings) +TemperatureType_t getTipTemp(void) { +#ifdef FILTER_DISPLAYED_TIP_TEMP + static history Filter_Temp; + TemperatureType_t reading = getSettingValue(SettingsOptions::TemperatureInF) ? TipThermoModel::getTipInF() : TipThermoModel::getTipInC(); + Filter_Temp.update(reading); + return Filter_Temp.average(); + +#else + return getSettingValue(SettingsOptions::TemperatureInF) ? TipThermoModel::getTipInF() : TipThermoModel::getTipInC(); +#endif +} diff --git a/source/Core/Threads/UI/logic/utils/SolderingCommon.h b/source/Core/Threads/UI/logic/utils/SolderingCommon.h new file mode 100644 index 000000000..43d29240b --- /dev/null +++ b/source/Core/Threads/UI/logic/utils/SolderingCommon.h @@ -0,0 +1,9 @@ +#include "Types.h" +#include +#ifndef SOLDERING_COMMON_H_ +#define SOLDERING_COMMON_H_ + +bool checkExitSoldering(); +TemperatureType_t getTipTemp(void); + +#endif // SOLDERING_COMMON_H_ diff --git a/source/Core/Threads/OperatingModes/utils/checkUndervoltage.cpp b/source/Core/Threads/UI/logic/utils/checkUndervoltage.cpp similarity index 53% rename from source/Core/Threads/OperatingModes/utils/checkUndervoltage.cpp rename to source/Core/Threads/UI/logic/utils/checkUndervoltage.cpp index 158e88427..7580acd7e 100644 --- a/source/Core/Threads/OperatingModes/utils/checkUndervoltage.cpp +++ b/source/Core/Threads/UI/logic/utils/checkUndervoltage.cpp @@ -1,6 +1,7 @@ #include "Buttons.hpp" #include "OperatingModeUtilities.h" #include "configuration.h" +#include "ui_drawing.hpp" #ifdef POW_DC extern volatile TemperatureType_t currentTempTargetDegC; // returns true if undervoltage has occured @@ -15,21 +16,7 @@ bool checkForUnderVoltage(void) { if (xTaskGetTickCount() > (TICKS_SECOND * 2)) { if ((v < lookupVoltageLevel())) { currentTempTargetDegC = 0; - OLED::clearScreen(); - OLED::setCursor(0, 0); - if (getSettingValue(SettingsOptions::DetailedSoldering)) { - OLED::print(translatedString(Tr->UndervoltageString), FontStyle::SMALL); - OLED::setCursor(0, 8); - OLED::print(translatedString(Tr->InputVoltageString), FontStyle::SMALL); - printVoltage(); - OLED::print(SmallSymbolVolts, FontStyle::SMALL); - } else { - OLED::print(translatedString(Tr->UVLOWarningString), FontStyle::LARGE); - } - - OLED::refresh(); - GUIDelay(); - waitForButtonPress(); + ui_draw_warning_undervoltage(); return true; } } diff --git a/source/Core/Threads/UI/logic/utils/getHallEffectSleepTimeout.cpp b/source/Core/Threads/UI/logic/utils/getHallEffectSleepTimeout.cpp new file mode 100644 index 000000000..22028205a --- /dev/null +++ b/source/Core/Threads/UI/logic/utils/getHallEffectSleepTimeout.cpp @@ -0,0 +1,13 @@ +#include "OperatingModeUtilities.h" + +#ifndef NO_SLEEP_MODE +#ifdef HALL_SENSOR +uint32_t getHallEffectSleepTimeout(void) { + if (getSettingValue(SettingsOptions::HallEffectSensitivity) && getSettingValue(SettingsOptions::HallEffectSleepTime)) { + uint32_t sleepThres = getSettingValue(SettingsOptions::HallEffectSleepTime) * 5 * TICKS_SECOND; + return sleepThres; + } + return TICKS_SECOND; +} +#endif +#endif diff --git a/source/Core/Threads/OperatingModes/utils/getSleepTimeout.cpp b/source/Core/Threads/UI/logic/utils/getSleepTimeout.cpp similarity index 100% rename from source/Core/Threads/OperatingModes/utils/getSleepTimeout.cpp rename to source/Core/Threads/UI/logic/utils/getSleepTimeout.cpp diff --git a/source/Core/Threads/OperatingModes/utils/min.cpp b/source/Core/Threads/UI/logic/utils/min.cpp similarity index 100% rename from source/Core/Threads/OperatingModes/utils/min.cpp rename to source/Core/Threads/UI/logic/utils/min.cpp diff --git a/source/Core/Threads/OperatingModes/utils/shouldDeviceShutdown.cpp b/source/Core/Threads/UI/logic/utils/shouldDeviceShutdown.cpp similarity index 100% rename from source/Core/Threads/OperatingModes/utils/shouldDeviceShutdown.cpp rename to source/Core/Threads/UI/logic/utils/shouldDeviceShutdown.cpp diff --git a/source/Core/Threads/OperatingModes/utils/shouldDeviceSleep.cpp b/source/Core/Threads/UI/logic/utils/shouldDeviceSleep.cpp similarity index 81% rename from source/Core/Threads/OperatingModes/utils/shouldDeviceSleep.cpp rename to source/Core/Threads/UI/logic/utils/shouldDeviceSleep.cpp index 92a99fc9d..6b50800e8 100644 --- a/source/Core/Threads/OperatingModes/utils/shouldDeviceSleep.cpp +++ b/source/Core/Threads/UI/logic/utils/shouldDeviceSleep.cpp @@ -4,15 +4,13 @@ TickType_t lastHallEffectSleepStart = 0; extern TickType_t lastMovementTime; -bool shouldBeSleeping(bool inAutoStart) { +bool shouldBeSleeping() { #ifndef NO_SLEEP_MODE // Return true if the iron should be in sleep mode if (getSettingValue(SettingsOptions::Sensitivity) && getSettingValue(SettingsOptions::SleepTime)) { - if (inAutoStart) { - // In auto start we are asleep until movement - if (lastMovementTime == 0 && lastButtonTime == 0) { - return true; - } + // In auto start we are asleep until movement + if (lastMovementTime == 0 && lastButtonTime == 0) { + return true; } if (lastMovementTime > 0 || lastButtonTime > 0) { if (((xTaskGetTickCount() - lastMovementTime) > getSleepTimeout()) && ((xTaskGetTickCount() - lastButtonTime) > getSleepTimeout())) { @@ -34,7 +32,7 @@ bool shouldBeSleeping(bool inAutoStart) { if (lastHallEffectSleepStart == 0) { lastHallEffectSleepStart = xTaskGetTickCount(); } - if ((xTaskGetTickCount() - lastHallEffectSleepStart) > TICKS_SECOND) { + if ((xTaskGetTickCount() - lastHallEffectSleepStart) > getHallEffectSleepTimeout()) { return true; } } else { diff --git a/source/Core/brieflz/brieflz.c b/source/Core/brieflz/brieflz.c index e197f573b..5d2bbff70 100644 --- a/source/Core/brieflz/brieflz.c +++ b/source/Core/brieflz/brieflz.c @@ -32,14 +32,14 @@ #include #if _MSC_VER >= 1400 -# include -# define BLZ_BUILTIN_MSVC +#include +#define BLZ_BUILTIN_MSVC #elif defined(__clang__) && defined(__has_builtin) -# if __has_builtin(__builtin_clz) -# define BLZ_BUILTIN_GCC -# endif +#if __has_builtin(__builtin_clz) +#define BLZ_BUILTIN_GCC +#endif #elif __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) -# define BLZ_BUILTIN_GCC +#define BLZ_BUILTIN_GCC #endif // Type used to store values in workmem. @@ -60,270 +60,163 @@ typedef uint32_t blz_word; // compromise. // #ifndef BLZ_HASH_BITS -# define BLZ_HASH_BITS 17 +#define BLZ_HASH_BITS 17 #endif #define LOOKUP_SIZE (1UL << BLZ_HASH_BITS) -#define NO_MATCH_POS ((blz_word) -1) +#define NO_MATCH_POS ((blz_word) - 1) // Internal data structure struct blz_state { - unsigned char *next_out; - unsigned char *tag_out; - unsigned int tag; - int bits_left; + unsigned char *next_out; + unsigned char *tag_out; + unsigned int tag; + int bits_left; }; +// clang-format off #if !defined(BLZ_NO_LUT) static const unsigned short blz_gamma_lookup[512][2] = { - {0, 0}, - {0, 0}, - - {0x00, 2}, {0x02, 2}, - - {0x04, 4}, {0x06, 4}, {0x0C, 4}, {0x0E, 4}, - - {0x14, 6}, {0x16, 6}, {0x1C, 6}, {0x1E, 6}, - {0x34, 6}, {0x36, 6}, {0x3C, 6}, {0x3E, 6}, - - {0x54, 8}, {0x56, 8}, {0x5C, 8}, {0x5E, 8}, - {0x74, 8}, {0x76, 8}, {0x7C, 8}, {0x7E, 8}, - {0xD4, 8}, {0xD6, 8}, {0xDC, 8}, {0xDE, 8}, - {0xF4, 8}, {0xF6, 8}, {0xFC, 8}, {0xFE, 8}, - - {0x154, 10}, {0x156, 10}, {0x15C, 10}, {0x15E, 10}, - {0x174, 10}, {0x176, 10}, {0x17C, 10}, {0x17E, 10}, - {0x1D4, 10}, {0x1D6, 10}, {0x1DC, 10}, {0x1DE, 10}, - {0x1F4, 10}, {0x1F6, 10}, {0x1FC, 10}, {0x1FE, 10}, - {0x354, 10}, {0x356, 10}, {0x35C, 10}, {0x35E, 10}, - {0x374, 10}, {0x376, 10}, {0x37C, 10}, {0x37E, 10}, - {0x3D4, 10}, {0x3D6, 10}, {0x3DC, 10}, {0x3DE, 10}, - {0x3F4, 10}, {0x3F6, 10}, {0x3FC, 10}, {0x3FE, 10}, - - {0x554, 12}, {0x556, 12}, {0x55C, 12}, {0x55E, 12}, - {0x574, 12}, {0x576, 12}, {0x57C, 12}, {0x57E, 12}, - {0x5D4, 12}, {0x5D6, 12}, {0x5DC, 12}, {0x5DE, 12}, - {0x5F4, 12}, {0x5F6, 12}, {0x5FC, 12}, {0x5FE, 12}, - {0x754, 12}, {0x756, 12}, {0x75C, 12}, {0x75E, 12}, - {0x774, 12}, {0x776, 12}, {0x77C, 12}, {0x77E, 12}, - {0x7D4, 12}, {0x7D6, 12}, {0x7DC, 12}, {0x7DE, 12}, - {0x7F4, 12}, {0x7F6, 12}, {0x7FC, 12}, {0x7FE, 12}, - {0xD54, 12}, {0xD56, 12}, {0xD5C, 12}, {0xD5E, 12}, - {0xD74, 12}, {0xD76, 12}, {0xD7C, 12}, {0xD7E, 12}, - {0xDD4, 12}, {0xDD6, 12}, {0xDDC, 12}, {0xDDE, 12}, - {0xDF4, 12}, {0xDF6, 12}, {0xDFC, 12}, {0xDFE, 12}, - {0xF54, 12}, {0xF56, 12}, {0xF5C, 12}, {0xF5E, 12}, - {0xF74, 12}, {0xF76, 12}, {0xF7C, 12}, {0xF7E, 12}, - {0xFD4, 12}, {0xFD6, 12}, {0xFDC, 12}, {0xFDE, 12}, - {0xFF4, 12}, {0xFF6, 12}, {0xFFC, 12}, {0xFFE, 12}, - - {0x1554, 14}, {0x1556, 14}, {0x155C, 14}, {0x155E, 14}, - {0x1574, 14}, {0x1576, 14}, {0x157C, 14}, {0x157E, 14}, - {0x15D4, 14}, {0x15D6, 14}, {0x15DC, 14}, {0x15DE, 14}, - {0x15F4, 14}, {0x15F6, 14}, {0x15FC, 14}, {0x15FE, 14}, - {0x1754, 14}, {0x1756, 14}, {0x175C, 14}, {0x175E, 14}, - {0x1774, 14}, {0x1776, 14}, {0x177C, 14}, {0x177E, 14}, - {0x17D4, 14}, {0x17D6, 14}, {0x17DC, 14}, {0x17DE, 14}, - {0x17F4, 14}, {0x17F6, 14}, {0x17FC, 14}, {0x17FE, 14}, - {0x1D54, 14}, {0x1D56, 14}, {0x1D5C, 14}, {0x1D5E, 14}, - {0x1D74, 14}, {0x1D76, 14}, {0x1D7C, 14}, {0x1D7E, 14}, - {0x1DD4, 14}, {0x1DD6, 14}, {0x1DDC, 14}, {0x1DDE, 14}, - {0x1DF4, 14}, {0x1DF6, 14}, {0x1DFC, 14}, {0x1DFE, 14}, - {0x1F54, 14}, {0x1F56, 14}, {0x1F5C, 14}, {0x1F5E, 14}, - {0x1F74, 14}, {0x1F76, 14}, {0x1F7C, 14}, {0x1F7E, 14}, - {0x1FD4, 14}, {0x1FD6, 14}, {0x1FDC, 14}, {0x1FDE, 14}, - {0x1FF4, 14}, {0x1FF6, 14}, {0x1FFC, 14}, {0x1FFE, 14}, - {0x3554, 14}, {0x3556, 14}, {0x355C, 14}, {0x355E, 14}, - {0x3574, 14}, {0x3576, 14}, {0x357C, 14}, {0x357E, 14}, - {0x35D4, 14}, {0x35D6, 14}, {0x35DC, 14}, {0x35DE, 14}, - {0x35F4, 14}, {0x35F6, 14}, {0x35FC, 14}, {0x35FE, 14}, - {0x3754, 14}, {0x3756, 14}, {0x375C, 14}, {0x375E, 14}, - {0x3774, 14}, {0x3776, 14}, {0x377C, 14}, {0x377E, 14}, - {0x37D4, 14}, {0x37D6, 14}, {0x37DC, 14}, {0x37DE, 14}, - {0x37F4, 14}, {0x37F6, 14}, {0x37FC, 14}, {0x37FE, 14}, - {0x3D54, 14}, {0x3D56, 14}, {0x3D5C, 14}, {0x3D5E, 14}, - {0x3D74, 14}, {0x3D76, 14}, {0x3D7C, 14}, {0x3D7E, 14}, - {0x3DD4, 14}, {0x3DD6, 14}, {0x3DDC, 14}, {0x3DDE, 14}, - {0x3DF4, 14}, {0x3DF6, 14}, {0x3DFC, 14}, {0x3DFE, 14}, - {0x3F54, 14}, {0x3F56, 14}, {0x3F5C, 14}, {0x3F5E, 14}, - {0x3F74, 14}, {0x3F76, 14}, {0x3F7C, 14}, {0x3F7E, 14}, - {0x3FD4, 14}, {0x3FD6, 14}, {0x3FDC, 14}, {0x3FDE, 14}, - {0x3FF4, 14}, {0x3FF6, 14}, {0x3FFC, 14}, {0x3FFE, 14}, - - {0x5554, 16}, {0x5556, 16}, {0x555C, 16}, {0x555E, 16}, - {0x5574, 16}, {0x5576, 16}, {0x557C, 16}, {0x557E, 16}, - {0x55D4, 16}, {0x55D6, 16}, {0x55DC, 16}, {0x55DE, 16}, - {0x55F4, 16}, {0x55F6, 16}, {0x55FC, 16}, {0x55FE, 16}, - {0x5754, 16}, {0x5756, 16}, {0x575C, 16}, {0x575E, 16}, - {0x5774, 16}, {0x5776, 16}, {0x577C, 16}, {0x577E, 16}, - {0x57D4, 16}, {0x57D6, 16}, {0x57DC, 16}, {0x57DE, 16}, - {0x57F4, 16}, {0x57F6, 16}, {0x57FC, 16}, {0x57FE, 16}, - {0x5D54, 16}, {0x5D56, 16}, {0x5D5C, 16}, {0x5D5E, 16}, - {0x5D74, 16}, {0x5D76, 16}, {0x5D7C, 16}, {0x5D7E, 16}, - {0x5DD4, 16}, {0x5DD6, 16}, {0x5DDC, 16}, {0x5DDE, 16}, - {0x5DF4, 16}, {0x5DF6, 16}, {0x5DFC, 16}, {0x5DFE, 16}, - {0x5F54, 16}, {0x5F56, 16}, {0x5F5C, 16}, {0x5F5E, 16}, - {0x5F74, 16}, {0x5F76, 16}, {0x5F7C, 16}, {0x5F7E, 16}, - {0x5FD4, 16}, {0x5FD6, 16}, {0x5FDC, 16}, {0x5FDE, 16}, - {0x5FF4, 16}, {0x5FF6, 16}, {0x5FFC, 16}, {0x5FFE, 16}, - {0x7554, 16}, {0x7556, 16}, {0x755C, 16}, {0x755E, 16}, - {0x7574, 16}, {0x7576, 16}, {0x757C, 16}, {0x757E, 16}, - {0x75D4, 16}, {0x75D6, 16}, {0x75DC, 16}, {0x75DE, 16}, - {0x75F4, 16}, {0x75F6, 16}, {0x75FC, 16}, {0x75FE, 16}, - {0x7754, 16}, {0x7756, 16}, {0x775C, 16}, {0x775E, 16}, - {0x7774, 16}, {0x7776, 16}, {0x777C, 16}, {0x777E, 16}, - {0x77D4, 16}, {0x77D6, 16}, {0x77DC, 16}, {0x77DE, 16}, - {0x77F4, 16}, {0x77F6, 16}, {0x77FC, 16}, {0x77FE, 16}, - {0x7D54, 16}, {0x7D56, 16}, {0x7D5C, 16}, {0x7D5E, 16}, - {0x7D74, 16}, {0x7D76, 16}, {0x7D7C, 16}, {0x7D7E, 16}, - {0x7DD4, 16}, {0x7DD6, 16}, {0x7DDC, 16}, {0x7DDE, 16}, - {0x7DF4, 16}, {0x7DF6, 16}, {0x7DFC, 16}, {0x7DFE, 16}, - {0x7F54, 16}, {0x7F56, 16}, {0x7F5C, 16}, {0x7F5E, 16}, - {0x7F74, 16}, {0x7F76, 16}, {0x7F7C, 16}, {0x7F7E, 16}, - {0x7FD4, 16}, {0x7FD6, 16}, {0x7FDC, 16}, {0x7FDE, 16}, - {0x7FF4, 16}, {0x7FF6, 16}, {0x7FFC, 16}, {0x7FFE, 16}, - {0xD554, 16}, {0xD556, 16}, {0xD55C, 16}, {0xD55E, 16}, - {0xD574, 16}, {0xD576, 16}, {0xD57C, 16}, {0xD57E, 16}, - {0xD5D4, 16}, {0xD5D6, 16}, {0xD5DC, 16}, {0xD5DE, 16}, - {0xD5F4, 16}, {0xD5F6, 16}, {0xD5FC, 16}, {0xD5FE, 16}, - {0xD754, 16}, {0xD756, 16}, {0xD75C, 16}, {0xD75E, 16}, - {0xD774, 16}, {0xD776, 16}, {0xD77C, 16}, {0xD77E, 16}, - {0xD7D4, 16}, {0xD7D6, 16}, {0xD7DC, 16}, {0xD7DE, 16}, - {0xD7F4, 16}, {0xD7F6, 16}, {0xD7FC, 16}, {0xD7FE, 16}, - {0xDD54, 16}, {0xDD56, 16}, {0xDD5C, 16}, {0xDD5E, 16}, - {0xDD74, 16}, {0xDD76, 16}, {0xDD7C, 16}, {0xDD7E, 16}, - {0xDDD4, 16}, {0xDDD6, 16}, {0xDDDC, 16}, {0xDDDE, 16}, - {0xDDF4, 16}, {0xDDF6, 16}, {0xDDFC, 16}, {0xDDFE, 16}, - {0xDF54, 16}, {0xDF56, 16}, {0xDF5C, 16}, {0xDF5E, 16}, - {0xDF74, 16}, {0xDF76, 16}, {0xDF7C, 16}, {0xDF7E, 16}, - {0xDFD4, 16}, {0xDFD6, 16}, {0xDFDC, 16}, {0xDFDE, 16}, - {0xDFF4, 16}, {0xDFF6, 16}, {0xDFFC, 16}, {0xDFFE, 16}, - {0xF554, 16}, {0xF556, 16}, {0xF55C, 16}, {0xF55E, 16}, - {0xF574, 16}, {0xF576, 16}, {0xF57C, 16}, {0xF57E, 16}, - {0xF5D4, 16}, {0xF5D6, 16}, {0xF5DC, 16}, {0xF5DE, 16}, - {0xF5F4, 16}, {0xF5F6, 16}, {0xF5FC, 16}, {0xF5FE, 16}, - {0xF754, 16}, {0xF756, 16}, {0xF75C, 16}, {0xF75E, 16}, - {0xF774, 16}, {0xF776, 16}, {0xF77C, 16}, {0xF77E, 16}, - {0xF7D4, 16}, {0xF7D6, 16}, {0xF7DC, 16}, {0xF7DE, 16}, - {0xF7F4, 16}, {0xF7F6, 16}, {0xF7FC, 16}, {0xF7FE, 16}, - {0xFD54, 16}, {0xFD56, 16}, {0xFD5C, 16}, {0xFD5E, 16}, - {0xFD74, 16}, {0xFD76, 16}, {0xFD7C, 16}, {0xFD7E, 16}, - {0xFDD4, 16}, {0xFDD6, 16}, {0xFDDC, 16}, {0xFDDE, 16}, - {0xFDF4, 16}, {0xFDF6, 16}, {0xFDFC, 16}, {0xFDFE, 16}, - {0xFF54, 16}, {0xFF56, 16}, {0xFF5C, 16}, {0xFF5E, 16}, - {0xFF74, 16}, {0xFF76, 16}, {0xFF7C, 16}, {0xFF7E, 16}, - {0xFFD4, 16}, {0xFFD6, 16}, {0xFFDC, 16}, {0xFFDE, 16}, - {0xFFF4, 16}, {0xFFF6, 16}, {0xFFFC, 16}, {0xFFFE, 16} -}; + {0, 0}, {0, 0}, + + {0x00, 2}, {0x02, 2}, + + {0x04, 4}, {0x06, 4}, {0x0C, 4}, {0x0E, 4}, + + {0x14, 6}, {0x16, 6}, {0x1C, 6}, {0x1E, 6}, {0x34, 6}, {0x36, 6}, {0x3C, 6}, {0x3E, 6}, + + {0x54, 8}, {0x56, 8}, {0x5C, 8}, {0x5E, 8}, {0x74, 8}, {0x76, 8}, {0x7C, 8}, {0x7E, 8}, {0xD4, 8}, {0xD6, 8}, {0xDC, 8}, {0xDE, 8}, {0xF4, 8}, {0xF6, 8}, + {0xFC, 8}, {0xFE, 8}, + + {0x154, 10}, {0x156, 10}, {0x15C, 10}, {0x15E, 10}, {0x174, 10}, {0x176, 10}, {0x17C, 10}, {0x17E, 10}, {0x1D4, 10}, {0x1D6, 10}, {0x1DC, 10}, {0x1DE, 10}, {0x1F4, 10}, {0x1F6, 10}, + {0x1FC, 10}, {0x1FE, 10}, {0x354, 10}, {0x356, 10}, {0x35C, 10}, {0x35E, 10}, {0x374, 10}, {0x376, 10}, {0x37C, 10}, {0x37E, 10}, {0x3D4, 10}, {0x3D6, 10}, {0x3DC, 10}, {0x3DE, 10}, + {0x3F4, 10}, {0x3F6, 10}, {0x3FC, 10}, {0x3FE, 10}, + + {0x554, 12}, {0x556, 12}, {0x55C, 12}, {0x55E, 12}, {0x574, 12}, {0x576, 12}, {0x57C, 12}, {0x57E, 12}, {0x5D4, 12}, {0x5D6, 12}, {0x5DC, 12}, {0x5DE, 12}, {0x5F4, 12}, {0x5F6, 12}, + {0x5FC, 12}, {0x5FE, 12}, {0x754, 12}, {0x756, 12}, {0x75C, 12}, {0x75E, 12}, {0x774, 12}, {0x776, 12}, {0x77C, 12}, {0x77E, 12}, {0x7D4, 12}, {0x7D6, 12}, {0x7DC, 12}, {0x7DE, 12}, + {0x7F4, 12}, {0x7F6, 12}, {0x7FC, 12}, {0x7FE, 12}, {0xD54, 12}, {0xD56, 12}, {0xD5C, 12}, {0xD5E, 12}, {0xD74, 12}, {0xD76, 12}, {0xD7C, 12}, {0xD7E, 12}, {0xDD4, 12}, {0xDD6, 12}, + {0xDDC, 12}, {0xDDE, 12}, {0xDF4, 12}, {0xDF6, 12}, {0xDFC, 12}, {0xDFE, 12}, {0xF54, 12}, {0xF56, 12}, {0xF5C, 12}, {0xF5E, 12}, {0xF74, 12}, {0xF76, 12}, {0xF7C, 12}, {0xF7E, 12}, + {0xFD4, 12}, {0xFD6, 12}, {0xFDC, 12}, {0xFDE, 12}, {0xFF4, 12}, {0xFF6, 12}, {0xFFC, 12}, {0xFFE, 12}, + + {0x1554, 14}, {0x1556, 14}, {0x155C, 14}, {0x155E, 14}, {0x1574, 14}, {0x1576, 14}, {0x157C, 14}, {0x157E, 14}, {0x15D4, 14}, {0x15D6, 14}, {0x15DC, 14}, {0x15DE, 14}, {0x15F4, 14}, {0x15F6, 14}, + {0x15FC, 14}, {0x15FE, 14}, {0x1754, 14}, {0x1756, 14}, {0x175C, 14}, {0x175E, 14}, {0x1774, 14}, {0x1776, 14}, {0x177C, 14}, {0x177E, 14}, {0x17D4, 14}, {0x17D6, 14}, {0x17DC, 14}, {0x17DE, 14}, + {0x17F4, 14}, {0x17F6, 14}, {0x17FC, 14}, {0x17FE, 14}, {0x1D54, 14}, {0x1D56, 14}, {0x1D5C, 14}, {0x1D5E, 14}, {0x1D74, 14}, {0x1D76, 14}, {0x1D7C, 14}, {0x1D7E, 14}, {0x1DD4, 14}, {0x1DD6, 14}, + {0x1DDC, 14}, {0x1DDE, 14}, {0x1DF4, 14}, {0x1DF6, 14}, {0x1DFC, 14}, {0x1DFE, 14}, {0x1F54, 14}, {0x1F56, 14}, {0x1F5C, 14}, {0x1F5E, 14}, {0x1F74, 14}, {0x1F76, 14}, {0x1F7C, 14}, {0x1F7E, 14}, + {0x1FD4, 14}, {0x1FD6, 14}, {0x1FDC, 14}, {0x1FDE, 14}, {0x1FF4, 14}, {0x1FF6, 14}, {0x1FFC, 14}, {0x1FFE, 14}, {0x3554, 14}, {0x3556, 14}, {0x355C, 14}, {0x355E, 14}, {0x3574, 14}, {0x3576, 14}, + {0x357C, 14}, {0x357E, 14}, {0x35D4, 14}, {0x35D6, 14}, {0x35DC, 14}, {0x35DE, 14}, {0x35F4, 14}, {0x35F6, 14}, {0x35FC, 14}, {0x35FE, 14}, {0x3754, 14}, {0x3756, 14}, {0x375C, 14}, {0x375E, 14}, + {0x3774, 14}, {0x3776, 14}, {0x377C, 14}, {0x377E, 14}, {0x37D4, 14}, {0x37D6, 14}, {0x37DC, 14}, {0x37DE, 14}, {0x37F4, 14}, {0x37F6, 14}, {0x37FC, 14}, {0x37FE, 14}, {0x3D54, 14}, {0x3D56, 14}, + {0x3D5C, 14}, {0x3D5E, 14}, {0x3D74, 14}, {0x3D76, 14}, {0x3D7C, 14}, {0x3D7E, 14}, {0x3DD4, 14}, {0x3DD6, 14}, {0x3DDC, 14}, {0x3DDE, 14}, {0x3DF4, 14}, {0x3DF6, 14}, {0x3DFC, 14}, {0x3DFE, 14}, + {0x3F54, 14}, {0x3F56, 14}, {0x3F5C, 14}, {0x3F5E, 14}, {0x3F74, 14}, {0x3F76, 14}, {0x3F7C, 14}, {0x3F7E, 14}, {0x3FD4, 14}, {0x3FD6, 14}, {0x3FDC, 14}, {0x3FDE, 14}, {0x3FF4, 14}, {0x3FF6, 14}, + {0x3FFC, 14}, {0x3FFE, 14}, + + {0x5554, 16}, {0x5556, 16}, {0x555C, 16}, {0x555E, 16}, {0x5574, 16}, {0x5576, 16}, {0x557C, 16}, {0x557E, 16}, {0x55D4, 16}, {0x55D6, 16}, {0x55DC, 16}, {0x55DE, 16}, {0x55F4, 16}, {0x55F6, 16}, + {0x55FC, 16}, {0x55FE, 16}, {0x5754, 16}, {0x5756, 16}, {0x575C, 16}, {0x575E, 16}, {0x5774, 16}, {0x5776, 16}, {0x577C, 16}, {0x577E, 16}, {0x57D4, 16}, {0x57D6, 16}, {0x57DC, 16}, {0x57DE, 16}, + {0x57F4, 16}, {0x57F6, 16}, {0x57FC, 16}, {0x57FE, 16}, {0x5D54, 16}, {0x5D56, 16}, {0x5D5C, 16}, {0x5D5E, 16}, {0x5D74, 16}, {0x5D76, 16}, {0x5D7C, 16}, {0x5D7E, 16}, {0x5DD4, 16}, {0x5DD6, 16}, + {0x5DDC, 16}, {0x5DDE, 16}, {0x5DF4, 16}, {0x5DF6, 16}, {0x5DFC, 16}, {0x5DFE, 16}, {0x5F54, 16}, {0x5F56, 16}, {0x5F5C, 16}, {0x5F5E, 16}, {0x5F74, 16}, {0x5F76, 16}, {0x5F7C, 16}, {0x5F7E, 16}, + {0x5FD4, 16}, {0x5FD6, 16}, {0x5FDC, 16}, {0x5FDE, 16}, {0x5FF4, 16}, {0x5FF6, 16}, {0x5FFC, 16}, {0x5FFE, 16}, {0x7554, 16}, {0x7556, 16}, {0x755C, 16}, {0x755E, 16}, {0x7574, 16}, {0x7576, 16}, + {0x757C, 16}, {0x757E, 16}, {0x75D4, 16}, {0x75D6, 16}, {0x75DC, 16}, {0x75DE, 16}, {0x75F4, 16}, {0x75F6, 16}, {0x75FC, 16}, {0x75FE, 16}, {0x7754, 16}, {0x7756, 16}, {0x775C, 16}, {0x775E, 16}, + {0x7774, 16}, {0x7776, 16}, {0x777C, 16}, {0x777E, 16}, {0x77D4, 16}, {0x77D6, 16}, {0x77DC, 16}, {0x77DE, 16}, {0x77F4, 16}, {0x77F6, 16}, {0x77FC, 16}, {0x77FE, 16}, {0x7D54, 16}, {0x7D56, 16}, + {0x7D5C, 16}, {0x7D5E, 16}, {0x7D74, 16}, {0x7D76, 16}, {0x7D7C, 16}, {0x7D7E, 16}, {0x7DD4, 16}, {0x7DD6, 16}, {0x7DDC, 16}, {0x7DDE, 16}, {0x7DF4, 16}, {0x7DF6, 16}, {0x7DFC, 16}, {0x7DFE, 16}, + {0x7F54, 16}, {0x7F56, 16}, {0x7F5C, 16}, {0x7F5E, 16}, {0x7F74, 16}, {0x7F76, 16}, {0x7F7C, 16}, {0x7F7E, 16}, {0x7FD4, 16}, {0x7FD6, 16}, {0x7FDC, 16}, {0x7FDE, 16}, {0x7FF4, 16}, {0x7FF6, 16}, + {0x7FFC, 16}, {0x7FFE, 16}, {0xD554, 16}, {0xD556, 16}, {0xD55C, 16}, {0xD55E, 16}, {0xD574, 16}, {0xD576, 16}, {0xD57C, 16}, {0xD57E, 16}, {0xD5D4, 16}, {0xD5D6, 16}, {0xD5DC, 16}, {0xD5DE, 16}, + {0xD5F4, 16}, {0xD5F6, 16}, {0xD5FC, 16}, {0xD5FE, 16}, {0xD754, 16}, {0xD756, 16}, {0xD75C, 16}, {0xD75E, 16}, {0xD774, 16}, {0xD776, 16}, {0xD77C, 16}, {0xD77E, 16}, {0xD7D4, 16}, {0xD7D6, 16}, + {0xD7DC, 16}, {0xD7DE, 16}, {0xD7F4, 16}, {0xD7F6, 16}, {0xD7FC, 16}, {0xD7FE, 16}, {0xDD54, 16}, {0xDD56, 16}, {0xDD5C, 16}, {0xDD5E, 16}, {0xDD74, 16}, {0xDD76, 16}, {0xDD7C, 16}, {0xDD7E, 16}, + {0xDDD4, 16}, {0xDDD6, 16}, {0xDDDC, 16}, {0xDDDE, 16}, {0xDDF4, 16}, {0xDDF6, 16}, {0xDDFC, 16}, {0xDDFE, 16}, {0xDF54, 16}, {0xDF56, 16}, {0xDF5C, 16}, {0xDF5E, 16}, {0xDF74, 16}, {0xDF76, 16}, + {0xDF7C, 16}, {0xDF7E, 16}, {0xDFD4, 16}, {0xDFD6, 16}, {0xDFDC, 16}, {0xDFDE, 16}, {0xDFF4, 16}, {0xDFF6, 16}, {0xDFFC, 16}, {0xDFFE, 16}, {0xF554, 16}, {0xF556, 16}, {0xF55C, 16}, {0xF55E, 16}, + {0xF574, 16}, {0xF576, 16}, {0xF57C, 16}, {0xF57E, 16}, {0xF5D4, 16}, {0xF5D6, 16}, {0xF5DC, 16}, {0xF5DE, 16}, {0xF5F4, 16}, {0xF5F6, 16}, {0xF5FC, 16}, {0xF5FE, 16}, {0xF754, 16}, {0xF756, 16}, + {0xF75C, 16}, {0xF75E, 16}, {0xF774, 16}, {0xF776, 16}, {0xF77C, 16}, {0xF77E, 16}, {0xF7D4, 16}, {0xF7D6, 16}, {0xF7DC, 16}, {0xF7DE, 16}, {0xF7F4, 16}, {0xF7F6, 16}, {0xF7FC, 16}, {0xF7FE, 16}, + {0xFD54, 16}, {0xFD56, 16}, {0xFD5C, 16}, {0xFD5E, 16}, {0xFD74, 16}, {0xFD76, 16}, {0xFD7C, 16}, {0xFD7E, 16}, {0xFDD4, 16}, {0xFDD6, 16}, {0xFDDC, 16}, {0xFDDE, 16}, {0xFDF4, 16}, {0xFDF6, 16}, + {0xFDFC, 16}, {0xFDFE, 16}, {0xFF54, 16}, {0xFF56, 16}, {0xFF5C, 16}, {0xFF5E, 16}, {0xFF74, 16}, {0xFF76, 16}, {0xFF7C, 16}, {0xFF7E, 16}, {0xFFD4, 16}, {0xFFD6, 16}, {0xFFDC, 16}, {0xFFDE, 16}, + {0xFFF4, 16}, {0xFFF6, 16}, {0xFFFC, 16}, {0xFFFE, 16}}; #endif +// clang-format on -static int -blz_log2(unsigned long n) -{ - assert(n > 0); +static int blz_log2(unsigned long n) { + assert(n > 0); #if defined(BLZ_BUILTIN_MSVC) - unsigned long msb_pos; - _BitScanReverse(&msb_pos, n); - return (int) msb_pos; + unsigned long msb_pos; + _BitScanReverse(&msb_pos, n); + return (int)msb_pos; #elif defined(BLZ_BUILTIN_GCC) - return (int) sizeof(n) * CHAR_BIT - 1 - __builtin_clzl(n); + return (int)sizeof(n) * CHAR_BIT - 1 - __builtin_clzl(n); #else - int bits = 0; + int bits = 0; - while (n >>= 1) { - ++bits; - } + while (n >>= 1) { + ++bits; + } - return bits; + return bits; #endif } -static unsigned long -blz_gamma_cost(unsigned long n) -{ - assert(n >= 2); +static unsigned long blz_gamma_cost(unsigned long n) { + assert(n >= 2); - return 2 * (unsigned long) blz_log2(n); + return 2 * (unsigned long)blz_log2(n); } -static unsigned long -blz_match_cost(unsigned long pos, unsigned long len) -{ - return 1 + blz_gamma_cost(len - 2) + blz_gamma_cost((pos >> 8) + 2) + 8; -} +static unsigned long blz_match_cost(unsigned long pos, unsigned long len) { return 1 + blz_gamma_cost(len - 2) + blz_gamma_cost((pos >> 8) + 2) + 8; } // Heuristic to compare matches -static int -blz_match_better(unsigned long cur, unsigned long new_pos, unsigned long new_len, - unsigned long pos, unsigned long len) -{ - const unsigned long offs = cur - pos - 1; - const unsigned long new_offs = cur - new_pos - 1; - - return (new_len > len + 1) - || (new_len >= len + 1 && new_offs / 8 <= offs); +static int blz_match_better(unsigned long cur, unsigned long new_pos, unsigned long new_len, unsigned long pos, unsigned long len) { + const unsigned long offs = cur - pos - 1; + const unsigned long new_offs = cur - new_pos - 1; + + return (new_len > len + 1) || (new_len >= len + 1 && new_offs / 8 <= offs); } // Heuristic to compare match with match at next position -static int -blz_next_match_better(unsigned long cur, unsigned long new_pos, unsigned long new_len, - unsigned long pos, unsigned long len) -{ - const unsigned long offs = cur - pos - 1; - const unsigned long new_offs = cur + 1 - new_pos - 1; - - return (new_len > len + 1 && new_offs / 8 < offs) - || (new_len > len && new_offs < offs) - || (new_len >= len && new_offs < offs / 4); +static int blz_next_match_better(unsigned long cur, unsigned long new_pos, unsigned long new_len, unsigned long pos, unsigned long len) { + const unsigned long offs = cur - pos - 1; + const unsigned long new_offs = cur + 1 - new_pos - 1; + + return (new_len > len + 1 && new_offs / 8 < offs) || (new_len > len && new_offs < offs) || (new_len >= len && new_offs < offs / 4); } -static void -blz_putbit(struct blz_state *bs, unsigned int bit) -{ - // Check if tag is full - if (!bs->bits_left--) { - // Store tag - bs->tag_out[0] = bs->tag & 0x00FF; - bs->tag_out[1] = (bs->tag >> 8) & 0x00FF; - - // Init next tag - bs->tag_out = bs->next_out; - bs->next_out += 2; - bs->bits_left = 15; - } - - // Shift bit into tag - bs->tag = (bs->tag << 1) + bit; +static void blz_putbit(struct blz_state *bs, unsigned int bit) { + // Check if tag is full + if (!bs->bits_left--) { + // Store tag + bs->tag_out[0] = bs->tag & 0x00FF; + bs->tag_out[1] = (bs->tag >> 8) & 0x00FF; + + // Init next tag + bs->tag_out = bs->next_out; + bs->next_out += 2; + bs->bits_left = 15; + } + + // Shift bit into tag + bs->tag = (bs->tag << 1) + bit; } -static void -blz_putbits(struct blz_state *bs, unsigned long bits, int num) -{ - assert(num >= 0 && num <= 16); - assert((bits & (~0UL << num)) == 0); +static void blz_putbits(struct blz_state *bs, unsigned long bits, int num) { + assert(num >= 0 && num <= 16); + assert((bits & (~0UL << num)) == 0); - // Shift num bits into tag - unsigned long tag = ((unsigned long) bs->tag << num) | bits; - bs->tag = (unsigned int) tag; + // Shift num bits into tag + unsigned long tag = ((unsigned long)bs->tag << num) | bits; + bs->tag = (unsigned int)tag; - // Check if tag is full - if (bs->bits_left < num) { - const unsigned int top16 = (unsigned int) (tag >> (num - bs->bits_left)); + // Check if tag is full + if (bs->bits_left < num) { + const unsigned int top16 = (unsigned int)(tag >> (num - bs->bits_left)); - // Store tag - bs->tag_out[0] = top16 & 0x00FF; - bs->tag_out[1] = (top16 >> 8) & 0x00FF; + // Store tag + bs->tag_out[0] = top16 & 0x00FF; + bs->tag_out[1] = (top16 >> 8) & 0x00FF; - // Init next tag - bs->tag_out = bs->next_out; - bs->next_out += 2; + // Init next tag + bs->tag_out = bs->next_out; + bs->next_out += 2; - bs->bits_left += 16; - } + bs->bits_left += 16; + } - bs->bits_left -= num; + bs->bits_left -= num; } // Encode val using a universal code based on Elias gamma. @@ -352,63 +245,59 @@ blz_putbits(struct blz_state *bs, unsigned long bits, int num) // known it as the gamma2 code. I am not sure where it originated from, but I // can see I used it in aPLib around 1998. // -static void -blz_putgamma(struct blz_state *bs, unsigned long val) -{ - assert(val >= 2); +static void blz_putgamma(struct blz_state *bs, unsigned long val) { + assert(val >= 2); #if !defined(BLZ_NO_LUT) - // Output small values using lookup - if (val < 512) { - const unsigned int bits = blz_gamma_lookup[val][0]; - const unsigned int shift = blz_gamma_lookup[val][1]; + // Output small values using lookup + if (val < 512) { + const unsigned int bits = blz_gamma_lookup[val][0]; + const unsigned int shift = blz_gamma_lookup[val][1]; - blz_putbits(bs, bits, (int) shift); + blz_putbits(bs, bits, (int)shift); - return; - } + return; + } #endif - // Create a mask for the second-highest bit of val + // Create a mask for the second-highest bit of val #if defined(BLZ_BUILTIN_MSVC) - unsigned long msb_pos; - _BitScanReverse(&msb_pos, val); - unsigned long mask = 1UL << (msb_pos - 1); + unsigned long msb_pos; + _BitScanReverse(&msb_pos, val); + unsigned long mask = 1UL << (msb_pos - 1); #elif defined(BLZ_BUILTIN_GCC) - unsigned long mask = 1UL << ((int) sizeof(val) * CHAR_BIT - 2 - __builtin_clzl(val)); + unsigned long mask = 1UL << ((int)sizeof(val) * CHAR_BIT - 2 - __builtin_clzl(val)); #else - unsigned long mask = val >> 1; + unsigned long mask = val >> 1; - // Clear bits except highest - while (mask & (mask - 1)) { - mask &= mask - 1; - } + // Clear bits except highest + while (mask & (mask - 1)) { + mask &= mask - 1; + } #endif - // Output gamma2-encoded bits - blz_putbit(bs, (val & mask) ? 1 : 0); + // Output gamma2-encoded bits + blz_putbit(bs, (val & mask) ? 1 : 0); - while (mask >>= 1) { - blz_putbit(bs, 1); - blz_putbit(bs, (val & mask) ? 1 : 0); - } + while (mask >>= 1) { + blz_putbit(bs, 1); + blz_putbit(bs, (val & mask) ? 1 : 0); + } - blz_putbit(bs, 0); + blz_putbit(bs, 0); } -static unsigned char* -blz_finalize(struct blz_state *bs) -{ - // Trailing one bit to delimit any literal tags - blz_putbit(bs, 1); +static unsigned char *blz_finalize(struct blz_state *bs) { + // Trailing one bit to delimit any literal tags + blz_putbit(bs, 1); - // Shift last tag into position and store - bs->tag <<= bs->bits_left; - bs->tag_out[0] = bs->tag & 0x00FF; - bs->tag_out[1] = (bs->tag >> 8) & 0x00FF; + // Shift last tag into position and store + bs->tag <<= bs->bits_left; + bs->tag_out[0] = bs->tag & 0x00FF; + bs->tag_out[1] = (bs->tag >> 8) & 0x00FF; - // Return pointer one past end of output - return bs->next_out; + // Return pointer one past end of output + return bs->next_out; } // Hash four bytes starting a p. @@ -416,37 +305,22 @@ blz_finalize(struct blz_state *bs) // This is Fibonacci hashing, also known as Knuth's multiplicative hash. The // constant is a prime close to 2^32/phi. // -static unsigned long -blz_hash4_bits(const unsigned char *p, int bits) -{ - assert(bits > 0 && bits <= 32); +static unsigned long blz_hash4_bits(const unsigned char *p, int bits) { + assert(bits > 0 && bits <= 32); - uint32_t val = (uint32_t) p[0] - | ((uint32_t) p[1] << 8) - | ((uint32_t) p[2] << 16) - | ((uint32_t) p[3] << 24); + uint32_t val = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); - return (val * UINT32_C(2654435761)) >> (32 - bits); + return (val * UINT32_C(2654435761)) >> (32 - bits); } -static unsigned long -blz_hash4(const unsigned char *p) -{ - return blz_hash4_bits(p, BLZ_HASH_BITS); -} +static unsigned long blz_hash4(const unsigned char *p) { return blz_hash4_bits(p, BLZ_HASH_BITS); } -size_t -blz_max_packed_size(size_t src_size) -{ - return src_size + src_size / 8 + 64; -} +size_t blz_max_packed_size(size_t src_size) { return src_size + src_size / 8 + 64; } -size_t -blz_workmem_size(size_t src_size) -{ - (void) src_size; +size_t blz_workmem_size(size_t src_size) { + (void)src_size; - return LOOKUP_SIZE * sizeof(blz_word); + return LOOKUP_SIZE * sizeof(blz_word); } // Simple LZSS using hashing. @@ -454,117 +328,113 @@ blz_workmem_size(size_t src_size) // The lookup table stores the previous position in the input that had a given // hash value, or NO_MATCH_POS if none. // -unsigned long -blz_pack(const void *src, void *dst, unsigned long src_size, void *workmem) -{ - struct blz_state bs; - blz_word *const lookup = (blz_word *) workmem; - const unsigned char *const in = (const unsigned char *) src; - const unsigned long last_match_pos = src_size > 4 ? src_size - 4 : 0; - unsigned long hash_pos = 0; - unsigned long cur = 0; - - assert(src_size < BLZ_WORD_MAX); - - // Check for empty input - if (src_size == 0) { - return 0; - } - - bs.next_out = (unsigned char *) dst; - - // First byte verbatim - *bs.next_out++ = in[0]; - - // Check for 1 byte input - if (src_size == 1) { - return 1; - } - - // Initialize first tag - bs.tag_out = bs.next_out; - bs.next_out += 2; - bs.tag = 0; - bs.bits_left = 16; - - // Initialize lookup - for (unsigned long i = 0; i < LOOKUP_SIZE; ++i) { - lookup[i] = NO_MATCH_POS; - } - - // Main compression loop - for (cur = 1; cur <= last_match_pos; ) { - // Update lookup up to current position - while (hash_pos < cur) { - lookup[blz_hash4(&in[hash_pos])] = hash_pos; - hash_pos++; - } - - // Look up match for current position - const unsigned long pos = lookup[blz_hash4(&in[cur])]; - unsigned long len = 0; - - // Check match - if (pos != NO_MATCH_POS) { - const unsigned long len_limit = src_size - cur; - - while (len < len_limit - && in[pos + len] == in[cur + len]) { - ++len; - } - } - - // Output match or literal - // - // When offs >= 0x1FFE00, encoding a match of length 4 - // (37 bits) is longer than encoding 4 literals (36 bits). - // - // The value 0x7E00 is a heuristic that sacrifices some - // length 4 matches in the hope that there will be a better - // match at the next position. - if (len > 4 || (len == 4 && cur - pos - 1 < 0x7E00UL)) { - const unsigned long offs = cur - pos - 1; - - // Output match tag - blz_putbit(&bs, 1); - - // Output match length - blz_putgamma(&bs, len - 2); - - // Output match offset - blz_putgamma(&bs, (offs >> 8) + 2); - *bs.next_out++ = offs & 0x00FF; - - cur += len; - } - else { - // Output literal tag - blz_putbit(&bs, 0); - - // Copy literal - *bs.next_out++ = in[cur++]; - } - } - - // Output any remaining literals - while (cur < src_size) { - // Output literal tag - blz_putbit(&bs, 0); - - // Copy literal - *bs.next_out++ = in[cur++]; - } - - // Trailing one bit to delimit any literal tags - blz_putbit(&bs, 1); - - // Shift last tag into position and store - bs.tag <<= bs.bits_left; - bs.tag_out[0] = bs.tag & 0x00FF; - bs.tag_out[1] = (bs.tag >> 8) & 0x00FF; - - // Return compressed size - return (unsigned long) (bs.next_out - (unsigned char *) dst); +unsigned long blz_pack(const void *src, void *dst, unsigned long src_size, void *workmem) { + struct blz_state bs; + blz_word *const lookup = (blz_word *)workmem; + const unsigned char *const in = (const unsigned char *)src; + const unsigned long last_match_pos = src_size > 4 ? src_size - 4 : 0; + unsigned long hash_pos = 0; + unsigned long cur = 0; + + assert(src_size < BLZ_WORD_MAX); + + // Check for empty input + if (src_size == 0) { + return 0; + } + + bs.next_out = (unsigned char *)dst; + + // First byte verbatim + *bs.next_out++ = in[0]; + + // Check for 1 byte input + if (src_size == 1) { + return 1; + } + + // Initialize first tag + bs.tag_out = bs.next_out; + bs.next_out += 2; + bs.tag = 0; + bs.bits_left = 16; + + // Initialize lookup + for (unsigned long i = 0; i < LOOKUP_SIZE; ++i) { + lookup[i] = NO_MATCH_POS; + } + + // Main compression loop + for (cur = 1; cur <= last_match_pos;) { + // Update lookup up to current position + while (hash_pos < cur) { + lookup[blz_hash4(&in[hash_pos])] = hash_pos; + hash_pos++; + } + + // Look up match for current position + const unsigned long pos = lookup[blz_hash4(&in[cur])]; + unsigned long len = 0; + + // Check match + if (pos != NO_MATCH_POS) { + const unsigned long len_limit = src_size - cur; + + while (len < len_limit && in[pos + len] == in[cur + len]) { + ++len; + } + } + + // Output match or literal + // + // When offs >= 0x1FFE00, encoding a match of length 4 + // (37 bits) is longer than encoding 4 literals (36 bits). + // + // The value 0x7E00 is a heuristic that sacrifices some + // length 4 matches in the hope that there will be a better + // match at the next position. + if (len > 4 || (len == 4 && cur - pos - 1 < 0x7E00UL)) { + const unsigned long offs = cur - pos - 1; + + // Output match tag + blz_putbit(&bs, 1); + + // Output match length + blz_putgamma(&bs, len - 2); + + // Output match offset + blz_putgamma(&bs, (offs >> 8) + 2); + *bs.next_out++ = offs & 0x00FF; + + cur += len; + } else { + // Output literal tag + blz_putbit(&bs, 0); + + // Copy literal + *bs.next_out++ = in[cur++]; + } + } + + // Output any remaining literals + while (cur < src_size) { + // Output literal tag + blz_putbit(&bs, 0); + + // Copy literal + *bs.next_out++ = in[cur++]; + } + + // Trailing one bit to delimit any literal tags + blz_putbit(&bs, 1); + + // Shift last tag into position and store + bs.tag <<= bs.bits_left; + bs.tag_out[0] = bs.tag & 0x00FF; + bs.tag_out[1] = (bs.tag >> 8) & 0x00FF; + + // Return compressed size + return (unsigned long)(bs.next_out - (unsigned char *)dst); } // Include compression algorithms used by blz_pack_level @@ -573,59 +443,54 @@ blz_pack(const void *src, void *dst, unsigned long src_size, void *workmem) #include "brieflz_lazy.h" #include "brieflz_leparse.h" -size_t -blz_workmem_size_level(size_t src_size, int level) -{ - switch (level) { - case 1: - return blz_workmem_size(src_size); - case 2: - return blz_lazy_workmem_size(src_size); - case 3: - return blz_hashbucket_workmem_size(src_size, 2); - case 4: - return blz_hashbucket_workmem_size(src_size, 4); - case 5: - case 6: - case 7: - return blz_leparse_workmem_size(src_size); - case 8: - case 9: - case 10: - return blz_btparse_workmem_size(src_size); - default: - return (size_t) -1; - } +size_t blz_workmem_size_level(size_t src_size, int level) { + switch (level) { + case 1: + return blz_workmem_size(src_size); + case 2: + return blz_lazy_workmem_size(src_size); + case 3: + return blz_hashbucket_workmem_size(src_size, 2); + case 4: + return blz_hashbucket_workmem_size(src_size, 4); + case 5: + case 6: + case 7: + return blz_leparse_workmem_size(src_size); + case 8: + case 9: + case 10: + return blz_btparse_workmem_size(src_size); + default: + return (size_t)-1; + } } -unsigned long -blz_pack_level(const void *src, void *dst, unsigned long src_size, - void *workmem, int level) -{ - switch (level) { - case 1: - return blz_pack(src, dst, src_size, workmem); - case 2: - return blz_pack_lazy(src, dst, src_size, workmem); - case 3: - return blz_pack_hashbucket(src, dst, src_size, workmem, 2, 16); - case 4: - return blz_pack_hashbucket(src, dst, src_size, workmem, 4, 16); - case 5: - return blz_pack_leparse(src, dst, src_size, workmem, 1, 16); - case 6: - return blz_pack_leparse(src, dst, src_size, workmem, 8, 32); - case 7: - return blz_pack_leparse(src, dst, src_size, workmem, 64, 64); - case 8: - return blz_pack_btparse(src, dst, src_size, workmem, 16, 96); - case 9: - return blz_pack_btparse(src, dst, src_size, workmem, 32, 224); - case 10: - return blz_pack_btparse(src, dst, src_size, workmem, ULONG_MAX, ULONG_MAX); - default: - return BLZ_ERROR; - } +unsigned long blz_pack_level(const void *src, void *dst, unsigned long src_size, void *workmem, int level) { + switch (level) { + case 1: + return blz_pack(src, dst, src_size, workmem); + case 2: + return blz_pack_lazy(src, dst, src_size, workmem); + case 3: + return blz_pack_hashbucket(src, dst, src_size, workmem, 2, 16); + case 4: + return blz_pack_hashbucket(src, dst, src_size, workmem, 4, 16); + case 5: + return blz_pack_leparse(src, dst, src_size, workmem, 1, 16); + case 6: + return blz_pack_leparse(src, dst, src_size, workmem, 8, 32); + case 7: + return blz_pack_leparse(src, dst, src_size, workmem, 64, 64); + case 8: + return blz_pack_btparse(src, dst, src_size, workmem, 16, 96); + case 9: + return blz_pack_btparse(src, dst, src_size, workmem, 32, 224); + case 10: + return blz_pack_btparse(src, dst, src_size, workmem, ULONG_MAX, ULONG_MAX); + default: + return BLZ_ERROR; + } } // clang -g -O1 -fsanitize=fuzzer,address -DBLZ_FUZZING brieflz.c depack.c @@ -637,23 +502,27 @@ blz_pack_level(const void *src, void *dst, unsigned long src_size, #include #ifndef BLZ_FUZZ_LEVEL -# define BLZ_FUZZ_LEVEL 1 +#define BLZ_FUZZ_LEVEL 1 #endif -extern int -LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) -{ - if (size > ULONG_MAX / 2) { return 0; } - void *workmem = malloc(blz_workmem_size_level(size, BLZ_FUZZ_LEVEL)); - void *packed = malloc(blz_max_packed_size(size)); - void *depacked = malloc(size); - if (!workmem || !packed || !depacked) { abort(); } - unsigned long packed_size = blz_pack_level(data, packed, size, workmem, BLZ_FUZZ_LEVEL); - blz_depack(packed, depacked, size); - if (memcmp(data, depacked, size)) { abort(); } - free(depacked); - free(packed); - free(workmem); - return 0; +extern int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + if (size > ULONG_MAX / 2) { + return 0; + } + void *workmem = malloc(blz_workmem_size_level(size, BLZ_FUZZ_LEVEL)); + void *packed = malloc(blz_max_packed_size(size)); + void *depacked = malloc(size); + if (!workmem || !packed || !depacked) { + abort(); + } + unsigned long packed_size = blz_pack_level(data, packed, size, workmem, BLZ_FUZZ_LEVEL); + blz_depack(packed, depacked, size); + if (memcmp(data, depacked, size)) { + abort(); + } + free(depacked); + free(packed); + free(workmem); + return 0; } #endif diff --git a/source/Core/brieflz/depack.c b/source/Core/brieflz/depack.c index b2324cfd2..90499511e 100644 --- a/source/Core/brieflz/depack.c +++ b/source/Core/brieflz/depack.c @@ -29,243 +29,448 @@ /* Internal data structure */ struct blz_state { - const unsigned char *src; - unsigned char *dst; - unsigned int tag; - int bits_left; + const unsigned char *src; + unsigned char *dst; + unsigned int tag; + int bits_left; }; #if !defined(BLZ_NO_LUT) static const unsigned char blz_gamma_lookup[256][2] = { - /* 00xxxxxx = 2 */ - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, - {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}, + /* 00xxxxxx = 2 */ + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + { 2, 2}, + + /* 0100xxxx = 4 */ + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + { 4, 4}, + + /* 010100xx = 8 */ + { 8, 6}, + { 8, 6}, + { 8, 6}, + { 8, 6}, + + /* 01010100 = 16 01010101 = 16+ 01010110 = 17 01010111 = 17+ */ + {16, 8}, + {16, 0}, + {17, 8}, + {17, 0}, + + /* 010110xx = 9 */ + { 9, 6}, + { 9, 6}, + { 9, 6}, + { 9, 6}, + + /* 01011100 = 18 01011101 = 18+ 01011110 = 19 01011111 = 19+ */ + {18, 8}, + {18, 0}, + {19, 8}, + {19, 0}, + + /* 0110xxxx = 5 */ + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + { 5, 4}, + + /* 011100xx = 10 */ + {10, 6}, + {10, 6}, + {10, 6}, + {10, 6}, + + /* 01110100 = 20 01110101 = 20+ 01110110 = 21 01110111 = 21+ */ + {20, 8}, + {20, 0}, + {21, 8}, + {21, 0}, + + /* 011110xx = 11 */ + {11, 6}, + {11, 6}, + {11, 6}, + {11, 6}, + + /* 01111100 = 22 01111101 = 22+ 01111110 = 23 01111111 = 23+ */ + {22, 8}, + {22, 0}, + {23, 8}, + {23, 0}, + + /* 10xxxxxx = 3 */ + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + { 3, 2}, + + /* 1100xxxx = 6 */ + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + { 6, 4}, + + /* 110100xx = 12 */ + {12, 6}, + {12, 6}, + {12, 6}, + {12, 6}, + + /* 11010100 = 24 11010101 = 24+ 11010110 = 25 11010111 = 25+ */ + {24, 8}, + {24, 0}, + {25, 8}, + {25, 0}, + + /* 110110xx = 13 */ + {13, 6}, + {13, 6}, + {13, 6}, + {13, 6}, + + /* 11011100 = 26 11011101 = 26+ 11011110 = 27 11011111 = 27+ */ + {26, 8}, + {26, 0}, + {27, 8}, + {27, 0}, + + /* 1110xxxx = 7 */ + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + { 7, 4}, + + /* 111100xx = 14 */ + {14, 6}, + {14, 6}, + {14, 6}, + {14, 6}, + + /* 11110100 = 28 11110101 = 28+ 11110110 = 29 11110111 = 29+ */ + {28, 8}, + {28, 0}, + {29, 8}, + {29, 0}, + + /* 111110xx = 15 */ + {15, 6}, + {15, 6}, + {15, 6}, + {15, 6}, + + /* 11111100 = 30 11111101 = 30+ 11111110 = 31 11111111 = 31+ */ + {30, 8}, + {30, 0}, + {31, 8}, + {31, 0} +}; +#endif - /* 0100xxxx = 4 */ - {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, - {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, +static unsigned int blz_getbit(struct blz_state *bs) { + unsigned int bit; - /* 010100xx = 8 */ - {8, 6}, {8, 6}, {8, 6}, {8, 6}, + /* Check if tag is empty */ + if (!bs->bits_left--) { + /* Load next tag */ + bs->tag = (unsigned int)bs->src[0] | ((unsigned int)bs->src[1] << 8); + bs->src += 2; + bs->bits_left = 15; + } - /* 01010100 = 16 01010101 = 16+ 01010110 = 17 01010111 = 17+ */ - {16, 8}, {16, 0}, {17, 8}, {17, 0}, + /* Shift bit out of tag */ + bit = (bs->tag & 0x8000) ? 1 : 0; + bs->tag <<= 1; - /* 010110xx = 9 */ - {9, 6}, {9, 6}, {9, 6}, {9, 6}, + return bit; +} - /* 01011100 = 18 01011101 = 18+ 01011110 = 19 01011111 = 19+ */ - {18, 8}, {18, 0}, {19, 8}, {19, 0}, +static unsigned long blz_getgamma(struct blz_state *bs) { + unsigned long result = 1; - /* 0110xxxx = 5 */ - {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, - {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4}, +#if !defined(BLZ_NO_LUT) + /* Decode up to 8 bits of gamma2 code using lookup if possible */ + if (bs->bits_left >= 8) { + unsigned int top8 = (bs->tag >> 8) & 0x00FF; + int shift; + + result = blz_gamma_lookup[top8][0]; + shift = (int)blz_gamma_lookup[top8][1]; + + if (shift) { + bs->tag <<= shift; + bs->bits_left -= shift; + return result; + } + + bs->tag <<= 8; + bs->bits_left -= 8; + } +#endif - /* 011100xx = 10 */ - {10, 6}, {10, 6}, {10, 6}, {10, 6}, + /* Input gamma2-encoded bits */ + do { + result = (result << 1) + blz_getbit(bs); + } while (blz_getbit(bs)); - /* 01110100 = 20 01110101 = 20+ 01110110 = 21 01110111 = 21+ */ - {20, 8}, {20, 0}, {21, 8}, {21, 0}, + return result; +} - /* 011110xx = 11 */ - {11, 6}, {11, 6}, {11, 6}, {11, 6}, +unsigned long blz_depack(const void *src, void *dst, unsigned long depacked_size) { + struct blz_state bs; + unsigned long dst_size = 0; - /* 01111100 = 22 01111101 = 22+ 01111110 = 23 01111111 = 23+ */ - {22, 8}, {22, 0}, {23, 8}, {23, 0}, + bs.src = (const unsigned char *)src; + bs.dst = (unsigned char *)dst; - /* 10xxxxxx = 3 */ - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, - {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, {3, 2}, + /* Initialise to one bit left in tag; that bit is zero (a literal) */ + bs.bits_left = 1; + bs.tag = 0x4000; - /* 1100xxxx = 6 */ - {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, - {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, {6, 4}, + /* Main decompression loop */ + while (dst_size < depacked_size) { + if (blz_getbit(&bs)) { + /* Input match length and offset */ + unsigned long len = blz_getgamma(&bs) + 2; + unsigned long off = blz_getgamma(&bs) - 2; - /* 110100xx = 12 */ - {12, 6}, {12, 6}, {12, 6}, {12, 6}, + off = (off << 8) + (unsigned long)*bs.src++ + 1; - /* 11010100 = 24 11010101 = 24+ 11010110 = 25 11010111 = 25+ */ - {24, 8}, {24, 0}, {25, 8}, {25, 0}, + /* Copy match */ + { + const unsigned char *p = bs.dst - off; + unsigned long i; - /* 110110xx = 13 */ - {13, 6}, {13, 6}, {13, 6}, {13, 6}, + for (i = len; i > 0; --i) { + *bs.dst++ = *p++; + } + } - /* 11011100 = 26 11011101 = 26+ 11011110 = 27 11011111 = 27+ */ - {26, 8}, {26, 0}, {27, 8}, {27, 0}, + dst_size += len; + } else { + /* Copy literal */ + *bs.dst++ = *bs.src++; - /* 1110xxxx = 7 */ - {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, - {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}, + dst_size++; + } + } - /* 111100xx = 14 */ - {14, 6}, {14, 6}, {14, 6}, {14, 6}, + /* Return decompressed size */ + return dst_size; +} - /* 11110100 = 28 11110101 = 28+ 11110110 = 29 11110111 = 29+ */ - {28, 8}, {28, 0}, {29, 8}, {29, 0}, +unsigned long blz_depack_srcsize(const void *src, void *dst, unsigned long src_size) { + struct blz_state bs; + unsigned long dst_size = 0; + const unsigned char *src_end = src + src_size; - /* 111110xx = 15 */ - {15, 6}, {15, 6}, {15, 6}, {15, 6}, + bs.src = (const unsigned char *)src; + bs.dst = (unsigned char *)dst; - /* 11111100 = 30 11111101 = 30+ 11111110 = 31 11111111 = 31+ */ - {30, 8}, {30, 0}, {31, 8}, {31, 0} -}; -#endif + /* Initialise to one bit left in tag; that bit is zero (a literal) */ + bs.bits_left = 1; + bs.tag = 0x4000; -static unsigned int -blz_getbit(struct blz_state *bs) -{ - unsigned int bit; - - /* Check if tag is empty */ - if (!bs->bits_left--) { - /* Load next tag */ - bs->tag = (unsigned int) bs->src[0] - | ((unsigned int) bs->src[1] << 8); - bs->src += 2; - bs->bits_left = 15; - } - - /* Shift bit out of tag */ - bit = (bs->tag & 0x8000) ? 1 : 0; - bs->tag <<= 1; - - return bit; -} + /* Main decompression loop */ + while (bs.src < src_end) { + if (blz_getbit(&bs)) { + /* Input match length and offset */ + unsigned long len = blz_getgamma(&bs) + 2; + unsigned long off = blz_getgamma(&bs) - 2; -static unsigned long -blz_getgamma(struct blz_state *bs) -{ - unsigned long result = 1; + off = (off << 8) + (unsigned long)*bs.src++ + 1; -#if !defined(BLZ_NO_LUT) - /* Decode up to 8 bits of gamma2 code using lookup if possible */ - if (bs->bits_left >= 8) { - unsigned int top8 = (bs->tag >> 8) & 0x00FF; - int shift; - - result = blz_gamma_lookup[top8][0]; - shift = (int) blz_gamma_lookup[top8][1]; - - if (shift) { - bs->tag <<= shift; - bs->bits_left -= shift; - return result; - } - - bs->tag <<= 8; - bs->bits_left -= 8; - } -#endif + /* Copy match */ + { + const unsigned char *p = bs.dst - off; + unsigned long i; - /* Input gamma2-encoded bits */ - do { - result = (result << 1) + blz_getbit(bs); - } while (blz_getbit(bs)); + for (i = len; i > 0; --i) { + *bs.dst++ = *p++; + } + } - return result; -} + dst_size += len; + } else { + /* Copy literal */ + *bs.dst++ = *bs.src++; -unsigned long -blz_depack(const void *src, void *dst, unsigned long depacked_size) -{ - struct blz_state bs; - unsigned long dst_size = 0; - - bs.src = (const unsigned char *) src; - bs.dst = (unsigned char *) dst; - - /* Initialise to one bit left in tag; that bit is zero (a literal) */ - bs.bits_left = 1; - bs.tag = 0x4000; - - /* Main decompression loop */ - while (dst_size < depacked_size) { - if (blz_getbit(&bs)) { - /* Input match length and offset */ - unsigned long len = blz_getgamma(&bs) + 2; - unsigned long off = blz_getgamma(&bs) - 2; - - off = (off << 8) + (unsigned long) *bs.src++ + 1; - - /* Copy match */ - { - const unsigned char *p = bs.dst - off; - unsigned long i; - - for (i = len; i > 0; --i) { - *bs.dst++ = *p++; - } - } - - dst_size += len; - } - else { - /* Copy literal */ - *bs.dst++ = *bs.src++; - - dst_size++; - } - } - - /* Return decompressed size */ - return dst_size; -} + dst_size++; + } + } -unsigned long -blz_depack_srcsize(const void *src, void *dst, unsigned long src_size) -{ - struct blz_state bs; - unsigned long dst_size = 0; - const unsigned char *src_end = src + src_size; - - bs.src = (const unsigned char *) src; - bs.dst = (unsigned char *) dst; - - /* Initialise to one bit left in tag; that bit is zero (a literal) */ - bs.bits_left = 1; - bs.tag = 0x4000; - - /* Main decompression loop */ - while (bs.src < src_end) { - if (blz_getbit(&bs)) { - /* Input match length and offset */ - unsigned long len = blz_getgamma(&bs) + 2; - unsigned long off = blz_getgamma(&bs) - 2; - - off = (off << 8) + (unsigned long) *bs.src++ + 1; - - /* Copy match */ - { - const unsigned char *p = bs.dst - off; - unsigned long i; - - for (i = len; i > 0; --i) { - *bs.dst++ = *p++; - } - } - - dst_size += len; - } - else { - /* Copy literal */ - *bs.dst++ = *bs.src++; - - dst_size++; - } - } - - /* Return decompressed size */ - return dst_size; + /* Return decompressed size */ + return dst_size; } diff --git a/source/Makefile b/source/Makefile index d1c123a87..d97b10cd3 100644 --- a/source/Makefile +++ b/source/Makefile @@ -1,12 +1,12 @@ ifndef model -model:=Pinecil +model:=Pinecilv2 endif ALL_MINIWARE_MODELS=TS100 TS80 TS80P TS101 ALL_PINECIL_MODELS=Pinecil ALL_PINECIL_V2_MODELS=Pinecilv2 ALL_MHP30_MODELS=MHP30 -ALL_SEQURE_MODELS=S60 +ALL_SEQURE_MODELS=S60 S60P T55 ALL_MODELS=$(ALL_MINIWARE_MODELS) $(ALL_PINECIL_MODELS) $(ALL_MHP30_MODELS) $(ALL_PINECIL_V2_MODELS) $(ALL_SEQURE_MODELS) ifneq ($(model),$(filter $(model),$(ALL_MODELS))) @@ -20,7 +20,7 @@ HEXFILE_DIR=Hexfile OUTPUT_DIR_BASE=Objects OUTPUT_DIR=Objects/$(model) -ALL_LANGUAGES=BG CS DA DE EN ES FI FR HR HU IT JA_JP LT NL NL_BE NB PL PT RU SK SL SR_CYRL SR_LATN SV TR UK VI YUE_HK ZH_CN ZH_TW +ALL_LANGUAGES=BE BG CS DA DE EL EN ES ET FI FR HR HU IT JA_JP LT NB NL_BE NL PL PT RO RU SK SL SR_CYRL SR_LATN SV TR UK UZ VI YUE_HK ZH_CN ZH_TW LANGUAGE_GROUP_CJK_LANGS=EN JA_JP YUE_HK ZH_TW ZH_CN LANGUAGE_GROUP_CJK_NAME=Chinese+Japanese @@ -31,8 +31,8 @@ LANGUAGE_GROUP_CUSTOM_LANGS=$(custom_multi_langs) LANGUAGE_GROUP_CUSTOM_NAME=Custom endif -LANGUAGE_GROUP_CYRILLIC_LANGS=EN BG RU SR_CYRL SR_LATN UK -LANGUAGE_GROUP_CYRILLIC_NAME=Bulgarian+Russian+Serbian+Ukrainian +LANGUAGE_GROUP_CYRILLIC_LANGS=EN BE BG RU SR_CYRL SR_LATN UK +LANGUAGE_GROUP_CYRILLIC_NAME=Belorussian+Bulgarian+Russian+Serbian+Ukrainian LANGUAGE_GROUP_EUR_LANGS=EN $(filter-out $(LANGUAGE_GROUP_CJK_LANGS) $(LANGUAGE_GROUP_CYRILLIC_LANGS),$(ALL_LANGUAGES)) LANGUAGE_GROUP_EUR_NAME=European @@ -55,149 +55,24 @@ HOST_OUTPUT_DIR=Objects/host DEVICE_DFU_ADDRESS=0x08000000 DEVICE_DFU_VID_PID=0x28E9:0x0189 + # Enumerate all of the include directories (HAL source dirs are used for clang-format only) APP_INC_DIR=./Core/Inc -BRIEFLZ_INC_DIR=./Core/brieflz -MINIWARE_INC_CMSIS_DEVICE=./Core/BSP/Miniware/Vendor/CMSIS/Device/ST/STM32F1xx/Include -MINIWARE_CMSIS_CORE_INC_DIR=./Core/BSP/Miniware/Vendor/CMSIS/Include -MINIWARE_HAL_SRC_DIR=./Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver -MINIWARE_HAL_INC_DIR=./Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Inc -MINIWARE_HAL_LEGACY_INC_DIR=./Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Inc/Legacy -MINIWARE_STARTUP_DIR=./Startup -MINIWARE_INC_DIR=./Core/BSP/Miniware -MINIWARE_LD_FILE=./Core/BSP/Miniware/stm32f103.ld - -S60_INC_CMSIS_DEVICE=./Core/BSP/Sequre_S60/Vendor/CMSIS/Device/ST/STM32F1xx/Include -S60_CMSIS_CORE_INC_DIR=./Core/BSP/Sequre_S60/Vendor/CMSIS/Include -S60_HAL_SRC_DIR=./Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver -S60_HAL_INC_DIR=./Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc -S60_HAL_LEGACY_INC_DIR=./Core/BSP/Sequre_S60/Vendor/STM32F1xx_HAL_Driver/Inc/Legacy -S60_STARTUP_DIR=./Startup -S60_INC_DIR=./Core/BSP/Sequre_S60 -S60_LD_FILE=./Core/BSP/Sequre_S60/stm32f103.ld - -MHP30_INC_CMSIS_DEVICE=./Core/BSP/MHP30/Vendor/CMSIS/Device/ST/STM32F1xx/Include -MHP30_CMSIS_CORE_INC_DIR=./Core/BSP/MHP30/Vendor/CMSIS/Include -MHP30_HAL_SRC_DIR=./Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver -MHP30_HAL_INC_DIR=./Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Inc -MHP30_HAL_LEGACY_INC_DIR=./Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Inc/Legacy -MHP30_STARTUP_DIR=./Startup -MHP30_INC_DIR=./Core/BSP/MHP30 -MHP30_LD_FILE=./Core/BSP/MHP30/stm32f103.ld - -PINE_INC_DIR=./Core/BSP/Pinecil -PINE_VENDOR_SRC_DIR=./Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Source -PINE_VENDOR_INC_DIR=./Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Include -PINE_VENDOR_USB_INC_DIR=./Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Common/Include/Usb -PINE_NMSIS_INC_DIR=./Core/BSP/Pinecil/Vendor/NMSIS/Core/Include -PINE_FREERTOS_PORT_INC_DIR=./Core/BSP/Pinecil/Vendor/OS/FreeRTOS/Source/portable/GCC - -PINECILV2_DIR=./Core/BSP/Pinecilv2 -PINECILV2_MEM_DIR=$(PINECILV2_DIR)/MemMang -PINECILV2_SDK_DIR=$(PINECILV2_DIR)/bl_mcu_sdk - -PINECILV2_VENDOR_BSP_DIR=$(PINECILV2_SDK_DIR)/bsp -PINECILV2_VENDOR_BSP_COMMON_DIR=$(PINECILV2_VENDOR_BSP_DIR)/bsp_common -PINECILV2_VENDOR_BSP_BOARD_DIR=$(PINECILV2_VENDOR_BSP_DIR)/board -PINECILV2_VENDOR_BSP_PLATFORM_DIR=$(PINECILV2_VENDOR_BSP_COMMON_DIR)/platform -PINECILV2_VENDOR_BSP_USB_DIR=$(PINECILV2_VENDOR_BSP_COMMON_DIR)/usb - -PINECILV2_COMMON_DIR=$(PINECILV2_SDK_DIR)/common -PINECILV2_COMMON_BL_MATH_DIR=$(PINECILV2_COMMON_DIR)/bl_math -PINECILV2_COMMON_DEVICE_DIR=$(PINECILV2_COMMON_DIR)/device -PINECILV2_COMMON_LIST_DIR=$(PINECILV2_COMMON_DIR)/list -PINECILV2_COMMON_MISC_DIR=$(PINECILV2_COMMON_DIR)/misc -PINECILV2_COMMON_PARTITION_DIR=$(PINECILV2_COMMON_DIR)/partition -PINECILV2_COMMON_PID_DIR=$(PINECILV2_COMMON_DIR)/pid -PINECILV2_COMMON_RING_BUFFERDIR=$(PINECILV2_COMMON_DIR)/ring_buffer -PINECILV2_COMMON_SOFT_CRC_DIR=$(PINECILV2_COMMON_DIR)/soft_crc -PINECILV2_COMMON_TIMESTAMP_DIR=$(PINECILV2_COMMON_DIR)/timestamp - -PINECILV2_COMPONENTS_DIR=$(PINECILV2_SDK_DIR)/components -PINECILV2_COMPONENTS_FREERTOS_DIR=$(PINECILV2_COMPONENTS_DIR)/freertos -PINECILV2_COMPONENTS_FREERTOS_BL602_DIR=$(PINECILV2_COMPONENTS_FREERTOS_DIR)/portable/gcc/risc-v/bl702 - -PINECILV2_COMPONENTS_BLE_STACK_PORT_INCLUDE_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/port/include -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/include -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DRIVERS_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/include/drivers -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DRIVERS_BLUETOOTH_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/include/drivers/bluetooth -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_BLUETOOTH_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/include/bluetooth -PINECILV2_COMPONENTS_BLE_STACK_COMMON_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common -PINECILV2_COMPONENTS_BLE_STACK_COMMON_INCLUDE_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/include -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_MISC_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/include/misc -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_ZEPHYR_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/include/zephyr -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_NET_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/include/net -PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_TOOLCHAIN_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/include/toolchain -PINECILV2_COMPONENTS_BLE_STACK_TINYCRYPT_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/tinycrypt/include -PINECILV2_COMPONENTS_BLE_STACK_TINYCRYPT_INCLUDE_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/common/tinycrypt/include/tinycrypt -PINECILV2_COMPONENTS_BLE_STACK_HOST_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/host -PINECILV2_COMPONENTS_BLE_STACK_BL_HCI_WRAPPER_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/bl_hci_wrapper -PINECILV2_COMPONENTS_BLE_CONTROLLER_BLE_INC_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/blecontroller/ble_inc -PINECILV2_COMPONENTS_BLE_STACK_BC_DEC_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/ble_stack/sbc/dec - -# Binary blobs suck and they should be ashamed -PINECILV2_BLE_CRAPWARE_BLOB_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/blecontroller/lib -PINECILV2_RF_CRAPWARE_BLOB_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/bl702_rf/lib - -PINECILV2_COMPONENTS_NMSIS_DIR=$(PINECILV2_COMPONENTS_DIR)/nmsis -PINECILV2_COMPONENTS_NMSIS_CORE_INC_DIR=$(PINECILV2_COMPONENTS_NMSIS_DIR)/core/inc - -PINECILV2_COMPONENTS_USB_STACK_DIR=$(PINECILV2_COMPONENTS_DIR)/usb_stack -PINECILV2_COMPONENTS_USB_STACK_COMMON_DIR=$(PINECILV2_COMPONENTS_USB_STACK_DIR)/common -PINECILV2_COMPONENTS_USB_STACK_CORE_DIR=$(PINECILV2_COMPONENTS_USB_STACK_DIR)/core -PINECILV2_COMPONENTS_USB_STACK_CDC_DIR=$(PINECILV2_COMPONENTS_USB_STACK_DIR)/class/cdc -PINECILV2_COMPONENTS_USB_STACK_WINUSB_DIR=$(PINECILV2_COMPONENTS_USB_STACK_DIR)/class/winusb - -PINECILV2_DRIVERS_DIR=$(PINECILV2_SDK_DIR)/drivers/bl702_driver -PINECILV2_DRIVERS_HAL_DRV_INC_DIR=$(PINECILV2_DRIVERS_DIR)/hal_drv/inc -PINECILV2_DRIVERS_HAL_DRV_DEF_DIR=$(PINECILV2_DRIVERS_DIR)/hal_drv/default_config -PINECILV2_DRIVERS_REGS_DIR=$(PINECILV2_DRIVERS_DIR)/regs -PINECILV2_DRIVERS_RISCV_DIR=$(PINECILV2_DRIVERS_DIR)/risc-v -PINECILV2_DRIVERS_STARTUP_DIR=$(PINECILV2_DRIVERS_DIR)/startup -PINECILV2_DRIVERS_STD_DRV_DIR=$(PINECILV2_DRIVERS_DIR)/std_drv/inc - -SOURCE_MIDDLEWARES_DIR=./Middlewares -FRTOS_CMIS_INC_DIR=./Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS -FRTOS_INC_DIR=./Middlewares/Third_Party/FreeRTOS/Source/include -DRIVER_INC_DIR=./Core/Drivers +MIDDLEWARES_DIR=./Middlewares BSP_INC_DIR=./Core/BSP -THREADS_INC_DIR=./Core/Threads -THREADS_OP_MODES_INC_DIR=./Core/Threads/OperatingModes -THREADS_OP_MODES_TOOLS_INC_DIR=./Core/Threads/OperatingModes/utils - -SOURCE_THREADS_DIR=./Core/Threads +THREADS_DIR=./Core/Threads SOURCE_CORE_DIR=./Core/Src -SOURCE_BRIEFLZ_DIR=./Core/brieflz -SOURCE_DRIVERS_DIR=./Core/Drivers -INC_PD_DRIVERS_DIR=./Core/Drivers/usb-pd/include -PD_DRIVER_TESTS_DIR=./Core/Drivers/usb-pd/tests +BRIEFLZ_DIR=./Core/brieflz +DRIVERS_DIR=./Core/Drivers PD_DRIVER_DIR=./Core/Drivers/usb-pd +# Exclude USB-PD tests +PD_DRIVER_TESTS_DIR=./Core/Drivers/usb-pd/tests -# Excludes for clang-format -ALL_INCLUDES_EXCEPT:=-path $(BRIEFLZ_INC_DIR) \ - -o -path $(PD_DRIVER_DIR) \ - -o -path $(PINECILV2_SDK_DIR) \ - -o -path $(MINIWARE_HAL_INC_DIR) \ - -o -path $(S60_HAL_INC_DIR) \ - -o -path $(MHP30_HAL_INC_DIR) \ - -o -path $(PINE_VENDOR_INC_DIR) \ - -o -path $(MINIWARE_CMSIS_CORE_INC_DIR) \ - -o -path $(S60_CMSIS_CORE_INC_DIR) \ - -o -path $(MINIWARE_INC_CMSIS_DEVICE) \ - -o -path $(S60_INC_CMSIS_DEVICE) \ - -o -path $(MHP30_INC_CMSIS_DEVICE) \ - -o -not -name "configuration.h" - -ALL_SOURCE_EXCEPT:=-path $(SOURCE_BRIEFLZ_DIR) \ - -o -path $(PD_DRIVER_DIR) \ - -o -path $(PINECILV2_SDK_DIR) \ - -o -path $(MINIWARE_HAL_SRC_DIR) \ - -o -path $(S60_HAL_SRC_DIR) \ - -o -path $(MHP30_HAL_SRC_DIR) \ - -o -path $(PINE_VENDOR_SRC_DIR) \ - -o -path $(PINECILV2_MEM_DIR) +# Excludes for clang-format +ALL_INCLUDES_EXCEPT:=-path $(PD_DRIVER_DIR) -o -not -name "configuration.h" +ALL_SOURCE_EXCEPT:=-path $(PD_DRIVER_DIR) # Find-all's used for formatting; have to exclude external modules ALL_INCLUDES=$(shell find ./Core -type d \( $(ALL_INCLUDES_EXCEPT) \) -prune -false -o \( -type f \( -name '*.h' -o -name '*.hpp' \) \) ) ALL_SOURCE=$(shell find ./Core -type d \( $(ALL_SOURCE_EXCEPT) \) -prune -false -o \( -type f \( -name '*.c' -o -name '*.cpp' \) \) ) @@ -205,18 +80,12 @@ ALL_SOURCE=$(shell find ./Core -type d \( $(ALL_SOURCE_EXCEPT) \) -prune -f # Device dependent settings ifeq ($(model),$(filter $(model),$(ALL_MINIWARE_MODELS))) $(info Building for Miniware ) -DEVICE_INCLUDES=-I$(MINIWARE_INC_DIR) \ - -I$(MINIWARE_INC_CMSIS_DEVICE) \ - -I$(MINIWARE_CMSIS_CORE_INC_DIR) \ - -I$(MINIWARE_HAL_INC_DIR) \ - -I$(MINIWARE_HAL_LEGACY_INC_DIR) - DEVICE_BSP_DIR=./Core/BSP/Miniware -S_SRCS:=$(shell find $(MINIWARE_STARTUP_DIR) -type f -name '*.S') -LDSCRIPT=$(MINIWARE_LD_FILE) +LDSCRIPT=./Core/BSP/Miniware/stm32f103.ld ifeq ($(model),$(filter $(model),TS101)) -flash_size=126k +# 128K, but logo must be at 99K so their broken ass DFU can flash it +flash_size=98k bootldr_size=0x8000 DEVICE_DFU_ADDRESS=0x08008000 else @@ -249,15 +118,10 @@ endif # ALL_MINIWARE_MODELS ifeq ($(model),$(filter $(model),$(ALL_SEQURE_MODELS))) $(info Building for Sequre ) -DEVICE_INCLUDES=-I$(S60_INC_DIR) \ - -I$(S60_INC_CMSIS_DEVICE) \ - -I$(S60_CMSIS_CORE_INC_DIR) \ - -I$(S60_HAL_INC_DIR) \ - -I$(S60_HAL_LEGACY_INC_DIR) - -DEVICE_BSP_DIR=./Core/BSP/Sequre_S60 -S_SRCS:=$(shell find $(S60_STARTUP_DIR) -type f -name '*.S') -LDSCRIPT=$(S60_LD_FILE) + +DEVICE_BSP_DIR=./Core/BSP/Sequre +S_SRCS:=$(shell find $(DEVICE_BSP_DIR) -type f -name '*.S') +LDSCRIPT=./Core/BSP/Sequre/stm32f103.ld DEV_GLOBAL_DEFS=-D STM32F103T8Ux \ -D STM32F1 \ -D STM32 \ @@ -278,22 +142,22 @@ CPUFLAGS=-mcpu=cortex-m3 \ -mfloat-abi=soft flash_size=62k +ifeq ($(model), S60P) +bootldr_size=0x5000 +DEVICE_DFU_ADDRESS=0x08005000 +else +# S60 or T55 bootldr_size=0x4400 DEVICE_DFU_ADDRESS=0x08004400 +endif DEVICE_DFU_VID_PID=0x1209:0xDB42 endif # ALL_SEQURE_MODELS ifeq ($(model),$(filter $(model),$(ALL_MHP30_MODELS))) $(info Building for MHP30 ) -DEVICE_INCLUDES=-I$(MHP30_INC_DIR) \ - -I$(MHP30_INC_CMSIS_DEVICE) \ - -I$(MHP30_CMSIS_CORE_INC_DIR) \ - -I$(MHP30_HAL_INC_DIR) \ - -I$(MHP30_HAL_LEGACY_INC_DIR) DEVICE_BSP_DIR=./Core/BSP/MHP30 -S_SRCS:=$(shell find $(MHP30_STARTUP_DIR) -type f -name '*.S') -LDSCRIPT=$(MHP30_LD_FILE) +LDSCRIPT=./Core/BSP/MHP30/stm32f103.ld DEV_GLOBAL_DEFS=-D STM32F103T8Ux \ -D STM32F1 \ -D STM32 \ @@ -320,25 +184,20 @@ endif # ALL_MHP30_MODELS ifeq ($(model),$(ALL_PINECIL_MODELS)) $(info Building for Pine64 Pinecilv1) -DEVICE_INCLUDES=-I$(PINE_INC_DIR) \ - -I$(PINE_VENDOR_INC_DIR) \ - -I$(PINE_VENDOR_USB_INC_DIR) \ - -I$(PINE_NMSIS_INC_DIR) \ - -I$(PINE_FREERTOS_PORT_INC_DIR) + DEVICE_BSP_DIR=./Core/BSP/Pinecil -S_SRCS:=$(shell find $(PINE_INC_DIR) -type f -name '*.S') $(info $(S_SRCS) ) -ASM_INC=-I$(PINE_RISCV_INC_DIR) +S_SRCS:=$(shell find $(DEVICE_BSP_DIR) -type f -name '*.S') LDSCRIPT=./Core/BSP/Pinecil/Vendor/SoC/gd32vf103/Board/pinecil/Source/GCC/gcc_gd32vf103_flashxip.ld flash_size=128k bootldr_size=0x0 # Flags -CPUFLAGS=-march=rv32imac \ - -mabi=ilp32 \ - -mcmodel=medany \ - -fsigned-char \ - -fno-builtin \ +CPUFLAGS=-march=rv32imaczicsr \ + -mabi=ilp32 \ + -mcmodel=medany \ + -fsigned-char \ + -fno-builtin \ -nostartfiles DEV_LDFLAGS=-nostartfiles @@ -351,66 +210,13 @@ endif # ALL_PINECIL_MODELS ifeq ($(model),$(ALL_PINECIL_V2_MODELS)) $(info Building for Pine64 Pinecilv2 ) -DEVICE_INCLUDES=-I$(PINECILV2_DIR) \ - -I$(PINECILV2_SDK_DIR) \ - -I$(PINECILV2_VENDOR_BSP_COMMON_DIR) \ - -I$(PINECILV2_VENDOR_BSP_PLATFORM_DIR) \ - -I$(PINECILV2_COMMON_DIR) \ - -I$(PINECILV2_COMMON_BL_MATH_DIR) \ - -I$(PINECILV2_COMMON_DEVICE_DIR) \ - -I$(PINECILV2_COMMON_LIST_DIR) \ - -I$(PINECILV2_COMMON_MISC_DIR) \ - -I$(PINECILV2_COMMON_PARTITION_DIR) \ - -I$(PINECILV2_COMMON_PID_DIR) \ - -I$(PINECILV2_COMMON_RING_BUFFERDIR) \ - -I$(PINECILV2_COMMON_SOFT_CRC_DIR) \ - -I$(PINECILV2_COMMON_TIMESTAMP_DIR) \ - -I$(PINECILV2_COMPONENTS_DIR) \ - -I$(PINECILV2_COMPONENTS_FREERTOS_DIR) \ - -I$(PINECILV2_COMPONENTS_FREERTOS_BL602_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DRIVERS_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_DRIVERS_BLUETOOTH_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_PORT_INCLUDE_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_BLUETOOTH_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_COMMON_INCLUDE_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_COMMON_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_MISC_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_ZEPHYR_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_NET_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_TOOLCHAIN_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_INCLUDE_TOOLCHAIN_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_TINYCRYPT_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_TINYCRYPT_INCLUDE_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_HOST_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_BL_HCI_WRAPPER_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_CONTROLLER_BLE_INC_DIR) \ - -I$(PINECILV2_COMPONENTS_BLE_STACK_BC_DEC_DIR) \ - -I$(PINECILV2_COMPONENTS_NMSIS_DIR) \ - -I$(PINECILV2_COMPONENTS_USB_STACK_DIR) \ - -I$(PINECILV2_DRIVERS_DIR) \ - -I$(PINECILV2_DRIVERS_HAL_DRV_INC_DIR) \ - -I$(PINECILV2_DRIVERS_HAL_DRV_DEF_DIR) \ - -I$(PINECILV2_DRIVERS_REGS_DIR) \ - -I$(PINECILV2_DRIVERS_RISCV_DIR) \ - -I$(PINECILV2_DRIVERS_STARTUP_DIR) \ - -I$(PINECILV2_DRIVERS_STD_DRV_DIR) \ - -I$(PINECILV2_VENDOR_BSP_PLATFORM_DIR) \ - -I$(PINECILV2_VENDOR_BSP_USB_DIR) \ - -I$(PINECILV2_COMPONENTS_USB_STACK_COMMON_DIR) \ - -I$(PINECILV2_COMPONENTS_USB_STACK_CORE_DIR) \ - -I$(PINECILV2_COMPONENTS_USB_STACK_CDC_DIR) \ - -I$(PINECILV2_COMPONENTS_USB_STACK_WINUSB_DIR) \ - -I$(PINECILV2_COMPONENTS_NMSIS_CORE_INC_DIR) DEVICE_BSP_DIR=./Core/BSP/Pinecilv2 -S_SRCS:=$(shell find $(PINECILV2_DIR) -type d \( -path $(PINECILV2_VENDOR_BSP_COMMON_DIR) \) -prune -false -o -type f -name '*.S') $(info $(S_SRCS) ) -ASM_INC=$(DEVICE_INCLUDES) LDSCRIPT=./Core/BSP/Pinecilv2/bl_mcu_sdk/drivers/bl702_driver/bl702_flash.ld DEVICE_DFU_ADDRESS=0x23000000 # DFU starts at the beginning of flash # Flags -CPUFLAGS=-march=rv32imafc \ +CPUFLAGS=-march=rv32imafczicsr \ -mabi=ilp32f \ -mcmodel=medany \ -fsigned-char \ @@ -420,7 +226,13 @@ CPUFLAGS=-march=rv32imafc \ -DARCH_RISCV \ -D__RISCV_FEATURE_MVE=0 \ -DBL702 \ - -DBFLB_USE_ROM_DRIVER=1 \ + -DBFLB_USE_ROM_DRIVER=0 \ + +# Binary blobs suck and they should be ashamed +PINECILV2_SDK_DIR=$(DEVICE_BSP_DIR)/bl_mcu_sdk +PINECILV2_COMPONENTS_DIR=$(PINECILV2_SDK_DIR)/components +PINECILV2_BLE_CRAPWARE_BLOB_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/blecontroller/lib +PINECILV2_RF_CRAPWARE_BLOB_DIR=$(PINECILV2_COMPONENTS_DIR)/ble/bl702_rf/lib DEV_LDFLAGS=-nostartfiles \ -L $(PINECILV2_BLE_CRAPWARE_BLOB_DIR) \ @@ -439,7 +251,7 @@ DEV_GLOBAL_DEFS=-DCFG_FREERTOS \ -DCFG_BLE \ -DOPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER \ -DBL_MCU_SDK \ - -DCFG_CON=2 \ + -DCFG_CON=1 \ -DCFG_BLE_TX_BUFF_DATA=2 \ -DCONFIG_BT_PERIPHERAL \ -DCONFIG_BT_L2CAP_DYNAMIC_CHANNEL \ @@ -463,57 +275,60 @@ DEV_GLOBAL_DEFS=-DCFG_FREERTOS \ -DCONFIG_BT_SETTINGS_CCC_LAZY_LOADING \ -DCONFIG_BT_SETTINGS_USE_PRINTK \ -DCFG_SLEEP \ - -DCONFIG_BT_ALLROLES \ - -DCONFIG_BT_CENTRAL \ -DCONFIG_BT_OBSERVER \ -DCONFIG_BT_BROADCASTER \ - -DCFG_BLE_STACK_DBG_PRINT \ -DportasmHANDLE_INTERRUPT=FreeRTOS_Interrupt_Handler \ -DCONFIG_BT_DEVICE_NAME=\"Pinecil\" \ -DCONFIG_BT_DEVICE_APPEARANCE=0x06C1 + # -DCFG_BLE_STACK_DBG_PRINT \ + # -DCONFIG_BT_CENTRAL \ + # -DCONFIG_BT_ALLROLES \ # -DBFLB_USE_HAL_DRIVER \ # -DCONFIG_BT_SMP # Required to be turned off due to their drivers tripping warnings -DEV_CFLAGS=-Wno-error=enum-conversion -Wno-type-limits -Wno-implicit-fallthrough +DEV_CFLAGS=-Wno-error=enum-conversion -Wno-type-limits -Wno-implicit-fallthrough -Wno-error=implicit-function-declaration -Wno-error=incompatible-pointer-types DEV_CXXFLAGS=$(DEV_CFLAGS) flash_size=128k bootldr_size=0x0 endif # ALL_PINECIL_V2_MODELS -INCLUDES=-I$(APP_INC_DIR) \ - -I$(BRIEFLZ_INC_DIR) \ - -I$(FRTOS_CMIS_INC_DIR) \ - -I$(FRTOS_INC_DIR) \ - -I$(DRIVER_INC_DIR) \ - -I$(BSP_INC_DIR) \ - -I$(THREADS_INC_DIR) \ - -I$(THREADS_OP_MODES_INC_DIR) \ - -I$(THREADS_OP_MODES_TOOLS_INC_DIR) \ - -I$(INC_PD_DRIVERS_DIR) \ - $(DEVICE_INCLUDES) - -EXCLUDED_DIRS:=-path $(PINECILV2_VENDOR_BSP_ES8388_DIR) \ - -o -path $(PINECILV2_VENDOR_BSP_IMAGE_SENSOR_DIR) \ - -o -path $(PINECILV2_VENDOR_BSP_LVGL_DIR) \ - -o -path $(PINECILV2_VENDOR_BSP_MCU_LCD_DIR) \ - -o -path $(PINECILV2_VENDOR_BSP_BOARD_DIR) \ - -o -path $(PINECILV2_VENDOR_BSP_USB_DIR) - -SOURCE:=$(shell find $(SOURCE_THREADS_DIR) -type f -name '*.c') \ - $(shell find $(SOURCE_CORE_DIR) -type f -name '*.c') \ - $(shell find $(SOURCE_DRIVERS_DIR) -type f -name '*.c') \ - $(shell find $(DEVICE_BSP_DIR) -type d \( $(EXCLUDED_DIRS) \) -prune -false -o -type f -name '*.c') \ - $(shell find $(SOURCE_MIDDLEWARES_DIR) -type f -name '*.c') \ - $(SOURCE_BRIEFLZ_DIR)/depack.c +DEVICE_BSP_INCLUDE_DIRS:= ${shell find ${DEVICE_BSP_DIR} -type d -print} +THREADS_INCLUDE_DIRS:= ${shell find ${THREADS_DIR} -type d -print} +DRIVERS_INCLUDE_DIRS:= ${shell find ${DRIVERS_DIR} -type d -print} +BRIEFLZ_INCLUDE_DIRS:= ${shell find ${BRIEFLZ_DIR} -type d -print} +MIDDLEWARES_INCLUDE_DIRS:= ${shell find ${MIDDLEWARES_DIR} -type d -print} + + +INCLUDES=-I$(APP_INC_DIR) \ + -I$(BSP_INC_DIR) \ + ${patsubst %,-I%,${DEVICE_BSP_INCLUDE_DIRS}} \ + ${patsubst %,-I%,${THREADS_INCLUDE_DIRS}} \ + ${patsubst %,-I%,${DRIVERS_INCLUDE_DIRS}} \ + ${patsubst %,-I%,${BRIEFLZ_INCLUDE_DIRS}} \ + ${patsubst %,-I%,${MIDDLEWARES_INCLUDE_DIRS}} + +ASM_INC=$(INCLUDES) + + +SOURCE:=$(shell find ${THREADS_DIR} -type f -name '*.c') \ + $(shell find ${SOURCE_CORE_DIR} -type f -name '*.c') \ + $(shell find ${DRIVERS_DIR} -type f -name '*.c') \ + $(shell find ${DEVICE_BSP_DIR} -type f -name '*.c') \ + $(shell find ${MIDDLEWARES_DIR} -type f -name '*.c') \ + $(BRIEFLZ_DIR)/depack.c # We exclude the USB-PD stack tests $(PD_DRIVER_TESTS_DIR) -SOURCE_CPP:=$(shell find $(SOURCE_THREADS_DIR) -type f -name '*.cpp') \ - $(shell find $(SOURCE_CORE_DIR) -type f -name '*.cpp') \ - $(shell find $(SOURCE_DRIVERS_DIR) -path $(PD_DRIVER_TESTS_DIR) -prune -false -o -type f -name '*.cpp') \ - $(shell find $(DEVICE_BSP_DIR) -type d \( $(EXCLUDED_DIRS) \) -prune -false -o -type f -name '*.cpp') \ - $(shell find $(SOURCE_MIDDLEWARES_DIR) -type f -name '*.cpp') +SOURCE_CPP:=$(shell find ${THREADS_DIR} -type f -name '*.cpp') \ + $(shell find ${SOURCE_CORE_DIR} -type f -name '*.cpp') \ + $(shell find ${DRIVERS_DIR} -type f -name '*.cpp' -not -path "${PD_DRIVER_TESTS_DIR}/*" ) \ + $(shell find ${DEVICE_BSP_DIR} -type f -name '*.cpp') \ + $(shell find ${MIDDLEWARES_DIR} -type f -name '*.cpp') + + +S_SRCS:=$(shell find $(DEVICE_BSP_DIR) -type f -name '*.S') + # Code optimisation ------------------------------------------------------------ OPTIM=-Os \ @@ -523,7 +338,7 @@ OPTIM=-Os \ -fdevirtualize-at-ltrans \ -fmerge-all-constants \ -fshort-wchar \ - -flto \ + -flto=auto \ -finline-small-functions \ -finline-functions \ -findirect-inlining \ @@ -546,6 +361,12 @@ ifdef swd_enable GLOBAL_DEFINES+=-DSWD_ENABLE endif +ifeq ($(model),$(filter $(model),$(ALL_PINECIL_V2_MODELS))) +ifdef ws2812b_enable + GLOBAL_DEFINES += -DWS2812B_ENABLE +endif +endif + # Libs ------------------------------------------------------------------------- LIBS= @@ -610,6 +431,7 @@ CHECKOPTIONS=-Wtrigraphs \ -Wmissing-field-initializers \ -Wshadow \ -Wno-unused-parameter \ + -Wno-undef \ -Wdouble-promotion CHECKOPTIONS_C=$(CHECKOPTIONS) -Wbad-function-cast @@ -639,6 +461,7 @@ CFLAGS=$(DEV_CFLAGS) \ -D${COMPILER} \ -MMD \ -std=gnu11 \ + -g3 \ $(OPTIM) \ -T$(LDSCRIPT) \ -c @@ -734,26 +557,26 @@ Core/Gen/Translation.%.cpp $(OUTPUT_DIR)/Core/Gen/translation.files/%.pickle: .. @test -d $(OUTPUT_DIR)/Core/Gen/translation.files || mkdir -p $(OUTPUT_DIR)/Core/Gen/translation.files @echo 'Generating translations for language $*' @$(HOST_PYTHON) ../Translations/make_translation.py \ - --macros $(CURDIR)/Core/Gen/macros.txt \ - -o $(CURDIR)/Core/Gen/Translation.$*.cpp \ - --output-pickled $(OUTPUT_DIR)/Core/Gen/translation.files/$*.pickle \ + --macros "$(CURDIR)/Core/Gen/macros.txt" \ + -o "$(CURDIR)/Core/Gen/Translation.$*.cpp" \ + --output-pickled "$(OUTPUT_DIR)/Core/Gen/translation.files/$*.pickle" \ $* Core/Gen/macros.txt: Makefile - @test -d $(CURDIR)/Core/Gen || mkdir -p $(CURDIR)/Core/Gen - echo "#include " | $(CC) -dM -E $(CFLAGS) -MF $(CURDIR)/Core/Gen/macros.tmp - > $(CURDIR)/Core/Gen/macros.txt + @test -d "$(CURDIR)/Core/Gen" || mkdir -p "$(CURDIR)/Core/Gen" + echo "#include " | $(CC) -dM -E $(CFLAGS) -MF "$(CURDIR)/Core/Gen/macros.tmp" - > "$(CURDIR)/Core/Gen/macros.txt" # The recipes to produce compressed translation data $(OUTPUT_DIR)/Core/Gen/translation.files/%.o: Core/Gen/Translation.%.cpp @test -d $(@D) || mkdir -p $(@D) @echo Generating $@ - @$(CPP) -c $(filter-out -flto ,$(CXXFLAGS)) $< -o $@ + @$(CPP) -c $(filter-out -flto=auto ,$(CXXFLAGS)) $< -o $@ $(OUTPUT_DIR)/Core/Gen/translation.files/multi.%.o: Core/Gen/Translation_multi.%.cpp @test -d $(@D) || mkdir -p $(@D) @echo Generating $@ - @$(CPP) -c $(filter-out -flto ,$(CXXFLAGS)) $< -o $@ + @$(CPP) -c $(filter-out -flto=auto ,$(CXXFLAGS)) $< -o $@ $(HOST_OUTPUT_DIR)/brieflz/libbrieflz.so: Core/brieflz/brieflz.c Core/brieflz/depack.c @test -d $(@D) || mkdir -p $(@D) @@ -764,10 +587,10 @@ Core/Gen/Translation_brieflz.%.cpp: $(OUTPUT_DIR)/Core/Gen/translation.files/%.o @test -d $(@D) || mkdir -p $(@D) @echo Generating BriefLZ compressed translation for $* @OBJCOPY=$(OBJCOPY) $(HOST_PYTHON) ../Translations/make_translation.py \ - --macros $(CURDIR)/Core/Gen/macros.txt \ - -o $(CURDIR)/Core/Gen/Translation_brieflz.$*.cpp \ - --input-pickled $(OUTPUT_DIR)/Core/Gen/translation.files/$*.pickle \ - --strings-obj $(OUTPUT_DIR)/Core/Gen/translation.files/$*.o \ + --macros "$(CURDIR)/Core/Gen/macros.txt" \ + -o "$(CURDIR)/Core/Gen/Translation_brieflz.$*.cpp" \ + --input-pickled "$(OUTPUT_DIR)/Core/Gen/translation.files/$*.pickle" \ + --strings-obj "$(OUTPUT_DIR)/Core/Gen/translation.files/$*.o" \ $* Core/Gen/Translation_brieflz_font.%.cpp: $(OUTPUT_DIR)/Core/Gen/translation.files/%.pickle $(HOST_OUTPUT_DIR)/brieflz/libbrieflz.so Core/Gen/macros.txt @@ -819,9 +642,9 @@ Core/Gen/Translation_multi.$(1).cpp: $(patsubst %,../Translations/translation_%. @test -d $(OUTPUT_DIR)/Core/Gen/translation.files || mkdir -p $(OUTPUT_DIR)/Core/Gen/translation.files @echo 'Generating translations for multi-language $(2)' @$(HOST_PYTHON) ../Translations/make_translation.py \ - --macros $(CURDIR)/Core/Gen/macros.txt \ - -o $(CURDIR)/Core/Gen/Translation_multi.$(1).cpp \ - --output-pickled $(OUTPUT_DIR)/Core/Gen/translation.files/multi.$(1).pickle \ + --macros "$(CURDIR)/Core/Gen/macros.txt" \ + -o "$(CURDIR)/Core/Gen/Translation_multi.$(1).cpp" \ + --output-pickled "$(OUTPUT_DIR)/Core/Gen/translation.files/multi.$(1).pickle" \ $(3) $(OUTPUT_DIR)/Core/Gen/translation.files/multi.$(1).pickle: Core/Gen/Translation_multi.$(1).cpp @@ -830,10 +653,10 @@ Core/Gen/Translation_brieflz_multi.$(1).cpp: $(OUTPUT_DIR)/Core/Gen/translation. @test -d $$(@D) || mkdir -p $$(@D) @echo Generating BriefLZ compressed translation for multi-language $(2) @OBJCOPY=$(OBJCOPY) $(HOST_PYTHON) ../Translations/make_translation.py \ - --macros $(CURDIR)/Core/Gen/macros.txt \ - -o $(CURDIR)/Core/Gen/Translation_brieflz_multi.$(1).cpp \ - --input-pickled $(OUTPUT_DIR)/Core/Gen/translation.files/multi.$(1).pickle \ - --strings-obj $(OUTPUT_DIR)/Core/Gen/translation.files/multi.$(1).o \ + --macros "$(CURDIR)/Core/Gen/macros.txt" \ + -o "$(CURDIR)/Core/Gen/Translation_brieflz_multi.$(1).cpp" \ + --input-pickled "$(OUTPUT_DIR)/Core/Gen/translation.files/multi.$(1).pickle" \ + --strings-obj "$(OUTPUT_DIR)/Core/Gen/translation.files/multi.$(1).o" \ --compress-font \ $(3) diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS/cmsis_os.c b/source/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS/cmsis_os.c index c261427b5..2e8957954 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS/cmsis_os.c +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS/cmsis_os.c @@ -21,9 +21,9 @@ * Version 1.02 * Control functions for short timeouts in microsecond resolution: * Added: osKernelSysTick, osKernelSysTickFrequency, osKernelSysTickMicroSec - * Removed: osSignalGet - * - * + * Removed: osSignalGet + * + * *---------------------------------------------------------------------------- * * Portions Copyright � 2016 STMicroelectronics International N.V. All rights reserved. @@ -54,58 +54,59 @@ *---------------------------------------------------------------------------*/ /** - ****************************************************************************** - * @file cmsis_os.c - * @author MCD Application Team - * @date 03-March-2017 - * @brief CMSIS-RTOS API implementation for FreeRTOS V9.0.0 - ****************************************************************************** - * @attention - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted, provided that the following conditions are met: - * - * 1. Redistribution of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of other - * contributors to this software may be used to endorse or promote products - * derived from this software without specific written permission. - * 4. This software, including modifications and/or derivative works of this - * software, must execute solely and exclusively on microcontroller or - * microprocessor devices manufactured by or for STMicroelectronics. - * 5. Redistribution and use of this software other than as permitted under - * this license is void and will automatically terminate your rights under - * this license. - * - * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY - * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT - * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + ****************************************************************************** + * @file cmsis_os.c + * @author MCD Application Team + * @date 03-March-2017 + * @brief CMSIS-RTOS API implementation for FreeRTOS V9.0.0 + ****************************************************************************** + * @attention + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ -#include #include "cmsis_os.h" +#include "portmacro.h" +#include /* * ARM Compiler 4/5 */ #if defined(__CC_ARM) -#define __ASM __asm -#define __INLINE __inline +#define __ASM __asm +#define __INLINE __inline #define __STATIC_INLINE static __inline #include "cmsis_armcc.h" @@ -114,8 +115,8 @@ */ #elif defined(__GNUC__) -#define __ASM __asm /*!< asm keyword for GNU Compiler */ -#define __INLINE inline /*!< inline keyword for GNU Compiler */ +#define __ASM __asm /*!< asm keyword for GNU Compiler */ +#define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline uint32_t __get_IPSR(void); // #include "cmsis_gcc.h" @@ -141,12 +142,10 @@ uint32_t __get_IPSR(void); extern void xPortSysTickHandler(void); /* Convert from CMSIS type osPriority to FreeRTOS priority number */ -static unsigned portBASE_TYPE makeFreeRtosPriority(osPriority priority) -{ +static unsigned portBASE_TYPE makeFreeRtosPriority(osPriority priority) { unsigned portBASE_TYPE fpriority = tskIDLE_PRIORITY; - if (priority != osPriorityError) - { + if (priority != osPriorityError) { fpriority += (priority - osPriorityIdle); } @@ -155,12 +154,10 @@ static unsigned portBASE_TYPE makeFreeRtosPriority(osPriority priority) #if (INCLUDE_uxTaskPriorityGet == 1) /* Convert from FreeRTOS priority number to CMSIS type osPriority */ -static osPriority makeCmsisPriority(unsigned portBASE_TYPE fpriority) -{ +static osPriority makeCmsisPriority(unsigned portBASE_TYPE fpriority) { osPriority priority = osPriorityError; - if ((fpriority - tskIDLE_PRIORITY) <= (osPriorityRealtime - osPriorityIdle)) - { + if ((fpriority - tskIDLE_PRIORITY) <= (osPriorityRealtime - osPriorityIdle)) { priority = (osPriority)((int)osPriorityIdle + (int)(fpriority - tskIDLE_PRIORITY)); } @@ -169,43 +166,38 @@ static osPriority makeCmsisPriority(unsigned portBASE_TYPE fpriority) #endif /* Determine whether we are in thread mode or handler mode. */ -static int inHandlerMode(void) -{ - return __get_IPSR() != 0; -} +static int inHandlerMode(void) { return __get_IPSR() != 0; } /*********************** Kernel Control Functions *****************************/ /** -* @brief Initialize the RTOS Kernel for creating objects. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osKernelInitialize shall be consistent in every CMSIS-RTOS. -*/ + * @brief Initialize the RTOS Kernel for creating objects. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osKernelInitialize shall be consistent in every CMSIS-RTOS. + */ osStatus osKernelInitialize(void); /** -* @brief Start the RTOS Kernel with executing the specified thread. -* @param thread_def thread definition referenced with \ref osThread. -* @param argument pointer that is passed to the thread function as start argument. -* @retval status code that indicates the execution status of the function -* @note MUST REMAIN UNCHANGED: \b osKernelStart shall be consistent in every CMSIS-RTOS. -*/ -osStatus osKernelStart(void) -{ + * @brief Start the RTOS Kernel with executing the specified thread. + * @param thread_def thread definition referenced with \ref osThread. + * @param argument pointer that is passed to the thread function as start argument. + * @retval status code that indicates the execution status of the function + * @note MUST REMAIN UNCHANGED: \b osKernelStart shall be consistent in every CMSIS-RTOS. + */ +osStatus osKernelStart(void) { vTaskStartScheduler(); return osOK; } /** -* @brief Check if the RTOS kernel is already started -* @param None -* @retval (0) RTOS is not started -* (1) RTOS is started -* (-1) if this feature is disabled in FreeRTOSConfig.h -* @note MUST REMAIN UNCHANGED: \b osKernelRunning shall be consistent in every CMSIS-RTOS. -*/ -int32_t osKernelRunning(void) -{ + * @brief Check if the RTOS kernel is already started + * @param None + * @retval (0) RTOS is not started + * (1) RTOS is started + * (-1) if this feature is disabled in FreeRTOSConfig.h + * @note MUST REMAIN UNCHANGED: \b osKernelRunning shall be consistent in every CMSIS-RTOS. + */ +int32_t osKernelRunning(void) { #if ((INCLUDE_xTaskGetSchedulerState == 1) || (configUSE_TIMERS == 1)) if (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED) return 0; @@ -218,61 +210,45 @@ int32_t osKernelRunning(void) #if (defined(osFeature_SysTick) && (osFeature_SysTick != 0)) // System Timer available /** -* @brief Get the value of the Kernel SysTick timer -* @param None -* @retval None -* @note MUST REMAIN UNCHANGED: \b osKernelSysTick shall be consistent in every CMSIS-RTOS. -*/ -uint32_t osKernelSysTick(void) -{ - if (inHandlerMode()) - { + * @brief Get the value of the Kernel SysTick timer + * @param None + * @retval None + * @note MUST REMAIN UNCHANGED: \b osKernelSysTick shall be consistent in every CMSIS-RTOS. + */ +uint32_t osKernelSysTick(void) { + if (inHandlerMode()) { return xTaskGetTickCountFromISR(); - } - else - { + } else { return xTaskGetTickCount(); } } #endif // System Timer available /*********************** Thread Management *****************************/ /** -* @brief Create a thread and add it to Active Threads and set it to state READY. -* @param thread_def thread definition referenced with \ref osThread. -* @param argument pointer that is passed to the thread function as start argument. -* @retval thread ID for reference by other functions or NULL in case of error. -* @note MUST REMAIN UNCHANGED: \b osThreadCreate shall be consistent in every CMSIS-RTOS. -*/ -osThreadId osThreadCreate(const osThreadDef_t *thread_def, void *argument) -{ + * @brief Create a thread and add it to Active Threads and set it to state READY. + * @param thread_def thread definition referenced with \ref osThread. + * @param argument pointer that is passed to the thread function as start argument. + * @retval thread ID for reference by other functions or NULL in case of error. + * @note MUST REMAIN UNCHANGED: \b osThreadCreate shall be consistent in every CMSIS-RTOS. + */ +osThreadId osThreadCreate(const osThreadDef_t *thread_def, void *argument) { TaskHandle_t handle; #if (configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1) - if ((thread_def->buffer != NULL) && (thread_def->controlblock != NULL)) - { - handle = xTaskCreateStatic((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, - thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), + if ((thread_def->buffer != NULL) && (thread_def->controlblock != NULL)) { + handle = xTaskCreateStatic((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), thread_def->buffer, thread_def->controlblock); - } - else - { - if (xTaskCreate((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, - thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), - &handle) != pdPASS) - { + } else { + if (xTaskCreate((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), &handle) != pdPASS) { return NULL; } } #elif (configSUPPORT_STATIC_ALLOCATION == 1) - handle = xTaskCreateStatic((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, - thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), - thread_def->buffer, thread_def->controlblock); + handle = xTaskCreateStatic((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), thread_def->buffer, + thread_def->controlblock); #else - if (xTaskCreate((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, - thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), - &handle) != pdPASS) - { + if (xTaskCreate((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), &handle) != pdPASS) { return NULL; } #endif @@ -281,12 +257,11 @@ osThreadId osThreadCreate(const osThreadDef_t *thread_def, void *argument) } /** -* @brief Return the thread ID of the current running thread. -* @retval thread ID for reference by other functions or NULL in case of error. -* @note MUST REMAIN UNCHANGED: \b osThreadGetId shall be consistent in every CMSIS-RTOS. -*/ -osThreadId osThreadGetId(void) -{ + * @brief Return the thread ID of the current running thread. + * @retval thread ID for reference by other functions or NULL in case of error. + * @note MUST REMAIN UNCHANGED: \b osThreadGetId shall be consistent in every CMSIS-RTOS. + */ +osThreadId osThreadGetId(void) { #if ((INCLUDE_xTaskGetCurrentTaskHandle == 1) || (configUSE_MUTEXES == 1)) return xTaskGetCurrentTaskHandle(); #else @@ -295,13 +270,12 @@ osThreadId osThreadGetId(void) } /** -* @brief Terminate execution of a thread and remove it from Active Threads. -* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osThreadTerminate shall be consistent in every CMSIS-RTOS. -*/ -osStatus osThreadTerminate(osThreadId thread_id) -{ + * @brief Terminate execution of a thread and remove it from Active Threads. + * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osThreadTerminate shall be consistent in every CMSIS-RTOS. + */ +osStatus osThreadTerminate(osThreadId thread_id) { #if (INCLUDE_vTaskDelete == 1) vTaskDelete(thread_id); return osOK; @@ -311,26 +285,24 @@ osStatus osThreadTerminate(osThreadId thread_id) } /** -* @brief Pass control to next thread that is in state \b READY. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osThreadYield shall be consistent in every CMSIS-RTOS. -*/ -osStatus osThreadYield(void) -{ + * @brief Pass control to next thread that is in state \b READY. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osThreadYield shall be consistent in every CMSIS-RTOS. + */ +osStatus osThreadYield(void) { taskYIELD(); return osOK; } /** -* @brief Change priority of an active thread. -* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. -* @param priority new priority value for the thread function. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osThreadSetPriority shall be consistent in every CMSIS-RTOS. -*/ -osStatus osThreadSetPriority(osThreadId thread_id, osPriority priority) -{ + * @brief Change priority of an active thread. + * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. + * @param priority new priority value for the thread function. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osThreadSetPriority shall be consistent in every CMSIS-RTOS. + */ +osStatus osThreadSetPriority(osThreadId thread_id, osPriority priority) { #if (INCLUDE_vTaskPrioritySet == 1) vTaskPrioritySet(thread_id, makeFreeRtosPriority(priority)); return osOK; @@ -340,20 +312,16 @@ osStatus osThreadSetPriority(osThreadId thread_id, osPriority priority) } /** -* @brief Get current priority of an active thread. -* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. -* @retval current priority value of the thread function. -* @note MUST REMAIN UNCHANGED: \b osThreadGetPriority shall be consistent in every CMSIS-RTOS. -*/ -osPriority osThreadGetPriority(osThreadId thread_id) -{ + * @brief Get current priority of an active thread. + * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. + * @retval current priority value of the thread function. + * @note MUST REMAIN UNCHANGED: \b osThreadGetPriority shall be consistent in every CMSIS-RTOS. + */ +osPriority osThreadGetPriority(osThreadId thread_id) { #if (INCLUDE_uxTaskPriorityGet == 1) - if (inHandlerMode()) - { + if (inHandlerMode()) { return makeCmsisPriority(uxTaskPriorityGetFromISR(thread_id)); - } - else - { + } else { return makeCmsisPriority(uxTaskPriorityGet(thread_id)); } #else @@ -363,12 +331,11 @@ osPriority osThreadGetPriority(osThreadId thread_id) /*********************** Generic Wait Functions *******************************/ /** -* @brief Wait for Timeout (Time Delay) -* @param millisec time delay value -* @retval status code that indicates the execution status of the function. -*/ -osStatus osDelay(uint32_t millisec) -{ + * @brief Wait for Timeout (Time Delay) + * @param millisec time delay value + * @retval status code that indicates the execution status of the function. + */ +osStatus osDelay(uint32_t millisec) { #if INCLUDE_vTaskDelay TickType_t ticks = millisec / portTICK_PERIOD_MS; @@ -384,59 +351,45 @@ osStatus osDelay(uint32_t millisec) #if (defined(osFeature_Wait) && (osFeature_Wait != 0)) /* Generic Wait available */ /** -* @brief Wait for Signal, Message, Mail, or Timeout -* @param millisec timeout value or 0 in case of no time-out -* @retval event that contains signal, message, or mail information or error code. -* @note MUST REMAIN UNCHANGED: \b osWait shall be consistent in every CMSIS-RTOS. -*/ + * @brief Wait for Signal, Message, Mail, or Timeout + * @param millisec timeout value or 0 in case of no time-out + * @retval event that contains signal, message, or mail information or error code. + * @note MUST REMAIN UNCHANGED: \b osWait shall be consistent in every CMSIS-RTOS. + */ osEvent osWait(uint32_t millisec); #endif /* Generic Wait available */ /*********************** Timer Management Functions ***************************/ /** -* @brief Create a timer. -* @param timer_def timer object referenced with \ref osTimer. -* @param type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior. -* @param argument argument to the timer call back function. -* @retval timer ID for reference by other functions or NULL in case of error. -* @note MUST REMAIN UNCHANGED: \b osTimerCreate shall be consistent in every CMSIS-RTOS. -*/ -osTimerId osTimerCreate(const osTimerDef_t *timer_def, os_timer_type type, void *argument) -{ + * @brief Create a timer. + * @param timer_def timer object referenced with \ref osTimer. + * @param type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior. + * @param argument argument to the timer call back function. + * @retval timer ID for reference by other functions or NULL in case of error. + * @note MUST REMAIN UNCHANGED: \b osTimerCreate shall be consistent in every CMSIS-RTOS. + */ +osTimerId osTimerCreate(const osTimerDef_t *timer_def, os_timer_type type, void *argument) { #if (configUSE_TIMERS == 1) #if ((configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1)) - if (timer_def->controlblock != NULL) - { + if (timer_def->controlblock != NULL) { return xTimerCreateStatic((const char *)"", 1, // period should be filled when starting the Timer using osTimerStart - (type == osTimerPeriodic) ? pdTRUE : pdFALSE, - (void *)argument, - (TaskFunction_t)timer_def->ptimer, - (StaticTimer_t *)timer_def->controlblock); - } - else - { + (type == osTimerPeriodic) ? pdTRUE : pdFALSE, (void *)argument, (TaskFunction_t)timer_def->ptimer, (StaticTimer_t *)timer_def->controlblock); + } else { return xTimerCreate((const char *)"", 1, // period should be filled when starting the Timer using osTimerStart - (type == osTimerPeriodic) ? pdTRUE : pdFALSE, - (void *)argument, - (TaskFunction_t)timer_def->ptimer); + (type == osTimerPeriodic) ? pdTRUE : pdFALSE, (void *)argument, (TaskFunction_t)timer_def->ptimer); } #elif (configSUPPORT_STATIC_ALLOCATION == 1) return xTimerCreateStatic((const char *)"", 1, // period should be filled when starting the Timer using osTimerStart - (type == osTimerPeriodic) ? pdTRUE : pdFALSE, - (void *)argument, - (TaskFunction_t)timer_def->ptimer, - (StaticTimer_t *)timer_def->controlblock); + (type == osTimerPeriodic) ? pdTRUE : pdFALSE, (void *)argument, (TaskFunction_t)timer_def->ptimer, (StaticTimer_t *)timer_def->controlblock); #else return xTimerCreate((const char *)"", 1, // period should be filled when starting the Timer using osTimerStart - (type == osTimerPeriodic) ? pdTRUE : pdFALSE, - (void *)argument, - (TaskFunction_t)timer_def->ptimer); + (type == osTimerPeriodic) ? pdTRUE : pdFALSE, (void *)argument, (TaskFunction_t)timer_def->ptimer); #endif #else @@ -445,35 +398,28 @@ osTimerId osTimerCreate(const osTimerDef_t *timer_def, os_timer_type type, void } /** -* @brief Start or restart a timer. -* @param timer_id timer ID obtained by \ref osTimerCreate. -* @param millisec time delay value of the timer. -* @retval status code that indicates the execution status of the function -* @note MUST REMAIN UNCHANGED: \b osTimerStart shall be consistent in every CMSIS-RTOS. -*/ -osStatus osTimerStart(osTimerId timer_id, uint32_t millisec) -{ + * @brief Start or restart a timer. + * @param timer_id timer ID obtained by \ref osTimerCreate. + * @param millisec time delay value of the timer. + * @retval status code that indicates the execution status of the function + * @note MUST REMAIN UNCHANGED: \b osTimerStart shall be consistent in every CMSIS-RTOS. + */ +osStatus osTimerStart(osTimerId timer_id, uint32_t millisec) { osStatus result = osOK; #if (configUSE_TIMERS == 1) portBASE_TYPE taskWoken = pdFALSE; - TickType_t ticks = millisec / portTICK_PERIOD_MS; + TickType_t ticks = millisec / portTICK_PERIOD_MS; if (ticks == 0) ticks = 1; - if (inHandlerMode()) - { - if (xTimerChangePeriodFromISR(timer_id, ticks, &taskWoken) != pdPASS) - { + if (inHandlerMode()) { + if (xTimerChangePeriodFromISR(timer_id, ticks, &taskWoken) != pdPASS) { result = osErrorOS; - } - else - { + } else { portEND_SWITCHING_ISR(taskWoken); } - } - else - { + } else { if (xTimerChangePeriod(timer_id, ticks, 0) != pdPASS) result = osErrorOS; } @@ -485,29 +431,23 @@ osStatus osTimerStart(osTimerId timer_id, uint32_t millisec) } /** -* @brief Stop a timer. -* @param timer_id timer ID obtained by \ref osTimerCreate -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osTimerStop shall be consistent in every CMSIS-RTOS. -*/ -osStatus osTimerStop(osTimerId timer_id) -{ + * @brief Stop a timer. + * @param timer_id timer ID obtained by \ref osTimerCreate + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osTimerStop shall be consistent in every CMSIS-RTOS. + */ +osStatus osTimerStop(osTimerId timer_id) { osStatus result = osOK; #if (configUSE_TIMERS == 1) portBASE_TYPE taskWoken = pdFALSE; - if (inHandlerMode()) - { - if (xTimerStopFromISR(timer_id, &taskWoken) != pdPASS) - { + if (inHandlerMode()) { + if (xTimerStopFromISR(timer_id, &taskWoken) != pdPASS) { return osErrorOS; } portEND_SWITCHING_ISR(taskWoken); - } - else - { - if (xTimerStop(timer_id, 0) != pdPASS) - { + } else { + if (xTimerStop(timer_id, 0) != pdPASS) { result = osErrorOS; } } @@ -518,25 +458,20 @@ osStatus osTimerStop(osTimerId timer_id) } /** -* @brief Delete a timer. -* @param timer_id timer ID obtained by \ref osTimerCreate -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osTimerDelete shall be consistent in every CMSIS-RTOS. -*/ -osStatus osTimerDelete(osTimerId timer_id) -{ + * @brief Delete a timer. + * @param timer_id timer ID obtained by \ref osTimerCreate + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osTimerDelete shall be consistent in every CMSIS-RTOS. + */ +osStatus osTimerDelete(osTimerId timer_id) { osStatus result = osOK; #if (configUSE_TIMERS == 1) - if (inHandlerMode()) - { + if (inHandlerMode()) { return osErrorISR; - } - else - { - if ((xTimerDelete(timer_id, osWaitForever)) != pdPASS) - { + } else { + if ((xTimerDelete(timer_id, osWaitForever)) != pdPASS) { result = osErrorOS; } } @@ -548,26 +483,21 @@ osStatus osTimerDelete(osTimerId timer_id) return result; } - /**************************** Mutex Management ********************************/ /** -* @brief Create and Initialize a Mutex object -* @param mutex_def mutex definition referenced with \ref osMutex. -* @retval mutex ID for reference by other functions or NULL in case of error. -* @note MUST REMAIN UNCHANGED: \b osMutexCreate shall be consistent in every CMSIS-RTOS. -*/ -osMutexId osMutexCreate(const osMutexDef_t *mutex_def) -{ + * @brief Create and Initialize a Mutex object + * @param mutex_def mutex definition referenced with \ref osMutex. + * @retval mutex ID for reference by other functions or NULL in case of error. + * @note MUST REMAIN UNCHANGED: \b osMutexCreate shall be consistent in every CMSIS-RTOS. + */ +osMutexId osMutexCreate(const osMutexDef_t *mutex_def) { #if (configUSE_MUTEXES == 1) #if (configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1) - if (mutex_def->controlblock != NULL) - { + if (mutex_def->controlblock != NULL) { return xSemaphoreCreateMutexStatic(mutex_def->controlblock); - } - else - { + } else { return xSemaphoreCreateMutex(); } #elif (configSUPPORT_STATIC_ALLOCATION == 1) @@ -581,46 +511,36 @@ osMutexId osMutexCreate(const osMutexDef_t *mutex_def) } /** -* @brief Wait until a Mutex becomes available -* @param mutex_id mutex ID obtained by \ref osMutexCreate. -* @param millisec timeout value or 0 in case of no time-out. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osMutexWait shall be consistent in every CMSIS-RTOS. -*/ -osStatus osMutexWait(osMutexId mutex_id, uint32_t millisec) -{ - TickType_t ticks; + * @brief Wait until a Mutex becomes available + * @param mutex_id mutex ID obtained by \ref osMutexCreate. + * @param millisec timeout value or 0 in case of no time-out. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osMutexWait shall be consistent in every CMSIS-RTOS. + */ +osStatus osMutexWait(osMutexId mutex_id, uint32_t millisec) { + TickType_t ticks; portBASE_TYPE taskWoken = pdFALSE; - if (mutex_id == NULL) - { + if (mutex_id == NULL) { return osErrorParameter; } ticks = 0; - if (millisec == osWaitForever) - { + if (millisec == osWaitForever) { ticks = portMAX_DELAY; - } - else if (millisec != 0) - { + } else if (millisec != 0) { ticks = millisec / portTICK_PERIOD_MS; - if (ticks == 0) - { + if (ticks == 0) { ticks = 1; } } - if (inHandlerMode()) - { - if (xSemaphoreTakeFromISR(mutex_id, &taskWoken) != pdTRUE) - { + if (inHandlerMode()) { + if (xSemaphoreTakeFromISR(mutex_id, &taskWoken) != pdTRUE) { return osErrorOS; } portEND_SWITCHING_ISR(taskWoken); - } - else if (xSemaphoreTake(mutex_id, ticks) != pdTRUE) - { + } else if (xSemaphoreTake(mutex_id, ticks) != pdTRUE) { return osErrorOS; } @@ -628,41 +548,34 @@ osStatus osMutexWait(osMutexId mutex_id, uint32_t millisec) } /** -* @brief Release a Mutex that was obtained by \ref osMutexWait -* @param mutex_id mutex ID obtained by \ref osMutexCreate. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osMutexRelease shall be consistent in every CMSIS-RTOS. -*/ -osStatus osMutexRelease(osMutexId mutex_id) -{ - osStatus result = osOK; + * @brief Release a Mutex that was obtained by \ref osMutexWait + * @param mutex_id mutex ID obtained by \ref osMutexCreate. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osMutexRelease shall be consistent in every CMSIS-RTOS. + */ +osStatus osMutexRelease(osMutexId mutex_id) { + osStatus result = osOK; portBASE_TYPE taskWoken = pdFALSE; - if (inHandlerMode()) - { - if (xSemaphoreGiveFromISR(mutex_id, &taskWoken) != pdTRUE) - { + if (inHandlerMode()) { + if (xSemaphoreGiveFromISR(mutex_id, &taskWoken) != pdTRUE) { return osErrorOS; } portEND_SWITCHING_ISR(taskWoken); - } - else if (xSemaphoreGive(mutex_id) != pdTRUE) - { + } else if (xSemaphoreGive(mutex_id) != pdTRUE) { result = osErrorOS; } return result; } /** -* @brief Delete a Mutex -* @param mutex_id mutex ID obtained by \ref osMutexCreate. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osMutexDelete shall be consistent in every CMSIS-RTOS. -*/ -osStatus osMutexDelete(osMutexId mutex_id) -{ - if (inHandlerMode()) - { + * @brief Delete a Mutex + * @param mutex_id mutex ID obtained by \ref osMutexCreate. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osMutexDelete shall be consistent in every CMSIS-RTOS. + */ +osStatus osMutexDelete(osMutexId mutex_id) { + if (inHandlerMode()) { return osErrorISR; } @@ -676,42 +589,32 @@ osStatus osMutexDelete(osMutexId mutex_id) #if (defined(osFeature_Semaphore) && (osFeature_Semaphore != 0)) /** -* @brief Create and Initialize a Semaphore object used for managing resources -* @param semaphore_def semaphore definition referenced with \ref osSemaphore. -* @param count number of available resources. -* @retval semaphore ID for reference by other functions or NULL in case of error. -* @note MUST REMAIN UNCHANGED: \b osSemaphoreCreate shall be consistent in every CMSIS-RTOS. -*/ -osSemaphoreId osSemaphoreCreate(const osSemaphoreDef_t *semaphore_def, int32_t count) -{ + * @brief Create and Initialize a Semaphore object used for managing resources + * @param semaphore_def semaphore definition referenced with \ref osSemaphore. + * @param count number of available resources. + * @retval semaphore ID for reference by other functions or NULL in case of error. + * @note MUST REMAIN UNCHANGED: \b osSemaphoreCreate shall be consistent in every CMSIS-RTOS. + */ +osSemaphoreId osSemaphoreCreate(const osSemaphoreDef_t *semaphore_def, int32_t count) { #if (configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1) osSemaphoreId sema; - if (semaphore_def->controlblock != NULL) - { - if (count == 1) - { + if (semaphore_def->controlblock != NULL) { + if (count == 1) { return xSemaphoreCreateBinaryStatic(semaphore_def->controlblock); - } - else - { + } else { #if (configUSE_COUNTING_SEMAPHORES == 1) return xSemaphoreCreateCountingStatic(count, count, semaphore_def->controlblock); #else return NULL; #endif } - } - else - { - if (count == 1) - { + } else { + if (count == 1) { vSemaphoreCreateBinary(sema); return sema; - } - else - { + } else { #if (configUSE_COUNTING_SEMAPHORES == 1) return xSemaphoreCreateCounting(count, count); #else @@ -720,12 +623,9 @@ osSemaphoreId osSemaphoreCreate(const osSemaphoreDef_t *semaphore_def, int32_t c } } #elif (configSUPPORT_STATIC_ALLOCATION == 1) // configSUPPORT_DYNAMIC_ALLOCATION == 0 - if (count == 1) - { + if (count == 1) { return xSemaphoreCreateBinaryStatic(semaphore_def->controlblock); - } - else - { + } else { #if (configUSE_COUNTING_SEMAPHORES == 1) return xSemaphoreCreateCountingStatic(count, count, semaphore_def->controlblock); #else @@ -735,13 +635,10 @@ osSemaphoreId osSemaphoreCreate(const osSemaphoreDef_t *semaphore_def, int32_t c #else // configSUPPORT_STATIC_ALLOCATION == 0 && configSUPPORT_DYNAMIC_ALLOCATION == 1 osSemaphoreId sema; - if (count == 1) - { + if (count == 1) { vSemaphoreCreateBinary(sema); return sema; - } - else - { + } else { #if (configUSE_COUNTING_SEMAPHORES == 1) return xSemaphoreCreateCounting(count, count); #else @@ -752,46 +649,36 @@ osSemaphoreId osSemaphoreCreate(const osSemaphoreDef_t *semaphore_def, int32_t c } /** -* @brief Wait until a Semaphore token becomes available -* @param semaphore_id semaphore object referenced with \ref osSemaphore. -* @param millisec timeout value or 0 in case of no time-out. -* @retval number of available tokens, or -1 in case of incorrect parameters. -* @note MUST REMAIN UNCHANGED: \b osSemaphoreWait shall be consistent in every CMSIS-RTOS. -*/ -int32_t osSemaphoreWait(osSemaphoreId semaphore_id, uint32_t millisec) -{ - TickType_t ticks; + * @brief Wait until a Semaphore token becomes available + * @param semaphore_id semaphore object referenced with \ref osSemaphore. + * @param millisec timeout value or 0 in case of no time-out. + * @retval number of available tokens, or -1 in case of incorrect parameters. + * @note MUST REMAIN UNCHANGED: \b osSemaphoreWait shall be consistent in every CMSIS-RTOS. + */ +int32_t osSemaphoreWait(osSemaphoreId semaphore_id, uint32_t millisec) { + TickType_t ticks; portBASE_TYPE taskWoken = pdFALSE; - if (semaphore_id == NULL) - { + if (semaphore_id == NULL) { return osErrorParameter; } ticks = 0; - if (millisec == osWaitForever) - { + if (millisec == osWaitForever) { ticks = portMAX_DELAY; - } - else if (millisec != 0) - { + } else if (millisec != 0) { ticks = millisec / portTICK_PERIOD_MS; - if (ticks == 0) - { + if (ticks == 0) { ticks = 1; } } - if (inHandlerMode()) - { - if (xSemaphoreTakeFromISR(semaphore_id, &taskWoken) != pdTRUE) - { + if (inHandlerMode()) { + if (xSemaphoreTakeFromISR(semaphore_id, &taskWoken) != pdTRUE) { return osErrorOS; } portEND_SWITCHING_ISR(taskWoken); - } - else if (xSemaphoreTake(semaphore_id, ticks) != pdTRUE) - { + } else if (xSemaphoreTake(semaphore_id, ticks) != pdTRUE) { return osErrorOS; } @@ -799,28 +686,22 @@ int32_t osSemaphoreWait(osSemaphoreId semaphore_id, uint32_t millisec) } /** -* @brief Release a Semaphore token -* @param semaphore_id semaphore object referenced with \ref osSemaphore. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osSemaphoreRelease shall be consistent in every CMSIS-RTOS. -*/ -osStatus osSemaphoreRelease(osSemaphoreId semaphore_id) -{ - osStatus result = osOK; + * @brief Release a Semaphore token + * @param semaphore_id semaphore object referenced with \ref osSemaphore. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osSemaphoreRelease shall be consistent in every CMSIS-RTOS. + */ +osStatus osSemaphoreRelease(osSemaphoreId semaphore_id) { + osStatus result = osOK; portBASE_TYPE taskWoken = pdFALSE; - if (inHandlerMode()) - { - if (xSemaphoreGiveFromISR(semaphore_id, &taskWoken) != pdTRUE) - { + if (inHandlerMode()) { + if (xSemaphoreGiveFromISR(semaphore_id, &taskWoken) != pdTRUE) { return osErrorOS; } portEND_SWITCHING_ISR(taskWoken); - } - else - { - if (xSemaphoreGive(semaphore_id) != pdTRUE) - { + } else { + if (xSemaphoreGive(semaphore_id) != pdTRUE) { result = osErrorOS; } } @@ -829,15 +710,13 @@ osStatus osSemaphoreRelease(osSemaphoreId semaphore_id) } /** -* @brief Delete a Semaphore -* @param semaphore_id semaphore object referenced with \ref osSemaphore. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osSemaphoreDelete shall be consistent in every CMSIS-RTOS. -*/ -osStatus osSemaphoreDelete(osSemaphoreId semaphore_id) -{ - if (inHandlerMode()) - { + * @brief Delete a Semaphore + * @param semaphore_id semaphore object referenced with \ref osSemaphore. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osSemaphoreDelete shall be consistent in every CMSIS-RTOS. + */ +osStatus osSemaphoreDelete(osSemaphoreId semaphore_id) { + if (inHandlerMode()) { return osErrorISR; } @@ -852,13 +731,12 @@ osStatus osSemaphoreDelete(osSemaphoreId semaphore_id) #if (defined(osFeature_Pool) && (osFeature_Pool != 0)) -//TODO -//This is a primitive and inefficient wrapper around the existing FreeRTOS memory management. -//A better implementation will have to modify heap_x.c! +// TODO +// This is a primitive and inefficient wrapper around the existing FreeRTOS memory management. +// A better implementation will have to modify heap_x.c! -typedef struct os_pool_cb -{ - void *pool; +typedef struct os_pool_cb { + void *pool; uint8_t *markers; uint32_t pool_sz; uint32_t item_sz; @@ -866,51 +744,42 @@ typedef struct os_pool_cb } os_pool_cb_t; /** -* @brief Create and Initialize a memory pool -* @param pool_def memory pool definition referenced with \ref osPool. -* @retval memory pool ID for reference by other functions or NULL in case of error. -* @note MUST REMAIN UNCHANGED: \b osPoolCreate shall be consistent in every CMSIS-RTOS. -*/ -osPoolId osPoolCreate(const osPoolDef_t *pool_def) -{ + * @brief Create and Initialize a memory pool + * @param pool_def memory pool definition referenced with \ref osPool. + * @retval memory pool ID for reference by other functions or NULL in case of error. + * @note MUST REMAIN UNCHANGED: \b osPoolCreate shall be consistent in every CMSIS-RTOS. + */ +osPoolId osPoolCreate(const osPoolDef_t *pool_def) { #if (configSUPPORT_DYNAMIC_ALLOCATION == 1) osPoolId thePool; - int itemSize = 4 * ((pool_def->item_sz + 3) / 4); + int itemSize = 4 * ((pool_def->item_sz + 3) / 4); uint32_t i; /* First have to allocate memory for the pool control block. */ thePool = pvPortMalloc(sizeof(os_pool_cb_t)); - if (thePool) - { - thePool->pool_sz = pool_def->pool_sz; - thePool->item_sz = itemSize; + if (thePool) { + thePool->pool_sz = pool_def->pool_sz; + thePool->item_sz = itemSize; thePool->currentIndex = 0; /* Memory for markers */ thePool->markers = pvPortMalloc(pool_def->pool_sz); - if (thePool->markers) - { + if (thePool->markers) { /* Now allocate the pool itself. */ thePool->pool = pvPortMalloc(pool_def->pool_sz * itemSize); - if (thePool->pool) - { - for (i = 0; i < pool_def->pool_sz; i++) - { + if (thePool->pool) { + for (i = 0; i < pool_def->pool_sz; i++) { thePool->markers[i] = 0; } - } - else - { + } else { vPortFree(thePool->markers); vPortFree(thePool); thePool = NULL; } - } - else - { + } else { vPortFree(thePool); thePool = NULL; } @@ -924,50 +793,40 @@ osPoolId osPoolCreate(const osPoolDef_t *pool_def) } /** -* @brief Allocate a memory block from a memory pool -* @param pool_id memory pool ID obtain referenced with \ref osPoolCreate. -* @retval address of the allocated memory block or NULL in case of no memory available. -* @note MUST REMAIN UNCHANGED: \b osPoolAlloc shall be consistent in every CMSIS-RTOS. -*/ -void *osPoolAlloc(osPoolId pool_id) -{ - int dummy = 0; - void *p = NULL; + * @brief Allocate a memory block from a memory pool + * @param pool_id memory pool ID obtain referenced with \ref osPoolCreate. + * @retval address of the allocated memory block or NULL in case of no memory available. + * @note MUST REMAIN UNCHANGED: \b osPoolAlloc shall be consistent in every CMSIS-RTOS. + */ +void *osPoolAlloc(osPoolId pool_id) { + int dummy = 0; + void *p = NULL; uint32_t i; uint32_t index; - if (inHandlerMode()) - { + if (inHandlerMode()) { dummy = portSET_INTERRUPT_MASK_FROM_ISR(); - } - else - { + } else { vPortEnterCritical(); } - for (i = 0; i < pool_id->pool_sz; i++) - { + for (i = 0; i < pool_id->pool_sz; i++) { index = pool_id->currentIndex + i; - if (index >= pool_id->pool_sz) - { + if (index >= pool_id->pool_sz) { index = 0; } - if (pool_id->markers[index] == 0) - { + if (pool_id->markers[index] == 0) { pool_id->markers[index] = 1; - p = (void *)((uint32_t)(pool_id->pool) + (index * pool_id->item_sz)); - pool_id->currentIndex = index; + p = (void *)((uint32_t)(pool_id->pool) + (index * pool_id->item_sz)); + pool_id->currentIndex = index; break; } } - if (inHandlerMode()) - { + if (inHandlerMode()) { portCLEAR_INTERRUPT_MASK_FROM_ISR(dummy); - } - else - { + } else { vPortExitCritical(); } @@ -975,17 +834,15 @@ void *osPoolAlloc(osPoolId pool_id) } /** -* @brief Allocate a memory block from a memory pool and set memory block to zero -* @param pool_id memory pool ID obtain referenced with \ref osPoolCreate. -* @retval address of the allocated memory block or NULL in case of no memory available. -* @note MUST REMAIN UNCHANGED: \b osPoolCAlloc shall be consistent in every CMSIS-RTOS. -*/ -void *osPoolCAlloc(osPoolId pool_id) -{ + * @brief Allocate a memory block from a memory pool and set memory block to zero + * @param pool_id memory pool ID obtain referenced with \ref osPoolCreate. + * @retval address of the allocated memory block or NULL in case of no memory available. + * @note MUST REMAIN UNCHANGED: \b osPoolCAlloc shall be consistent in every CMSIS-RTOS. + */ +void *osPoolCAlloc(osPoolId pool_id) { void *p = osPoolAlloc(pool_id); - if (p != NULL) - { + if (p != NULL) { memset(p, 0, sizeof(pool_id->pool_sz)); } @@ -993,39 +850,33 @@ void *osPoolCAlloc(osPoolId pool_id) } /** -* @brief Return an allocated memory block back to a specific memory pool -* @param pool_id memory pool ID obtain referenced with \ref osPoolCreate. -* @param block address of the allocated memory block that is returned to the memory pool. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osPoolFree shall be consistent in every CMSIS-RTOS. -*/ -osStatus osPoolFree(osPoolId pool_id, void *block) -{ + * @brief Return an allocated memory block back to a specific memory pool + * @param pool_id memory pool ID obtain referenced with \ref osPoolCreate. + * @param block address of the allocated memory block that is returned to the memory pool. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osPoolFree shall be consistent in every CMSIS-RTOS. + */ +osStatus osPoolFree(osPoolId pool_id, void *block) { uint32_t index; - if (pool_id == NULL) - { + if (pool_id == NULL) { return osErrorParameter; } - if (block == NULL) - { + if (block == NULL) { return osErrorParameter; } - if (block < pool_id->pool) - { + if (block < pool_id->pool) { return osErrorParameter; } index = (uint32_t)block - (uint32_t)(pool_id->pool); - if (index % pool_id->item_sz) - { + if (index % pool_id->item_sz) { return osErrorParameter; } index = index / pool_id->item_sz; - if (index >= pool_id->pool_sz) - { + if (index >= pool_id->pool_sz) { return osErrorParameter; } @@ -1041,24 +892,20 @@ osStatus osPoolFree(osPoolId pool_id, void *block) #if (defined(osFeature_MessageQ) && (osFeature_MessageQ != 0)) /* Use Message Queues */ /** -* @brief Create and Initialize a Message Queue -* @param queue_def queue definition referenced with \ref osMessageQ. -* @param thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. -* @retval message queue ID for reference by other functions or NULL in case of error. -* @note MUST REMAIN UNCHANGED: \b osMessageCreate shall be consistent in every CMSIS-RTOS. -*/ -osMessageQId osMessageCreate(const osMessageQDef_t *queue_def, osThreadId thread_id) -{ + * @brief Create and Initialize a Message Queue + * @param queue_def queue definition referenced with \ref osMessageQ. + * @param thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. + * @retval message queue ID for reference by other functions or NULL in case of error. + * @note MUST REMAIN UNCHANGED: \b osMessageCreate shall be consistent in every CMSIS-RTOS. + */ +osMessageQId osMessageCreate(const osMessageQDef_t *queue_def, osThreadId thread_id) { (void)thread_id; #if (configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1) - if ((queue_def->buffer != NULL) && (queue_def->controlblock != NULL)) - { + if ((queue_def->buffer != NULL) && (queue_def->controlblock != NULL)) { return xQueueCreateStatic(queue_def->queue_sz, queue_def->item_sz, queue_def->buffer, queue_def->controlblock); - } - else - { + } else { return xQueueCreate(queue_def->queue_sz, queue_def->item_sz); } #elif (configSUPPORT_STATIC_ALLOCATION == 1) @@ -1069,36 +916,29 @@ osMessageQId osMessageCreate(const osMessageQDef_t *queue_def, osThreadId thread } /** -* @brief Put a Message to a Queue. -* @param queue_id message queue ID obtained with \ref osMessageCreate. -* @param info message information. -* @param millisec timeout value or 0 in case of no time-out. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osMessagePut shall be consistent in every CMSIS-RTOS. -*/ -osStatus osMessagePut(osMessageQId queue_id, uint32_t info, uint32_t millisec) -{ + * @brief Put a Message to a Queue. + * @param queue_id message queue ID obtained with \ref osMessageCreate. + * @param info message information. + * @param millisec timeout value or 0 in case of no time-out. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osMessagePut shall be consistent in every CMSIS-RTOS. + */ +osStatus osMessagePut(osMessageQId queue_id, uint32_t info, uint32_t millisec) { portBASE_TYPE taskWoken = pdFALSE; - TickType_t ticks; + TickType_t ticks; ticks = millisec / portTICK_PERIOD_MS; - if (ticks == 0) - { + if (ticks == 0) { ticks = 1; } - if (inHandlerMode()) - { - if (xQueueSendFromISR(queue_id, &info, &taskWoken) != pdTRUE) - { + if (inHandlerMode()) { + if (xQueueSendFromISR(queue_id, &info, &taskWoken) != pdTRUE) { return osErrorOS; } portEND_SWITCHING_ISR(taskWoken); - } - else - { - if (xQueueSend(queue_id, &info, ticks) != pdTRUE) - { + } else { + if (xQueueSend(queue_id, &info, ticks) != pdTRUE) { return osErrorOS; } } @@ -1107,23 +947,21 @@ osStatus osMessagePut(osMessageQId queue_id, uint32_t info, uint32_t millisec) } /** -* @brief Get a Message or Wait for a Message from a Queue. -* @param queue_id message queue ID obtained with \ref osMessageCreate. -* @param millisec timeout value or 0 in case of no time-out. -* @retval event information that includes status code. -* @note MUST REMAIN UNCHANGED: \b osMessageGet shall be consistent in every CMSIS-RTOS. -*/ -osEvent osMessageGet(osMessageQId queue_id, uint32_t millisec) -{ + * @brief Get a Message or Wait for a Message from a Queue. + * @param queue_id message queue ID obtained with \ref osMessageCreate. + * @param millisec timeout value or 0 in case of no time-out. + * @retval event information that includes status code. + * @note MUST REMAIN UNCHANGED: \b osMessageGet shall be consistent in every CMSIS-RTOS. + */ +osEvent osMessageGet(osMessageQId queue_id, uint32_t millisec) { portBASE_TYPE taskWoken; - TickType_t ticks; - osEvent event; + TickType_t ticks; + osEvent event; event.def.message_id = queue_id; - event.value.v = 0; + event.value.v = 0; - if (queue_id == NULL) - { + if (queue_id == NULL) { event.status = osErrorParameter; return event; } @@ -1131,41 +969,28 @@ osEvent osMessageGet(osMessageQId queue_id, uint32_t millisec) taskWoken = pdFALSE; ticks = 0; - if (millisec == osWaitForever) - { + if (millisec == osWaitForever) { ticks = portMAX_DELAY; - } - else if (millisec != 0) - { + } else if (millisec != 0) { ticks = millisec / portTICK_PERIOD_MS; - if (ticks == 0) - { + if (ticks == 0) { ticks = 1; } } - if (inHandlerMode()) - { - if (xQueueReceiveFromISR(queue_id, &event.value.v, &taskWoken) == pdTRUE) - { + if (inHandlerMode()) { + if (xQueueReceiveFromISR(queue_id, &event.value.v, &taskWoken) == pdTRUE) { /* We have mail */ event.status = osEventMessage; - } - else - { + } else { event.status = osOK; } portEND_SWITCHING_ISR(taskWoken); - } - else - { - if (xQueueReceive(queue_id, &event.value.v, ticks) == pdTRUE) - { + } else { + if (xQueueReceive(queue_id, &event.value.v, ticks) == pdTRUE) { /* We have mail */ event.status = osEventMessage; - } - else - { + } else { event.status = (ticks == 0) ? osOK : osEventTimeout; } } @@ -1178,22 +1003,20 @@ osEvent osMessageGet(osMessageQId queue_id, uint32_t millisec) /******************** Mail Queue Management Functions ***********************/ #if (defined(osFeature_MailQ) && (osFeature_MailQ != 0)) /* Use Mail Queues */ -typedef struct os_mailQ_cb -{ +typedef struct os_mailQ_cb { const osMailQDef_t *queue_def; - QueueHandle_t handle; - osPoolId pool; + QueueHandle_t handle; + osPoolId pool; } os_mailQ_cb_t; /** -* @brief Create and Initialize mail queue -* @param queue_def reference to the mail queue definition obtain with \ref osMailQ -* @param thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. -* @retval mail queue ID for reference by other functions or NULL in case of error. -* @note MUST REMAIN UNCHANGED: \b osMailCreate shall be consistent in every CMSIS-RTOS. -*/ -osMailQId osMailCreate(const osMailQDef_t *queue_def, osThreadId thread_id) -{ + * @brief Create and Initialize mail queue + * @param queue_def reference to the mail queue definition obtain with \ref osMailQ + * @param thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. + * @retval mail queue ID for reference by other functions or NULL in case of error. + * @note MUST REMAIN UNCHANGED: \b osMailCreate shall be consistent in every CMSIS-RTOS. + */ +osMailQId osMailCreate(const osMailQDef_t *queue_def, osThreadId thread_id) { #if (configSUPPORT_DYNAMIC_ALLOCATION == 1) (void)thread_id; @@ -1203,8 +1026,7 @@ osMailQId osMailCreate(const osMailQDef_t *queue_def, osThreadId thread_id) *(queue_def->cb) = pvPortMalloc(sizeof(struct os_mailQ_cb)); - if (*(queue_def->cb) == NULL) - { + if (*(queue_def->cb) == NULL) { return NULL; } (*(queue_def->cb))->queue_def = queue_def; @@ -1212,17 +1034,15 @@ osMailQId osMailCreate(const osMailQDef_t *queue_def, osThreadId thread_id) /* Create a queue in FreeRTOS */ (*(queue_def->cb))->handle = xQueueCreate(queue_def->queue_sz, sizeof(void *)); - if ((*(queue_def->cb))->handle == NULL) - { + if ((*(queue_def->cb))->handle == NULL) { vPortFree(*(queue_def->cb)); return NULL; } /* Create a mail pool */ (*(queue_def->cb))->pool = osPoolCreate(&pool_def); - if ((*(queue_def->cb))->pool == NULL) - { - //TODO: Delete queue. How to do it in FreeRTOS? + if ((*(queue_def->cb))->pool == NULL) { + // TODO: Delete queue. How to do it in FreeRTOS? vPortFree(*(queue_def->cb)); return NULL; } @@ -1234,19 +1054,17 @@ osMailQId osMailCreate(const osMailQDef_t *queue_def, osThreadId thread_id) } /** -* @brief Allocate a memory block from a mail -* @param queue_id mail queue ID obtained with \ref osMailCreate. -* @param millisec timeout value or 0 in case of no time-out. -* @retval pointer to memory block that can be filled with mail or NULL in case error. -* @note MUST REMAIN UNCHANGED: \b osMailAlloc shall be consistent in every CMSIS-RTOS. -*/ -void *osMailAlloc(osMailQId queue_id, uint32_t millisec) -{ + * @brief Allocate a memory block from a mail + * @param queue_id mail queue ID obtained with \ref osMailCreate. + * @param millisec timeout value or 0 in case of no time-out. + * @retval pointer to memory block that can be filled with mail or NULL in case error. + * @note MUST REMAIN UNCHANGED: \b osMailAlloc shall be consistent in every CMSIS-RTOS. + */ +void *osMailAlloc(osMailQId queue_id, uint32_t millisec) { (void)millisec; void *p; - if (queue_id == NULL) - { + if (queue_id == NULL) { return NULL; } @@ -1256,21 +1074,18 @@ void *osMailAlloc(osMailQId queue_id, uint32_t millisec) } /** -* @brief Allocate a memory block from a mail and set memory block to zero -* @param queue_id mail queue ID obtained with \ref osMailCreate. -* @param millisec timeout value or 0 in case of no time-out. -* @retval pointer to memory block that can be filled with mail or NULL in case error. -* @note MUST REMAIN UNCHANGED: \b osMailCAlloc shall be consistent in every CMSIS-RTOS. -*/ -void *osMailCAlloc(osMailQId queue_id, uint32_t millisec) -{ + * @brief Allocate a memory block from a mail and set memory block to zero + * @param queue_id mail queue ID obtained with \ref osMailCreate. + * @param millisec timeout value or 0 in case of no time-out. + * @retval pointer to memory block that can be filled with mail or NULL in case error. + * @note MUST REMAIN UNCHANGED: \b osMailCAlloc shall be consistent in every CMSIS-RTOS. + */ +void *osMailCAlloc(osMailQId queue_id, uint32_t millisec) { uint32_t i; - void *p = osMailAlloc(queue_id, millisec); + void *p = osMailAlloc(queue_id, millisec); - if (p) - { - for (i = 0; i < queue_id->queue_def->item_sz; i++) - { + if (p) { + for (i = 0; i < queue_id->queue_def->item_sz; i++) { ((uint8_t *)p)[i] = 0; } } @@ -1279,35 +1094,28 @@ void *osMailCAlloc(osMailQId queue_id, uint32_t millisec) } /** -* @brief Put a mail to a queue -* @param queue_id mail queue ID obtained with \ref osMailCreate. -* @param mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osMailPut shall be consistent in every CMSIS-RTOS. -*/ -osStatus osMailPut(osMailQId queue_id, void *mail) -{ + * @brief Put a mail to a queue + * @param queue_id mail queue ID obtained with \ref osMailCreate. + * @param mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osMailPut shall be consistent in every CMSIS-RTOS. + */ +osStatus osMailPut(osMailQId queue_id, void *mail) { portBASE_TYPE taskWoken; - if (queue_id == NULL) - { + if (queue_id == NULL) { return osErrorParameter; } taskWoken = pdFALSE; - if (inHandlerMode()) - { - if (xQueueSendFromISR(queue_id->handle, &mail, &taskWoken) != pdTRUE) - { + if (inHandlerMode()) { + if (xQueueSendFromISR(queue_id->handle, &mail, &taskWoken) != pdTRUE) { return osErrorOS; } portEND_SWITCHING_ISR(taskWoken); - } - else - { - if (xQueueSend(queue_id->handle, &mail, 0) != pdTRUE) - { + } else { + if (xQueueSend(queue_id->handle, &mail, 0) != pdTRUE) { return osErrorOS; } } @@ -1316,22 +1124,20 @@ osStatus osMailPut(osMailQId queue_id, void *mail) } /** -* @brief Get a mail from a queue -* @param queue_id mail queue ID obtained with \ref osMailCreate. -* @param millisec timeout value or 0 in case of no time-out -* @retval event that contains mail information or error code. -* @note MUST REMAIN UNCHANGED: \b osMailGet shall be consistent in every CMSIS-RTOS. -*/ -osEvent osMailGet(osMailQId queue_id, uint32_t millisec) -{ + * @brief Get a mail from a queue + * @param queue_id mail queue ID obtained with \ref osMailCreate. + * @param millisec timeout value or 0 in case of no time-out + * @retval event that contains mail information or error code. + * @note MUST REMAIN UNCHANGED: \b osMailGet shall be consistent in every CMSIS-RTOS. + */ +osEvent osMailGet(osMailQId queue_id, uint32_t millisec) { portBASE_TYPE taskWoken; - TickType_t ticks; - osEvent event; + TickType_t ticks; + osEvent event; event.def.mail_id = queue_id; - if (queue_id == NULL) - { + if (queue_id == NULL) { event.status = osErrorParameter; return event; } @@ -1339,41 +1145,28 @@ osEvent osMailGet(osMailQId queue_id, uint32_t millisec) taskWoken = pdFALSE; ticks = 0; - if (millisec == osWaitForever) - { + if (millisec == osWaitForever) { ticks = portMAX_DELAY; - } - else if (millisec != 0) - { + } else if (millisec != 0) { ticks = millisec / portTICK_PERIOD_MS; - if (ticks == 0) - { + if (ticks == 0) { ticks = 1; } } - if (inHandlerMode()) - { - if (xQueueReceiveFromISR(queue_id->handle, &event.value.p, &taskWoken) == pdTRUE) - { + if (inHandlerMode()) { + if (xQueueReceiveFromISR(queue_id->handle, &event.value.p, &taskWoken) == pdTRUE) { /* We have mail */ event.status = osEventMail; - } - else - { + } else { event.status = osOK; } portEND_SWITCHING_ISR(taskWoken); - } - else - { - if (xQueueReceive(queue_id->handle, &event.value.p, ticks) == pdTRUE) - { + } else { + if (xQueueReceive(queue_id->handle, &event.value.p, ticks) == pdTRUE) { /* We have mail */ event.status = osEventMail; - } - else - { + } else { event.status = (ticks == 0) ? osOK : osEventTimeout; } } @@ -1382,16 +1175,14 @@ osEvent osMailGet(osMailQId queue_id, uint32_t millisec) } /** -* @brief Free a memory block from a mail -* @param queue_id mail queue ID obtained with \ref osMailCreate. -* @param mail pointer to the memory block that was obtained with \ref osMailGet. -* @retval status code that indicates the execution status of the function. -* @note MUST REMAIN UNCHANGED: \b osMailFree shall be consistent in every CMSIS-RTOS. -*/ -osStatus osMailFree(osMailQId queue_id, void *mail) -{ - if (queue_id == NULL) - { + * @brief Free a memory block from a mail + * @param queue_id mail queue ID obtained with \ref osMailCreate. + * @param mail pointer to the memory block that was obtained with \ref osMailGet. + * @retval status code that indicates the execution status of the function. + * @note MUST REMAIN UNCHANGED: \b osMailFree shall be consistent in every CMSIS-RTOS. + */ +osStatus osMailFree(osMailQId queue_id, void *mail) { + if (queue_id == NULL) { return osErrorParameter; } @@ -1401,16 +1192,14 @@ osStatus osMailFree(osMailQId queue_id, void *mail) /*************************** Additional specific APIs to Free RTOS ************/ /** -* @brief Handles the tick increment -* @param none. -* @retval none. -*/ -void osSystickHandler(void) -{ + * @brief Handles the tick increment + * @param none. + * @retval none. + */ +void osSystickHandler(void) { #if (INCLUDE_xTaskGetSchedulerState == 1) - if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) - { + if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) { #endif /* INCLUDE_xTaskGetSchedulerState */ xPortSysTickHandler(); #if (INCLUDE_xTaskGetSchedulerState == 1) @@ -1420,19 +1209,17 @@ void osSystickHandler(void) #if (INCLUDE_eTaskGetState == 1) /** -* @brief Obtain the state of any thread. -* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. -* @retval the stae of the thread, states are encoded by the osThreadState enumerated type. -*/ -osThreadState osThreadGetState(osThreadId thread_id) -{ - eTaskState ThreadState; + * @brief Obtain the state of any thread. + * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. + * @retval the stae of the thread, states are encoded by the osThreadState enumerated type. + */ +osThreadState osThreadGetState(osThreadId thread_id) { + eTaskState ThreadState; osThreadState result; ThreadState = eTaskGetState(thread_id); - switch (ThreadState) - { + switch (ThreadState) { case eRunning: result = osThreadRunning; break; @@ -1458,12 +1245,11 @@ osThreadState osThreadGetState(osThreadId thread_id) #if (INCLUDE_eTaskGetState == 1) /** -* @brief Check if a thread is already suspended or not. -* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. -* @retval status code that indicates the execution status of the function. -*/ -osStatus osThreadIsSuspended(osThreadId thread_id) -{ + * @brief Check if a thread is already suspended or not. + * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. + * @retval status code that indicates the execution status of the function. + */ +osStatus osThreadIsSuspended(osThreadId thread_id) { if (eTaskGetState(thread_id) == eSuspended) return osOK; else @@ -1471,12 +1257,11 @@ osStatus osThreadIsSuspended(osThreadId thread_id) } #endif /* INCLUDE_eTaskGetState */ /** -* @brief Suspend execution of a thread. -* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. -* @retval status code that indicates the execution status of the function. -*/ -osStatus osThreadSuspend(osThreadId thread_id) -{ + * @brief Suspend execution of a thread. + * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. + * @retval status code that indicates the execution status of the function. + */ +osStatus osThreadSuspend(osThreadId thread_id) { #if (INCLUDE_vTaskSuspend == 1) vTaskSuspend(thread_id); @@ -1487,22 +1272,17 @@ osStatus osThreadSuspend(osThreadId thread_id) } /** -* @brief Resume execution of a suspended thread. -* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. -* @retval status code that indicates the execution status of the function. -*/ -osStatus osThreadResume(osThreadId thread_id) -{ + * @brief Resume execution of a suspended thread. + * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. + * @retval status code that indicates the execution status of the function. + */ +osStatus osThreadResume(osThreadId thread_id) { #if (INCLUDE_vTaskSuspend == 1) - if (inHandlerMode()) - { - if (xTaskResumeFromISR(thread_id) == pdTRUE) - { + if (inHandlerMode()) { + if (xTaskResumeFromISR(thread_id) == pdTRUE) { portYIELD_FROM_ISR(pdTRUE); } - } - else - { + } else { vTaskResume(thread_id); } return osOK; @@ -1512,22 +1292,20 @@ osStatus osThreadResume(osThreadId thread_id) } /** -* @brief Suspend execution of a all active threads. -* @retval status code that indicates the execution status of the function. -*/ -osStatus osThreadSuspendAll(void) -{ + * @brief Suspend execution of a all active threads. + * @retval status code that indicates the execution status of the function. + */ +osStatus osThreadSuspendAll(void) { vTaskSuspendAll(); return osOK; } /** -* @brief Resume execution of a all suspended threads. -* @retval status code that indicates the execution status of the function. -*/ -osStatus osThreadResumeAll(void) -{ + * @brief Resume execution of a all suspended threads. + * @retval status code that indicates the execution status of the function. + */ +osStatus osThreadResumeAll(void) { if (xTaskResumeAll() == pdTRUE) return osOK; else @@ -1535,15 +1313,14 @@ osStatus osThreadResumeAll(void) } /** -* @brief Delay a task until a specified time -* @param PreviousWakeTime Pointer to a variable that holds the time at which the -* task was last unblocked. PreviousWakeTime must be initialised with the current time -* prior to its first use (PreviousWakeTime = osKernelSysTick() ) -* @param millisec time delay value -* @retval status code that indicates the execution status of the function. -*/ -osStatus osDelayUntil(uint32_t *PreviousWakeTime, uint32_t millisec) -{ + * @brief Delay a task until a specified time + * @param PreviousWakeTime Pointer to a variable that holds the time at which the + * task was last unblocked. PreviousWakeTime must be initialised with the current time + * prior to its first use (PreviousWakeTime = osKernelSysTick() ) + * @param millisec time delay value + * @retval status code that indicates the execution status of the function. + */ +osStatus osDelayUntil(uint32_t *PreviousWakeTime, uint32_t millisec) { #if INCLUDE_vTaskDelayUntil TickType_t ticks = (millisec / portTICK_PERIOD_MS); vTaskDelayUntil((TickType_t *)PreviousWakeTime, ticks ? ticks : 1); @@ -1558,12 +1335,11 @@ osStatus osDelayUntil(uint32_t *PreviousWakeTime, uint32_t millisec) } /** -* @brief Abort the delay for a specific thread -* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId -* @retval status code that indicates the execution status of the function. -*/ -osStatus osAbortDelay(osThreadId thread_id) -{ + * @brief Abort the delay for a specific thread + * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId + * @retval status code that indicates the execution status of the function. + */ +osStatus osAbortDelay(osThreadId thread_id) { #if INCLUDE_xTaskAbortDelay xTaskAbortDelay(thread_id); @@ -1577,14 +1353,13 @@ osStatus osAbortDelay(osThreadId thread_id) } /** -* @brief Lists all the current threads, along with their current state -* and stack usage high water mark. -* @param buffer A buffer into which the above mentioned details -* will be written -* @retval status code that indicates the execution status of the function. -*/ -osStatus osThreadList(uint8_t *buffer) -{ + * @brief Lists all the current threads, along with their current state + * and stack usage high water mark. + * @param buffer A buffer into which the above mentioned details + * will be written + * @retval status code that indicates the execution status of the function. + */ +osStatus osThreadList(uint8_t *buffer) { #if ((configUSE_TRACE_FACILITY == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS == 1)) vTaskList((char *)buffer); #endif @@ -1592,45 +1367,36 @@ osStatus osThreadList(uint8_t *buffer) } /** -* @brief Receive an item from a queue without removing the item from the queue. -* @param queue_id message queue ID obtained with \ref osMessageCreate. -* @param millisec timeout value or 0 in case of no time-out. -* @retval event information that includes status code. -*/ -osEvent osMessagePeek(osMessageQId queue_id, uint32_t millisec) -{ + * @brief Receive an item from a queue without removing the item from the queue. + * @param queue_id message queue ID obtained with \ref osMessageCreate. + * @param millisec timeout value or 0 in case of no time-out. + * @retval event information that includes status code. + */ +osEvent osMessagePeek(osMessageQId queue_id, uint32_t millisec) { TickType_t ticks; - osEvent event; + osEvent event; event.def.message_id = queue_id; - if (queue_id == NULL) - { + if (queue_id == NULL) { event.status = osErrorParameter; return event; } ticks = 0; - if (millisec == osWaitForever) - { + if (millisec == osWaitForever) { ticks = portMAX_DELAY; - } - else if (millisec != 0) - { + } else if (millisec != 0) { ticks = millisec / portTICK_PERIOD_MS; - if (ticks == 0) - { + if (ticks == 0) { ticks = 1; } } - if (xQueuePeek(queue_id, &event.value.v, ticks) == pdTRUE) - { + if (xQueuePeek(queue_id, &event.value.v, ticks) == pdTRUE) { /* We have mail */ event.status = osEventMessage; - } - else - { + } else { event.status = (ticks == 0) ? osOK : osEventTimeout; } @@ -1638,41 +1404,32 @@ osEvent osMessagePeek(osMessageQId queue_id, uint32_t millisec) } /** -* @brief Get the number of messaged stored in a queue. -* @param queue_id message queue ID obtained with \ref osMessageCreate. -* @retval number of messages stored in a queue. -*/ -uint32_t osMessageWaiting(osMessageQId queue_id) -{ - if (inHandlerMode()) - { + * @brief Get the number of messaged stored in a queue. + * @param queue_id message queue ID obtained with \ref osMessageCreate. + * @retval number of messages stored in a queue. + */ +uint32_t osMessageWaiting(osMessageQId queue_id) { + if (inHandlerMode()) { return uxQueueMessagesWaitingFromISR(queue_id); - } - else - { + } else { return uxQueueMessagesWaiting(queue_id); } } /** -* @brief Get the available space in a message queue. -* @param queue_id message queue ID obtained with \ref osMessageCreate. -* @retval available space in a message queue. -*/ -uint32_t osMessageAvailableSpace(osMessageQId queue_id) -{ - return uxQueueSpacesAvailable(queue_id); -} + * @brief Get the available space in a message queue. + * @param queue_id message queue ID obtained with \ref osMessageCreate. + * @retval available space in a message queue. + */ +uint32_t osMessageAvailableSpace(osMessageQId queue_id) { return uxQueueSpacesAvailable(queue_id); } /** -* @brief Delete a Message Queue -* @param queue_id message queue ID obtained with \ref osMessageCreate. -* @retval status code that indicates the execution status of the function. -*/ -osStatus osMessageDelete(osMessageQId queue_id) -{ - if (inHandlerMode()) - { + * @brief Delete a Message Queue + * @param queue_id message queue ID obtained with \ref osMessageCreate. + * @retval status code that indicates the execution status of the function. + */ +osStatus osMessageDelete(osMessageQId queue_id) { + if (inHandlerMode()) { return osErrorISR; } @@ -1682,21 +1439,17 @@ osStatus osMessageDelete(osMessageQId queue_id) } /** -* @brief Create and Initialize a Recursive Mutex -* @param mutex_def mutex definition referenced with \ref osMutex. -* @retval mutex ID for reference by other functions or NULL in case of error.. -*/ -osMutexId osRecursiveMutexCreate(const osMutexDef_t *mutex_def) -{ + * @brief Create and Initialize a Recursive Mutex + * @param mutex_def mutex definition referenced with \ref osMutex. + * @retval mutex ID for reference by other functions or NULL in case of error.. + */ +osMutexId osRecursiveMutexCreate(const osMutexDef_t *mutex_def) { #if (configUSE_RECURSIVE_MUTEXES == 1) #if (configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1) - if (mutex_def->controlblock != NULL) - { + if (mutex_def->controlblock != NULL) { return xSemaphoreCreateRecursiveMutexStatic(mutex_def->controlblock); - } - else - { + } else { return xSemaphoreCreateRecursiveMutex(); } #elif (configSUPPORT_STATIC_ALLOCATION == 1) @@ -1710,17 +1463,15 @@ osMutexId osRecursiveMutexCreate(const osMutexDef_t *mutex_def) } /** -* @brief Release a Recursive Mutex -* @param mutex_id mutex ID obtained by \ref osRecursiveMutexCreate. -* @retval status code that indicates the execution status of the function. -*/ -osStatus osRecursiveMutexRelease(osMutexId mutex_id) -{ + * @brief Release a Recursive Mutex + * @param mutex_id mutex ID obtained by \ref osRecursiveMutexCreate. + * @retval status code that indicates the execution status of the function. + */ +osStatus osRecursiveMutexRelease(osMutexId mutex_id) { #if (configUSE_RECURSIVE_MUTEXES == 1) osStatus result = osOK; - if (xSemaphoreGiveRecursive(mutex_id) != pdTRUE) - { + if (xSemaphoreGiveRecursive(mutex_id) != pdTRUE) { result = osErrorOS; } return result; @@ -1730,37 +1481,30 @@ osStatus osRecursiveMutexRelease(osMutexId mutex_id) } /** -* @brief Release a Recursive Mutex -* @param mutex_id mutex ID obtained by \ref osRecursiveMutexCreate. -* @param millisec timeout value or 0 in case of no time-out. -* @retval status code that indicates the execution status of the function. -*/ -osStatus osRecursiveMutexWait(osMutexId mutex_id, uint32_t millisec) -{ + * @brief Release a Recursive Mutex + * @param mutex_id mutex ID obtained by \ref osRecursiveMutexCreate. + * @param millisec timeout value or 0 in case of no time-out. + * @retval status code that indicates the execution status of the function. + */ +osStatus osRecursiveMutexWait(osMutexId mutex_id, uint32_t millisec) { #if (configUSE_RECURSIVE_MUTEXES == 1) TickType_t ticks; - if (mutex_id == NULL) - { + if (mutex_id == NULL) { return osErrorParameter; } ticks = 0; - if (millisec == osWaitForever) - { + if (millisec == osWaitForever) { ticks = portMAX_DELAY; - } - else if (millisec != 0) - { + } else if (millisec != 0) { ticks = millisec / portTICK_PERIOD_MS; - if (ticks == 0) - { + if (ticks == 0) { ticks = 1; } } - if (xSemaphoreTakeRecursive(mutex_id, ticks) != pdTRUE) - { + if (xSemaphoreTakeRecursive(mutex_id, ticks) != pdTRUE) { return osErrorOS; } return osOK; @@ -1770,11 +1514,8 @@ osStatus osRecursiveMutexWait(osMutexId mutex_id, uint32_t millisec) } /** -* @brief Returns the current count value of a counting semaphore -* @param semaphore_id semaphore_id ID obtained by \ref osSemaphoreCreate. -* @retval count value -*/ -uint32_t osSemaphoreGetCount(osSemaphoreId semaphore_id) -{ - return uxSemaphoreGetCount(semaphore_id); -} + * @brief Returns the current count value of a counting semaphore + * @param semaphore_id semaphore_id ID obtained by \ref osSemaphoreCreate. + * @retval count value + */ +uint32_t osSemaphoreGetCount(osSemaphoreId semaphore_id) { return uxSemaphoreGetCount(semaphore_id); } diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/croutine.c b/source/Middlewares/Third_Party/FreeRTOS/Source/croutine.c index 6959fac3c..e2c9cb012 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/croutine.c +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/croutine.c @@ -1,361 +1,405 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -#include "FreeRTOS.h" -#include "task.h" -#include "croutine.h" - -/* Remove the whole file is co-routines are not being used. */ -#if ( configUSE_CO_ROUTINES != 0 ) - -/* - * Some kernel aware debuggers require data to be viewed to be global, rather - * than file scope. - */ - #ifdef portREMOVE_STATIC_QUALIFIER - #define static - #endif - - -/* Lists for ready and blocked co-routines. --------------------*/ - static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */ - static List_t xDelayedCoRoutineList1; /*< Delayed co-routines. */ - static List_t xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */ - static List_t * pxDelayedCoRoutineList = NULL; /*< Points to the delayed co-routine list currently being used. */ - static List_t * pxOverflowDelayedCoRoutineList = NULL; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */ - static List_t xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */ - -/* Other file private variables. --------------------------------*/ - CRCB_t * pxCurrentCoRoutine = NULL; - static UBaseType_t uxTopCoRoutineReadyPriority = 0; - static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0; - -/* The initial state of the co-routine when it is created. */ - #define corINITIAL_STATE ( 0 ) - -/* - * Place the co-routine represented by pxCRCB into the appropriate ready queue - * for the priority. It is inserted at the end of the list. - * - * This macro accesses the co-routine ready lists and therefore must not be - * used from within an ISR. - */ - #define prvAddCoRoutineToReadyQueue( pxCRCB ) \ - { \ - if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \ - { \ - uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \ - } \ - vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \ - } - -/* - * Utility to ready all the lists used by the scheduler. This is called - * automatically upon the creation of the first co-routine. - */ - static void prvInitialiseCoRoutineLists( void ); - -/* - * Co-routines that are readied by an interrupt cannot be placed directly into - * the ready lists (there is no mutual exclusion). Instead they are placed in - * in the pending ready list in order that they can later be moved to the ready - * list by the co-routine scheduler. - */ - static void prvCheckPendingReadyList( void ); - -/* - * Macro that looks at the list of co-routines that are currently delayed to - * see if any require waking. - * - * Co-routines are stored in the queue in the order of their wake time - - * meaning once one co-routine has been found whose timer has not expired - * we need not look any further down the list. - */ - static void prvCheckDelayedList( void ); - -/*-----------------------------------------------------------*/ - - BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, - UBaseType_t uxPriority, - UBaseType_t uxIndex ) - { - BaseType_t xReturn; - CRCB_t * pxCoRoutine; - - /* Allocate the memory that will store the co-routine control block. */ - pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) ); - - if( pxCoRoutine ) - { - /* If pxCurrentCoRoutine is NULL then this is the first co-routine to - * be created and the co-routine data structures need initialising. */ - if( pxCurrentCoRoutine == NULL ) - { - pxCurrentCoRoutine = pxCoRoutine; - prvInitialiseCoRoutineLists(); - } - - /* Check the priority is within limits. */ - if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ) - { - uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1; - } - - /* Fill out the co-routine control block from the function parameters. */ - pxCoRoutine->uxState = corINITIAL_STATE; - pxCoRoutine->uxPriority = uxPriority; - pxCoRoutine->uxIndex = uxIndex; - pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode; - - /* Initialise all the other co-routine control block parameters. */ - vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) ); - vListInitialiseItem( &( pxCoRoutine->xEventListItem ) ); - - /* Set the co-routine control block as a link back from the ListItem_t. - * This is so we can get back to the containing CRCB from a generic item - * in a list. */ - listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine ); - listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine ); - - /* Event lists are always in priority order. */ - listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) ); - - /* Now the co-routine has been initialised it can be added to the ready - * list at the correct priority. */ - prvAddCoRoutineToReadyQueue( pxCoRoutine ); - - xReturn = pdPASS; - } - else - { - xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - } - - return xReturn; - } -/*-----------------------------------------------------------*/ - - void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, - List_t * pxEventList ) - { - TickType_t xTimeToWake; - - /* Calculate the time to wake - this may overflow but this is - * not a problem. */ - xTimeToWake = xCoRoutineTickCount + xTicksToDelay; - - /* We must remove ourselves from the ready list before adding - * ourselves to the blocked list as the same list item is used for - * both lists. */ - ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake ); - - if( xTimeToWake < xCoRoutineTickCount ) - { - /* Wake time has overflowed. Place this item in the - * overflow list. */ - vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - } - else - { - /* The wake time has not overflowed, so we can use the - * current block list. */ - vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - } - - if( pxEventList ) - { - /* Also add the co-routine to an event list. If this is done then the - * function must be called with interrupts disabled. */ - vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) ); - } - } -/*-----------------------------------------------------------*/ - - static void prvCheckPendingReadyList( void ) - { - /* Are there any co-routines waiting to get moved to the ready list? These - * are co-routines that have been readied by an ISR. The ISR cannot access - * the ready lists itself. */ - while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ) - { - CRCB_t * pxUnblockedCRCB; - - /* The pending ready list can be accessed by an ISR. */ - portDISABLE_INTERRUPTS(); - { - pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyCoRoutineList ) ); - ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); - } - portENABLE_INTERRUPTS(); - - ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) ); - prvAddCoRoutineToReadyQueue( pxUnblockedCRCB ); - } - } -/*-----------------------------------------------------------*/ - - static void prvCheckDelayedList( void ) - { - CRCB_t * pxCRCB; - - xPassedTicks = xTaskGetTickCount() - xLastTickCount; - - while( xPassedTicks ) - { - xCoRoutineTickCount++; - xPassedTicks--; - - /* If the tick count has overflowed we need to swap the ready lists. */ - if( xCoRoutineTickCount == 0 ) - { - List_t * pxTemp; - - /* Tick count has overflowed so we need to swap the delay lists. If there are - * any items in pxDelayedCoRoutineList here then there is an error! */ - pxTemp = pxDelayedCoRoutineList; - pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList; - pxOverflowDelayedCoRoutineList = pxTemp; - } - - /* See if this tick has made a timeout expire. */ - while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ) - { - pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList ); - - if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ) - { - /* Timeout not yet expired. */ - break; - } - - portDISABLE_INTERRUPTS(); - { - /* The event could have occurred just before this critical - * section. If this is the case then the generic list item will - * have been moved to the pending ready list and the following - * line is still valid. Also the pvContainer parameter will have - * been set to NULL so the following lines are also valid. */ - ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) ); - - /* Is the co-routine waiting on an event also? */ - if( pxCRCB->xEventListItem.pxContainer ) - { - ( void ) uxListRemove( &( pxCRCB->xEventListItem ) ); - } - } - portENABLE_INTERRUPTS(); - - prvAddCoRoutineToReadyQueue( pxCRCB ); - } - } - - xLastTickCount = xCoRoutineTickCount; - } -/*-----------------------------------------------------------*/ - - void vCoRoutineSchedule( void ) - { - /* Only run a co-routine after prvInitialiseCoRoutineLists() has been - * called. prvInitialiseCoRoutineLists() is called automatically when a - * co-routine is created. */ - if( pxDelayedCoRoutineList != NULL ) - { - /* See if any co-routines readied by events need moving to the ready lists. */ - prvCheckPendingReadyList(); - - /* See if any delayed co-routines have timed out. */ - prvCheckDelayedList(); - - /* Find the highest priority queue that contains ready co-routines. */ - while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ) - { - if( uxTopCoRoutineReadyPriority == 0 ) - { - /* No more co-routines to check. */ - return; - } - - --uxTopCoRoutineReadyPriority; - } - - /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines - * of the same priority get an equal share of the processor time. */ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ); - - /* Call the co-routine. */ - ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex ); - } - } -/*-----------------------------------------------------------*/ - - static void prvInitialiseCoRoutineLists( void ) - { - UBaseType_t uxPriority; - - for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ) - { - vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) ); - } - - vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 ); - vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 ); - vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList ); - - /* Start with pxDelayedCoRoutineList using list1 and the - * pxOverflowDelayedCoRoutineList using list2. */ - pxDelayedCoRoutineList = &xDelayedCoRoutineList1; - pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2; - } -/*-----------------------------------------------------------*/ - - BaseType_t xCoRoutineRemoveFromEventList( const List_t * pxEventList ) - { - CRCB_t * pxUnblockedCRCB; - BaseType_t xReturn; - - /* This function is called from within an interrupt. It can only access - * event lists and the pending ready list. This function assumes that a - * check has already been made to ensure pxEventList is not empty. */ - pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); - ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); - vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) ); - - if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; - } - -#endif /* configUSE_CO_ROUTINES == 0 */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#include "FreeRTOS.h" +#include "task.h" +#include "croutine.h" + +/* Remove the whole file if co-routines are not being used. */ +#if ( configUSE_CO_ROUTINES != 0 ) + +/* + * Some kernel aware debuggers require data to be viewed to be global, rather + * than file scope. + */ + #ifdef portREMOVE_STATIC_QUALIFIER + #define static + #endif + + +/* Lists for ready and blocked co-routines. --------------------*/ + static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /**< Prioritised ready co-routines. */ + static List_t xDelayedCoRoutineList1; /**< Delayed co-routines. */ + static List_t xDelayedCoRoutineList2; /**< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */ + static List_t * pxDelayedCoRoutineList = NULL; /**< Points to the delayed co-routine list currently being used. */ + static List_t * pxOverflowDelayedCoRoutineList = NULL; /**< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */ + static List_t xPendingReadyCoRoutineList; /**< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */ + +/* Other file private variables. --------------------------------*/ + CRCB_t * pxCurrentCoRoutine = NULL; + static UBaseType_t uxTopCoRoutineReadyPriority = ( UBaseType_t ) 0U; + static TickType_t xCoRoutineTickCount = ( TickType_t ) 0U; + static TickType_t xLastTickCount = ( TickType_t ) 0U; + static TickType_t xPassedTicks = ( TickType_t ) 0U; + +/* The initial state of the co-routine when it is created. */ + #define corINITIAL_STATE ( 0 ) + +/* + * Place the co-routine represented by pxCRCB into the appropriate ready queue + * for the priority. It is inserted at the end of the list. + * + * This macro accesses the co-routine ready lists and therefore must not be + * used from within an ISR. + */ + #define prvAddCoRoutineToReadyQueue( pxCRCB ) \ + do { \ + if( ( pxCRCB )->uxPriority > uxTopCoRoutineReadyPriority ) \ + { \ + uxTopCoRoutineReadyPriority = ( pxCRCB )->uxPriority; \ + } \ + vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ ( pxCRCB )->uxPriority ] ), &( ( pxCRCB )->xGenericListItem ) ); \ + } while( 0 ) + +/* + * Utility to ready all the lists used by the scheduler. This is called + * automatically upon the creation of the first co-routine. + */ + static void prvInitialiseCoRoutineLists( void ); + +/* + * Co-routines that are readied by an interrupt cannot be placed directly into + * the ready lists (there is no mutual exclusion). Instead they are placed in + * in the pending ready list in order that they can later be moved to the ready + * list by the co-routine scheduler. + */ + static void prvCheckPendingReadyList( void ); + +/* + * Macro that looks at the list of co-routines that are currently delayed to + * see if any require waking. + * + * Co-routines are stored in the queue in the order of their wake time - + * meaning once one co-routine has been found whose timer has not expired + * we need not look any further down the list. + */ + static void prvCheckDelayedList( void ); + +/*-----------------------------------------------------------*/ + + BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, + UBaseType_t uxPriority, + UBaseType_t uxIndex ) + { + BaseType_t xReturn; + CRCB_t * pxCoRoutine; + + traceENTER_xCoRoutineCreate( pxCoRoutineCode, uxPriority, uxIndex ); + + /* Allocate the memory that will store the co-routine control block. */ + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) ); + + if( pxCoRoutine ) + { + /* If pxCurrentCoRoutine is NULL then this is the first co-routine to + * be created and the co-routine data structures need initialising. */ + if( pxCurrentCoRoutine == NULL ) + { + pxCurrentCoRoutine = pxCoRoutine; + prvInitialiseCoRoutineLists(); + } + + /* Check the priority is within limits. */ + if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ) + { + uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1; + } + + /* Fill out the co-routine control block from the function parameters. */ + pxCoRoutine->uxState = corINITIAL_STATE; + pxCoRoutine->uxPriority = uxPriority; + pxCoRoutine->uxIndex = uxIndex; + pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode; + + /* Initialise all the other co-routine control block parameters. */ + vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) ); + vListInitialiseItem( &( pxCoRoutine->xEventListItem ) ); + + /* Set the co-routine control block as a link back from the ListItem_t. + * This is so we can get back to the containing CRCB from a generic item + * in a list. */ + listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine ); + listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine ); + + /* Event lists are always in priority order. */ + listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) ); + + /* Now the co-routine has been initialised it can be added to the ready + * list at the correct priority. */ + prvAddCoRoutineToReadyQueue( pxCoRoutine ); + + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + traceRETURN_xCoRoutineCreate( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + + void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, + List_t * pxEventList ) + { + TickType_t xTimeToWake; + + traceENTER_vCoRoutineAddToDelayedList( xTicksToDelay, pxEventList ); + + /* Calculate the time to wake - this may overflow but this is + * not a problem. */ + xTimeToWake = xCoRoutineTickCount + xTicksToDelay; + + /* We must remove ourselves from the ready list before adding + * ourselves to the blocked list as the same list item is used for + * both lists. */ + ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake ); + + if( xTimeToWake < xCoRoutineTickCount ) + { + /* Wake time has overflowed. Place this item in the + * overflow list. */ + vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + } + else + { + /* The wake time has not overflowed, so we can use the + * current block list. */ + vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + } + + if( pxEventList ) + { + /* Also add the co-routine to an event list. If this is done then the + * function must be called with interrupts disabled. */ + vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) ); + } + + traceRETURN_vCoRoutineAddToDelayedList(); + } +/*-----------------------------------------------------------*/ + + static void prvCheckPendingReadyList( void ) + { + /* Are there any co-routines waiting to get moved to the ready list? These + * are co-routines that have been readied by an ISR. The ISR cannot access + * the ready lists itself. */ + while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ) + { + CRCB_t * pxUnblockedCRCB; + + /* The pending ready list can be accessed by an ISR. */ + portDISABLE_INTERRUPTS(); + { + pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyCoRoutineList ) ); + ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); + } + portENABLE_INTERRUPTS(); + + ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) ); + prvAddCoRoutineToReadyQueue( pxUnblockedCRCB ); + } + } +/*-----------------------------------------------------------*/ + + static void prvCheckDelayedList( void ) + { + CRCB_t * pxCRCB; + + xPassedTicks = xTaskGetTickCount() - xLastTickCount; + + while( xPassedTicks ) + { + xCoRoutineTickCount++; + xPassedTicks--; + + /* If the tick count has overflowed we need to swap the ready lists. */ + if( xCoRoutineTickCount == 0 ) + { + List_t * pxTemp; + + /* Tick count has overflowed so we need to swap the delay lists. If there are + * any items in pxDelayedCoRoutineList here then there is an error! */ + pxTemp = pxDelayedCoRoutineList; + pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList; + pxOverflowDelayedCoRoutineList = pxTemp; + } + + /* See if this tick has made a timeout expire. */ + while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ) + { + pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList ); + + if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ) + { + /* Timeout not yet expired. */ + break; + } + + portDISABLE_INTERRUPTS(); + { + /* The event could have occurred just before this critical + * section. If this is the case then the generic list item will + * have been moved to the pending ready list and the following + * line is still valid. Also the pvContainer parameter will have + * been set to NULL so the following lines are also valid. */ + ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) ); + + /* Is the co-routine waiting on an event also? */ + if( pxCRCB->xEventListItem.pxContainer ) + { + ( void ) uxListRemove( &( pxCRCB->xEventListItem ) ); + } + } + portENABLE_INTERRUPTS(); + + prvAddCoRoutineToReadyQueue( pxCRCB ); + } + } + + xLastTickCount = xCoRoutineTickCount; + } +/*-----------------------------------------------------------*/ + + void vCoRoutineSchedule( void ) + { + traceENTER_vCoRoutineSchedule(); + + /* Only run a co-routine after prvInitialiseCoRoutineLists() has been + * called. prvInitialiseCoRoutineLists() is called automatically when a + * co-routine is created. */ + if( pxDelayedCoRoutineList != NULL ) + { + /* See if any co-routines readied by events need moving to the ready lists. */ + prvCheckPendingReadyList(); + + /* See if any delayed co-routines have timed out. */ + prvCheckDelayedList(); + + /* Find the highest priority queue that contains ready co-routines. */ + while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ) + { + if( uxTopCoRoutineReadyPriority == 0 ) + { + /* No more co-routines to check. */ + return; + } + + --uxTopCoRoutineReadyPriority; + } + + /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines + * of the same priority get an equal share of the processor time. */ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ); + + /* Call the co-routine. */ + ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex ); + } + + traceRETURN_vCoRoutineSchedule(); + } +/*-----------------------------------------------------------*/ + + static void prvInitialiseCoRoutineLists( void ) + { + UBaseType_t uxPriority; + + for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ) + { + vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) ); + } + + vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 ); + vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 ); + vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList ); + + /* Start with pxDelayedCoRoutineList using list1 and the + * pxOverflowDelayedCoRoutineList using list2. */ + pxDelayedCoRoutineList = &xDelayedCoRoutineList1; + pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2; + } +/*-----------------------------------------------------------*/ + + BaseType_t xCoRoutineRemoveFromEventList( const List_t * pxEventList ) + { + CRCB_t * pxUnblockedCRCB; + BaseType_t xReturn; + + traceENTER_xCoRoutineRemoveFromEventList( pxEventList ); + + /* This function is called from within an interrupt. It can only access + * event lists and the pending ready list. This function assumes that a + * check has already been made to ensure pxEventList is not empty. */ + pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); + ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); + vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) ); + + if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + traceRETURN_xCoRoutineRemoveFromEventList( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + +/* + * Reset state in this file. This state is normally initialized at start up. + * This function must be called by the application before restarting the + * scheduler. + */ + void vCoRoutineResetState( void ) + { + /* Lists for ready and blocked co-routines. */ + pxDelayedCoRoutineList = NULL; + pxOverflowDelayedCoRoutineList = NULL; + + /* Other file private variables. */ + pxCurrentCoRoutine = NULL; + uxTopCoRoutineReadyPriority = ( UBaseType_t ) 0U; + xCoRoutineTickCount = ( TickType_t ) 0U; + xLastTickCount = ( TickType_t ) 0U; + xPassedTicks = ( TickType_t ) 0U; + } +/*-----------------------------------------------------------*/ + +#endif /* configUSE_CO_ROUTINES == 0 */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/event_groups.c b/source/Middlewares/Third_Party/FreeRTOS/Source/event_groups.c index c46013ab3..9e6fd8059 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/event_groups.c +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/event_groups.c @@ -1,771 +1,884 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -/* Standard includes. */ -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining - * all the API functions to use the MPU wrappers. That should only be done when - * task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -/* FreeRTOS includes. */ -#include "FreeRTOS.h" -#include "task.h" -#include "timers.h" -#include "event_groups.h" - -/* Lint e961, e750 and e9021 are suppressed as a MISRA exception justified - * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined - * for the header files above, but not in this file, in order to generate the - * correct privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021 See comment above. */ - -/* The following bit fields convey control information in a task's event list - * item value. It is important they don't clash with the - * taskEVENT_LIST_ITEM_VALUE_IN_USE definition. */ -#if configUSE_16_BIT_TICKS == 1 - #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U - #define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U - #define eventWAIT_FOR_ALL_BITS 0x0400U - #define eventEVENT_BITS_CONTROL_BYTES 0xff00U -#else - #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL - #define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL - #define eventWAIT_FOR_ALL_BITS 0x04000000UL - #define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL -#endif - -typedef struct EventGroupDef_t -{ - EventBits_t uxEventBits; - List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */ - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxEventGroupNumber; - #endif - - #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */ - #endif -} EventGroup_t; - -/*-----------------------------------------------------------*/ - -/* - * Test the bits set in uxCurrentEventBits to see if the wait condition is met. - * The wait condition is defined by xWaitForAllBits. If xWaitForAllBits is - * pdTRUE then the wait condition is met if all the bits set in uxBitsToWaitFor - * are also set in uxCurrentEventBits. If xWaitForAllBits is pdFALSE then the - * wait condition is met if any of the bits set in uxBitsToWait for are also set - * in uxCurrentEventBits. - */ -static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, - const EventBits_t uxBitsToWaitFor, - const BaseType_t xWaitForAllBits ) PRIVILEGED_FUNCTION; - -/*-----------------------------------------------------------*/ - -#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - - EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) - { - EventGroup_t * pxEventBits; - - /* A StaticEventGroup_t object must be provided. */ - configASSERT( pxEventGroupBuffer ); - - #if ( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - * variable of type StaticEventGroup_t equals the size of the real - * event group structure. */ - volatile size_t xSize = sizeof( StaticEventGroup_t ); - configASSERT( xSize == sizeof( EventGroup_t ) ); - } /*lint !e529 xSize is referenced if configASSERT() is defined. */ - #endif /* configASSERT_DEFINED */ - - /* The user has provided a statically allocated event group - use it. */ - pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; /*lint !e740 !e9087 EventGroup_t and StaticEventGroup_t are deliberately aliased for data hiding purposes and guaranteed to have the same size and alignment requirement - checked by configASSERT(). */ - - if( pxEventBits != NULL ) - { - pxEventBits->uxEventBits = 0; - vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); - - #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Both static and dynamic allocation can be used, so note that - * this event group was created statically in case the event group - * is later deleted. */ - pxEventBits->ucStaticallyAllocated = pdTRUE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - - traceEVENT_GROUP_CREATE( pxEventBits ); - } - else - { - /* xEventGroupCreateStatic should only ever be called with - * pxEventGroupBuffer pointing to a pre-allocated (compile time - * allocated) StaticEventGroup_t variable. */ - traceEVENT_GROUP_CREATE_FAILED(); - } - - return pxEventBits; - } - -#endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - - EventGroupHandle_t xEventGroupCreate( void ) - { - EventGroup_t * pxEventBits; - - /* Allocate the event group. Justification for MISRA deviation as - * follows: pvPortMalloc() always ensures returned memory blocks are - * aligned per the requirements of the MCU stack. In this case - * pvPortMalloc() must return a pointer that is guaranteed to meet the - * alignment requirements of the EventGroup_t structure - which (if you - * follow it through) is the alignment requirements of the TickType_t type - * (EventBits_t being of TickType_t itself). Therefore, whenever the - * stack alignment requirements are greater than or equal to the - * TickType_t alignment requirements the cast is safe. In other cases, - * where the natural word size of the architecture is less than - * sizeof( TickType_t ), the TickType_t variables will be accessed in two - * or more reads operations, and the alignment requirements is only that - * of each individual read. */ - pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); /*lint !e9087 !e9079 see comment above. */ - - if( pxEventBits != NULL ) - { - pxEventBits->uxEventBits = 0; - vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); - - #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* Both static and dynamic allocation can be used, so note this - * event group was allocated statically in case the event group is - * later deleted. */ - pxEventBits->ucStaticallyAllocated = pdFALSE; - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - - traceEVENT_GROUP_CREATE( pxEventBits ); - } - else - { - traceEVENT_GROUP_CREATE_FAILED(); /*lint !e9063 Else branch only exists to allow tracing and does not generate code if trace macros are not defined. */ - } - - return pxEventBits; - } - -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, - const EventBits_t uxBitsToSet, - const EventBits_t uxBitsToWaitFor, - TickType_t xTicksToWait ) -{ - EventBits_t uxOriginalBitValue, uxReturn; - EventGroup_t * pxEventBits = xEventGroup; - BaseType_t xAlreadyYielded; - BaseType_t xTimeoutOccurred = pdFALSE; - - configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - configASSERT( uxBitsToWaitFor != 0 ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - vTaskSuspendAll(); - { - uxOriginalBitValue = pxEventBits->uxEventBits; - - ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet ); - - if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - /* All the rendezvous bits are now set - no need to block. */ - uxReturn = ( uxOriginalBitValue | uxBitsToSet ); - - /* Rendezvous always clear the bits. They will have been cleared - * already unless this is the only task in the rendezvous. */ - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - - xTicksToWait = 0; - } - else - { - if( xTicksToWait != ( TickType_t ) 0 ) - { - traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ); - - /* Store the bits that the calling task is waiting for in the - * task's event list item so the kernel knows when a match is - * found. Then enter the blocked state. */ - vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait ); - - /* This assignment is obsolete as uxReturn will get set after - * the task unblocks, but some compilers mistakenly generate a - * warning about uxReturn being returned without being set if the - * assignment is omitted. */ - uxReturn = 0; - } - else - { - /* The rendezvous bits were not set, but no block time was - * specified - just return the current event bit value. */ - uxReturn = pxEventBits->uxEventBits; - xTimeoutOccurred = pdTRUE; - } - } - } - xAlreadyYielded = xTaskResumeAll(); - - if( xTicksToWait != ( TickType_t ) 0 ) - { - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* The task blocked to wait for its required bits to be set - at this - * point either the required bits were set or the block time expired. If - * the required bits were set they will have been stored in the task's - * event list item, and they should now be retrieved then cleared. */ - uxReturn = uxTaskResetEventItemValue(); - - if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) - { - /* The task timed out, just return the current event bit value. */ - taskENTER_CRITICAL(); - { - uxReturn = pxEventBits->uxEventBits; - - /* Although the task got here because it timed out before the - * bits it was waiting for were set, it is possible that since it - * unblocked another task has set the bits. If this is the case - * then it needs to clear the bits before exiting. */ - if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - xTimeoutOccurred = pdTRUE; - } - else - { - /* The task unblocked because the bits were set. */ - } - - /* Control bits might be set as the task had blocked should not be - * returned. */ - uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; - } - - traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ); - - /* Prevent compiler warnings when trace macros are not used. */ - ( void ) xTimeoutOccurred; - - return uxReturn; -} -/*-----------------------------------------------------------*/ - -EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, - const EventBits_t uxBitsToWaitFor, - const BaseType_t xClearOnExit, - const BaseType_t xWaitForAllBits, - TickType_t xTicksToWait ) -{ - EventGroup_t * pxEventBits = xEventGroup; - EventBits_t uxReturn, uxControlBits = 0; - BaseType_t xWaitConditionMet, xAlreadyYielded; - BaseType_t xTimeoutOccurred = pdFALSE; - - /* Check the user is not attempting to wait on the bits used by the kernel - * itself, and that at least one bit is being requested. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - configASSERT( uxBitsToWaitFor != 0 ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - vTaskSuspendAll(); - { - const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits; - - /* Check to see if the wait condition is already met or not. */ - xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits ); - - if( xWaitConditionMet != pdFALSE ) - { - /* The wait condition has already been met so there is no need to - * block. */ - uxReturn = uxCurrentEventBits; - xTicksToWait = ( TickType_t ) 0; - - /* Clear the wait bits if requested to do so. */ - if( xClearOnExit != pdFALSE ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The wait condition has not been met, but no block time was - * specified, so just return the current value. */ - uxReturn = uxCurrentEventBits; - xTimeoutOccurred = pdTRUE; - } - else - { - /* The task is going to block to wait for its required bits to be - * set. uxControlBits are used to remember the specified behaviour of - * this call to xEventGroupWaitBits() - for use when the event bits - * unblock the task. */ - if( xClearOnExit != pdFALSE ) - { - uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( xWaitForAllBits != pdFALSE ) - { - uxControlBits |= eventWAIT_FOR_ALL_BITS; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Store the bits that the calling task is waiting for in the - * task's event list item so the kernel knows when a match is - * found. Then enter the blocked state. */ - vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait ); - - /* This is obsolete as it will get set after the task unblocks, but - * some compilers mistakenly generate a warning about the variable - * being returned without being set if it is not done. */ - uxReturn = 0; - - traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ); - } - } - xAlreadyYielded = xTaskResumeAll(); - - if( xTicksToWait != ( TickType_t ) 0 ) - { - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* The task blocked to wait for its required bits to be set - at this - * point either the required bits were set or the block time expired. If - * the required bits were set they will have been stored in the task's - * event list item, and they should now be retrieved then cleared. */ - uxReturn = uxTaskResetEventItemValue(); - - if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) - { - taskENTER_CRITICAL(); - { - /* The task timed out, just return the current event bit value. */ - uxReturn = pxEventBits->uxEventBits; - - /* It is possible that the event bits were updated between this - * task leaving the Blocked state and running again. */ - if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE ) - { - if( xClearOnExit != pdFALSE ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xTimeoutOccurred = pdTRUE; - } - taskEXIT_CRITICAL(); - } - else - { - /* The task unblocked because the bits were set. */ - } - - /* The task blocked so control bits may have been set. */ - uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; - } - - traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ); - - /* Prevent compiler warnings when trace macros are not used. */ - ( void ) xTimeoutOccurred; - - return uxReturn; -} -/*-----------------------------------------------------------*/ - -EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, - const EventBits_t uxBitsToClear ) -{ - EventGroup_t * pxEventBits = xEventGroup; - EventBits_t uxReturn; - - /* Check the user is not attempting to clear the bits used by the kernel - * itself. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - - taskENTER_CRITICAL(); - { - traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ); - - /* The value returned is the event group value prior to the bits being - * cleared. */ - uxReturn = pxEventBits->uxEventBits; - - /* Clear the bits. */ - pxEventBits->uxEventBits &= ~uxBitsToClear; - } - taskEXIT_CRITICAL(); - - return uxReturn; -} -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) - - BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, - const EventBits_t uxBitsToClear ) - { - BaseType_t xReturn; - - traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ); - xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ - - return xReturn; - } - -#endif /* if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) */ -/*-----------------------------------------------------------*/ - -EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) -{ - UBaseType_t uxSavedInterruptStatus; - EventGroup_t const * const pxEventBits = xEventGroup; - EventBits_t uxReturn; - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - uxReturn = pxEventBits->uxEventBits; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return uxReturn; -} /*lint !e818 EventGroupHandle_t is a typedef used in other functions to so can't be pointer to const. */ -/*-----------------------------------------------------------*/ - -EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, - const EventBits_t uxBitsToSet ) -{ - ListItem_t * pxListItem, * pxNext; - ListItem_t const * pxListEnd; - List_t const * pxList; - EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits; - EventGroup_t * pxEventBits = xEventGroup; - BaseType_t xMatchFound = pdFALSE; - - /* Check the user is not attempting to set the bits used by the kernel - * itself. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - - pxList = &( pxEventBits->xTasksWaitingForBits ); - pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - vTaskSuspendAll(); - { - traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ); - - pxListItem = listGET_HEAD_ENTRY( pxList ); - - /* Set the bits. */ - pxEventBits->uxEventBits |= uxBitsToSet; - - /* See if the new bit value should unblock any tasks. */ - while( pxListItem != pxListEnd ) - { - pxNext = listGET_NEXT( pxListItem ); - uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem ); - xMatchFound = pdFALSE; - - /* Split the bits waited for from the control bits. */ - uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES; - uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES; - - if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 ) - { - /* Just looking for single bit being set. */ - if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 ) - { - xMatchFound = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor ) - { - /* All bits are set. */ - xMatchFound = pdTRUE; - } - else - { - /* Need all bits to be set, but not all the bits were set. */ - } - - if( xMatchFound != pdFALSE ) - { - /* The bits match. Should the bits be cleared on exit? */ - if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 ) - { - uxBitsToClear |= uxBitsWaitedFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Store the actual event flag value in the task's event list - * item before removing the task from the event list. The - * eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows - * that is was unblocked due to its required bits matching, rather - * than because it timed out. */ - vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET ); - } - - /* Move onto the next list item. Note pxListItem->pxNext is not - * used here as the list item may have been removed from the event list - * and inserted into the ready/pending reading list. */ - pxListItem = pxNext; - } - - /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT - * bit was set in the control word. */ - pxEventBits->uxEventBits &= ~uxBitsToClear; - } - ( void ) xTaskResumeAll(); - - return pxEventBits->uxEventBits; -} -/*-----------------------------------------------------------*/ - -void vEventGroupDelete( EventGroupHandle_t xEventGroup ) -{ - EventGroup_t * pxEventBits = xEventGroup; - const List_t * pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits ); - - vTaskSuspendAll(); - { - traceEVENT_GROUP_DELETE( xEventGroup ); - - while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 ) - { - /* Unblock the task, returning 0 as the event list is being deleted - * and cannot therefore have any bits set. */ - configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) ); - vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET ); - } - - #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) - { - /* The event group can only have been allocated dynamically - free - * it again. */ - vPortFree( pxEventBits ); - } - #elif ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - { - /* The event group could have been allocated statically or - * dynamically, so check before attempting to free the memory. */ - if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) - { - vPortFree( pxEventBits ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - } - ( void ) xTaskResumeAll(); -} -/*-----------------------------------------------------------*/ - -/* For internal use only - execute a 'set bits' command that was pended from - * an interrupt. */ -void vEventGroupSetBitsCallback( void * pvEventGroup, - const uint32_t ulBitsToSet ) -{ - ( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ -} -/*-----------------------------------------------------------*/ - -/* For internal use only - execute a 'clear bits' command that was pended from - * an interrupt. */ -void vEventGroupClearBitsCallback( void * pvEventGroup, - const uint32_t ulBitsToClear ) -{ - ( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ -} -/*-----------------------------------------------------------*/ - -static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, - const EventBits_t uxBitsToWaitFor, - const BaseType_t xWaitForAllBits ) -{ - BaseType_t xWaitConditionMet = pdFALSE; - - if( xWaitForAllBits == pdFALSE ) - { - /* Task only has to wait for one bit within uxBitsToWaitFor to be - * set. Is one already set? */ - if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 ) - { - xWaitConditionMet = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Task has to wait for all the bits in uxBitsToWaitFor to be set. - * Are they set already? */ - if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - xWaitConditionMet = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - return xWaitConditionMet; -} -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) - - BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, - const EventBits_t uxBitsToSet, - BaseType_t * pxHigherPriorityTaskWoken ) - { - BaseType_t xReturn; - - traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ); - xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ - - return xReturn; - } - -#endif /* if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxEventGroupGetNumber( void * xEventGroup ) - { - UBaseType_t xReturn; - EventGroup_t const * pxEventBits = ( EventGroup_t * ) xEventGroup; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ - - if( xEventGroup == NULL ) - { - xReturn = 0; - } - else - { - xReturn = pxEventBits->uxEventGroupNumber; - } - - return xReturn; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - void vEventGroupSetNumber( void * xEventGroup, - UBaseType_t uxEventGroupNumber ) - { - ( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" +#include "event_groups.h" + +/* The MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* This entire source file will be skipped if the application is not configured + * to include event groups functionality. This #if is closed at the very bottom + * of this file. If you want to include event groups then ensure + * configUSE_EVENT_GROUPS is set to 1 in FreeRTOSConfig.h. */ +#if ( configUSE_EVENT_GROUPS == 1 ) + + typedef struct EventGroupDef_t + { + EventBits_t uxEventBits; + List_t xTasksWaitingForBits; /**< List of tasks waiting for a bit to be set. */ + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxEventGroupNumber; + #endif + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /**< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */ + #endif + } EventGroup_t; + +/*-----------------------------------------------------------*/ + +/* + * Test the bits set in uxCurrentEventBits to see if the wait condition is met. + * The wait condition is defined by xWaitForAllBits. If xWaitForAllBits is + * pdTRUE then the wait condition is met if all the bits set in uxBitsToWaitFor + * are also set in uxCurrentEventBits. If xWaitForAllBits is pdFALSE then the + * wait condition is met if any of the bits set in uxBitsToWait for are also set + * in uxCurrentEventBits. + */ + static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xWaitForAllBits ) PRIVILEGED_FUNCTION; + +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) + { + EventGroup_t * pxEventBits; + + traceENTER_xEventGroupCreateStatic( pxEventGroupBuffer ); + + /* A StaticEventGroup_t object must be provided. */ + configASSERT( pxEventGroupBuffer ); + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticEventGroup_t equals the size of the real + * event group structure. */ + volatile size_t xSize = sizeof( StaticEventGroup_t ); + configASSERT( xSize == sizeof( EventGroup_t ) ); + } + #endif /* configASSERT_DEFINED */ + + /* The user has provided a statically allocated event group - use it. */ + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; + + if( pxEventBits != NULL ) + { + pxEventBits->uxEventBits = 0; + vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both static and dynamic allocation can be used, so note that + * this event group was created statically in case the event group + * is later deleted. */ + pxEventBits->ucStaticallyAllocated = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + + traceEVENT_GROUP_CREATE( pxEventBits ); + } + else + { + /* xEventGroupCreateStatic should only ever be called with + * pxEventGroupBuffer pointing to a pre-allocated (compile time + * allocated) StaticEventGroup_t variable. */ + traceEVENT_GROUP_CREATE_FAILED(); + } + + traceRETURN_xEventGroupCreateStatic( pxEventBits ); + + return pxEventBits; + } + + #endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + EventGroupHandle_t xEventGroupCreate( void ) + { + EventGroup_t * pxEventBits; + + traceENTER_xEventGroupCreate(); + + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); + + if( pxEventBits != NULL ) + { + pxEventBits->uxEventBits = 0; + vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Both static and dynamic allocation can be used, so note this + * event group was allocated statically in case the event group is + * later deleted. */ + pxEventBits->ucStaticallyAllocated = pdFALSE; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + traceEVENT_GROUP_CREATE( pxEventBits ); + } + else + { + traceEVENT_GROUP_CREATE_FAILED(); + } + + traceRETURN_xEventGroupCreate( pxEventBits ); + + return pxEventBits; + } + + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + + EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + const EventBits_t uxBitsToWaitFor, + TickType_t xTicksToWait ) + { + EventBits_t uxOriginalBitValue, uxReturn; + EventGroup_t * pxEventBits = xEventGroup; + BaseType_t xAlreadyYielded; + BaseType_t xTimeoutOccurred = pdFALSE; + + traceENTER_xEventGroupSync( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTicksToWait ); + + configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + configASSERT( uxBitsToWaitFor != 0 ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + vTaskSuspendAll(); + { + uxOriginalBitValue = pxEventBits->uxEventBits; + + ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet ); + + if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + /* All the rendezvous bits are now set - no need to block. */ + uxReturn = ( uxOriginalBitValue | uxBitsToSet ); + + /* Rendezvous always clear the bits. They will have been cleared + * already unless this is the only task in the rendezvous. */ + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + + xTicksToWait = 0; + } + else + { + if( xTicksToWait != ( TickType_t ) 0 ) + { + traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ); + + /* Store the bits that the calling task is waiting for in the + * task's event list item so the kernel knows when a match is + * found. Then enter the blocked state. */ + vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait ); + + /* This assignment is obsolete as uxReturn will get set after + * the task unblocks, but some compilers mistakenly generate a + * warning about uxReturn being returned without being set if the + * assignment is omitted. */ + uxReturn = 0; + } + else + { + /* The rendezvous bits were not set, but no block time was + * specified - just return the current event bit value. */ + uxReturn = pxEventBits->uxEventBits; + xTimeoutOccurred = pdTRUE; + } + } + } + xAlreadyYielded = xTaskResumeAll(); + + if( xTicksToWait != ( TickType_t ) 0 ) + { + if( xAlreadyYielded == pdFALSE ) + { + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The task blocked to wait for its required bits to be set - at this + * point either the required bits were set or the block time expired. If + * the required bits were set they will have been stored in the task's + * event list item, and they should now be retrieved then cleared. */ + uxReturn = uxTaskResetEventItemValue(); + + if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) + { + /* The task timed out, just return the current event bit value. */ + taskENTER_CRITICAL(); + { + uxReturn = pxEventBits->uxEventBits; + + /* Although the task got here because it timed out before the + * bits it was waiting for were set, it is possible that since it + * unblocked another task has set the bits. If this is the case + * then it needs to clear the bits before exiting. */ + if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + xTimeoutOccurred = pdTRUE; + } + else + { + /* The task unblocked because the bits were set. */ + } + + /* Control bits might be set as the task had blocked should not be + * returned. */ + uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; + } + + traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ); + + /* Prevent compiler warnings when trace macros are not used. */ + ( void ) xTimeoutOccurred; + + traceRETURN_xEventGroupSync( uxReturn ); + + return uxReturn; + } +/*-----------------------------------------------------------*/ + + EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xClearOnExit, + const BaseType_t xWaitForAllBits, + TickType_t xTicksToWait ) + { + EventGroup_t * pxEventBits = xEventGroup; + EventBits_t uxReturn, uxControlBits = 0; + BaseType_t xWaitConditionMet, xAlreadyYielded; + BaseType_t xTimeoutOccurred = pdFALSE; + + traceENTER_xEventGroupWaitBits( xEventGroup, uxBitsToWaitFor, xClearOnExit, xWaitForAllBits, xTicksToWait ); + + /* Check the user is not attempting to wait on the bits used by the kernel + * itself, and that at least one bit is being requested. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + configASSERT( uxBitsToWaitFor != 0 ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + vTaskSuspendAll(); + { + const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits; + + /* Check to see if the wait condition is already met or not. */ + xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits ); + + if( xWaitConditionMet != pdFALSE ) + { + /* The wait condition has already been met so there is no need to + * block. */ + uxReturn = uxCurrentEventBits; + xTicksToWait = ( TickType_t ) 0; + + /* Clear the wait bits if requested to do so. */ + if( xClearOnExit != pdFALSE ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The wait condition has not been met, but no block time was + * specified, so just return the current value. */ + uxReturn = uxCurrentEventBits; + xTimeoutOccurred = pdTRUE; + } + else + { + /* The task is going to block to wait for its required bits to be + * set. uxControlBits are used to remember the specified behaviour of + * this call to xEventGroupWaitBits() - for use when the event bits + * unblock the task. */ + if( xClearOnExit != pdFALSE ) + { + uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xWaitForAllBits != pdFALSE ) + { + uxControlBits |= eventWAIT_FOR_ALL_BITS; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Store the bits that the calling task is waiting for in the + * task's event list item so the kernel knows when a match is + * found. Then enter the blocked state. */ + vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait ); + + /* This is obsolete as it will get set after the task unblocks, but + * some compilers mistakenly generate a warning about the variable + * being returned without being set if it is not done. */ + uxReturn = 0; + + traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ); + } + } + xAlreadyYielded = xTaskResumeAll(); + + if( xTicksToWait != ( TickType_t ) 0 ) + { + if( xAlreadyYielded == pdFALSE ) + { + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The task blocked to wait for its required bits to be set - at this + * point either the required bits were set or the block time expired. If + * the required bits were set they will have been stored in the task's + * event list item, and they should now be retrieved then cleared. */ + uxReturn = uxTaskResetEventItemValue(); + + if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) + { + taskENTER_CRITICAL(); + { + /* The task timed out, just return the current event bit value. */ + uxReturn = pxEventBits->uxEventBits; + + /* It is possible that the event bits were updated between this + * task leaving the Blocked state and running again. */ + if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE ) + { + if( xClearOnExit != pdFALSE ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xTimeoutOccurred = pdTRUE; + } + taskEXIT_CRITICAL(); + } + else + { + /* The task unblocked because the bits were set. */ + } + + /* The task blocked so control bits may have been set. */ + uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; + } + + traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ); + + /* Prevent compiler warnings when trace macros are not used. */ + ( void ) xTimeoutOccurred; + + traceRETURN_xEventGroupWaitBits( uxReturn ); + + return uxReturn; + } +/*-----------------------------------------------------------*/ + + EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) + { + EventGroup_t * pxEventBits = xEventGroup; + EventBits_t uxReturn; + + traceENTER_xEventGroupClearBits( xEventGroup, uxBitsToClear ); + + /* Check the user is not attempting to clear the bits used by the kernel + * itself. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + + taskENTER_CRITICAL(); + { + traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ); + + /* The value returned is the event group value prior to the bits being + * cleared. */ + uxReturn = pxEventBits->uxEventBits; + + /* Clear the bits. */ + pxEventBits->uxEventBits &= ~uxBitsToClear; + } + taskEXIT_CRITICAL(); + + traceRETURN_xEventGroupClearBits( uxReturn ); + + return uxReturn; + } +/*-----------------------------------------------------------*/ + + #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) + + BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) + { + BaseType_t xReturn; + + traceENTER_xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ); + + traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ); + xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); + + traceRETURN_xEventGroupClearBitsFromISR( xReturn ); + + return xReturn; + } + + #endif /* if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) */ +/*-----------------------------------------------------------*/ + + EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) + { + UBaseType_t uxSavedInterruptStatus; + EventGroup_t const * const pxEventBits = xEventGroup; + EventBits_t uxReturn; + + traceENTER_xEventGroupGetBitsFromISR( xEventGroup ); + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); + { + uxReturn = pxEventBits->uxEventBits; + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xEventGroupGetBitsFromISR( uxReturn ); + + return uxReturn; + } +/*-----------------------------------------------------------*/ + + EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet ) + { + ListItem_t * pxListItem; + ListItem_t * pxNext; + ListItem_t const * pxListEnd; + List_t const * pxList; + EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits; + EventGroup_t * pxEventBits = xEventGroup; + BaseType_t xMatchFound = pdFALSE; + + traceENTER_xEventGroupSetBits( xEventGroup, uxBitsToSet ); + + /* Check the user is not attempting to set the bits used by the kernel + * itself. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + + pxList = &( pxEventBits->xTasksWaitingForBits ); + pxListEnd = listGET_END_MARKER( pxList ); + vTaskSuspendAll(); + { + traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ); + + pxListItem = listGET_HEAD_ENTRY( pxList ); + + /* Set the bits. */ + pxEventBits->uxEventBits |= uxBitsToSet; + + /* See if the new bit value should unblock any tasks. */ + while( pxListItem != pxListEnd ) + { + pxNext = listGET_NEXT( pxListItem ); + uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem ); + xMatchFound = pdFALSE; + + /* Split the bits waited for from the control bits. */ + uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES; + uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES; + + if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 ) + { + /* Just looking for single bit being set. */ + if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 ) + { + xMatchFound = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor ) + { + /* All bits are set. */ + xMatchFound = pdTRUE; + } + else + { + /* Need all bits to be set, but not all the bits were set. */ + } + + if( xMatchFound != pdFALSE ) + { + /* The bits match. Should the bits be cleared on exit? */ + if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 ) + { + uxBitsToClear |= uxBitsWaitedFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Store the actual event flag value in the task's event list + * item before removing the task from the event list. The + * eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows + * that is was unblocked due to its required bits matching, rather + * than because it timed out. */ + vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET ); + } + + /* Move onto the next list item. Note pxListItem->pxNext is not + * used here as the list item may have been removed from the event list + * and inserted into the ready/pending reading list. */ + pxListItem = pxNext; + } + + /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT + * bit was set in the control word. */ + pxEventBits->uxEventBits &= ~uxBitsToClear; + } + ( void ) xTaskResumeAll(); + + traceRETURN_xEventGroupSetBits( pxEventBits->uxEventBits ); + + return pxEventBits->uxEventBits; + } +/*-----------------------------------------------------------*/ + + void vEventGroupDelete( EventGroupHandle_t xEventGroup ) + { + EventGroup_t * pxEventBits = xEventGroup; + const List_t * pxTasksWaitingForBits; + + traceENTER_vEventGroupDelete( xEventGroup ); + + configASSERT( pxEventBits ); + + pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits ); + + vTaskSuspendAll(); + { + traceEVENT_GROUP_DELETE( xEventGroup ); + + while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 ) + { + /* Unblock the task, returning 0 as the event list is being deleted + * and cannot therefore have any bits set. */ + configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) ); + vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET ); + } + } + ( void ) xTaskResumeAll(); + + #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The event group can only have been allocated dynamically - free + * it again. */ + vPortFree( pxEventBits ); + } + #elif ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The event group could have been allocated statically or + * dynamically, so check before attempting to free the memory. */ + if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxEventBits ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + + traceRETURN_vEventGroupDelete(); + } +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + BaseType_t xEventGroupGetStaticBuffer( EventGroupHandle_t xEventGroup, + StaticEventGroup_t ** ppxEventGroupBuffer ) + { + BaseType_t xReturn; + EventGroup_t * pxEventBits = xEventGroup; + + traceENTER_xEventGroupGetStaticBuffer( xEventGroup, ppxEventGroupBuffer ); + + configASSERT( pxEventBits ); + configASSERT( ppxEventGroupBuffer ); + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Check if the event group was statically allocated. */ + if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdTRUE ) + { + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + *ppxEventGroupBuffer = ( StaticEventGroup_t * ) pxEventBits; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + #else /* configSUPPORT_DYNAMIC_ALLOCATION */ + { + /* Event group must have been statically allocated. */ + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + *ppxEventGroupBuffer = ( StaticEventGroup_t * ) pxEventBits; + xReturn = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + + traceRETURN_xEventGroupGetStaticBuffer( xReturn ); + + return xReturn; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +/* For internal use only - execute a 'set bits' command that was pended from + * an interrupt. */ + void vEventGroupSetBitsCallback( void * pvEventGroup, + uint32_t ulBitsToSet ) + { + traceENTER_vEventGroupSetBitsCallback( pvEventGroup, ulBitsToSet ); + + /* MISRA Ref 11.5.4 [Callback function parameter] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + ( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); + + traceRETURN_vEventGroupSetBitsCallback(); + } +/*-----------------------------------------------------------*/ + +/* For internal use only - execute a 'clear bits' command that was pended from + * an interrupt. */ + void vEventGroupClearBitsCallback( void * pvEventGroup, + uint32_t ulBitsToClear ) + { + traceENTER_vEventGroupClearBitsCallback( pvEventGroup, ulBitsToClear ); + + /* MISRA Ref 11.5.4 [Callback function parameter] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + ( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); + + traceRETURN_vEventGroupClearBitsCallback(); + } +/*-----------------------------------------------------------*/ + + static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xWaitForAllBits ) + { + BaseType_t xWaitConditionMet = pdFALSE; + + if( xWaitForAllBits == pdFALSE ) + { + /* Task only has to wait for one bit within uxBitsToWaitFor to be + * set. Is one already set? */ + if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 ) + { + xWaitConditionMet = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Task has to wait for all the bits in uxBitsToWaitFor to be set. + * Are they set already? */ + if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + xWaitConditionMet = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + return xWaitConditionMet; + } +/*-----------------------------------------------------------*/ + + #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) + + BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + BaseType_t * pxHigherPriorityTaskWoken ) + { + BaseType_t xReturn; + + traceENTER_xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ); + + traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ); + xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); + + traceRETURN_xEventGroupSetBitsFromISR( xReturn ); + + return xReturn; + } + + #endif /* if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) */ +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxEventGroupGetNumber( void * xEventGroup ) + { + UBaseType_t xReturn; + + /* MISRA Ref 11.5.2 [Opaque pointer] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + EventGroup_t const * pxEventBits = ( EventGroup_t * ) xEventGroup; + + traceENTER_uxEventGroupGetNumber( xEventGroup ); + + if( xEventGroup == NULL ) + { + xReturn = 0; + } + else + { + xReturn = pxEventBits->uxEventGroupNumber; + } + + traceRETURN_uxEventGroupGetNumber( xReturn ); + + return xReturn; + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + void vEventGroupSetNumber( void * xEventGroup, + UBaseType_t uxEventGroupNumber ) + { + traceENTER_vEventGroupSetNumber( xEventGroup, uxEventGroupNumber ); + + /* MISRA Ref 11.5.2 [Opaque pointer] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + ( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; + + traceRETURN_vEventGroupSetNumber(); + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +/* This entire source file will be skipped if the application is not configured + * to include event groups functionality. If you want to include event groups + * then ensure configUSE_EVENT_GROUPS is set to 1 in FreeRTOSConfig.h. */ +#endif /* configUSE_EVENT_GROUPS == 1 */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/FreeRTOS.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/FreeRTOS.h index 96cf880a4..146f286fe 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/FreeRTOS.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/FreeRTOS.h @@ -1,1325 +1,3334 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -#ifndef INC_FREERTOS_H -#define INC_FREERTOS_H - -/* - * Include the generic headers required for the FreeRTOS port being used. - */ -#include - -/* - * If stdint.h cannot be located then: - * + If using GCC ensure the -nostdint options is *not* being used. - * + Ensure the project's include path includes the directory in which your - * compiler stores stdint.h. - * + Set any compiler options necessary for it to support C99, as technically - * stdint.h is only mandatory with C99 (FreeRTOS does not require C99 in any - * other way). - * + The FreeRTOS download includes a simple stdint.h definition that can be - * used in cases where none is provided by the compiler. The files only - * contains the typedefs required to build FreeRTOS. Read the instructions - * in FreeRTOS/source/stdint.readme for more information. - */ -#include /* READ COMMENT ABOVE. */ - -/* *INDENT-OFF* */ -#ifdef __cplusplus - extern "C" { -#endif -/* *INDENT-ON* */ - -/* Application specific configuration options. */ -#include "FreeRTOSConfig.h" - -/* Basic FreeRTOS definitions. */ -#include "projdefs.h" - -/* Definitions specific to the port being used. */ -#include "portable.h" - -/* Must be defaulted before configUSE_NEWLIB_REENTRANT is used below. */ -#ifndef configUSE_NEWLIB_REENTRANT - #define configUSE_NEWLIB_REENTRANT 0 -#endif - -/* Required if struct _reent is used. */ -#if ( configUSE_NEWLIB_REENTRANT == 1 ) - #include -#endif - -/* - * Check all the required application specific macros have been defined. - * These macros are application specific and (as downloaded) are defined - * within FreeRTOSConfig.h. - */ - -#ifndef configMINIMAL_STACK_SIZE - #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. -#endif - -#ifndef configMAX_PRIORITIES - #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. -#endif - -#if configMAX_PRIORITIES < 1 - #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. -#endif - -#ifndef configUSE_PREEMPTION - #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. -#endif - -#ifndef configUSE_IDLE_HOOK - #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. -#endif - -#ifndef configUSE_TICK_HOOK - #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. -#endif - -#ifndef configUSE_16_BIT_TICKS - #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. -#endif - -#ifndef configUSE_CO_ROUTINES - #define configUSE_CO_ROUTINES 0 -#endif - -#ifndef INCLUDE_vTaskPrioritySet - #define INCLUDE_vTaskPrioritySet 0 -#endif - -#ifndef INCLUDE_uxTaskPriorityGet - #define INCLUDE_uxTaskPriorityGet 0 -#endif - -#ifndef INCLUDE_vTaskDelete - #define INCLUDE_vTaskDelete 0 -#endif - -#ifndef INCLUDE_vTaskSuspend - #define INCLUDE_vTaskSuspend 0 -#endif - -#ifndef INCLUDE_vTaskDelayUntil - #define INCLUDE_vTaskDelayUntil 0 -#endif - -#ifndef INCLUDE_vTaskDelay - #define INCLUDE_vTaskDelay 0 -#endif - -#ifndef INCLUDE_xTaskGetIdleTaskHandle - #define INCLUDE_xTaskGetIdleTaskHandle 0 -#endif - -#ifndef INCLUDE_xTaskAbortDelay - #define INCLUDE_xTaskAbortDelay 0 -#endif - -#ifndef INCLUDE_xQueueGetMutexHolder - #define INCLUDE_xQueueGetMutexHolder 0 -#endif - -#ifndef INCLUDE_xSemaphoreGetMutexHolder - #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder -#endif - -#ifndef INCLUDE_xTaskGetHandle - #define INCLUDE_xTaskGetHandle 0 -#endif - -#ifndef INCLUDE_uxTaskGetStackHighWaterMark - #define INCLUDE_uxTaskGetStackHighWaterMark 0 -#endif - -#ifndef INCLUDE_uxTaskGetStackHighWaterMark2 - #define INCLUDE_uxTaskGetStackHighWaterMark2 0 -#endif - -#ifndef INCLUDE_eTaskGetState - #define INCLUDE_eTaskGetState 0 -#endif - -#ifndef INCLUDE_xTaskResumeFromISR - #define INCLUDE_xTaskResumeFromISR 1 -#endif - -#ifndef INCLUDE_xTimerPendFunctionCall - #define INCLUDE_xTimerPendFunctionCall 0 -#endif - -#ifndef INCLUDE_xTaskGetSchedulerState - #define INCLUDE_xTaskGetSchedulerState 0 -#endif - -#ifndef INCLUDE_xTaskGetCurrentTaskHandle - #define INCLUDE_xTaskGetCurrentTaskHandle 0 -#endif - -#if configUSE_CO_ROUTINES != 0 - #ifndef configMAX_CO_ROUTINE_PRIORITIES - #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. - #endif -#endif - -#ifndef configUSE_DAEMON_TASK_STARTUP_HOOK - #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 -#endif - -#ifndef configUSE_APPLICATION_TASK_TAG - #define configUSE_APPLICATION_TASK_TAG 0 -#endif - -#ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS - #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 -#endif - -#ifndef configUSE_RECURSIVE_MUTEXES - #define configUSE_RECURSIVE_MUTEXES 0 -#endif - -#ifndef configUSE_MUTEXES - #define configUSE_MUTEXES 0 -#endif - -#ifndef configUSE_TIMERS - #define configUSE_TIMERS 0 -#endif - -#ifndef configUSE_COUNTING_SEMAPHORES - #define configUSE_COUNTING_SEMAPHORES 0 -#endif - -#ifndef configUSE_ALTERNATIVE_API - #define configUSE_ALTERNATIVE_API 0 -#endif - -#ifndef portCRITICAL_NESTING_IN_TCB - #define portCRITICAL_NESTING_IN_TCB 0 -#endif - -#ifndef configMAX_TASK_NAME_LEN - #define configMAX_TASK_NAME_LEN 16 -#endif - -#ifndef configIDLE_SHOULD_YIELD - #define configIDLE_SHOULD_YIELD 1 -#endif - -#if configMAX_TASK_NAME_LEN < 1 - #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h -#endif - -#ifndef configASSERT - #define configASSERT( x ) - #define configASSERT_DEFINED 0 -#else - #define configASSERT_DEFINED 1 -#endif - -/* configPRECONDITION should be defined as configASSERT. - * The CBMC proofs need a way to track assumptions and assertions. - * A configPRECONDITION statement should express an implicit invariant or - * assumption made. A configASSERT statement should express an invariant that must - * hold explicit before calling the code. */ -#ifndef configPRECONDITION - #define configPRECONDITION( X ) configASSERT( X ) - #define configPRECONDITION_DEFINED 0 -#else - #define configPRECONDITION_DEFINED 1 -#endif - -#ifndef portMEMORY_BARRIER - #define portMEMORY_BARRIER() -#endif - -#ifndef portSOFTWARE_BARRIER - #define portSOFTWARE_BARRIER() -#endif - -/* The timers module relies on xTaskGetSchedulerState(). */ -#if configUSE_TIMERS == 1 - - #ifndef configTIMER_TASK_PRIORITY - #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. - #endif /* configTIMER_TASK_PRIORITY */ - - #ifndef configTIMER_QUEUE_LENGTH - #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. - #endif /* configTIMER_QUEUE_LENGTH */ - - #ifndef configTIMER_TASK_STACK_DEPTH - #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. - #endif /* configTIMER_TASK_STACK_DEPTH */ - -#endif /* configUSE_TIMERS */ - -#ifndef portSET_INTERRUPT_MASK_FROM_ISR - #define portSET_INTERRUPT_MASK_FROM_ISR() 0 -#endif - -#ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR - #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue -#endif - -#ifndef portCLEAN_UP_TCB - #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB -#endif - -#ifndef portPRE_TASK_DELETE_HOOK - #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) -#endif - -#ifndef portSETUP_TCB - #define portSETUP_TCB( pxTCB ) ( void ) pxTCB -#endif - -#ifndef configQUEUE_REGISTRY_SIZE - #define configQUEUE_REGISTRY_SIZE 0U -#endif - -#if ( configQUEUE_REGISTRY_SIZE < 1 ) - #define vQueueAddToRegistry( xQueue, pcName ) - #define vQueueUnregisterQueue( xQueue ) - #define pcQueueGetName( xQueue ) -#endif - -#ifndef portPOINTER_SIZE_TYPE - #define portPOINTER_SIZE_TYPE uint32_t -#endif - -/* Remove any unused trace macros. */ -#ifndef traceSTART - -/* Used to perform any necessary initialisation - for example, open a file - * into which trace is to be written. */ - #define traceSTART() -#endif - -#ifndef traceEND - -/* Use to close a trace, for example close a file into which trace has been - * written. */ - #define traceEND() -#endif - -#ifndef traceTASK_SWITCHED_IN - -/* Called after a task has been selected to run. pxCurrentTCB holds a pointer - * to the task control block of the selected task. */ - #define traceTASK_SWITCHED_IN() -#endif - -#ifndef traceINCREASE_TICK_COUNT - -/* Called before stepping the tick count after waking from tickless idle - * sleep. */ - #define traceINCREASE_TICK_COUNT( x ) -#endif - -#ifndef traceLOW_POWER_IDLE_BEGIN - /* Called immediately before entering tickless idle. */ - #define traceLOW_POWER_IDLE_BEGIN() -#endif - -#ifndef traceLOW_POWER_IDLE_END - /* Called when returning to the Idle task after a tickless idle. */ - #define traceLOW_POWER_IDLE_END() -#endif - -#ifndef traceTASK_SWITCHED_OUT - -/* Called before a task has been selected to run. pxCurrentTCB holds a pointer - * to the task control block of the task being switched out. */ - #define traceTASK_SWITCHED_OUT() -#endif - -#ifndef traceTASK_PRIORITY_INHERIT - -/* Called when a task attempts to take a mutex that is already held by a - * lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task - * that holds the mutex. uxInheritedPriority is the priority the mutex holder - * will inherit (the priority of the task that is attempting to obtain the - * muted. */ - #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) -#endif - -#ifndef traceTASK_PRIORITY_DISINHERIT - -/* Called when a task releases a mutex, the holding of which had resulted in - * the task inheriting the priority of a higher priority task. - * pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the - * mutex. uxOriginalPriority is the task's configured (base) priority. */ - #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) -#endif - -#ifndef traceBLOCKING_ON_QUEUE_RECEIVE - -/* Task is about to block because it cannot read from a - * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - * upon which the read was attempted. pxCurrentTCB points to the TCB of the - * task that attempted the read. */ - #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) -#endif - -#ifndef traceBLOCKING_ON_QUEUE_PEEK - -/* Task is about to block because it cannot read from a - * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - * upon which the read was attempted. pxCurrentTCB points to the TCB of the - * task that attempted the read. */ - #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) -#endif - -#ifndef traceBLOCKING_ON_QUEUE_SEND - -/* Task is about to block because it cannot write to a - * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - * upon which the write was attempted. pxCurrentTCB points to the TCB of the - * task that attempted the write. */ - #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) -#endif - -#ifndef configCHECK_FOR_STACK_OVERFLOW - #define configCHECK_FOR_STACK_OVERFLOW 0 -#endif - -#ifndef configRECORD_STACK_HIGH_ADDRESS - #define configRECORD_STACK_HIGH_ADDRESS 0 -#endif - -#ifndef configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H - #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 -#endif - -/* The following event macros are embedded in the kernel API calls. */ - -#ifndef traceMOVED_TASK_TO_READY_STATE - #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) -#endif - -#ifndef tracePOST_MOVED_TASK_TO_READY_STATE - #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) -#endif - -#ifndef traceQUEUE_CREATE - #define traceQUEUE_CREATE( pxNewQueue ) -#endif - -#ifndef traceQUEUE_CREATE_FAILED - #define traceQUEUE_CREATE_FAILED( ucQueueType ) -#endif - -#ifndef traceCREATE_MUTEX - #define traceCREATE_MUTEX( pxNewQueue ) -#endif - -#ifndef traceCREATE_MUTEX_FAILED - #define traceCREATE_MUTEX_FAILED() -#endif - -#ifndef traceGIVE_MUTEX_RECURSIVE - #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) -#endif - -#ifndef traceGIVE_MUTEX_RECURSIVE_FAILED - #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) -#endif - -#ifndef traceTAKE_MUTEX_RECURSIVE - #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) -#endif - -#ifndef traceTAKE_MUTEX_RECURSIVE_FAILED - #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) -#endif - -#ifndef traceCREATE_COUNTING_SEMAPHORE - #define traceCREATE_COUNTING_SEMAPHORE() -#endif - -#ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED - #define traceCREATE_COUNTING_SEMAPHORE_FAILED() -#endif - -#ifndef traceQUEUE_SET_SEND - #define traceQUEUE_SET_SEND traceQUEUE_SEND -#endif - -#ifndef traceQUEUE_SEND - #define traceQUEUE_SEND( pxQueue ) -#endif - -#ifndef traceQUEUE_SEND_FAILED - #define traceQUEUE_SEND_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_RECEIVE - #define traceQUEUE_RECEIVE( pxQueue ) -#endif - -#ifndef traceQUEUE_PEEK - #define traceQUEUE_PEEK( pxQueue ) -#endif - -#ifndef traceQUEUE_PEEK_FAILED - #define traceQUEUE_PEEK_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_PEEK_FROM_ISR - #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) -#endif - -#ifndef traceQUEUE_RECEIVE_FAILED - #define traceQUEUE_RECEIVE_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_SEND_FROM_ISR - #define traceQUEUE_SEND_FROM_ISR( pxQueue ) -#endif - -#ifndef traceQUEUE_SEND_FROM_ISR_FAILED - #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_RECEIVE_FROM_ISR - #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) -#endif - -#ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED - #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_PEEK_FROM_ISR_FAILED - #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_DELETE - #define traceQUEUE_DELETE( pxQueue ) -#endif - -#ifndef traceTASK_CREATE - #define traceTASK_CREATE( pxNewTCB ) -#endif - -#ifndef traceTASK_CREATE_FAILED - #define traceTASK_CREATE_FAILED() -#endif - -#ifndef traceTASK_DELETE - #define traceTASK_DELETE( pxTaskToDelete ) -#endif - -#ifndef traceTASK_DELAY_UNTIL - #define traceTASK_DELAY_UNTIL( x ) -#endif - -#ifndef traceTASK_DELAY - #define traceTASK_DELAY() -#endif - -#ifndef traceTASK_PRIORITY_SET - #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) -#endif - -#ifndef traceTASK_SUSPEND - #define traceTASK_SUSPEND( pxTaskToSuspend ) -#endif - -#ifndef traceTASK_RESUME - #define traceTASK_RESUME( pxTaskToResume ) -#endif - -#ifndef traceTASK_RESUME_FROM_ISR - #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) -#endif - -#ifndef traceTASK_INCREMENT_TICK - #define traceTASK_INCREMENT_TICK( xTickCount ) -#endif - -#ifndef traceTIMER_CREATE - #define traceTIMER_CREATE( pxNewTimer ) -#endif - -#ifndef traceTIMER_CREATE_FAILED - #define traceTIMER_CREATE_FAILED() -#endif - -#ifndef traceTIMER_COMMAND_SEND - #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) -#endif - -#ifndef traceTIMER_EXPIRED - #define traceTIMER_EXPIRED( pxTimer ) -#endif - -#ifndef traceTIMER_COMMAND_RECEIVED - #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) -#endif - -#ifndef traceMALLOC - #define traceMALLOC( pvAddress, uiSize ) -#endif - -#ifndef traceFREE - #define traceFREE( pvAddress, uiSize ) -#endif - -#ifndef traceEVENT_GROUP_CREATE - #define traceEVENT_GROUP_CREATE( xEventGroup ) -#endif - -#ifndef traceEVENT_GROUP_CREATE_FAILED - #define traceEVENT_GROUP_CREATE_FAILED() -#endif - -#ifndef traceEVENT_GROUP_SYNC_BLOCK - #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) -#endif - -#ifndef traceEVENT_GROUP_SYNC_END - #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred -#endif - -#ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK - #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) -#endif - -#ifndef traceEVENT_GROUP_WAIT_BITS_END - #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred -#endif - -#ifndef traceEVENT_GROUP_CLEAR_BITS - #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) -#endif - -#ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR - #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) -#endif - -#ifndef traceEVENT_GROUP_SET_BITS - #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) -#endif - -#ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR - #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) -#endif - -#ifndef traceEVENT_GROUP_DELETE - #define traceEVENT_GROUP_DELETE( xEventGroup ) -#endif - -#ifndef tracePEND_FUNC_CALL - #define tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, ret ) -#endif - -#ifndef tracePEND_FUNC_CALL_FROM_ISR - #define tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, ret ) -#endif - -#ifndef traceQUEUE_REGISTRY_ADD - #define traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ) -#endif - -#ifndef traceTASK_NOTIFY_TAKE_BLOCK - #define traceTASK_NOTIFY_TAKE_BLOCK( uxIndexToWait ) -#endif - -#ifndef traceTASK_NOTIFY_TAKE - #define traceTASK_NOTIFY_TAKE( uxIndexToWait ) -#endif - -#ifndef traceTASK_NOTIFY_WAIT_BLOCK - #define traceTASK_NOTIFY_WAIT_BLOCK( uxIndexToWait ) -#endif - -#ifndef traceTASK_NOTIFY_WAIT - #define traceTASK_NOTIFY_WAIT( uxIndexToWait ) -#endif - -#ifndef traceTASK_NOTIFY - #define traceTASK_NOTIFY( uxIndexToNotify ) -#endif - -#ifndef traceTASK_NOTIFY_FROM_ISR - #define traceTASK_NOTIFY_FROM_ISR( uxIndexToNotify ) -#endif - -#ifndef traceTASK_NOTIFY_GIVE_FROM_ISR - #define traceTASK_NOTIFY_GIVE_FROM_ISR( uxIndexToNotify ) -#endif - -#ifndef traceSTREAM_BUFFER_CREATE_FAILED - #define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_CREATE_STATIC_FAILED - #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_CREATE - #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_DELETE - #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_RESET - #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) -#endif - -#ifndef traceBLOCKING_ON_STREAM_BUFFER_SEND - #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_SEND - #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) -#endif - -#ifndef traceSTREAM_BUFFER_SEND_FAILED - #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_SEND_FROM_ISR - #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) -#endif - -#ifndef traceBLOCKING_ON_STREAM_BUFFER_RECEIVE - #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_RECEIVE - #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) -#endif - -#ifndef traceSTREAM_BUFFER_RECEIVE_FAILED - #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_RECEIVE_FROM_ISR - #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) -#endif - -#ifndef configGENERATE_RUN_TIME_STATS - #define configGENERATE_RUN_TIME_STATS 0 -#endif - -#if ( configGENERATE_RUN_TIME_STATS == 1 ) - - #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS - #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. - #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ - - #ifndef portGET_RUN_TIME_COUNTER_VALUE - #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE - #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. - #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ - #endif /* portGET_RUN_TIME_COUNTER_VALUE */ - -#endif /* configGENERATE_RUN_TIME_STATS */ - -#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS - #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() -#endif - -#ifndef configUSE_MALLOC_FAILED_HOOK - #define configUSE_MALLOC_FAILED_HOOK 0 -#endif - -#ifndef portPRIVILEGE_BIT - #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) -#endif - -#ifndef portYIELD_WITHIN_API - #define portYIELD_WITHIN_API portYIELD -#endif - -#ifndef portSUPPRESS_TICKS_AND_SLEEP - #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) -#endif - -#ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP - #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 -#endif - -#if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2 - #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 -#endif - -#ifndef configUSE_TICKLESS_IDLE - #define configUSE_TICKLESS_IDLE 0 -#endif - -#ifndef configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING - #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) -#endif - -#ifndef configPRE_SLEEP_PROCESSING - #define configPRE_SLEEP_PROCESSING( x ) -#endif - -#ifndef configPOST_SLEEP_PROCESSING - #define configPOST_SLEEP_PROCESSING( x ) -#endif - -#ifndef configUSE_QUEUE_SETS - #define configUSE_QUEUE_SETS 0 -#endif - -#ifndef portTASK_USES_FLOATING_POINT - #define portTASK_USES_FLOATING_POINT() -#endif - -#ifndef portALLOCATE_SECURE_CONTEXT - #define portALLOCATE_SECURE_CONTEXT( ulSecureStackSize ) -#endif - -#ifndef portDONT_DISCARD - #define portDONT_DISCARD -#endif - -#ifndef configUSE_TIME_SLICING - #define configUSE_TIME_SLICING 1 -#endif - -#ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS - #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 -#endif - -#ifndef configUSE_STATS_FORMATTING_FUNCTIONS - #define configUSE_STATS_FORMATTING_FUNCTIONS 0 -#endif - -#ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID - #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() -#endif - -#ifndef configUSE_TRACE_FACILITY - #define configUSE_TRACE_FACILITY 0 -#endif - -#ifndef mtCOVERAGE_TEST_MARKER - #define mtCOVERAGE_TEST_MARKER() -#endif - -#ifndef mtCOVERAGE_TEST_DELAY - #define mtCOVERAGE_TEST_DELAY() -#endif - -#ifndef portASSERT_IF_IN_ISR - #define portASSERT_IF_IN_ISR() -#endif - -#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION - #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 -#endif - -#ifndef configAPPLICATION_ALLOCATED_HEAP - #define configAPPLICATION_ALLOCATED_HEAP 0 -#endif - -#ifndef configUSE_TASK_NOTIFICATIONS - #define configUSE_TASK_NOTIFICATIONS 1 -#endif - -#ifndef configTASK_NOTIFICATION_ARRAY_ENTRIES - #define configTASK_NOTIFICATION_ARRAY_ENTRIES 1 -#endif - -#if configTASK_NOTIFICATION_ARRAY_ENTRIES < 1 - #error configTASK_NOTIFICATION_ARRAY_ENTRIES must be at least 1 -#endif - -#ifndef configUSE_POSIX_ERRNO - #define configUSE_POSIX_ERRNO 0 -#endif - -#ifndef portTICK_TYPE_IS_ATOMIC - #define portTICK_TYPE_IS_ATOMIC 0 -#endif - -#ifndef configSUPPORT_STATIC_ALLOCATION - /* Defaults to 0 for backward compatibility. */ - #define configSUPPORT_STATIC_ALLOCATION 0 -#endif - -#ifndef configSUPPORT_DYNAMIC_ALLOCATION - /* Defaults to 1 for backward compatibility. */ - #define configSUPPORT_DYNAMIC_ALLOCATION 1 -#endif - -#ifndef configSTACK_DEPTH_TYPE - -/* Defaults to uint16_t for backward compatibility, but can be overridden - * in FreeRTOSConfig.h if uint16_t is too restrictive. */ - #define configSTACK_DEPTH_TYPE uint16_t -#endif - -#ifndef configMESSAGE_BUFFER_LENGTH_TYPE - -/* Defaults to size_t for backward compatibility, but can be overridden - * in FreeRTOSConfig.h if lengths will always be less than the number of bytes - * in a size_t. */ - #define configMESSAGE_BUFFER_LENGTH_TYPE size_t -#endif - -/* Sanity check the configuration. */ -#if ( configUSE_TICKLESS_IDLE != 0 ) - #if ( INCLUDE_vTaskSuspend != 1 ) - #error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0 - #endif /* INCLUDE_vTaskSuspend */ -#endif /* configUSE_TICKLESS_IDLE */ - -#if ( ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) ) - #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. -#endif - -#if ( ( configUSE_RECURSIVE_MUTEXES == 1 ) && ( configUSE_MUTEXES != 1 ) ) - #error configUSE_MUTEXES must be set to 1 to use recursive mutexes -#endif - -#ifndef configINITIAL_TICK_COUNT - #define configINITIAL_TICK_COUNT 0 -#endif - -#if ( portTICK_TYPE_IS_ATOMIC == 0 ) - -/* Either variables of tick type cannot be read atomically, or - * portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when - * the tick count is returned to the standard critical section macros. */ - #define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL() - #define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL() - #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() - #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) -#else - -/* The tick type can be read atomically, so critical sections used when the - * tick count is returned can be defined away. */ - #define portTICK_TYPE_ENTER_CRITICAL() - #define portTICK_TYPE_EXIT_CRITICAL() - #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 - #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x -#endif /* if ( portTICK_TYPE_IS_ATOMIC == 0 ) */ - -/* Definitions to allow backward compatibility with FreeRTOS versions prior to - * V8 if desired. */ -#ifndef configENABLE_BACKWARD_COMPATIBILITY - #define configENABLE_BACKWARD_COMPATIBILITY 1 -#endif - -#ifndef configPRINTF - -/* configPRINTF() was not defined, so define it away to nothing. To use - * configPRINTF() then define it as follows (where MyPrintFunction() is - * provided by the application writer): - * - * void MyPrintFunction(const char *pcFormat, ... ); - #define configPRINTF( X ) MyPrintFunction X - * - * Then call like a standard printf() function, but placing brackets around - * all parameters so they are passed as a single parameter. For example: - * configPRINTF( ("Value = %d", MyVariable) ); */ - #define configPRINTF( X ) -#endif - -#ifndef configMAX - -/* The application writer has not provided their own MAX macro, so define - * the following generic implementation. */ - #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) -#endif - -#ifndef configMIN - -/* The application writer has not provided their own MAX macro, so define - * the following generic implementation. */ - #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) -#endif - -#if configENABLE_BACKWARD_COMPATIBILITY == 1 - #define eTaskStateGet eTaskGetState - #define portTickType TickType_t - #define xTaskHandle TaskHandle_t - #define xQueueHandle QueueHandle_t - #define xSemaphoreHandle SemaphoreHandle_t - #define xQueueSetHandle QueueSetHandle_t - #define xQueueSetMemberHandle QueueSetMemberHandle_t - #define xTimeOutType TimeOut_t - #define xMemoryRegion MemoryRegion_t - #define xTaskParameters TaskParameters_t - #define xTaskStatusType TaskStatus_t - #define xTimerHandle TimerHandle_t - #define xCoRoutineHandle CoRoutineHandle_t - #define pdTASK_HOOK_CODE TaskHookFunction_t - #define portTICK_RATE_MS portTICK_PERIOD_MS - #define pcTaskGetTaskName pcTaskGetName - #define pcTimerGetTimerName pcTimerGetName - #define pcQueueGetQueueName pcQueueGetName - #define vTaskGetTaskInfo vTaskGetInfo - #define xTaskGetIdleRunTimeCounter ulTaskGetIdleRunTimeCounter - -/* Backward compatibility within the scheduler code only - these definitions - * are not really required but are included for completeness. */ - #define tmrTIMER_CALLBACK TimerCallbackFunction_t - #define pdTASK_CODE TaskFunction_t - #define xListItem ListItem_t - #define xList List_t - -/* For libraries that break the list data hiding, and access list structure - * members directly (which is not supposed to be done). */ - #define pxContainer pvContainer -#endif /* configENABLE_BACKWARD_COMPATIBILITY */ - -#if ( configUSE_ALTERNATIVE_API != 0 ) - #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 -#endif - -/* Set configUSE_TASK_FPU_SUPPORT to 0 to omit floating point support even - * if floating point hardware is otherwise supported by the FreeRTOS port in use. - * This constant is not supported by all FreeRTOS ports that include floating - * point support. */ -#ifndef configUSE_TASK_FPU_SUPPORT - #define configUSE_TASK_FPU_SUPPORT 1 -#endif - -/* Set configENABLE_MPU to 1 to enable MPU support and 0 to disable it. This is - * currently used in ARMv8M ports. */ -#ifndef configENABLE_MPU - #define configENABLE_MPU 0 -#endif - -/* Set configENABLE_FPU to 1 to enable FPU support and 0 to disable it. This is - * currently used in ARMv8M ports. */ -#ifndef configENABLE_FPU - #define configENABLE_FPU 1 -#endif - -/* Set configENABLE_TRUSTZONE to 1 enable TrustZone support and 0 to disable it. - * This is currently used in ARMv8M ports. */ -#ifndef configENABLE_TRUSTZONE - #define configENABLE_TRUSTZONE 1 -#endif - -/* Set configRUN_FREERTOS_SECURE_ONLY to 1 to run the FreeRTOS ARMv8M port on - * the Secure Side only. */ -#ifndef configRUN_FREERTOS_SECURE_ONLY - #define configRUN_FREERTOS_SECURE_ONLY 0 -#endif - -/* Sometimes the FreeRTOSConfig.h settings only allow a task to be created using - * dynamically allocated RAM, in which case when any task is deleted it is known - * that both the task's stack and TCB need to be freed. Sometimes the - * FreeRTOSConfig.h settings only allow a task to be created using statically - * allocated RAM, in which case when any task is deleted it is known that neither - * the task's stack or TCB should be freed. Sometimes the FreeRTOSConfig.h - * settings allow a task to be created using either statically or dynamically - * allocated RAM, in which case a member of the TCB is used to record whether the - * stack and/or TCB were allocated statically or dynamically, so when a task is - * deleted the RAM that was allocated dynamically is freed again and no attempt is - * made to free the RAM that was allocated statically. - * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE is only true if it is possible for a - * task to be created using either statically or dynamically allocated RAM. Note - * that if portUSING_MPU_WRAPPERS is 1 then a protected task can be created with - * a statically allocated stack and a dynamically allocated TCB. - * - * The following table lists various combinations of portUSING_MPU_WRAPPERS, - * configSUPPORT_DYNAMIC_ALLOCATION and configSUPPORT_STATIC_ALLOCATION and - * when it is possible to have both static and dynamic allocation: - * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ - * | MPU | Dynamic | Static | Available Functions | Possible Allocations | Both Dynamic and | Need Free | - * | | | | | | Static Possible | | - * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ - * | 0 | 0 | 1 | xTaskCreateStatic | TCB - Static, Stack - Static | No | No | - * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| - * | 0 | 1 | 0 | xTaskCreate | TCB - Dynamic, Stack - Dynamic | No | Yes | - * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| - * | 0 | 1 | 1 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | - * | | | | xTaskCreateStatic | 2. TCB - Static, Stack - Static | | | - * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| - * | 1 | 0 | 1 | xTaskCreateStatic, | TCB - Static, Stack - Static | No | No | - * | | | | xTaskCreateRestrictedStatic | | | | - * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| - * | 1 | 1 | 0 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | - * | | | | xTaskCreateRestricted | 2. TCB - Dynamic, Stack - Static | | | - * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| - * | 1 | 1 | 1 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | - * | | | | xTaskCreateStatic, | 2. TCB - Dynamic, Stack - Static | | | - * | | | | xTaskCreateRestricted, | 3. TCB - Static, Stack - Static | | | - * | | | | xTaskCreateRestrictedStatic | | | | - * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ - */ -#define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE \ - ( ( ( portUSING_MPU_WRAPPERS == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) || \ - ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) ) - -/* - * In line with software engineering best practice, FreeRTOS implements a strict - * data hiding policy, so the real structures used by FreeRTOS to maintain the - * state of tasks, queues, semaphores, etc. are not accessible to the application - * code. However, if the application writer wants to statically allocate such - * an object then the size of the object needs to be know. Dummy structures - * that are guaranteed to have the same size and alignment requirements of the - * real objects are used for this purpose. The dummy list and list item - * structures below are used for inclusion in such a dummy structure. - */ -struct xSTATIC_LIST_ITEM -{ - #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy1; - #endif - TickType_t xDummy2; - void * pvDummy3[ 4 ]; - #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy4; - #endif -}; -typedef struct xSTATIC_LIST_ITEM StaticListItem_t; - -/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ -struct xSTATIC_MINI_LIST_ITEM -{ - #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy1; - #endif - TickType_t xDummy2; - void * pvDummy3[ 2 ]; -}; -typedef struct xSTATIC_MINI_LIST_ITEM StaticMiniListItem_t; - -/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ -typedef struct xSTATIC_LIST -{ - #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy1; - #endif - UBaseType_t uxDummy2; - void * pvDummy3; - StaticMiniListItem_t xDummy4; - #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy5; - #endif -} StaticList_t; - -/* - * In line with software engineering best practice, especially when supplying a - * library that is likely to change in future versions, FreeRTOS implements a - * strict data hiding policy. This means the Task structure used internally by - * FreeRTOS is not accessible to application code. However, if the application - * writer wants to statically allocate the memory required to create a task then - * the size of the task object needs to be know. The StaticTask_t structure - * below is provided for this purpose. Its sizes and alignment requirements are - * guaranteed to match those of the genuine structure, no matter which - * architecture is being used, and no matter how the values in FreeRTOSConfig.h - * are set. Its contents are somewhat obfuscated in the hope users will - * recognise that it would be unwise to make direct use of the structure members. - */ -typedef struct xSTATIC_TCB -{ - void * pxDummy1; - #if ( portUSING_MPU_WRAPPERS == 1 ) - xMPU_SETTINGS xDummy2; - #endif - StaticListItem_t xDummy3[ 2 ]; - UBaseType_t uxDummy5; - void * pxDummy6; - uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; - #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) - void * pxDummy8; - #endif - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - UBaseType_t uxDummy9; - #endif - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy10[ 2 ]; - #endif - #if ( configUSE_MUTEXES == 1 ) - UBaseType_t uxDummy12[ 2 ]; - #endif - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - void * pxDummy14; - #endif - #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - void * pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; - #endif - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - uint32_t ulDummy16; - #endif - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - struct _reent xDummy17; - #endif - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - uint32_t ulDummy18[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; - uint8_t ucDummy19[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; - #endif - #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) - uint8_t uxDummy20; - #endif - - #if ( INCLUDE_xTaskAbortDelay == 1 ) - uint8_t ucDummy21; - #endif - #if ( configUSE_POSIX_ERRNO == 1 ) - int iDummy22; - #endif -} StaticTask_t; - -/* - * In line with software engineering best practice, especially when supplying a - * library that is likely to change in future versions, FreeRTOS implements a - * strict data hiding policy. This means the Queue structure used internally by - * FreeRTOS is not accessible to application code. However, if the application - * writer wants to statically allocate the memory required to create a queue - * then the size of the queue object needs to be know. The StaticQueue_t - * structure below is provided for this purpose. Its sizes and alignment - * requirements are guaranteed to match those of the genuine structure, no - * matter which architecture is being used, and no matter how the values in - * FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in the hope - * users will recognise that it would be unwise to make direct use of the - * structure members. - */ -typedef struct xSTATIC_QUEUE -{ - void * pvDummy1[ 3 ]; - - union - { - void * pvDummy2; - UBaseType_t uxDummy2; - } u; - - StaticList_t xDummy3[ 2 ]; - UBaseType_t uxDummy4[ 3 ]; - uint8_t ucDummy5[ 2 ]; - - #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucDummy6; - #endif - - #if ( configUSE_QUEUE_SETS == 1 ) - void * pvDummy7; - #endif - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy8; - uint8_t ucDummy9; - #endif -} StaticQueue_t; -typedef StaticQueue_t StaticSemaphore_t; - -/* - * In line with software engineering best practice, especially when supplying a - * library that is likely to change in future versions, FreeRTOS implements a - * strict data hiding policy. This means the event group structure used - * internally by FreeRTOS is not accessible to application code. However, if - * the application writer wants to statically allocate the memory required to - * create an event group then the size of the event group object needs to be - * know. The StaticEventGroup_t structure below is provided for this purpose. - * Its sizes and alignment requirements are guaranteed to match those of the - * genuine structure, no matter which architecture is being used, and no matter - * how the values in FreeRTOSConfig.h are set. Its contents are somewhat - * obfuscated in the hope users will recognise that it would be unwise to make - * direct use of the structure members. - */ -typedef struct xSTATIC_EVENT_GROUP -{ - TickType_t xDummy1; - StaticList_t xDummy2; - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy3; - #endif - - #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucDummy4; - #endif -} StaticEventGroup_t; - -/* - * In line with software engineering best practice, especially when supplying a - * library that is likely to change in future versions, FreeRTOS implements a - * strict data hiding policy. This means the software timer structure used - * internally by FreeRTOS is not accessible to application code. However, if - * the application writer wants to statically allocate the memory required to - * create a software timer then the size of the queue object needs to be know. - * The StaticTimer_t structure below is provided for this purpose. Its sizes - * and alignment requirements are guaranteed to match those of the genuine - * structure, no matter which architecture is being used, and no matter how the - * values in FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in - * the hope users will recognise that it would be unwise to make direct use of - * the structure members. - */ -typedef struct xSTATIC_TIMER -{ - void * pvDummy1; - StaticListItem_t xDummy2; - TickType_t xDummy3; - void * pvDummy5; - TaskFunction_t pvDummy6; - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy7; - #endif - uint8_t ucDummy8; -} StaticTimer_t; - -/* - * In line with software engineering best practice, especially when supplying a - * library that is likely to change in future versions, FreeRTOS implements a - * strict data hiding policy. This means the stream buffer structure used - * internally by FreeRTOS is not accessible to application code. However, if - * the application writer wants to statically allocate the memory required to - * create a stream buffer then the size of the stream buffer object needs to be - * know. The StaticStreamBuffer_t structure below is provided for this purpose. - * Its size and alignment requirements are guaranteed to match those of the - * genuine structure, no matter which architecture is being used, and no matter - * how the values in FreeRTOSConfig.h are set. Its contents are somewhat - * obfuscated in the hope users will recognise that it would be unwise to make - * direct use of the structure members. - */ -typedef struct xSTATIC_STREAM_BUFFER -{ - size_t uxDummy1[ 4 ]; - void * pvDummy2[ 3 ]; - uint8_t ucDummy3; - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy4; - #endif -} StaticStreamBuffer_t; - -/* Message buffers are built on stream buffers. */ -typedef StaticStreamBuffer_t StaticMessageBuffer_t; - -/* *INDENT-OFF* */ -#ifdef __cplusplus - } -#endif -/* *INDENT-ON* */ - -#endif /* INC_FREERTOS_H */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef INC_FREERTOS_H +#define INC_FREERTOS_H + +/* + * Include the generic headers required for the FreeRTOS port being used. + */ +#include + +/* + * If stdint.h cannot be located then: + * + If using GCC ensure the -nostdint options is *not* being used. + * + Ensure the project's include path includes the directory in which your + * compiler stores stdint.h. + * + Set any compiler options necessary for it to support C99, as technically + * stdint.h is only mandatory with C99 (FreeRTOS does not require C99 in any + * other way). + * + The FreeRTOS download includes a simple stdint.h definition that can be + * used in cases where none is provided by the compiler. The files only + * contains the typedefs required to build FreeRTOS. Read the instructions + * in FreeRTOS/source/stdint.readme for more information. + */ +#include /* READ COMMENT ABOVE. */ + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* Acceptable values for configTICK_TYPE_WIDTH_IN_BITS. */ +#define TICK_TYPE_WIDTH_16_BITS 0 +#define TICK_TYPE_WIDTH_32_BITS 1 +#define TICK_TYPE_WIDTH_64_BITS 2 + +/* Application specific configuration options. */ +#include "FreeRTOSConfig.h" + +#if !defined( configUSE_16_BIT_TICKS ) && !defined( configTICK_TYPE_WIDTH_IN_BITS ) + #error Missing definition: One of configUSE_16_BIT_TICKS and configTICK_TYPE_WIDTH_IN_BITS must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#if defined( configUSE_16_BIT_TICKS ) && defined( configTICK_TYPE_WIDTH_IN_BITS ) + #error Only one of configUSE_16_BIT_TICKS and configTICK_TYPE_WIDTH_IN_BITS must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +/* Define configTICK_TYPE_WIDTH_IN_BITS according to the + * value of configUSE_16_BIT_TICKS for backward compatibility. */ +#ifndef configTICK_TYPE_WIDTH_IN_BITS + #if ( configUSE_16_BIT_TICKS == 1 ) + #define configTICK_TYPE_WIDTH_IN_BITS TICK_TYPE_WIDTH_16_BITS + #else + #define configTICK_TYPE_WIDTH_IN_BITS TICK_TYPE_WIDTH_32_BITS + #endif +#endif + +/* Set configUSE_MPU_WRAPPERS_V1 to 1 to use MPU wrappers v1. */ +#ifndef configUSE_MPU_WRAPPERS_V1 + #define configUSE_MPU_WRAPPERS_V1 0 +#endif + +/* Set configENABLE_ACCESS_CONTROL_LIST to 1 to enable access control list support. */ +#ifndef configENABLE_ACCESS_CONTROL_LIST + #define configENABLE_ACCESS_CONTROL_LIST 0 +#endif + +/* Set default value of configNUMBER_OF_CORES to 1 to use single core FreeRTOS. */ +#ifndef configNUMBER_OF_CORES + #define configNUMBER_OF_CORES 1 +#endif + +#ifndef configUSE_MALLOC_FAILED_HOOK + #define configUSE_MALLOC_FAILED_HOOK 0 +#endif + +/* Basic FreeRTOS definitions. */ +#include "projdefs.h" + +/* Definitions specific to the port being used. */ +#include "portable.h" + +/* Must be defaulted before configUSE_NEWLIB_REENTRANT is used below. */ +#ifndef configUSE_NEWLIB_REENTRANT + #define configUSE_NEWLIB_REENTRANT 0 +#endif + +/* Required if struct _reent is used. */ +#if ( configUSE_NEWLIB_REENTRANT == 1 ) + + #include "newlib-freertos.h" + +#endif /* if ( configUSE_NEWLIB_REENTRANT == 1 ) */ + +/* Must be defaulted before configUSE_PICOLIBC_TLS is used below. */ +#ifndef configUSE_PICOLIBC_TLS + #define configUSE_PICOLIBC_TLS 0 +#endif + +#if ( configUSE_PICOLIBC_TLS == 1 ) + + #include "picolibc-freertos.h" + +#endif /* if ( configUSE_PICOLIBC_TLS == 1 ) */ + +#ifndef configUSE_C_RUNTIME_TLS_SUPPORT + #define configUSE_C_RUNTIME_TLS_SUPPORT 0 +#endif + +#if ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) + + #ifndef configTLS_BLOCK_TYPE + #error Missing definition: configTLS_BLOCK_TYPE must be defined in FreeRTOSConfig.h when configUSE_C_RUNTIME_TLS_SUPPORT is set to 1. + #endif + + #ifndef configINIT_TLS_BLOCK + #error Missing definition: configINIT_TLS_BLOCK must be defined in FreeRTOSConfig.h when configUSE_C_RUNTIME_TLS_SUPPORT is set to 1. + #endif + + #ifndef configSET_TLS_BLOCK + #error Missing definition: configSET_TLS_BLOCK must be defined in FreeRTOSConfig.h when configUSE_C_RUNTIME_TLS_SUPPORT is set to 1. + #endif + + #ifndef configDEINIT_TLS_BLOCK + #error Missing definition: configDEINIT_TLS_BLOCK must be defined in FreeRTOSConfig.h when configUSE_C_RUNTIME_TLS_SUPPORT is set to 1. + #endif +#endif /* if ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) */ + +/* + * Check all the required application specific macros have been defined. + * These macros are application specific and (as downloaded) are defined + * within FreeRTOSConfig.h. + */ + +#ifndef configMINIMAL_STACK_SIZE + #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. +#endif + +#ifndef configMAX_PRIORITIES + #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#if configMAX_PRIORITIES < 1 + #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. +#endif + +#ifndef configUSE_PREEMPTION + #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_IDLE_HOOK + #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#if ( configNUMBER_OF_CORES > 1 ) + #ifndef configUSE_PASSIVE_IDLE_HOOK + #error Missing definition: configUSE_PASSIVE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. + #endif +#endif + +#ifndef configUSE_TICK_HOOK + #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#if ( ( configTICK_TYPE_WIDTH_IN_BITS != TICK_TYPE_WIDTH_16_BITS ) && \ + ( configTICK_TYPE_WIDTH_IN_BITS != TICK_TYPE_WIDTH_32_BITS ) && \ + ( configTICK_TYPE_WIDTH_IN_BITS != TICK_TYPE_WIDTH_64_BITS ) ) + #error Macro configTICK_TYPE_WIDTH_IN_BITS is defined to incorrect value. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_CO_ROUTINES + #define configUSE_CO_ROUTINES 0 +#endif + +#ifndef INCLUDE_vTaskPrioritySet + #define INCLUDE_vTaskPrioritySet 0 +#endif + +#ifndef INCLUDE_uxTaskPriorityGet + #define INCLUDE_uxTaskPriorityGet 0 +#endif + +#ifndef INCLUDE_vTaskDelete + #define INCLUDE_vTaskDelete 0 +#endif + +#ifndef INCLUDE_vTaskSuspend + #define INCLUDE_vTaskSuspend 0 +#endif + +#ifdef INCLUDE_xTaskDelayUntil + #ifdef INCLUDE_vTaskDelayUntil + +/* INCLUDE_vTaskDelayUntil was replaced by INCLUDE_xTaskDelayUntil. Backward + * compatibility is maintained if only one or the other is defined, but + * there is a conflict if both are defined. */ + #error INCLUDE_vTaskDelayUntil and INCLUDE_xTaskDelayUntil are both defined. INCLUDE_vTaskDelayUntil is no longer required and should be removed + #endif +#endif + +#ifndef INCLUDE_xTaskDelayUntil + #ifdef INCLUDE_vTaskDelayUntil + +/* If INCLUDE_vTaskDelayUntil is set but INCLUDE_xTaskDelayUntil is not then + * the project's FreeRTOSConfig.h probably pre-dates the introduction of + * xTaskDelayUntil and setting INCLUDE_xTaskDelayUntil to whatever + * INCLUDE_vTaskDelayUntil is set to will ensure backward compatibility. + */ + #define INCLUDE_xTaskDelayUntil INCLUDE_vTaskDelayUntil + #endif +#endif + +#ifndef INCLUDE_xTaskDelayUntil + #define INCLUDE_xTaskDelayUntil 0 +#endif + +#ifndef INCLUDE_vTaskDelay + #define INCLUDE_vTaskDelay 0 +#endif + +#ifndef INCLUDE_xTaskGetIdleTaskHandle + #define INCLUDE_xTaskGetIdleTaskHandle 0 +#endif + +#ifndef INCLUDE_xTaskAbortDelay + #define INCLUDE_xTaskAbortDelay 0 +#endif + +#ifndef INCLUDE_xQueueGetMutexHolder + #define INCLUDE_xQueueGetMutexHolder 0 +#endif + +#ifndef INCLUDE_xSemaphoreGetMutexHolder + #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder +#endif + +#ifndef INCLUDE_xTaskGetHandle + #define INCLUDE_xTaskGetHandle 0 +#endif + +#ifndef INCLUDE_uxTaskGetStackHighWaterMark + #define INCLUDE_uxTaskGetStackHighWaterMark 0 +#endif + +#ifndef INCLUDE_uxTaskGetStackHighWaterMark2 + #define INCLUDE_uxTaskGetStackHighWaterMark2 0 +#endif + +#ifndef INCLUDE_eTaskGetState + #define INCLUDE_eTaskGetState 0 +#endif + +#ifndef INCLUDE_xTaskResumeFromISR + #define INCLUDE_xTaskResumeFromISR 1 +#endif + +#ifndef INCLUDE_xTimerPendFunctionCall + #define INCLUDE_xTimerPendFunctionCall 0 +#endif + +#ifndef INCLUDE_xTaskGetSchedulerState + #define INCLUDE_xTaskGetSchedulerState 0 +#endif + +#ifndef INCLUDE_xTaskGetCurrentTaskHandle + #define INCLUDE_xTaskGetCurrentTaskHandle 1 +#endif + +#if configUSE_CO_ROUTINES != 0 + #ifndef configMAX_CO_ROUTINE_PRIORITIES + #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. + #endif +#endif + +#ifndef configUSE_APPLICATION_TASK_TAG + #define configUSE_APPLICATION_TASK_TAG 0 +#endif + +#ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS + #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 +#endif + +#ifndef configUSE_RECURSIVE_MUTEXES + #define configUSE_RECURSIVE_MUTEXES 0 +#endif + +#ifndef configUSE_MUTEXES + #define configUSE_MUTEXES 0 +#endif + +#ifndef configUSE_TIMERS + #define configUSE_TIMERS 0 +#endif + +#ifndef configUSE_EVENT_GROUPS + #define configUSE_EVENT_GROUPS 1 +#endif + +#ifndef configUSE_STREAM_BUFFERS + #define configUSE_STREAM_BUFFERS 1 +#endif + +#ifndef configUSE_DAEMON_TASK_STARTUP_HOOK + #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 +#endif + +#if ( configUSE_DAEMON_TASK_STARTUP_HOOK != 0 ) + #if ( configUSE_TIMERS == 0 ) + #error configUSE_DAEMON_TASK_STARTUP_HOOK is set, but the daemon task is not created because configUSE_TIMERS is 0. + #endif +#endif + +#ifndef configUSE_COUNTING_SEMAPHORES + #define configUSE_COUNTING_SEMAPHORES 0 +#endif + +#ifndef configUSE_TASK_PREEMPTION_DISABLE + #define configUSE_TASK_PREEMPTION_DISABLE 0 +#endif + +#ifndef configUSE_ALTERNATIVE_API + #define configUSE_ALTERNATIVE_API 0 +#endif + +#ifndef portCRITICAL_NESTING_IN_TCB + #define portCRITICAL_NESTING_IN_TCB 0 +#endif + +#ifndef configMAX_TASK_NAME_LEN + #define configMAX_TASK_NAME_LEN 16 +#endif + +#ifndef configIDLE_SHOULD_YIELD + #define configIDLE_SHOULD_YIELD 1 +#endif + +#if configMAX_TASK_NAME_LEN < 1 + #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h +#endif + +#ifndef configASSERT + #define configASSERT( x ) + #define configASSERT_DEFINED 0 +#else + #define configASSERT_DEFINED 1 +#endif + +/* configPRECONDITION should be defined as configASSERT. + * The CBMC proofs need a way to track assumptions and assertions. + * A configPRECONDITION statement should express an implicit invariant or + * assumption made. A configASSERT statement should express an invariant that must + * hold explicit before calling the code. */ +#ifndef configPRECONDITION + #define configPRECONDITION( X ) configASSERT( X ) + #define configPRECONDITION_DEFINED 0 +#else + #define configPRECONDITION_DEFINED 1 +#endif + +#ifndef configCHECK_HANDLER_INSTALLATION + #define configCHECK_HANDLER_INSTALLATION 1 +#else + +/* The application has explicitly defined configCHECK_HANDLER_INSTALLATION + * to 1. The checks requires configASSERT() to be defined. */ + #if ( ( configCHECK_HANDLER_INSTALLATION == 1 ) && ( configASSERT_DEFINED == 0 ) ) + #error You must define configASSERT() when configCHECK_HANDLER_INSTALLATION is 1. + #endif +#endif + +#ifndef portMEMORY_BARRIER + #define portMEMORY_BARRIER() +#endif + +#ifndef portSOFTWARE_BARRIER + #define portSOFTWARE_BARRIER() +#endif + +#ifndef configRUN_MULTIPLE_PRIORITIES + #define configRUN_MULTIPLE_PRIORITIES 0 +#endif + +#ifndef portGET_CORE_ID + + #if ( configNUMBER_OF_CORES == 1 ) + #define portGET_CORE_ID() 0 + #else + #error configNUMBER_OF_CORES is set to more than 1 then portGET_CORE_ID must also be defined. + #endif /* configNUMBER_OF_CORES */ + +#endif /* portGET_CORE_ID */ + +#ifndef portYIELD_CORE + + #if ( configNUMBER_OF_CORES == 1 ) + #define portYIELD_CORE( x ) portYIELD() + #else + #error configNUMBER_OF_CORES is set to more than 1 then portYIELD_CORE must also be defined. + #endif /* configNUMBER_OF_CORES */ + +#endif /* portYIELD_CORE */ + +#ifndef portSET_INTERRUPT_MASK + + #if ( configNUMBER_OF_CORES > 1 ) + #error portSET_INTERRUPT_MASK is required in SMP + #endif + +#endif /* portSET_INTERRUPT_MASK */ + +#ifndef portCLEAR_INTERRUPT_MASK + + #if ( configNUMBER_OF_CORES > 1 ) + #error portCLEAR_INTERRUPT_MASK is required in SMP + #endif + +#endif /* portCLEAR_INTERRUPT_MASK */ + +#ifndef portRELEASE_TASK_LOCK + + #if ( configNUMBER_OF_CORES == 1 ) + #define portRELEASE_TASK_LOCK() + #else + #error portRELEASE_TASK_LOCK is required in SMP + #endif + +#endif /* portRELEASE_TASK_LOCK */ + +#ifndef portGET_TASK_LOCK + + #if ( configNUMBER_OF_CORES == 1 ) + #define portGET_TASK_LOCK() + #else + #error portGET_TASK_LOCK is required in SMP + #endif + +#endif /* portGET_TASK_LOCK */ + +#ifndef portRELEASE_ISR_LOCK + + #if ( configNUMBER_OF_CORES == 1 ) + #define portRELEASE_ISR_LOCK() + #else + #error portRELEASE_ISR_LOCK is required in SMP + #endif + +#endif /* portRELEASE_ISR_LOCK */ + +#ifndef portGET_ISR_LOCK + + #if ( configNUMBER_OF_CORES == 1 ) + #define portGET_ISR_LOCK() + #else + #error portGET_ISR_LOCK is required in SMP + #endif + +#endif /* portGET_ISR_LOCK */ + +#ifndef portENTER_CRITICAL_FROM_ISR + + #if ( configNUMBER_OF_CORES > 1 ) + #error portENTER_CRITICAL_FROM_ISR is required in SMP + #endif + +#endif + +#ifndef portEXIT_CRITICAL_FROM_ISR + + #if ( configNUMBER_OF_CORES > 1 ) + #error portEXIT_CRITICAL_FROM_ISR is required in SMP + #endif + +#endif + +#ifndef configUSE_CORE_AFFINITY + #define configUSE_CORE_AFFINITY 0 +#endif /* configUSE_CORE_AFFINITY */ + +#if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + #ifndef configTASK_DEFAULT_CORE_AFFINITY + #define configTASK_DEFAULT_CORE_AFFINITY tskNO_AFFINITY + #endif +#endif + +#ifndef configUSE_PASSIVE_IDLE_HOOK + #define configUSE_PASSIVE_IDLE_HOOK 0 +#endif /* configUSE_PASSIVE_IDLE_HOOK */ + +/* The timers module relies on xTaskGetSchedulerState(). */ +#if configUSE_TIMERS == 1 + + #ifndef configTIMER_TASK_PRIORITY + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. + #endif /* configTIMER_TASK_PRIORITY */ + + #ifndef configTIMER_QUEUE_LENGTH + #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. + #endif /* configTIMER_QUEUE_LENGTH */ + + #ifndef configTIMER_TASK_STACK_DEPTH + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. + #endif /* configTIMER_TASK_STACK_DEPTH */ + + #ifndef portTIMER_CALLBACK_ATTRIBUTE + #define portTIMER_CALLBACK_ATTRIBUTE + #endif /* portTIMER_CALLBACK_ATTRIBUTE */ + +#endif /* configUSE_TIMERS */ + +#ifndef portHAS_NESTED_INTERRUPTS + #if defined( portSET_INTERRUPT_MASK_FROM_ISR ) && defined( portCLEAR_INTERRUPT_MASK_FROM_ISR ) + #define portHAS_NESTED_INTERRUPTS 1 + #else + #define portHAS_NESTED_INTERRUPTS 0 + #endif +#endif + +#ifndef portSET_INTERRUPT_MASK_FROM_ISR + #if ( portHAS_NESTED_INTERRUPTS == 1 ) + #error portSET_INTERRUPT_MASK_FROM_ISR must be defined for ports that support nested interrupts (i.e. portHAS_NESTED_INTERRUPTS is set to 1) + #else + #define portSET_INTERRUPT_MASK_FROM_ISR() 0 + #endif +#else + #if ( portHAS_NESTED_INTERRUPTS == 0 ) + #error portSET_INTERRUPT_MASK_FROM_ISR must not be defined for ports that do not support nested interrupts (i.e. portHAS_NESTED_INTERRUPTS is set to 0) + #endif +#endif + +#ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR + #if ( portHAS_NESTED_INTERRUPTS == 1 ) + #error portCLEAR_INTERRUPT_MASK_FROM_ISR must be defined for ports that support nested interrupts (i.e. portHAS_NESTED_INTERRUPTS is set to 1) + #else + #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) ( uxSavedStatusValue ) + #endif +#else + #if ( portHAS_NESTED_INTERRUPTS == 0 ) + #error portCLEAR_INTERRUPT_MASK_FROM_ISR must not be defined for ports that do not support nested interrupts (i.e. portHAS_NESTED_INTERRUPTS is set to 0) + #endif +#endif + +#ifndef portCLEAN_UP_TCB + #define portCLEAN_UP_TCB( pxTCB ) ( void ) ( pxTCB ) +#endif + +#ifndef portPRE_TASK_DELETE_HOOK + #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) +#endif + +#ifndef portSETUP_TCB + #define portSETUP_TCB( pxTCB ) ( void ) ( pxTCB ) +#endif + +#ifndef portTASK_SWITCH_HOOK + #define portTASK_SWITCH_HOOK( pxTCB ) ( void ) ( pxTCB ) +#endif + +#ifndef configQUEUE_REGISTRY_SIZE + #define configQUEUE_REGISTRY_SIZE 0U +#endif + +#if ( configQUEUE_REGISTRY_SIZE < 1 ) + #define vQueueAddToRegistry( xQueue, pcName ) + #define vQueueUnregisterQueue( xQueue ) + #define pcQueueGetName( xQueue ) +#endif + +#ifndef configUSE_MINI_LIST_ITEM + #define configUSE_MINI_LIST_ITEM 1 +#endif + +#ifndef portPOINTER_SIZE_TYPE + #define portPOINTER_SIZE_TYPE uint32_t +#endif + +/* Remove any unused trace macros. */ +#ifndef traceSTART + +/* Used to perform any necessary initialisation - for example, open a file + * into which trace is to be written. */ + #define traceSTART() +#endif + +#ifndef traceEND + +/* Use to close a trace, for example close a file into which trace has been + * written. */ + #define traceEND() +#endif + +#ifndef traceTASK_SWITCHED_IN + +/* Called after a task has been selected to run. pxCurrentTCB holds a pointer + * to the task control block of the selected task. */ + #define traceTASK_SWITCHED_IN() +#endif + +#ifndef traceINCREASE_TICK_COUNT + +/* Called before stepping the tick count after waking from tickless idle + * sleep. */ + #define traceINCREASE_TICK_COUNT( x ) +#endif + +#ifndef traceLOW_POWER_IDLE_BEGIN + /* Called immediately before entering tickless idle. */ + #define traceLOW_POWER_IDLE_BEGIN() +#endif + +#ifndef traceLOW_POWER_IDLE_END + /* Called when returning to the Idle task after a tickless idle. */ + #define traceLOW_POWER_IDLE_END() +#endif + +#ifndef traceTASK_SWITCHED_OUT + +/* Called before a task has been selected to run. pxCurrentTCB holds a pointer + * to the task control block of the task being switched out. */ + #define traceTASK_SWITCHED_OUT() +#endif + +#ifndef traceTASK_PRIORITY_INHERIT + +/* Called when a task attempts to take a mutex that is already held by a + * lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task + * that holds the mutex. uxInheritedPriority is the priority the mutex holder + * will inherit (the priority of the task that is attempting to obtain the + * muted. */ + #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) +#endif + +#ifndef traceTASK_PRIORITY_DISINHERIT + +/* Called when a task releases a mutex, the holding of which had resulted in + * the task inheriting the priority of a higher priority task. + * pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the + * mutex. uxOriginalPriority is the task's configured (base) priority. */ + #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_RECEIVE + +/* Task is about to block because it cannot read from a + * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + * upon which the read was attempted. pxCurrentTCB points to the TCB of the + * task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_PEEK + +/* Task is about to block because it cannot read from a + * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + * upon which the read was attempted. pxCurrentTCB points to the TCB of the + * task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_SEND + +/* Task is about to block because it cannot write to a + * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + * upon which the write was attempted. pxCurrentTCB points to the TCB of the + * task that attempted the write. */ + #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) +#endif + +#ifndef configCHECK_FOR_STACK_OVERFLOW + #define configCHECK_FOR_STACK_OVERFLOW 0 +#endif + +#ifndef configRECORD_STACK_HIGH_ADDRESS + #define configRECORD_STACK_HIGH_ADDRESS 0 +#endif + +#ifndef configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H + #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 +#endif + +/* The following event macros are embedded in the kernel API calls. */ + +#ifndef traceMOVED_TASK_TO_READY_STATE + #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) +#endif + +#ifndef tracePOST_MOVED_TASK_TO_READY_STATE + #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) +#endif + +#ifndef traceMOVED_TASK_TO_DELAYED_LIST + #define traceMOVED_TASK_TO_DELAYED_LIST() +#endif + +#ifndef traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST + #define traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST() +#endif + +#ifndef traceQUEUE_CREATE + #define traceQUEUE_CREATE( pxNewQueue ) +#endif + +#ifndef traceQUEUE_CREATE_FAILED + #define traceQUEUE_CREATE_FAILED( ucQueueType ) +#endif + +#ifndef traceCREATE_MUTEX + #define traceCREATE_MUTEX( pxNewQueue ) +#endif + +#ifndef traceCREATE_MUTEX_FAILED + #define traceCREATE_MUTEX_FAILED() +#endif + +#ifndef traceGIVE_MUTEX_RECURSIVE + #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) +#endif + +#ifndef traceGIVE_MUTEX_RECURSIVE_FAILED + #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) +#endif + +#ifndef traceTAKE_MUTEX_RECURSIVE + #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) +#endif + +#ifndef traceTAKE_MUTEX_RECURSIVE_FAILED + #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) +#endif + +#ifndef traceCREATE_COUNTING_SEMAPHORE + #define traceCREATE_COUNTING_SEMAPHORE() +#endif + +#ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED + #define traceCREATE_COUNTING_SEMAPHORE_FAILED() +#endif + +#ifndef traceQUEUE_SET_SEND + #define traceQUEUE_SET_SEND traceQUEUE_SEND +#endif + +#ifndef traceQUEUE_SEND + #define traceQUEUE_SEND( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FAILED + #define traceQUEUE_SEND_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE + #define traceQUEUE_RECEIVE( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK + #define traceQUEUE_PEEK( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FAILED + #define traceQUEUE_PEEK_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FROM_ISR + #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FAILED + #define traceQUEUE_RECEIVE_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FROM_ISR + #define traceQUEUE_SEND_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FROM_ISR_FAILED + #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FROM_ISR + #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED + #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FROM_ISR_FAILED + #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_DELETE + #define traceQUEUE_DELETE( pxQueue ) +#endif + +#ifndef traceTASK_CREATE + #define traceTASK_CREATE( pxNewTCB ) +#endif + +#ifndef traceTASK_CREATE_FAILED + #define traceTASK_CREATE_FAILED() +#endif + +#ifndef traceTASK_DELETE + #define traceTASK_DELETE( pxTaskToDelete ) +#endif + +#ifndef traceTASK_DELAY_UNTIL + #define traceTASK_DELAY_UNTIL( x ) +#endif + +#ifndef traceTASK_DELAY + #define traceTASK_DELAY() +#endif + +#ifndef traceTASK_PRIORITY_SET + #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) +#endif + +#ifndef traceTASK_SUSPEND + #define traceTASK_SUSPEND( pxTaskToSuspend ) +#endif + +#ifndef traceTASK_RESUME + #define traceTASK_RESUME( pxTaskToResume ) +#endif + +#ifndef traceTASK_RESUME_FROM_ISR + #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) +#endif + +#ifndef traceTASK_INCREMENT_TICK + #define traceTASK_INCREMENT_TICK( xTickCount ) +#endif + +#ifndef traceTIMER_CREATE + #define traceTIMER_CREATE( pxNewTimer ) +#endif + +#ifndef traceTIMER_CREATE_FAILED + #define traceTIMER_CREATE_FAILED() +#endif + +#ifndef traceTIMER_COMMAND_SEND + #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) +#endif + +#ifndef traceTIMER_EXPIRED + #define traceTIMER_EXPIRED( pxTimer ) +#endif + +#ifndef traceTIMER_COMMAND_RECEIVED + #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) +#endif + +#ifndef traceMALLOC + #define traceMALLOC( pvAddress, uiSize ) +#endif + +#ifndef traceFREE + #define traceFREE( pvAddress, uiSize ) +#endif + +#ifndef traceEVENT_GROUP_CREATE + #define traceEVENT_GROUP_CREATE( xEventGroup ) +#endif + +#ifndef traceEVENT_GROUP_CREATE_FAILED + #define traceEVENT_GROUP_CREATE_FAILED() +#endif + +#ifndef traceEVENT_GROUP_SYNC_BLOCK + #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) +#endif + +#ifndef traceEVENT_GROUP_SYNC_END + #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) ( xTimeoutOccurred ) +#endif + +#ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK + #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) +#endif + +#ifndef traceEVENT_GROUP_WAIT_BITS_END + #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) ( xTimeoutOccurred ) +#endif + +#ifndef traceEVENT_GROUP_CLEAR_BITS + #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) +#endif + +#ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR + #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) +#endif + +#ifndef traceEVENT_GROUP_SET_BITS + #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) +#endif + +#ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR + #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) +#endif + +#ifndef traceEVENT_GROUP_DELETE + #define traceEVENT_GROUP_DELETE( xEventGroup ) +#endif + +#ifndef tracePEND_FUNC_CALL + #define tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, ret ) +#endif + +#ifndef tracePEND_FUNC_CALL_FROM_ISR + #define tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, ret ) +#endif + +#ifndef traceQUEUE_REGISTRY_ADD + #define traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ) +#endif + +#ifndef traceTASK_NOTIFY_TAKE_BLOCK + #define traceTASK_NOTIFY_TAKE_BLOCK( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY_TAKE + #define traceTASK_NOTIFY_TAKE( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY_WAIT_BLOCK + #define traceTASK_NOTIFY_WAIT_BLOCK( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY_WAIT + #define traceTASK_NOTIFY_WAIT( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY + #define traceTASK_NOTIFY( uxIndexToNotify ) +#endif + +#ifndef traceTASK_NOTIFY_FROM_ISR + #define traceTASK_NOTIFY_FROM_ISR( uxIndexToNotify ) +#endif + +#ifndef traceTASK_NOTIFY_GIVE_FROM_ISR + #define traceTASK_NOTIFY_GIVE_FROM_ISR( uxIndexToNotify ) +#endif + +#ifndef traceISR_EXIT_TO_SCHEDULER + #define traceISR_EXIT_TO_SCHEDULER() +#endif + +#ifndef traceISR_EXIT + #define traceISR_EXIT() +#endif + +#ifndef traceISR_ENTER + #define traceISR_ENTER() +#endif + +#ifndef traceSTREAM_BUFFER_CREATE_FAILED + #define traceSTREAM_BUFFER_CREATE_FAILED( xStreamBufferType ) +#endif + +#ifndef traceSTREAM_BUFFER_CREATE_STATIC_FAILED + #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xStreamBufferType ) +#endif + +#ifndef traceSTREAM_BUFFER_CREATE + #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xStreamBufferType ) +#endif + +#ifndef traceSTREAM_BUFFER_DELETE + #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RESET + #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RESET_FROM_ISR + #define traceSTREAM_BUFFER_RESET_FROM_ISR( xStreamBuffer ) +#endif + +#ifndef traceBLOCKING_ON_STREAM_BUFFER_SEND + #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND + #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND_FAILED + #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND_FROM_ISR + #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) +#endif + +#ifndef traceBLOCKING_ON_STREAM_BUFFER_RECEIVE + #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE + #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE_FAILED + #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE_FROM_ISR + #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) +#endif + +#ifndef traceENTER_xEventGroupCreateStatic + #define traceENTER_xEventGroupCreateStatic( pxEventGroupBuffer ) +#endif + +#ifndef traceRETURN_xEventGroupCreateStatic + #define traceRETURN_xEventGroupCreateStatic( pxEventBits ) +#endif + +#ifndef traceENTER_xEventGroupCreate + #define traceENTER_xEventGroupCreate() +#endif + +#ifndef traceRETURN_xEventGroupCreate + #define traceRETURN_xEventGroupCreate( pxEventBits ) +#endif + +#ifndef traceENTER_xEventGroupSync + #define traceENTER_xEventGroupSync( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTicksToWait ) +#endif + +#ifndef traceRETURN_xEventGroupSync + #define traceRETURN_xEventGroupSync( uxReturn ) +#endif + +#ifndef traceENTER_xEventGroupWaitBits + #define traceENTER_xEventGroupWaitBits( xEventGroup, uxBitsToWaitFor, xClearOnExit, xWaitForAllBits, xTicksToWait ) +#endif + +#ifndef traceRETURN_xEventGroupWaitBits + #define traceRETURN_xEventGroupWaitBits( uxReturn ) +#endif + +#ifndef traceENTER_xEventGroupClearBits + #define traceENTER_xEventGroupClearBits( xEventGroup, uxBitsToClear ) +#endif + +#ifndef traceRETURN_xEventGroupClearBits + #define traceRETURN_xEventGroupClearBits( uxReturn ) +#endif + +#ifndef traceENTER_xEventGroupClearBitsFromISR + #define traceENTER_xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) +#endif + +#ifndef traceRETURN_xEventGroupClearBitsFromISR + #define traceRETURN_xEventGroupClearBitsFromISR( xReturn ) +#endif + +#ifndef traceENTER_xEventGroupGetBitsFromISR + #define traceENTER_xEventGroupGetBitsFromISR( xEventGroup ) +#endif + +#ifndef traceRETURN_xEventGroupGetBitsFromISR + #define traceRETURN_xEventGroupGetBitsFromISR( uxReturn ) +#endif + +#ifndef traceENTER_xEventGroupSetBits + #define traceENTER_xEventGroupSetBits( xEventGroup, uxBitsToSet ) +#endif + +#ifndef traceRETURN_xEventGroupSetBits + #define traceRETURN_xEventGroupSetBits( uxEventBits ) +#endif + +#ifndef traceENTER_vEventGroupDelete + #define traceENTER_vEventGroupDelete( xEventGroup ) +#endif + +#ifndef traceRETURN_vEventGroupDelete + #define traceRETURN_vEventGroupDelete() +#endif + +#ifndef traceENTER_xEventGroupGetStaticBuffer + #define traceENTER_xEventGroupGetStaticBuffer( xEventGroup, ppxEventGroupBuffer ) +#endif + +#ifndef traceRETURN_xEventGroupGetStaticBuffer + #define traceRETURN_xEventGroupGetStaticBuffer( xReturn ) +#endif + +#ifndef traceENTER_vEventGroupSetBitsCallback + #define traceENTER_vEventGroupSetBitsCallback( pvEventGroup, ulBitsToSet ) +#endif + +#ifndef traceRETURN_vEventGroupSetBitsCallback + #define traceRETURN_vEventGroupSetBitsCallback() +#endif + +#ifndef traceENTER_vEventGroupClearBitsCallback + #define traceENTER_vEventGroupClearBitsCallback( pvEventGroup, ulBitsToClear ) +#endif + +#ifndef traceRETURN_vEventGroupClearBitsCallback + #define traceRETURN_vEventGroupClearBitsCallback() +#endif + +#ifndef traceENTER_xEventGroupSetBitsFromISR + #define traceENTER_xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) +#endif + +#ifndef traceRETURN_xEventGroupSetBitsFromISR + #define traceRETURN_xEventGroupSetBitsFromISR( xReturn ) +#endif + +#ifndef traceENTER_uxEventGroupGetNumber + #define traceENTER_uxEventGroupGetNumber( xEventGroup ) +#endif + +#ifndef traceRETURN_uxEventGroupGetNumber + #define traceRETURN_uxEventGroupGetNumber( xReturn ) +#endif + +#ifndef traceENTER_vEventGroupSetNumber + #define traceENTER_vEventGroupSetNumber( xEventGroup, uxEventGroupNumber ) +#endif + +#ifndef traceRETURN_vEventGroupSetNumber + #define traceRETURN_vEventGroupSetNumber() +#endif + +#ifndef traceENTER_xQueueGenericReset + #define traceENTER_xQueueGenericReset( xQueue, xNewQueue ) +#endif + +#ifndef traceRETURN_xQueueGenericReset + #define traceRETURN_xQueueGenericReset( xReturn ) +#endif + +#ifndef traceENTER_xQueueGenericCreateStatic + #define traceENTER_xQueueGenericCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxStaticQueue, ucQueueType ) +#endif + +#ifndef traceRETURN_xQueueGenericCreateStatic + #define traceRETURN_xQueueGenericCreateStatic( pxNewQueue ) +#endif + +#ifndef traceENTER_xQueueGenericGetStaticBuffers + #define traceENTER_xQueueGenericGetStaticBuffers( xQueue, ppucQueueStorage, ppxStaticQueue ) +#endif + +#ifndef traceRETURN_xQueueGenericGetStaticBuffers + #define traceRETURN_xQueueGenericGetStaticBuffers( xReturn ) +#endif + +#ifndef traceENTER_xQueueGenericCreate + #define traceENTER_xQueueGenericCreate( uxQueueLength, uxItemSize, ucQueueType ) +#endif + +#ifndef traceRETURN_xQueueGenericCreate + #define traceRETURN_xQueueGenericCreate( pxNewQueue ) +#endif + +#ifndef traceENTER_xQueueCreateMutex + #define traceENTER_xQueueCreateMutex( ucQueueType ) +#endif + +#ifndef traceRETURN_xQueueCreateMutex + #define traceRETURN_xQueueCreateMutex( xNewQueue ) +#endif + +#ifndef traceENTER_xQueueCreateMutexStatic + #define traceENTER_xQueueCreateMutexStatic( ucQueueType, pxStaticQueue ) +#endif + +#ifndef traceRETURN_xQueueCreateMutexStatic + #define traceRETURN_xQueueCreateMutexStatic( xNewQueue ) +#endif + +#ifndef traceENTER_xQueueGetMutexHolder + #define traceENTER_xQueueGetMutexHolder( xSemaphore ) +#endif + +#ifndef traceRETURN_xQueueGetMutexHolder + #define traceRETURN_xQueueGetMutexHolder( pxReturn ) +#endif + +#ifndef traceENTER_xQueueGetMutexHolderFromISR + #define traceENTER_xQueueGetMutexHolderFromISR( xSemaphore ) +#endif + +#ifndef traceRETURN_xQueueGetMutexHolderFromISR + #define traceRETURN_xQueueGetMutexHolderFromISR( pxReturn ) +#endif + +#ifndef traceENTER_xQueueGiveMutexRecursive + #define traceENTER_xQueueGiveMutexRecursive( xMutex ) +#endif + +#ifndef traceRETURN_xQueueGiveMutexRecursive + #define traceRETURN_xQueueGiveMutexRecursive( xReturn ) +#endif + +#ifndef traceENTER_xQueueTakeMutexRecursive + #define traceENTER_xQueueTakeMutexRecursive( xMutex, xTicksToWait ) +#endif + +#ifndef traceRETURN_xQueueTakeMutexRecursive + #define traceRETURN_xQueueTakeMutexRecursive( xReturn ) +#endif + +#ifndef traceENTER_xQueueCreateCountingSemaphoreStatic + #define traceENTER_xQueueCreateCountingSemaphoreStatic( uxMaxCount, uxInitialCount, pxStaticQueue ) +#endif + +#ifndef traceRETURN_xQueueCreateCountingSemaphoreStatic + #define traceRETURN_xQueueCreateCountingSemaphoreStatic( xHandle ) +#endif + +#ifndef traceENTER_xQueueCreateCountingSemaphore + #define traceENTER_xQueueCreateCountingSemaphore( uxMaxCount, uxInitialCount ) +#endif + +#ifndef traceRETURN_xQueueCreateCountingSemaphore + #define traceRETURN_xQueueCreateCountingSemaphore( xHandle ) +#endif + +#ifndef traceENTER_xQueueGenericSend + #define traceENTER_xQueueGenericSend( xQueue, pvItemToQueue, xTicksToWait, xCopyPosition ) +#endif + +#ifndef traceRETURN_xQueueGenericSend + #define traceRETURN_xQueueGenericSend( xReturn ) +#endif + +#ifndef traceENTER_xQueueGenericSendFromISR + #define traceENTER_xQueueGenericSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken, xCopyPosition ) +#endif + +#ifndef traceRETURN_xQueueGenericSendFromISR + #define traceRETURN_xQueueGenericSendFromISR( xReturn ) +#endif + +#ifndef traceENTER_xQueueGiveFromISR + #define traceENTER_xQueueGiveFromISR( xQueue, pxHigherPriorityTaskWoken ) +#endif + +#ifndef traceRETURN_xQueueGiveFromISR + #define traceRETURN_xQueueGiveFromISR( xReturn ) +#endif + +#ifndef traceENTER_xQueueReceive + #define traceENTER_xQueueReceive( xQueue, pvBuffer, xTicksToWait ) +#endif + +#ifndef traceRETURN_xQueueReceive + #define traceRETURN_xQueueReceive( xReturn ) +#endif + +#ifndef traceENTER_xQueueSemaphoreTake + #define traceENTER_xQueueSemaphoreTake( xQueue, xTicksToWait ) +#endif + +#ifndef traceRETURN_xQueueSemaphoreTake + #define traceRETURN_xQueueSemaphoreTake( xReturn ) +#endif + +#ifndef traceENTER_xQueuePeek + #define traceENTER_xQueuePeek( xQueue, pvBuffer, xTicksToWait ) +#endif + +#ifndef traceRETURN_xQueuePeek + #define traceRETURN_xQueuePeek( xReturn ) +#endif + +#ifndef traceENTER_xQueueReceiveFromISR + #define traceENTER_xQueueReceiveFromISR( xQueue, pvBuffer, pxHigherPriorityTaskWoken ) +#endif + +#ifndef traceRETURN_xQueueReceiveFromISR + #define traceRETURN_xQueueReceiveFromISR( xReturn ) +#endif + +#ifndef traceENTER_xQueuePeekFromISR + #define traceENTER_xQueuePeekFromISR( xQueue, pvBuffer ) +#endif + +#ifndef traceRETURN_xQueuePeekFromISR + #define traceRETURN_xQueuePeekFromISR( xReturn ) +#endif + +#ifndef traceENTER_uxQueueMessagesWaiting + #define traceENTER_uxQueueMessagesWaiting( xQueue ) +#endif + +#ifndef traceRETURN_uxQueueMessagesWaiting + #define traceRETURN_uxQueueMessagesWaiting( uxReturn ) +#endif + +#ifndef traceENTER_uxQueueSpacesAvailable + #define traceENTER_uxQueueSpacesAvailable( xQueue ) +#endif + +#ifndef traceRETURN_uxQueueSpacesAvailable + #define traceRETURN_uxQueueSpacesAvailable( uxReturn ) +#endif + +#ifndef traceENTER_uxQueueMessagesWaitingFromISR + #define traceENTER_uxQueueMessagesWaitingFromISR( xQueue ) +#endif + +#ifndef traceRETURN_uxQueueMessagesWaitingFromISR + #define traceRETURN_uxQueueMessagesWaitingFromISR( uxReturn ) +#endif + +#ifndef traceENTER_vQueueDelete + #define traceENTER_vQueueDelete( xQueue ) +#endif + +#ifndef traceRETURN_vQueueDelete + #define traceRETURN_vQueueDelete() +#endif + +#ifndef traceENTER_uxQueueGetQueueNumber + #define traceENTER_uxQueueGetQueueNumber( xQueue ) +#endif + +#ifndef traceRETURN_uxQueueGetQueueNumber + #define traceRETURN_uxQueueGetQueueNumber( uxQueueNumber ) +#endif + +#ifndef traceENTER_vQueueSetQueueNumber + #define traceENTER_vQueueSetQueueNumber( xQueue, uxQueueNumber ) +#endif + +#ifndef traceRETURN_vQueueSetQueueNumber + #define traceRETURN_vQueueSetQueueNumber() +#endif + +#ifndef traceENTER_ucQueueGetQueueType + #define traceENTER_ucQueueGetQueueType( xQueue ) +#endif + +#ifndef traceRETURN_ucQueueGetQueueType + #define traceRETURN_ucQueueGetQueueType( ucQueueType ) +#endif + +#ifndef traceENTER_uxQueueGetQueueItemSize + #define traceENTER_uxQueueGetQueueItemSize( xQueue ) +#endif + +#ifndef traceRETURN_uxQueueGetQueueItemSize + #define traceRETURN_uxQueueGetQueueItemSize( uxItemSize ) +#endif + +#ifndef traceENTER_uxQueueGetQueueLength + #define traceENTER_uxQueueGetQueueLength( xQueue ) +#endif + +#ifndef traceRETURN_uxQueueGetQueueLength + #define traceRETURN_uxQueueGetQueueLength( uxLength ) +#endif + +#ifndef traceENTER_xQueueIsQueueEmptyFromISR + #define traceENTER_xQueueIsQueueEmptyFromISR( xQueue ) +#endif + +#ifndef traceRETURN_xQueueIsQueueEmptyFromISR + #define traceRETURN_xQueueIsQueueEmptyFromISR( xReturn ) +#endif + +#ifndef traceENTER_xQueueIsQueueFullFromISR + #define traceENTER_xQueueIsQueueFullFromISR( xQueue ) +#endif + +#ifndef traceRETURN_xQueueIsQueueFullFromISR + #define traceRETURN_xQueueIsQueueFullFromISR( xReturn ) +#endif + +#ifndef traceENTER_xQueueCRSend + #define traceENTER_xQueueCRSend( xQueue, pvItemToQueue, xTicksToWait ) +#endif + +#ifndef traceRETURN_xQueueCRSend + #define traceRETURN_xQueueCRSend( xReturn ) +#endif + +#ifndef traceENTER_xQueueCRReceive + #define traceENTER_xQueueCRReceive( xQueue, pvBuffer, xTicksToWait ) +#endif + +#ifndef traceRETURN_xQueueCRReceive + #define traceRETURN_xQueueCRReceive( xReturn ) +#endif + +#ifndef traceENTER_xQueueCRSendFromISR + #define traceENTER_xQueueCRSendFromISR( xQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) +#endif + +#ifndef traceRETURN_xQueueCRSendFromISR + #define traceRETURN_xQueueCRSendFromISR( xCoRoutinePreviouslyWoken ) +#endif + +#ifndef traceENTER_xQueueCRReceiveFromISR + #define traceENTER_xQueueCRReceiveFromISR( xQueue, pvBuffer, pxCoRoutineWoken ) +#endif + +#ifndef traceRETURN_xQueueCRReceiveFromISR + #define traceRETURN_xQueueCRReceiveFromISR( xReturn ) +#endif + +#ifndef traceENTER_vQueueAddToRegistry + #define traceENTER_vQueueAddToRegistry( xQueue, pcQueueName ) +#endif + +#ifndef traceRETURN_vQueueAddToRegistry + #define traceRETURN_vQueueAddToRegistry() +#endif + +#ifndef traceENTER_pcQueueGetName + #define traceENTER_pcQueueGetName( xQueue ) +#endif + +#ifndef traceRETURN_pcQueueGetName + #define traceRETURN_pcQueueGetName( pcReturn ) +#endif + +#ifndef traceENTER_vQueueUnregisterQueue + #define traceENTER_vQueueUnregisterQueue( xQueue ) +#endif + +#ifndef traceRETURN_vQueueUnregisterQueue + #define traceRETURN_vQueueUnregisterQueue() +#endif + +#ifndef traceENTER_vQueueWaitForMessageRestricted + #define traceENTER_vQueueWaitForMessageRestricted( xQueue, xTicksToWait, xWaitIndefinitely ) +#endif + +#ifndef traceRETURN_vQueueWaitForMessageRestricted + #define traceRETURN_vQueueWaitForMessageRestricted() +#endif + +#ifndef traceENTER_xQueueCreateSet + #define traceENTER_xQueueCreateSet( uxEventQueueLength ) +#endif + +#ifndef traceRETURN_xQueueCreateSet + #define traceRETURN_xQueueCreateSet( pxQueue ) +#endif + +#ifndef traceENTER_xQueueAddToSet + #define traceENTER_xQueueAddToSet( xQueueOrSemaphore, xQueueSet ) +#endif + +#ifndef traceRETURN_xQueueAddToSet + #define traceRETURN_xQueueAddToSet( xReturn ) +#endif + +#ifndef traceENTER_xQueueRemoveFromSet + #define traceENTER_xQueueRemoveFromSet( xQueueOrSemaphore, xQueueSet ) +#endif + +#ifndef traceRETURN_xQueueRemoveFromSet + #define traceRETURN_xQueueRemoveFromSet( xReturn ) +#endif + +#ifndef traceENTER_xQueueSelectFromSet + #define traceENTER_xQueueSelectFromSet( xQueueSet, xTicksToWait ) +#endif + +#ifndef traceRETURN_xQueueSelectFromSet + #define traceRETURN_xQueueSelectFromSet( xReturn ) +#endif + +#ifndef traceENTER_xQueueSelectFromSetFromISR + #define traceENTER_xQueueSelectFromSetFromISR( xQueueSet ) +#endif + +#ifndef traceRETURN_xQueueSelectFromSetFromISR + #define traceRETURN_xQueueSelectFromSetFromISR( xReturn ) +#endif + +#ifndef traceENTER_xTimerCreateTimerTask + #define traceENTER_xTimerCreateTimerTask() +#endif + +#ifndef traceRETURN_xTimerCreateTimerTask + #define traceRETURN_xTimerCreateTimerTask( xReturn ) +#endif + +#ifndef traceENTER_xTimerCreate + #define traceENTER_xTimerCreate( pcTimerName, xTimerPeriodInTicks, xAutoReload, pvTimerID, pxCallbackFunction ) +#endif + +#ifndef traceRETURN_xTimerCreate + #define traceRETURN_xTimerCreate( pxNewTimer ) +#endif + +#ifndef traceENTER_xTimerCreateStatic + #define traceENTER_xTimerCreateStatic( pcTimerName, xTimerPeriodInTicks, xAutoReload, pvTimerID, pxCallbackFunction, pxTimerBuffer ) +#endif + +#ifndef traceRETURN_xTimerCreateStatic + #define traceRETURN_xTimerCreateStatic( pxNewTimer ) +#endif + +#ifndef traceENTER_xTimerGenericCommandFromTask + #define traceENTER_xTimerGenericCommandFromTask( xTimer, xCommandID, xOptionalValue, pxHigherPriorityTaskWoken, xTicksToWait ) +#endif + +#ifndef traceRETURN_xTimerGenericCommandFromTask + #define traceRETURN_xTimerGenericCommandFromTask( xReturn ) +#endif + +#ifndef traceENTER_xTimerGenericCommandFromISR + #define traceENTER_xTimerGenericCommandFromISR( xTimer, xCommandID, xOptionalValue, pxHigherPriorityTaskWoken, xTicksToWait ) +#endif + +#ifndef traceRETURN_xTimerGenericCommandFromISR + #define traceRETURN_xTimerGenericCommandFromISR( xReturn ) +#endif + +#ifndef traceENTER_xTimerGetTimerDaemonTaskHandle + #define traceENTER_xTimerGetTimerDaemonTaskHandle() +#endif + +#ifndef traceRETURN_xTimerGetTimerDaemonTaskHandle + #define traceRETURN_xTimerGetTimerDaemonTaskHandle( xTimerTaskHandle ) +#endif + +#ifndef traceENTER_xTimerGetPeriod + #define traceENTER_xTimerGetPeriod( xTimer ) +#endif + +#ifndef traceRETURN_xTimerGetPeriod + #define traceRETURN_xTimerGetPeriod( xTimerPeriodInTicks ) +#endif + +#ifndef traceENTER_vTimerSetReloadMode + #define traceENTER_vTimerSetReloadMode( xTimer, xAutoReload ) +#endif + +#ifndef traceRETURN_vTimerSetReloadMode + #define traceRETURN_vTimerSetReloadMode() +#endif + +#ifndef traceENTER_xTimerGetReloadMode + #define traceENTER_xTimerGetReloadMode( xTimer ) +#endif + +#ifndef traceRETURN_xTimerGetReloadMode + #define traceRETURN_xTimerGetReloadMode( xReturn ) +#endif + +#ifndef traceENTER_uxTimerGetReloadMode + #define traceENTER_uxTimerGetReloadMode( xTimer ) +#endif + +#ifndef traceRETURN_uxTimerGetReloadMode + #define traceRETURN_uxTimerGetReloadMode( uxReturn ) +#endif + +#ifndef traceENTER_xTimerGetExpiryTime + #define traceENTER_xTimerGetExpiryTime( xTimer ) +#endif + +#ifndef traceRETURN_xTimerGetExpiryTime + #define traceRETURN_xTimerGetExpiryTime( xReturn ) +#endif + +#ifndef traceENTER_xTimerGetStaticBuffer + #define traceENTER_xTimerGetStaticBuffer( xTimer, ppxTimerBuffer ) +#endif + +#ifndef traceRETURN_xTimerGetStaticBuffer + #define traceRETURN_xTimerGetStaticBuffer( xReturn ) +#endif + +#ifndef traceENTER_pcTimerGetName + #define traceENTER_pcTimerGetName( xTimer ) +#endif + +#ifndef traceRETURN_pcTimerGetName + #define traceRETURN_pcTimerGetName( pcTimerName ) +#endif + +#ifndef traceENTER_xTimerIsTimerActive + #define traceENTER_xTimerIsTimerActive( xTimer ) +#endif + +#ifndef traceRETURN_xTimerIsTimerActive + #define traceRETURN_xTimerIsTimerActive( xReturn ) +#endif + +#ifndef traceENTER_pvTimerGetTimerID + #define traceENTER_pvTimerGetTimerID( xTimer ) +#endif + +#ifndef traceRETURN_pvTimerGetTimerID + #define traceRETURN_pvTimerGetTimerID( pvReturn ) +#endif + +#ifndef traceENTER_vTimerSetTimerID + #define traceENTER_vTimerSetTimerID( xTimer, pvNewID ) +#endif + +#ifndef traceRETURN_vTimerSetTimerID + #define traceRETURN_vTimerSetTimerID() +#endif + +#ifndef traceENTER_xTimerPendFunctionCallFromISR + #define traceENTER_xTimerPendFunctionCallFromISR( xFunctionToPend, pvParameter1, ulParameter2, pxHigherPriorityTaskWoken ) +#endif + +#ifndef traceRETURN_xTimerPendFunctionCallFromISR + #define traceRETURN_xTimerPendFunctionCallFromISR( xReturn ) +#endif + +#ifndef traceENTER_xTimerPendFunctionCall + #define traceENTER_xTimerPendFunctionCall( xFunctionToPend, pvParameter1, ulParameter2, xTicksToWait ) +#endif + +#ifndef traceRETURN_xTimerPendFunctionCall + #define traceRETURN_xTimerPendFunctionCall( xReturn ) +#endif + +#ifndef traceENTER_uxTimerGetTimerNumber + #define traceENTER_uxTimerGetTimerNumber( xTimer ) +#endif + +#ifndef traceRETURN_uxTimerGetTimerNumber + #define traceRETURN_uxTimerGetTimerNumber( uxTimerNumber ) +#endif + +#ifndef traceENTER_vTimerSetTimerNumber + #define traceENTER_vTimerSetTimerNumber( xTimer, uxTimerNumber ) +#endif + +#ifndef traceRETURN_vTimerSetTimerNumber + #define traceRETURN_vTimerSetTimerNumber() +#endif + +#ifndef traceENTER_xTaskCreateStatic + #define traceENTER_xTaskCreateStatic( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, puxStackBuffer, pxTaskBuffer ) +#endif + +#ifndef traceRETURN_xTaskCreateStatic + #define traceRETURN_xTaskCreateStatic( xReturn ) +#endif + +#ifndef traceENTER_xTaskCreateStaticAffinitySet + #define traceENTER_xTaskCreateStaticAffinitySet( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, puxStackBuffer, pxTaskBuffer, uxCoreAffinityMask ) +#endif + +#ifndef traceRETURN_xTaskCreateStaticAffinitySet + #define traceRETURN_xTaskCreateStaticAffinitySet( xReturn ) +#endif + +#ifndef traceENTER_xTaskCreateRestrictedStatic + #define traceENTER_xTaskCreateRestrictedStatic( pxTaskDefinition, pxCreatedTask ) +#endif + +#ifndef traceRETURN_xTaskCreateRestrictedStatic + #define traceRETURN_xTaskCreateRestrictedStatic( xReturn ) +#endif + +#ifndef traceENTER_xTaskCreateRestrictedStaticAffinitySet + #define traceENTER_xTaskCreateRestrictedStaticAffinitySet( pxTaskDefinition, uxCoreAffinityMask, pxCreatedTask ) +#endif + +#ifndef traceRETURN_xTaskCreateRestrictedStaticAffinitySet + #define traceRETURN_xTaskCreateRestrictedStaticAffinitySet( xReturn ) +#endif + +#ifndef traceENTER_xTaskCreateRestricted + #define traceENTER_xTaskCreateRestricted( pxTaskDefinition, pxCreatedTask ) +#endif + +#ifndef traceRETURN_xTaskCreateRestricted + #define traceRETURN_xTaskCreateRestricted( xReturn ) +#endif + +#ifndef traceENTER_xTaskCreateRestrictedAffinitySet + #define traceENTER_xTaskCreateRestrictedAffinitySet( pxTaskDefinition, uxCoreAffinityMask, pxCreatedTask ) +#endif + +#ifndef traceRETURN_xTaskCreateRestrictedAffinitySet + #define traceRETURN_xTaskCreateRestrictedAffinitySet( xReturn ) +#endif + +#ifndef traceENTER_xTaskCreate + #define traceENTER_xTaskCreate( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, pxCreatedTask ) +#endif + +#ifndef traceRETURN_xTaskCreate + #define traceRETURN_xTaskCreate( xReturn ) +#endif + +#ifndef traceENTER_xTaskCreateAffinitySet + #define traceENTER_xTaskCreateAffinitySet( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, uxCoreAffinityMask, pxCreatedTask ) +#endif + +#ifndef traceRETURN_xTaskCreateAffinitySet + #define traceRETURN_xTaskCreateAffinitySet( xReturn ) +#endif + +#ifndef traceENTER_vTaskDelete + #define traceENTER_vTaskDelete( xTaskToDelete ) +#endif + +#ifndef traceRETURN_vTaskDelete + #define traceRETURN_vTaskDelete() +#endif + +#ifndef traceENTER_xTaskDelayUntil + #define traceENTER_xTaskDelayUntil( pxPreviousWakeTime, xTimeIncrement ) +#endif + +#ifndef traceRETURN_xTaskDelayUntil + #define traceRETURN_xTaskDelayUntil( xShouldDelay ) +#endif + +#ifndef traceENTER_vTaskDelay + #define traceENTER_vTaskDelay( xTicksToDelay ) +#endif + +#ifndef traceRETURN_vTaskDelay + #define traceRETURN_vTaskDelay() +#endif + +#ifndef traceENTER_eTaskGetState + #define traceENTER_eTaskGetState( xTask ) +#endif + +#ifndef traceRETURN_eTaskGetState + #define traceRETURN_eTaskGetState( eReturn ) +#endif + +#ifndef traceENTER_uxTaskPriorityGet + #define traceENTER_uxTaskPriorityGet( xTask ) +#endif + +#ifndef traceRETURN_uxTaskPriorityGet + #define traceRETURN_uxTaskPriorityGet( uxReturn ) +#endif + +#ifndef traceENTER_uxTaskPriorityGetFromISR + #define traceENTER_uxTaskPriorityGetFromISR( xTask ) +#endif + +#ifndef traceRETURN_uxTaskPriorityGetFromISR + #define traceRETURN_uxTaskPriorityGetFromISR( uxReturn ) +#endif + +#ifndef traceENTER_uxTaskBasePriorityGet + #define traceENTER_uxTaskBasePriorityGet( xTask ) +#endif + +#ifndef traceRETURN_uxTaskBasePriorityGet + #define traceRETURN_uxTaskBasePriorityGet( uxReturn ) +#endif + +#ifndef traceENTER_uxTaskBasePriorityGetFromISR + #define traceENTER_uxTaskBasePriorityGetFromISR( xTask ) +#endif + +#ifndef traceRETURN_uxTaskBasePriorityGetFromISR + #define traceRETURN_uxTaskBasePriorityGetFromISR( uxReturn ) +#endif + +#ifndef traceENTER_vTaskPrioritySet + #define traceENTER_vTaskPrioritySet( xTask, uxNewPriority ) +#endif + +#ifndef traceRETURN_vTaskPrioritySet + #define traceRETURN_vTaskPrioritySet() +#endif + +#ifndef traceENTER_vTaskCoreAffinitySet + #define traceENTER_vTaskCoreAffinitySet( xTask, uxCoreAffinityMask ) +#endif + +#ifndef traceRETURN_vTaskCoreAffinitySet + #define traceRETURN_vTaskCoreAffinitySet() +#endif + +#ifndef traceENTER_vTaskCoreAffinityGet + #define traceENTER_vTaskCoreAffinityGet( xTask ) +#endif + +#ifndef traceRETURN_vTaskCoreAffinityGet + #define traceRETURN_vTaskCoreAffinityGet( uxCoreAffinityMask ) +#endif + +#ifndef traceENTER_vTaskPreemptionDisable + #define traceENTER_vTaskPreemptionDisable( xTask ) +#endif + +#ifndef traceRETURN_vTaskPreemptionDisable + #define traceRETURN_vTaskPreemptionDisable() +#endif + +#ifndef traceENTER_vTaskPreemptionEnable + #define traceENTER_vTaskPreemptionEnable( xTask ) +#endif + +#ifndef traceRETURN_vTaskPreemptionEnable + #define traceRETURN_vTaskPreemptionEnable() +#endif + +#ifndef traceENTER_vTaskSuspend + #define traceENTER_vTaskSuspend( xTaskToSuspend ) +#endif + +#ifndef traceRETURN_vTaskSuspend + #define traceRETURN_vTaskSuspend() +#endif + +#ifndef traceENTER_vTaskResume + #define traceENTER_vTaskResume( xTaskToResume ) +#endif + +#ifndef traceRETURN_vTaskResume + #define traceRETURN_vTaskResume() +#endif + +#ifndef traceENTER_xTaskResumeFromISR + #define traceENTER_xTaskResumeFromISR( xTaskToResume ) +#endif + +#ifndef traceRETURN_xTaskResumeFromISR + #define traceRETURN_xTaskResumeFromISR( xYieldRequired ) +#endif + +#ifndef traceENTER_vTaskStartScheduler + #define traceENTER_vTaskStartScheduler() +#endif + +#ifndef traceRETURN_vTaskStartScheduler + #define traceRETURN_vTaskStartScheduler() +#endif + +#ifndef traceENTER_vTaskEndScheduler + #define traceENTER_vTaskEndScheduler() +#endif + +#ifndef traceRETURN_vTaskEndScheduler + #define traceRETURN_vTaskEndScheduler() +#endif + +#ifndef traceENTER_vTaskSuspendAll + #define traceENTER_vTaskSuspendAll() +#endif + +#ifndef traceRETURN_vTaskSuspendAll + #define traceRETURN_vTaskSuspendAll() +#endif + +#ifndef traceENTER_xTaskResumeAll + #define traceENTER_xTaskResumeAll() +#endif + +#ifndef traceRETURN_xTaskResumeAll + #define traceRETURN_xTaskResumeAll( xAlreadyYielded ) +#endif + +#ifndef traceENTER_xTaskGetTickCount + #define traceENTER_xTaskGetTickCount() +#endif + +#ifndef traceRETURN_xTaskGetTickCount + #define traceRETURN_xTaskGetTickCount( xTicks ) +#endif + +#ifndef traceENTER_xTaskGetTickCountFromISR + #define traceENTER_xTaskGetTickCountFromISR() +#endif + +#ifndef traceRETURN_xTaskGetTickCountFromISR + #define traceRETURN_xTaskGetTickCountFromISR( xReturn ) +#endif + +#ifndef traceENTER_uxTaskGetNumberOfTasks + #define traceENTER_uxTaskGetNumberOfTasks() +#endif + +#ifndef traceRETURN_uxTaskGetNumberOfTasks + #define traceRETURN_uxTaskGetNumberOfTasks( uxCurrentNumberOfTasks ) +#endif + +#ifndef traceENTER_pcTaskGetName + #define traceENTER_pcTaskGetName( xTaskToQuery ) +#endif + +#ifndef traceRETURN_pcTaskGetName + #define traceRETURN_pcTaskGetName( pcTaskName ) +#endif + +#ifndef traceENTER_xTaskGetHandle + #define traceENTER_xTaskGetHandle( pcNameToQuery ) +#endif + +#ifndef traceRETURN_xTaskGetHandle + #define traceRETURN_xTaskGetHandle( pxTCB ) +#endif + +#ifndef traceENTER_xTaskGetStaticBuffers + #define traceENTER_xTaskGetStaticBuffers( xTask, ppuxStackBuffer, ppxTaskBuffer ) +#endif + +#ifndef traceRETURN_xTaskGetStaticBuffers + #define traceRETURN_xTaskGetStaticBuffers( xReturn ) +#endif + +#ifndef traceENTER_uxTaskGetSystemState + #define traceENTER_uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, pulTotalRunTime ) +#endif + +#ifndef traceRETURN_uxTaskGetSystemState + #define traceRETURN_uxTaskGetSystemState( uxTask ) +#endif + +#if ( configNUMBER_OF_CORES == 1 ) + #ifndef traceENTER_xTaskGetIdleTaskHandle + #define traceENTER_xTaskGetIdleTaskHandle() + #endif +#endif + +#if ( configNUMBER_OF_CORES == 1 ) + #ifndef traceRETURN_xTaskGetIdleTaskHandle + #define traceRETURN_xTaskGetIdleTaskHandle( xIdleTaskHandle ) + #endif +#endif + +#ifndef traceENTER_xTaskGetIdleTaskHandleForCore + #define traceENTER_xTaskGetIdleTaskHandleForCore( xCoreID ) +#endif + +#ifndef traceRETURN_xTaskGetIdleTaskHandleForCore + #define traceRETURN_xTaskGetIdleTaskHandleForCore( xIdleTaskHandle ) +#endif + +#ifndef traceENTER_vTaskStepTick + #define traceENTER_vTaskStepTick( xTicksToJump ) +#endif + +#ifndef traceRETURN_vTaskStepTick + #define traceRETURN_vTaskStepTick() +#endif + +#ifndef traceENTER_xTaskCatchUpTicks + #define traceENTER_xTaskCatchUpTicks( xTicksToCatchUp ) +#endif + +#ifndef traceRETURN_xTaskCatchUpTicks + #define traceRETURN_xTaskCatchUpTicks( xYieldOccurred ) +#endif + +#ifndef traceENTER_xTaskAbortDelay + #define traceENTER_xTaskAbortDelay( xTask ) +#endif + +#ifndef traceRETURN_xTaskAbortDelay + #define traceRETURN_xTaskAbortDelay( xReturn ) +#endif + +#ifndef traceENTER_xTaskIncrementTick + #define traceENTER_xTaskIncrementTick() +#endif + +#ifndef traceRETURN_xTaskIncrementTick + #define traceRETURN_xTaskIncrementTick( xSwitchRequired ) +#endif + +#ifndef traceENTER_vTaskSetApplicationTaskTag + #define traceENTER_vTaskSetApplicationTaskTag( xTask, pxHookFunction ) +#endif + +#ifndef traceRETURN_vTaskSetApplicationTaskTag + #define traceRETURN_vTaskSetApplicationTaskTag() +#endif + +#ifndef traceENTER_xTaskGetApplicationTaskTag + #define traceENTER_xTaskGetApplicationTaskTag( xTask ) +#endif + +#ifndef traceRETURN_xTaskGetApplicationTaskTag + #define traceRETURN_xTaskGetApplicationTaskTag( xReturn ) +#endif + +#ifndef traceENTER_xTaskGetApplicationTaskTagFromISR + #define traceENTER_xTaskGetApplicationTaskTagFromISR( xTask ) +#endif + +#ifndef traceRETURN_xTaskGetApplicationTaskTagFromISR + #define traceRETURN_xTaskGetApplicationTaskTagFromISR( xReturn ) +#endif + +#ifndef traceENTER_xTaskCallApplicationTaskHook + #define traceENTER_xTaskCallApplicationTaskHook( xTask, pvParameter ) +#endif + +#ifndef traceRETURN_xTaskCallApplicationTaskHook + #define traceRETURN_xTaskCallApplicationTaskHook( xReturn ) +#endif + +#ifndef traceENTER_vTaskSwitchContext + #define traceENTER_vTaskSwitchContext() +#endif + +#ifndef traceRETURN_vTaskSwitchContext + #define traceRETURN_vTaskSwitchContext() +#endif + +#ifndef traceENTER_vTaskPlaceOnEventList + #define traceENTER_vTaskPlaceOnEventList( pxEventList, xTicksToWait ) +#endif + +#ifndef traceRETURN_vTaskPlaceOnEventList + #define traceRETURN_vTaskPlaceOnEventList() +#endif + +#ifndef traceENTER_vTaskPlaceOnUnorderedEventList + #define traceENTER_vTaskPlaceOnUnorderedEventList( pxEventList, xItemValue, xTicksToWait ) +#endif + +#ifndef traceRETURN_vTaskPlaceOnUnorderedEventList + #define traceRETURN_vTaskPlaceOnUnorderedEventList() +#endif + +#ifndef traceENTER_vTaskPlaceOnEventListRestricted + #define traceENTER_vTaskPlaceOnEventListRestricted( pxEventList, xTicksToWait, xWaitIndefinitely ) +#endif + +#ifndef traceRETURN_vTaskPlaceOnEventListRestricted + #define traceRETURN_vTaskPlaceOnEventListRestricted() +#endif + +#ifndef traceENTER_xTaskRemoveFromEventList + #define traceENTER_xTaskRemoveFromEventList( pxEventList ) +#endif + +#ifndef traceRETURN_xTaskRemoveFromEventList + #define traceRETURN_xTaskRemoveFromEventList( xReturn ) +#endif + +#ifndef traceENTER_vTaskRemoveFromUnorderedEventList + #define traceENTER_vTaskRemoveFromUnorderedEventList( pxEventListItem, xItemValue ) +#endif + +#ifndef traceRETURN_vTaskRemoveFromUnorderedEventList + #define traceRETURN_vTaskRemoveFromUnorderedEventList() +#endif + +#ifndef traceENTER_vTaskSetTimeOutState + #define traceENTER_vTaskSetTimeOutState( pxTimeOut ) +#endif + +#ifndef traceRETURN_vTaskSetTimeOutState + #define traceRETURN_vTaskSetTimeOutState() +#endif + +#ifndef traceENTER_vTaskInternalSetTimeOutState + #define traceENTER_vTaskInternalSetTimeOutState( pxTimeOut ) +#endif + +#ifndef traceRETURN_vTaskInternalSetTimeOutState + #define traceRETURN_vTaskInternalSetTimeOutState() +#endif + +#ifndef traceENTER_xTaskCheckForTimeOut + #define traceENTER_xTaskCheckForTimeOut( pxTimeOut, pxTicksToWait ) +#endif + +#ifndef traceRETURN_xTaskCheckForTimeOut + #define traceRETURN_xTaskCheckForTimeOut( xReturn ) +#endif + +#ifndef traceENTER_vTaskMissedYield + #define traceENTER_vTaskMissedYield() +#endif + +#ifndef traceRETURN_vTaskMissedYield + #define traceRETURN_vTaskMissedYield() +#endif + +#ifndef traceENTER_uxTaskGetTaskNumber + #define traceENTER_uxTaskGetTaskNumber( xTask ) +#endif + +#ifndef traceRETURN_uxTaskGetTaskNumber + #define traceRETURN_uxTaskGetTaskNumber( uxReturn ) +#endif + +#ifndef traceENTER_vTaskSetTaskNumber + #define traceENTER_vTaskSetTaskNumber( xTask, uxHandle ) +#endif + +#ifndef traceRETURN_vTaskSetTaskNumber + #define traceRETURN_vTaskSetTaskNumber() +#endif + +#ifndef traceENTER_eTaskConfirmSleepModeStatus + #define traceENTER_eTaskConfirmSleepModeStatus() +#endif + +#ifndef traceRETURN_eTaskConfirmSleepModeStatus + #define traceRETURN_eTaskConfirmSleepModeStatus( eReturn ) +#endif + +#ifndef traceENTER_vTaskSetThreadLocalStoragePointer + #define traceENTER_vTaskSetThreadLocalStoragePointer( xTaskToSet, xIndex, pvValue ) +#endif + +#ifndef traceRETURN_vTaskSetThreadLocalStoragePointer + #define traceRETURN_vTaskSetThreadLocalStoragePointer() +#endif + +#ifndef traceENTER_pvTaskGetThreadLocalStoragePointer + #define traceENTER_pvTaskGetThreadLocalStoragePointer( xTaskToQuery, xIndex ) +#endif + +#ifndef traceRETURN_pvTaskGetThreadLocalStoragePointer + #define traceRETURN_pvTaskGetThreadLocalStoragePointer( pvReturn ) +#endif + +#ifndef traceENTER_vTaskAllocateMPURegions + #define traceENTER_vTaskAllocateMPURegions( xTaskToModify, pxRegions ) +#endif + +#ifndef traceRETURN_vTaskAllocateMPURegions + #define traceRETURN_vTaskAllocateMPURegions() +#endif + +#ifndef traceENTER_vTaskGetInfo + #define traceENTER_vTaskGetInfo( xTask, pxTaskStatus, xGetFreeStackSpace, eState ) +#endif + +#ifndef traceRETURN_vTaskGetInfo + #define traceRETURN_vTaskGetInfo() +#endif + +#ifndef traceENTER_uxTaskGetStackHighWaterMark2 + #define traceENTER_uxTaskGetStackHighWaterMark2( xTask ) +#endif + +#ifndef traceRETURN_uxTaskGetStackHighWaterMark2 + #define traceRETURN_uxTaskGetStackHighWaterMark2( uxReturn ) +#endif + +#ifndef traceENTER_uxTaskGetStackHighWaterMark + #define traceENTER_uxTaskGetStackHighWaterMark( xTask ) +#endif + +#ifndef traceRETURN_uxTaskGetStackHighWaterMark + #define traceRETURN_uxTaskGetStackHighWaterMark( uxReturn ) +#endif + +#ifndef traceENTER_xTaskGetCurrentTaskHandle + #define traceENTER_xTaskGetCurrentTaskHandle() +#endif + +#ifndef traceRETURN_xTaskGetCurrentTaskHandle + #define traceRETURN_xTaskGetCurrentTaskHandle( xReturn ) +#endif + +#ifndef traceENTER_xTaskGetCurrentTaskHandleForCore + #define traceENTER_xTaskGetCurrentTaskHandleForCore( xCoreID ) +#endif + +#ifndef traceRETURN_xTaskGetCurrentTaskHandleForCore + #define traceRETURN_xTaskGetCurrentTaskHandleForCore( xReturn ) +#endif + +#ifndef traceENTER_xTaskGetSchedulerState + #define traceENTER_xTaskGetSchedulerState() +#endif + +#ifndef traceRETURN_xTaskGetSchedulerState + #define traceRETURN_xTaskGetSchedulerState( xReturn ) +#endif + +#ifndef traceENTER_xTaskPriorityInherit + #define traceENTER_xTaskPriorityInherit( pxMutexHolder ) +#endif + +#ifndef traceRETURN_xTaskPriorityInherit + #define traceRETURN_xTaskPriorityInherit( xReturn ) +#endif + +#ifndef traceENTER_xTaskPriorityDisinherit + #define traceENTER_xTaskPriorityDisinherit( pxMutexHolder ) +#endif + +#ifndef traceRETURN_xTaskPriorityDisinherit + #define traceRETURN_xTaskPriorityDisinherit( xReturn ) +#endif + +#ifndef traceENTER_vTaskPriorityDisinheritAfterTimeout + #define traceENTER_vTaskPriorityDisinheritAfterTimeout( pxMutexHolder, uxHighestPriorityWaitingTask ) +#endif + +#ifndef traceRETURN_vTaskPriorityDisinheritAfterTimeout + #define traceRETURN_vTaskPriorityDisinheritAfterTimeout() +#endif + +#ifndef traceENTER_vTaskYieldWithinAPI + #define traceENTER_vTaskYieldWithinAPI() +#endif + +#ifndef traceRETURN_vTaskYieldWithinAPI + #define traceRETURN_vTaskYieldWithinAPI() +#endif + +#ifndef traceENTER_vTaskEnterCritical + #define traceENTER_vTaskEnterCritical() +#endif + +#ifndef traceRETURN_vTaskEnterCritical + #define traceRETURN_vTaskEnterCritical() +#endif + +#ifndef traceENTER_vTaskEnterCriticalFromISR + #define traceENTER_vTaskEnterCriticalFromISR() +#endif + +#ifndef traceRETURN_vTaskEnterCriticalFromISR + #define traceRETURN_vTaskEnterCriticalFromISR( uxSavedInterruptStatus ) +#endif + +#ifndef traceENTER_vTaskExitCritical + #define traceENTER_vTaskExitCritical() +#endif + +#ifndef traceRETURN_vTaskExitCritical + #define traceRETURN_vTaskExitCritical() +#endif + +#ifndef traceENTER_vTaskExitCriticalFromISR + #define traceENTER_vTaskExitCriticalFromISR( uxSavedInterruptStatus ) +#endif + +#ifndef traceRETURN_vTaskExitCriticalFromISR + #define traceRETURN_vTaskExitCriticalFromISR() +#endif + +#ifndef traceENTER_vTaskListTasks + #define traceENTER_vTaskListTasks( pcWriteBuffer, uxBufferLength ) +#endif + +#ifndef traceRETURN_vTaskListTasks + #define traceRETURN_vTaskListTasks() +#endif + +#ifndef traceENTER_vTaskGetRunTimeStatistics + #define traceENTER_vTaskGetRunTimeStatistics( pcWriteBuffer, uxBufferLength ) +#endif + +#ifndef traceRETURN_vTaskGetRunTimeStatistics + #define traceRETURN_vTaskGetRunTimeStatistics() +#endif + +#ifndef traceENTER_uxTaskResetEventItemValue + #define traceENTER_uxTaskResetEventItemValue() +#endif + +#ifndef traceRETURN_uxTaskResetEventItemValue + #define traceRETURN_uxTaskResetEventItemValue( uxReturn ) +#endif + +#ifndef traceENTER_pvTaskIncrementMutexHeldCount + #define traceENTER_pvTaskIncrementMutexHeldCount() +#endif + +#ifndef traceRETURN_pvTaskIncrementMutexHeldCount + #define traceRETURN_pvTaskIncrementMutexHeldCount( pxTCB ) +#endif + +#ifndef traceENTER_ulTaskGenericNotifyTake + #define traceENTER_ulTaskGenericNotifyTake( uxIndexToWaitOn, xClearCountOnExit, xTicksToWait ) +#endif + +#ifndef traceRETURN_ulTaskGenericNotifyTake + #define traceRETURN_ulTaskGenericNotifyTake( ulReturn ) +#endif + +#ifndef traceENTER_xTaskGenericNotifyWait + #define traceENTER_xTaskGenericNotifyWait( uxIndexToWaitOn, ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait ) +#endif + +#ifndef traceRETURN_xTaskGenericNotifyWait + #define traceRETURN_xTaskGenericNotifyWait( xReturn ) +#endif + +#ifndef traceENTER_xTaskGenericNotify + #define traceENTER_xTaskGenericNotify( xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotificationValue ) +#endif + +#ifndef traceRETURN_xTaskGenericNotify + #define traceRETURN_xTaskGenericNotify( xReturn ) +#endif + +#ifndef traceENTER_xTaskGenericNotifyFromISR + #define traceENTER_xTaskGenericNotifyFromISR( xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ) +#endif + +#ifndef traceRETURN_xTaskGenericNotifyFromISR + #define traceRETURN_xTaskGenericNotifyFromISR( xReturn ) +#endif + +#ifndef traceENTER_vTaskGenericNotifyGiveFromISR + #define traceENTER_vTaskGenericNotifyGiveFromISR( xTaskToNotify, uxIndexToNotify, pxHigherPriorityTaskWoken ) +#endif + +#ifndef traceRETURN_vTaskGenericNotifyGiveFromISR + #define traceRETURN_vTaskGenericNotifyGiveFromISR() +#endif + +#ifndef traceENTER_xTaskGenericNotifyStateClear + #define traceENTER_xTaskGenericNotifyStateClear( xTask, uxIndexToClear ) +#endif + +#ifndef traceRETURN_xTaskGenericNotifyStateClear + #define traceRETURN_xTaskGenericNotifyStateClear( xReturn ) +#endif + +#ifndef traceENTER_ulTaskGenericNotifyValueClear + #define traceENTER_ulTaskGenericNotifyValueClear( xTask, uxIndexToClear, ulBitsToClear ) +#endif + +#ifndef traceRETURN_ulTaskGenericNotifyValueClear + #define traceRETURN_ulTaskGenericNotifyValueClear( ulReturn ) +#endif + +#ifndef traceENTER_ulTaskGetRunTimeCounter + #define traceENTER_ulTaskGetRunTimeCounter( xTask ) +#endif + +#ifndef traceRETURN_ulTaskGetRunTimeCounter + #define traceRETURN_ulTaskGetRunTimeCounter( ulRunTimeCounter ) +#endif + +#ifndef traceENTER_ulTaskGetRunTimePercent + #define traceENTER_ulTaskGetRunTimePercent( xTask ) +#endif + +#ifndef traceRETURN_ulTaskGetRunTimePercent + #define traceRETURN_ulTaskGetRunTimePercent( ulReturn ) +#endif + +#ifndef traceENTER_ulTaskGetIdleRunTimeCounter + #define traceENTER_ulTaskGetIdleRunTimeCounter() +#endif + +#ifndef traceRETURN_ulTaskGetIdleRunTimeCounter + #define traceRETURN_ulTaskGetIdleRunTimeCounter( ulReturn ) +#endif + +#ifndef traceENTER_ulTaskGetIdleRunTimePercent + #define traceENTER_ulTaskGetIdleRunTimePercent() +#endif + +#ifndef traceRETURN_ulTaskGetIdleRunTimePercent + #define traceRETURN_ulTaskGetIdleRunTimePercent( ulReturn ) +#endif + +#ifndef traceENTER_xTaskGetMPUSettings + #define traceENTER_xTaskGetMPUSettings( xTask ) +#endif + +#ifndef traceRETURN_xTaskGetMPUSettings + #define traceRETURN_xTaskGetMPUSettings( xMPUSettings ) +#endif + +#ifndef traceENTER_xStreamBufferGenericCreate + #define traceENTER_xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, xStreamBufferType, pxSendCompletedCallback, pxReceiveCompletedCallback ) +#endif + +#ifndef traceRETURN_xStreamBufferGenericCreate + #define traceRETURN_xStreamBufferGenericCreate( pvAllocatedMemory ) +#endif + +#ifndef traceENTER_xStreamBufferGenericCreateStatic + #define traceENTER_xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, xStreamBufferType, pucStreamBufferStorageArea, pxStaticStreamBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback ) +#endif + +#ifndef traceRETURN_xStreamBufferGenericCreateStatic + #define traceRETURN_xStreamBufferGenericCreateStatic( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferGetStaticBuffers + #define traceENTER_xStreamBufferGetStaticBuffers( xStreamBuffer, ppucStreamBufferStorageArea, ppxStaticStreamBuffer ) +#endif + +#ifndef traceRETURN_xStreamBufferGetStaticBuffers + #define traceRETURN_xStreamBufferGetStaticBuffers( xReturn ) +#endif + +#ifndef traceENTER_vStreamBufferDelete + #define traceENTER_vStreamBufferDelete( xStreamBuffer ) +#endif + +#ifndef traceRETURN_vStreamBufferDelete + #define traceRETURN_vStreamBufferDelete() +#endif + +#ifndef traceENTER_xStreamBufferReset + #define traceENTER_xStreamBufferReset( xStreamBuffer ) +#endif + +#ifndef traceRETURN_xStreamBufferReset + #define traceRETURN_xStreamBufferReset( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferResetFromISR + #define traceENTER_xStreamBufferResetFromISR( xStreamBuffer ) +#endif + +#ifndef traceRETURN_xStreamBufferResetFromISR + #define traceRETURN_xStreamBufferResetFromISR( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferSetTriggerLevel + #define traceENTER_xStreamBufferSetTriggerLevel( xStreamBuffer, xTriggerLevel ) +#endif + +#ifndef traceRETURN_xStreamBufferSetTriggerLevel + #define traceRETURN_xStreamBufferSetTriggerLevel( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferSpacesAvailable + #define traceENTER_xStreamBufferSpacesAvailable( xStreamBuffer ) +#endif + +#ifndef traceRETURN_xStreamBufferSpacesAvailable + #define traceRETURN_xStreamBufferSpacesAvailable( xSpace ) +#endif + +#ifndef traceENTER_xStreamBufferBytesAvailable + #define traceENTER_xStreamBufferBytesAvailable( xStreamBuffer ) +#endif + +#ifndef traceRETURN_xStreamBufferBytesAvailable + #define traceRETURN_xStreamBufferBytesAvailable( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferSend + #define traceENTER_xStreamBufferSend( xStreamBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) +#endif + +#ifndef traceRETURN_xStreamBufferSend + #define traceRETURN_xStreamBufferSend( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferSendFromISR + #define traceENTER_xStreamBufferSendFromISR( xStreamBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) +#endif + +#ifndef traceRETURN_xStreamBufferSendFromISR + #define traceRETURN_xStreamBufferSendFromISR( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferReceive + #define traceENTER_xStreamBufferReceive( xStreamBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) +#endif + +#ifndef traceRETURN_xStreamBufferReceive + #define traceRETURN_xStreamBufferReceive( xReceivedLength ) +#endif + +#ifndef traceENTER_xStreamBufferNextMessageLengthBytes + #define traceENTER_xStreamBufferNextMessageLengthBytes( xStreamBuffer ) +#endif + +#ifndef traceRETURN_xStreamBufferNextMessageLengthBytes + #define traceRETURN_xStreamBufferNextMessageLengthBytes( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferReceiveFromISR + #define traceENTER_xStreamBufferReceiveFromISR( xStreamBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) +#endif + +#ifndef traceRETURN_xStreamBufferReceiveFromISR + #define traceRETURN_xStreamBufferReceiveFromISR( xReceivedLength ) +#endif + +#ifndef traceENTER_xStreamBufferIsEmpty + #define traceENTER_xStreamBufferIsEmpty( xStreamBuffer ) +#endif + +#ifndef traceRETURN_xStreamBufferIsEmpty + #define traceRETURN_xStreamBufferIsEmpty( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferIsFull + #define traceENTER_xStreamBufferIsFull( xStreamBuffer ) +#endif + +#ifndef traceRETURN_xStreamBufferIsFull + #define traceRETURN_xStreamBufferIsFull( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferSendCompletedFromISR + #define traceENTER_xStreamBufferSendCompletedFromISR( xStreamBuffer, pxHigherPriorityTaskWoken ) +#endif + +#ifndef traceRETURN_xStreamBufferSendCompletedFromISR + #define traceRETURN_xStreamBufferSendCompletedFromISR( xReturn ) +#endif + +#ifndef traceENTER_xStreamBufferReceiveCompletedFromISR + #define traceENTER_xStreamBufferReceiveCompletedFromISR( xStreamBuffer, pxHigherPriorityTaskWoken ) +#endif + +#ifndef traceRETURN_xStreamBufferReceiveCompletedFromISR + #define traceRETURN_xStreamBufferReceiveCompletedFromISR( xReturn ) +#endif + +#ifndef traceENTER_uxStreamBufferGetStreamBufferNotificationIndex + #define traceENTER_uxStreamBufferGetStreamBufferNotificationIndex( xStreamBuffer ) +#endif + +#ifndef traceRETURN_uxStreamBufferGetStreamBufferNotificationIndex + #define traceRETURN_uxStreamBufferGetStreamBufferNotificationIndex( uxNotificationIndex ) +#endif + +#ifndef traceENTER_vStreamBufferSetStreamBufferNotificationIndex + #define traceENTER_vStreamBufferSetStreamBufferNotificationIndex( xStreamBuffer, uxNotificationIndex ) +#endif + +#ifndef traceRETURN_vStreamBufferSetStreamBufferNotificationIndex + #define traceRETURN_vStreamBufferSetStreamBufferNotificationIndex() +#endif + +#ifndef traceENTER_uxStreamBufferGetStreamBufferNumber + #define traceENTER_uxStreamBufferGetStreamBufferNumber( xStreamBuffer ) +#endif + +#ifndef traceRETURN_uxStreamBufferGetStreamBufferNumber + #define traceRETURN_uxStreamBufferGetStreamBufferNumber( uxStreamBufferNumber ) +#endif + +#ifndef traceENTER_vStreamBufferSetStreamBufferNumber + #define traceENTER_vStreamBufferSetStreamBufferNumber( xStreamBuffer, uxStreamBufferNumber ) +#endif + +#ifndef traceRETURN_vStreamBufferSetStreamBufferNumber + #define traceRETURN_vStreamBufferSetStreamBufferNumber() +#endif + +#ifndef traceENTER_ucStreamBufferGetStreamBufferType + #define traceENTER_ucStreamBufferGetStreamBufferType( xStreamBuffer ) +#endif + +#ifndef traceRETURN_ucStreamBufferGetStreamBufferType + #define traceRETURN_ucStreamBufferGetStreamBufferType( ucStreamBufferType ) +#endif + +#ifndef traceENTER_vListInitialise + #define traceENTER_vListInitialise( pxList ) +#endif + +#ifndef traceRETURN_vListInitialise + #define traceRETURN_vListInitialise() +#endif + +#ifndef traceENTER_vListInitialiseItem + #define traceENTER_vListInitialiseItem( pxItem ) +#endif + +#ifndef traceRETURN_vListInitialiseItem + #define traceRETURN_vListInitialiseItem() +#endif + +#ifndef traceENTER_vListInsertEnd + #define traceENTER_vListInsertEnd( pxList, pxNewListItem ) +#endif + +#ifndef traceRETURN_vListInsertEnd + #define traceRETURN_vListInsertEnd() +#endif + +#ifndef traceENTER_vListInsert + #define traceENTER_vListInsert( pxList, pxNewListItem ) +#endif + +#ifndef traceRETURN_vListInsert + #define traceRETURN_vListInsert() +#endif + +#ifndef traceENTER_uxListRemove + #define traceENTER_uxListRemove( pxItemToRemove ) +#endif + +#ifndef traceRETURN_uxListRemove + #define traceRETURN_uxListRemove( uxNumberOfItems ) +#endif + +#ifndef traceENTER_xCoRoutineCreate + #define traceENTER_xCoRoutineCreate( pxCoRoutineCode, uxPriority, uxIndex ) +#endif + +#ifndef traceRETURN_xCoRoutineCreate + #define traceRETURN_xCoRoutineCreate( xReturn ) +#endif + +#ifndef traceENTER_vCoRoutineAddToDelayedList + #define traceENTER_vCoRoutineAddToDelayedList( xTicksToDelay, pxEventList ) +#endif + +#ifndef traceRETURN_vCoRoutineAddToDelayedList + #define traceRETURN_vCoRoutineAddToDelayedList() +#endif + +#ifndef traceENTER_vCoRoutineSchedule + #define traceENTER_vCoRoutineSchedule() +#endif + +#ifndef traceRETURN_vCoRoutineSchedule + #define traceRETURN_vCoRoutineSchedule() +#endif + +#ifndef traceENTER_xCoRoutineRemoveFromEventList + #define traceENTER_xCoRoutineRemoveFromEventList( pxEventList ) +#endif + +#ifndef traceRETURN_xCoRoutineRemoveFromEventList + #define traceRETURN_xCoRoutineRemoveFromEventList( xReturn ) +#endif + +#ifndef configGENERATE_RUN_TIME_STATS + #define configGENERATE_RUN_TIME_STATS 0 +#endif + +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + + #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS + #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. + #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ + + #ifndef portGET_RUN_TIME_COUNTER_VALUE + #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE + #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. + #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ + #endif /* portGET_RUN_TIME_COUNTER_VALUE */ + +#endif /* configGENERATE_RUN_TIME_STATS */ + +#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS + #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() +#endif + +#ifndef portPRIVILEGE_BIT + #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) +#endif + +#ifndef portYIELD_WITHIN_API + #define portYIELD_WITHIN_API portYIELD +#endif + +#ifndef portSUPPRESS_TICKS_AND_SLEEP + #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) +#endif + +#ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP + #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 +#endif + +#if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2 + #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 +#endif + +#ifndef configUSE_TICKLESS_IDLE + #define configUSE_TICKLESS_IDLE 0 +#endif + +#ifndef configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING + #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) +#endif + +#ifndef configPRE_SLEEP_PROCESSING + #define configPRE_SLEEP_PROCESSING( x ) +#endif + +#ifndef configPOST_SLEEP_PROCESSING + #define configPOST_SLEEP_PROCESSING( x ) +#endif + +#ifndef configUSE_QUEUE_SETS + #define configUSE_QUEUE_SETS 0 +#endif + +#ifndef portTASK_USES_FLOATING_POINT + #define portTASK_USES_FLOATING_POINT() +#endif + +#ifndef portALLOCATE_SECURE_CONTEXT + #define portALLOCATE_SECURE_CONTEXT( ulSecureStackSize ) +#endif + +#ifndef portDONT_DISCARD + #define portDONT_DISCARD +#endif + +#ifndef configUSE_TIME_SLICING + #define configUSE_TIME_SLICING 1 +#endif + +#ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS + #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 +#endif + +#ifndef configUSE_STATS_FORMATTING_FUNCTIONS + #define configUSE_STATS_FORMATTING_FUNCTIONS 0 +#endif + +#ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID + #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() +#endif + +#ifndef configUSE_TRACE_FACILITY + #define configUSE_TRACE_FACILITY 0 +#endif + +#ifndef mtCOVERAGE_TEST_MARKER + #define mtCOVERAGE_TEST_MARKER() +#endif + +#ifndef mtCOVERAGE_TEST_DELAY + #define mtCOVERAGE_TEST_DELAY() +#endif + +#ifndef portASSERT_IF_IN_ISR + #define portASSERT_IF_IN_ISR() +#endif + +#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION + #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 +#endif + +#ifndef configAPPLICATION_ALLOCATED_HEAP + #define configAPPLICATION_ALLOCATED_HEAP 0 +#endif + +#ifndef configENABLE_HEAP_PROTECTOR + #define configENABLE_HEAP_PROTECTOR 0 +#endif + +#ifndef configUSE_TASK_NOTIFICATIONS + #define configUSE_TASK_NOTIFICATIONS 1 +#endif + +#ifndef configTASK_NOTIFICATION_ARRAY_ENTRIES + #define configTASK_NOTIFICATION_ARRAY_ENTRIES 1 +#endif + +#if configTASK_NOTIFICATION_ARRAY_ENTRIES < 1 + #error configTASK_NOTIFICATION_ARRAY_ENTRIES must be at least 1 +#endif + +#ifndef configUSE_POSIX_ERRNO + #define configUSE_POSIX_ERRNO 0 +#endif + +#ifndef configUSE_SB_COMPLETED_CALLBACK + +/* By default per-instance callbacks are not enabled for stream buffer or message buffer. */ + #define configUSE_SB_COMPLETED_CALLBACK 0 +#endif + +#ifndef portTICK_TYPE_IS_ATOMIC + #define portTICK_TYPE_IS_ATOMIC 0 +#endif + +#ifndef configSUPPORT_STATIC_ALLOCATION + /* Defaults to 0 for backward compatibility. */ + #define configSUPPORT_STATIC_ALLOCATION 0 +#endif + +#ifndef configKERNEL_PROVIDED_STATIC_MEMORY + #define configKERNEL_PROVIDED_STATIC_MEMORY 0 +#endif + +#ifndef configSUPPORT_DYNAMIC_ALLOCATION + /* Defaults to 1 for backward compatibility. */ + #define configSUPPORT_DYNAMIC_ALLOCATION 1 +#endif + +#if ( ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION != 1 ) ) + #error configUSE_STATS_FORMATTING_FUNCTIONS cannot be used without dynamic allocation, but configSUPPORT_DYNAMIC_ALLOCATION is not set to 1. +#endif + +#if ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) + #if ( ( configUSE_TRACE_FACILITY != 1 ) && ( configGENERATE_RUN_TIME_STATS != 1 ) ) + #error configUSE_STATS_FORMATTING_FUNCTIONS is 1 but the functions it enables are not used because neither configUSE_TRACE_FACILITY or configGENERATE_RUN_TIME_STATS are 1. Set configUSE_STATS_FORMATTING_FUNCTIONS to 0 in FreeRTOSConfig.h. + #endif +#endif + +#ifndef configSTATS_BUFFER_MAX_LENGTH + #define configSTATS_BUFFER_MAX_LENGTH 0xFFFF +#endif + +#ifndef configSTACK_DEPTH_TYPE + +/* Defaults to StackType_t for backward compatibility, but can be overridden + * in FreeRTOSConfig.h if StackType_t is too restrictive. */ + #define configSTACK_DEPTH_TYPE StackType_t +#endif + +#ifndef configRUN_TIME_COUNTER_TYPE + +/* Defaults to uint32_t for backward compatibility, but can be overridden in + * FreeRTOSConfig.h if uint32_t is too restrictive. */ + + #define configRUN_TIME_COUNTER_TYPE uint32_t +#endif + +#ifndef configMESSAGE_BUFFER_LENGTH_TYPE + +/* Defaults to size_t for backward compatibility, but can be overridden + * in FreeRTOSConfig.h if lengths will always be less than the number of bytes + * in a size_t. */ + #define configMESSAGE_BUFFER_LENGTH_TYPE size_t +#endif + +/* Sanity check the configuration. */ +#if ( ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) ) + #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. +#endif + +#if ( ( configUSE_RECURSIVE_MUTEXES == 1 ) && ( configUSE_MUTEXES != 1 ) ) + #error configUSE_MUTEXES must be set to 1 to use recursive mutexes +#endif + +#if ( ( configRUN_MULTIPLE_PRIORITIES == 0 ) && ( configUSE_TASK_PREEMPTION_DISABLE != 0 ) ) + #error configRUN_MULTIPLE_PRIORITIES must be set to 1 to use task preemption disable +#endif + +#if ( ( configUSE_PREEMPTION == 0 ) && ( configUSE_TASK_PREEMPTION_DISABLE != 0 ) ) + #error configUSE_PREEMPTION must be set to 1 to use task preemption disable +#endif + +#if ( ( configNUMBER_OF_CORES == 1 ) && ( configUSE_TASK_PREEMPTION_DISABLE != 0 ) ) + #error configUSE_TASK_PREEMPTION_DISABLE is not supported in single core FreeRTOS +#endif + +#if ( ( configNUMBER_OF_CORES == 1 ) && ( configUSE_CORE_AFFINITY != 0 ) ) + #error configUSE_CORE_AFFINITY is not supported in single core FreeRTOS +#endif + +#if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_PORT_OPTIMISED_TASK_SELECTION != 0 ) ) + #error configUSE_PORT_OPTIMISED_TASK_SELECTION is not supported in SMP FreeRTOS +#endif + +#ifndef configINITIAL_TICK_COUNT + #define configINITIAL_TICK_COUNT 0 +#endif + +#if ( portTICK_TYPE_IS_ATOMIC == 0 ) + +/* Either variables of tick type cannot be read atomically, or + * portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when + * the tick count is returned to the standard critical section macros. */ + #define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) +#else + +/* The tick type can be read atomically, so critical sections used when the + * tick count is returned can be defined away. */ + #define portTICK_TYPE_ENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) ( x ) +#endif /* if ( portTICK_TYPE_IS_ATOMIC == 0 ) */ + +/* Definitions to allow backward compatibility with FreeRTOS versions prior to + * V8 if desired. */ +#ifndef configENABLE_BACKWARD_COMPATIBILITY + #define configENABLE_BACKWARD_COMPATIBILITY 1 +#endif + +#ifndef configPRINTF + +/* configPRINTF() was not defined, so define it away to nothing. To use + * configPRINTF() then define it as follows (where MyPrintFunction() is + * provided by the application writer): + * + * void MyPrintFunction(const char *pcFormat, ... ); + #define configPRINTF( X ) MyPrintFunction X + * + * Then call like a standard printf() function, but placing brackets around + * all parameters so they are passed as a single parameter. For example: + * configPRINTF( ("Value = %d", MyVariable) ); */ + #define configPRINTF( X ) +#endif + +#ifndef configMAX + +/* The application writer has not provided their own MAX macro, so define + * the following generic implementation. */ + #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) +#endif + +#ifndef configMIN + +/* The application writer has not provided their own MIN macro, so define + * the following generic implementation. */ + #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) +#endif + +#if configENABLE_BACKWARD_COMPATIBILITY == 1 + #define eTaskStateGet eTaskGetState + #define portTickType TickType_t + #define xTaskHandle TaskHandle_t + #define xQueueHandle QueueHandle_t + #define xSemaphoreHandle SemaphoreHandle_t + #define xQueueSetHandle QueueSetHandle_t + #define xQueueSetMemberHandle QueueSetMemberHandle_t + #define xTimeOutType TimeOut_t + #define xMemoryRegion MemoryRegion_t + #define xTaskParameters TaskParameters_t + #define xTaskStatusType TaskStatus_t + #define xTimerHandle TimerHandle_t + #define xCoRoutineHandle CoRoutineHandle_t + #define pdTASK_HOOK_CODE TaskHookFunction_t + #define portTICK_RATE_MS portTICK_PERIOD_MS + #define pcTaskGetTaskName pcTaskGetName + #define pcTimerGetTimerName pcTimerGetName + #define pcQueueGetQueueName pcQueueGetName + #define vTaskGetTaskInfo vTaskGetInfo + #define xTaskGetIdleRunTimeCounter ulTaskGetIdleRunTimeCounter + +/* Backward compatibility within the scheduler code only - these definitions + * are not really required but are included for completeness. */ + #define tmrTIMER_CALLBACK TimerCallbackFunction_t + #define pdTASK_CODE TaskFunction_t + #define xListItem ListItem_t + #define xList List_t + +/* For libraries that break the list data hiding, and access list structure + * members directly (which is not supposed to be done). */ + #define pxContainer pvContainer +#endif /* configENABLE_BACKWARD_COMPATIBILITY */ + +#if ( configUSE_ALTERNATIVE_API != 0 ) + #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 +#endif + +/* Set configUSE_TASK_FPU_SUPPORT to 0 to omit floating point support even + * if floating point hardware is otherwise supported by the FreeRTOS port in use. + * This constant is not supported by all FreeRTOS ports that include floating + * point support. */ +#ifndef configUSE_TASK_FPU_SUPPORT + #define configUSE_TASK_FPU_SUPPORT 1 +#endif + +/* Set configENABLE_MPU to 1 to enable MPU support and 0 to disable it. This is + * currently used in ARMv8M ports. */ +#ifndef configENABLE_MPU + #define configENABLE_MPU 0 +#endif + +/* Set configENABLE_FPU to 1 to enable FPU support and 0 to disable it. This is + * currently used in ARMv8M ports. */ +#ifndef configENABLE_FPU + #define configENABLE_FPU 1 +#endif + +/* Set configENABLE_MVE to 1 to enable MVE support and 0 to disable it. This is + * currently used in ARMv8M ports. */ +#ifndef configENABLE_MVE + #define configENABLE_MVE 0 +#endif + +/* Set configENABLE_TRUSTZONE to 1 enable TrustZone support and 0 to disable it. + * This is currently used in ARMv8M ports. */ +#ifndef configENABLE_TRUSTZONE + #define configENABLE_TRUSTZONE 1 +#endif + +/* Set configRUN_FREERTOS_SECURE_ONLY to 1 to run the FreeRTOS ARMv8M port on + * the Secure Side only. */ +#ifndef configRUN_FREERTOS_SECURE_ONLY + #define configRUN_FREERTOS_SECURE_ONLY 0 +#endif + +#ifndef configRUN_ADDITIONAL_TESTS + #define configRUN_ADDITIONAL_TESTS 0 +#endif + +/* The following config allows infinite loop control. For example, control the + * infinite loop in idle task function when performing unit tests. */ +#ifndef configCONTROL_INFINITE_LOOP + #define configCONTROL_INFINITE_LOOP() +#endif + +/* Sometimes the FreeRTOSConfig.h settings only allow a task to be created using + * dynamically allocated RAM, in which case when any task is deleted it is known + * that both the task's stack and TCB need to be freed. Sometimes the + * FreeRTOSConfig.h settings only allow a task to be created using statically + * allocated RAM, in which case when any task is deleted it is known that neither + * the task's stack or TCB should be freed. Sometimes the FreeRTOSConfig.h + * settings allow a task to be created using either statically or dynamically + * allocated RAM, in which case a member of the TCB is used to record whether the + * stack and/or TCB were allocated statically or dynamically, so when a task is + * deleted the RAM that was allocated dynamically is freed again and no attempt is + * made to free the RAM that was allocated statically. + * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE is only true if it is possible for a + * task to be created using either statically or dynamically allocated RAM. Note + * that if portUSING_MPU_WRAPPERS is 1 then a protected task can be created with + * a statically allocated stack and a dynamically allocated TCB. + * + * The following table lists various combinations of portUSING_MPU_WRAPPERS, + * configSUPPORT_DYNAMIC_ALLOCATION and configSUPPORT_STATIC_ALLOCATION and + * when it is possible to have both static and dynamic allocation: + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + * | MPU | Dynamic | Static | Available Functions | Possible Allocations | Both Dynamic and | Need Free | + * | | | | | | Static Possible | | + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + * | 0 | 0 | 1 | xTaskCreateStatic | TCB - Static, Stack - Static | No | No | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 0 | 1 | 0 | xTaskCreate | TCB - Dynamic, Stack - Dynamic | No | Yes | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 0 | 1 | 1 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateStatic | 2. TCB - Static, Stack - Static | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 0 | 1 | xTaskCreateStatic, | TCB - Static, Stack - Static | No | No | + * | | | | xTaskCreateRestrictedStatic | | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 1 | 0 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateRestricted | 2. TCB - Dynamic, Stack - Static | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 1 | 1 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateStatic, | 2. TCB - Dynamic, Stack - Static | | | + * | | | | xTaskCreateRestricted, | 3. TCB - Static, Stack - Static | | | + * | | | | xTaskCreateRestrictedStatic | | | | + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + */ +#define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE \ + ( ( ( portUSING_MPU_WRAPPERS == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) || \ + ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) ) + +/* + * In line with software engineering best practice, FreeRTOS implements a strict + * data hiding policy, so the real structures used by FreeRTOS to maintain the + * state of tasks, queues, semaphores, etc. are not accessible to the application + * code. However, if the application writer wants to statically allocate such + * an object then the size of the object needs to be known. Dummy structures + * that are guaranteed to have the same size and alignment requirements of the + * real objects are used for this purpose. The dummy list and list item + * structures below are used for inclusion in such a dummy structure. + */ +struct xSTATIC_LIST_ITEM +{ + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void * pvDummy3[ 4 ]; + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy4; + #endif +}; +typedef struct xSTATIC_LIST_ITEM StaticListItem_t; + +#if ( configUSE_MINI_LIST_ITEM == 1 ) + /* See the comments above the struct xSTATIC_LIST_ITEM definition. */ + struct xSTATIC_MINI_LIST_ITEM + { + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void * pvDummy3[ 2 ]; + }; + typedef struct xSTATIC_MINI_LIST_ITEM StaticMiniListItem_t; +#else /* if ( configUSE_MINI_LIST_ITEM == 1 ) */ + typedef struct xSTATIC_LIST_ITEM StaticMiniListItem_t; +#endif /* if ( configUSE_MINI_LIST_ITEM == 1 ) */ + +/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ +typedef struct xSTATIC_LIST +{ + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + UBaseType_t uxDummy2; + void * pvDummy3; + StaticMiniListItem_t xDummy4; + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy5; + #endif +} StaticList_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the Task structure used internally by + * FreeRTOS is not accessible to application code. However, if the application + * writer wants to statically allocate the memory required to create a task then + * the size of the task object needs to be known. The StaticTask_t structure + * below is provided for this purpose. Its sizes and alignment requirements are + * guaranteed to match those of the genuine structure, no matter which + * architecture is being used, and no matter how the values in FreeRTOSConfig.h + * are set. Its contents are somewhat obfuscated in the hope users will + * recognise that it would be unwise to make direct use of the structure members. + */ +typedef struct xSTATIC_TCB +{ + void * pxDummy1; + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xDummy2; + #endif + #if ( configUSE_CORE_AFFINITY == 1 ) && ( configNUMBER_OF_CORES > 1 ) + UBaseType_t uxDummy26; + #endif + StaticListItem_t xDummy3[ 2 ]; + UBaseType_t uxDummy5; + void * pxDummy6; + #if ( configNUMBER_OF_CORES > 1 ) + BaseType_t xDummy23; + UBaseType_t uxDummy24; + #endif + uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; + #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) + BaseType_t xDummy25; + #endif + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + void * pxDummy8; + #endif + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxDummy9; + #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy10[ 2 ]; + #endif + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxDummy12[ 2 ]; + #endif + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + void * pxDummy14; + #endif + #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void * pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + configRUN_TIME_COUNTER_TYPE ulDummy16; + #endif + #if ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) + configTLS_BLOCK_TYPE xDummy17; + #endif + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + uint32_t ulDummy18[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + uint8_t ucDummy19[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + #endif + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + uint8_t uxDummy20; + #endif + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDummy21; + #endif + #if ( configUSE_POSIX_ERRNO == 1 ) + int iDummy22; + #endif +} StaticTask_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the Queue structure used internally by + * FreeRTOS is not accessible to application code. However, if the application + * writer wants to statically allocate the memory required to create a queue + * then the size of the queue object needs to be known. The StaticQueue_t + * structure below is provided for this purpose. Its sizes and alignment + * requirements are guaranteed to match those of the genuine structure, no + * matter which architecture is being used, and no matter how the values in + * FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in the hope + * users will recognise that it would be unwise to make direct use of the + * structure members. + */ +typedef struct xSTATIC_QUEUE +{ + void * pvDummy1[ 3 ]; + + union + { + void * pvDummy2; + UBaseType_t uxDummy2; + } u; + + StaticList_t xDummy3[ 2 ]; + UBaseType_t uxDummy4[ 3 ]; + uint8_t ucDummy5[ 2 ]; + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy6; + #endif + + #if ( configUSE_QUEUE_SETS == 1 ) + void * pvDummy7; + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy8; + uint8_t ucDummy9; + #endif +} StaticQueue_t; +typedef StaticQueue_t StaticSemaphore_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the event group structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create an event group then the size of the event group object needs to be + * know. The StaticEventGroup_t structure below is provided for this purpose. + * Its sizes and alignment requirements are guaranteed to match those of the + * genuine structure, no matter which architecture is being used, and no matter + * how the values in FreeRTOSConfig.h are set. Its contents are somewhat + * obfuscated in the hope users will recognise that it would be unwise to make + * direct use of the structure members. + */ +typedef struct xSTATIC_EVENT_GROUP +{ + TickType_t xDummy1; + StaticList_t xDummy2; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy3; + #endif + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy4; + #endif +} StaticEventGroup_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the software timer structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create a software timer then the size of the queue object needs to be known. + * The StaticTimer_t structure below is provided for this purpose. Its sizes + * and alignment requirements are guaranteed to match those of the genuine + * structure, no matter which architecture is being used, and no matter how the + * values in FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in + * the hope users will recognise that it would be unwise to make direct use of + * the structure members. + */ +typedef struct xSTATIC_TIMER +{ + void * pvDummy1; + StaticListItem_t xDummy2; + TickType_t xDummy3; + void * pvDummy5; + TaskFunction_t pvDummy6; + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy7; + #endif + uint8_t ucDummy8; +} StaticTimer_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the stream buffer structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create a stream buffer then the size of the stream buffer object needs to be + * known. The StaticStreamBuffer_t structure below is provided for this + * purpose. Its size and alignment requirements are guaranteed to match those + * of the genuine structure, no matter which architecture is being used, and + * no matter how the values in FreeRTOSConfig.h are set. Its contents are + * somewhat obfuscated in the hope users will recognise that it would be unwise + * to make direct use of the structure members. + */ +typedef struct xSTATIC_STREAM_BUFFER +{ + size_t uxDummy1[ 4 ]; + void * pvDummy2[ 3 ]; + uint8_t ucDummy3; + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy4; + #endif + #if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + void * pvDummy5[ 2 ]; + #endif + UBaseType_t uxDummy6; +} StaticStreamBuffer_t; + +/* Message buffers are built on stream buffers. */ +typedef StaticStreamBuffer_t StaticMessageBuffer_t; + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* INC_FREERTOS_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/StackMacros.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/StackMacros.h index 0b7e99d48..f47b1c420 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/StackMacros.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/StackMacros.h @@ -1,32 +1,34 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - - -#ifndef _MSC_VER /* Visual Studio doesn't support #warning. */ - #warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in future released. -#endif - -#include "stack_macros.h" +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#ifndef _MSC_VER /* Visual Studio doesn't support #warning. */ + #warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in a future release. +#endif + +#include "stack_macros.h" diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/atomic.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/atomic.h index 093530739..c2480d19f 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/atomic.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/atomic.h @@ -1,417 +1,427 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -/** - * @file atomic.h - * @brief FreeRTOS atomic operation support. - * - * This file implements atomic functions by disabling interrupts globally. - * Implementations with architecture specific atomic instructions can be - * provided under each compiler directory. - */ - -#ifndef ATOMIC_H -#define ATOMIC_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include atomic.h" -#endif - -/* Standard includes. */ -#include - -/* *INDENT-OFF* */ -#ifdef __cplusplus - extern "C" { -#endif -/* *INDENT-ON* */ - -/* - * Port specific definitions -- entering/exiting critical section. - * Refer template -- ./lib/FreeRTOS/portable/Compiler/Arch/portmacro.h - * - * Every call to ATOMIC_EXIT_CRITICAL() must be closely paired with - * ATOMIC_ENTER_CRITICAL(). - * - */ -#if defined( portSET_INTERRUPT_MASK_FROM_ISR ) - -/* Nested interrupt scheme is supported in this port. */ - #define ATOMIC_ENTER_CRITICAL() \ - UBaseType_t uxCriticalSectionType = portSET_INTERRUPT_MASK_FROM_ISR() - - #define ATOMIC_EXIT_CRITICAL() \ - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxCriticalSectionType ) - -#else - -/* Nested interrupt scheme is NOT supported in this port. */ - #define ATOMIC_ENTER_CRITICAL() portENTER_CRITICAL() - #define ATOMIC_EXIT_CRITICAL() portEXIT_CRITICAL() - -#endif /* portSET_INTERRUPT_MASK_FROM_ISR() */ - -/* - * Port specific definition -- "always inline". - * Inline is compiler specific, and may not always get inlined depending on your - * optimization level. Also, inline is considered as performance optimization - * for atomic. Thus, if portFORCE_INLINE is not provided by portmacro.h, - * instead of resulting error, simply define it away. - */ -#ifndef portFORCE_INLINE - #define portFORCE_INLINE -#endif - -#define ATOMIC_COMPARE_AND_SWAP_SUCCESS 0x1U /**< Compare and swap succeeded, swapped. */ -#define ATOMIC_COMPARE_AND_SWAP_FAILURE 0x0U /**< Compare and swap failed, did not swap. */ - -/*----------------------------- Swap && CAS ------------------------------*/ - -/** - * Atomic compare-and-swap - * - * @brief Performs an atomic compare-and-swap operation on the specified values. - * - * @param[in, out] pulDestination Pointer to memory location from where value is - * to be loaded and checked. - * @param[in] ulExchange If condition meets, write this value to memory. - * @param[in] ulComparand Swap condition. - * - * @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped. - * - * @note This function only swaps *pulDestination with ulExchange, if previous - * *pulDestination value equals ulComparand. - */ -static portFORCE_INLINE uint32_t Atomic_CompareAndSwap_u32( uint32_t volatile * pulDestination, - uint32_t ulExchange, - uint32_t ulComparand ) -{ - uint32_t ulReturnValue; - - ATOMIC_ENTER_CRITICAL(); - { - if( *pulDestination == ulComparand ) - { - *pulDestination = ulExchange; - ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS; - } - else - { - ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE; - } - } - ATOMIC_EXIT_CRITICAL(); - - return ulReturnValue; -} -/*-----------------------------------------------------------*/ - -/** - * Atomic swap (pointers) - * - * @brief Atomically sets the address pointed to by *ppvDestination to the value - * of *pvExchange. - * - * @param[in, out] ppvDestination Pointer to memory location from where a pointer - * value is to be loaded and written back to. - * @param[in] pvExchange Pointer value to be written to *ppvDestination. - * - * @return The initial value of *ppvDestination. - */ -static portFORCE_INLINE void * Atomic_SwapPointers_p32( void * volatile * ppvDestination, - void * pvExchange ) -{ - void * pReturnValue; - - ATOMIC_ENTER_CRITICAL(); - { - pReturnValue = *ppvDestination; - *ppvDestination = pvExchange; - } - ATOMIC_EXIT_CRITICAL(); - - return pReturnValue; -} -/*-----------------------------------------------------------*/ - -/** - * Atomic compare-and-swap (pointers) - * - * @brief Performs an atomic compare-and-swap operation on the specified pointer - * values. - * - * @param[in, out] ppvDestination Pointer to memory location from where a pointer - * value is to be loaded and checked. - * @param[in] pvExchange If condition meets, write this value to memory. - * @param[in] pvComparand Swap condition. - * - * @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped. - * - * @note This function only swaps *ppvDestination with pvExchange, if previous - * *ppvDestination value equals pvComparand. - */ -static portFORCE_INLINE uint32_t Atomic_CompareAndSwapPointers_p32( void * volatile * ppvDestination, - void * pvExchange, - void * pvComparand ) -{ - uint32_t ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE; - - ATOMIC_ENTER_CRITICAL(); - { - if( *ppvDestination == pvComparand ) - { - *ppvDestination = pvExchange; - ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS; - } - } - ATOMIC_EXIT_CRITICAL(); - - return ulReturnValue; -} - - -/*----------------------------- Arithmetic ------------------------------*/ - -/** - * Atomic add - * - * @brief Atomically adds count to the value of the specified pointer points to. - * - * @param[in,out] pulAddend Pointer to memory location from where value is to be - * loaded and written back to. - * @param[in] ulCount Value to be added to *pulAddend. - * - * @return previous *pulAddend value. - */ -static portFORCE_INLINE uint32_t Atomic_Add_u32( uint32_t volatile * pulAddend, - uint32_t ulCount ) -{ - uint32_t ulCurrent; - - ATOMIC_ENTER_CRITICAL(); - { - ulCurrent = *pulAddend; - *pulAddend += ulCount; - } - ATOMIC_EXIT_CRITICAL(); - - return ulCurrent; -} -/*-----------------------------------------------------------*/ - -/** - * Atomic subtract - * - * @brief Atomically subtracts count from the value of the specified pointer - * pointers to. - * - * @param[in,out] pulAddend Pointer to memory location from where value is to be - * loaded and written back to. - * @param[in] ulCount Value to be subtract from *pulAddend. - * - * @return previous *pulAddend value. - */ -static portFORCE_INLINE uint32_t Atomic_Subtract_u32( uint32_t volatile * pulAddend, - uint32_t ulCount ) -{ - uint32_t ulCurrent; - - ATOMIC_ENTER_CRITICAL(); - { - ulCurrent = *pulAddend; - *pulAddend -= ulCount; - } - ATOMIC_EXIT_CRITICAL(); - - return ulCurrent; -} -/*-----------------------------------------------------------*/ - -/** - * Atomic increment - * - * @brief Atomically increments the value of the specified pointer points to. - * - * @param[in,out] pulAddend Pointer to memory location from where value is to be - * loaded and written back to. - * - * @return *pulAddend value before increment. - */ -static portFORCE_INLINE uint32_t Atomic_Increment_u32( uint32_t volatile * pulAddend ) -{ - uint32_t ulCurrent; - - ATOMIC_ENTER_CRITICAL(); - { - ulCurrent = *pulAddend; - *pulAddend += 1; - } - ATOMIC_EXIT_CRITICAL(); - - return ulCurrent; -} -/*-----------------------------------------------------------*/ - -/** - * Atomic decrement - * - * @brief Atomically decrements the value of the specified pointer points to - * - * @param[in,out] pulAddend Pointer to memory location from where value is to be - * loaded and written back to. - * - * @return *pulAddend value before decrement. - */ -static portFORCE_INLINE uint32_t Atomic_Decrement_u32( uint32_t volatile * pulAddend ) -{ - uint32_t ulCurrent; - - ATOMIC_ENTER_CRITICAL(); - { - ulCurrent = *pulAddend; - *pulAddend -= 1; - } - ATOMIC_EXIT_CRITICAL(); - - return ulCurrent; -} - -/*----------------------------- Bitwise Logical ------------------------------*/ - -/** - * Atomic OR - * - * @brief Performs an atomic OR operation on the specified values. - * - * @param [in, out] pulDestination Pointer to memory location from where value is - * to be loaded and written back to. - * @param [in] ulValue Value to be ORed with *pulDestination. - * - * @return The original value of *pulDestination. - */ -static portFORCE_INLINE uint32_t Atomic_OR_u32( uint32_t volatile * pulDestination, - uint32_t ulValue ) -{ - uint32_t ulCurrent; - - ATOMIC_ENTER_CRITICAL(); - { - ulCurrent = *pulDestination; - *pulDestination |= ulValue; - } - ATOMIC_EXIT_CRITICAL(); - - return ulCurrent; -} -/*-----------------------------------------------------------*/ - -/** - * Atomic AND - * - * @brief Performs an atomic AND operation on the specified values. - * - * @param [in, out] pulDestination Pointer to memory location from where value is - * to be loaded and written back to. - * @param [in] ulValue Value to be ANDed with *pulDestination. - * - * @return The original value of *pulDestination. - */ -static portFORCE_INLINE uint32_t Atomic_AND_u32( uint32_t volatile * pulDestination, - uint32_t ulValue ) -{ - uint32_t ulCurrent; - - ATOMIC_ENTER_CRITICAL(); - { - ulCurrent = *pulDestination; - *pulDestination &= ulValue; - } - ATOMIC_EXIT_CRITICAL(); - - return ulCurrent; -} -/*-----------------------------------------------------------*/ - -/** - * Atomic NAND - * - * @brief Performs an atomic NAND operation on the specified values. - * - * @param [in, out] pulDestination Pointer to memory location from where value is - * to be loaded and written back to. - * @param [in] ulValue Value to be NANDed with *pulDestination. - * - * @return The original value of *pulDestination. - */ -static portFORCE_INLINE uint32_t Atomic_NAND_u32( uint32_t volatile * pulDestination, - uint32_t ulValue ) -{ - uint32_t ulCurrent; - - ATOMIC_ENTER_CRITICAL(); - { - ulCurrent = *pulDestination; - *pulDestination = ~( ulCurrent & ulValue ); - } - ATOMIC_EXIT_CRITICAL(); - - return ulCurrent; -} -/*-----------------------------------------------------------*/ - -/** - * Atomic XOR - * - * @brief Performs an atomic XOR operation on the specified values. - * - * @param [in, out] pulDestination Pointer to memory location from where value is - * to be loaded and written back to. - * @param [in] ulValue Value to be XORed with *pulDestination. - * - * @return The original value of *pulDestination. - */ -static portFORCE_INLINE uint32_t Atomic_XOR_u32( uint32_t volatile * pulDestination, - uint32_t ulValue ) -{ - uint32_t ulCurrent; - - ATOMIC_ENTER_CRITICAL(); - { - ulCurrent = *pulDestination; - *pulDestination ^= ulValue; - } - ATOMIC_EXIT_CRITICAL(); - - return ulCurrent; -} - -/* *INDENT-OFF* */ -#ifdef __cplusplus - } -#endif -/* *INDENT-ON* */ - -#endif /* ATOMIC_H */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/** + * @file atomic.h + * @brief FreeRTOS atomic operation support. + * + * This file implements atomic functions by disabling interrupts globally. + * Implementations with architecture specific atomic instructions can be + * provided under each compiler directory. + * + * The atomic interface can be used in FreeRTOS tasks on all FreeRTOS ports. It + * can also be used in Interrupt Service Routines (ISRs) on FreeRTOS ports that + * support nested interrupts (i.e. portHAS_NESTED_INTERRUPTS is set to 1). The + * atomic interface must not be used in ISRs on FreeRTOS ports that do not + * support nested interrupts (i.e. portHAS_NESTED_INTERRUPTS is set to 0) + * because ISRs on these ports cannot be interrupted and therefore, do not need + * atomics in ISRs. + */ + +#ifndef ATOMIC_H +#define ATOMIC_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include atomic.h" +#endif + +/* Standard includes. */ +#include + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* + * Port specific definitions -- entering/exiting critical section. + * Refer template -- ./lib/FreeRTOS/portable/Compiler/Arch/portmacro.h + * + * Every call to ATOMIC_EXIT_CRITICAL() must be closely paired with + * ATOMIC_ENTER_CRITICAL(). + * + */ +#if ( portHAS_NESTED_INTERRUPTS == 1 ) + +/* Nested interrupt scheme is supported in this port. */ + #define ATOMIC_ENTER_CRITICAL() \ + UBaseType_t uxCriticalSectionType = portSET_INTERRUPT_MASK_FROM_ISR() + + #define ATOMIC_EXIT_CRITICAL() \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxCriticalSectionType ) + +#else + +/* Nested interrupt scheme is NOT supported in this port. */ + #define ATOMIC_ENTER_CRITICAL() portENTER_CRITICAL() + #define ATOMIC_EXIT_CRITICAL() portEXIT_CRITICAL() + +#endif /* portSET_INTERRUPT_MASK_FROM_ISR() */ + +/* + * Port specific definition -- "always inline". + * Inline is compiler specific, and may not always get inlined depending on your + * optimization level. Also, inline is considered as performance optimization + * for atomic. Thus, if portFORCE_INLINE is not provided by portmacro.h, + * instead of resulting error, simply define it away. + */ +#ifndef portFORCE_INLINE + #define portFORCE_INLINE +#endif + +#define ATOMIC_COMPARE_AND_SWAP_SUCCESS 0x1U /**< Compare and swap succeeded, swapped. */ +#define ATOMIC_COMPARE_AND_SWAP_FAILURE 0x0U /**< Compare and swap failed, did not swap. */ + +/*----------------------------- Swap && CAS ------------------------------*/ + +/** + * Atomic compare-and-swap + * + * @brief Performs an atomic compare-and-swap operation on the specified values. + * + * @param[in, out] pulDestination Pointer to memory location from where value is + * to be loaded and checked. + * @param[in] ulExchange If condition meets, write this value to memory. + * @param[in] ulComparand Swap condition. + * + * @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped. + * + * @note This function only swaps *pulDestination with ulExchange, if previous + * *pulDestination value equals ulComparand. + */ +static portFORCE_INLINE uint32_t Atomic_CompareAndSwap_u32( uint32_t volatile * pulDestination, + uint32_t ulExchange, + uint32_t ulComparand ) +{ + uint32_t ulReturnValue; + + ATOMIC_ENTER_CRITICAL(); + { + if( *pulDestination == ulComparand ) + { + *pulDestination = ulExchange; + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS; + } + else + { + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE; + } + } + ATOMIC_EXIT_CRITICAL(); + + return ulReturnValue; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic swap (pointers) + * + * @brief Atomically sets the address pointed to by *ppvDestination to the value + * of *pvExchange. + * + * @param[in, out] ppvDestination Pointer to memory location from where a pointer + * value is to be loaded and written back to. + * @param[in] pvExchange Pointer value to be written to *ppvDestination. + * + * @return The initial value of *ppvDestination. + */ +static portFORCE_INLINE void * Atomic_SwapPointers_p32( void * volatile * ppvDestination, + void * pvExchange ) +{ + void * pReturnValue; + + ATOMIC_ENTER_CRITICAL(); + { + pReturnValue = *ppvDestination; + *ppvDestination = pvExchange; + } + ATOMIC_EXIT_CRITICAL(); + + return pReturnValue; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic compare-and-swap (pointers) + * + * @brief Performs an atomic compare-and-swap operation on the specified pointer + * values. + * + * @param[in, out] ppvDestination Pointer to memory location from where a pointer + * value is to be loaded and checked. + * @param[in] pvExchange If condition meets, write this value to memory. + * @param[in] pvComparand Swap condition. + * + * @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped. + * + * @note This function only swaps *ppvDestination with pvExchange, if previous + * *ppvDestination value equals pvComparand. + */ +static portFORCE_INLINE uint32_t Atomic_CompareAndSwapPointers_p32( void * volatile * ppvDestination, + void * pvExchange, + void * pvComparand ) +{ + uint32_t ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE; + + ATOMIC_ENTER_CRITICAL(); + { + if( *ppvDestination == pvComparand ) + { + *ppvDestination = pvExchange; + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS; + } + } + ATOMIC_EXIT_CRITICAL(); + + return ulReturnValue; +} + + +/*----------------------------- Arithmetic ------------------------------*/ + +/** + * Atomic add + * + * @brief Atomically adds count to the value of the specified pointer points to. + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * @param[in] ulCount Value to be added to *pulAddend. + * + * @return previous *pulAddend value. + */ +static portFORCE_INLINE uint32_t Atomic_Add_u32( uint32_t volatile * pulAddend, + uint32_t ulCount ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend += ulCount; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic subtract + * + * @brief Atomically subtracts count from the value of the specified pointer + * pointers to. + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * @param[in] ulCount Value to be subtract from *pulAddend. + * + * @return previous *pulAddend value. + */ +static portFORCE_INLINE uint32_t Atomic_Subtract_u32( uint32_t volatile * pulAddend, + uint32_t ulCount ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend -= ulCount; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic increment + * + * @brief Atomically increments the value of the specified pointer points to. + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * + * @return *pulAddend value before increment. + */ +static portFORCE_INLINE uint32_t Atomic_Increment_u32( uint32_t volatile * pulAddend ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend += 1; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic decrement + * + * @brief Atomically decrements the value of the specified pointer points to + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * + * @return *pulAddend value before decrement. + */ +static portFORCE_INLINE uint32_t Atomic_Decrement_u32( uint32_t volatile * pulAddend ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend -= 1; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/*----------------------------- Bitwise Logical ------------------------------*/ + +/** + * Atomic OR + * + * @brief Performs an atomic OR operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be ORed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_OR_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination |= ulValue; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic AND + * + * @brief Performs an atomic AND operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be ANDed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_AND_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination &= ulValue; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic NAND + * + * @brief Performs an atomic NAND operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be NANDed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_NAND_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination = ~( ulCurrent & ulValue ); + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic XOR + * + * @brief Performs an atomic XOR operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be XORed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_XOR_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination ^= ulValue; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* ATOMIC_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/croutine.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/croutine.h index bf51e6f50..6cbb743c5 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/croutine.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/croutine.h @@ -1,751 +1,762 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -#ifndef CO_ROUTINE_H -#define CO_ROUTINE_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include croutine.h" -#endif - -#include "list.h" - -/* *INDENT-OFF* */ -#ifdef __cplusplus - extern "C" { -#endif -/* *INDENT-ON* */ - -/* Used to hide the implementation of the co-routine control block. The - * control block structure however has to be included in the header due to - * the macro implementation of the co-routine functionality. */ -typedef void * CoRoutineHandle_t; - -/* Defines the prototype to which co-routine functions must conform. */ -typedef void (* crCOROUTINE_CODE)( CoRoutineHandle_t, - UBaseType_t ); - -typedef struct corCoRoutineControlBlock -{ - crCOROUTINE_CODE pxCoRoutineFunction; - ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */ - ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */ - UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */ - UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */ - uint16_t uxState; /*< Used internally by the co-routine implementation. */ -} CRCB_t; /* Co-routine control block. Note must be identical in size down to uxPriority with TCB_t. */ - -/** - * croutine. h - *
- * BaseType_t xCoRoutineCreate(
- *                               crCOROUTINE_CODE pxCoRoutineCode,
- *                               UBaseType_t uxPriority,
- *                               UBaseType_t uxIndex
- *                             ); 
- * 
- * - * Create a new co-routine and add it to the list of co-routines that are - * ready to run. - * - * @param pxCoRoutineCode Pointer to the co-routine function. Co-routine - * functions require special syntax - see the co-routine section of the WEB - * documentation for more information. - * - * @param uxPriority The priority with respect to other co-routines at which - * the co-routine will run. - * - * @param uxIndex Used to distinguish between different co-routines that - * execute the same function. See the example below and the co-routine section - * of the WEB documentation for further information. - * - * @return pdPASS if the co-routine was successfully created and added to a ready - * list, otherwise an error code defined with ProjDefs.h. - * - * Example usage: - *
- * // Co-routine to be created.
- * void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- * {
- * // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- * // This may not be necessary for const variables.
- * static const char cLedToFlash[ 2 ] = { 5, 6 };
- * static const TickType_t uxFlashRates[ 2 ] = { 200, 400 };
- *
- *   // Must start every co-routine with a call to crSTART();
- *   crSTART( xHandle );
- *
- *   for( ;; )
- *   {
- *       // This co-routine just delays for a fixed period, then toggles
- *       // an LED.  Two co-routines are created using this function, so
- *       // the uxIndex parameter is used to tell the co-routine which
- *       // LED to flash and how int32_t to delay.  This assumes xQueue has
- *       // already been created.
- *       vParTestToggleLED( cLedToFlash[ uxIndex ] );
- *       crDELAY( xHandle, uxFlashRates[ uxIndex ] );
- *   }
- *
- *   // Must end every co-routine with a call to crEND();
- *   crEND();
- * }
- *
- * // Function that creates two co-routines.
- * void vOtherFunction( void )
- * {
- * uint8_t ucParameterToPass;
- * TaskHandle_t xHandle;
- *
- *   // Create two co-routines at priority 0.  The first is given index 0
- *   // so (from the code above) toggles LED 5 every 200 ticks.  The second
- *   // is given index 1 so toggles LED 6 every 400 ticks.
- *   for( uxIndex = 0; uxIndex < 2; uxIndex++ )
- *   {
- *       xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex );
- *   }
- * }
- * 
- * \defgroup xCoRoutineCreate xCoRoutineCreate - * \ingroup Tasks - */ -BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, - UBaseType_t uxPriority, - UBaseType_t uxIndex ); - - -/** - * croutine. h - *
- * void vCoRoutineSchedule( void );
- * 
- * - * Run a co-routine. - * - * vCoRoutineSchedule() executes the highest priority co-routine that is able - * to run. The co-routine will execute until it either blocks, yields or is - * preempted by a task. Co-routines execute cooperatively so one - * co-routine cannot be preempted by another, but can be preempted by a task. - * - * If an application comprises of both tasks and co-routines then - * vCoRoutineSchedule should be called from the idle task (in an idle task - * hook). - * - * Example usage: - *
- * // This idle task hook will schedule a co-routine each time it is called.
- * // The rest of the idle task will execute between co-routine calls.
- * void vApplicationIdleHook( void )
- * {
- *  vCoRoutineSchedule();
- * }
- *
- * // Alternatively, if you do not require any other part of the idle task to
- * // execute, the idle task hook can call vCoRoutineSchedule() within an
- * // infinite loop.
- * void vApplicationIdleHook( void )
- * {
- *  for( ;; )
- *  {
- *      vCoRoutineSchedule();
- *  }
- * }
- * 
- * \defgroup vCoRoutineSchedule vCoRoutineSchedule - * \ingroup Tasks - */ -void vCoRoutineSchedule( void ); - -/** - * croutine. h - *
- * crSTART( CoRoutineHandle_t xHandle );
- * 
- * - * This macro MUST always be called at the start of a co-routine function. - * - * Example usage: - *
- * // Co-routine to be created.
- * void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- * {
- * // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- * static int32_t ulAVariable;
- *
- *   // Must start every co-routine with a call to crSTART();
- *   crSTART( xHandle );
- *
- *   for( ;; )
- *   {
- *        // Co-routine functionality goes here.
- *   }
- *
- *   // Must end every co-routine with a call to crEND();
- *   crEND();
- * }
- * 
- * \defgroup crSTART crSTART - * \ingroup Tasks - */ -#define crSTART( pxCRCB ) \ - switch( ( ( CRCB_t * ) ( pxCRCB ) )->uxState ) { \ - case 0: - -/** - * croutine. h - *
- * crEND();
- * 
- * - * This macro MUST always be called at the end of a co-routine function. - * - * Example usage: - *
- * // Co-routine to be created.
- * void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- * {
- * // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- * static int32_t ulAVariable;
- *
- *   // Must start every co-routine with a call to crSTART();
- *   crSTART( xHandle );
- *
- *   for( ;; )
- *   {
- *        // Co-routine functionality goes here.
- *   }
- *
- *   // Must end every co-routine with a call to crEND();
- *   crEND();
- * }
- * 
- * \defgroup crSTART crSTART - * \ingroup Tasks - */ -#define crEND() } - -/* - * These macros are intended for internal use by the co-routine implementation - * only. The macros should not be used directly by application writers. - */ -#define crSET_STATE0( xHandle ) \ - ( ( CRCB_t * ) ( xHandle ) )->uxState = ( __LINE__ * 2 ); return; \ - case ( __LINE__ * 2 ): -#define crSET_STATE1( xHandle ) \ - ( ( CRCB_t * ) ( xHandle ) )->uxState = ( ( __LINE__ * 2 ) + 1 ); return; \ - case ( ( __LINE__ * 2 ) + 1 ): - -/** - * croutine. h - *
- * crDELAY( CoRoutineHandle_t xHandle, TickType_t xTicksToDelay );
- * 
- * - * Delay a co-routine for a fixed period of time. - * - * crDELAY can only be called from the co-routine function itself - not - * from within a function called by the co-routine function. This is because - * co-routines do not maintain their own stack. - * - * @param xHandle The handle of the co-routine to delay. This is the xHandle - * parameter of the co-routine function. - * - * @param xTickToDelay The number of ticks that the co-routine should delay - * for. The actual amount of time this equates to is defined by - * configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant portTICK_PERIOD_MS - * can be used to convert ticks to milliseconds. - * - * Example usage: - *
- * // Co-routine to be created.
- * void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- * {
- * // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- * // This may not be necessary for const variables.
- * // We are to delay for 200ms.
- * static const xTickType xDelayTime = 200 / portTICK_PERIOD_MS;
- *
- *   // Must start every co-routine with a call to crSTART();
- *   crSTART( xHandle );
- *
- *   for( ;; )
- *   {
- *      // Delay for 200ms.
- *      crDELAY( xHandle, xDelayTime );
- *
- *      // Do something here.
- *   }
- *
- *   // Must end every co-routine with a call to crEND();
- *   crEND();
- * }
- * 
- * \defgroup crDELAY crDELAY - * \ingroup Tasks - */ -#define crDELAY( xHandle, xTicksToDelay ) \ - if( ( xTicksToDelay ) > 0 ) \ - { \ - vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \ - } \ - crSET_STATE0( ( xHandle ) ); - -/** - *
- * crQUEUE_SEND(
- *                CoRoutineHandle_t xHandle,
- *                QueueHandle_t pxQueue,
- *                void *pvItemToQueue,
- *                TickType_t xTicksToWait,
- *                BaseType_t *pxResult
- *           )
- * 
- * - * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine - * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. - * - * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas - * xQueueSend() and xQueueReceive() can only be used from tasks. - * - * crQUEUE_SEND can only be called from the co-routine function itself - not - * from within a function called by the co-routine function. This is because - * co-routines do not maintain their own stack. - * - * See the co-routine section of the WEB documentation for information on - * passing data between tasks and co-routines and between ISR's and - * co-routines. - * - * @param xHandle The handle of the calling co-routine. This is the xHandle - * parameter of the co-routine function. - * - * @param pxQueue The handle of the queue on which the data will be posted. - * The handle is obtained as the return value when the queue is created using - * the xQueueCreate() API function. - * - * @param pvItemToQueue A pointer to the data being posted onto the queue. - * The number of bytes of each queued item is specified when the queue is - * created. This number of bytes is copied from pvItemToQueue into the queue - * itself. - * - * @param xTickToDelay The number of ticks that the co-routine should block - * to wait for space to become available on the queue, should space not be - * available immediately. The actual amount of time this equates to is defined - * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant - * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see example - * below). - * - * @param pxResult The variable pointed to by pxResult will be set to pdPASS if - * data was successfully posted onto the queue, otherwise it will be set to an - * error defined within ProjDefs.h. - * - * Example usage: - *
- * // Co-routine function that blocks for a fixed period then posts a number onto
- * // a queue.
- * static void prvCoRoutineFlashTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- * {
- * // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- * static BaseType_t xNumberToPost = 0;
- * static BaseType_t xResult;
- *
- *  // Co-routines must begin with a call to crSTART().
- *  crSTART( xHandle );
- *
- *  for( ;; )
- *  {
- *      // This assumes the queue has already been created.
- *      crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult );
- *
- *      if( xResult != pdPASS )
- *      {
- *          // The message was not posted!
- *      }
- *
- *      // Increment the number to be posted onto the queue.
- *      xNumberToPost++;
- *
- *      // Delay for 100 ticks.
- *      crDELAY( xHandle, 100 );
- *  }
- *
- *  // Co-routines must end with a call to crEND().
- *  crEND();
- * }
- * 
- * \defgroup crQUEUE_SEND crQUEUE_SEND - * \ingroup Tasks - */ -#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult ) \ - { \ - *( pxResult ) = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), ( xTicksToWait ) ); \ - if( *( pxResult ) == errQUEUE_BLOCKED ) \ - { \ - crSET_STATE0( ( xHandle ) ); \ - *pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 ); \ - } \ - if( *pxResult == errQUEUE_YIELD ) \ - { \ - crSET_STATE1( ( xHandle ) ); \ - *pxResult = pdPASS; \ - } \ - } - -/** - * croutine. h - *
- * crQUEUE_RECEIVE(
- *                   CoRoutineHandle_t xHandle,
- *                   QueueHandle_t pxQueue,
- *                   void *pvBuffer,
- *                   TickType_t xTicksToWait,
- *                   BaseType_t *pxResult
- *               )
- * 
- * - * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine - * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. - * - * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas - * xQueueSend() and xQueueReceive() can only be used from tasks. - * - * crQUEUE_RECEIVE can only be called from the co-routine function itself - not - * from within a function called by the co-routine function. This is because - * co-routines do not maintain their own stack. - * - * See the co-routine section of the WEB documentation for information on - * passing data between tasks and co-routines and between ISR's and - * co-routines. - * - * @param xHandle The handle of the calling co-routine. This is the xHandle - * parameter of the co-routine function. - * - * @param pxQueue The handle of the queue from which the data will be received. - * The handle is obtained as the return value when the queue is created using - * the xQueueCreate() API function. - * - * @param pvBuffer The buffer into which the received item is to be copied. - * The number of bytes of each queued item is specified when the queue is - * created. This number of bytes is copied into pvBuffer. - * - * @param xTickToDelay The number of ticks that the co-routine should block - * to wait for data to become available from the queue, should data not be - * available immediately. The actual amount of time this equates to is defined - * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant - * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see the - * crQUEUE_SEND example). - * - * @param pxResult The variable pointed to by pxResult will be set to pdPASS if - * data was successfully retrieved from the queue, otherwise it will be set to - * an error code as defined within ProjDefs.h. - * - * Example usage: - *
- * // A co-routine receives the number of an LED to flash from a queue.  It
- * // blocks on the queue until the number is received.
- * static void prvCoRoutineFlashWorkTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- * {
- * // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- * static BaseType_t xResult;
- * static UBaseType_t uxLEDToFlash;
- *
- *  // All co-routines must start with a call to crSTART().
- *  crSTART( xHandle );
- *
- *  for( ;; )
- *  {
- *      // Wait for data to become available on the queue.
- *      crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
- *
- *      if( xResult == pdPASS )
- *      {
- *          // We received the LED to flash - flash it!
- *          vParTestToggleLED( uxLEDToFlash );
- *      }
- *  }
- *
- *  crEND();
- * }
- * 
- * \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE - * \ingroup Tasks - */ -#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult ) \ - { \ - *( pxResult ) = xQueueCRReceive( ( pxQueue ), ( pvBuffer ), ( xTicksToWait ) ); \ - if( *( pxResult ) == errQUEUE_BLOCKED ) \ - { \ - crSET_STATE0( ( xHandle ) ); \ - *( pxResult ) = xQueueCRReceive( ( pxQueue ), ( pvBuffer ), 0 ); \ - } \ - if( *( pxResult ) == errQUEUE_YIELD ) \ - { \ - crSET_STATE1( ( xHandle ) ); \ - *( pxResult ) = pdPASS; \ - } \ - } - -/** - * croutine. h - *
- * crQUEUE_SEND_FROM_ISR(
- *                          QueueHandle_t pxQueue,
- *                          void *pvItemToQueue,
- *                          BaseType_t xCoRoutinePreviouslyWoken
- *                     )
- * 
- * - * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the - * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() - * functions used by tasks. - * - * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to - * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and - * xQueueReceiveFromISR() can only be used to pass data between a task and and - * ISR. - * - * crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue - * that is being used from within a co-routine. - * - * See the co-routine section of the WEB documentation for information on - * passing data between tasks and co-routines and between ISR's and - * co-routines. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param xCoRoutinePreviouslyWoken This is included so an ISR can post onto - * the same queue multiple times from a single interrupt. The first call - * should always pass in pdFALSE. Subsequent calls should pass in - * the value returned from the previous call. - * - * @return pdTRUE if a co-routine was woken by posting onto the queue. This is - * used by the ISR to determine if a context switch may be required following - * the ISR. - * - * Example usage: - *
- * // A co-routine that blocks on a queue waiting for characters to be received.
- * static void vReceivingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- * {
- * char cRxedChar;
- * BaseType_t xResult;
- *
- *   // All co-routines must start with a call to crSTART().
- *   crSTART( xHandle );
- *
- *   for( ;; )
- *   {
- *       // Wait for data to become available on the queue.  This assumes the
- *       // queue xCommsRxQueue has already been created!
- *       crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
- *
- *       // Was a character received?
- *       if( xResult == pdPASS )
- *       {
- *           // Process the character here.
- *       }
- *   }
- *
- *   // All co-routines must end with a call to crEND().
- *   crEND();
- * }
- *
- * // An ISR that uses a queue to send characters received on a serial port to
- * // a co-routine.
- * void vUART_ISR( void )
- * {
- * char cRxedChar;
- * BaseType_t xCRWokenByPost = pdFALSE;
- *
- *   // We loop around reading characters until there are none left in the UART.
- *   while( UART_RX_REG_NOT_EMPTY() )
- *   {
- *       // Obtain the character from the UART.
- *       cRxedChar = UART_RX_REG;
- *
- *       // Post the character onto a queue.  xCRWokenByPost will be pdFALSE
- *       // the first time around the loop.  If the post causes a co-routine
- *       // to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE.
- *       // In this manner we can ensure that if more than one co-routine is
- *       // blocked on the queue only one is woken by this ISR no matter how
- *       // many characters are posted to the queue.
- *       xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost );
- *   }
- * }
- * 
- * \defgroup crQUEUE_SEND_FROM_ISR crQUEUE_SEND_FROM_ISR - * \ingroup Tasks - */ -#define crQUEUE_SEND_FROM_ISR( pxQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) \ - xQueueCRSendFromISR( ( pxQueue ), ( pvItemToQueue ), ( xCoRoutinePreviouslyWoken ) ) - - -/** - * croutine. h - *
- * crQUEUE_SEND_FROM_ISR(
- *                          QueueHandle_t pxQueue,
- *                          void *pvBuffer,
- *                          BaseType_t * pxCoRoutineWoken
- *                     )
- * 
- * - * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the - * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() - * functions used by tasks. - * - * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to - * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and - * xQueueReceiveFromISR() can only be used to pass data between a task and and - * ISR. - * - * crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data - * from a queue that is being used from within a co-routine (a co-routine - * posted to the queue). - * - * See the co-routine section of the WEB documentation for information on - * passing data between tasks and co-routines and between ISR's and - * co-routines. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvBuffer A pointer to a buffer into which the received item will be - * placed. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from the queue into - * pvBuffer. - * - * @param pxCoRoutineWoken A co-routine may be blocked waiting for space to become - * available on the queue. If crQUEUE_RECEIVE_FROM_ISR causes such a - * co-routine to unblock *pxCoRoutineWoken will get set to pdTRUE, otherwise - * *pxCoRoutineWoken will remain unchanged. - * - * @return pdTRUE an item was successfully received from the queue, otherwise - * pdFALSE. - * - * Example usage: - *
- * // A co-routine that posts a character to a queue then blocks for a fixed
- * // period.  The character is incremented each time.
- * static void vSendingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- * {
- * // cChar holds its value while this co-routine is blocked and must therefore
- * // be declared static.
- * static char cCharToTx = 'a';
- * BaseType_t xResult;
- *
- *   // All co-routines must start with a call to crSTART().
- *   crSTART( xHandle );
- *
- *   for( ;; )
- *   {
- *       // Send the next character to the queue.
- *       crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult );
- *
- *       if( xResult == pdPASS )
- *       {
- *           // The character was successfully posted to the queue.
- *       }
- *       else
- *       {
- *          // Could not post the character to the queue.
- *       }
- *
- *       // Enable the UART Tx interrupt to cause an interrupt in this
- *       // hypothetical UART.  The interrupt will obtain the character
- *       // from the queue and send it.
- *       ENABLE_RX_INTERRUPT();
- *
- *       // Increment to the next character then block for a fixed period.
- *       // cCharToTx will maintain its value across the delay as it is
- *       // declared static.
- *       cCharToTx++;
- *       if( cCharToTx > 'x' )
- *       {
- *          cCharToTx = 'a';
- *       }
- *       crDELAY( 100 );
- *   }
- *
- *   // All co-routines must end with a call to crEND().
- *   crEND();
- * }
- *
- * // An ISR that uses a queue to receive characters to send on a UART.
- * void vUART_ISR( void )
- * {
- * char cCharToTx;
- * BaseType_t xCRWokenByPost = pdFALSE;
- *
- *   while( UART_TX_REG_EMPTY() )
- *   {
- *       // Are there any characters in the queue waiting to be sent?
- *       // xCRWokenByPost will automatically be set to pdTRUE if a co-routine
- *       // is woken by the post - ensuring that only a single co-routine is
- *       // woken no matter how many times we go around this loop.
- *       if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) )
- *       {
- *           SEND_CHARACTER( cCharToTx );
- *       }
- *   }
- * }
- * 
- * \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR - * \ingroup Tasks - */ -#define crQUEUE_RECEIVE_FROM_ISR( pxQueue, pvBuffer, pxCoRoutineWoken ) \ - xQueueCRReceiveFromISR( ( pxQueue ), ( pvBuffer ), ( pxCoRoutineWoken ) ) - -/* - * This function is intended for internal use by the co-routine macros only. - * The macro nature of the co-routine implementation requires that the - * prototype appears here. The function should not be used by application - * writers. - * - * Removes the current co-routine from its ready list and places it in the - * appropriate delayed list. - */ -void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, - List_t * pxEventList ); - -/* - * This function is intended for internal use by the queue implementation only. - * The function should not be used by application writers. - * - * Removes the highest priority co-routine from the event list and places it in - * the pending ready list. - */ -BaseType_t xCoRoutineRemoveFromEventList( const List_t * pxEventList ); - -/* *INDENT-OFF* */ -#ifdef __cplusplus - } -#endif -/* *INDENT-ON* */ - -#endif /* CO_ROUTINE_H */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef CO_ROUTINE_H +#define CO_ROUTINE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include croutine.h" +#endif + +#include "list.h" + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* Used to hide the implementation of the co-routine control block. The + * control block structure however has to be included in the header due to + * the macro implementation of the co-routine functionality. */ +typedef void * CoRoutineHandle_t; + +/* Defines the prototype to which co-routine functions must conform. */ +typedef void (* crCOROUTINE_CODE)( CoRoutineHandle_t xHandle, + UBaseType_t uxIndex ); + +typedef struct corCoRoutineControlBlock +{ + crCOROUTINE_CODE pxCoRoutineFunction; + ListItem_t xGenericListItem; /**< List item used to place the CRCB in ready and blocked queues. */ + ListItem_t xEventListItem; /**< List item used to place the CRCB in event lists. */ + UBaseType_t uxPriority; /**< The priority of the co-routine in relation to other co-routines. */ + UBaseType_t uxIndex; /**< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */ + uint16_t uxState; /**< Used internally by the co-routine implementation. */ +} CRCB_t; /* Co-routine control block. Note must be identical in size down to uxPriority with TCB_t. */ + +/** + * croutine. h + * @code{c} + * BaseType_t xCoRoutineCreate( + * crCOROUTINE_CODE pxCoRoutineCode, + * UBaseType_t uxPriority, + * UBaseType_t uxIndex + * ); + * @endcode + * + * Create a new co-routine and add it to the list of co-routines that are + * ready to run. + * + * @param pxCoRoutineCode Pointer to the co-routine function. Co-routine + * functions require special syntax - see the co-routine section of the WEB + * documentation for more information. + * + * @param uxPriority The priority with respect to other co-routines at which + * the co-routine will run. + * + * @param uxIndex Used to distinguish between different co-routines that + * execute the same function. See the example below and the co-routine section + * of the WEB documentation for further information. + * + * @return pdPASS if the co-routine was successfully created and added to a ready + * list, otherwise an error code defined with ProjDefs.h. + * + * Example usage: + * @code{c} + * // Co-routine to be created. + * void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * // This may not be necessary for const variables. + * static const char cLedToFlash[ 2 ] = { 5, 6 }; + * static const TickType_t uxFlashRates[ 2 ] = { 200, 400 }; + * + * // Must start every co-routine with a call to crSTART(); + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // This co-routine just delays for a fixed period, then toggles + * // an LED. Two co-routines are created using this function, so + * // the uxIndex parameter is used to tell the co-routine which + * // LED to flash and how int32_t to delay. This assumes xQueue has + * // already been created. + * vParTestToggleLED( cLedToFlash[ uxIndex ] ); + * crDELAY( xHandle, uxFlashRates[ uxIndex ] ); + * } + * + * // Must end every co-routine with a call to crEND(); + * crEND(); + * } + * + * // Function that creates two co-routines. + * void vOtherFunction( void ) + * { + * uint8_t ucParameterToPass; + * TaskHandle_t xHandle; + * + * // Create two co-routines at priority 0. The first is given index 0 + * // so (from the code above) toggles LED 5 every 200 ticks. The second + * // is given index 1 so toggles LED 6 every 400 ticks. + * for( uxIndex = 0; uxIndex < 2; uxIndex++ ) + * { + * xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex ); + * } + * } + * @endcode + * \defgroup xCoRoutineCreate xCoRoutineCreate + * \ingroup Tasks + */ +BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, + UBaseType_t uxPriority, + UBaseType_t uxIndex ); + + +/** + * croutine. h + * @code{c} + * void vCoRoutineSchedule( void ); + * @endcode + * + * Run a co-routine. + * + * vCoRoutineSchedule() executes the highest priority co-routine that is able + * to run. The co-routine will execute until it either blocks, yields or is + * preempted by a task. Co-routines execute cooperatively so one + * co-routine cannot be preempted by another, but can be preempted by a task. + * + * If an application comprises of both tasks and co-routines then + * vCoRoutineSchedule should be called from the idle task (in an idle task + * hook). + * + * Example usage: + * @code{c} + * // This idle task hook will schedule a co-routine each time it is called. + * // The rest of the idle task will execute between co-routine calls. + * void vApplicationIdleHook( void ) + * { + * vCoRoutineSchedule(); + * } + * + * // Alternatively, if you do not require any other part of the idle task to + * // execute, the idle task hook can call vCoRoutineSchedule() within an + * // infinite loop. + * void vApplicationIdleHook( void ) + * { + * for( ;; ) + * { + * vCoRoutineSchedule(); + * } + * } + * @endcode + * \defgroup vCoRoutineSchedule vCoRoutineSchedule + * \ingroup Tasks + */ +void vCoRoutineSchedule( void ); + +/** + * croutine. h + * @code{c} + * crSTART( CoRoutineHandle_t xHandle ); + * @endcode + * + * This macro MUST always be called at the start of a co-routine function. + * + * Example usage: + * @code{c} + * // Co-routine to be created. + * void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * static int32_t ulAVariable; + * + * // Must start every co-routine with a call to crSTART(); + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Co-routine functionality goes here. + * } + * + * // Must end every co-routine with a call to crEND(); + * crEND(); + * } + * @endcode + * \defgroup crSTART crSTART + * \ingroup Tasks + */ +#define crSTART( pxCRCB ) \ + switch( ( ( CRCB_t * ) ( pxCRCB ) )->uxState ) { \ + case 0: + +/** + * croutine. h + * @code{c} + * crEND(); + * @endcode + * + * This macro MUST always be called at the end of a co-routine function. + * + * Example usage: + * @code{c} + * // Co-routine to be created. + * void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * static int32_t ulAVariable; + * + * // Must start every co-routine with a call to crSTART(); + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Co-routine functionality goes here. + * } + * + * // Must end every co-routine with a call to crEND(); + * crEND(); + * } + * @endcode + * \defgroup crSTART crSTART + * \ingroup Tasks + */ +#define crEND() } + +/* + * These macros are intended for internal use by the co-routine implementation + * only. The macros should not be used directly by application writers. + */ +#define crSET_STATE0( xHandle ) \ + ( ( CRCB_t * ) ( xHandle ) )->uxState = ( __LINE__ * 2 ); return; \ + case ( __LINE__ * 2 ): +#define crSET_STATE1( xHandle ) \ + ( ( CRCB_t * ) ( xHandle ) )->uxState = ( ( __LINE__ * 2 ) + 1 ); return; \ + case ( ( __LINE__ * 2 ) + 1 ): + +/** + * croutine. h + * @code{c} + * crDELAY( CoRoutineHandle_t xHandle, TickType_t xTicksToDelay ); + * @endcode + * + * Delay a co-routine for a fixed period of time. + * + * crDELAY can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * @param xHandle The handle of the co-routine to delay. This is the xHandle + * parameter of the co-routine function. + * + * @param xTickToDelay The number of ticks that the co-routine should delay + * for. The actual amount of time this equates to is defined by + * configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant portTICK_PERIOD_MS + * can be used to convert ticks to milliseconds. + * + * Example usage: + * @code{c} + * // Co-routine to be created. + * void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * // This may not be necessary for const variables. + * // We are to delay for 200ms. + * static const xTickType xDelayTime = 200 / portTICK_PERIOD_MS; + * + * // Must start every co-routine with a call to crSTART(); + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Delay for 200ms. + * crDELAY( xHandle, xDelayTime ); + * + * // Do something here. + * } + * + * // Must end every co-routine with a call to crEND(); + * crEND(); + * } + * @endcode + * \defgroup crDELAY crDELAY + * \ingroup Tasks + */ +#define crDELAY( xHandle, xTicksToDelay ) \ + do { \ + if( ( xTicksToDelay ) > 0 ) \ + { \ + vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \ + } \ + crSET_STATE0( ( xHandle ) ); \ + } while( 0 ) + +/** + * @code{c} + * crQUEUE_SEND( + * CoRoutineHandle_t xHandle, + * QueueHandle_t pxQueue, + * void *pvItemToQueue, + * TickType_t xTicksToWait, + * BaseType_t *pxResult + * ) + * @endcode + * + * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine + * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. + * + * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas + * xQueueSend() and xQueueReceive() can only be used from tasks. + * + * crQUEUE_SEND can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xHandle The handle of the calling co-routine. This is the xHandle + * parameter of the co-routine function. + * + * @param pxQueue The handle of the queue on which the data will be posted. + * The handle is obtained as the return value when the queue is created using + * the xQueueCreate() API function. + * + * @param pvItemToQueue A pointer to the data being posted onto the queue. + * The number of bytes of each queued item is specified when the queue is + * created. This number of bytes is copied from pvItemToQueue into the queue + * itself. + * + * @param xTickToDelay The number of ticks that the co-routine should block + * to wait for space to become available on the queue, should space not be + * available immediately. The actual amount of time this equates to is defined + * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant + * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see example + * below). + * + * @param pxResult The variable pointed to by pxResult will be set to pdPASS if + * data was successfully posted onto the queue, otherwise it will be set to an + * error defined within ProjDefs.h. + * + * Example usage: + * @code{c} + * // Co-routine function that blocks for a fixed period then posts a number onto + * // a queue. + * static void prvCoRoutineFlashTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * static BaseType_t xNumberToPost = 0; + * static BaseType_t xResult; + * + * // Co-routines must begin with a call to crSTART(). + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // This assumes the queue has already been created. + * crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult ); + * + * if( xResult != pdPASS ) + * { + * // The message was not posted! + * } + * + * // Increment the number to be posted onto the queue. + * xNumberToPost++; + * + * // Delay for 100 ticks. + * crDELAY( xHandle, 100 ); + * } + * + * // Co-routines must end with a call to crEND(). + * crEND(); + * } + * @endcode + * \defgroup crQUEUE_SEND crQUEUE_SEND + * \ingroup Tasks + */ +#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult ) \ + do { \ + *( pxResult ) = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), ( xTicksToWait ) ); \ + if( *( pxResult ) == errQUEUE_BLOCKED ) \ + { \ + crSET_STATE0( ( xHandle ) ); \ + *pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 ); \ + } \ + if( *pxResult == errQUEUE_YIELD ) \ + { \ + crSET_STATE1( ( xHandle ) ); \ + *pxResult = pdPASS; \ + } \ + } while( 0 ) + +/** + * croutine. h + * @code{c} + * crQUEUE_RECEIVE( + * CoRoutineHandle_t xHandle, + * QueueHandle_t pxQueue, + * void *pvBuffer, + * TickType_t xTicksToWait, + * BaseType_t *pxResult + * ) + * @endcode + * + * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine + * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. + * + * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas + * xQueueSend() and xQueueReceive() can only be used from tasks. + * + * crQUEUE_RECEIVE can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xHandle The handle of the calling co-routine. This is the xHandle + * parameter of the co-routine function. + * + * @param pxQueue The handle of the queue from which the data will be received. + * The handle is obtained as the return value when the queue is created using + * the xQueueCreate() API function. + * + * @param pvBuffer The buffer into which the received item is to be copied. + * The number of bytes of each queued item is specified when the queue is + * created. This number of bytes is copied into pvBuffer. + * + * @param xTickToDelay The number of ticks that the co-routine should block + * to wait for data to become available from the queue, should data not be + * available immediately. The actual amount of time this equates to is defined + * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant + * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see the + * crQUEUE_SEND example). + * + * @param pxResult The variable pointed to by pxResult will be set to pdPASS if + * data was successfully retrieved from the queue, otherwise it will be set to + * an error code as defined within ProjDefs.h. + * + * Example usage: + * @code{c} + * // A co-routine receives the number of an LED to flash from a queue. It + * // blocks on the queue until the number is received. + * static void prvCoRoutineFlashWorkTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * static BaseType_t xResult; + * static UBaseType_t uxLEDToFlash; + * + * // All co-routines must start with a call to crSTART(). + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Wait for data to become available on the queue. + * crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult ); + * + * if( xResult == pdPASS ) + * { + * // We received the LED to flash - flash it! + * vParTestToggleLED( uxLEDToFlash ); + * } + * } + * + * crEND(); + * } + * @endcode + * \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE + * \ingroup Tasks + */ +#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult ) \ + do { \ + *( pxResult ) = xQueueCRReceive( ( pxQueue ), ( pvBuffer ), ( xTicksToWait ) ); \ + if( *( pxResult ) == errQUEUE_BLOCKED ) \ + { \ + crSET_STATE0( ( xHandle ) ); \ + *( pxResult ) = xQueueCRReceive( ( pxQueue ), ( pvBuffer ), 0 ); \ + } \ + if( *( pxResult ) == errQUEUE_YIELD ) \ + { \ + crSET_STATE1( ( xHandle ) ); \ + *( pxResult ) = pdPASS; \ + } \ + } while( 0 ) + +/** + * croutine. h + * @code{c} + * crQUEUE_SEND_FROM_ISR( + * QueueHandle_t pxQueue, + * void *pvItemToQueue, + * BaseType_t xCoRoutinePreviouslyWoken + * ) + * @endcode + * + * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the + * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() + * functions used by tasks. + * + * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to + * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and + * xQueueReceiveFromISR() can only be used to pass data between a task and and + * ISR. + * + * crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue + * that is being used from within a co-routine. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xCoRoutinePreviouslyWoken This is included so an ISR can post onto + * the same queue multiple times from a single interrupt. The first call + * should always pass in pdFALSE. Subsequent calls should pass in + * the value returned from the previous call. + * + * @return pdTRUE if a co-routine was woken by posting onto the queue. This is + * used by the ISR to determine if a context switch may be required following + * the ISR. + * + * Example usage: + * @code{c} + * // A co-routine that blocks on a queue waiting for characters to be received. + * static void vReceivingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * char cRxedChar; + * BaseType_t xResult; + * + * // All co-routines must start with a call to crSTART(). + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Wait for data to become available on the queue. This assumes the + * // queue xCommsRxQueue has already been created! + * crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult ); + * + * // Was a character received? + * if( xResult == pdPASS ) + * { + * // Process the character here. + * } + * } + * + * // All co-routines must end with a call to crEND(). + * crEND(); + * } + * + * // An ISR that uses a queue to send characters received on a serial port to + * // a co-routine. + * void vUART_ISR( void ) + * { + * char cRxedChar; + * BaseType_t xCRWokenByPost = pdFALSE; + * + * // We loop around reading characters until there are none left in the UART. + * while( UART_RX_REG_NOT_EMPTY() ) + * { + * // Obtain the character from the UART. + * cRxedChar = UART_RX_REG; + * + * // Post the character onto a queue. xCRWokenByPost will be pdFALSE + * // the first time around the loop. If the post causes a co-routine + * // to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE. + * // In this manner we can ensure that if more than one co-routine is + * // blocked on the queue only one is woken by this ISR no matter how + * // many characters are posted to the queue. + * xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost ); + * } + * } + * @endcode + * \defgroup crQUEUE_SEND_FROM_ISR crQUEUE_SEND_FROM_ISR + * \ingroup Tasks + */ +#define crQUEUE_SEND_FROM_ISR( pxQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) \ + xQueueCRSendFromISR( ( pxQueue ), ( pvItemToQueue ), ( xCoRoutinePreviouslyWoken ) ) + + +/** + * croutine. h + * @code{c} + * crQUEUE_SEND_FROM_ISR( + * QueueHandle_t pxQueue, + * void *pvBuffer, + * BaseType_t * pxCoRoutineWoken + * ) + * @endcode + * + * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the + * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() + * functions used by tasks. + * + * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to + * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and + * xQueueReceiveFromISR() can only be used to pass data between a task and and + * ISR. + * + * crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data + * from a queue that is being used from within a co-routine (a co-routine + * posted to the queue). + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvBuffer A pointer to a buffer into which the received item will be + * placed. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from the queue into + * pvBuffer. + * + * @param pxCoRoutineWoken A co-routine may be blocked waiting for space to become + * available on the queue. If crQUEUE_RECEIVE_FROM_ISR causes such a + * co-routine to unblock *pxCoRoutineWoken will get set to pdTRUE, otherwise + * *pxCoRoutineWoken will remain unchanged. + * + * @return pdTRUE an item was successfully received from the queue, otherwise + * pdFALSE. + * + * Example usage: + * @code{c} + * // A co-routine that posts a character to a queue then blocks for a fixed + * // period. The character is incremented each time. + * static void vSendingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // cChar holds its value while this co-routine is blocked and must therefore + * // be declared static. + * static char cCharToTx = 'a'; + * BaseType_t xResult; + * + * // All co-routines must start with a call to crSTART(). + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Send the next character to the queue. + * crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult ); + * + * if( xResult == pdPASS ) + * { + * // The character was successfully posted to the queue. + * } + * else + * { + * // Could not post the character to the queue. + * } + * + * // Enable the UART Tx interrupt to cause an interrupt in this + * // hypothetical UART. The interrupt will obtain the character + * // from the queue and send it. + * ENABLE_RX_INTERRUPT(); + * + * // Increment to the next character then block for a fixed period. + * // cCharToTx will maintain its value across the delay as it is + * // declared static. + * cCharToTx++; + * if( cCharToTx > 'x' ) + * { + * cCharToTx = 'a'; + * } + * crDELAY( 100 ); + * } + * + * // All co-routines must end with a call to crEND(). + * crEND(); + * } + * + * // An ISR that uses a queue to receive characters to send on a UART. + * void vUART_ISR( void ) + * { + * char cCharToTx; + * BaseType_t xCRWokenByPost = pdFALSE; + * + * while( UART_TX_REG_EMPTY() ) + * { + * // Are there any characters in the queue waiting to be sent? + * // xCRWokenByPost will automatically be set to pdTRUE if a co-routine + * // is woken by the post - ensuring that only a single co-routine is + * // woken no matter how many times we go around this loop. + * if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) ) + * { + * SEND_CHARACTER( cCharToTx ); + * } + * } + * } + * @endcode + * \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR + * \ingroup Tasks + */ +#define crQUEUE_RECEIVE_FROM_ISR( pxQueue, pvBuffer, pxCoRoutineWoken ) \ + xQueueCRReceiveFromISR( ( pxQueue ), ( pvBuffer ), ( pxCoRoutineWoken ) ) + +/* + * This function is intended for internal use by the co-routine macros only. + * The macro nature of the co-routine implementation requires that the + * prototype appears here. The function should not be used by application + * writers. + * + * Removes the current co-routine from its ready list and places it in the + * appropriate delayed list. + */ +void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, + List_t * pxEventList ); + +/* + * This function is intended for internal use by the queue implementation only. + * The function should not be used by application writers. + * + * Removes the highest priority co-routine from the event list and places it in + * the pending ready list. + */ +BaseType_t xCoRoutineRemoveFromEventList( const List_t * pxEventList ); + + +/* + * This function resets the internal state of the coroutine module. It must be + * called by the application before restarting the scheduler. + */ +void vCoRoutineResetState( void ) PRIVILEGED_FUNCTION; + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* CO_ROUTINE_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/deprecated_definitions.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/deprecated_definitions.h deleted file mode 100644 index 4ca714875..000000000 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/deprecated_definitions.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -#ifndef DEPRECATED_DEFINITIONS_H -#define DEPRECATED_DEFINITIONS_H - -/* Each FreeRTOS port has a unique portmacro.h header file. Originally a - * pre-processor definition was used to ensure the pre-processor found the correct - * portmacro.h file for the port being used. That scheme was deprecated in favour - * of setting the compiler's include path such that it found the correct - * portmacro.h file - removing the need for the constant and allowing the - * portmacro.h file to be located anywhere in relation to the port being used. The - * definitions below remain in the code for backward compatibility only. New - * projects should not use them. */ -#include "portmacro.h" - -#endif /* DEPRECATED_DEFINITIONS_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/event_groups.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/event_groups.h index e03b70dc8..e872cf23b 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/event_groups.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/event_groups.h @@ -1,6 +1,8 @@ /* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in @@ -34,6 +36,26 @@ /* FreeRTOS includes. */ #include "timers.h" +/* The following bit fields convey control information in a task's event list + * item value. It is important they don't clash with the + * taskEVENT_LIST_ITEM_VALUE_IN_USE definition. */ +#if ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_16_BITS ) + #define eventCLEAR_EVENTS_ON_EXIT_BIT ( ( uint16_t ) 0x0100U ) + #define eventUNBLOCKED_DUE_TO_BIT_SET ( ( uint16_t ) 0x0200U ) + #define eventWAIT_FOR_ALL_BITS ( ( uint16_t ) 0x0400U ) + #define eventEVENT_BITS_CONTROL_BYTES ( ( uint16_t ) 0xff00U ) +#elif ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_32_BITS ) + #define eventCLEAR_EVENTS_ON_EXIT_BIT ( ( uint32_t ) 0x01000000U ) + #define eventUNBLOCKED_DUE_TO_BIT_SET ( ( uint32_t ) 0x02000000U ) + #define eventWAIT_FOR_ALL_BITS ( ( uint32_t ) 0x04000000U ) + #define eventEVENT_BITS_CONTROL_BYTES ( ( uint32_t ) 0xff000000U ) +#elif ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_64_BITS ) + #define eventCLEAR_EVENTS_ON_EXIT_BIT ( ( uint64_t ) 0x0100000000000000U ) + #define eventUNBLOCKED_DUE_TO_BIT_SET ( ( uint64_t ) 0x0200000000000000U ) + #define eventWAIT_FOR_ALL_BITS ( ( uint64_t ) 0x0400000000000000U ) + #define eventEVENT_BITS_CONTROL_BYTES ( ( uint64_t ) 0xff00000000000000U ) +#endif /* if ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_16_BITS ) */ + /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { @@ -63,8 +85,6 @@ * be set and then tested atomically - as is the case where event groups are * used to create a synchronisation point between multiple tasks (a * 'rendezvous'). - * - * \defgroup EventGroup */ @@ -84,8 +104,8 @@ typedef struct EventGroupDef_t * EventGroupHandle_t; /* * The type that holds event bits always matches TickType_t - therefore the - * number of bits it holds is set by configUSE_16_BIT_TICKS (16 bits if set to 1, - * 32 bits if set to 0. + * number of bits it holds is set by configTICK_TYPE_WIDTH_IN_BITS (16 bits if set to 0, + * 32 bits if set to 1, 64 bits if set to 2. * * \defgroup EventBits_t EventBits_t * \ingroup EventGroup @@ -94,36 +114,40 @@ typedef TickType_t EventBits_t; /** * event_groups.h - *
+ * @code{c}
  * EventGroupHandle_t xEventGroupCreate( void );
- * 
+ * @endcode * * Create a new event group. * * Internally, within the FreeRTOS implementation, event groups use a [small] * block of memory, in which the event group's structure is stored. If an event - * groups is created using xEventGropuCreate() then the required memory is + * groups is created using xEventGroupCreate() then the required memory is * automatically dynamically allocated inside the xEventGroupCreate() function. * (see https://www.FreeRTOS.org/a00111.html). If an event group is created - * using xEventGropuCreateStatic() then the application writer must instead + * using xEventGroupCreateStatic() then the application writer must instead * provide the memory that will get used by the event group. * xEventGroupCreateStatic() therefore allows an event group to be created * without using any dynamic memory allocation. * * Although event groups are not related to ticks, for internal implementation * reasons the number of bits available for use in an event group is dependent - * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If - * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit - * 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has - * 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store - * event bits within an event group. + * on the configTICK_TYPE_WIDTH_IN_BITS setting in FreeRTOSConfig.h. If + * configTICK_TYPE_WIDTH_IN_BITS is 0 then each event group contains 8 usable bits (bit + * 0 to bit 7). If configTICK_TYPE_WIDTH_IN_BITS is set to 1 then each event group has + * 24 usable bits (bit 0 to bit 23). If configTICK_TYPE_WIDTH_IN_BITS is set to 2 then + * each event group has 56 usable bits (bit 0 to bit 53). The EventBits_t type + * is used to store event bits within an event group. + * + * The configUSE_EVENT_GROUPS configuration constant must be set to 1 for xEventGroupCreate() + * to be available. * * @return If the event group was created then a handle to the event group is * returned. If there was insufficient FreeRTOS heap available to create the * event group then NULL is returned. See https://www.FreeRTOS.org/a00111.html * * Example usage: - *
+ * @code{c}
  *  // Declare a variable to hold the created event group.
  *  EventGroupHandle_t xCreatedEventGroup;
  *
@@ -140,7 +164,7 @@ typedef TickType_t               EventBits_t;
  *  {
  *      // The event group was created.
  *  }
- * 
+ * @endcode * \defgroup xEventGroupCreate xEventGroupCreate * \ingroup EventGroup */ @@ -150,29 +174,33 @@ typedef TickType_t EventBits_t; /** * event_groups.h - *
+ * @code{c}
  * EventGroupHandle_t xEventGroupCreateStatic( EventGroupHandle_t * pxEventGroupBuffer );
- * 
+ * @endcode * * Create a new event group. * * Internally, within the FreeRTOS implementation, event groups use a [small] * block of memory, in which the event group's structure is stored. If an event - * groups is created using xEventGropuCreate() then the required memory is + * groups is created using xEventGroupCreate() then the required memory is * automatically dynamically allocated inside the xEventGroupCreate() function. * (see https://www.FreeRTOS.org/a00111.html). If an event group is created - * using xEventGropuCreateStatic() then the application writer must instead + * using xEventGroupCreateStatic() then the application writer must instead * provide the memory that will get used by the event group. * xEventGroupCreateStatic() therefore allows an event group to be created * without using any dynamic memory allocation. * * Although event groups are not related to ticks, for internal implementation * reasons the number of bits available for use in an event group is dependent - * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If - * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit - * 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has - * 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store - * event bits within an event group. + * on the configTICK_TYPE_WIDTH_IN_BITS setting in FreeRTOSConfig.h. If + * configTICK_TYPE_WIDTH_IN_BITS is 0 then each event group contains 8 usable bits (bit + * 0 to bit 7). If configTICK_TYPE_WIDTH_IN_BITS is set to 1 then each event group has + * 24 usable bits (bit 0 to bit 23). If configTICK_TYPE_WIDTH_IN_BITS is set to 2 then + * each event group has 56 usable bits (bit 0 to bit 53). The EventBits_t type + * is used to store event bits within an event group. + * + * The configUSE_EVENT_GROUPS configuration constant must be set to 1 for xEventGroupCreateStatic() + * to be available. * * @param pxEventGroupBuffer pxEventGroupBuffer must point to a variable of type * StaticEventGroup_t, which will be then be used to hold the event group's data @@ -182,7 +210,7 @@ typedef TickType_t EventBits_t; * returned. If pxEventGroupBuffer was NULL then NULL is returned. * * Example usage: - *
+ * @code{c}
  *  // StaticEventGroup_t is a publicly accessible structure that has the same
  *  // size and alignment requirements as the real event group structure.  It is
  *  // provided as a mechanism for applications to know the size of the event
@@ -195,7 +223,7 @@ typedef TickType_t               EventBits_t;
  *
  *  // Create the event group without dynamically allocating any memory.
  *  xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer );
- * 
+ * @endcode */ #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) PRIVILEGED_FUNCTION; @@ -203,19 +231,22 @@ typedef TickType_t EventBits_t; /** * event_groups.h - *
+ * @code{c}
  *  EventBits_t xEventGroupWaitBits(    EventGroupHandle_t xEventGroup,
  *                                      const EventBits_t uxBitsToWaitFor,
  *                                      const BaseType_t xClearOnExit,
  *                                      const BaseType_t xWaitForAllBits,
  *                                      const TickType_t xTicksToWait );
- * 
+ * @endcode * * [Potentially] block to wait for one or more bits to be set within a * previously created event group. * * This function cannot be called from an interrupt. * + * The configUSE_EVENT_GROUPS configuration constant must be set to 1 for xEventGroupWaitBits() + * to be available. + * * @param xEventGroup The event group in which the bits are being tested. The * event group must have previously been created using a call to * xEventGroupCreate(). @@ -241,7 +272,8 @@ typedef TickType_t EventBits_t; * * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait * for one/all (depending on the xWaitForAllBits value) of the bits specified by - * uxBitsToWaitFor to become set. + * uxBitsToWaitFor to become set. A value of portMAX_DELAY can be used to block + * indefinitely (provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). * * @return The value of the event group at the time either the bits being waited * for became set, or the block time expired. Test the return value to know @@ -253,9 +285,9 @@ typedef TickType_t EventBits_t; * pdTRUE. * * Example usage: - *
- #define BIT_0 ( 1 << 0 )
- #define BIT_4 ( 1 << 4 )
+ * @code{c}
+ * #define BIT_0 ( 1 << 0 )
+ * #define BIT_4 ( 1 << 4 )
  *
  * void aFunction( EventGroupHandle_t xEventGroup )
  * {
@@ -289,7 +321,7 @@ typedef TickType_t               EventBits_t;
  *          // without either BIT_0 or BIT_4 becoming set.
  *      }
  * }
- * 
+ * @endcode * \defgroup xEventGroupWaitBits xEventGroupWaitBits * \ingroup EventGroup */ @@ -301,13 +333,16 @@ EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, /** * event_groups.h - *
+ * @code{c}
  *  EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear );
- * 
+ * @endcode * * Clear bits within an event group. This function cannot be called from an * interrupt. * + * The configUSE_EVENT_GROUPS configuration constant must be set to 1 for xEventGroupClearBits() + * to be available. + * * @param xEventGroup The event group in which the bits are to be cleared. * * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear @@ -317,9 +352,9 @@ EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, * @return The value of the event group before the specified bits were cleared. * * Example usage: - *
- #define BIT_0 ( 1 << 0 )
- #define BIT_4 ( 1 << 4 )
+ * @code{c}
+ * #define BIT_0 ( 1 << 0 )
+ * #define BIT_4 ( 1 << 4 )
  *
  * void aFunction( EventGroupHandle_t xEventGroup )
  * {
@@ -350,7 +385,7 @@ EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup,
  *          // Neither bit 0 nor bit 4 were set in the first place.
  *      }
  * }
- * 
+ * @endcode * \defgroup xEventGroupClearBits xEventGroupClearBits * \ingroup EventGroup */ @@ -359,9 +394,9 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, /** * event_groups.h - *
+ * @code{c}
  *  BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
- * 
+ * @endcode * * A version of xEventGroupClearBits() that can be called from an interrupt. * @@ -375,6 +410,12 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, * timer task to have the clear operation performed in the context of the timer * task. * + * @note If this function returns pdPASS then the timer task is ready to run + * and a portYIELD_FROM_ISR(pdTRUE) should be executed to perform the needed + * clear on the event group. This behavior is different from + * xEventGroupSetBitsFromISR because the parameter xHigherPriorityTaskWoken is + * not present. + * * @param xEventGroup The event group in which the bits are to be cleared. * * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear. @@ -386,9 +427,9 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, * if the timer service queue was full. * * Example usage: - *
- #define BIT_0 ( 1 << 0 )
- #define BIT_4 ( 1 << 4 )
+ * @code{c}
+ * #define BIT_0 ( 1 << 0 )
+ * #define BIT_4 ( 1 << 4 )
  *
  * // An event group which it is assumed has already been created by a call to
  * // xEventGroupCreate().
@@ -404,9 +445,10 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup,
  *      if( xResult == pdPASS )
  *      {
  *          // The message was posted successfully.
+ *          portYIELD_FROM_ISR(pdTRUE);
  *      }
  * }
- * 
+ * @endcode * \defgroup xEventGroupClearBitsFromISR xEventGroupClearBitsFromISR * \ingroup EventGroup */ @@ -415,14 +457,14 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; #else #define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) \ - xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ) + xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) ( xEventGroup ), ( uint32_t ) ( uxBitsToClear ), NULL ) #endif /** * event_groups.h - *
+ * @code{c}
  *  EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
- * 
+ * @endcode * * Set bits within an event group. * This function cannot be called from an interrupt. xEventGroupSetBitsFromISR() @@ -431,6 +473,9 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, * Setting bits in an event group will automatically unblock tasks that are * blocked waiting for the bits. * + * The configUSE_EVENT_GROUPS configuration constant must be set to 1 for xEventGroupSetBits() + * to be available. + * * @param xEventGroup The event group in which the bits are to be set. * * @param uxBitsToSet A bitwise value that indicates the bit or bits to set. @@ -448,9 +493,9 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, * event group value before the call to xEventGroupSetBits() returns. * * Example usage: - *
- #define BIT_0 ( 1 << 0 )
- #define BIT_4 ( 1 << 4 )
+ * @code{c}
+ * #define BIT_0 ( 1 << 0 )
+ * #define BIT_4 ( 1 << 4 )
  *
  * void aFunction( EventGroupHandle_t xEventGroup )
  * {
@@ -486,7 +531,7 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup,
  *          // cleared as the task left the Blocked state.
  *      }
  * }
- * 
+ * @endcode * \defgroup xEventGroupSetBits xEventGroupSetBits * \ingroup EventGroup */ @@ -495,9 +540,9 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, /** * event_groups.h - *
+ * @code{c}
  *  BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken );
- * 
+ * @endcode * * A version of xEventGroupSetBits() that can be called from an interrupt. * @@ -530,9 +575,9 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, * if the timer service queue was full. * * Example usage: - *
- #define BIT_0 ( 1 << 0 )
- #define BIT_4 ( 1 << 4 )
+ * @code{c}
+ * #define BIT_0 ( 1 << 0 )
+ * #define BIT_4 ( 1 << 4 )
  *
  * // An event group which it is assumed has already been created by a call to
  * // xEventGroupCreate().
@@ -561,7 +606,7 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup,
  *          portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
  *      }
  * }
- * 
+ * @endcode * \defgroup xEventGroupSetBitsFromISR xEventGroupSetBitsFromISR * \ingroup EventGroup */ @@ -571,17 +616,17 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; #else #define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) \ - xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ) + xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) ( xEventGroup ), ( uint32_t ) ( uxBitsToSet ), ( pxHigherPriorityTaskWoken ) ) #endif /** * event_groups.h - *
+ * @code{c}
  *  EventBits_t xEventGroupSync(    EventGroupHandle_t xEventGroup,
  *                                  const EventBits_t uxBitsToSet,
  *                                  const EventBits_t uxBitsToWaitFor,
  *                                  TickType_t xTicksToWait );
- * 
+ * @endcode * * Atomically set bits within an event group, then wait for a combination of * bits to be set within the same event group. This functionality is typically @@ -595,6 +640,9 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, * this case all the bits specified by uxBitsToWait will be automatically * cleared before the function returns. * + * The configUSE_EVENT_GROUPS configuration constant must be set to 1 for xEventGroupSync() + * to be available. + * * @param xEventGroup The event group in which the bits are being tested. The * event group must have previously been created using a call to * xEventGroupCreate(). @@ -620,13 +668,13 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, * automatically cleared. * * Example usage: - *
+ * @code{c}
  * // Bits used by the three tasks.
- #define TASK_0_BIT     ( 1 << 0 )
- #define TASK_1_BIT     ( 1 << 1 )
- #define TASK_2_BIT     ( 1 << 2 )
+ * #define TASK_0_BIT     ( 1 << 0 )
+ * #define TASK_1_BIT     ( 1 << 1 )
+ * #define TASK_2_BIT     ( 1 << 2 )
  *
- #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT )
+ * #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT )
  *
  * // Use an event group to synchronise three tasks.  It is assumed this event
  * // group has already been created elsewhere.
@@ -694,7 +742,7 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup,
  *  }
  * }
  *
- * 
+ * @endcode * \defgroup xEventGroupSync xEventGroupSync * \ingroup EventGroup */ @@ -706,13 +754,16 @@ EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, /** * event_groups.h - *
+ * @code{c}
  *  EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup );
- * 
+ * @endcode * * Returns the current value of the bits in an event group. This function * cannot be used from an interrupt. * + * The configUSE_EVENT_GROUPS configuration constant must be set to 1 for xEventGroupGetBits() + * to be available. + * * @param xEventGroup The event group being queried. * * @return The event group bits at the time xEventGroupGetBits() was called. @@ -720,16 +771,19 @@ EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, * \defgroup xEventGroupGetBits xEventGroupGetBits * \ingroup EventGroup */ -#define xEventGroupGetBits( xEventGroup ) xEventGroupClearBits( xEventGroup, 0 ) +#define xEventGroupGetBits( xEventGroup ) xEventGroupClearBits( ( xEventGroup ), 0 ) /** * event_groups.h - *
+ * @code{c}
  *  EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup );
- * 
+ * @endcode * * A version of xEventGroupGetBits() that can be called from an ISR. * + * The configUSE_EVENT_GROUPS configuration constant must be set to 1 for xEventGroupGetBitsFromISR() + * to be available. + * * @param xEventGroup The event group being queried. * * @return The event group bits at the time xEventGroupGetBitsFromISR() was called. @@ -741,23 +795,51 @@ EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) PRIVILEG /** * event_groups.h - *
+ * @code{c}
  *  void xEventGroupDelete( EventGroupHandle_t xEventGroup );
- * 
+ * @endcode * * Delete an event group that was previously created by a call to * xEventGroupCreate(). Tasks that are blocked on the event group will be * unblocked and obtain 0 as the event group's value. * + * The configUSE_EVENT_GROUPS configuration constant must be set to 1 for vEventGroupDelete() + * to be available. + * * @param xEventGroup The event group being deleted. */ void vEventGroupDelete( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; +/** + * event_groups.h + * @code{c} + * BaseType_t xEventGroupGetStaticBuffer( EventGroupHandle_t xEventGroup, + * StaticEventGroup_t ** ppxEventGroupBuffer ); + * @endcode + * + * Retrieve a pointer to a statically created event groups's data structure + * buffer. It is the same buffer that is supplied at the time of creation. + * + * The configUSE_EVENT_GROUPS configuration constant must be set to 1 for xEventGroupGetStaticBuffer() + * to be available. + * + * @param xEventGroup The event group for which to retrieve the buffer. + * + * @param ppxEventGroupBuffer Used to return a pointer to the event groups's + * data structure buffer. + * + * @return pdTRUE if the buffer was retrieved, pdFALSE otherwise. + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + BaseType_t xEventGroupGetStaticBuffer( EventGroupHandle_t xEventGroup, + StaticEventGroup_t ** ppxEventGroupBuffer ) PRIVILEGED_FUNCTION; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + /* For internal use only. */ void vEventGroupSetBitsCallback( void * pvEventGroup, - const uint32_t ulBitsToSet ) PRIVILEGED_FUNCTION; + uint32_t ulBitsToSet ) PRIVILEGED_FUNCTION; void vEventGroupClearBitsCallback( void * pvEventGroup, - const uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION; + uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION; #if ( configUSE_TRACE_FACILITY == 1 ) diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/list.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/list.h index e2a00750c..e5e6583b4 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/list.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/list.h @@ -1,417 +1,511 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -/* - * This is the list implementation used by the scheduler. While it is tailored - * heavily for the schedulers needs, it is also available for use by - * application code. - * - * list_ts can only store pointers to list_item_ts. Each ListItem_t contains a - * numeric value (xItemValue). Most of the time the lists are sorted in - * descending item value order. - * - * Lists are created already containing one list item. The value of this - * item is the maximum possible that can be stored, it is therefore always at - * the end of the list and acts as a marker. The list member pxHead always - * points to this marker - even though it is at the tail of the list. This - * is because the tail contains a wrap back pointer to the true head of - * the list. - * - * In addition to it's value, each list item contains a pointer to the next - * item in the list (pxNext), a pointer to the list it is in (pxContainer) - * and a pointer to back to the object that contains it. These later two - * pointers are included for efficiency of list manipulation. There is - * effectively a two way link between the object containing the list item and - * the list item itself. - * - * - * \page ListIntroduction List Implementation - * \ingroup FreeRTOSIntro - */ - - -#ifndef LIST_H -#define LIST_H - -#ifndef INC_FREERTOS_H - #error "FreeRTOS.h must be included before list.h" -#endif - -/* - * The list structure members are modified from within interrupts, and therefore - * by rights should be declared volatile. However, they are only modified in a - * functionally atomic way (within critical sections of with the scheduler - * suspended) and are either passed by reference into a function or indexed via - * a volatile variable. Therefore, in all use cases tested so far, the volatile - * qualifier can be omitted in order to provide a moderate performance - * improvement without adversely affecting functional behaviour. The assembly - * instructions generated by the IAR, ARM and GCC compilers when the respective - * compiler's options were set for maximum optimisation has been inspected and - * deemed to be as intended. That said, as compiler technology advances, and - * especially if aggressive cross module optimisation is used (a use case that - * has not been exercised to any great extend) then it is feasible that the - * volatile qualifier will be needed for correct optimisation. It is expected - * that a compiler removing essential code because, without the volatile - * qualifier on the list structure members and with aggressive cross module - * optimisation, the compiler deemed the code unnecessary will result in - * complete and obvious failure of the scheduler. If this is ever experienced - * then the volatile qualifier can be inserted in the relevant places within the - * list structures by simply defining configLIST_VOLATILE to volatile in - * FreeRTOSConfig.h (as per the example at the bottom of this comment block). - * If configLIST_VOLATILE is not defined then the preprocessor directives below - * will simply #define configLIST_VOLATILE away completely. - * - * To use volatile list structure members then add the following line to - * FreeRTOSConfig.h (without the quotes): - * "#define configLIST_VOLATILE volatile" - */ -#ifndef configLIST_VOLATILE - #define configLIST_VOLATILE -#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */ - -/* *INDENT-OFF* */ -#ifdef __cplusplus - extern "C" { -#endif -/* *INDENT-ON* */ - -/* Macros that can be used to place known values within the list structures, - * then check that the known values do not get corrupted during the execution of - * the application. These may catch the list data structures being overwritten in - * memory. They will not catch data errors caused by incorrect configuration or - * use of FreeRTOS.*/ -#if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) - /* Define the macros to do nothing. */ - #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE - #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE - #define listFIRST_LIST_INTEGRITY_CHECK_VALUE - #define listSECOND_LIST_INTEGRITY_CHECK_VALUE - #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) - #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) - #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) - #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) - #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) - #define listTEST_LIST_INTEGRITY( pxList ) -#else /* if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) */ - /* Define macros that add new members into the list structures. */ - #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; - #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; - #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; - #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; - -/* Define macros that set the new structure members to known values. */ - #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE - #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE - #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE - #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE - -/* Define macros that will assert if one of the structure members does not - * contain its expected value. */ - #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) - #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) -#endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */ - - -/* - * Definition of the only type of object that a list can contain. - */ -struct xLIST; -struct xLIST_ITEM -{ - listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in descending order. */ - struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next ListItem_t in the list. */ - struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous ListItem_t in the list. */ - void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ - struct xLIST * configLIST_VOLATILE pxContainer; /*< Pointer to the list in which this list item is placed (if any). */ - listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ -}; -typedef struct xLIST_ITEM ListItem_t; /* For some reason lint wants this as two separate definitions. */ - -struct xMINI_LIST_ITEM -{ - listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - configLIST_VOLATILE TickType_t xItemValue; - struct xLIST_ITEM * configLIST_VOLATILE pxNext; - struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; -}; -typedef struct xMINI_LIST_ITEM MiniListItem_t; - -/* - * Definition of the type of queue used by the scheduler. - */ -typedef struct xLIST -{ - listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - volatile UBaseType_t uxNumberOfItems; - ListItem_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ - MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ - listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ -} List_t; - -/* - * Access macro to set the owner of a list item. The owner of a list item - * is the object (usually a TCB) that contains the list item. - * - * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER - * \ingroup LinkedList - */ -#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) - -/* - * Access macro to get the owner of a list item. The owner of a list item - * is the object (usually a TCB) that contains the list item. - * - * \page listGET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER - * \ingroup LinkedList - */ -#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) - -/* - * Access macro to set the value of the list item. In most cases the value is - * used to sort the list in descending order. - * - * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE - * \ingroup LinkedList - */ -#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) - -/* - * Access macro to retrieve the value of the list item. The value can - * represent anything - for example the priority of a task, or the time at - * which a task should be unblocked. - * - * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE - * \ingroup LinkedList - */ -#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) - -/* - * Access macro to retrieve the value of the list item at the head of a given - * list. - * - * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE - * \ingroup LinkedList - */ -#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) - -/* - * Return the list item at the head of the list. - * - * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY - * \ingroup LinkedList - */ -#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) - -/* - * Return the next list item. - * - * \page listGET_NEXT listGET_NEXT - * \ingroup LinkedList - */ -#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) - -/* - * Return the list item that marks the end of the list - * - * \page listGET_END_MARKER listGET_END_MARKER - * \ingroup LinkedList - */ -#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) ) - -/* - * Access macro to determine if a list contains any items. The macro will - * only have the value true if the list is empty. - * - * \page listLIST_IS_EMPTY listLIST_IS_EMPTY - * \ingroup LinkedList - */ -#define listLIST_IS_EMPTY( pxList ) ( ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ? pdTRUE : pdFALSE ) - -/* - * Access macro to return the number of items in the list. - */ -#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) - -/* - * Access function to obtain the owner of the next entry in a list. - * - * The list member pxIndex is used to walk through a list. Calling - * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list - * and returns that entry's pxOwner parameter. Using multiple calls to this - * function it is therefore possible to move through every item contained in - * a list. - * - * The pxOwner parameter of a list item is a pointer to the object that owns - * the list item. In the scheduler this is normally a task control block. - * The pxOwner parameter effectively creates a two way link between the list - * item and its owner. - * - * @param pxTCB pxTCB is set to the address of the owner of the next list item. - * @param pxList The list from which the next item owner is to be returned. - * - * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY - * \ingroup LinkedList - */ -#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ - { \ - List_t * const pxConstList = ( pxList ); \ - /* Increment the index to the next item and return the item, ensuring */ \ - /* we don't return the marker used at the end of the list. */ \ - ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ - if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ - { \ - ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ - } \ - ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ - } - - -/* - * Access function to obtain the owner of the first entry in a list. Lists - * are normally sorted in ascending item value order. - * - * This function returns the pxOwner member of the first item in the list. - * The pxOwner parameter of a list item is a pointer to the object that owns - * the list item. In the scheduler this is normally a task control block. - * The pxOwner parameter effectively creates a two way link between the list - * item and its owner. - * - * @param pxList The list from which the owner of the head item is to be - * returned. - * - * \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY - * \ingroup LinkedList - */ -#define listGET_OWNER_OF_HEAD_ENTRY( pxList ) ( ( &( ( pxList )->xListEnd ) )->pxNext->pvOwner ) - -/* - * Check to see if a list item is within a list. The list item maintains a - * "container" pointer that points to the list it is in. All this macro does - * is check to see if the container and the list match. - * - * @param pxList The list we want to know if the list item is within. - * @param pxListItem The list item we want to know if is in the list. - * @return pdTRUE if the list item is in the list, otherwise pdFALSE. - */ -#define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( ( pxListItem )->pxContainer == ( pxList ) ) ? ( pdTRUE ) : ( pdFALSE ) ) - -/* - * Return the list a list item is contained within (referenced from). - * - * @param pxListItem The list item being queried. - * @return A pointer to the List_t object that references the pxListItem - */ -#define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pxContainer ) - -/* - * This provides a crude means of knowing if a list has been initialised, as - * pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise() - * function. - */ -#define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY ) - -/* - * Must be called before a list is used! This initialises all the members - * of the list structure and inserts the xListEnd item into the list as a - * marker to the back of the list. - * - * @param pxList Pointer to the list being initialised. - * - * \page vListInitialise vListInitialise - * \ingroup LinkedList - */ -void vListInitialise( List_t * const pxList ) PRIVILEGED_FUNCTION; - -/* - * Must be called before a list item is used. This sets the list container to - * null so the item does not think that it is already contained in a list. - * - * @param pxItem Pointer to the list item being initialised. - * - * \page vListInitialiseItem vListInitialiseItem - * \ingroup LinkedList - */ -void vListInitialiseItem( ListItem_t * const pxItem ) PRIVILEGED_FUNCTION; - -/* - * Insert a list item into a list. The item will be inserted into the list in - * a position determined by its item value (descending item value order). - * - * @param pxList The list into which the item is to be inserted. - * - * @param pxNewListItem The item that is to be placed in the list. - * - * \page vListInsert vListInsert - * \ingroup LinkedList - */ -void vListInsert( List_t * const pxList, - ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; - -/* - * Insert a list item into a list. The item will be inserted in a position - * such that it will be the last item within the list returned by multiple - * calls to listGET_OWNER_OF_NEXT_ENTRY. - * - * The list member pxIndex is used to walk through a list. Calling - * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list. - * Placing an item in a list using vListInsertEnd effectively places the item - * in the list position pointed to by pxIndex. This means that every other - * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before - * the pxIndex parameter again points to the item being inserted. - * - * @param pxList The list into which the item is to be inserted. - * - * @param pxNewListItem The list item to be inserted into the list. - * - * \page vListInsertEnd vListInsertEnd - * \ingroup LinkedList - */ -void vListInsertEnd( List_t * const pxList, - ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; - -/* - * Remove an item from a list. The list item has a pointer to the list that - * it is in, so only the list item need be passed into the function. - * - * @param uxListRemove The item to be removed. The item will remove itself from - * the list pointed to by it's pxContainer parameter. - * - * @return The number of items that remain in the list after the list item has - * been removed. - * - * \page uxListRemove uxListRemove - * \ingroup LinkedList - */ -UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) PRIVILEGED_FUNCTION; - -/* *INDENT-OFF* */ -#ifdef __cplusplus - } -#endif -/* *INDENT-ON* */ - -#endif /* ifndef LIST_H */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * This is the list implementation used by the scheduler. While it is tailored + * heavily for the schedulers needs, it is also available for use by + * application code. + * + * list_ts can only store pointers to list_item_ts. Each ListItem_t contains a + * numeric value (xItemValue). Most of the time the lists are sorted in + * ascending item value order. + * + * Lists are created already containing one list item. The value of this + * item is the maximum possible that can be stored, it is therefore always at + * the end of the list and acts as a marker. The list member pxHead always + * points to this marker - even though it is at the tail of the list. This + * is because the tail contains a wrap back pointer to the true head of + * the list. + * + * In addition to it's value, each list item contains a pointer to the next + * item in the list (pxNext), a pointer to the list it is in (pxContainer) + * and a pointer to back to the object that contains it. These later two + * pointers are included for efficiency of list manipulation. There is + * effectively a two way link between the object containing the list item and + * the list item itself. + * + * + * \page ListIntroduction List Implementation + * \ingroup FreeRTOSIntro + */ + + +#ifndef LIST_H +#define LIST_H + +#ifndef INC_FREERTOS_H + #error "FreeRTOS.h must be included before list.h" +#endif + +/* + * The list structure members are modified from within interrupts, and therefore + * by rights should be declared volatile. However, they are only modified in a + * functionally atomic way (within critical sections of with the scheduler + * suspended) and are either passed by reference into a function or indexed via + * a volatile variable. Therefore, in all use cases tested so far, the volatile + * qualifier can be omitted in order to provide a moderate performance + * improvement without adversely affecting functional behaviour. The assembly + * instructions generated by the IAR, ARM and GCC compilers when the respective + * compiler's options were set for maximum optimisation has been inspected and + * deemed to be as intended. That said, as compiler technology advances, and + * especially if aggressive cross module optimisation is used (a use case that + * has not been exercised to any great extend) then it is feasible that the + * volatile qualifier will be needed for correct optimisation. It is expected + * that a compiler removing essential code because, without the volatile + * qualifier on the list structure members and with aggressive cross module + * optimisation, the compiler deemed the code unnecessary will result in + * complete and obvious failure of the scheduler. If this is ever experienced + * then the volatile qualifier can be inserted in the relevant places within the + * list structures by simply defining configLIST_VOLATILE to volatile in + * FreeRTOSConfig.h (as per the example at the bottom of this comment block). + * If configLIST_VOLATILE is not defined then the preprocessor directives below + * will simply #define configLIST_VOLATILE away completely. + * + * To use volatile list structure members then add the following line to + * FreeRTOSConfig.h (without the quotes): + * "#define configLIST_VOLATILE volatile" + */ +#ifndef configLIST_VOLATILE + #define configLIST_VOLATILE +#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */ + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* Macros that can be used to place known values within the list structures, + * then check that the known values do not get corrupted during the execution of + * the application. These may catch the list data structures being overwritten in + * memory. They will not catch data errors caused by incorrect configuration or + * use of FreeRTOS.*/ +#if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) + /* Define the macros to do nothing. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) + #define listTEST_LIST_INTEGRITY( pxList ) +#else /* if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) */ + /* Define macros that add new members into the list structures. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; + +/* Define macros that set the new structure members to known values. */ + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + +/* Define macros that will assert if one of the structure members does not + * contain its expected value. */ + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) + #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) +#endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */ + + +/* + * Definition of the only type of object that a list can contain. + */ +struct xLIST; +struct xLIST_ITEM +{ + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /**< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; /**< The value being listed. In most cases this is used to sort the list in ascending order. */ + struct xLIST_ITEM * configLIST_VOLATILE pxNext; /**< Pointer to the next ListItem_t in the list. */ + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /**< Pointer to the previous ListItem_t in the list. */ + void * pvOwner; /**< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ + struct xLIST * configLIST_VOLATILE pxContainer; /**< Pointer to the list in which this list item is placed (if any). */ + listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /**< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ +}; +typedef struct xLIST_ITEM ListItem_t; + +#if ( configUSE_MINI_LIST_ITEM == 1 ) + struct xMINI_LIST_ITEM + { + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /**< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; + struct xLIST_ITEM * configLIST_VOLATILE pxNext; + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; + }; + typedef struct xMINI_LIST_ITEM MiniListItem_t; +#else + typedef struct xLIST_ITEM MiniListItem_t; +#endif + +/* + * Definition of the type of queue used by the scheduler. + */ +typedef struct xLIST +{ + listFIRST_LIST_INTEGRITY_CHECK_VALUE /**< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE UBaseType_t uxNumberOfItems; + ListItem_t * configLIST_VOLATILE pxIndex; /**< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ + MiniListItem_t xListEnd; /**< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ + listSECOND_LIST_INTEGRITY_CHECK_VALUE /**< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ +} List_t; + +/* + * Access macro to set the owner of a list item. The owner of a list item + * is the object (usually a TCB) that contains the list item. + * + * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER + * \ingroup LinkedList + */ +#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) + +/* + * Access macro to get the owner of a list item. The owner of a list item + * is the object (usually a TCB) that contains the list item. + * + * \page listGET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER + * \ingroup LinkedList + */ +#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) + +/* + * Access macro to set the value of the list item. In most cases the value is + * used to sort the list in ascending order. + * + * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) + +/* + * Access macro to retrieve the value of the list item. The value can + * represent anything - for example the priority of a task, or the time at + * which a task should be unblocked. + * + * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) + +/* + * Access macro to retrieve the value of the list item at the head of a given + * list. + * + * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) + +/* + * Return the list item at the head of the list. + * + * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY + * \ingroup LinkedList + */ +#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) + +/* + * Return the next list item. + * + * \page listGET_NEXT listGET_NEXT + * \ingroup LinkedList + */ +#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) + +/* + * Return the list item that marks the end of the list + * + * \page listGET_END_MARKER listGET_END_MARKER + * \ingroup LinkedList + */ +#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) ) + +/* + * Access macro to determine if a list contains any items. The macro will + * only have the value true if the list is empty. + * + * \page listLIST_IS_EMPTY listLIST_IS_EMPTY + * \ingroup LinkedList + */ +#define listLIST_IS_EMPTY( pxList ) ( ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ? pdTRUE : pdFALSE ) + +/* + * Access macro to return the number of items in the list. + */ +#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) + +/* + * Access function to obtain the owner of the next entry in a list. + * + * The list member pxIndex is used to walk through a list. Calling + * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list + * and returns that entry's pxOwner parameter. Using multiple calls to this + * function it is therefore possible to move through every item contained in + * a list. + * + * The pxOwner parameter of a list item is a pointer to the object that owns + * the list item. In the scheduler this is normally a task control block. + * The pxOwner parameter effectively creates a two way link between the list + * item and its owner. + * + * @param pxTCB pxTCB is set to the address of the owner of the next list item. + * @param pxList The list from which the next item owner is to be returned. + * + * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY + * \ingroup LinkedList + */ +#if ( configNUMBER_OF_CORES == 1 ) + #define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ + do { \ + List_t * const pxConstList = ( pxList ); \ + /* Increment the index to the next item and return the item, ensuring */ \ + /* we don't return the marker used at the end of the list. */ \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ + { \ + ( pxConstList )->pxIndex = ( pxConstList )->xListEnd.pxNext; \ + } \ + ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ + } while( 0 ) +#else /* #if ( configNUMBER_OF_CORES == 1 ) */ + +/* This function is not required in SMP. FreeRTOS SMP scheduler doesn't use + * pxIndex and it should always point to the xListEnd. Not defining this macro + * here to prevent updating pxIndex. + */ +#endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + +/* + * Version of uxListRemove() that does not return a value. Provided as a slight + * optimisation for xTaskIncrementTick() by being inline. + * + * Remove an item from a list. The list item has a pointer to the list that + * it is in, so only the list item need be passed into the function. + * + * @param uxListRemove The item to be removed. The item will remove itself from + * the list pointed to by it's pxContainer parameter. + * + * @return The number of items that remain in the list after the list item has + * been removed. + * + * \page listREMOVE_ITEM listREMOVE_ITEM + * \ingroup LinkedList + */ +#define listREMOVE_ITEM( pxItemToRemove ) \ + do { \ + /* The list item knows which list it is in. Obtain the list from the list \ + * item. */ \ + List_t * const pxList = ( pxItemToRemove )->pxContainer; \ + \ + ( pxItemToRemove )->pxNext->pxPrevious = ( pxItemToRemove )->pxPrevious; \ + ( pxItemToRemove )->pxPrevious->pxNext = ( pxItemToRemove )->pxNext; \ + /* Make sure the index is left pointing to a valid item. */ \ + if( pxList->pxIndex == ( pxItemToRemove ) ) \ + { \ + pxList->pxIndex = ( pxItemToRemove )->pxPrevious; \ + } \ + \ + ( pxItemToRemove )->pxContainer = NULL; \ + ( ( pxList )->uxNumberOfItems ) = ( UBaseType_t ) ( ( ( pxList )->uxNumberOfItems ) - 1U ); \ + } while( 0 ) + +/* + * Inline version of vListInsertEnd() to provide slight optimisation for + * xTaskIncrementTick(). + * + * Insert a list item into a list. The item will be inserted in a position + * such that it will be the last item within the list returned by multiple + * calls to listGET_OWNER_OF_NEXT_ENTRY. + * + * The list member pxIndex is used to walk through a list. Calling + * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list. + * Placing an item in a list using vListInsertEnd effectively places the item + * in the list position pointed to by pxIndex. This means that every other + * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before + * the pxIndex parameter again points to the item being inserted. + * + * @param pxList The list into which the item is to be inserted. + * + * @param pxNewListItem The list item to be inserted into the list. + * + * \page listINSERT_END listINSERT_END + * \ingroup LinkedList + */ +#define listINSERT_END( pxList, pxNewListItem ) \ + do { \ + ListItem_t * const pxIndex = ( pxList )->pxIndex; \ + \ + /* Only effective when configASSERT() is also defined, these tests may catch \ + * the list data structures being overwritten in memory. They will not catch \ + * data errors caused by incorrect configuration or use of FreeRTOS. */ \ + listTEST_LIST_INTEGRITY( ( pxList ) ); \ + listTEST_LIST_ITEM_INTEGRITY( ( pxNewListItem ) ); \ + \ + /* Insert a new list item into ( pxList ), but rather than sort the list, \ + * makes the new list item the last item to be removed by a call to \ + * listGET_OWNER_OF_NEXT_ENTRY(). */ \ + ( pxNewListItem )->pxNext = pxIndex; \ + ( pxNewListItem )->pxPrevious = pxIndex->pxPrevious; \ + \ + pxIndex->pxPrevious->pxNext = ( pxNewListItem ); \ + pxIndex->pxPrevious = ( pxNewListItem ); \ + \ + /* Remember which list the item is in. */ \ + ( pxNewListItem )->pxContainer = ( pxList ); \ + \ + ( ( pxList )->uxNumberOfItems ) = ( UBaseType_t ) ( ( ( pxList )->uxNumberOfItems ) + 1U ); \ + } while( 0 ) + +/* + * Access function to obtain the owner of the first entry in a list. Lists + * are normally sorted in ascending item value order. + * + * This function returns the pxOwner member of the first item in the list. + * The pxOwner parameter of a list item is a pointer to the object that owns + * the list item. In the scheduler this is normally a task control block. + * The pxOwner parameter effectively creates a two way link between the list + * item and its owner. + * + * @param pxList The list from which the owner of the head item is to be + * returned. + * + * \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY + * \ingroup LinkedList + */ +#define listGET_OWNER_OF_HEAD_ENTRY( pxList ) ( ( &( ( pxList )->xListEnd ) )->pxNext->pvOwner ) + +/* + * Check to see if a list item is within a list. The list item maintains a + * "container" pointer that points to the list it is in. All this macro does + * is check to see if the container and the list match. + * + * @param pxList The list we want to know if the list item is within. + * @param pxListItem The list item we want to know if is in the list. + * @return pdTRUE if the list item is in the list, otherwise pdFALSE. + */ +#define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( ( pxListItem )->pxContainer == ( pxList ) ) ? ( pdTRUE ) : ( pdFALSE ) ) + +/* + * Return the list a list item is contained within (referenced from). + * + * @param pxListItem The list item being queried. + * @return A pointer to the List_t object that references the pxListItem + */ +#define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pxContainer ) + +/* + * This provides a crude means of knowing if a list has been initialised, as + * pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise() + * function. + */ +#define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY ) + +/* + * Must be called before a list is used! This initialises all the members + * of the list structure and inserts the xListEnd item into the list as a + * marker to the back of the list. + * + * @param pxList Pointer to the list being initialised. + * + * \page vListInitialise vListInitialise + * \ingroup LinkedList + */ +void vListInitialise( List_t * const pxList ) PRIVILEGED_FUNCTION; + +/* + * Must be called before a list item is used. This sets the list container to + * null so the item does not think that it is already contained in a list. + * + * @param pxItem Pointer to the list item being initialised. + * + * \page vListInitialiseItem vListInitialiseItem + * \ingroup LinkedList + */ +void vListInitialiseItem( ListItem_t * const pxItem ) PRIVILEGED_FUNCTION; + +/* + * Insert a list item into a list. The item will be inserted into the list in + * a position determined by its item value (ascending item value order). + * + * @param pxList The list into which the item is to be inserted. + * + * @param pxNewListItem The item that is to be placed in the list. + * + * \page vListInsert vListInsert + * \ingroup LinkedList + */ +void vListInsert( List_t * const pxList, + ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; + +/* + * Insert a list item into a list. The item will be inserted in a position + * such that it will be the last item within the list returned by multiple + * calls to listGET_OWNER_OF_NEXT_ENTRY. + * + * The list member pxIndex is used to walk through a list. Calling + * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list. + * Placing an item in a list using vListInsertEnd effectively places the item + * in the list position pointed to by pxIndex. This means that every other + * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before + * the pxIndex parameter again points to the item being inserted. + * + * @param pxList The list into which the item is to be inserted. + * + * @param pxNewListItem The list item to be inserted into the list. + * + * \page vListInsertEnd vListInsertEnd + * \ingroup LinkedList + */ +void vListInsertEnd( List_t * const pxList, + ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; + +/* + * Remove an item from a list. The list item has a pointer to the list that + * it is in, so only the list item need be passed into the function. + * + * @param uxListRemove The item to be removed. The item will remove itself from + * the list pointed to by it's pxContainer parameter. + * + * @return The number of items that remain in the list after the list item has + * been removed. + * + * \page uxListRemove uxListRemove + * \ingroup LinkedList + */ +UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) PRIVILEGED_FUNCTION; + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* ifndef LIST_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/message_buffer.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/message_buffer.h index 0fc36702b..a47ce467f 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/message_buffer.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/message_buffer.h @@ -1,821 +1,967 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - - -/* - * Message buffers build functionality on top of FreeRTOS stream buffers. - * Whereas stream buffers are used to send a continuous stream of data from one - * task or interrupt to another, message buffers are used to send variable - * length discrete messages from one task or interrupt to another. Their - * implementation is light weight, making them particularly suited for interrupt - * to task and core to core communication scenarios. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xMessageBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xMessageBufferRead()) inside a critical section and set the receive - * timeout to 0. - * - * Message buffers hold variable length messages. To enable that, when a - * message is written to the message buffer an additional sizeof( size_t ) bytes - * are also written to store the message's length (that happens internally, with - * the API function). sizeof( size_t ) is typically 4 bytes on a 32-bit - * architecture, so writing a 10 byte message to a message buffer on a 32-bit - * architecture will actually reduce the available space in the message buffer - * by 14 bytes (10 byte are used by the message, and 4 bytes to hold the length - * of the message). - */ - -#ifndef FREERTOS_MESSAGE_BUFFER_H -#define FREERTOS_MESSAGE_BUFFER_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include message_buffer.h" -#endif - -/* Message buffers are built onto of stream buffers. */ -#include "stream_buffer.h" - -/* *INDENT-OFF* */ -#if defined( __cplusplus ) - extern "C" { -#endif -/* *INDENT-ON* */ - -/** - * Type by which message buffers are referenced. For example, a call to - * xMessageBufferCreate() returns an MessageBufferHandle_t variable that can - * then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(), - * etc. - */ -typedef void * MessageBufferHandle_t; - -/*-----------------------------------------------------------*/ - -/** - * message_buffer.h - * - *
- * MessageBufferHandle_t xMessageBufferCreate( size_t xBufferSizeBytes );
- * 
- * - * Creates a new message buffer using dynamically allocated memory. See - * xMessageBufferCreateStatic() for a version that uses statically allocated - * memory (memory that is allocated at compile time). - * - * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in - * FreeRTOSConfig.h for xMessageBufferCreate() to be available. - * - * @param xBufferSizeBytes The total number of bytes (not messages) the message - * buffer will be able to hold at any one time. When a message is written to - * the message buffer an additional sizeof( size_t ) bytes are also written to - * store the message's length. sizeof( size_t ) is typically 4 bytes on a - * 32-bit architecture, so on most 32-bit architectures a 10 byte message will - * take up 14 bytes of message buffer space. - * - * @return If NULL is returned, then the message buffer cannot be created - * because there is insufficient heap memory available for FreeRTOS to allocate - * the message buffer data structures and storage area. A non-NULL value being - * returned indicates that the message buffer has been created successfully - - * the returned value should be stored as the handle to the created message - * buffer. - * - * Example use: - *
- *
- * void vAFunction( void )
- * {
- * MessageBufferHandle_t xMessageBuffer;
- * const size_t xMessageBufferSizeBytes = 100;
- *
- *  // Create a message buffer that can hold 100 bytes.  The memory used to hold
- *  // both the message buffer structure and the messages themselves is allocated
- *  // dynamically.  Each message added to the buffer consumes an additional 4
- *  // bytes which are used to hold the lengh of the message.
- *  xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes );
- *
- *  if( xMessageBuffer == NULL )
- *  {
- *      // There was not enough heap memory space available to create the
- *      // message buffer.
- *  }
- *  else
- *  {
- *      // The message buffer was created successfully and can now be used.
- *  }
- *
- * 
- * \defgroup xMessageBufferCreate xMessageBufferCreate - * \ingroup MessageBufferManagement - */ -#define xMessageBufferCreate( xBufferSizeBytes ) \ - ( MessageBufferHandle_t ) xStreamBufferGenericCreate( xBufferSizeBytes, ( size_t ) 0, pdTRUE ) - -/** - * message_buffer.h - * - *
- * MessageBufferHandle_t xMessageBufferCreateStatic( size_t xBufferSizeBytes,
- *                                                uint8_t *pucMessageBufferStorageArea,
- *                                                StaticMessageBuffer_t *pxStaticMessageBuffer );
- * 
- * Creates a new message buffer using statically allocated memory. See - * xMessageBufferCreate() for a version that uses dynamically allocated memory. - * - * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the - * pucMessageBufferStorageArea parameter. When a message is written to the - * message buffer an additional sizeof( size_t ) bytes are also written to store - * the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit - * architecture, so on most 32-bit architecture a 10 byte message will take up - * 14 bytes of message buffer space. The maximum number of bytes that can be - * stored in the message buffer is actually (xBufferSizeBytes - 1). - * - * @param pucMessageBufferStorageArea Must point to a uint8_t array that is at - * least xBufferSizeBytes + 1 big. This is the array to which messages are - * copied when they are written to the message buffer. - * - * @param pxStaticMessageBuffer Must point to a variable of type - * StaticMessageBuffer_t, which will be used to hold the message buffer's data - * structure. - * - * @return If the message buffer is created successfully then a handle to the - * created message buffer is returned. If either pucMessageBufferStorageArea or - * pxStaticmessageBuffer are NULL then NULL is returned. - * - * Example use: - *
- *
- * // Used to dimension the array used to hold the messages.  The available space
- * // will actually be one less than this, so 999.
- #define STORAGE_SIZE_BYTES 1000
- *
- * // Defines the memory that will actually hold the messages within the message
- * // buffer.
- * static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];
- *
- * // The variable used to hold the message buffer structure.
- * StaticMessageBuffer_t xMessageBufferStruct;
- *
- * void MyFunction( void )
- * {
- * MessageBufferHandle_t xMessageBuffer;
- *
- *  xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucBufferStorage ),
- *                                               ucBufferStorage,
- *                                               &xMessageBufferStruct );
- *
- *  // As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer
- *  // parameters were NULL, xMessageBuffer will not be NULL, and can be used to
- *  // reference the created message buffer in other message buffer API calls.
- *
- *  // Other code that uses the message buffer can go here.
- * }
- *
- * 
- * \defgroup xMessageBufferCreateStatic xMessageBufferCreateStatic - * \ingroup MessageBufferManagement - */ -#define xMessageBufferCreateStatic( xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer ) \ - ( MessageBufferHandle_t ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, 0, pdTRUE, pucMessageBufferStorageArea, pxStaticMessageBuffer ) - -/** - * message_buffer.h - * - *
- * size_t xMessageBufferSend( MessageBufferHandle_t xMessageBuffer,
- *                         const void *pvTxData,
- *                         size_t xDataLengthBytes,
- *                         TickType_t xTicksToWait );
- * 
- * - * Sends a discrete message to the message buffer. The message can be any - * length that fits within the buffer's free space, and is copied into the - * buffer. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xMessageBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xMessageBufferRead()) inside a critical section and set the receive - * block time to 0. - * - * Use xMessageBufferSend() to write to a message buffer from a task. Use - * xMessageBufferSendFromISR() to write to a message buffer from an interrupt - * service routine (ISR). - * - * @param xMessageBuffer The handle of the message buffer to which a message is - * being sent. - * - * @param pvTxData A pointer to the message that is to be copied into the - * message buffer. - * - * @param xDataLengthBytes The length of the message. That is, the number of - * bytes to copy from pvTxData into the message buffer. When a message is - * written to the message buffer an additional sizeof( size_t ) bytes are also - * written to store the message's length. sizeof( size_t ) is typically 4 bytes - * on a 32-bit architecture, so on most 32-bit architecture setting - * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 - * bytes (20 bytes of message data and 4 bytes to hold the message length). - * - * @param xTicksToWait The maximum amount of time the calling task should remain - * in the Blocked state to wait for enough space to become available in the - * message buffer, should the message buffer have insufficient space when - * xMessageBufferSend() is called. The calling task will never block if - * xTicksToWait is zero. The block time is specified in tick periods, so the - * absolute time it represents is dependent on the tick frequency. The macro - * pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into - * a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause - * the task to wait indefinitely (without timing out), provided - * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any - * CPU time when they are in the Blocked state. - * - * @return The number of bytes written to the message buffer. If the call to - * xMessageBufferSend() times out before there was enough space to write the - * message into the message buffer then zero is returned. If the call did not - * time out then xDataLengthBytes is returned. - * - * Example use: - *
- * void vAFunction( MessageBufferHandle_t xMessageBuffer )
- * {
- * size_t xBytesSent;
- * uint8_t ucArrayToSend[] = { 0, 1, 2, 3 };
- * char *pcStringToSend = "String to send";
- * const TickType_t x100ms = pdMS_TO_TICKS( 100 );
- *
- *  // Send an array to the message buffer, blocking for a maximum of 100ms to
- *  // wait for enough space to be available in the message buffer.
- *  xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms );
- *
- *  if( xBytesSent != sizeof( ucArrayToSend ) )
- *  {
- *      // The call to xMessageBufferSend() times out before there was enough
- *      // space in the buffer for the data to be written.
- *  }
- *
- *  // Send the string to the message buffer.  Return immediately if there is
- *  // not enough space in the buffer.
- *  xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 );
- *
- *  if( xBytesSent != strlen( pcStringToSend ) )
- *  {
- *      // The string could not be added to the message buffer because there was
- *      // not enough free space in the buffer.
- *  }
- * }
- * 
- * \defgroup xMessageBufferSend xMessageBufferSend - * \ingroup MessageBufferManagement - */ -#define xMessageBufferSend( xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) \ - xStreamBufferSend( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) - -/** - * message_buffer.h - * - *
- * size_t xMessageBufferSendFromISR( MessageBufferHandle_t xMessageBuffer,
- *                                const void *pvTxData,
- *                                size_t xDataLengthBytes,
- *                                BaseType_t *pxHigherPriorityTaskWoken );
- * 
- * - * Interrupt safe version of the API function that sends a discrete message to - * the message buffer. The message can be any length that fits within the - * buffer's free space, and is copied into the buffer. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xMessageBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xMessageBufferRead()) inside a critical section and set the receive - * block time to 0. - * - * Use xMessageBufferSend() to write to a message buffer from a task. Use - * xMessageBufferSendFromISR() to write to a message buffer from an interrupt - * service routine (ISR). - * - * @param xMessageBuffer The handle of the message buffer to which a message is - * being sent. - * - * @param pvTxData A pointer to the message that is to be copied into the - * message buffer. - * - * @param xDataLengthBytes The length of the message. That is, the number of - * bytes to copy from pvTxData into the message buffer. When a message is - * written to the message buffer an additional sizeof( size_t ) bytes are also - * written to store the message's length. sizeof( size_t ) is typically 4 bytes - * on a 32-bit architecture, so on most 32-bit architecture setting - * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 - * bytes (20 bytes of message data and 4 bytes to hold the message length). - * - * @param pxHigherPriorityTaskWoken It is possible that a message buffer will - * have a task blocked on it waiting for data. Calling - * xMessageBufferSendFromISR() can make data available, and so cause a task that - * was waiting for data to leave the Blocked state. If calling - * xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the - * unblocked task has a priority higher than the currently executing task (the - * task that was interrupted), then, internally, xMessageBufferSendFromISR() - * will set *pxHigherPriorityTaskWoken to pdTRUE. If - * xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a - * context switch should be performed before the interrupt is exited. This will - * ensure that the interrupt returns directly to the highest priority Ready - * state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it - * is passed into the function. See the code example below for an example. - * - * @return The number of bytes actually written to the message buffer. If the - * message buffer didn't have enough free space for the message to be stored - * then 0 is returned, otherwise xDataLengthBytes is returned. - * - * Example use: - *
- * // A message buffer that has already been created.
- * MessageBufferHandle_t xMessageBuffer;
- *
- * void vAnInterruptServiceRoutine( void )
- * {
- * size_t xBytesSent;
- * char *pcStringToSend = "String to send";
- * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.
- *
- *  // Attempt to send the string to the message buffer.
- *  xBytesSent = xMessageBufferSendFromISR( xMessageBuffer,
- *                                          ( void * ) pcStringToSend,
- *                                          strlen( pcStringToSend ),
- *                                          &xHigherPriorityTaskWoken );
- *
- *  if( xBytesSent != strlen( pcStringToSend ) )
- *  {
- *      // The string could not be added to the message buffer because there was
- *      // not enough free space in the buffer.
- *  }
- *
- *  // If xHigherPriorityTaskWoken was set to pdTRUE inside
- *  // xMessageBufferSendFromISR() then a task that has a priority above the
- *  // priority of the currently executing task was unblocked and a context
- *  // switch should be performed to ensure the ISR returns to the unblocked
- *  // task.  In most FreeRTOS ports this is done by simply passing
- *  // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the
- *  // variables value, and perform the context switch if necessary.  Check the
- *  // documentation for the port in use for port specific instructions.
- *  portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
- * }
- * 
- * \defgroup xMessageBufferSendFromISR xMessageBufferSendFromISR - * \ingroup MessageBufferManagement - */ -#define xMessageBufferSendFromISR( xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) \ - xStreamBufferSendFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) - -/** - * message_buffer.h - * - *
- * size_t xMessageBufferReceive( MessageBufferHandle_t xMessageBuffer,
- *                            void *pvRxData,
- *                            size_t xBufferLengthBytes,
- *                            TickType_t xTicksToWait );
- * 
- * - * Receives a discrete message from a message buffer. Messages can be of - * variable length and are copied out of the buffer. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xMessageBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xMessageBufferRead()) inside a critical section and set the receive - * block time to 0. - * - * Use xMessageBufferReceive() to read from a message buffer from a task. Use - * xMessageBufferReceiveFromISR() to read from a message buffer from an - * interrupt service routine (ISR). - * - * @param xMessageBuffer The handle of the message buffer from which a message - * is being received. - * - * @param pvRxData A pointer to the buffer into which the received message is - * to be copied. - * - * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData - * parameter. This sets the maximum length of the message that can be received. - * If xBufferLengthBytes is too small to hold the next message then the message - * will be left in the message buffer and 0 will be returned. - * - * @param xTicksToWait The maximum amount of time the task should remain in the - * Blocked state to wait for a message, should the message buffer be empty. - * xMessageBufferReceive() will return immediately if xTicksToWait is zero and - * the message buffer is empty. The block time is specified in tick periods, so - * the absolute time it represents is dependent on the tick frequency. The - * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds - * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will - * cause the task to wait indefinitely (without timing out), provided - * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any - * CPU time when they are in the Blocked state. - * - * @return The length, in bytes, of the message read from the message buffer, if - * any. If xMessageBufferReceive() times out before a message became available - * then zero is returned. If the length of the message is greater than - * xBufferLengthBytes then the message will be left in the message buffer and - * zero is returned. - * - * Example use: - *
- * void vAFunction( MessageBuffer_t xMessageBuffer )
- * {
- * uint8_t ucRxData[ 20 ];
- * size_t xReceivedBytes;
- * const TickType_t xBlockTime = pdMS_TO_TICKS( 20 );
- *
- *  // Receive the next message from the message buffer.  Wait in the Blocked
- *  // state (so not using any CPU processing time) for a maximum of 100ms for
- *  // a message to become available.
- *  xReceivedBytes = xMessageBufferReceive( xMessageBuffer,
- *                                          ( void * ) ucRxData,
- *                                          sizeof( ucRxData ),
- *                                          xBlockTime );
- *
- *  if( xReceivedBytes > 0 )
- *  {
- *      // A ucRxData contains a message that is xReceivedBytes long.  Process
- *      // the message here....
- *  }
- * }
- * 
- * \defgroup xMessageBufferReceive xMessageBufferReceive - * \ingroup MessageBufferManagement - */ -#define xMessageBufferReceive( xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) \ - xStreamBufferReceive( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) - - -/** - * message_buffer.h - * - *
- * size_t xMessageBufferReceiveFromISR( MessageBufferHandle_t xMessageBuffer,
- *                                   void *pvRxData,
- *                                   size_t xBufferLengthBytes,
- *                                   BaseType_t *pxHigherPriorityTaskWoken );
- * 
- * - * An interrupt safe version of the API function that receives a discrete - * message from a message buffer. Messages can be of variable length and are - * copied out of the buffer. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xMessageBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xMessageBufferRead()) inside a critical section and set the receive - * block time to 0. - * - * Use xMessageBufferReceive() to read from a message buffer from a task. Use - * xMessageBufferReceiveFromISR() to read from a message buffer from an - * interrupt service routine (ISR). - * - * @param xMessageBuffer The handle of the message buffer from which a message - * is being received. - * - * @param pvRxData A pointer to the buffer into which the received message is - * to be copied. - * - * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData - * parameter. This sets the maximum length of the message that can be received. - * If xBufferLengthBytes is too small to hold the next message then the message - * will be left in the message buffer and 0 will be returned. - * - * @param pxHigherPriorityTaskWoken It is possible that a message buffer will - * have a task blocked on it waiting for space to become available. Calling - * xMessageBufferReceiveFromISR() can make space available, and so cause a task - * that is waiting for space to leave the Blocked state. If calling - * xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and - * the unblocked task has a priority higher than the currently executing task - * (the task that was interrupted), then, internally, - * xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. - * If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a - * context switch should be performed before the interrupt is exited. That will - * ensure the interrupt returns directly to the highest priority Ready state - * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is - * passed into the function. See the code example below for an example. - * - * @return The length, in bytes, of the message read from the message buffer, if - * any. - * - * Example use: - *
- * // A message buffer that has already been created.
- * MessageBuffer_t xMessageBuffer;
- *
- * void vAnInterruptServiceRoutine( void )
- * {
- * uint8_t ucRxData[ 20 ];
- * size_t xReceivedBytes;
- * BaseType_t xHigherPriorityTaskWoken = pdFALSE;  // Initialised to pdFALSE.
- *
- *  // Receive the next message from the message buffer.
- *  xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer,
- *                                                ( void * ) ucRxData,
- *                                                sizeof( ucRxData ),
- *                                                &xHigherPriorityTaskWoken );
- *
- *  if( xReceivedBytes > 0 )
- *  {
- *      // A ucRxData contains a message that is xReceivedBytes long.  Process
- *      // the message here....
- *  }
- *
- *  // If xHigherPriorityTaskWoken was set to pdTRUE inside
- *  // xMessageBufferReceiveFromISR() then a task that has a priority above the
- *  // priority of the currently executing task was unblocked and a context
- *  // switch should be performed to ensure the ISR returns to the unblocked
- *  // task.  In most FreeRTOS ports this is done by simply passing
- *  // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the
- *  // variables value, and perform the context switch if necessary.  Check the
- *  // documentation for the port in use for port specific instructions.
- *  portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
- * }
- * 
- * \defgroup xMessageBufferReceiveFromISR xMessageBufferReceiveFromISR - * \ingroup MessageBufferManagement - */ -#define xMessageBufferReceiveFromISR( xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) \ - xStreamBufferReceiveFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) - -/** - * message_buffer.h - * - *
- * void vMessageBufferDelete( MessageBufferHandle_t xMessageBuffer );
- * 
- * - * Deletes a message buffer that was previously created using a call to - * xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message - * buffer was created using dynamic memory (that is, by xMessageBufferCreate()), - * then the allocated memory is freed. - * - * A message buffer handle must not be used after the message buffer has been - * deleted. - * - * @param xMessageBuffer The handle of the message buffer to be deleted. - * - */ -#define vMessageBufferDelete( xMessageBuffer ) \ - vStreamBufferDelete( ( StreamBufferHandle_t ) xMessageBuffer ) - -/** - * message_buffer.h - *
- * BaseType_t xMessageBufferIsFull( MessageBufferHandle_t xMessageBuffer ) );
- * 
- * - * Tests to see if a message buffer is full. A message buffer is full if it - * cannot accept any more messages, of any size, until space is made available - * by a message being removed from the message buffer. - * - * @param xMessageBuffer The handle of the message buffer being queried. - * - * @return If the message buffer referenced by xMessageBuffer is full then - * pdTRUE is returned. Otherwise pdFALSE is returned. - */ -#define xMessageBufferIsFull( xMessageBuffer ) \ - xStreamBufferIsFull( ( StreamBufferHandle_t ) xMessageBuffer ) - -/** - * message_buffer.h - *
- * BaseType_t xMessageBufferIsEmpty( MessageBufferHandle_t xMessageBuffer ) );
- * 
- * - * Tests to see if a message buffer is empty (does not contain any messages). - * - * @param xMessageBuffer The handle of the message buffer being queried. - * - * @return If the message buffer referenced by xMessageBuffer is empty then - * pdTRUE is returned. Otherwise pdFALSE is returned. - * - */ -#define xMessageBufferIsEmpty( xMessageBuffer ) \ - xStreamBufferIsEmpty( ( StreamBufferHandle_t ) xMessageBuffer ) - -/** - * message_buffer.h - *
- * BaseType_t xMessageBufferReset( MessageBufferHandle_t xMessageBuffer );
- * 
- * - * Resets a message buffer to its initial empty state, discarding any message it - * contained. - * - * A message buffer can only be reset if there are no tasks blocked on it. - * - * @param xMessageBuffer The handle of the message buffer being reset. - * - * @return If the message buffer was reset then pdPASS is returned. If the - * message buffer could not be reset because either there was a task blocked on - * the message queue to wait for space to become available, or to wait for a - * a message to be available, then pdFAIL is returned. - * - * \defgroup xMessageBufferReset xMessageBufferReset - * \ingroup MessageBufferManagement - */ -#define xMessageBufferReset( xMessageBuffer ) \ - xStreamBufferReset( ( StreamBufferHandle_t ) xMessageBuffer ) - - -/** - * message_buffer.h - *
- * size_t xMessageBufferSpaceAvailable( MessageBufferHandle_t xMessageBuffer ) );
- * 
- * Returns the number of bytes of free space in the message buffer. - * - * @param xMessageBuffer The handle of the message buffer being queried. - * - * @return The number of bytes that can be written to the message buffer before - * the message buffer would be full. When a message is written to the message - * buffer an additional sizeof( size_t ) bytes are also written to store the - * message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit - * architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size - * of the largest message that can be written to the message buffer is 6 bytes. - * - * \defgroup xMessageBufferSpaceAvailable xMessageBufferSpaceAvailable - * \ingroup MessageBufferManagement - */ -#define xMessageBufferSpaceAvailable( xMessageBuffer ) \ - xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer ) -#define xMessageBufferSpacesAvailable( xMessageBuffer ) \ - xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer ) /* Corrects typo in original macro name. */ - -/** - * message_buffer.h - *
- * size_t xMessageBufferNextLengthBytes( MessageBufferHandle_t xMessageBuffer ) );
- * 
- * Returns the length (in bytes) of the next message in a message buffer. - * Useful if xMessageBufferReceive() returned 0 because the size of the buffer - * passed into xMessageBufferReceive() was too small to hold the next message. - * - * @param xMessageBuffer The handle of the message buffer being queried. - * - * @return The length (in bytes) of the next message in the message buffer, or 0 - * if the message buffer is empty. - * - * \defgroup xMessageBufferNextLengthBytes xMessageBufferNextLengthBytes - * \ingroup MessageBufferManagement - */ -#define xMessageBufferNextLengthBytes( xMessageBuffer ) \ - xStreamBufferNextMessageLengthBytes( ( StreamBufferHandle_t ) xMessageBuffer ) PRIVILEGED_FUNCTION; - -/** - * message_buffer.h - * - *
- * BaseType_t xMessageBufferSendCompletedFromISR( MessageBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
- * 
- * - * For advanced users only. - * - * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when - * data is sent to a message buffer or stream buffer. If there was a task that - * was blocked on the message or stream buffer waiting for data to arrive then - * the sbSEND_COMPLETED() macro sends a notification to the task to remove it - * from the Blocked state. xMessageBufferSendCompletedFromISR() does the same - * thing. It is provided to enable application writers to implement their own - * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. - * - * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for - * additional information. - * - * @param xStreamBuffer The handle of the stream buffer to which data was - * written. - * - * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be - * initialised to pdFALSE before it is passed into - * xMessageBufferSendCompletedFromISR(). If calling - * xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, - * and the task has a priority above the priority of the currently running task, - * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a - * context switch should be performed before exiting the ISR. - * - * @return If a task was removed from the Blocked state then pdTRUE is returned. - * Otherwise pdFALSE is returned. - * - * \defgroup xMessageBufferSendCompletedFromISR xMessageBufferSendCompletedFromISR - * \ingroup StreamBufferManagement - */ -#define xMessageBufferSendCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) \ - xStreamBufferSendCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) - -/** - * message_buffer.h - * - *
- * BaseType_t xMessageBufferReceiveCompletedFromISR( MessageBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
- * 
- * - * For advanced users only. - * - * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when - * data is read out of a message buffer or stream buffer. If there was a task - * that was blocked on the message or stream buffer waiting for data to arrive - * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to - * remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR() - * does the same thing. It is provided to enable application writers to - * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT - * ANY OTHER TIME. - * - * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for - * additional information. - * - * @param xStreamBuffer The handle of the stream buffer from which data was - * read. - * - * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be - * initialised to pdFALSE before it is passed into - * xMessageBufferReceiveCompletedFromISR(). If calling - * xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, - * and the task has a priority above the priority of the currently running task, - * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a - * context switch should be performed before exiting the ISR. - * - * @return If a task was removed from the Blocked state then pdTRUE is returned. - * Otherwise pdFALSE is returned. - * - * \defgroup xMessageBufferReceiveCompletedFromISR xMessageBufferReceiveCompletedFromISR - * \ingroup StreamBufferManagement - */ -#define xMessageBufferReceiveCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) \ - xStreamBufferReceiveCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) - -/* *INDENT-OFF* */ -#if defined( __cplusplus ) - } /* extern "C" */ -#endif -/* *INDENT-ON* */ - -#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +/* + * Message buffers build functionality on top of FreeRTOS stream buffers. + * Whereas stream buffers are used to send a continuous stream of data from one + * task or interrupt to another, message buffers are used to send variable + * length discrete messages from one task or interrupt to another. Their + * implementation is light weight, making them particularly suited for interrupt + * to task and core to core communication scenarios. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * timeout to 0. + * + * Message buffers hold variable length messages. To enable that, when a + * message is written to the message buffer an additional sizeof( size_t ) bytes + * are also written to store the message's length (that happens internally, with + * the API function). sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so writing a 10 byte message to a message buffer on a 32-bit + * architecture will actually reduce the available space in the message buffer + * by 14 bytes (10 byte are used by the message, and 4 bytes to hold the length + * of the message). + */ + +#ifndef FREERTOS_MESSAGE_BUFFER_H +#define FREERTOS_MESSAGE_BUFFER_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include message_buffer.h" +#endif + +/* Message buffers are built onto of stream buffers. */ +#include "stream_buffer.h" + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + extern "C" { +#endif +/* *INDENT-ON* */ + +/** + * Type by which message buffers are referenced. For example, a call to + * xMessageBufferCreate() returns an MessageBufferHandle_t variable that can + * then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(), + * etc. Message buffer is essentially built as a stream buffer hence its handle + * is also set to same type as a stream buffer handle. + */ +typedef StreamBufferHandle_t MessageBufferHandle_t; + +/*-----------------------------------------------------------*/ + +/** + * message_buffer.h + * + * @code{c} + * MessageBufferHandle_t xMessageBufferCreate( size_t xBufferSizeBytes ); + * @endcode + * + * Creates a new message buffer using dynamically allocated memory. See + * xMessageBufferCreateStatic() for a version that uses statically allocated + * memory (memory that is allocated at compile time). + * + * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in + * FreeRTOSConfig.h for xMessageBufferCreate() to be available. + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferCreate() to be available. + * + * @param xBufferSizeBytes The total number of bytes (not messages) the message + * buffer will be able to hold at any one time. When a message is written to + * the message buffer an additional sizeof( size_t ) bytes are also written to + * store the message's length. sizeof( size_t ) is typically 4 bytes on a + * 32-bit architecture, so on most 32-bit architectures a 10 byte message will + * take up 14 bytes of message buffer space. + * + * @param pxSendCompletedCallback Callback invoked when a send operation to the + * message buffer is complete. If the parameter is NULL or xMessageBufferCreate() + * is called without the parameter, then it will use the default implementation + * provided by sbSEND_COMPLETED macro. To enable the callback, + * configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. + * + * @param pxReceiveCompletedCallback Callback invoked when a receive operation from + * the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() + * is called without the parameter, it will use the default implementation provided + * by sbRECEIVE_COMPLETED macro. To enable the callback, + * configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. + * + * @return If NULL is returned, then the message buffer cannot be created + * because there is insufficient heap memory available for FreeRTOS to allocate + * the message buffer data structures and storage area. A non-NULL value being + * returned indicates that the message buffer has been created successfully - + * the returned value should be stored as the handle to the created message + * buffer. + * + * Example use: + * @code{c} + * + * void vAFunction( void ) + * { + * MessageBufferHandle_t xMessageBuffer; + * const size_t xMessageBufferSizeBytes = 100; + * + * // Create a message buffer that can hold 100 bytes. The memory used to hold + * // both the message buffer structure and the messages themselves is allocated + * // dynamically. Each message added to the buffer consumes an additional 4 + * // bytes which are used to hold the length of the message. + * xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes ); + * + * if( xMessageBuffer == NULL ) + * { + * // There was not enough heap memory space available to create the + * // message buffer. + * } + * else + * { + * // The message buffer was created successfully and can now be used. + * } + * + * @endcode + * \defgroup xMessageBufferCreate xMessageBufferCreate + * \ingroup MessageBufferManagement + */ +#define xMessageBufferCreate( xBufferSizeBytes ) \ + xStreamBufferGenericCreate( ( xBufferSizeBytes ), ( size_t ) 0, sbTYPE_MESSAGE_BUFFER, NULL, NULL ) + +#if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + #define xMessageBufferCreateWithCallback( xBufferSizeBytes, pxSendCompletedCallback, pxReceiveCompletedCallback ) \ + xStreamBufferGenericCreate( ( xBufferSizeBytes ), ( size_t ) 0, sbTYPE_MESSAGE_BUFFER, ( pxSendCompletedCallback ), ( pxReceiveCompletedCallback ) ) +#endif + +/** + * message_buffer.h + * + * @code{c} + * MessageBufferHandle_t xMessageBufferCreateStatic( size_t xBufferSizeBytes, + * uint8_t *pucMessageBufferStorageArea, + * StaticMessageBuffer_t *pxStaticMessageBuffer ); + * @endcode + * Creates a new message buffer using statically allocated memory. See + * xMessageBufferCreate() for a version that uses dynamically allocated memory. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferCreateStatic() to be available. + * + * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the + * pucMessageBufferStorageArea parameter. When a message is written to the + * message buffer an additional sizeof( size_t ) bytes are also written to store + * the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so on most 32-bit architecture a 10 byte message will take up + * 14 bytes of message buffer space. The maximum number of bytes that can be + * stored in the message buffer is actually (xBufferSizeBytes - 1). + * + * @param pucMessageBufferStorageArea Must point to a uint8_t array that is at + * least xBufferSizeBytes big. This is the array to which messages are + * copied when they are written to the message buffer. + * + * @param pxStaticMessageBuffer Must point to a variable of type + * StaticMessageBuffer_t, which will be used to hold the message buffer's data + * structure. + * + * @param pxSendCompletedCallback Callback invoked when a new message is sent to the message buffer. + * If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default + * implementation provided by sbSEND_COMPLETED macro. To enable the callback, + * configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. + * + * @param pxReceiveCompletedCallback Callback invoked when a message is read from a + * message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will + * use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, + * configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. + * + * @return If the message buffer is created successfully then a handle to the + * created message buffer is returned. If either pucMessageBufferStorageArea or + * pxStaticmessageBuffer are NULL then NULL is returned. + * + * Example use: + * @code{c} + * + * // Used to dimension the array used to hold the messages. The available space + * // will actually be one less than this, so 999. + #define STORAGE_SIZE_BYTES 1000 + * + * // Defines the memory that will actually hold the messages within the message + * // buffer. + * static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; + * + * // The variable used to hold the message buffer structure. + * StaticMessageBuffer_t xMessageBufferStruct; + * + * void MyFunction( void ) + * { + * MessageBufferHandle_t xMessageBuffer; + * + * xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucStorageBuffer ), + * ucStorageBuffer, + * &xMessageBufferStruct ); + * + * // As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer + * // parameters were NULL, xMessageBuffer will not be NULL, and can be used to + * // reference the created message buffer in other message buffer API calls. + * + * // Other code that uses the message buffer can go here. + * } + * + * @endcode + * \defgroup xMessageBufferCreateStatic xMessageBufferCreateStatic + * \ingroup MessageBufferManagement + */ +#define xMessageBufferCreateStatic( xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer ) \ + xStreamBufferGenericCreateStatic( ( xBufferSizeBytes ), 0, sbTYPE_MESSAGE_BUFFER, ( pucMessageBufferStorageArea ), ( pxStaticMessageBuffer ), NULL, NULL ) + +#if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + #define xMessageBufferCreateStaticWithCallback( xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback ) \ + xStreamBufferGenericCreateStatic( ( xBufferSizeBytes ), 0, sbTYPE_MESSAGE_BUFFER, ( pucMessageBufferStorageArea ), ( pxStaticMessageBuffer ), ( pxSendCompletedCallback ), ( pxReceiveCompletedCallback ) ) +#endif + +/** + * message_buffer.h + * + * @code{c} + * BaseType_t xMessageBufferGetStaticBuffers( MessageBufferHandle_t xMessageBuffer, + * uint8_t ** ppucMessageBufferStorageArea, + * StaticMessageBuffer_t ** ppxStaticMessageBuffer ); + * @endcode + * + * Retrieve pointers to a statically created message buffer's data structure + * buffer and storage area buffer. These are the same buffers that are supplied + * at the time of creation. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferGetStaticBuffers() to be available. + * + * @param xMessageBuffer The message buffer for which to retrieve the buffers. + * + * @param ppucMessageBufferStorageArea Used to return a pointer to the + * message buffer's storage area buffer. + * + * @param ppxStaticMessageBuffer Used to return a pointer to the message + * buffer's data structure buffer. + * + * @return pdTRUE if buffers were retrieved, pdFALSE otherwise.. + * + * \defgroup xMessageBufferGetStaticBuffers xMessageBufferGetStaticBuffers + * \ingroup MessageBufferManagement + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xMessageBufferGetStaticBuffers( xMessageBuffer, ppucMessageBufferStorageArea, ppxStaticMessageBuffer ) \ + xStreamBufferGetStaticBuffers( ( xMessageBuffer ), ( ppucMessageBufferStorageArea ), ( ppxStaticMessageBuffer ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * message_buffer.h + * + * @code{c} + * size_t xMessageBufferSend( MessageBufferHandle_t xMessageBuffer, + * const void *pvTxData, + * size_t xDataLengthBytes, + * TickType_t xTicksToWait ); + * @endcode + * + * Sends a discrete message to the message buffer. The message can be any + * length that fits within the buffer's free space, and is copied into the + * buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferSend() to write to a message buffer from a task. Use + * xMessageBufferSendFromISR() to write to a message buffer from an interrupt + * service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferSend() to be available. + * + * @param xMessageBuffer The handle of the message buffer to which a message is + * being sent. + * + * @param pvTxData A pointer to the message that is to be copied into the + * message buffer. + * + * @param xDataLengthBytes The length of the message. That is, the number of + * bytes to copy from pvTxData into the message buffer. When a message is + * written to the message buffer an additional sizeof( size_t ) bytes are also + * written to store the message's length. sizeof( size_t ) is typically 4 bytes + * on a 32-bit architecture, so on most 32-bit architecture setting + * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 + * bytes (20 bytes of message data and 4 bytes to hold the message length). + * + * @param xTicksToWait The maximum amount of time the calling task should remain + * in the Blocked state to wait for enough space to become available in the + * message buffer, should the message buffer have insufficient space when + * xMessageBufferSend() is called. The calling task will never block if + * xTicksToWait is zero. The block time is specified in tick periods, so the + * absolute time it represents is dependent on the tick frequency. The macro + * pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into + * a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause + * the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any + * CPU time when they are in the Blocked state. + * + * @return The number of bytes written to the message buffer. If the call to + * xMessageBufferSend() times out before there was enough space to write the + * message into the message buffer then zero is returned. If the call did not + * time out then xDataLengthBytes is returned. + * + * Example use: + * @code{c} + * void vAFunction( MessageBufferHandle_t xMessageBuffer ) + * { + * size_t xBytesSent; + * uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; + * char *pcStringToSend = "String to send"; + * const TickType_t x100ms = pdMS_TO_TICKS( 100 ); + * + * // Send an array to the message buffer, blocking for a maximum of 100ms to + * // wait for enough space to be available in the message buffer. + * xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); + * + * if( xBytesSent != sizeof( ucArrayToSend ) ) + * { + * // The call to xMessageBufferSend() times out before there was enough + * // space in the buffer for the data to be written. + * } + * + * // Send the string to the message buffer. Return immediately if there is + * // not enough space in the buffer. + * xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // The string could not be added to the message buffer because there was + * // not enough free space in the buffer. + * } + * } + * @endcode + * \defgroup xMessageBufferSend xMessageBufferSend + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSend( xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) \ + xStreamBufferSend( ( xMessageBuffer ), ( pvTxData ), ( xDataLengthBytes ), ( xTicksToWait ) ) + +/** + * message_buffer.h + * + * @code{c} + * size_t xMessageBufferSendFromISR( MessageBufferHandle_t xMessageBuffer, + * const void *pvTxData, + * size_t xDataLengthBytes, + * BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * Interrupt safe version of the API function that sends a discrete message to + * the message buffer. The message can be any length that fits within the + * buffer's free space, and is copied into the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferSend() to write to a message buffer from a task. Use + * xMessageBufferSendFromISR() to write to a message buffer from an interrupt + * service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferSendFromISR() to be available. + * + * @param xMessageBuffer The handle of the message buffer to which a message is + * being sent. + * + * @param pvTxData A pointer to the message that is to be copied into the + * message buffer. + * + * @param xDataLengthBytes The length of the message. That is, the number of + * bytes to copy from pvTxData into the message buffer. When a message is + * written to the message buffer an additional sizeof( size_t ) bytes are also + * written to store the message's length. sizeof( size_t ) is typically 4 bytes + * on a 32-bit architecture, so on most 32-bit architecture setting + * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 + * bytes (20 bytes of message data and 4 bytes to hold the message length). + * + * @param pxHigherPriorityTaskWoken It is possible that a message buffer will + * have a task blocked on it waiting for data. Calling + * xMessageBufferSendFromISR() can make data available, and so cause a task that + * was waiting for data to leave the Blocked state. If calling + * xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the + * unblocked task has a priority higher than the currently executing task (the + * task that was interrupted), then, internally, xMessageBufferSendFromISR() + * will set *pxHigherPriorityTaskWoken to pdTRUE. If + * xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. This will + * ensure that the interrupt returns directly to the highest priority Ready + * state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it + * is passed into the function. See the code example below for an example. + * + * @return The number of bytes actually written to the message buffer. If the + * message buffer didn't have enough free space for the message to be stored + * then 0 is returned, otherwise xDataLengthBytes is returned. + * + * Example use: + * @code{c} + * // A message buffer that has already been created. + * MessageBufferHandle_t xMessageBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * size_t xBytesSent; + * char *pcStringToSend = "String to send"; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Attempt to send the string to the message buffer. + * xBytesSent = xMessageBufferSendFromISR( xMessageBuffer, + * ( void * ) pcStringToSend, + * strlen( pcStringToSend ), + * &xHigherPriorityTaskWoken ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // The string could not be added to the message buffer because there was + * // not enough free space in the buffer. + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xMessageBufferSendFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \defgroup xMessageBufferSendFromISR xMessageBufferSendFromISR + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSendFromISR( xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) \ + xStreamBufferSendFromISR( ( xMessageBuffer ), ( pvTxData ), ( xDataLengthBytes ), ( pxHigherPriorityTaskWoken ) ) + +/** + * message_buffer.h + * + * @code{c} + * size_t xMessageBufferReceive( MessageBufferHandle_t xMessageBuffer, + * void *pvRxData, + * size_t xBufferLengthBytes, + * TickType_t xTicksToWait ); + * @endcode + * + * Receives a discrete message from a message buffer. Messages can be of + * variable length and are copied out of the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferReceive() to read from a message buffer from a task. Use + * xMessageBufferReceiveFromISR() to read from a message buffer from an + * interrupt service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferReceive() to be available. + * + * @param xMessageBuffer The handle of the message buffer from which a message + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received message is + * to be copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData + * parameter. This sets the maximum length of the message that can be received. + * If xBufferLengthBytes is too small to hold the next message then the message + * will be left in the message buffer and 0 will be returned. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for a message, should the message buffer be empty. + * xMessageBufferReceive() will return immediately if xTicksToWait is zero and + * the message buffer is empty. The block time is specified in tick periods, so + * the absolute time it represents is dependent on the tick frequency. The + * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds + * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will + * cause the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any + * CPU time when they are in the Blocked state. + * + * @return The length, in bytes, of the message read from the message buffer, if + * any. If xMessageBufferReceive() times out before a message became available + * then zero is returned. If the length of the message is greater than + * xBufferLengthBytes then the message will be left in the message buffer and + * zero is returned. + * + * Example use: + * @code{c} + * void vAFunction( MessageBuffer_t xMessageBuffer ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); + * + * // Receive the next message from the message buffer. Wait in the Blocked + * // state (so not using any CPU processing time) for a maximum of 100ms for + * // a message to become available. + * xReceivedBytes = xMessageBufferReceive( xMessageBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * xBlockTime ); + * + * if( xReceivedBytes > 0 ) + * { + * // A ucRxData contains a message that is xReceivedBytes long. Process + * // the message here.... + * } + * } + * @endcode + * \defgroup xMessageBufferReceive xMessageBufferReceive + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReceive( xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) \ + xStreamBufferReceive( ( xMessageBuffer ), ( pvRxData ), ( xBufferLengthBytes ), ( xTicksToWait ) ) + + +/** + * message_buffer.h + * + * @code{c} + * size_t xMessageBufferReceiveFromISR( MessageBufferHandle_t xMessageBuffer, + * void *pvRxData, + * size_t xBufferLengthBytes, + * BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * An interrupt safe version of the API function that receives a discrete + * message from a message buffer. Messages can be of variable length and are + * copied out of the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferReceive() to read from a message buffer from a task. Use + * xMessageBufferReceiveFromISR() to read from a message buffer from an + * interrupt service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferReceiveFromISR() to be available. + * + * @param xMessageBuffer The handle of the message buffer from which a message + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received message is + * to be copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData + * parameter. This sets the maximum length of the message that can be received. + * If xBufferLengthBytes is too small to hold the next message then the message + * will be left in the message buffer and 0 will be returned. + * + * @param pxHigherPriorityTaskWoken It is possible that a message buffer will + * have a task blocked on it waiting for space to become available. Calling + * xMessageBufferReceiveFromISR() can make space available, and so cause a task + * that is waiting for space to leave the Blocked state. If calling + * xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and + * the unblocked task has a priority higher than the currently executing task + * (the task that was interrupted), then, internally, + * xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. + * If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. That will + * ensure the interrupt returns directly to the highest priority Ready state + * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is + * passed into the function. See the code example below for an example. + * + * @return The length, in bytes, of the message read from the message buffer, if + * any. + * + * Example use: + * @code{c} + * // A message buffer that has already been created. + * MessageBuffer_t xMessageBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Receive the next message from the message buffer. + * xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * &xHigherPriorityTaskWoken ); + * + * if( xReceivedBytes > 0 ) + * { + * // A ucRxData contains a message that is xReceivedBytes long. Process + * // the message here.... + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xMessageBufferReceiveFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \defgroup xMessageBufferReceiveFromISR xMessageBufferReceiveFromISR + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReceiveFromISR( xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) \ + xStreamBufferReceiveFromISR( ( xMessageBuffer ), ( pvRxData ), ( xBufferLengthBytes ), ( pxHigherPriorityTaskWoken ) ) + +/** + * message_buffer.h + * + * @code{c} + * void vMessageBufferDelete( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * + * Deletes a message buffer that was previously created using a call to + * xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message + * buffer was created using dynamic memory (that is, by xMessageBufferCreate()), + * then the allocated memory is freed. + * + * A message buffer handle must not be used after the message buffer has been + * deleted. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * vMessageBufferDelete() to be available. + * + * @param xMessageBuffer The handle of the message buffer to be deleted. + * + */ +#define vMessageBufferDelete( xMessageBuffer ) \ + vStreamBufferDelete( xMessageBuffer ) + +/** + * message_buffer.h + * @code{c} + * BaseType_t xMessageBufferIsFull( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * + * Tests to see if a message buffer is full. A message buffer is full if it + * cannot accept any more messages, of any size, until space is made available + * by a message being removed from the message buffer. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferIsFull() to be available. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return If the message buffer referenced by xMessageBuffer is full then + * pdTRUE is returned. Otherwise pdFALSE is returned. + */ +#define xMessageBufferIsFull( xMessageBuffer ) \ + xStreamBufferIsFull( xMessageBuffer ) + +/** + * message_buffer.h + * @code{c} + * BaseType_t xMessageBufferIsEmpty( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * + * Tests to see if a message buffer is empty (does not contain any messages). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferIsEmpty() to be available. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return If the message buffer referenced by xMessageBuffer is empty then + * pdTRUE is returned. Otherwise pdFALSE is returned. + * + */ +#define xMessageBufferIsEmpty( xMessageBuffer ) \ + xStreamBufferIsEmpty( xMessageBuffer ) + +/** + * message_buffer.h + * @code{c} + * BaseType_t xMessageBufferReset( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * + * Resets a message buffer to its initial empty state, discarding any message it + * contained. + * + * A message buffer can only be reset if there are no tasks blocked on it. + * + * Use xMessageBufferReset() to reset a message buffer from a task. + * Use xMessageBufferResetFromISR() to reset a message buffer from an + * interrupt service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferReset() to be available. + * + * @param xMessageBuffer The handle of the message buffer being reset. + * + * @return If the message buffer was reset then pdPASS is returned. If the + * message buffer could not be reset because either there was a task blocked on + * the message queue to wait for space to become available, or to wait for a + * a message to be available, then pdFAIL is returned. + * + * \defgroup xMessageBufferReset xMessageBufferReset + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReset( xMessageBuffer ) \ + xStreamBufferReset( xMessageBuffer ) + + +/** + * message_buffer.h + * @code{c} + * BaseType_t xMessageBufferResetFromISR( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * + * An interrupt safe version of the API function that resets the message buffer. + * Resets a message buffer to its initial empty state, discarding any message it + * contained. + * + * A message buffer can only be reset if there are no tasks blocked on it. + * + * Use xMessageBufferReset() to reset a message buffer from a task. + * Use xMessageBufferResetFromISR() to reset a message buffer from an + * interrupt service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferResetFromISR() to be available. + * + * @param xMessageBuffer The handle of the message buffer being reset. + * + * @return If the message buffer was reset then pdPASS is returned. If the + * message buffer could not be reset because either there was a task blocked on + * the message queue to wait for space to become available, or to wait for a + * a message to be available, then pdFAIL is returned. + * + * \defgroup xMessageBufferResetFromISR xMessageBufferResetFromISR + * \ingroup MessageBufferManagement + */ +#define xMessageBufferResetFromISR( xMessageBuffer ) \ + xStreamBufferResetFromISR( xMessageBuffer ) + +/** + * message_buffer.h + * @code{c} + * size_t xMessageBufferSpaceAvailable( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * Returns the number of bytes of free space in the message buffer. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferSpaceAvailable() to be available. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return The number of bytes that can be written to the message buffer before + * the message buffer would be full. When a message is written to the message + * buffer an additional sizeof( size_t ) bytes are also written to store the + * message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size + * of the largest message that can be written to the message buffer is 6 bytes. + * + * \defgroup xMessageBufferSpaceAvailable xMessageBufferSpaceAvailable + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSpaceAvailable( xMessageBuffer ) \ + xStreamBufferSpacesAvailable( xMessageBuffer ) +#define xMessageBufferSpacesAvailable( xMessageBuffer ) \ + xStreamBufferSpacesAvailable( xMessageBuffer ) /* Corrects typo in original macro name. */ + +/** + * message_buffer.h + * @code{c} + * size_t xMessageBufferNextLengthBytes( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * Returns the length (in bytes) of the next message in a message buffer. + * Useful if xMessageBufferReceive() returned 0 because the size of the buffer + * passed into xMessageBufferReceive() was too small to hold the next message. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferNextLengthBytes() to be available. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return The length (in bytes) of the next message in the message buffer, or 0 + * if the message buffer is empty. + * + * \defgroup xMessageBufferNextLengthBytes xMessageBufferNextLengthBytes + * \ingroup MessageBufferManagement + */ +#define xMessageBufferNextLengthBytes( xMessageBuffer ) \ + xStreamBufferNextMessageLengthBytes( xMessageBuffer ) + +/** + * message_buffer.h + * + * @code{c} + * BaseType_t xMessageBufferSendCompletedFromISR( MessageBufferHandle_t xMessageBuffer, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * For advanced users only. + * + * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is sent to a message buffer or stream buffer. If there was a task that + * was blocked on the message or stream buffer waiting for data to arrive then + * the sbSEND_COMPLETED() macro sends a notification to the task to remove it + * from the Blocked state. xMessageBufferSendCompletedFromISR() does the same + * thing. It is provided to enable application writers to implement their own + * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferSendCompletedFromISR() to be available. + * + * @param xMessageBuffer The handle of the stream buffer to which data was + * written. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xMessageBufferSendCompletedFromISR(). If calling + * xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xMessageBufferSendCompletedFromISR xMessageBufferSendCompletedFromISR + * \ingroup StreamBufferManagement + */ +#define xMessageBufferSendCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) \ + xStreamBufferSendCompletedFromISR( ( xMessageBuffer ), ( pxHigherPriorityTaskWoken ) ) + +/** + * message_buffer.h + * + * @code{c} + * BaseType_t xMessageBufferReceiveCompletedFromISR( MessageBufferHandle_t xMessageBuffer, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * For advanced users only. + * + * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is read out of a message buffer or stream buffer. If there was a task + * that was blocked on the message or stream buffer waiting for data to arrive + * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to + * remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR() + * does the same thing. It is provided to enable application writers to + * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT + * ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xMessageBufferReceiveCompletedFromISR() to be available. + * + * @param xMessageBuffer The handle of the stream buffer from which data was + * read. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xMessageBufferReceiveCompletedFromISR(). If calling + * xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xMessageBufferReceiveCompletedFromISR xMessageBufferReceiveCompletedFromISR + * \ingroup StreamBufferManagement + */ +#define xMessageBufferReceiveCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) \ + xStreamBufferReceiveCompletedFromISR( ( xMessageBuffer ), ( pxHigherPriorityTaskWoken ) ) + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + } /* extern "C" */ +#endif +/* *INDENT-ON* */ + +#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_prototypes.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_prototypes.h index d95dcd8c4..0f42d6b91 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_prototypes.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_prototypes.h @@ -1,263 +1,389 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -/* - * When the MPU is used the standard (non MPU) API functions are mapped to - * equivalents that start "MPU_", the prototypes for which are defined in this - * header files. This will cause the application code to call the MPU_ version - * which wraps the non-MPU version with privilege promoting then demoting code, - * so the kernel code always runs will full privileges. - */ - - -#ifndef MPU_PROTOTYPES_H -#define MPU_PROTOTYPES_H - -/* MPU versions of tasks.h API functions. */ -BaseType_t MPU_xTaskCreate( TaskFunction_t pxTaskCode, - const char * const pcName, - const uint16_t usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask ) FREERTOS_SYSTEM_CALL; -TaskHandle_t MPU_xTaskCreateStatic( TaskFunction_t pxTaskCode, - const char * const pcName, - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - StackType_t * const puxStackBuffer, - StaticTask_t * const pxTaskBuffer ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, - TaskHandle_t * pxCreatedTask ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, - TaskHandle_t * pxCreatedTask ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskAllocateMPURegions( TaskHandle_t xTask, - const MemoryRegion_t * const pxRegions ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskDelete( TaskHandle_t xTaskToDelete ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskDelay( const TickType_t xTicksToDelay ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, - const TickType_t xTimeIncrement ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskAbortDelay( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; -UBaseType_t MPU_uxTaskPriorityGet( const TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; -eTaskState MPU_eTaskGetState( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskGetInfo( TaskHandle_t xTask, - TaskStatus_t * pxTaskStatus, - BaseType_t xGetFreeStackSpace, - eTaskState eState ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskPrioritySet( TaskHandle_t xTask, - UBaseType_t uxNewPriority ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskSuspend( TaskHandle_t xTaskToSuspend ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskResume( TaskHandle_t xTaskToResume ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskStartScheduler( void ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskSuspendAll( void ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskResumeAll( void ) FREERTOS_SYSTEM_CALL; -TickType_t MPU_xTaskGetTickCount( void ) FREERTOS_SYSTEM_CALL; -UBaseType_t MPU_uxTaskGetNumberOfTasks( void ) FREERTOS_SYSTEM_CALL; -char * MPU_pcTaskGetName( TaskHandle_t xTaskToQuery ) FREERTOS_SYSTEM_CALL; -TaskHandle_t MPU_xTaskGetHandle( const char * pcNameToQuery ) FREERTOS_SYSTEM_CALL; -UBaseType_t MPU_uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; -configSTACK_DEPTH_TYPE MPU_uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskSetApplicationTaskTag( TaskHandle_t xTask, - TaskHookFunction_t pxHookFunction ) FREERTOS_SYSTEM_CALL; -TaskHookFunction_t MPU_xTaskGetApplicationTaskTag( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, - BaseType_t xIndex, - void * pvValue ) FREERTOS_SYSTEM_CALL; -void * MPU_pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, - BaseType_t xIndex ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskCallApplicationTaskHook( TaskHandle_t xTask, - void * pvParameter ) FREERTOS_SYSTEM_CALL; -TaskHandle_t MPU_xTaskGetIdleTaskHandle( void ) FREERTOS_SYSTEM_CALL; -UBaseType_t MPU_uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, - const UBaseType_t uxArraySize, - uint32_t * const pulTotalRunTime ) FREERTOS_SYSTEM_CALL; -uint32_t MPU_ulTaskGetIdleRunTimeCounter( void ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskList( char * pcWriteBuffer ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskGetRunTimeStats( char * pcWriteBuffer ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskGenericNotify( TaskHandle_t xTaskToNotify, - UBaseType_t uxIndexToNotify, - uint32_t ulValue, - eNotifyAction eAction, - uint32_t * pulPreviousNotificationValue ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, - uint32_t ulBitsToClearOnEntry, - uint32_t ulBitsToClearOnExit, - uint32_t * pulNotificationValue, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -uint32_t MPU_ulTaskGenericNotifyTake( UBaseType_t uxIndexToWaitOn, - BaseType_t xClearCountOnExit, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskGenericNotifyStateClear( TaskHandle_t xTask, - UBaseType_t uxIndexToClear ) FREERTOS_SYSTEM_CALL; -uint32_t MPU_ulTaskGenericNotifyValueClear( TaskHandle_t xTask, - UBaseType_t uxIndexToClear, - uint32_t ulBitsToClear ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskIncrementTick( void ) FREERTOS_SYSTEM_CALL; -TaskHandle_t MPU_xTaskGetCurrentTaskHandle( void ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, - TickType_t * const pxTicksToWait ) FREERTOS_SYSTEM_CALL; -void MPU_vTaskMissedYield( void ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskGetSchedulerState( void ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) FREERTOS_SYSTEM_CALL; - -/* MPU versions of queue.h API functions. */ -BaseType_t MPU_xQueueGenericSend( QueueHandle_t xQueue, - const void * const pvItemToQueue, - TickType_t xTicksToWait, - const BaseType_t xCopyPosition ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xQueueReceive( QueueHandle_t xQueue, - void * const pvBuffer, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xQueuePeek( QueueHandle_t xQueue, - void * const pvBuffer, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xQueueSemaphoreTake( QueueHandle_t xQueue, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -UBaseType_t MPU_uxQueueMessagesWaiting( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; -UBaseType_t MPU_uxQueueSpacesAvailable( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; -void MPU_vQueueDelete( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; -QueueHandle_t MPU_xQueueCreateMutex( const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; -QueueHandle_t MPU_xQueueCreateMutexStatic( const uint8_t ucQueueType, - StaticQueue_t * pxStaticQueue ) FREERTOS_SYSTEM_CALL; -QueueHandle_t MPU_xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, - const UBaseType_t uxInitialCount ) FREERTOS_SYSTEM_CALL; -QueueHandle_t MPU_xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, - const UBaseType_t uxInitialCount, - StaticQueue_t * pxStaticQueue ) FREERTOS_SYSTEM_CALL; -TaskHandle_t MPU_xQueueGetMutexHolder( QueueHandle_t xSemaphore ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xQueueTakeMutexRecursive( QueueHandle_t xMutex, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xQueueGiveMutexRecursive( QueueHandle_t pxMutex ) FREERTOS_SYSTEM_CALL; -void MPU_vQueueAddToRegistry( QueueHandle_t xQueue, - const char * pcName ) FREERTOS_SYSTEM_CALL; -void MPU_vQueueUnregisterQueue( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; -const char * MPU_pcQueueGetName( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; -QueueHandle_t MPU_xQueueGenericCreate( const UBaseType_t uxQueueLength, - const UBaseType_t uxItemSize, - const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; -QueueHandle_t MPU_xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, - const UBaseType_t uxItemSize, - uint8_t * pucQueueStorage, - StaticQueue_t * pxStaticQueue, - const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; -QueueSetHandle_t MPU_xQueueCreateSet( const UBaseType_t uxEventQueueLength ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, - QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, - QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL; -QueueSetMemberHandle_t MPU_xQueueSelectFromSet( QueueSetHandle_t xQueueSet, - const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xQueueGenericReset( QueueHandle_t xQueue, - BaseType_t xNewQueue ) FREERTOS_SYSTEM_CALL; -void MPU_vQueueSetQueueNumber( QueueHandle_t xQueue, - UBaseType_t uxQueueNumber ) FREERTOS_SYSTEM_CALL; -UBaseType_t MPU_uxQueueGetQueueNumber( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; -uint8_t MPU_ucQueueGetQueueType( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; - -/* MPU versions of timers.h API functions. */ -TimerHandle_t MPU_xTimerCreate( const char * const pcTimerName, - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction ) FREERTOS_SYSTEM_CALL; -TimerHandle_t MPU_xTimerCreateStatic( const char * const pcTimerName, - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - StaticTimer_t * pxTimerBuffer ) FREERTOS_SYSTEM_CALL; -void * MPU_pvTimerGetTimerID( const TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; -void MPU_vTimerSetTimerID( TimerHandle_t xTimer, - void * pvNewID ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTimerIsTimerActive( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; -TaskHandle_t MPU_xTimerGetTimerDaemonTaskHandle( void ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, - void * pvParameter1, - uint32_t ulParameter2, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -const char * MPU_pcTimerGetName( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; -void MPU_vTimerSetReloadMode( TimerHandle_t xTimer, - const UBaseType_t uxAutoReload ) FREERTOS_SYSTEM_CALL; -UBaseType_t MPU_uxTimerGetReloadMode( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; -TickType_t MPU_xTimerGetPeriod( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; -TickType_t MPU_xTimerGetExpiryTime( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTimerCreateTimerTask( void ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xTimerGenericCommand( TimerHandle_t xTimer, - const BaseType_t xCommandID, - const TickType_t xOptionalValue, - BaseType_t * const pxHigherPriorityTaskWoken, - const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; - -/* MPU versions of event_group.h API functions. */ -EventGroupHandle_t MPU_xEventGroupCreate( void ) FREERTOS_SYSTEM_CALL; -EventGroupHandle_t MPU_xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) FREERTOS_SYSTEM_CALL; -EventBits_t MPU_xEventGroupWaitBits( EventGroupHandle_t xEventGroup, - const EventBits_t uxBitsToWaitFor, - const BaseType_t xClearOnExit, - const BaseType_t xWaitForAllBits, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -EventBits_t MPU_xEventGroupClearBits( EventGroupHandle_t xEventGroup, - const EventBits_t uxBitsToClear ) FREERTOS_SYSTEM_CALL; -EventBits_t MPU_xEventGroupSetBits( EventGroupHandle_t xEventGroup, - const EventBits_t uxBitsToSet ) FREERTOS_SYSTEM_CALL; -EventBits_t MPU_xEventGroupSync( EventGroupHandle_t xEventGroup, - const EventBits_t uxBitsToSet, - const EventBits_t uxBitsToWaitFor, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -void MPU_vEventGroupDelete( EventGroupHandle_t xEventGroup ) FREERTOS_SYSTEM_CALL; -UBaseType_t MPU_uxEventGroupGetNumber( void * xEventGroup ) FREERTOS_SYSTEM_CALL; - -/* MPU versions of message/stream_buffer.h API functions. */ -size_t MPU_xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -size_t MPU_xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, - void * pvRxData, - size_t xBufferLengthBytes, - TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; -size_t MPU_xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; -void MPU_vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; -size_t MPU_xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; -size_t MPU_xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; -BaseType_t MPU_xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, - size_t xTriggerLevel ) FREERTOS_SYSTEM_CALL; -StreamBufferHandle_t MPU_xStreamBufferGenericCreate( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer ) FREERTOS_SYSTEM_CALL; -StreamBufferHandle_t MPU_xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer, - uint8_t * const pucStreamBufferStorageArea, - StaticStreamBuffer_t * const pxStaticStreamBuffer ) FREERTOS_SYSTEM_CALL; - - - -#endif /* MPU_PROTOTYPES_H */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * When the MPU is used the standard (non MPU) API functions are mapped to + * equivalents that start "MPU_", the prototypes for which are defined in this + * header files. This will cause the application code to call the MPU_ version + * which wraps the non-MPU version with privilege promoting then demoting code, + * so the kernel code always runs will full privileges. + */ + + +#ifndef MPU_PROTOTYPES_H +#define MPU_PROTOTYPES_H + +typedef struct xTaskGenericNotifyParams +{ + TaskHandle_t xTaskToNotify; + UBaseType_t uxIndexToNotify; + uint32_t ulValue; + eNotifyAction eAction; + uint32_t * pulPreviousNotificationValue; +} xTaskGenericNotifyParams_t; + +typedef struct xTaskGenericNotifyWaitParams +{ + UBaseType_t uxIndexToWaitOn; + uint32_t ulBitsToClearOnEntry; + uint32_t ulBitsToClearOnExit; + uint32_t * pulNotificationValue; + TickType_t xTicksToWait; +} xTaskGenericNotifyWaitParams_t; + +typedef struct xTimerGenericCommandFromTaskParams +{ + TimerHandle_t xTimer; + BaseType_t xCommandID; + TickType_t xOptionalValue; + BaseType_t * pxHigherPriorityTaskWoken; + TickType_t xTicksToWait; +} xTimerGenericCommandFromTaskParams_t; + +typedef struct xEventGroupWaitBitsParams +{ + EventGroupHandle_t xEventGroup; + EventBits_t uxBitsToWaitFor; + BaseType_t xClearOnExit; + BaseType_t xWaitForAllBits; + TickType_t xTicksToWait; +} xEventGroupWaitBitsParams_t; + +/* MPU versions of task.h API functions. */ +void MPU_vTaskDelay( const TickType_t xTicksToDelay ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskDelayUntil( TickType_t * const pxPreviousWakeTime, + const TickType_t xTimeIncrement ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskAbortDelay( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskPriorityGet( const TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +eTaskState MPU_eTaskGetState( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskGetInfo( TaskHandle_t xTask, + TaskStatus_t * pxTaskStatus, + BaseType_t xGetFreeStackSpace, + eTaskState eState ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSuspend( TaskHandle_t xTaskToSuspend ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskResume( TaskHandle_t xTaskToResume ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTaskGetTickCount( void ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetNumberOfTasks( void ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +configSTACK_DEPTH_TYPE MPU_uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetApplicationTaskTag( TaskHandle_t xTask, + TaskHookFunction_t pxHookFunction ) FREERTOS_SYSTEM_CALL; +TaskHookFunction_t MPU_xTaskGetApplicationTaskTag( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, + BaseType_t xIndex, + void * pvValue ) FREERTOS_SYSTEM_CALL; +void * MPU_pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, + BaseType_t xIndex ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetIdleTaskHandle( void ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, + const UBaseType_t uxArraySize, + configRUN_TIME_COUNTER_TYPE * const pulTotalRunTime ) FREERTOS_SYSTEM_CALL; +configRUN_TIME_COUNTER_TYPE MPU_ulTaskGetRunTimeCounter( const TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +configRUN_TIME_COUNTER_TYPE MPU_ulTaskGetRunTimePercent( const TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +configRUN_TIME_COUNTER_TYPE MPU_ulTaskGetIdleRunTimeCounter( void ) FREERTOS_SYSTEM_CALL; +configRUN_TIME_COUNTER_TYPE MPU_ulTaskGetIdleRunTimePercent( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotify( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotifyEntry( const xTaskGenericNotifyParams_t * pxParams ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, + uint32_t ulBitsToClearOnEntry, + uint32_t ulBitsToClearOnExit, + uint32_t * pulNotificationValue, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotifyWaitEntry( const xTaskGenericNotifyWaitParams_t * pxParams ) FREERTOS_SYSTEM_CALL; +uint32_t MPU_ulTaskGenericNotifyTake( UBaseType_t uxIndexToWaitOn, + BaseType_t xClearCountOnExit, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotifyStateClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear ) FREERTOS_SYSTEM_CALL; +uint32_t MPU_ulTaskGenericNotifyValueClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear, + uint32_t ulBitsToClear ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, + TickType_t * const pxTicksToWait ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetCurrentTaskHandle( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGetSchedulerState( void ) FREERTOS_SYSTEM_CALL; + +/* Privileged only wrappers for Task APIs. These are needed so that + * the application can use opaque handles maintained in mpu_wrappers.c + * with all the APIs. */ +BaseType_t MPU_xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; +TaskHandle_t MPU_xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) PRIVILEGED_FUNCTION; +void MPU_vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION; +void MPU_vTaskPrioritySet( TaskHandle_t xTask, + UBaseType_t uxNewPriority ) PRIVILEGED_FUNCTION; +TaskHandle_t MPU_xTaskGetHandle( const char * pcNameToQuery ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xTaskCallApplicationTaskHook( TaskHandle_t xTask, + void * pvParameter ) PRIVILEGED_FUNCTION; +char * MPU_pcTaskGetName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * pxCreatedTask ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * pxCreatedTask ) PRIVILEGED_FUNCTION; +void MPU_vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, + const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xTaskGetStaticBuffers( TaskHandle_t xTask, + StackType_t ** ppuxStackBuffer, + StaticTask_t ** ppxTaskBuffer ) PRIVILEGED_FUNCTION; +UBaseType_t MPU_uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +UBaseType_t MPU_uxTaskBasePriorityGet( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +UBaseType_t MPU_uxTaskBasePriorityGetFromISR( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; +TaskHookFunction_t MPU_xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +void MPU_vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/* MPU versions of queue.h API functions. */ +BaseType_t MPU_xQueueGenericSend( QueueHandle_t xQueue, + const void * const pvItemToQueue, + TickType_t xTicksToWait, + const BaseType_t xCopyPosition ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueReceive( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueuePeek( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueSemaphoreTake( QueueHandle_t xQueue, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueMessagesWaiting( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueSpacesAvailable( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xQueueGetMutexHolder( QueueHandle_t xSemaphore ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueTakeMutexRecursive( QueueHandle_t xMutex, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueGiveMutexRecursive( QueueHandle_t pxMutex ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueAddToRegistry( QueueHandle_t xQueue, + const char * pcName ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueUnregisterQueue( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +const char * MPU_pcQueueGetName( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL; +QueueSetMemberHandle_t MPU_xQueueSelectFromSet( QueueSetHandle_t xQueueSet, + const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueSetQueueNumber( QueueHandle_t xQueue, + UBaseType_t uxQueueNumber ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueGetQueueNumber( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +uint8_t MPU_ucQueueGetQueueType( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; + +/* Privileged only wrappers for Queue APIs. These are needed so that + * the application can use opaque handles maintained in mpu_wrappers.c + * with all the APIs. */ +void MPU_vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +QueueHandle_t MPU_xQueueCreateMutex( const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +QueueHandle_t MPU_xQueueCreateMutexStatic( const uint8_t ucQueueType, + StaticQueue_t * pxStaticQueue ) PRIVILEGED_FUNCTION; +QueueHandle_t MPU_xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount ) PRIVILEGED_FUNCTION; +QueueHandle_t MPU_xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount, + StaticQueue_t * pxStaticQueue ) PRIVILEGED_FUNCTION; +QueueHandle_t MPU_xQueueGenericCreate( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +QueueHandle_t MPU_xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + StaticQueue_t * pxStaticQueue, + const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +QueueSetHandle_t MPU_xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xQueueGenericReset( QueueHandle_t xQueue, + BaseType_t xNewQueue ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xQueueGenericGetStaticBuffers( QueueHandle_t xQueue, + uint8_t ** ppucQueueStorage, + StaticQueue_t ** ppxStaticQueue ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xQueueGenericSendFromISR( QueueHandle_t xQueue, + const void * const pvItemToQueue, + BaseType_t * const pxHigherPriorityTaskWoken, + const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xQueueGiveFromISR( QueueHandle_t xQueue, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xQueuePeekFromISR( QueueHandle_t xQueue, + void * const pvBuffer ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xQueueReceiveFromISR( QueueHandle_t xQueue, + void * const pvBuffer, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +UBaseType_t MPU_uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +TaskHandle_t MPU_xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; +QueueSetMemberHandle_t MPU_xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/* MPU versions of timers.h API functions. */ +void * MPU_pvTimerGetTimerID( const TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +void MPU_vTimerSetTimerID( TimerHandle_t xTimer, + void * pvNewID ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerIsTimerActive( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTimerGetTimerDaemonTaskHandle( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerGenericCommandFromTask( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerGenericCommandFromTaskEntry( const xTimerGenericCommandFromTaskParams_t * pxParams ) FREERTOS_SYSTEM_CALL; +const char * MPU_pcTimerGetName( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +void MPU_vTimerSetReloadMode( TimerHandle_t xTimer, + const BaseType_t uxAutoReload ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerGetReloadMode( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTimerGetReloadMode( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTimerGetPeriod( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTimerGetExpiryTime( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; + +/* Privileged only wrappers for Timer APIs. These are needed so that + * the application can use opaque handles maintained in mpu_wrappers.c + * with all the APIs. */ +TimerHandle_t MPU_xTimerCreate( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; +TimerHandle_t MPU_xTimerCreateStatic( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t * pxTimerBuffer ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xTimerGetStaticBuffer( TimerHandle_t xTimer, + StaticTimer_t ** ppxTimerBuffer ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xTimerGenericCommandFromISR( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/* MPU versions of event_group.h API functions. */ +EventBits_t MPU_xEventGroupWaitBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xClearOnExit, + const BaseType_t xWaitForAllBits, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupWaitBitsEntry( const xEventGroupWaitBitsParams_t * pxParams ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupClearBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupSetBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupSync( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + const EventBits_t uxBitsToWaitFor, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +#if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t MPU_uxEventGroupGetNumber( void * xEventGroup ) FREERTOS_SYSTEM_CALL; + void MPU_vEventGroupSetNumber( void * xEventGroup, + UBaseType_t uxEventGroupNumber ) FREERTOS_SYSTEM_CALL; +#endif /* ( configUSE_TRACE_FACILITY == 1 )*/ + +/* Privileged only wrappers for Event Group APIs. These are needed so that + * the application can use opaque handles maintained in mpu_wrappers.c + * with all the APIs. */ +EventGroupHandle_t MPU_xEventGroupCreate( void ) PRIVILEGED_FUNCTION; +EventGroupHandle_t MPU_xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) PRIVILEGED_FUNCTION; +void MPU_vEventGroupDelete( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xEventGroupGetStaticBuffer( EventGroupHandle_t xEventGroup, + StaticEventGroup_t ** ppxEventGroupBuffer ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +EventBits_t MPU_xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; + +/* MPU versions of message/stream_buffer.h API functions. */ +size_t MPU_xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, + size_t xTriggerLevel ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; + +/* Privileged only wrappers for Stream Buffer APIs. These are needed so that + * the application can use opaque handles maintained in mpu_wrappers.c + * with all the APIs. */ +StreamBufferHandle_t MPU_xStreamBufferGenericCreate( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xStreamBufferType, + StreamBufferCallbackFunction_t pxSendCompletedCallback, + StreamBufferCallbackFunction_t pxReceiveCompletedCallback ) PRIVILEGED_FUNCTION; +StreamBufferHandle_t MPU_xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xStreamBufferType, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer, + StreamBufferCallbackFunction_t pxSendCompletedCallback, + StreamBufferCallbackFunction_t pxReceiveCompletedCallback ) PRIVILEGED_FUNCTION; +void MPU_vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xStreamBufferGetStaticBuffers( StreamBufferHandle_t xStreamBuffers, + uint8_t * ppucStreamBufferStorageArea, + StaticStreamBuffer_t * ppxStaticStreamBuffer ) PRIVILEGED_FUNCTION; +size_t MPU_xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +size_t MPU_xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +BaseType_t MPU_xStreamBufferResetFromISR( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +#endif /* MPU_PROTOTYPES_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_syscall_numbers.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_syscall_numbers.h new file mode 100644 index 000000000..820923429 --- /dev/null +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_syscall_numbers.h @@ -0,0 +1,105 @@ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef MPU_SYSCALL_NUMBERS_H +#define MPU_SYSCALL_NUMBERS_H + +/* Numbers assigned to various system calls. */ +#define SYSTEM_CALL_xTaskGenericNotify 0 +#define SYSTEM_CALL_xTaskGenericNotifyWait 1 +#define SYSTEM_CALL_xTimerGenericCommandFromTask 2 +#define SYSTEM_CALL_xEventGroupWaitBits 3 +#define SYSTEM_CALL_xTaskDelayUntil 4 +#define SYSTEM_CALL_xTaskAbortDelay 5 +#define SYSTEM_CALL_vTaskDelay 6 +#define SYSTEM_CALL_uxTaskPriorityGet 7 +#define SYSTEM_CALL_eTaskGetState 8 +#define SYSTEM_CALL_vTaskGetInfo 9 +#define SYSTEM_CALL_xTaskGetIdleTaskHandle 10 +#define SYSTEM_CALL_vTaskSuspend 11 +#define SYSTEM_CALL_vTaskResume 12 +#define SYSTEM_CALL_xTaskGetTickCount 13 +#define SYSTEM_CALL_uxTaskGetNumberOfTasks 14 +#define SYSTEM_CALL_ulTaskGetRunTimeCounter 15 +#define SYSTEM_CALL_ulTaskGetRunTimePercent 16 +#define SYSTEM_CALL_ulTaskGetIdleRunTimePercent 17 +#define SYSTEM_CALL_ulTaskGetIdleRunTimeCounter 18 +#define SYSTEM_CALL_vTaskSetApplicationTaskTag 19 +#define SYSTEM_CALL_xTaskGetApplicationTaskTag 20 +#define SYSTEM_CALL_vTaskSetThreadLocalStoragePointer 21 +#define SYSTEM_CALL_pvTaskGetThreadLocalStoragePointer 22 +#define SYSTEM_CALL_uxTaskGetSystemState 23 +#define SYSTEM_CALL_uxTaskGetStackHighWaterMark 24 +#define SYSTEM_CALL_uxTaskGetStackHighWaterMark2 25 +#define SYSTEM_CALL_xTaskGetCurrentTaskHandle 26 +#define SYSTEM_CALL_xTaskGetSchedulerState 27 +#define SYSTEM_CALL_vTaskSetTimeOutState 28 +#define SYSTEM_CALL_xTaskCheckForTimeOut 29 +#define SYSTEM_CALL_ulTaskGenericNotifyTake 30 +#define SYSTEM_CALL_xTaskGenericNotifyStateClear 31 +#define SYSTEM_CALL_ulTaskGenericNotifyValueClear 32 +#define SYSTEM_CALL_xQueueGenericSend 33 +#define SYSTEM_CALL_uxQueueMessagesWaiting 34 +#define SYSTEM_CALL_uxQueueSpacesAvailable 35 +#define SYSTEM_CALL_xQueueReceive 36 +#define SYSTEM_CALL_xQueuePeek 37 +#define SYSTEM_CALL_xQueueSemaphoreTake 38 +#define SYSTEM_CALL_xQueueGetMutexHolder 39 +#define SYSTEM_CALL_xQueueTakeMutexRecursive 40 +#define SYSTEM_CALL_xQueueGiveMutexRecursive 41 +#define SYSTEM_CALL_xQueueSelectFromSet 42 +#define SYSTEM_CALL_xQueueAddToSet 43 +#define SYSTEM_CALL_vQueueAddToRegistry 44 +#define SYSTEM_CALL_vQueueUnregisterQueue 45 +#define SYSTEM_CALL_pcQueueGetName 46 +#define SYSTEM_CALL_pvTimerGetTimerID 47 +#define SYSTEM_CALL_vTimerSetTimerID 48 +#define SYSTEM_CALL_xTimerIsTimerActive 49 +#define SYSTEM_CALL_xTimerGetTimerDaemonTaskHandle 50 +#define SYSTEM_CALL_pcTimerGetName 51 +#define SYSTEM_CALL_vTimerSetReloadMode 52 +#define SYSTEM_CALL_xTimerGetReloadMode 53 +#define SYSTEM_CALL_uxTimerGetReloadMode 54 +#define SYSTEM_CALL_xTimerGetPeriod 55 +#define SYSTEM_CALL_xTimerGetExpiryTime 56 +#define SYSTEM_CALL_xEventGroupClearBits 57 +#define SYSTEM_CALL_xEventGroupSetBits 58 +#define SYSTEM_CALL_xEventGroupSync 59 +#define SYSTEM_CALL_uxEventGroupGetNumber 60 +#define SYSTEM_CALL_vEventGroupSetNumber 61 +#define SYSTEM_CALL_xStreamBufferSend 62 +#define SYSTEM_CALL_xStreamBufferReceive 63 +#define SYSTEM_CALL_xStreamBufferIsFull 64 +#define SYSTEM_CALL_xStreamBufferIsEmpty 65 +#define SYSTEM_CALL_xStreamBufferSpacesAvailable 66 +#define SYSTEM_CALL_xStreamBufferBytesAvailable 67 +#define SYSTEM_CALL_xStreamBufferSetTriggerLevel 68 +#define SYSTEM_CALL_xStreamBufferNextMessageLengthBytes 69 +#define NUM_SYSTEM_CALLS 70 /* Total number of system calls. */ + +#endif /* MPU_SYSCALL_NUMBERS_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_wrappers.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_wrappers.h index 7951b0ac9..5b5057266 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_wrappers.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_wrappers.h @@ -1,186 +1,276 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -#ifndef MPU_WRAPPERS_H -#define MPU_WRAPPERS_H - -/* This file redefines API functions to be called through a wrapper macro, but - * only for ports that are using the MPU. */ -#ifdef portUSING_MPU_WRAPPERS -#error MPU - -/* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is - * included from queue.c or task.c to prevent it from having an effect within - * those files. */ -#ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -/* - * Map standard (non MPU) API functions to equivalents that start - * "MPU_". This will cause the application code to call the MPU_ - * version, which wraps the non-MPU version with privilege promoting - * then demoting code, so the kernel code always runs will full - * privileges. - */ - -/* Map standard tasks.h API functions to the MPU equivalents. */ -#define xTaskCreate MPU_xTaskCreate -#define xTaskCreateStatic MPU_xTaskCreateStatic -#define xTaskCreateRestricted MPU_xTaskCreateRestricted -#define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions -#define vTaskDelete MPU_vTaskDelete -#define vTaskDelay MPU_vTaskDelay -#define vTaskDelayUntil MPU_vTaskDelayUntil -#define xTaskAbortDelay MPU_xTaskAbortDelay -#define uxTaskPriorityGet MPU_uxTaskPriorityGet -#define eTaskGetState MPU_eTaskGetState -#define vTaskGetInfo MPU_vTaskGetInfo -#define vTaskPrioritySet MPU_vTaskPrioritySet -#define vTaskSuspend MPU_vTaskSuspend -#define vTaskResume MPU_vTaskResume -#define vTaskSuspendAll MPU_vTaskSuspendAll -#define xTaskResumeAll MPU_xTaskResumeAll -#define xTaskGetTickCount MPU_xTaskGetTickCount -#define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks -#define pcTaskGetName MPU_pcTaskGetName -#define xTaskGetHandle MPU_xTaskGetHandle -#define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark -#define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2 -#define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag -#define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag -#define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer -#define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer -#define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook -#define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle -#define uxTaskGetSystemState MPU_uxTaskGetSystemState -#define vTaskList MPU_vTaskList -#define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats -#define ulTaskGetIdleRunTimeCounter MPU_ulTaskGetIdleRunTimeCounter -#define xTaskGenericNotify MPU_xTaskGenericNotify -#define xTaskGenericNotifyWait MPU_xTaskGenericNotifyWait -#define ulTaskGenericNotifyTake MPU_ulTaskGenericNotifyTake -#define xTaskGenericNotifyStateClear MPU_xTaskGenericNotifyStateClear -#define ulTaskGenericNotifyValueClear MPU_ulTaskGenericNotifyValueClear -#define xTaskCatchUpTicks MPU_xTaskCatchUpTicks - -#define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle -#define vTaskSetTimeOutState MPU_vTaskSetTimeOutState -#define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut -#define xTaskGetSchedulerState MPU_xTaskGetSchedulerState - -/* Map standard queue.h API functions to the MPU equivalents. */ -#define xQueueGenericSend MPU_xQueueGenericSend -#define xQueueReceive MPU_xQueueReceive -#define xQueuePeek MPU_xQueuePeek -#define xQueueSemaphoreTake MPU_xQueueSemaphoreTake -#define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting -#define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable -#define vQueueDelete MPU_vQueueDelete -#define xQueueCreateMutex MPU_xQueueCreateMutex -#define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic -#define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore -#define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic -#define xQueueGetMutexHolder MPU_xQueueGetMutexHolder -#define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive -#define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive -#define xQueueGenericCreate MPU_xQueueGenericCreate -#define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic -#define xQueueCreateSet MPU_xQueueCreateSet -#define xQueueAddToSet MPU_xQueueAddToSet -#define xQueueRemoveFromSet MPU_xQueueRemoveFromSet -#define xQueueSelectFromSet MPU_xQueueSelectFromSet -#define xQueueGenericReset MPU_xQueueGenericReset - -#if (configQUEUE_REGISTRY_SIZE > 0) -#define vQueueAddToRegistry MPU_vQueueAddToRegistry -#define vQueueUnregisterQueue MPU_vQueueUnregisterQueue -#define pcQueueGetName MPU_pcQueueGetName -#endif - -/* Map standard timer.h API functions to the MPU equivalents. */ -#define xTimerCreate MPU_xTimerCreate -#define xTimerCreateStatic MPU_xTimerCreateStatic -#define pvTimerGetTimerID MPU_pvTimerGetTimerID -#define vTimerSetTimerID MPU_vTimerSetTimerID -#define xTimerIsTimerActive MPU_xTimerIsTimerActive -#define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle -#define xTimerPendFunctionCall MPU_xTimerPendFunctionCall -#define pcTimerGetName MPU_pcTimerGetName -#define vTimerSetReloadMode MPU_vTimerSetReloadMode -#define uxTimerGetReloadMode MPU_uxTimerGetReloadMode -#define xTimerGetPeriod MPU_xTimerGetPeriod -#define xTimerGetExpiryTime MPU_xTimerGetExpiryTime -#define xTimerGenericCommand MPU_xTimerGenericCommand - -/* Map standard event_group.h API functions to the MPU equivalents. */ -#define xEventGroupCreate MPU_xEventGroupCreate -#define xEventGroupCreateStatic MPU_xEventGroupCreateStatic -#define xEventGroupWaitBits MPU_xEventGroupWaitBits -#define xEventGroupClearBits MPU_xEventGroupClearBits -#define xEventGroupSetBits MPU_xEventGroupSetBits -#define xEventGroupSync MPU_xEventGroupSync -#define vEventGroupDelete MPU_vEventGroupDelete - -/* Map standard message/stream_buffer.h API functions to the MPU - * equivalents. */ -#define xStreamBufferSend MPU_xStreamBufferSend -#define xStreamBufferReceive MPU_xStreamBufferReceive -#define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes -#define vStreamBufferDelete MPU_vStreamBufferDelete -#define xStreamBufferIsFull MPU_xStreamBufferIsFull -#define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty -#define xStreamBufferReset MPU_xStreamBufferReset -#define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable -#define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable -#define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel -#define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate -#define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic - -/* Remove the privileged function macro, but keep the PRIVILEGED_DATA - * macro so applications can place data in privileged access sections - * (useful when using statically allocated objects). */ -#define PRIVILEGED_FUNCTION -#define PRIVILEGED_DATA __attribute__((section("privileged_data"))) -#define FREERTOS_SYSTEM_CALL - -#else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ - -/* Ensure API functions go in the privileged execution section. */ -#define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions"))) -#define PRIVILEGED_DATA __attribute__((section("privileged_data"))) -#define FREERTOS_SYSTEM_CALL __attribute__((section("freertos_system_calls"))) - -#endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ - -#else /* portUSING_MPU_WRAPPERS */ - -#define PRIVILEGED_FUNCTION -#define PRIVILEGED_DATA -#define FREERTOS_SYSTEM_CALL -#define portUSING_MPU_WRAPPERS 0 - -#endif /* portUSING_MPU_WRAPPERS */ - -#endif /* MPU_WRAPPERS_H */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef MPU_WRAPPERS_H +#define MPU_WRAPPERS_H + +/* This file redefines API functions to be called through a wrapper macro, but + * only for ports that are using the MPU. */ +#if ( portUSING_MPU_WRAPPERS == 1 ) + +/* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is + * included from queue.c or task.c to prevent it from having an effect within + * those files. */ + #ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* + * Map standard (non MPU) API functions to equivalents that start + * "MPU_". This will cause the application code to call the MPU_ + * version, which wraps the non-MPU version with privilege promoting + * then demoting code, so the kernel code always runs will full + * privileges. + */ + +/* Map standard task.h API functions to the MPU equivalents. */ + #define vTaskDelay MPU_vTaskDelay + #define xTaskDelayUntil MPU_xTaskDelayUntil + #define xTaskAbortDelay MPU_xTaskAbortDelay + #define uxTaskPriorityGet MPU_uxTaskPriorityGet + #define eTaskGetState MPU_eTaskGetState + #define vTaskGetInfo MPU_vTaskGetInfo + #define vTaskSuspend MPU_vTaskSuspend + #define vTaskResume MPU_vTaskResume + #define xTaskGetTickCount MPU_xTaskGetTickCount + #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks + #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark + #define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2 + #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag + #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag + #define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer + #define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer + #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle + #define uxTaskGetSystemState MPU_uxTaskGetSystemState + #define ulTaskGetIdleRunTimeCounter MPU_ulTaskGetIdleRunTimeCounter + #define ulTaskGetIdleRunTimePercent MPU_ulTaskGetIdleRunTimePercent + #define xTaskGenericNotify MPU_xTaskGenericNotify + #define xTaskGenericNotifyWait MPU_xTaskGenericNotifyWait + #define ulTaskGenericNotifyTake MPU_ulTaskGenericNotifyTake + #define xTaskGenericNotifyStateClear MPU_xTaskGenericNotifyStateClear + #define ulTaskGenericNotifyValueClear MPU_ulTaskGenericNotifyValueClear + #define vTaskSetTimeOutState MPU_vTaskSetTimeOutState + #define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut + #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle + #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState + + #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) + #define ulTaskGetRunTimeCounter MPU_ulTaskGetRunTimeCounter + #define ulTaskGetRunTimePercent MPU_ulTaskGetRunTimePercent + #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */ + +/* Privileged only wrappers for Task APIs. These are needed so that + * the application can use opaque handles maintained in mpu_wrappers.c + * with all the APIs. */ + #define xTaskCreate MPU_xTaskCreate + #define xTaskCreateStatic MPU_xTaskCreateStatic + #define vTaskDelete MPU_vTaskDelete + #define vTaskPrioritySet MPU_vTaskPrioritySet + #define xTaskGetHandle MPU_xTaskGetHandle + #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook + + #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) + #define pcTaskGetName MPU_pcTaskGetName + #define xTaskCreateRestricted MPU_xTaskCreateRestricted + #define xTaskCreateRestrictedStatic MPU_xTaskCreateRestrictedStatic + #define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions + #define xTaskGetStaticBuffers MPU_xTaskGetStaticBuffers + #define uxTaskPriorityGetFromISR MPU_uxTaskPriorityGetFromISR + #define uxTaskBasePriorityGet MPU_uxTaskBasePriorityGet + #define uxTaskBasePriorityGetFromISR MPU_uxTaskBasePriorityGetFromISR + #define xTaskResumeFromISR MPU_xTaskResumeFromISR + #define xTaskGetApplicationTaskTagFromISR MPU_xTaskGetApplicationTaskTagFromISR + #define xTaskGenericNotifyFromISR MPU_xTaskGenericNotifyFromISR + #define vTaskGenericNotifyGiveFromISR MPU_vTaskGenericNotifyGiveFromISR + #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */ + +/* Map standard queue.h API functions to the MPU equivalents. */ + #define xQueueGenericSend MPU_xQueueGenericSend + #define xQueueReceive MPU_xQueueReceive + #define xQueuePeek MPU_xQueuePeek + #define xQueueSemaphoreTake MPU_xQueueSemaphoreTake + #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting + #define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable + #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder + #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive + #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive + #define xQueueAddToSet MPU_xQueueAddToSet + #define xQueueSelectFromSet MPU_xQueueSelectFromSet + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + #define vQueueAddToRegistry MPU_vQueueAddToRegistry + #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue + #define pcQueueGetName MPU_pcQueueGetName + #endif /* #if ( configQUEUE_REGISTRY_SIZE > 0 ) */ + +/* Privileged only wrappers for Queue APIs. These are needed so that + * the application can use opaque handles maintained in mpu_wrappers.c + * with all the APIs. */ + #define vQueueDelete MPU_vQueueDelete + #define xQueueCreateMutex MPU_xQueueCreateMutex + #define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic + #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore + #define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic + #define xQueueGenericCreate MPU_xQueueGenericCreate + #define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic + #define xQueueGenericReset MPU_xQueueGenericReset + #define xQueueCreateSet MPU_xQueueCreateSet + #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet + + #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) + #define xQueueGenericGetStaticBuffers MPU_xQueueGenericGetStaticBuffers + #define xQueueGenericSendFromISR MPU_xQueueGenericSendFromISR + #define xQueueGiveFromISR MPU_xQueueGiveFromISR + #define xQueuePeekFromISR MPU_xQueuePeekFromISR + #define xQueueReceiveFromISR MPU_xQueueReceiveFromISR + #define xQueueIsQueueEmptyFromISR MPU_xQueueIsQueueEmptyFromISR + #define xQueueIsQueueFullFromISR MPU_xQueueIsQueueFullFromISR + #define uxQueueMessagesWaitingFromISR MPU_uxQueueMessagesWaitingFromISR + #define xQueueGetMutexHolderFromISR MPU_xQueueGetMutexHolderFromISR + #define xQueueSelectFromSetFromISR MPU_xQueueSelectFromSetFromISR + #endif /* if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */ + +/* Map standard timer.h API functions to the MPU equivalents. */ + #define pvTimerGetTimerID MPU_pvTimerGetTimerID + #define vTimerSetTimerID MPU_vTimerSetTimerID + #define xTimerIsTimerActive MPU_xTimerIsTimerActive + #define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle + #define xTimerGenericCommandFromTask MPU_xTimerGenericCommandFromTask + #define pcTimerGetName MPU_pcTimerGetName + #define vTimerSetReloadMode MPU_vTimerSetReloadMode + #define uxTimerGetReloadMode MPU_uxTimerGetReloadMode + #define xTimerGetPeriod MPU_xTimerGetPeriod + #define xTimerGetExpiryTime MPU_xTimerGetExpiryTime + +/* Privileged only wrappers for Timer APIs. These are needed so that + * the application can use opaque handles maintained in mpu_wrappers.c + * with all the APIs. */ + #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) + #define xTimerGetReloadMode MPU_xTimerGetReloadMode + #define xTimerCreate MPU_xTimerCreate + #define xTimerCreateStatic MPU_xTimerCreateStatic + #define xTimerGetStaticBuffer MPU_xTimerGetStaticBuffer + #define xTimerGenericCommandFromISR MPU_xTimerGenericCommandFromISR + #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */ + +/* Map standard event_group.h API functions to the MPU equivalents. */ + #define xEventGroupWaitBits MPU_xEventGroupWaitBits + #define xEventGroupClearBits MPU_xEventGroupClearBits + #define xEventGroupSetBits MPU_xEventGroupSetBits + #define xEventGroupSync MPU_xEventGroupSync + + #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) ) + #define uxEventGroupGetNumber MPU_uxEventGroupGetNumber + #define vEventGroupSetNumber MPU_vEventGroupSetNumber + #endif /* #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) ) */ + +/* Privileged only wrappers for Event Group APIs. These are needed so that + * the application can use opaque handles maintained in mpu_wrappers.c + * with all the APIs. */ + #define xEventGroupCreate MPU_xEventGroupCreate + #define xEventGroupCreateStatic MPU_xEventGroupCreateStatic + #define vEventGroupDelete MPU_vEventGroupDelete + + #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) + #define xEventGroupGetStaticBuffer MPU_xEventGroupGetStaticBuffer + #define xEventGroupClearBitsFromISR MPU_xEventGroupClearBitsFromISR + #define xEventGroupSetBitsFromISR MPU_xEventGroupSetBitsFromISR + #define xEventGroupGetBitsFromISR MPU_xEventGroupGetBitsFromISR + #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */ + +/* Map standard message/stream_buffer.h API functions to the MPU + * equivalents. */ + #define xStreamBufferSend MPU_xStreamBufferSend + #define xStreamBufferReceive MPU_xStreamBufferReceive + #define xStreamBufferIsFull MPU_xStreamBufferIsFull + #define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty + #define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable + #define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable + #define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel + #define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes + +/* Privileged only wrappers for Stream Buffer APIs. These are needed so that + * the application can use opaque handles maintained in mpu_wrappers.c + * with all the APIs. */ + + #define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate + #define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic + #define vStreamBufferDelete MPU_vStreamBufferDelete + #define xStreamBufferReset MPU_xStreamBufferReset + + #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) + #define xStreamBufferGetStaticBuffers MPU_xStreamBufferGetStaticBuffers + #define xStreamBufferSendFromISR MPU_xStreamBufferSendFromISR + #define xStreamBufferReceiveFromISR MPU_xStreamBufferReceiveFromISR + #define xStreamBufferSendCompletedFromISR MPU_xStreamBufferSendCompletedFromISR + #define xStreamBufferReceiveCompletedFromISR MPU_xStreamBufferReceiveCompletedFromISR + #define xStreamBufferResetFromISR MPU_xStreamBufferResetFromISR + #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */ + + #if ( ( configUSE_MPU_WRAPPERS_V1 == 0 ) && ( configENABLE_ACCESS_CONTROL_LIST == 1 ) ) + + #define vGrantAccessToTask( xTask, xTaskToGrantAccess ) vGrantAccessToKernelObject( ( xTask ), ( int32_t ) ( xTaskToGrantAccess ) ) + #define vRevokeAccessToTask( xTask, xTaskToRevokeAccess ) vRevokeAccessToKernelObject( ( xTask ), ( int32_t ) ( xTaskToRevokeAccess ) ) + + #define vGrantAccessToSemaphore( xTask, xSemaphoreToGrantAccess ) vGrantAccessToKernelObject( ( xTask ), ( int32_t ) ( xSemaphoreToGrantAccess ) ) + #define vRevokeAccessToSemaphore( xTask, xSemaphoreToRevokeAccess ) vRevokeAccessToKernelObject( ( xTask ), ( int32_t ) ( xSemaphoreToRevokeAccess ) ) + + #define vGrantAccessToQueue( xTask, xQueueToGrantAccess ) vGrantAccessToKernelObject( ( xTask ), ( int32_t ) ( xQueueToGrantAccess ) ) + #define vRevokeAccessToQueue( xTask, xQueueToRevokeAccess ) vRevokeAccessToKernelObject( ( xTask ), ( int32_t ) ( xQueueToRevokeAccess ) ) + + #define vGrantAccessToQueueSet( xTask, xQueueSetToGrantAccess ) vGrantAccessToKernelObject( ( xTask ), ( int32_t ) ( xQueueSetToGrantAccess ) ) + #define vRevokeAccessToQueueSet( xTask, xQueueSetToRevokeAccess ) vRevokeAccessToKernelObject( ( xTask ), ( int32_t ) ( xQueueSetToRevokeAccess ) ) + + #define vGrantAccessToEventGroup( xTask, xEventGroupToGrantAccess ) vGrantAccessToKernelObject( ( xTask ), ( int32_t ) ( xEventGroupToGrantAccess ) ) + #define vRevokeAccessToEventGroup( xTask, xEventGroupToRevokeAccess ) vRevokeAccessToKernelObject( ( xTask ), ( int32_t ) ( xEventGroupToRevokeAccess ) ) + + #define vGrantAccessToStreamBuffer( xTask, xStreamBufferToGrantAccess ) vGrantAccessToKernelObject( ( xTask ), ( int32_t ) ( xStreamBufferToGrantAccess ) ) + #define vRevokeAccessToStreamBuffer( xTask, xStreamBufferToRevokeAccess ) vRevokeAccessToKernelObject( ( xTask ), ( int32_t ) ( xStreamBufferToRevokeAccess ) ) + + #define vGrantAccessToMessageBuffer( xTask, xMessageBufferToGrantAccess ) vGrantAccessToKernelObject( ( xTask ), ( int32_t ) ( xMessageBufferToGrantAccess ) ) + #define vRevokeAccessToMessageBuffer( xTask, xMessageBufferToRevokeAccess ) vRevokeAccessToKernelObject( ( xTask ), ( int32_t ) ( xMessageBufferToRevokeAccess ) ) + + #define vGrantAccessToTimer( xTask, xTimerToGrantAccess ) vGrantAccessToKernelObject( ( xTask ), ( int32_t ) ( xTimerToGrantAccess ) ) + #define vRevokeAccessToTimer( xTask, xTimerToRevokeAccess ) vRevokeAccessToKernelObject( ( xTask ), ( int32_t ) ( xTimerToRevokeAccess ) ) + + #endif /* #if ( ( configUSE_MPU_WRAPPERS_V1 == 0 ) && ( configENABLE_ACCESS_CONTROL_LIST == 1 ) ) */ + + #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + + #define PRIVILEGED_FUNCTION __attribute__( ( section( "privileged_functions" ) ) ) + #define PRIVILEGED_DATA __attribute__( ( section( "privileged_data" ) ) ) + #define FREERTOS_SYSTEM_CALL __attribute__( ( section( "freertos_system_calls" ) ) ) + +#else /* portUSING_MPU_WRAPPERS */ + + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA + #define FREERTOS_SYSTEM_CALL + +#endif /* portUSING_MPU_WRAPPERS */ + + +#endif /* MPU_WRAPPERS_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/newlib-freertos.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/newlib-freertos.h new file mode 100644 index 000000000..2b51ee712 --- /dev/null +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/newlib-freertos.h @@ -0,0 +1,62 @@ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef INC_NEWLIB_FREERTOS_H +#define INC_NEWLIB_FREERTOS_H + +/* Note Newlib support has been included by popular demand, but is not + * used by the FreeRTOS maintainers themselves. FreeRTOS is not + * responsible for resulting newlib operation. User must be familiar with + * newlib and must provide system-wide implementations of the necessary + * stubs. Be warned that (at the time of writing) the current newlib design + * implements a system-wide malloc() that must be provided with locks. + * + * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + * for additional information. */ + +#include + +#define configUSE_C_RUNTIME_TLS_SUPPORT 1 + +#ifndef configTLS_BLOCK_TYPE + #define configTLS_BLOCK_TYPE struct _reent +#endif + +#ifndef configINIT_TLS_BLOCK + #define configINIT_TLS_BLOCK( xTLSBlock, pxTopOfStack ) _REENT_INIT_PTR( &( xTLSBlock ) ) +#endif + +#ifndef configSET_TLS_BLOCK + #define configSET_TLS_BLOCK( xTLSBlock ) ( _impure_ptr = &( xTLSBlock ) ) +#endif + +#ifndef configDEINIT_TLS_BLOCK + #define configDEINIT_TLS_BLOCK( xTLSBlock ) _reclaim_reent( &( xTLSBlock ) ) +#endif + +#endif /* INC_NEWLIB_FREERTOS_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/picolibc-freertos.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/picolibc-freertos.h new file mode 100644 index 000000000..9a3b5a866 --- /dev/null +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/picolibc-freertos.h @@ -0,0 +1,91 @@ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef INC_PICOLIBC_FREERTOS_H +#define INC_PICOLIBC_FREERTOS_H + +/* Use picolibc TLS support to allocate space for __thread variables, + * initialize them at thread creation and set the TLS context at + * thread switch time. + * + * See the picolibc TLS docs: + * https://github.com/picolibc/picolibc/blob/main/doc/tls.md + * for additional information. */ + +#include + +#define configUSE_C_RUNTIME_TLS_SUPPORT 1 + +#define configTLS_BLOCK_TYPE void * + +#define picolibcTLS_SIZE ( ( portPOINTER_SIZE_TYPE ) _tls_size() ) +#define picolibcSTACK_ALIGNMENT_MASK ( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) + +#if __PICOLIBC_MAJOR__ > 1 || __PICOLIBC_MINOR__ >= 8 + +/* Picolibc 1.8 and newer have explicit alignment values provided + * by the _tls_align() inline */ + #define picolibcTLS_ALIGNMENT_MASK ( ( portPOINTER_SIZE_TYPE ) ( _tls_align() - 1 ) ) +#else + +/* For older Picolibc versions, use the general port alignment value */ + #define picolibcTLS_ALIGNMENT_MASK ( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) +#endif + +/* Allocate thread local storage block off the end of the + * stack. The picolibcTLS_SIZE macro returns the size (in + * bytes) of the total TLS area used by the application. + * Calculate the top of stack address. */ +#if ( portSTACK_GROWTH < 0 ) + + #define configINIT_TLS_BLOCK( xTLSBlock, pxTopOfStack ) \ + do { \ + xTLSBlock = ( void * ) ( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) - \ + picolibcTLS_SIZE ) & \ + ~picolibcTLS_ALIGNMENT_MASK ); \ + pxTopOfStack = ( StackType_t * ) ( ( ( ( portPOINTER_SIZE_TYPE ) xTLSBlock ) - 1 ) & \ + ~picolibcSTACK_ALIGNMENT_MASK ); \ + _init_tls( xTLSBlock ); \ + } while( 0 ) +#else /* portSTACK_GROWTH */ + #define configINIT_TLS_BLOCK( xTLSBlock, pxTopOfStack ) \ + do { \ + xTLSBlock = ( void * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack + \ + picolibcTLS_ALIGNMENT_MASK ) & ~picolibcTLS_ALIGNMENT_MASK ); \ + pxTopOfStack = ( StackType_t * ) ( ( ( ( ( portPOINTER_SIZE_TYPE ) xTLSBlock ) + \ + picolibcTLS_SIZE ) + picolibcSTACK_ALIGNMENT_MASK ) & \ + ~picolibcSTACK_ALIGNMENT_MASK ); \ + _init_tls( xTLSBlock ); \ + } while( 0 ) +#endif /* portSTACK_GROWTH */ + +#define configSET_TLS_BLOCK( xTLSBlock ) _set_tls( xTLSBlock ) + +#define configDEINIT_TLS_BLOCK( xTLSBlock ) + +#endif /* INC_PICOLIBC_FREERTOS_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/portable.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/portable.h index 7bcea0248..51f04345a 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/portable.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/portable.h @@ -1,216 +1,259 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -/*----------------------------------------------------------- -* Portable layer API. Each function must be defined for each port. -*----------------------------------------------------------*/ - -#ifndef PORTABLE_H -#define PORTABLE_H - -/* Each FreeRTOS port has a unique portmacro.h header file. Originally a - * pre-processor definition was used to ensure the pre-processor found the correct - * portmacro.h file for the port being used. That scheme was deprecated in favour - * of setting the compiler's include path such that it found the correct - * portmacro.h file - removing the need for the constant and allowing the - * portmacro.h file to be located anywhere in relation to the port being used. - * Purely for reasons of backward compatibility the old method is still valid, but - * to make it clear that new projects should not use it, support for the port - * specific constants has been moved into the deprecated_definitions.h header - * file. */ -#include "deprecated_definitions.h" - -/* If portENTER_CRITICAL is not defined then including deprecated_definitions.h - * did not result in a portmacro.h header file being included - and it should be - * included here. In this case the path to the correct portmacro.h header file - * must be set in the compiler's include path. */ -#ifndef portENTER_CRITICAL - #include "portmacro.h" -#endif - -#if portBYTE_ALIGNMENT == 32 - #define portBYTE_ALIGNMENT_MASK ( 0x001f ) -#endif - -#if portBYTE_ALIGNMENT == 16 - #define portBYTE_ALIGNMENT_MASK ( 0x000f ) -#endif - -#if portBYTE_ALIGNMENT == 8 - #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) -#endif - -#if portBYTE_ALIGNMENT == 4 - #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) -#endif - -#if portBYTE_ALIGNMENT == 2 - #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) -#endif - -#if portBYTE_ALIGNMENT == 1 - #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) -#endif - -#ifndef portBYTE_ALIGNMENT_MASK - #error "Invalid portBYTE_ALIGNMENT definition" -#endif - -#ifndef portNUM_CONFIGURABLE_REGIONS - #define portNUM_CONFIGURABLE_REGIONS 1 -#endif - -#ifndef portHAS_STACK_OVERFLOW_CHECKING - #define portHAS_STACK_OVERFLOW_CHECKING 0 -#endif - -#ifndef portARCH_NAME - #define portARCH_NAME NULL -#endif - -/* *INDENT-OFF* */ -#ifdef __cplusplus - extern "C" { -#endif -/* *INDENT-ON* */ - -#include "mpu_wrappers.h" - -/* - * Setup the stack of a new task so it is ready to be placed under the - * scheduler control. The registers have to be placed on the stack in - * the order that the port expects to find them. - * - */ -#if ( portUSING_MPU_WRAPPERS == 1 ) - #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, - StackType_t * pxEndOfStack, - TaskFunction_t pxCode, - void * pvParameters, - BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; - #else - StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, - TaskFunction_t pxCode, - void * pvParameters, - BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; - #endif -#else /* if ( portUSING_MPU_WRAPPERS == 1 ) */ - #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, - StackType_t * pxEndOfStack, - TaskFunction_t pxCode, - void * pvParameters ) PRIVILEGED_FUNCTION; - #else - StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, - TaskFunction_t pxCode, - void * pvParameters ) PRIVILEGED_FUNCTION; - #endif -#endif /* if ( portUSING_MPU_WRAPPERS == 1 ) */ - -/* Used by heap_5.c to define the start address and size of each memory region - * that together comprise the total FreeRTOS heap space. */ -typedef struct HeapRegion -{ - uint8_t * pucStartAddress; - size_t xSizeInBytes; -} HeapRegion_t; - -/* Used to pass information about the heap out of vPortGetHeapStats(). */ -typedef struct xHeapStats -{ - size_t xAvailableHeapSpaceInBytes; /* The total heap size currently available - this is the sum of all the free blocks, not the largest block that can be allocated. */ - size_t xSizeOfLargestFreeBlockInBytes; /* The maximum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ - size_t xSizeOfSmallestFreeBlockInBytes; /* The minimum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ - size_t xNumberOfFreeBlocks; /* The number of free memory blocks within the heap at the time vPortGetHeapStats() is called. */ - size_t xMinimumEverFreeBytesRemaining; /* The minimum amount of total free memory (sum of all free blocks) there has been in the heap since the system booted. */ - size_t xNumberOfSuccessfulAllocations; /* The number of calls to pvPortMalloc() that have returned a valid memory block. */ - size_t xNumberOfSuccessfulFrees; /* The number of calls to vPortFree() that has successfully freed a block of memory. */ -} HeapStats_t; - -/* - * Used to define multiple heap regions for use by heap_5.c. This function - * must be called before any calls to pvPortMalloc() - not creating a task, - * queue, semaphore, mutex, software timer, event group, etc. will result in - * pvPortMalloc being called. - * - * pxHeapRegions passes in an array of HeapRegion_t structures - each of which - * defines a region of memory that can be used as the heap. The array is - * terminated by a HeapRegions_t structure that has a size of 0. The region - * with the lowest start address must appear first in the array. - */ -void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) PRIVILEGED_FUNCTION; - -/* - * Returns a HeapStats_t structure filled with information about the current - * heap state. - */ -void vPortGetHeapStats( HeapStats_t * pxHeapStats ); - -/* - * Map to the memory management routines required for the port. - */ -void * pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION; -void vPortFree( void * pv ) PRIVILEGED_FUNCTION; -void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION; -size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION; -size_t xPortGetMinimumEverFreeHeapSize( void ) PRIVILEGED_FUNCTION; - -/* - * Setup the hardware ready for the scheduler to take control. This generally - * sets up a tick interrupt and sets timers for the correct tick frequency. - */ -BaseType_t xPortStartScheduler( void ) PRIVILEGED_FUNCTION; - -/* - * Undo any hardware/ISR setup that was performed by xPortStartScheduler() so - * the hardware is left in its original condition after the scheduler stops - * executing. - */ -void vPortEndScheduler( void ) PRIVILEGED_FUNCTION; - -/* - * The structures and methods of manipulating the MPU are contained within the - * port layer. - * - * Fills the xMPUSettings structure with the memory region information - * contained in xRegions. - */ -#if ( portUSING_MPU_WRAPPERS == 1 ) - struct xMEMORY_REGION; - void vPortStoreTaskMPUSettings( xMPU_SETTINGS * xMPUSettings, - const struct xMEMORY_REGION * const xRegions, - StackType_t * pxBottomOfStack, - uint32_t ulStackDepth ) PRIVILEGED_FUNCTION; -#endif - -/* *INDENT-OFF* */ -#ifdef __cplusplus - } -#endif -/* *INDENT-ON* */ - -#endif /* PORTABLE_H */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/*----------------------------------------------------------- + * Portable layer API. Each function must be defined for each port. + *----------------------------------------------------------*/ + +#ifndef PORTABLE_H +#define PORTABLE_H + +/* Each FreeRTOS port has a unique portmacro.h header file. Originally a + * pre-processor definition was used to ensure the pre-processor found the correct + * portmacro.h file for the port being used. That scheme was deprecated in favour + * of setting the compiler's include path such that it found the correct + * portmacro.h file - removing the need for the constant and allowing the + * portmacro.h file to be located anywhere in relation to the port being used. + * Purely for reasons of backward compatibility the old method is still valid, but + * to make it clear that new projects should not use it, support for the port + * specific constants has been moved into the deprecated_definitions.h header + * file. */ + +/* If portENTER_CRITICAL is not defined then including deprecated_definitions.h + * did not result in a portmacro.h header file being included - and it should be + * included here. In this case the path to the correct portmacro.h header file + * must be set in the compiler's include path. */ +#ifndef portENTER_CRITICAL +#include "portmacro.h" +#endif + +#if portBYTE_ALIGNMENT == 32 +#define portBYTE_ALIGNMENT_MASK (0x001f) +#elif portBYTE_ALIGNMENT == 16 +#define portBYTE_ALIGNMENT_MASK (0x000f) +#elif portBYTE_ALIGNMENT == 8 +#define portBYTE_ALIGNMENT_MASK (0x0007) +#elif portBYTE_ALIGNMENT == 4 +#define portBYTE_ALIGNMENT_MASK (0x0003) +#elif portBYTE_ALIGNMENT == 2 +#define portBYTE_ALIGNMENT_MASK (0x0001) +#elif portBYTE_ALIGNMENT == 1 +#define portBYTE_ALIGNMENT_MASK (0x0000) +#else /* if portBYTE_ALIGNMENT == 32 */ +#error "Invalid portBYTE_ALIGNMENT definition" +#endif /* if portBYTE_ALIGNMENT == 32 */ + +#ifndef portUSING_MPU_WRAPPERS +#define portUSING_MPU_WRAPPERS 0 +#endif + +#ifndef portNUM_CONFIGURABLE_REGIONS +#define portNUM_CONFIGURABLE_REGIONS 1 +#endif + +#ifndef portHAS_STACK_OVERFLOW_CHECKING +#define portHAS_STACK_OVERFLOW_CHECKING 0 +#endif + +#ifndef portARCH_NAME +#define portARCH_NAME NULL +#endif + +#ifndef configSTACK_DEPTH_TYPE +#define configSTACK_DEPTH_TYPE StackType_t +#endif + +#ifndef configSTACK_ALLOCATION_FROM_SEPARATE_HEAP +/* Defaults to 0 for backward compatibility. */ +#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0 +#endif + +/* *INDENT-OFF* */ +#ifdef __cplusplus +extern "C" { +#endif +/* *INDENT-ON* */ + +#include "mpu_wrappers.h" + +/* + * Setup the stack of a new task so it is ready to be placed under the + * scheduler control. The registers have to be placed on the stack in + * the order that the port expects to find them. + * + */ +#if (portUSING_MPU_WRAPPERS == 1) +#if (portHAS_STACK_OVERFLOW_CHECKING == 1) +StackType_t *pxPortInitialiseStack(StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged, + xMPU_SETTINGS *xMPUSettings) PRIVILEGED_FUNCTION; +#else +StackType_t *pxPortInitialiseStack(StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged, xMPU_SETTINGS *xMPUSettings) PRIVILEGED_FUNCTION; +#endif /* if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) */ +#else /* if ( portUSING_MPU_WRAPPERS == 1 ) */ +#if (portHAS_STACK_OVERFLOW_CHECKING == 1) +StackType_t *pxPortInitialiseStack(StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters) PRIVILEGED_FUNCTION; +#else +StackType_t *pxPortInitialiseStack(StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters) PRIVILEGED_FUNCTION; +#endif +#endif /* if ( portUSING_MPU_WRAPPERS == 1 ) */ + +/* Used by heap_5.c to define the start address and size of each memory region + * that together comprise the total FreeRTOS heap space. */ +typedef struct HeapRegion { + uint8_t *pucStartAddress; + size_t xSizeInBytes; +} HeapRegion_t; + +/* Used to pass information about the heap out of vPortGetHeapStats(). */ +typedef struct xHeapStats { + size_t xAvailableHeapSpaceInBytes; /* The total heap size currently available - this is the sum of all the free blocks, not the largest block that can be allocated. */ + size_t xSizeOfLargestFreeBlockInBytes; /* The maximum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xSizeOfSmallestFreeBlockInBytes; /* The minimum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xNumberOfFreeBlocks; /* The number of free memory blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xMinimumEverFreeBytesRemaining; /* The minimum amount of total free memory (sum of all free blocks) there has been in the heap since the system booted. */ + size_t xNumberOfSuccessfulAllocations; /* The number of calls to pvPortMalloc() that have returned a valid memory block. */ + size_t xNumberOfSuccessfulFrees; /* The number of calls to vPortFree() that has successfully freed a block of memory. */ +} HeapStats_t; + +/* + * Used to define multiple heap regions for use by heap_5.c. This function + * must be called before any calls to pvPortMalloc() - not creating a task, + * queue, semaphore, mutex, software timer, event group, etc. will result in + * pvPortMalloc being called. + * + * pxHeapRegions passes in an array of HeapRegion_t structures - each of which + * defines a region of memory that can be used as the heap. The array is + * terminated by a HeapRegions_t structure that has a size of 0. The region + * with the lowest start address must appear first in the array. + */ +void vPortDefineHeapRegions(const HeapRegion_t *const pxHeapRegions) PRIVILEGED_FUNCTION; + +/* + * Returns a HeapStats_t structure filled with information about the current + * heap state. + */ +void vPortGetHeapStats(HeapStats_t *pxHeapStats); + +/* + * Map to the memory management routines required for the port. + */ +void *pvPortMalloc(size_t xWantedSize) PRIVILEGED_FUNCTION; +void *pvPortCalloc(size_t xNum, size_t xSize) PRIVILEGED_FUNCTION; +void vPortFree(void *pv) PRIVILEGED_FUNCTION; +void vPortInitialiseBlocks(void) PRIVILEGED_FUNCTION; +size_t xPortGetFreeHeapSize(void) PRIVILEGED_FUNCTION; +size_t xPortGetMinimumEverFreeHeapSize(void) PRIVILEGED_FUNCTION; + +#if (configSTACK_ALLOCATION_FROM_SEPARATE_HEAP == 1) +void *pvPortMallocStack(size_t xSize) PRIVILEGED_FUNCTION; +void vPortFreeStack(void *pv) PRIVILEGED_FUNCTION; +#else +#define pvPortMallocStack pvPortMalloc +#define vPortFreeStack vPortFree +#endif + +/* + * This function resets the internal state of the heap module. It must be called + * by the application before restarting the scheduler. + */ +void vPortHeapResetState(void) PRIVILEGED_FUNCTION; + +#if (configUSE_MALLOC_FAILED_HOOK == 1) + +/** + * task.h + * @code{c} + * void vApplicationMallocFailedHook( void ) + * @endcode + * + * This hook function is called when allocation failed. + */ +void vApplicationMallocFailedHook(void); +#endif + +/* + * Setup the hardware ready for the scheduler to take control. This generally + * sets up a tick interrupt and sets timers for the correct tick frequency. + */ +BaseType_t xPortStartScheduler(void) PRIVILEGED_FUNCTION; + +/* + * Undo any hardware/ISR setup that was performed by xPortStartScheduler() so + * the hardware is left in its original condition after the scheduler stops + * executing. + */ +void vPortEndScheduler(void) PRIVILEGED_FUNCTION; + +/* + * The structures and methods of manipulating the MPU are contained within the + * port layer. + * + * Fills the xMPUSettings structure with the memory region information + * contained in xRegions. + */ +#if (portUSING_MPU_WRAPPERS == 1) +struct xMEMORY_REGION; +void vPortStoreTaskMPUSettings(xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION *const xRegions, StackType_t *pxBottomOfStack, configSTACK_DEPTH_TYPE uxStackDepth) PRIVILEGED_FUNCTION; +#endif + +/** + * @brief Checks if the calling task is authorized to access the given buffer. + * + * @param pvBuffer The buffer which the calling task wants to access. + * @param ulBufferLength The length of the pvBuffer. + * @param ulAccessRequested The permissions that the calling task wants. + * + * @return pdTRUE if the calling task is authorized to access the buffer, + * pdFALSE otherwise. + */ +#if (portUSING_MPU_WRAPPERS == 1) +BaseType_t xPortIsAuthorizedToAccessBuffer(const void *pvBuffer, uint32_t ulBufferLength, uint32_t ulAccessRequested) PRIVILEGED_FUNCTION; +#endif + +/** + * @brief Checks if the calling task is authorized to access the given kernel object. + * + * @param lInternalIndexOfKernelObject The index of the kernel object in the kernel + * object handle pool. + * + * @return pdTRUE if the calling task is authorized to access the kernel object, + * pdFALSE otherwise. + */ +#if ((portUSING_MPU_WRAPPERS == 1) && (configUSE_MPU_WRAPPERS_V1 == 0)) + +BaseType_t xPortIsAuthorizedToAccessKernelObject(int32_t lInternalIndexOfKernelObject) PRIVILEGED_FUNCTION; + +#endif + +/* *INDENT-OFF* */ +#ifdef __cplusplus +} +#endif +/* *INDENT-ON* */ + +#endif /* PORTABLE_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/projdefs.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/projdefs.h index 918256564..d55dfde2b 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/projdefs.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/projdefs.h @@ -1,120 +1,138 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -#ifndef PROJDEFS_H -#define PROJDEFS_H - -/* - * Defines the prototype to which task functions must conform. Defined in this - * file to ensure the type is known before portable.h is included. - */ -typedef void (* TaskFunction_t)( void * ); - -/* Converts a time in milliseconds to a time in ticks. This macro can be - * overridden by a macro of the same name defined in FreeRTOSConfig.h in case the - * definition here is not suitable for your application. */ -#ifndef pdMS_TO_TICKS - #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000U ) ) -#endif - -#define pdFALSE ( ( BaseType_t ) 0 ) -#define pdTRUE ( ( BaseType_t ) 1 ) - -#define pdPASS ( pdTRUE ) -#define pdFAIL ( pdFALSE ) -#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) -#define errQUEUE_FULL ( ( BaseType_t ) 0 ) - -/* FreeRTOS error definitions. */ -#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) -#define errQUEUE_BLOCKED ( -4 ) -#define errQUEUE_YIELD ( -5 ) - -/* Macros used for basic data corruption checks. */ -#ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES - #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 -#endif - -#if ( configUSE_16_BIT_TICKS == 1 ) - #define pdINTEGRITY_CHECK_VALUE 0x5a5a -#else - #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL -#endif - -/* The following errno values are used by FreeRTOS+ components, not FreeRTOS - * itself. */ -#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ -#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ -#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ -#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ -#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ -#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ -#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ -#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ -#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ -#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ -#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ -#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ -#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ -#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ -#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ -#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ -#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ -#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ -#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ -#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ -#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ -#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ -#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ -#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ -#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ -#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ -#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ -#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ -#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ -#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ -#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ -#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ -#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ -#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ -#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ -#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ -#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ -#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ -#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ -#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ - -/* The following endian values are used by FreeRTOS+ components, not FreeRTOS - * itself. */ -#define pdFREERTOS_LITTLE_ENDIAN 0 -#define pdFREERTOS_BIG_ENDIAN 1 - -/* Re-defining endian values for generic naming. */ -#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN -#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN - - -#endif /* PROJDEFS_H */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef PROJDEFS_H +#define PROJDEFS_H + +/* + * Defines the prototype to which task functions must conform. Defined in this + * file to ensure the type is known before portable.h is included. + */ +typedef void (* TaskFunction_t)( void * arg ); + +/* Converts a time in milliseconds to a time in ticks. This macro can be + * overridden by a macro of the same name defined in FreeRTOSConfig.h in case the + * definition here is not suitable for your application. */ +#ifndef pdMS_TO_TICKS + #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( uint64_t ) ( xTimeInMs ) * ( uint64_t ) configTICK_RATE_HZ ) / ( uint64_t ) 1000U ) ) +#endif + +/* Converts a time in ticks to a time in milliseconds. This macro can be + * overridden by a macro of the same name defined in FreeRTOSConfig.h in case the + * definition here is not suitable for your application. */ +#ifndef pdTICKS_TO_MS + #define pdTICKS_TO_MS( xTimeInTicks ) ( ( TickType_t ) ( ( ( uint64_t ) ( xTimeInTicks ) * ( uint64_t ) 1000U ) / ( uint64_t ) configTICK_RATE_HZ ) ) +#endif + +#define pdFALSE ( ( BaseType_t ) 0 ) +#define pdTRUE ( ( BaseType_t ) 1 ) +#define pdFALSE_SIGNED ( ( BaseType_t ) 0 ) +#define pdTRUE_SIGNED ( ( BaseType_t ) 1 ) +#define pdFALSE_UNSIGNED ( ( UBaseType_t ) 0 ) +#define pdTRUE_UNSIGNED ( ( UBaseType_t ) 1 ) + +#define pdPASS ( pdTRUE ) +#define pdFAIL ( pdFALSE ) +#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) +#define errQUEUE_FULL ( ( BaseType_t ) 0 ) + +/* FreeRTOS error definitions. */ +#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) +#define errQUEUE_BLOCKED ( -4 ) +#define errQUEUE_YIELD ( -5 ) + +/* Macros used for basic data corruption checks. */ +#ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES + #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 +#endif + +#if ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_16_BITS ) + #define pdINTEGRITY_CHECK_VALUE 0x5a5a +#elif ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_32_BITS ) + #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL +#elif ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_64_BITS ) + #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5a5a5a5a5aULL +#else + #error configTICK_TYPE_WIDTH_IN_BITS set to unsupported tick type width. +#endif + +/* The following errno values are used by FreeRTOS+ components, not FreeRTOS + * itself. */ +#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ +#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ +#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ +#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ +#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ +#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ +#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ +#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ +#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ +#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ +#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ +#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ +#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ +#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ +#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ +#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ +#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ +#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ +#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ +#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ +#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ +#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ +#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ +#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ +#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ +#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ +#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ +#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define pdFREERTOS_ERRNO_EAFNOSUPPORT 97 /* Address family not supported by protocol */ +#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ +#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ +#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ +#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ +#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ +#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ +#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ +#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ +#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ +#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ +#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ +#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ + +/* The following endian values are used by FreeRTOS+ components, not FreeRTOS + * itself. */ +#define pdFREERTOS_LITTLE_ENDIAN 0 +#define pdFREERTOS_BIG_ENDIAN 1 + +/* Re-defining endian values for generic naming. */ +#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN +#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN + + +#endif /* PROJDEFS_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/queue.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/queue.h index d2ea2ae3b..1e5cf2bb8 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/queue.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/queue.h @@ -1,6 +1,8 @@ /* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in @@ -77,12 +79,12 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; /** * queue. h - *
+ * @code{c}
  * QueueHandle_t xQueueCreate(
  *                            UBaseType_t uxQueueLength,
  *                            UBaseType_t uxItemSize
  *                        );
- * 
+ * @endcode * * Creates a new queue instance, and returns a handle by which the new queue * can be referenced. @@ -111,7 +113,7 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * returned. * * Example usage: - *
+ * @code{c}
  * struct AMessage
  * {
  *  char ucMessageID;
@@ -139,7 +141,7 @@ typedef struct QueueDefinition   * QueueSetMemberHandle_t;
  *
  *  // ... Rest of task code.
  * }
- * 
+ * @endcode * \defgroup xQueueCreate xQueueCreate * \ingroup QueueManagement */ @@ -149,14 +151,14 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; /** * queue. h - *
+ * @code{c}
  * QueueHandle_t xQueueCreateStatic(
  *                            UBaseType_t uxQueueLength,
  *                            UBaseType_t uxItemSize,
- *                            uint8_t *pucQueueStorageBuffer,
+ *                            uint8_t *pucQueueStorage,
  *                            StaticQueue_t *pxQueueBuffer
  *                        );
- * 
+ * @endcode * * Creates a new queue instance, and returns a handle by which the new queue * can be referenced. @@ -180,11 +182,11 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * that will be copied for each posted item. Each item on the queue must be * the same size. * - * @param pucQueueStorageBuffer If uxItemSize is not zero then - * pucQueueStorageBuffer must point to a uint8_t array that is at least large + * @param pucQueueStorage If uxItemSize is not zero then + * pucQueueStorage must point to a uint8_t array that is at least large * enough to hold the maximum number of items that can be in the queue at any * one time - which is ( uxQueueLength * uxItemsSize ) bytes. If uxItemSize is - * zero then pucQueueStorageBuffer can be NULL. + * zero then pucQueueStorage can be NULL. * * @param pxQueueBuffer Must point to a variable of type StaticQueue_t, which * will be used to hold the queue's data structure. @@ -193,7 +195,7 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * returned. If pxQueueBuffer is NULL then NULL is returned. * * Example usage: - *
+ * @code{c}
  * struct AMessage
  * {
  *  char ucMessageID;
@@ -212,7 +214,7 @@ typedef struct QueueDefinition   * QueueSetMemberHandle_t;
  *
  * void vATask( void *pvParameters )
  * {
- * QueueHandle_t xQueue1;
+ *  QueueHandle_t xQueue1;
  *
  *  // Create a queue capable of containing 10 uint32_t values.
  *  xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold.
@@ -225,7 +227,7 @@ typedef struct QueueDefinition   * QueueSetMemberHandle_t;
  *
  *  // ... Rest of task code.
  * }
- * 
+ * @endcode * \defgroup xQueueCreateStatic xQueueCreateStatic * \ingroup QueueManagement */ @@ -235,13 +237,42 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; /** * queue. h - *
- * BaseType_t xQueueSendToToFront(
+ * @code{c}
+ * BaseType_t xQueueGetStaticBuffers( QueueHandle_t xQueue,
+ *                                    uint8_t ** ppucQueueStorage,
+ *                                    StaticQueue_t ** ppxStaticQueue );
+ * @endcode
+ *
+ * Retrieve pointers to a statically created queue's data structure buffer
+ * and storage area buffer. These are the same buffers that are supplied
+ * at the time of creation.
+ *
+ * @param xQueue The queue for which to retrieve the buffers.
+ *
+ * @param ppucQueueStorage Used to return a pointer to the queue's storage
+ * area buffer.
+ *
+ * @param ppxStaticQueue Used to return a pointer to the queue's data
+ * structure buffer.
+ *
+ * @return pdTRUE if buffers were retrieved, pdFALSE otherwise.
+ *
+ * \defgroup xQueueGetStaticBuffers xQueueGetStaticBuffers
+ * \ingroup QueueManagement
+ */
+#if ( configSUPPORT_STATIC_ALLOCATION == 1 )
+    #define xQueueGetStaticBuffers( xQueue, ppucQueueStorage, ppxStaticQueue )    xQueueGenericGetStaticBuffers( ( xQueue ), ( ppucQueueStorage ), ( ppxStaticQueue ) )
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+/**
+ * queue. h
+ * @code{c}
+ * BaseType_t xQueueSendToFront(
  *                                 QueueHandle_t    xQueue,
  *                                 const void       *pvItemToQueue,
  *                                 TickType_t       xTicksToWait
  *                             );
- * 
+ * @endcode * * Post an item to the front of a queue. The item is queued by copy, not by * reference. This function must not be called from an interrupt service @@ -264,14 +295,14 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. * * Example usage: - *
+ * @code{c}
  * struct AMessage
  * {
  *  char ucMessageID;
  *  char ucData[ 20 ];
  * } xMessage;
  *
- * uint32_t ulVar = 10UL;
+ * uint32_t ulVar = 10U;
  *
  * void vATask( void *pvParameters )
  * {
@@ -307,7 +338,7 @@ typedef struct QueueDefinition   * QueueSetMemberHandle_t;
  *
  *  // ... Rest of task code.
  * }
- * 
+ * @endcode * \defgroup xQueueSend xQueueSend * \ingroup QueueManagement */ @@ -316,13 +347,13 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueSendToBack(
  *                                 QueueHandle_t    xQueue,
  *                                 const void       *pvItemToQueue,
  *                                 TickType_t       xTicksToWait
  *                             );
- * 
+ * @endcode * * This is a macro that calls xQueueGenericSend(). * @@ -347,14 +378,14 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. * * Example usage: - *
+ * @code{c}
  * struct AMessage
  * {
  *  char ucMessageID;
  *  char ucData[ 20 ];
  * } xMessage;
  *
- * uint32_t ulVar = 10UL;
+ * uint32_t ulVar = 10U;
  *
  * void vATask( void *pvParameters )
  * {
@@ -390,7 +421,7 @@ typedef struct QueueDefinition   * QueueSetMemberHandle_t;
  *
  *  // ... Rest of task code.
  * }
- * 
+ * @endcode * \defgroup xQueueSend xQueueSend * \ingroup QueueManagement */ @@ -399,13 +430,13 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueSend(
  *                            QueueHandle_t xQueue,
  *                            const void * pvItemToQueue,
  *                            TickType_t xTicksToWait
  *                       );
- * 
+ * @endcode * * This is a macro that calls xQueueGenericSend(). It is included for * backward compatibility with versions of FreeRTOS.org that did not @@ -432,14 +463,14 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. * * Example usage: - *
+ * @code{c}
  * struct AMessage
  * {
  *  char ucMessageID;
  *  char ucData[ 20 ];
  * } xMessage;
  *
- * uint32_t ulVar = 10UL;
+ * uint32_t ulVar = 10U;
  *
  * void vATask( void *pvParameters )
  * {
@@ -475,7 +506,7 @@ typedef struct QueueDefinition   * QueueSetMemberHandle_t;
  *
  *  // ... Rest of task code.
  * }
- * 
+ * @endcode * \defgroup xQueueSend xQueueSend * \ingroup QueueManagement */ @@ -484,12 +515,12 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueOverwrite(
  *                            QueueHandle_t xQueue,
  *                            const void * pvItemToQueue
  *                       );
- * 
+ * @endcode * * Only for use with queues that have a length of one - so the queue is either * empty or full. @@ -513,7 +544,7 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * to the queue even when the queue is already full. * * Example usage: - *
+ * @code{c}
  *
  * void vFunction( void *pvParameters )
  * {
@@ -559,7 +590,7 @@ typedef struct QueueDefinition   * QueueSetMemberHandle_t;
  *
  *  // ...
  * }
- * 
+ * @endcode * \defgroup xQueueOverwrite xQueueOverwrite * \ingroup QueueManagement */ @@ -569,14 +600,14 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueGenericSend(
  *                                  QueueHandle_t xQueue,
  *                                  const void * pvItemToQueue,
  *                                  TickType_t xTicksToWait
  *                                  BaseType_t xCopyPosition
  *                              );
- * 
+ * @endcode * * It is preferred that the macros xQueueSend(), xQueueSendToFront() and * xQueueSendToBack() are used in place of calling this function directly. @@ -605,14 +636,14 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. * * Example usage: - *
+ * @code{c}
  * struct AMessage
  * {
  *  char ucMessageID;
  *  char ucData[ 20 ];
  * } xMessage;
  *
- * uint32_t ulVar = 10UL;
+ * uint32_t ulVar = 10U;
  *
  * void vATask( void *pvParameters )
  * {
@@ -648,7 +679,7 @@ typedef struct QueueDefinition   * QueueSetMemberHandle_t;
  *
  *  // ... Rest of task code.
  * }
- * 
+ * @endcode * \defgroup xQueueSend xQueueSend * \ingroup QueueManagement */ @@ -659,13 +690,13 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueuePeek(
  *                           QueueHandle_t xQueue,
  *                           void * const pvBuffer,
  *                           TickType_t xTicksToWait
  *                       );
- * 
+ * @endcode * * Receive an item from a queue without removing the item from the queue. * The item is received by copy so a buffer of adequate size must be @@ -696,7 +727,7 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, * otherwise pdFALSE. * * Example usage: - *
+ * @code{c}
  * struct AMessage
  * {
  *  char ucMessageID;
@@ -746,7 +777,7 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue,
  *
  *  // ... Rest of task code.
  * }
- * 
+ * @endcode * \defgroup xQueuePeek xQueuePeek * \ingroup QueueManagement */ @@ -756,12 +787,12 @@ BaseType_t xQueuePeek( QueueHandle_t xQueue, /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueuePeekFromISR(
  *                                  QueueHandle_t xQueue,
  *                                  void *pvBuffer,
  *                              );
- * 
+ * @endcode * * A version of xQueuePeek() that can be called from an interrupt service * routine (ISR). @@ -791,13 +822,13 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueReceive(
  *                               QueueHandle_t xQueue,
  *                               void *pvBuffer,
  *                               TickType_t xTicksToWait
  *                          );
- * 
+ * @endcode * * Receive an item from a queue. The item is received by copy so a buffer of * adequate size must be provided. The number of bytes copied into the buffer @@ -825,7 +856,7 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, * otherwise pdFALSE. * * Example usage: - *
+ * @code{c}
  * struct AMessage
  * {
  *  char ucMessageID;
@@ -875,7 +906,7 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue,
  *
  *  // ... Rest of task code.
  * }
- * 
+ * @endcode * \defgroup xQueueReceive xQueueReceive * \ingroup QueueManagement */ @@ -885,9 +916,9 @@ BaseType_t xQueueReceive( QueueHandle_t xQueue, /** * queue. h - *
+ * @code{c}
  * UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue );
- * 
+ * @endcode * * Return the number of messages stored in a queue. * @@ -902,9 +933,9 @@ UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) PRIVILEGED_FUNC /** * queue. h - *
+ * @code{c}
  * UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue );
- * 
+ * @endcode * * Return the number of free spaces available in a queue. This is equal to the * number of items that can be sent to the queue before the queue becomes full @@ -921,9 +952,9 @@ UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) PRIVILEGED_FUNC /** * queue. h - *
+ * @code{c}
  * void vQueueDelete( QueueHandle_t xQueue );
- * 
+ * @endcode * * Delete a queue - freeing all the memory allocated for storing of items * placed on the queue. @@ -937,13 +968,13 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueSendToFrontFromISR(
  *                                       QueueHandle_t xQueue,
  *                                       const void *pvItemToQueue,
  *                                       BaseType_t *pxHigherPriorityTaskWoken
  *                                    );
- * 
+ * @endcode * * This is a macro that calls xQueueGenericSendFromISR(). * @@ -964,7 +995,7 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * @param pxHigherPriorityTaskWoken xQueueSendToFrontFromISR() will set * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task * to unblock, and the unblocked task has a priority higher than the currently - * running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then + * running task. If xQueueSendToFrontFromISR() sets this value to pdTRUE then * a context switch should be requested before the interrupt is exited. * * @return pdTRUE if the data was successfully sent to the queue, otherwise @@ -972,11 +1003,11 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * * Example usage for buffered IO (where the ISR can obtain more than one value * per call): - *
+ * @code{c}
  * void vBufferISR( void )
  * {
  * char cIn;
- * BaseType_t xHigherPrioritTaskWoken;
+ * BaseType_t xHigherPriorityTaskWoken;
  *
  *  // We have not woken a task at the start of the ISR.
  *  xHigherPriorityTaskWoken = pdFALSE;
@@ -998,7 +1029,7 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
  *      taskYIELD ();
  *  }
  * }
- * 
+ * @endcode * * \defgroup xQueueSendFromISR xQueueSendFromISR * \ingroup QueueManagement @@ -1009,13 +1040,13 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueSendToBackFromISR(
  *                                       QueueHandle_t xQueue,
  *                                       const void *pvItemToQueue,
  *                                       BaseType_t *pxHigherPriorityTaskWoken
  *                                    );
- * 
+ * @endcode * * This is a macro that calls xQueueGenericSendFromISR(). * @@ -1044,7 +1075,7 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * * Example usage for buffered IO (where the ISR can obtain more than one value * per call): - *
+ * @code{c}
  * void vBufferISR( void )
  * {
  * char cIn;
@@ -1070,7 +1101,7 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
  *      taskYIELD ();
  *  }
  * }
- * 
+ * @endcode * * \defgroup xQueueSendFromISR xQueueSendFromISR * \ingroup QueueManagement @@ -1080,13 +1111,13 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueOverwriteFromISR(
  *                            QueueHandle_t xQueue,
  *                            const void * pvItemToQueue,
  *                            BaseType_t *pxHigherPriorityTaskWoken
  *                       );
- * 
+ * @endcode * * A version of xQueueOverwrite() that can be used in an interrupt service * routine (ISR). @@ -1117,7 +1148,7 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * the queue is already full. * * Example usage: - *
+ * @code{c}
  *
  * QueueHandle_t xQueue;
  *
@@ -1154,12 +1185,15 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
  *  {
  *      // Writing to the queue caused a task to unblock and the unblocked task
  *      // has a priority higher than or equal to the priority of the currently
- *      // executing task (the task this interrupt interrupted).  Perform a context
+ *      // executing task (the task this interrupt interrupted). Perform a context
  *      // switch so this interrupt returns directly to the unblocked task.
- *      portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port.
+ *      // The macro used is port specific and will be either
+ *      // portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to the documentation
+ *      // page for the port being used.
+ *      portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
  *  }
  * }
- * 
+ * @endcode * \defgroup xQueueOverwriteFromISR xQueueOverwriteFromISR * \ingroup QueueManagement */ @@ -1168,13 +1202,13 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueSendFromISR(
  *                                   QueueHandle_t xQueue,
  *                                   const void *pvItemToQueue,
  *                                   BaseType_t *pxHigherPriorityTaskWoken
  *                              );
- * 
+ * @endcode * * This is a macro that calls xQueueGenericSendFromISR(). It is included * for backward compatibility with versions of FreeRTOS.org that did not @@ -1206,7 +1240,7 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * * Example usage for buffered IO (where the ISR can obtain more than one value * per call): - *
+ * @code{c}
  * void vBufferISR( void )
  * {
  * char cIn;
@@ -1229,11 +1263,14 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
  *  // Now the buffer is empty we can switch context if necessary.
  *  if( xHigherPriorityTaskWoken )
  *  {
- *      // Actual macro used here is port specific.
- *      portYIELD_FROM_ISR ();
+ *       // As xHigherPriorityTaskWoken is now set to pdTRUE then a context
+ *       // switch should be requested. The macro used is port specific and
+ *       // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() -
+ *       // refer to the documentation page for the port being used.
+ *       portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
  *  }
  * }
- * 
+ * @endcode * * \defgroup xQueueSendFromISR xQueueSendFromISR * \ingroup QueueManagement @@ -1243,14 +1280,14 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueGenericSendFromISR(
  *                                         QueueHandle_t    xQueue,
  *                                         const    void    *pvItemToQueue,
  *                                         BaseType_t  *pxHigherPriorityTaskWoken,
  *                                         BaseType_t  xCopyPosition
  *                                     );
- * 
+ * @endcode * * It is preferred that the macros xQueueSendFromISR(), * xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place @@ -1286,7 +1323,7 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * * Example usage for buffered IO (where the ISR can obtain more than one value * per call): - *
+ * @code{c}
  * void vBufferISR( void )
  * {
  * char cIn;
@@ -1306,14 +1343,17 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
  *
  *  } while( portINPUT_BYTE( BUFFER_COUNT ) );
  *
- *  // Now the buffer is empty we can switch context if necessary.  Note that the
- *  // name of the yield function required is port specific.
+ *  // Now the buffer is empty we can switch context if necessary.
  *  if( xHigherPriorityTaskWokenByPost )
  *  {
- *      portYIELD_FROM_ISR();
+ *       // As xHigherPriorityTaskWokenByPost is now set to pdTRUE then a context
+ *       // switch should be requested. The macro used is port specific and
+ *       // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() -
+ *       // refer to the documentation page for the port being used.
+ *       portYIELD_FROM_ISR( xHigherPriorityTaskWokenByPost );
  *  }
  * }
- * 
+ * @endcode * * \defgroup xQueueSendFromISR xQueueSendFromISR * \ingroup QueueManagement @@ -1327,13 +1367,13 @@ BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, /** * queue. h - *
+ * @code{c}
  * BaseType_t xQueueReceiveFromISR(
  *                                     QueueHandle_t    xQueue,
  *                                     void             *pvBuffer,
  *                                     BaseType_t       *pxTaskWoken
  *                                 );
- * 
+ * @endcode * * Receive an item from a queue. It is safe to use this function from within an * interrupt service routine. @@ -1344,16 +1384,16 @@ BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, * @param pvBuffer Pointer to the buffer into which the received item will * be copied. * - * @param pxTaskWoken A task may be blocked waiting for space to become - * available on the queue. If xQueueReceiveFromISR causes such a task to - * unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will + * @param pxHigherPriorityTaskWoken A task may be blocked waiting for space to + * become available on the queue. If xQueueReceiveFromISR causes such a task + * to unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will * remain unchanged. * * @return pdTRUE if an item was successfully received from the queue, * otherwise pdFALSE. * * Example usage: - *
+ * @code{c}
  *
  * QueueHandle_t xQueue;
  *
@@ -1398,17 +1438,17 @@ BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue,
  *      vOutputCharacter( cRxedChar );
  *
  *      // If removing the character from the queue woke the task that was
- *      // posting onto the queue cTaskWokenByReceive will have been set to
+ *      // posting onto the queue xTaskWokenByReceive will have been set to
  *      // pdTRUE.  No matter how many times this loop iterates only one
  *      // task will be woken.
  *  }
  *
- *  if( cTaskWokenByPost != ( char ) pdFALSE;
+ *  if( xTaskWokenByReceive != ( char ) pdFALSE;
  *  {
  *      taskYIELD ();
  *  }
  * }
- * 
+ * @endcode * \defgroup xQueueReceiveFromISR xQueueReceiveFromISR * \ingroup QueueManagement */ @@ -1418,12 +1458,14 @@ BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, /* * Utilities to query queues that are safe to use from an ISR. These utilities - * should be used only from witin an ISR, or within a critical section. + * should be used only from within an ISR, or within a critical section. */ BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +#if ( configUSE_CO_ROUTINES == 1 ) + /* * The functions defined above are for passing data to and from tasks. The * functions below are the equivalents for passing data to and from @@ -1433,18 +1475,20 @@ UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) PRIVILEG * should not be called directly from application code. Instead use the macro * wrappers defined within croutine.h. */ -BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, - const void * pvItemToQueue, - BaseType_t xCoRoutinePreviouslyWoken ); -BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, - void * pvBuffer, - BaseType_t * pxTaskWoken ); -BaseType_t xQueueCRSend( QueueHandle_t xQueue, - const void * pvItemToQueue, - TickType_t xTicksToWait ); -BaseType_t xQueueCRReceive( QueueHandle_t xQueue, - void * pvBuffer, - TickType_t xTicksToWait ); + BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, + const void * pvItemToQueue, + BaseType_t xCoRoutinePreviouslyWoken ); + BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, + void * pvBuffer, + BaseType_t * pxTaskWoken ); + BaseType_t xQueueCRSend( QueueHandle_t xQueue, + const void * pvItemToQueue, + TickType_t xTicksToWait ); + BaseType_t xQueueCRReceive( QueueHandle_t xQueue, + void * pvBuffer, + TickType_t xTicksToWait ); + +#endif /* if ( configUSE_CO_ROUTINES == 1 ) */ /* * For internal use only. Use xSemaphoreCreateMutex(), @@ -1452,21 +1496,34 @@ BaseType_t xQueueCRReceive( QueueHandle_t xQueue, * these functions directly. */ QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; -QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, - StaticQueue_t * pxStaticQueue ) PRIVILEGED_FUNCTION; -QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, - const UBaseType_t uxInitialCount ) PRIVILEGED_FUNCTION; -QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, - const UBaseType_t uxInitialCount, - StaticQueue_t * pxStaticQueue ) PRIVILEGED_FUNCTION; + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, + StaticQueue_t * pxStaticQueue ) PRIVILEGED_FUNCTION; +#endif + +#if ( configUSE_COUNTING_SEMAPHORES == 1 ) + QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount ) PRIVILEGED_FUNCTION; +#endif + +#if ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount, + StaticQueue_t * pxStaticQueue ) PRIVILEGED_FUNCTION; +#endif + BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; -TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; -TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; + +#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) + TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; + TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; +#endif /* - * For internal use only. Use xSemaphoreTakeMutexRecursive() or - * xSemaphoreGiveMutexRecursive() instead of calling these functions directly. + * For internal use only. Use xSemaphoreTakeRecursive() or + * xSemaphoreGiveRecursive() instead of calling these functions directly. */ BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; @@ -1476,7 +1533,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * Reset a queue back to its original empty state. The return value is now * obsolete and is always set to pdPASS. */ -#define xQueueReset( xQueue ) xQueueGenericReset( xQueue, pdFALSE ) +#define xQueueReset( xQueue ) xQueueGenericReset( ( xQueue ), pdFALSE ) /* * The registry is provided as a means for kernel aware debuggers to @@ -1488,21 +1545,25 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * configQUEUE_REGISTRY_SIZE defines the maximum number of handles the * registry can hold. configQUEUE_REGISTRY_SIZE must be greater than 0 * within FreeRTOSConfig.h for the registry to be available. Its value - * does not effect the number of queues, semaphores and mutexes that can be + * does not affect the number of queues, semaphores and mutexes that can be * created - just the number that the registry can hold. * + * If vQueueAddToRegistry is called more than once with the same xQueue + * parameter, the registry will store the pcQueueName parameter from the + * most recent call to vQueueAddToRegistry. + * * @param xQueue The handle of the queue being added to the registry. This * is the handle returned by a call to xQueueCreate(). Semaphore and mutex * handles can also be passed in here. * - * @param pcName The name to be associated with the handle. This is the + * @param pcQueueName The name to be associated with the handle. This is the * name that the kernel aware debugger will display. The queue registry only * stores a pointer to the string - so the string must be persistent (global or * preferably in ROM/Flash), not on the stack. */ #if ( configQUEUE_REGISTRY_SIZE > 0 ) void vQueueAddToRegistry( QueueHandle_t xQueue, - const char * pcQueueName ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const char * pcQueueName ) PRIVILEGED_FUNCTION; #endif /* @@ -1531,7 +1592,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * returned. */ #if ( configQUEUE_REGISTRY_SIZE > 0 ) - const char * pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const char * pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; #endif /* @@ -1558,6 +1619,18 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; #endif +/* + * Generic version of the function used to retrieve the buffers of statically + * created queues. This is called by other functions and macros that retrieve + * the buffers of other statically created RTOS objects that use the queue + * structure as their base. + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + BaseType_t xQueueGenericGetStaticBuffers( QueueHandle_t xQueue, + uint8_t ** ppucQueueStorage, + StaticQueue_t ** ppxStaticQueue ) PRIVILEGED_FUNCTION; +#endif + /* * Queue sets provide a mechanism to allow a task to block (pend) on a read * operation from multiple queues or semaphores simultaneously. @@ -1572,7 +1645,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * or semaphores contained in the set is in a state where a queue read or * semaphore take operation would be successful. * - * Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html + * Note 1: See the documentation on https://www.FreeRTOS.org/RTOS-queue-sets.html * for reasons why queue sets are very rarely needed in practice as there are * simpler methods of blocking on multiple objects. * @@ -1606,7 +1679,9 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * @return If the queue set is created successfully then a handle to the created * queue set is returned. Otherwise NULL is returned. */ -QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILEGED_FUNCTION; +#if ( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILEGED_FUNCTION; +#endif /* * Adds a queue or semaphore to a queue set that was previously created by a @@ -1630,8 +1705,10 @@ QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILE * queue set because it is already a member of a different queue set then pdFAIL * is returned. */ -BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, - QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; +#if ( configUSE_QUEUE_SETS == 1 ) + BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; +#endif /* * Removes a queue or semaphore from a queue set. A queue or semaphore can only @@ -1650,8 +1727,10 @@ BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, * then pdPASS is returned. If the queue was not in the queue set, or the * queue (or semaphore) was not empty, then pdFAIL is returned. */ -BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, - QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; +#if ( configUSE_QUEUE_SETS == 1 ) + BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; +#endif /* * xQueueSelectFromSet() selects from the members of a queue set a queue or @@ -1663,7 +1742,7 @@ BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this * function. * - * Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html + * Note 1: See the documentation on https://www.FreeRTOS.org/RTOS-queue-sets.html * for reasons why queue sets are very rarely needed in practice as there are * simpler methods of blocking on multiple objects. * @@ -1687,13 +1766,17 @@ BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, * in the queue set that is available, or NULL if no such queue or semaphore * exists before before the specified block time expires. */ -QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, - const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +#if ( configUSE_QUEUE_SETS == 1 ) + QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, + const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +#endif /* * A version of xQueueSelectFromSet() that can be used from an ISR. */ -QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; +#if ( configUSE_QUEUE_SETS == 1 ) + QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; +#endif /* Not public API functions. */ void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, @@ -1701,11 +1784,22 @@ void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, const BaseType_t xWaitIndefinitely ) PRIVILEGED_FUNCTION; BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) PRIVILEGED_FUNCTION; -void vQueueSetQueueNumber( QueueHandle_t xQueue, - UBaseType_t uxQueueNumber ) PRIVILEGED_FUNCTION; -UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; -uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +#if ( configUSE_TRACE_FACILITY == 1 ) + void vQueueSetQueueNumber( QueueHandle_t xQueue, + UBaseType_t uxQueueNumber ) PRIVILEGED_FUNCTION; +#endif + +#if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +#endif + +#if ( configUSE_TRACE_FACILITY == 1 ) + uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +#endif + +UBaseType_t uxQueueGetQueueItemSize( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +UBaseType_t uxQueueGetQueueLength( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /* *INDENT-OFF* */ #ifdef __cplusplus diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/semphr.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/semphr.h index fa82554e2..13e01339d 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/semphr.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/semphr.h @@ -1,1173 +1,1215 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -#ifndef SEMAPHORE_H -#define SEMAPHORE_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h" must appear in source files before "include semphr.h" -#endif - -#include "queue.h" - -typedef QueueHandle_t SemaphoreHandle_t; - -#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) -#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) -#define semGIVE_BLOCK_TIME ( ( TickType_t ) 0U ) - - -/** - * semphr. h - *
- * vSemaphoreCreateBinary( SemaphoreHandle_t xSemaphore );
- * 
- * - * In many usage scenarios it is faster and more memory efficient to use a - * direct to task notification in place of a binary semaphore! - * https://www.FreeRTOS.org/RTOS-task-notifications.html - * - * This old vSemaphoreCreateBinary() macro is now deprecated in favour of the - * xSemaphoreCreateBinary() function. Note that binary semaphores created using - * the vSemaphoreCreateBinary() macro are created in a state such that the - * first call to 'take' the semaphore would pass, whereas binary semaphores - * created using xSemaphoreCreateBinary() are created in a state such that the - * the semaphore must first be 'given' before it can be 'taken'. - * - * Macro that implements a semaphore by using the existing queue mechanism. - * The queue length is 1 as this is a binary semaphore. The data size is 0 - * as we don't want to actually store any data - we just want to know if the - * queue is empty or full. - * - * This type of semaphore can be used for pure synchronisation between tasks or - * between an interrupt and a task. The semaphore need not be given back once - * obtained, so one task/interrupt can continuously 'give' the semaphore while - * another continuously 'takes' the semaphore. For this reason this type of - * semaphore does not use a priority inheritance mechanism. For an alternative - * that does use priority inheritance see xSemaphoreCreateMutex(). - * - * @param xSemaphore Handle to the created semaphore. Should be of type SemaphoreHandle_t. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore = NULL;
- *
- * void vATask( void * pvParameters )
- * {
- *  // Semaphore cannot be used before a call to vSemaphoreCreateBinary ().
- *  // This is a macro so pass the variable in directly.
- *  vSemaphoreCreateBinary( xSemaphore );
- *
- *  if( xSemaphore != NULL )
- *  {
- *      // The semaphore was created successfully.
- *      // The semaphore can now be used.
- *  }
- * }
- * 
- * \defgroup vSemaphoreCreateBinary vSemaphoreCreateBinary - * \ingroup Semaphores - */ -#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define vSemaphoreCreateBinary( xSemaphore ) \ - { \ - ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ - if( ( xSemaphore ) != NULL ) \ - { \ - ( void ) xSemaphoreGive( ( xSemaphore ) ); \ - } \ - } -#endif - -/** - * semphr. h - *
- * SemaphoreHandle_t xSemaphoreCreateBinary( void );
- * 
- * - * Creates a new binary semaphore instance, and returns a handle by which the - * new semaphore can be referenced. - * - * In many usage scenarios it is faster and more memory efficient to use a - * direct to task notification in place of a binary semaphore! - * https://www.FreeRTOS.org/RTOS-task-notifications.html - * - * Internally, within the FreeRTOS implementation, binary semaphores use a block - * of memory, in which the semaphore structure is stored. If a binary semaphore - * is created using xSemaphoreCreateBinary() then the required memory is - * automatically dynamically allocated inside the xSemaphoreCreateBinary() - * function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore - * is created using xSemaphoreCreateBinaryStatic() then the application writer - * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a - * binary semaphore to be created without using any dynamic memory allocation. - * - * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this - * xSemaphoreCreateBinary() function. Note that binary semaphores created using - * the vSemaphoreCreateBinary() macro are created in a state such that the - * first call to 'take' the semaphore would pass, whereas binary semaphores - * created using xSemaphoreCreateBinary() are created in a state such that the - * the semaphore must first be 'given' before it can be 'taken'. - * - * This type of semaphore can be used for pure synchronisation between tasks or - * between an interrupt and a task. The semaphore need not be given back once - * obtained, so one task/interrupt can continuously 'give' the semaphore while - * another continuously 'takes' the semaphore. For this reason this type of - * semaphore does not use a priority inheritance mechanism. For an alternative - * that does use priority inheritance see xSemaphoreCreateMutex(). - * - * @return Handle to the created semaphore, or NULL if the memory required to - * hold the semaphore's data structures could not be allocated. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore = NULL;
- *
- * void vATask( void * pvParameters )
- * {
- *  // Semaphore cannot be used before a call to xSemaphoreCreateBinary().
- *  // This is a macro so pass the variable in directly.
- *  xSemaphore = xSemaphoreCreateBinary();
- *
- *  if( xSemaphore != NULL )
- *  {
- *      // The semaphore was created successfully.
- *      // The semaphore can now be used.
- *  }
- * }
- * 
- * \defgroup xSemaphoreCreateBinary xSemaphoreCreateBinary - * \ingroup Semaphores - */ -#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ) -#endif - -/** - * semphr. h - *
- * SemaphoreHandle_t xSemaphoreCreateBinaryStatic( StaticSemaphore_t *pxSemaphoreBuffer );
- * 
- * - * Creates a new binary semaphore instance, and returns a handle by which the - * new semaphore can be referenced. - * - * NOTE: In many usage scenarios it is faster and more memory efficient to use a - * direct to task notification in place of a binary semaphore! - * https://www.FreeRTOS.org/RTOS-task-notifications.html - * - * Internally, within the FreeRTOS implementation, binary semaphores use a block - * of memory, in which the semaphore structure is stored. If a binary semaphore - * is created using xSemaphoreCreateBinary() then the required memory is - * automatically dynamically allocated inside the xSemaphoreCreateBinary() - * function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore - * is created using xSemaphoreCreateBinaryStatic() then the application writer - * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a - * binary semaphore to be created without using any dynamic memory allocation. - * - * This type of semaphore can be used for pure synchronisation between tasks or - * between an interrupt and a task. The semaphore need not be given back once - * obtained, so one task/interrupt can continuously 'give' the semaphore while - * another continuously 'takes' the semaphore. For this reason this type of - * semaphore does not use a priority inheritance mechanism. For an alternative - * that does use priority inheritance see xSemaphoreCreateMutex(). - * - * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, - * which will then be used to hold the semaphore's data structure, removing the - * need for the memory to be allocated dynamically. - * - * @return If the semaphore is created then a handle to the created semaphore is - * returned. If pxSemaphoreBuffer is NULL then NULL is returned. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore = NULL;
- * StaticSemaphore_t xSemaphoreBuffer;
- *
- * void vATask( void * pvParameters )
- * {
- *  // Semaphore cannot be used before a call to xSemaphoreCreateBinary().
- *  // The semaphore's data structures will be placed in the xSemaphoreBuffer
- *  // variable, the address of which is passed into the function.  The
- *  // function's parameter is not NULL, so the function will not attempt any
- *  // dynamic memory allocation, and therefore the function will not return
- *  // return NULL.
- *  xSemaphore = xSemaphoreCreateBinary( &xSemaphoreBuffer );
- *
- *  // Rest of task code goes here.
- * }
- * 
- * \defgroup xSemaphoreCreateBinaryStatic xSemaphoreCreateBinaryStatic - * \ingroup Semaphores - */ -#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE ) -#endif /* configSUPPORT_STATIC_ALLOCATION */ - -/** - * semphr. h - *
- * xSemaphoreTake(
- *                   SemaphoreHandle_t xSemaphore,
- *                   TickType_t xBlockTime
- *               );
- * 
- * - * Macro to obtain a semaphore. The semaphore must have previously been - * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or - * xSemaphoreCreateCounting(). - * - * @param xSemaphore A handle to the semaphore being taken - obtained when - * the semaphore was created. - * - * @param xBlockTime The time in ticks to wait for the semaphore to become - * available. The macro portTICK_PERIOD_MS can be used to convert this to a - * real time. A block time of zero can be used to poll the semaphore. A block - * time of portMAX_DELAY can be used to block indefinitely (provided - * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). - * - * @return pdTRUE if the semaphore was obtained. pdFALSE - * if xBlockTime expired without the semaphore becoming available. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore = NULL;
- *
- * // A task that creates a semaphore.
- * void vATask( void * pvParameters )
- * {
- *  // Create the semaphore to guard a shared resource.
- *  xSemaphore = xSemaphoreCreateBinary();
- * }
- *
- * // A task that uses the semaphore.
- * void vAnotherTask( void * pvParameters )
- * {
- *  // ... Do other things.
- *
- *  if( xSemaphore != NULL )
- *  {
- *      // See if we can obtain the semaphore.  If the semaphore is not available
- *      // wait 10 ticks to see if it becomes free.
- *      if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE )
- *      {
- *          // We were able to obtain the semaphore and can now access the
- *          // shared resource.
- *
- *          // ...
- *
- *          // We have finished accessing the shared resource.  Release the
- *          // semaphore.
- *          xSemaphoreGive( xSemaphore );
- *      }
- *      else
- *      {
- *          // We could not obtain the semaphore and can therefore not access
- *          // the shared resource safely.
- *      }
- *  }
- * }
- * 
- * \defgroup xSemaphoreTake xSemaphoreTake - * \ingroup Semaphores - */ -#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) ) - -/** - * semphr. h - *
- * xSemaphoreTakeRecursive(
- *                          SemaphoreHandle_t xMutex,
- *                          TickType_t xBlockTime
- *                        );
- * 
- * - * Macro to recursively obtain, or 'take', a mutex type semaphore. - * The mutex must have previously been created using a call to - * xSemaphoreCreateRecursiveMutex(); - * - * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this - * macro to be available. - * - * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). - * - * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex - * doesn't become available again until the owner has called - * xSemaphoreGiveRecursive() for each successful 'take' request. For example, - * if a task successfully 'takes' the same mutex 5 times then the mutex will - * not be available to any other task until it has also 'given' the mutex back - * exactly five times. - * - * @param xMutex A handle to the mutex being obtained. This is the - * handle returned by xSemaphoreCreateRecursiveMutex(); - * - * @param xBlockTime The time in ticks to wait for the semaphore to become - * available. The macro portTICK_PERIOD_MS can be used to convert this to a - * real time. A block time of zero can be used to poll the semaphore. If - * the task already owns the semaphore then xSemaphoreTakeRecursive() will - * return immediately no matter what the value of xBlockTime. - * - * @return pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime - * expired without the semaphore becoming available. - * - * Example usage: - *
- * SemaphoreHandle_t xMutex = NULL;
- *
- * // A task that creates a mutex.
- * void vATask( void * pvParameters )
- * {
- *  // Create the mutex to guard a shared resource.
- *  xMutex = xSemaphoreCreateRecursiveMutex();
- * }
- *
- * // A task that uses the mutex.
- * void vAnotherTask( void * pvParameters )
- * {
- *  // ... Do other things.
- *
- *  if( xMutex != NULL )
- *  {
- *      // See if we can obtain the mutex.  If the mutex is not available
- *      // wait 10 ticks to see if it becomes free.
- *      if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE )
- *      {
- *          // We were able to obtain the mutex and can now access the
- *          // shared resource.
- *
- *          // ...
- *          // For some reason due to the nature of the code further calls to
- *          // xSemaphoreTakeRecursive() are made on the same mutex.  In real
- *          // code these would not be just sequential calls as this would make
- *          // no sense.  Instead the calls are likely to be buried inside
- *          // a more complex call structure.
- *          xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
- *          xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
- *
- *          // The mutex has now been 'taken' three times, so will not be
- *          // available to another task until it has also been given back
- *          // three times.  Again it is unlikely that real code would have
- *          // these calls sequentially, but instead buried in a more complex
- *          // call structure.  This is just for illustrative purposes.
- *          xSemaphoreGiveRecursive( xMutex );
- *          xSemaphoreGiveRecursive( xMutex );
- *          xSemaphoreGiveRecursive( xMutex );
- *
- *          // Now the mutex can be taken by other tasks.
- *      }
- *      else
- *      {
- *          // We could not obtain the mutex and can therefore not access
- *          // the shared resource safely.
- *      }
- *  }
- * }
- * 
- * \defgroup xSemaphoreTakeRecursive xSemaphoreTakeRecursive - * \ingroup Semaphores - */ -#if ( configUSE_RECURSIVE_MUTEXES == 1 ) - #define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) ) -#endif - -/** - * semphr. h - *
- * xSemaphoreGive( SemaphoreHandle_t xSemaphore );
- * 
- * - * Macro to release a semaphore. The semaphore must have previously been - * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or - * xSemaphoreCreateCounting(). and obtained using sSemaphoreTake(). - * - * This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for - * an alternative which can be used from an ISR. - * - * This macro must also not be used on semaphores created using - * xSemaphoreCreateRecursiveMutex(). - * - * @param xSemaphore A handle to the semaphore being released. This is the - * handle returned when the semaphore was created. - * - * @return pdTRUE if the semaphore was released. pdFALSE if an error occurred. - * Semaphores are implemented using queues. An error can occur if there is - * no space on the queue to post a message - indicating that the - * semaphore was not first obtained correctly. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore = NULL;
- *
- * void vATask( void * pvParameters )
- * {
- *  // Create the semaphore to guard a shared resource.
- *  xSemaphore = vSemaphoreCreateBinary();
- *
- *  if( xSemaphore != NULL )
- *  {
- *      if( xSemaphoreGive( xSemaphore ) != pdTRUE )
- *      {
- *          // We would expect this call to fail because we cannot give
- *          // a semaphore without first "taking" it!
- *      }
- *
- *      // Obtain the semaphore - don't block if the semaphore is not
- *      // immediately available.
- *      if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) )
- *      {
- *          // We now have the semaphore and can access the shared resource.
- *
- *          // ...
- *
- *          // We have finished accessing the shared resource so can free the
- *          // semaphore.
- *          if( xSemaphoreGive( xSemaphore ) != pdTRUE )
- *          {
- *              // We would not expect this call to fail because we must have
- *              // obtained the semaphore to get here.
- *          }
- *      }
- *  }
- * }
- * 
- * \defgroup xSemaphoreGive xSemaphoreGive - * \ingroup Semaphores - */ -#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) - -/** - * semphr. h - *
- * xSemaphoreGiveRecursive( SemaphoreHandle_t xMutex );
- * 
- * - * Macro to recursively release, or 'give', a mutex type semaphore. - * The mutex must have previously been created using a call to - * xSemaphoreCreateRecursiveMutex(); - * - * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this - * macro to be available. - * - * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). - * - * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex - * doesn't become available again until the owner has called - * xSemaphoreGiveRecursive() for each successful 'take' request. For example, - * if a task successfully 'takes' the same mutex 5 times then the mutex will - * not be available to any other task until it has also 'given' the mutex back - * exactly five times. - * - * @param xMutex A handle to the mutex being released, or 'given'. This is the - * handle returned by xSemaphoreCreateMutex(); - * - * @return pdTRUE if the semaphore was given. - * - * Example usage: - *
- * SemaphoreHandle_t xMutex = NULL;
- *
- * // A task that creates a mutex.
- * void vATask( void * pvParameters )
- * {
- *  // Create the mutex to guard a shared resource.
- *  xMutex = xSemaphoreCreateRecursiveMutex();
- * }
- *
- * // A task that uses the mutex.
- * void vAnotherTask( void * pvParameters )
- * {
- *  // ... Do other things.
- *
- *  if( xMutex != NULL )
- *  {
- *      // See if we can obtain the mutex.  If the mutex is not available
- *      // wait 10 ticks to see if it becomes free.
- *      if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE )
- *      {
- *          // We were able to obtain the mutex and can now access the
- *          // shared resource.
- *
- *          // ...
- *          // For some reason due to the nature of the code further calls to
- *          // xSemaphoreTakeRecursive() are made on the same mutex.  In real
- *          // code these would not be just sequential calls as this would make
- *          // no sense.  Instead the calls are likely to be buried inside
- *          // a more complex call structure.
- *          xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
- *          xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
- *
- *          // The mutex has now been 'taken' three times, so will not be
- *          // available to another task until it has also been given back
- *          // three times.  Again it is unlikely that real code would have
- *          // these calls sequentially, it would be more likely that the calls
- *          // to xSemaphoreGiveRecursive() would be called as a call stack
- *          // unwound.  This is just for demonstrative purposes.
- *          xSemaphoreGiveRecursive( xMutex );
- *          xSemaphoreGiveRecursive( xMutex );
- *          xSemaphoreGiveRecursive( xMutex );
- *
- *          // Now the mutex can be taken by other tasks.
- *      }
- *      else
- *      {
- *          // We could not obtain the mutex and can therefore not access
- *          // the shared resource safely.
- *      }
- *  }
- * }
- * 
- * \defgroup xSemaphoreGiveRecursive xSemaphoreGiveRecursive - * \ingroup Semaphores - */ -#if ( configUSE_RECURSIVE_MUTEXES == 1 ) - #define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) ) -#endif - -/** - * semphr. h - *
- * xSemaphoreGiveFromISR(
- *                        SemaphoreHandle_t xSemaphore,
- *                        BaseType_t *pxHigherPriorityTaskWoken
- *                    );
- * 
- * - * Macro to release a semaphore. The semaphore must have previously been - * created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). - * - * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) - * must not be used with this macro. - * - * This macro can be used from an ISR. - * - * @param xSemaphore A handle to the semaphore being released. This is the - * handle returned when the semaphore was created. - * - * @param pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set - * *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task - * to unblock, and the unblocked task has a priority higher than the currently - * running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then - * a context switch should be requested before the interrupt is exited. - * - * @return pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL. - * - * Example usage: - *
- \#define LONG_TIME 0xffff
- \#define TICKS_TO_WAIT 10
- * SemaphoreHandle_t xSemaphore = NULL;
- *
- * // Repetitive task.
- * void vATask( void * pvParameters )
- * {
- *  for( ;; )
- *  {
- *      // We want this task to run every 10 ticks of a timer.  The semaphore
- *      // was created before this task was started.
- *
- *      // Block waiting for the semaphore to become available.
- *      if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE )
- *      {
- *          // It is time to execute.
- *
- *          // ...
- *
- *          // We have finished our task.  Return to the top of the loop where
- *          // we will block on the semaphore until it is time to execute
- *          // again.  Note when using the semaphore for synchronisation with an
- *          // ISR in this manner there is no need to 'give' the semaphore back.
- *      }
- *  }
- * }
- *
- * // Timer ISR
- * void vTimerISR( void * pvParameters )
- * {
- * static uint8_t ucLocalTickCount = 0;
- * static BaseType_t xHigherPriorityTaskWoken;
- *
- *  // A timer tick has occurred.
- *
- *  // ... Do other time functions.
- *
- *  // Is it time for vATask () to run?
- *  xHigherPriorityTaskWoken = pdFALSE;
- *  ucLocalTickCount++;
- *  if( ucLocalTickCount >= TICKS_TO_WAIT )
- *  {
- *      // Unblock the task by releasing the semaphore.
- *      xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken );
- *
- *      // Reset the count so we release the semaphore again in 10 ticks time.
- *      ucLocalTickCount = 0;
- *  }
- *
- *  if( xHigherPriorityTaskWoken != pdFALSE )
- *  {
- *      // We can force a context switch here.  Context switching from an
- *      // ISR uses port specific syntax.  Check the demo task for your port
- *      // to find the syntax required.
- *  }
- * }
- * 
- * \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR - * \ingroup Semaphores - */ -#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) ) - -/** - * semphr. h - *
- * xSemaphoreTakeFromISR(
- *                        SemaphoreHandle_t xSemaphore,
- *                        BaseType_t *pxHigherPriorityTaskWoken
- *                    );
- * 
- * - * Macro to take a semaphore from an ISR. The semaphore must have - * previously been created with a call to xSemaphoreCreateBinary() or - * xSemaphoreCreateCounting(). - * - * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) - * must not be used with this macro. - * - * This macro can be used from an ISR, however taking a semaphore from an ISR - * is not a common operation. It is likely to only be useful when taking a - * counting semaphore when an interrupt is obtaining an object from a resource - * pool (when the semaphore count indicates the number of resources available). - * - * @param xSemaphore A handle to the semaphore being taken. This is the - * handle returned when the semaphore was created. - * - * @param pxHigherPriorityTaskWoken xSemaphoreTakeFromISR() will set - * *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task - * to unblock, and the unblocked task has a priority higher than the currently - * running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then - * a context switch should be requested before the interrupt is exited. - * - * @return pdTRUE if the semaphore was successfully taken, otherwise - * pdFALSE - */ -#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) ) - -/** - * semphr. h - *
- * SemaphoreHandle_t xSemaphoreCreateMutex( void );
- * 
- * - * Creates a new mutex type semaphore instance, and returns a handle by which - * the new mutex can be referenced. - * - * Internally, within the FreeRTOS implementation, mutex semaphores use a block - * of memory, in which the mutex structure is stored. If a mutex is created - * using xSemaphoreCreateMutex() then the required memory is automatically - * dynamically allocated inside the xSemaphoreCreateMutex() function. (see - * https://www.FreeRTOS.org/a00111.html). If a mutex is created using - * xSemaphoreCreateMutexStatic() then the application writer must provided the - * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created - * without using any dynamic memory allocation. - * - * Mutexes created using this function can be accessed using the xSemaphoreTake() - * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and - * xSemaphoreGiveRecursive() macros must not be used. - * - * This type of semaphore uses a priority inheritance mechanism so a task - * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the - * semaphore it is no longer required. - * - * Mutex type semaphores cannot be used from within interrupt service routines. - * - * See xSemaphoreCreateBinary() for an alternative implementation that can be - * used for pure synchronisation (where one task or interrupt always 'gives' the - * semaphore and another always 'takes' the semaphore) and from within interrupt - * service routines. - * - * @return If the mutex was successfully created then a handle to the created - * semaphore is returned. If there was not enough heap to allocate the mutex - * data structures then NULL is returned. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore;
- *
- * void vATask( void * pvParameters )
- * {
- *  // Semaphore cannot be used before a call to xSemaphoreCreateMutex().
- *  // This is a macro so pass the variable in directly.
- *  xSemaphore = xSemaphoreCreateMutex();
- *
- *  if( xSemaphore != NULL )
- *  {
- *      // The semaphore was created successfully.
- *      // The semaphore can now be used.
- *  }
- * }
- * 
- * \defgroup xSemaphoreCreateMutex xSemaphoreCreateMutex - * \ingroup Semaphores - */ -#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX ) -#endif - -/** - * semphr. h - *
- * SemaphoreHandle_t xSemaphoreCreateMutexStatic( StaticSemaphore_t *pxMutexBuffer );
- * 
- * - * Creates a new mutex type semaphore instance, and returns a handle by which - * the new mutex can be referenced. - * - * Internally, within the FreeRTOS implementation, mutex semaphores use a block - * of memory, in which the mutex structure is stored. If a mutex is created - * using xSemaphoreCreateMutex() then the required memory is automatically - * dynamically allocated inside the xSemaphoreCreateMutex() function. (see - * https://www.FreeRTOS.org/a00111.html). If a mutex is created using - * xSemaphoreCreateMutexStatic() then the application writer must provided the - * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created - * without using any dynamic memory allocation. - * - * Mutexes created using this function can be accessed using the xSemaphoreTake() - * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and - * xSemaphoreGiveRecursive() macros must not be used. - * - * This type of semaphore uses a priority inheritance mechanism so a task - * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the - * semaphore it is no longer required. - * - * Mutex type semaphores cannot be used from within interrupt service routines. - * - * See xSemaphoreCreateBinary() for an alternative implementation that can be - * used for pure synchronisation (where one task or interrupt always 'gives' the - * semaphore and another always 'takes' the semaphore) and from within interrupt - * service routines. - * - * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, - * which will be used to hold the mutex's data structure, removing the need for - * the memory to be allocated dynamically. - * - * @return If the mutex was successfully created then a handle to the created - * mutex is returned. If pxMutexBuffer was NULL then NULL is returned. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore;
- * StaticSemaphore_t xMutexBuffer;
- *
- * void vATask( void * pvParameters )
- * {
- *  // A mutex cannot be used before it has been created.  xMutexBuffer is
- *  // into xSemaphoreCreateMutexStatic() so no dynamic memory allocation is
- *  // attempted.
- *  xSemaphore = xSemaphoreCreateMutexStatic( &xMutexBuffer );
- *
- *  // As no dynamic memory allocation was performed, xSemaphore cannot be NULL,
- *  // so there is no need to check it.
- * }
- * 
- * \defgroup xSemaphoreCreateMutexStatic xSemaphoreCreateMutexStatic - * \ingroup Semaphores - */ -#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) ) -#endif /* configSUPPORT_STATIC_ALLOCATION */ - - -/** - * semphr. h - *
- * SemaphoreHandle_t xSemaphoreCreateRecursiveMutex( void );
- * 
- * - * Creates a new recursive mutex type semaphore instance, and returns a handle - * by which the new recursive mutex can be referenced. - * - * Internally, within the FreeRTOS implementation, recursive mutexs use a block - * of memory, in which the mutex structure is stored. If a recursive mutex is - * created using xSemaphoreCreateRecursiveMutex() then the required memory is - * automatically dynamically allocated inside the - * xSemaphoreCreateRecursiveMutex() function. (see - * https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using - * xSemaphoreCreateRecursiveMutexStatic() then the application writer must - * provide the memory that will get used by the mutex. - * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to - * be created without using any dynamic memory allocation. - * - * Mutexes created using this macro can be accessed using the - * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The - * xSemaphoreTake() and xSemaphoreGive() macros must not be used. - * - * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex - * doesn't become available again until the owner has called - * xSemaphoreGiveRecursive() for each successful 'take' request. For example, - * if a task successfully 'takes' the same mutex 5 times then the mutex will - * not be available to any other task until it has also 'given' the mutex back - * exactly five times. - * - * This type of semaphore uses a priority inheritance mechanism so a task - * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the - * semaphore it is no longer required. - * - * Mutex type semaphores cannot be used from within interrupt service routines. - * - * See xSemaphoreCreateBinary() for an alternative implementation that can be - * used for pure synchronisation (where one task or interrupt always 'gives' the - * semaphore and another always 'takes' the semaphore) and from within interrupt - * service routines. - * - * @return xSemaphore Handle to the created mutex semaphore. Should be of type - * SemaphoreHandle_t. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore;
- *
- * void vATask( void * pvParameters )
- * {
- *  // Semaphore cannot be used before a call to xSemaphoreCreateMutex().
- *  // This is a macro so pass the variable in directly.
- *  xSemaphore = xSemaphoreCreateRecursiveMutex();
- *
- *  if( xSemaphore != NULL )
- *  {
- *      // The semaphore was created successfully.
- *      // The semaphore can now be used.
- *  }
- * }
- * 
- * \defgroup xSemaphoreCreateRecursiveMutex xSemaphoreCreateRecursiveMutex - * \ingroup Semaphores - */ -#if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) - #define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX ) -#endif - -/** - * semphr. h - *
- * SemaphoreHandle_t xSemaphoreCreateRecursiveMutexStatic( StaticSemaphore_t *pxMutexBuffer );
- * 
- * - * Creates a new recursive mutex type semaphore instance, and returns a handle - * by which the new recursive mutex can be referenced. - * - * Internally, within the FreeRTOS implementation, recursive mutexs use a block - * of memory, in which the mutex structure is stored. If a recursive mutex is - * created using xSemaphoreCreateRecursiveMutex() then the required memory is - * automatically dynamically allocated inside the - * xSemaphoreCreateRecursiveMutex() function. (see - * https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using - * xSemaphoreCreateRecursiveMutexStatic() then the application writer must - * provide the memory that will get used by the mutex. - * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to - * be created without using any dynamic memory allocation. - * - * Mutexes created using this macro can be accessed using the - * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The - * xSemaphoreTake() and xSemaphoreGive() macros must not be used. - * - * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex - * doesn't become available again until the owner has called - * xSemaphoreGiveRecursive() for each successful 'take' request. For example, - * if a task successfully 'takes' the same mutex 5 times then the mutex will - * not be available to any other task until it has also 'given' the mutex back - * exactly five times. - * - * This type of semaphore uses a priority inheritance mechanism so a task - * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the - * semaphore it is no longer required. - * - * Mutex type semaphores cannot be used from within interrupt service routines. - * - * See xSemaphoreCreateBinary() for an alternative implementation that can be - * used for pure synchronisation (where one task or interrupt always 'gives' the - * semaphore and another always 'takes' the semaphore) and from within interrupt - * service routines. - * - * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, - * which will then be used to hold the recursive mutex's data structure, - * removing the need for the memory to be allocated dynamically. - * - * @return If the recursive mutex was successfully created then a handle to the - * created recursive mutex is returned. If pxMutexBuffer was NULL then NULL is - * returned. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore;
- * StaticSemaphore_t xMutexBuffer;
- *
- * void vATask( void * pvParameters )
- * {
- *  // A recursive semaphore cannot be used before it is created.  Here a
- *  // recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic().
- *  // The address of xMutexBuffer is passed into the function, and will hold
- *  // the mutexes data structures - so no dynamic memory allocation will be
- *  // attempted.
- *  xSemaphore = xSemaphoreCreateRecursiveMutexStatic( &xMutexBuffer );
- *
- *  // As no dynamic memory allocation was performed, xSemaphore cannot be NULL,
- *  // so there is no need to check it.
- * }
- * 
- * \defgroup xSemaphoreCreateRecursiveMutexStatic xSemaphoreCreateRecursiveMutexStatic - * \ingroup Semaphores - */ -#if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) - #define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore ) -#endif /* configSUPPORT_STATIC_ALLOCATION */ - -/** - * semphr. h - *
- * SemaphoreHandle_t xSemaphoreCreateCounting( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount );
- * 
- * - * Creates a new counting semaphore instance, and returns a handle by which the - * new counting semaphore can be referenced. - * - * In many usage scenarios it is faster and more memory efficient to use a - * direct to task notification in place of a counting semaphore! - * https://www.FreeRTOS.org/RTOS-task-notifications.html - * - * Internally, within the FreeRTOS implementation, counting semaphores use a - * block of memory, in which the counting semaphore structure is stored. If a - * counting semaphore is created using xSemaphoreCreateCounting() then the - * required memory is automatically dynamically allocated inside the - * xSemaphoreCreateCounting() function. (see - * https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created - * using xSemaphoreCreateCountingStatic() then the application writer can - * instead optionally provide the memory that will get used by the counting - * semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting - * semaphore to be created without using any dynamic memory allocation. - * - * Counting semaphores are typically used for two things: - * - * 1) Counting events. - * - * In this usage scenario an event handler will 'give' a semaphore each time - * an event occurs (incrementing the semaphore count value), and a handler - * task will 'take' a semaphore each time it processes an event - * (decrementing the semaphore count value). The count value is therefore - * the difference between the number of events that have occurred and the - * number that have been processed. In this case it is desirable for the - * initial count value to be zero. - * - * 2) Resource management. - * - * In this usage scenario the count value indicates the number of resources - * available. To obtain control of a resource a task must first obtain a - * semaphore - decrementing the semaphore count value. When the count value - * reaches zero there are no free resources. When a task finishes with the - * resource it 'gives' the semaphore back - incrementing the semaphore count - * value. In this case it is desirable for the initial count value to be - * equal to the maximum count value, indicating that all resources are free. - * - * @param uxMaxCount The maximum count value that can be reached. When the - * semaphore reaches this value it can no longer be 'given'. - * - * @param uxInitialCount The count value assigned to the semaphore when it is - * created. - * - * @return Handle to the created semaphore. Null if the semaphore could not be - * created. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore;
- *
- * void vATask( void * pvParameters )
- * {
- * SemaphoreHandle_t xSemaphore = NULL;
- *
- *  // Semaphore cannot be used before a call to xSemaphoreCreateCounting().
- *  // The max value to which the semaphore can count should be 10, and the
- *  // initial value assigned to the count should be 0.
- *  xSemaphore = xSemaphoreCreateCounting( 10, 0 );
- *
- *  if( xSemaphore != NULL )
- *  {
- *      // The semaphore was created successfully.
- *      // The semaphore can now be used.
- *  }
- * }
- * 
- * \defgroup xSemaphoreCreateCounting xSemaphoreCreateCounting - * \ingroup Semaphores - */ -#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) ) -#endif - -/** - * semphr. h - *
- * SemaphoreHandle_t xSemaphoreCreateCountingStatic( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount, StaticSemaphore_t *pxSemaphoreBuffer );
- * 
- * - * Creates a new counting semaphore instance, and returns a handle by which the - * new counting semaphore can be referenced. - * - * In many usage scenarios it is faster and more memory efficient to use a - * direct to task notification in place of a counting semaphore! - * https://www.FreeRTOS.org/RTOS-task-notifications.html - * - * Internally, within the FreeRTOS implementation, counting semaphores use a - * block of memory, in which the counting semaphore structure is stored. If a - * counting semaphore is created using xSemaphoreCreateCounting() then the - * required memory is automatically dynamically allocated inside the - * xSemaphoreCreateCounting() function. (see - * https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created - * using xSemaphoreCreateCountingStatic() then the application writer must - * provide the memory. xSemaphoreCreateCountingStatic() therefore allows a - * counting semaphore to be created without using any dynamic memory allocation. - * - * Counting semaphores are typically used for two things: - * - * 1) Counting events. - * - * In this usage scenario an event handler will 'give' a semaphore each time - * an event occurs (incrementing the semaphore count value), and a handler - * task will 'take' a semaphore each time it processes an event - * (decrementing the semaphore count value). The count value is therefore - * the difference between the number of events that have occurred and the - * number that have been processed. In this case it is desirable for the - * initial count value to be zero. - * - * 2) Resource management. - * - * In this usage scenario the count value indicates the number of resources - * available. To obtain control of a resource a task must first obtain a - * semaphore - decrementing the semaphore count value. When the count value - * reaches zero there are no free resources. When a task finishes with the - * resource it 'gives' the semaphore back - incrementing the semaphore count - * value. In this case it is desirable for the initial count value to be - * equal to the maximum count value, indicating that all resources are free. - * - * @param uxMaxCount The maximum count value that can be reached. When the - * semaphore reaches this value it can no longer be 'given'. - * - * @param uxInitialCount The count value assigned to the semaphore when it is - * created. - * - * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, - * which will then be used to hold the semaphore's data structure, removing the - * need for the memory to be allocated dynamically. - * - * @return If the counting semaphore was successfully created then a handle to - * the created counting semaphore is returned. If pxSemaphoreBuffer was NULL - * then NULL is returned. - * - * Example usage: - *
- * SemaphoreHandle_t xSemaphore;
- * StaticSemaphore_t xSemaphoreBuffer;
- *
- * void vATask( void * pvParameters )
- * {
- * SemaphoreHandle_t xSemaphore = NULL;
- *
- *  // Counting semaphore cannot be used before they have been created.  Create
- *  // a counting semaphore using xSemaphoreCreateCountingStatic().  The max
- *  // value to which the semaphore can count is 10, and the initial value
- *  // assigned to the count will be 0.  The address of xSemaphoreBuffer is
- *  // passed in and will be used to hold the semaphore structure, so no dynamic
- *  // memory allocation will be used.
- *  xSemaphore = xSemaphoreCreateCounting( 10, 0, &xSemaphoreBuffer );
- *
- *  // No memory allocation was attempted so xSemaphore cannot be NULL, so there
- *  // is no need to check its value.
- * }
- * 
- * \defgroup xSemaphoreCreateCountingStatic xSemaphoreCreateCountingStatic - * \ingroup Semaphores - */ -#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) ) -#endif /* configSUPPORT_STATIC_ALLOCATION */ - -/** - * semphr. h - *
- * void vSemaphoreDelete( SemaphoreHandle_t xSemaphore );
- * 
- * - * Delete a semaphore. This function must be used with care. For example, - * do not delete a mutex type semaphore if the mutex is held by a task. - * - * @param xSemaphore A handle to the semaphore to be deleted. - * - * \defgroup vSemaphoreDelete vSemaphoreDelete - * \ingroup Semaphores - */ -#define vSemaphoreDelete( xSemaphore ) vQueueDelete( ( QueueHandle_t ) ( xSemaphore ) ) - -/** - * semphr.h - *
- * TaskHandle_t xSemaphoreGetMutexHolder( SemaphoreHandle_t xMutex );
- * 
- * - * If xMutex is indeed a mutex type semaphore, return the current mutex holder. - * If xMutex is not a mutex type semaphore, or the mutex is available (not held - * by a task), return NULL. - * - * Note: This is a good way of determining if the calling task is the mutex - * holder, but not a good way of determining the identity of the mutex holder as - * the holder may change between the function exiting and the returned value - * being tested. - */ -#define xSemaphoreGetMutexHolder( xSemaphore ) xQueueGetMutexHolder( ( xSemaphore ) ) - -/** - * semphr.h - *
- * TaskHandle_t xSemaphoreGetMutexHolderFromISR( SemaphoreHandle_t xMutex );
- * 
- * - * If xMutex is indeed a mutex type semaphore, return the current mutex holder. - * If xMutex is not a mutex type semaphore, or the mutex is available (not held - * by a task), return NULL. - * - */ -#define xSemaphoreGetMutexHolderFromISR( xSemaphore ) xQueueGetMutexHolderFromISR( ( xSemaphore ) ) - -/** - * semphr.h - *
- * UBaseType_t uxSemaphoreGetCount( SemaphoreHandle_t xSemaphore );
- * 
- * - * If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns - * its current count value. If the semaphore is a binary semaphore then - * uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the - * semaphore is not available. - * - */ -#define uxSemaphoreGetCount( xSemaphore ) uxQueueMessagesWaiting( ( QueueHandle_t ) ( xSemaphore ) ) - -#endif /* SEMAPHORE_H */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef SEMAPHORE_H +#define SEMAPHORE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include semphr.h" +#endif + +#include "queue.h" + +typedef QueueHandle_t SemaphoreHandle_t; + +#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) +#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) +#define semGIVE_BLOCK_TIME ( ( TickType_t ) 0U ) + + +/** + * semphr. h + * @code{c} + * vSemaphoreCreateBinary( SemaphoreHandle_t xSemaphore ); + * @endcode + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * This old vSemaphoreCreateBinary() macro is now deprecated in favour of the + * xSemaphoreCreateBinary() function. Note that binary semaphores created using + * the vSemaphoreCreateBinary() macro are created in a state such that the + * first call to 'take' the semaphore would pass, whereas binary semaphores + * created using xSemaphoreCreateBinary() are created in a state such that the + * the semaphore must first be 'given' before it can be 'taken'. + * + * Macro that implements a semaphore by using the existing queue mechanism. + * The queue length is 1 as this is a binary semaphore. The data size is 0 + * as we don't want to actually store any data - we just want to know if the + * queue is empty or full. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @param xSemaphore Handle to the created semaphore. Should be of type SemaphoreHandle_t. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to vSemaphoreCreateBinary (). + * // This is a macro so pass the variable in directly. + * vSemaphoreCreateBinary( xSemaphore ); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \defgroup vSemaphoreCreateBinary vSemaphoreCreateBinary + * \ingroup Semaphores + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define vSemaphoreCreateBinary( xSemaphore ) \ + do { \ + ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ + if( ( xSemaphore ) != NULL ) \ + { \ + ( void ) xSemaphoreGive( ( xSemaphore ) ); \ + } \ + } while( 0 ) +#endif + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateBinary( void ); + * @endcode + * + * Creates a new binary semaphore instance, and returns a handle by which the + * new semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, binary semaphores use a block + * of memory, in which the semaphore structure is stored. If a binary semaphore + * is created using xSemaphoreCreateBinary() then the required memory is + * automatically dynamically allocated inside the xSemaphoreCreateBinary() + * function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore + * is created using xSemaphoreCreateBinaryStatic() then the application writer + * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a + * binary semaphore to be created without using any dynamic memory allocation. + * + * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this + * xSemaphoreCreateBinary() function. Note that binary semaphores created using + * the vSemaphoreCreateBinary() macro are created in a state such that the + * first call to 'take' the semaphore would pass, whereas binary semaphores + * created using xSemaphoreCreateBinary() are created in a state such that the + * the semaphore must first be 'given' before it can be 'taken'. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @return Handle to the created semaphore, or NULL if the memory required to + * hold the semaphore's data structures could not be allocated. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). + * // This is a macro so pass the variable in directly. + * xSemaphore = xSemaphoreCreateBinary(); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \defgroup xSemaphoreCreateBinary xSemaphoreCreateBinary + * \ingroup Semaphores + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ) +#endif + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateBinaryStatic( StaticSemaphore_t *pxSemaphoreBuffer ); + * @endcode + * + * Creates a new binary semaphore instance, and returns a handle by which the + * new semaphore can be referenced. + * + * NOTE: In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, binary semaphores use a block + * of memory, in which the semaphore structure is stored. If a binary semaphore + * is created using xSemaphoreCreateBinary() then the required memory is + * automatically dynamically allocated inside the xSemaphoreCreateBinary() + * function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore + * is created using xSemaphoreCreateBinaryStatic() then the application writer + * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a + * binary semaphore to be created without using any dynamic memory allocation. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the semaphore's data structure, removing the + * need for the memory to be allocated dynamically. + * + * @return If the semaphore is created then a handle to the created semaphore is + * returned. If pxSemaphoreBuffer is NULL then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * StaticSemaphore_t xSemaphoreBuffer; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). + * // The semaphore's data structures will be placed in the xSemaphoreBuffer + * // variable, the address of which is passed into the function. The + * // function's parameter is not NULL, so the function will not attempt any + * // dynamic memory allocation, and therefore the function will not return + * // return NULL. + * xSemaphore = xSemaphoreCreateBinary( &xSemaphoreBuffer ); + * + * // Rest of task code goes here. + * } + * @endcode + * \defgroup xSemaphoreCreateBinaryStatic xSemaphoreCreateBinaryStatic + * \ingroup Semaphores + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, ( pxStaticSemaphore ), queueQUEUE_TYPE_BINARY_SEMAPHORE ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * semphr. h + * @code{c} + * xSemaphoreTake( + * SemaphoreHandle_t xSemaphore, + * TickType_t xBlockTime + * ); + * @endcode + * + * Macro to obtain a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or + * xSemaphoreCreateCounting(). + * + * @param xSemaphore A handle to the semaphore being taken - obtained when + * the semaphore was created. + * + * @param xBlockTime The time in ticks to wait for the semaphore to become + * available. The macro portTICK_PERIOD_MS can be used to convert this to a + * real time. A block time of zero can be used to poll the semaphore. A block + * time of portMAX_DELAY can be used to block indefinitely (provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). + * + * @return pdTRUE if the semaphore was obtained. pdFALSE + * if xBlockTime expired without the semaphore becoming available. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * // A task that creates a semaphore. + * void vATask( void * pvParameters ) + * { + * // Create the semaphore to guard a shared resource. + * xSemaphore = xSemaphoreCreateBinary(); + * } + * + * // A task that uses the semaphore. + * void vAnotherTask( void * pvParameters ) + * { + * // ... Do other things. + * + * if( xSemaphore != NULL ) + * { + * // See if we can obtain the semaphore. If the semaphore is not available + * // wait 10 ticks to see if it becomes free. + * if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) + * { + * // We were able to obtain the semaphore and can now access the + * // shared resource. + * + * // ... + * + * // We have finished accessing the shared resource. Release the + * // semaphore. + * xSemaphoreGive( xSemaphore ); + * } + * else + * { + * // We could not obtain the semaphore and can therefore not access + * // the shared resource safely. + * } + * } + * } + * @endcode + * \defgroup xSemaphoreTake xSemaphoreTake + * \ingroup Semaphores + */ +#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) ) + +/** + * semphr. h + * @code{c} + * xSemaphoreTakeRecursive( + * SemaphoreHandle_t xMutex, + * TickType_t xBlockTime + * ); + * @endcode + * + * Macro to recursively obtain, or 'take', a mutex type semaphore. + * The mutex must have previously been created using a call to + * xSemaphoreCreateRecursiveMutex(); + * + * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this + * macro to be available. + * + * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * @param xMutex A handle to the mutex being obtained. This is the + * handle returned by xSemaphoreCreateRecursiveMutex(); + * + * @param xBlockTime The time in ticks to wait for the semaphore to become + * available. The macro portTICK_PERIOD_MS can be used to convert this to a + * real time. A block time of zero can be used to poll the semaphore. If + * the task already owns the semaphore then xSemaphoreTakeRecursive() will + * return immediately no matter what the value of xBlockTime. + * + * @return pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime + * expired without the semaphore becoming available. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xMutex = NULL; + * + * // A task that creates a mutex. + * void vATask( void * pvParameters ) + * { + * // Create the mutex to guard a shared resource. + * xMutex = xSemaphoreCreateRecursiveMutex(); + * } + * + * // A task that uses the mutex. + * void vAnotherTask( void * pvParameters ) + * { + * // ... Do other things. + * + * if( xMutex != NULL ) + * { + * // See if we can obtain the mutex. If the mutex is not available + * // wait 10 ticks to see if it becomes free. + * if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) + * { + * // We were able to obtain the mutex and can now access the + * // shared resource. + * + * // ... + * // For some reason due to the nature of the code further calls to + * // xSemaphoreTakeRecursive() are made on the same mutex. In real + * // code these would not be just sequential calls as this would make + * // no sense. Instead the calls are likely to be buried inside + * // a more complex call structure. + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * + * // The mutex has now been 'taken' three times, so will not be + * // available to another task until it has also been given back + * // three times. Again it is unlikely that real code would have + * // these calls sequentially, but instead buried in a more complex + * // call structure. This is just for illustrative purposes. + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * + * // Now the mutex can be taken by other tasks. + * } + * else + * { + * // We could not obtain the mutex and can therefore not access + * // the shared resource safely. + * } + * } + * } + * @endcode + * \defgroup xSemaphoreTakeRecursive xSemaphoreTakeRecursive + * \ingroup Semaphores + */ +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + #define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) ) +#endif + +/** + * semphr. h + * @code{c} + * xSemaphoreGive( SemaphoreHandle_t xSemaphore ); + * @endcode + * + * Macro to release a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or + * xSemaphoreCreateCounting(). and obtained using sSemaphoreTake(). + * + * This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for + * an alternative which can be used from an ISR. + * + * This macro must also not be used on semaphores created using + * xSemaphoreCreateRecursiveMutex(). + * + * @param xSemaphore A handle to the semaphore being released. This is the + * handle returned when the semaphore was created. + * + * @return pdTRUE if the semaphore was released. pdFALSE if an error occurred. + * Semaphores are implemented using queues. An error can occur if there is + * no space on the queue to post a message - indicating that the + * semaphore was not first obtained correctly. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * void vATask( void * pvParameters ) + * { + * // Create the semaphore to guard a shared resource. + * xSemaphore = vSemaphoreCreateBinary(); + * + * if( xSemaphore != NULL ) + * { + * if( xSemaphoreGive( xSemaphore ) != pdTRUE ) + * { + * // We would expect this call to fail because we cannot give + * // a semaphore without first "taking" it! + * } + * + * // Obtain the semaphore - don't block if the semaphore is not + * // immediately available. + * if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) ) + * { + * // We now have the semaphore and can access the shared resource. + * + * // ... + * + * // We have finished accessing the shared resource so can free the + * // semaphore. + * if( xSemaphoreGive( xSemaphore ) != pdTRUE ) + * { + * // We would not expect this call to fail because we must have + * // obtained the semaphore to get here. + * } + * } + * } + * } + * @endcode + * \defgroup xSemaphoreGive xSemaphoreGive + * \ingroup Semaphores + */ +#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) + +/** + * semphr. h + * @code{c} + * xSemaphoreGiveRecursive( SemaphoreHandle_t xMutex ); + * @endcode + * + * Macro to recursively release, or 'give', a mutex type semaphore. + * The mutex must have previously been created using a call to + * xSemaphoreCreateRecursiveMutex(); + * + * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this + * macro to be available. + * + * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * @param xMutex A handle to the mutex being released, or 'given'. This is the + * handle returned by xSemaphoreCreateMutex(); + * + * @return pdTRUE if the semaphore was given. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xMutex = NULL; + * + * // A task that creates a mutex. + * void vATask( void * pvParameters ) + * { + * // Create the mutex to guard a shared resource. + * xMutex = xSemaphoreCreateRecursiveMutex(); + * } + * + * // A task that uses the mutex. + * void vAnotherTask( void * pvParameters ) + * { + * // ... Do other things. + * + * if( xMutex != NULL ) + * { + * // See if we can obtain the mutex. If the mutex is not available + * // wait 10 ticks to see if it becomes free. + * if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE ) + * { + * // We were able to obtain the mutex and can now access the + * // shared resource. + * + * // ... + * // For some reason due to the nature of the code further calls to + * // xSemaphoreTakeRecursive() are made on the same mutex. In real + * // code these would not be just sequential calls as this would make + * // no sense. Instead the calls are likely to be buried inside + * // a more complex call structure. + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * + * // The mutex has now been 'taken' three times, so will not be + * // available to another task until it has also been given back + * // three times. Again it is unlikely that real code would have + * // these calls sequentially, it would be more likely that the calls + * // to xSemaphoreGiveRecursive() would be called as a call stack + * // unwound. This is just for demonstrative purposes. + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * + * // Now the mutex can be taken by other tasks. + * } + * else + * { + * // We could not obtain the mutex and can therefore not access + * // the shared resource safely. + * } + * } + * } + * @endcode + * \defgroup xSemaphoreGiveRecursive xSemaphoreGiveRecursive + * \ingroup Semaphores + */ +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + #define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) ) +#endif + +/** + * semphr. h + * @code{c} + * xSemaphoreGiveFromISR( + * SemaphoreHandle_t xSemaphore, + * BaseType_t *pxHigherPriorityTaskWoken + * ); + * @endcode + * + * Macro to release a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). + * + * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) + * must not be used with this macro. + * + * This macro can be used from an ISR. + * + * @param xSemaphore A handle to the semaphore being released. This is the + * handle returned when the semaphore was created. + * + * @param pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + \#define LONG_TIME 0xffff + \#define TICKS_TO_WAIT 10 + * SemaphoreHandle_t xSemaphore = NULL; + * + * // Repetitive task. + * void vATask( void * pvParameters ) + * { + * for( ;; ) + * { + * // We want this task to run every 10 ticks of a timer. The semaphore + * // was created before this task was started. + * + * // Block waiting for the semaphore to become available. + * if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE ) + * { + * // It is time to execute. + * + * // ... + * + * // We have finished our task. Return to the top of the loop where + * // we will block on the semaphore until it is time to execute + * // again. Note when using the semaphore for synchronisation with an + * // ISR in this manner there is no need to 'give' the semaphore back. + * } + * } + * } + * + * // Timer ISR + * void vTimerISR( void * pvParameters ) + * { + * static uint8_t ucLocalTickCount = 0; + * static BaseType_t xHigherPriorityTaskWoken; + * + * // A timer tick has occurred. + * + * // ... Do other time functions. + * + * // Is it time for vATask () to run? + * xHigherPriorityTaskWoken = pdFALSE; + * ucLocalTickCount++; + * if( ucLocalTickCount >= TICKS_TO_WAIT ) + * { + * // Unblock the task by releasing the semaphore. + * xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken ); + * + * // Reset the count so we release the semaphore again in 10 ticks time. + * ucLocalTickCount = 0; + * } + * + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // We can force a context switch here. Context switching from an + * // ISR uses port specific syntax. Check the demo task for your port + * // to find the syntax required. + * } + * } + * @endcode + * \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR + * \ingroup Semaphores + */ +#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) ) + +/** + * semphr. h + * @code{c} + * xSemaphoreTakeFromISR( + * SemaphoreHandle_t xSemaphore, + * BaseType_t *pxHigherPriorityTaskWoken + * ); + * @endcode + * + * Macro to take a semaphore from an ISR. The semaphore must have + * previously been created with a call to xSemaphoreCreateBinary() or + * xSemaphoreCreateCounting(). + * + * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) + * must not be used with this macro. + * + * This macro can be used from an ISR, however taking a semaphore from an ISR + * is not a common operation. It is likely to only be useful when taking a + * counting semaphore when an interrupt is obtaining an object from a resource + * pool (when the semaphore count indicates the number of resources available). + * + * @param xSemaphore A handle to the semaphore being taken. This is the + * handle returned when the semaphore was created. + * + * @param pxHigherPriorityTaskWoken xSemaphoreTakeFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the semaphore was successfully taken, otherwise + * pdFALSE + */ +#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) ) + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateMutex( void ); + * @endcode + * + * Creates a new mutex type semaphore instance, and returns a handle by which + * the new mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, mutex semaphores use a block + * of memory, in which the mutex structure is stored. If a mutex is created + * using xSemaphoreCreateMutex() then the required memory is automatically + * dynamically allocated inside the xSemaphoreCreateMutex() function. (see + * https://www.FreeRTOS.org/a00111.html). If a mutex is created using + * xSemaphoreCreateMutexStatic() then the application writer must provided the + * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created + * without using any dynamic memory allocation. + * + * Mutexes created using this function can be accessed using the xSemaphoreTake() + * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and + * xSemaphoreGiveRecursive() macros must not be used. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @return If the mutex was successfully created then a handle to the created + * semaphore is returned. If there was not enough heap to allocate the mutex + * data structures then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). + * // This is a macro so pass the variable in directly. + * xSemaphore = xSemaphoreCreateMutex(); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \defgroup xSemaphoreCreateMutex xSemaphoreCreateMutex + * \ingroup Semaphores + */ +#if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_MUTEXES == 1 ) ) + #define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX ) +#endif + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateMutexStatic( StaticSemaphore_t *pxMutexBuffer ); + * @endcode + * + * Creates a new mutex type semaphore instance, and returns a handle by which + * the new mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, mutex semaphores use a block + * of memory, in which the mutex structure is stored. If a mutex is created + * using xSemaphoreCreateMutex() then the required memory is automatically + * dynamically allocated inside the xSemaphoreCreateMutex() function. (see + * https://www.FreeRTOS.org/a00111.html). If a mutex is created using + * xSemaphoreCreateMutexStatic() then the application writer must provided the + * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created + * without using any dynamic memory allocation. + * + * Mutexes created using this function can be accessed using the xSemaphoreTake() + * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and + * xSemaphoreGiveRecursive() macros must not be used. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, + * which will be used to hold the mutex's data structure, removing the need for + * the memory to be allocated dynamically. + * + * @return If the mutex was successfully created then a handle to the created + * mutex is returned. If pxMutexBuffer was NULL then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * StaticSemaphore_t xMutexBuffer; + * + * void vATask( void * pvParameters ) + * { + * // A mutex cannot be used before it has been created. xMutexBuffer is + * // into xSemaphoreCreateMutexStatic() so no dynamic memory allocation is + * // attempted. + * xSemaphore = xSemaphoreCreateMutexStatic( &xMutexBuffer ); + * + * // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, + * // so there is no need to check it. + * } + * @endcode + * \defgroup xSemaphoreCreateMutexStatic xSemaphoreCreateMutexStatic + * \ingroup Semaphores + */ +#if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_MUTEXES == 1 ) ) + #define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) ) +#endif + + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateRecursiveMutex( void ); + * @endcode + * + * Creates a new recursive mutex type semaphore instance, and returns a handle + * by which the new recursive mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, recursive mutexes use a block + * of memory, in which the mutex structure is stored. If a recursive mutex is + * created using xSemaphoreCreateRecursiveMutex() then the required memory is + * automatically dynamically allocated inside the + * xSemaphoreCreateRecursiveMutex() function. (see + * https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using + * xSemaphoreCreateRecursiveMutexStatic() then the application writer must + * provide the memory that will get used by the mutex. + * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to + * be created without using any dynamic memory allocation. + * + * Mutexes created using this macro can be accessed using the + * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The + * xSemaphoreTake() and xSemaphoreGive() macros must not be used. + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @return xSemaphore Handle to the created mutex semaphore. Should be of type + * SemaphoreHandle_t. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). + * // This is a macro so pass the variable in directly. + * xSemaphore = xSemaphoreCreateRecursiveMutex(); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \defgroup xSemaphoreCreateRecursiveMutex xSemaphoreCreateRecursiveMutex + * \ingroup Semaphores + */ +#if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) + #define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX ) +#endif + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateRecursiveMutexStatic( StaticSemaphore_t *pxMutexBuffer ); + * @endcode + * + * Creates a new recursive mutex type semaphore instance, and returns a handle + * by which the new recursive mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, recursive mutexes use a block + * of memory, in which the mutex structure is stored. If a recursive mutex is + * created using xSemaphoreCreateRecursiveMutex() then the required memory is + * automatically dynamically allocated inside the + * xSemaphoreCreateRecursiveMutex() function. (see + * https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using + * xSemaphoreCreateRecursiveMutexStatic() then the application writer must + * provide the memory that will get used by the mutex. + * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to + * be created without using any dynamic memory allocation. + * + * Mutexes created using this macro can be accessed using the + * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The + * xSemaphoreTake() and xSemaphoreGive() macros must not be used. + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the recursive mutex's data structure, + * removing the need for the memory to be allocated dynamically. + * + * @return If the recursive mutex was successfully created then a handle to the + * created recursive mutex is returned. If pxMutexBuffer was NULL then NULL is + * returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * StaticSemaphore_t xMutexBuffer; + * + * void vATask( void * pvParameters ) + * { + * // A recursive semaphore cannot be used before it is created. Here a + * // recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic(). + * // The address of xMutexBuffer is passed into the function, and will hold + * // the mutexes data structures - so no dynamic memory allocation will be + * // attempted. + * xSemaphore = xSemaphoreCreateRecursiveMutexStatic( &xMutexBuffer ); + * + * // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, + * // so there is no need to check it. + * } + * @endcode + * \defgroup xSemaphoreCreateRecursiveMutexStatic xSemaphoreCreateRecursiveMutexStatic + * \ingroup Semaphores + */ +#if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) + #define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, ( pxStaticSemaphore ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateCounting( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount ); + * @endcode + * + * Creates a new counting semaphore instance, and returns a handle by which the + * new counting semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a counting semaphore! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, counting semaphores use a + * block of memory, in which the counting semaphore structure is stored. If a + * counting semaphore is created using xSemaphoreCreateCounting() then the + * required memory is automatically dynamically allocated inside the + * xSemaphoreCreateCounting() function. (see + * https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created + * using xSemaphoreCreateCountingStatic() then the application writer can + * instead optionally provide the memory that will get used by the counting + * semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting + * semaphore to be created without using any dynamic memory allocation. + * + * Counting semaphores are typically used for two things: + * + * 1) Counting events. + * + * In this usage scenario an event handler will 'give' a semaphore each time + * an event occurs (incrementing the semaphore count value), and a handler + * task will 'take' a semaphore each time it processes an event + * (decrementing the semaphore count value). The count value is therefore + * the difference between the number of events that have occurred and the + * number that have been processed. In this case it is desirable for the + * initial count value to be zero. + * + * 2) Resource management. + * + * In this usage scenario the count value indicates the number of resources + * available. To obtain control of a resource a task must first obtain a + * semaphore - decrementing the semaphore count value. When the count value + * reaches zero there are no free resources. When a task finishes with the + * resource it 'gives' the semaphore back - incrementing the semaphore count + * value. In this case it is desirable for the initial count value to be + * equal to the maximum count value, indicating that all resources are free. + * + * @param uxMaxCount The maximum count value that can be reached. When the + * semaphore reaches this value it can no longer be 'given'. + * + * @param uxInitialCount The count value assigned to the semaphore when it is + * created. + * + * @return Handle to the created semaphore. Null if the semaphore could not be + * created. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * + * void vATask( void * pvParameters ) + * { + * SemaphoreHandle_t xSemaphore = NULL; + * + * // Semaphore cannot be used before a call to xSemaphoreCreateCounting(). + * // The max value to which the semaphore can count should be 10, and the + * // initial value assigned to the count should be 0. + * xSemaphore = xSemaphoreCreateCounting( 10, 0 ); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \defgroup xSemaphoreCreateCounting xSemaphoreCreateCounting + * \ingroup Semaphores + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) ) +#endif + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateCountingStatic( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount, StaticSemaphore_t *pxSemaphoreBuffer ); + * @endcode + * + * Creates a new counting semaphore instance, and returns a handle by which the + * new counting semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a counting semaphore! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, counting semaphores use a + * block of memory, in which the counting semaphore structure is stored. If a + * counting semaphore is created using xSemaphoreCreateCounting() then the + * required memory is automatically dynamically allocated inside the + * xSemaphoreCreateCounting() function. (see + * https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created + * using xSemaphoreCreateCountingStatic() then the application writer must + * provide the memory. xSemaphoreCreateCountingStatic() therefore allows a + * counting semaphore to be created without using any dynamic memory allocation. + * + * Counting semaphores are typically used for two things: + * + * 1) Counting events. + * + * In this usage scenario an event handler will 'give' a semaphore each time + * an event occurs (incrementing the semaphore count value), and a handler + * task will 'take' a semaphore each time it processes an event + * (decrementing the semaphore count value). The count value is therefore + * the difference between the number of events that have occurred and the + * number that have been processed. In this case it is desirable for the + * initial count value to be zero. + * + * 2) Resource management. + * + * In this usage scenario the count value indicates the number of resources + * available. To obtain control of a resource a task must first obtain a + * semaphore - decrementing the semaphore count value. When the count value + * reaches zero there are no free resources. When a task finishes with the + * resource it 'gives' the semaphore back - incrementing the semaphore count + * value. In this case it is desirable for the initial count value to be + * equal to the maximum count value, indicating that all resources are free. + * + * @param uxMaxCount The maximum count value that can be reached. When the + * semaphore reaches this value it can no longer be 'given'. + * + * @param uxInitialCount The count value assigned to the semaphore when it is + * created. + * + * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the semaphore's data structure, removing the + * need for the memory to be allocated dynamically. + * + * @return If the counting semaphore was successfully created then a handle to + * the created counting semaphore is returned. If pxSemaphoreBuffer was NULL + * then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * StaticSemaphore_t xSemaphoreBuffer; + * + * void vATask( void * pvParameters ) + * { + * SemaphoreHandle_t xSemaphore = NULL; + * + * // Counting semaphore cannot be used before they have been created. Create + * // a counting semaphore using xSemaphoreCreateCountingStatic(). The max + * // value to which the semaphore can count is 10, and the initial value + * // assigned to the count will be 0. The address of xSemaphoreBuffer is + * // passed in and will be used to hold the semaphore structure, so no dynamic + * // memory allocation will be used. + * xSemaphore = xSemaphoreCreateCounting( 10, 0, &xSemaphoreBuffer ); + * + * // No memory allocation was attempted so xSemaphore cannot be NULL, so there + * // is no need to check its value. + * } + * @endcode + * \defgroup xSemaphoreCreateCountingStatic xSemaphoreCreateCountingStatic + * \ingroup Semaphores + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * semphr. h + * @code{c} + * void vSemaphoreDelete( SemaphoreHandle_t xSemaphore ); + * @endcode + * + * Delete a semaphore. This function must be used with care. For example, + * do not delete a mutex type semaphore if the mutex is held by a task. + * + * @param xSemaphore A handle to the semaphore to be deleted. + * + * \defgroup vSemaphoreDelete vSemaphoreDelete + * \ingroup Semaphores + */ +#define vSemaphoreDelete( xSemaphore ) vQueueDelete( ( QueueHandle_t ) ( xSemaphore ) ) + +/** + * semphr.h + * @code{c} + * TaskHandle_t xSemaphoreGetMutexHolder( SemaphoreHandle_t xMutex ); + * @endcode + * + * If xMutex is indeed a mutex type semaphore, return the current mutex holder. + * If xMutex is not a mutex type semaphore, or the mutex is available (not held + * by a task), return NULL. + * + * Note: This is a good way of determining if the calling task is the mutex + * holder, but not a good way of determining the identity of the mutex holder as + * the holder may change between the function exiting and the returned value + * being tested. + */ +#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) + #define xSemaphoreGetMutexHolder( xSemaphore ) xQueueGetMutexHolder( ( xSemaphore ) ) +#endif + +/** + * semphr.h + * @code{c} + * TaskHandle_t xSemaphoreGetMutexHolderFromISR( SemaphoreHandle_t xMutex ); + * @endcode + * + * If xMutex is indeed a mutex type semaphore, return the current mutex holder. + * If xMutex is not a mutex type semaphore, or the mutex is available (not held + * by a task), return NULL. + * + */ +#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) + #define xSemaphoreGetMutexHolderFromISR( xSemaphore ) xQueueGetMutexHolderFromISR( ( xSemaphore ) ) +#endif + +/** + * semphr.h + * @code{c} + * UBaseType_t uxSemaphoreGetCount( SemaphoreHandle_t xSemaphore ); + * @endcode + * + * If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns + * its current count value. If the semaphore is a binary semaphore then + * uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the + * semaphore is not available. + * + */ +#define uxSemaphoreGetCount( xSemaphore ) uxQueueMessagesWaiting( ( QueueHandle_t ) ( xSemaphore ) ) + +/** + * semphr.h + * @code{c} + * UBaseType_t uxSemaphoreGetCountFromISR( SemaphoreHandle_t xSemaphore ); + * @endcode + * + * If the semaphore is a counting semaphore then uxSemaphoreGetCountFromISR() returns + * its current count value. If the semaphore is a binary semaphore then + * uxSemaphoreGetCountFromISR() returns 1 if the semaphore is available, and 0 if the + * semaphore is not available. + * + */ +#define uxSemaphoreGetCountFromISR( xSemaphore ) uxQueueMessagesWaitingFromISR( ( QueueHandle_t ) ( xSemaphore ) ) + +/** + * semphr.h + * @code{c} + * BaseType_t xSemaphoreGetStaticBuffer( SemaphoreHandle_t xSemaphore, + * StaticSemaphore_t ** ppxSemaphoreBuffer ); + * @endcode + * + * Retrieve pointer to a statically created binary semaphore, counting semaphore, + * or mutex semaphore's data structure buffer. This is the same buffer that is + * supplied at the time of creation. + * + * @param xSemaphore The semaphore for which to retrieve the buffer. + * + * @param ppxSemaphoreBuffer Used to return a pointer to the semaphore's + * data structure buffer. + * + * @return pdTRUE if buffer was retrieved, pdFALSE otherwise. + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreGetStaticBuffer( xSemaphore, ppxSemaphoreBuffer ) xQueueGenericGetStaticBuffers( ( QueueHandle_t ) ( xSemaphore ), NULL, ( ppxSemaphoreBuffer ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +#endif /* SEMAPHORE_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/stack_macros.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/stack_macros.h index 317d1e06c..393c95c8e 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/stack_macros.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/stack_macros.h @@ -1,127 +1,141 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -#ifndef STACK_MACROS_H -#define STACK_MACROS_H - -/* - * Call the stack overflow hook function if the stack of the task being swapped - * out is currently overflowed, or looks like it might have overflowed in the - * past. - * - * Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check - * the current stack state only - comparing the current top of stack value to - * the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1 - * will also cause the last few stack bytes to be checked to ensure the value - * to which the bytes were set when the task was created have not been - * overwritten. Note this second test does not guarantee that an overflowed - * stack will always be recognised. - */ - -/*-----------------------------------------------------------*/ - -#if ( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) ) - -/* Only the current stack state is to be checked. */ - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - /* Is the currently saved stack pointer within the stack limit? */ \ - if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ -/*-----------------------------------------------------------*/ - -#if ( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) ) - -/* Only the current stack state is to be checked. */ - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - \ - /* Is the currently saved stack pointer within the stack limit? */ \ - if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ -/*-----------------------------------------------------------*/ - -#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) - - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ - const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ - \ - if( ( pulStack[ 0 ] != ulCheckValue ) || \ - ( pulStack[ 1 ] != ulCheckValue ) || \ - ( pulStack[ 2 ] != ulCheckValue ) || \ - ( pulStack[ 3 ] != ulCheckValue ) ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ -/*-----------------------------------------------------------*/ - -#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) - - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - int8_t * pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ - static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ - \ - \ - pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ - \ - /* Has the extremity of the task stack ever been written over? */ \ - if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ -/*-----------------------------------------------------------*/ - -/* Remove stack overflow macro if not being used. */ -#ifndef taskCHECK_FOR_STACK_OVERFLOW - #define taskCHECK_FOR_STACK_OVERFLOW() -#endif - - - -#endif /* STACK_MACROS_H */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef STACK_MACROS_H +#define STACK_MACROS_H + +/* + * Call the stack overflow hook function if the stack of the task being swapped + * out is currently overflowed, or looks like it might have overflowed in the + * past. + * + * Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check + * the current stack state only - comparing the current top of stack value to + * the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1 + * will also cause the last few stack bytes to be checked to ensure the value + * to which the bytes were set when the task was created have not been + * overwritten. Note this second test does not guarantee that an overflowed + * stack will always be recognised. + */ + +/*-----------------------------------------------------------*/ + +/* + * portSTACK_LIMIT_PADDING is a number of extra words to consider to be in + * use on the stack. + */ +#ifndef portSTACK_LIMIT_PADDING + #define portSTACK_LIMIT_PADDING 0 +#endif + +#if ( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) ) + +/* Only the current stack state is to be checked. */ + #define taskCHECK_FOR_STACK_OVERFLOW() \ + do { \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack + portSTACK_LIMIT_PADDING ) \ + { \ + char * pcOverflowTaskName = pxCurrentTCB->pcTaskName; \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pcOverflowTaskName ); \ + } \ + } while( 0 ) + +#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ +/*-----------------------------------------------------------*/ + +#if ( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) ) + +/* Only the current stack state is to be checked. */ + #define taskCHECK_FOR_STACK_OVERFLOW() \ + do { \ + \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack - portSTACK_LIMIT_PADDING ) \ + { \ + char * pcOverflowTaskName = pxCurrentTCB->pcTaskName; \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pcOverflowTaskName ); \ + } \ + } while( 0 ) + +#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ +/*-----------------------------------------------------------*/ + +#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) + + #define taskCHECK_FOR_STACK_OVERFLOW() \ + do { \ + const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ + const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5U; \ + \ + if( ( pulStack[ 0 ] != ulCheckValue ) || \ + ( pulStack[ 1 ] != ulCheckValue ) || \ + ( pulStack[ 2 ] != ulCheckValue ) || \ + ( pulStack[ 3 ] != ulCheckValue ) ) \ + { \ + char * pcOverflowTaskName = pxCurrentTCB->pcTaskName; \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pcOverflowTaskName ); \ + } \ + } while( 0 ) + +#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) + + #define taskCHECK_FOR_STACK_OVERFLOW() \ + do { \ + int8_t * pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ + static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ + \ + \ + pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ + \ + /* Has the extremity of the task stack ever been written over? */ \ + if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ + { \ + char * pcOverflowTaskName = pxCurrentTCB->pcTaskName; \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pcOverflowTaskName ); \ + } \ + } while( 0 ) + +#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ +/*-----------------------------------------------------------*/ + +/* Remove stack overflow macro if not being used. */ +#ifndef taskCHECK_FOR_STACK_OVERFLOW + #define taskCHECK_FOR_STACK_OVERFLOW() +#endif + + + +#endif /* STACK_MACROS_H */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/stream_buffer.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/stream_buffer.h index 2f56c483c..84fde67c6 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/stream_buffer.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/stream_buffer.h @@ -1,867 +1,1280 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -/* - * Stream buffers are used to send a continuous stream of data from one task or - * interrupt to another. Their implementation is light weight, making them - * particularly suited for interrupt to task and core to core communication - * scenarios. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xStreamBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xStreamBufferReceive()) inside a critical section section and set the - * receive block time to 0. - * - */ - -#ifndef STREAM_BUFFER_H -#define STREAM_BUFFER_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include stream_buffer.h" -#endif - -/* *INDENT-OFF* */ -#if defined( __cplusplus ) - extern "C" { -#endif -/* *INDENT-ON* */ - -/** - * Type by which stream buffers are referenced. For example, a call to - * xStreamBufferCreate() returns an StreamBufferHandle_t variable that can - * then be used as a parameter to xStreamBufferSend(), xStreamBufferReceive(), - * etc. - */ -struct StreamBufferDef_t; -typedef struct StreamBufferDef_t * StreamBufferHandle_t; - - -/** - * message_buffer.h - * - *
- * StreamBufferHandle_t xStreamBufferCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes );
- * 
- * - * Creates a new stream buffer using dynamically allocated memory. See - * xStreamBufferCreateStatic() for a version that uses statically allocated - * memory (memory that is allocated at compile time). - * - * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in - * FreeRTOSConfig.h for xStreamBufferCreate() to be available. - * - * @param xBufferSizeBytes The total number of bytes the stream buffer will be - * able to hold at any one time. - * - * @param xTriggerLevelBytes The number of bytes that must be in the stream - * buffer before a task that is blocked on the stream buffer to wait for data is - * moved out of the blocked state. For example, if a task is blocked on a read - * of an empty stream buffer that has a trigger level of 1 then the task will be - * unblocked when a single byte is written to the buffer or the task's block - * time expires. As another example, if a task is blocked on a read of an empty - * stream buffer that has a trigger level of 10 then the task will not be - * unblocked until the stream buffer contains at least 10 bytes or the task's - * block time expires. If a reading task's block time expires before the - * trigger level is reached then the task will still receive however many bytes - * are actually available. Setting a trigger level of 0 will result in a - * trigger level of 1 being used. It is not valid to specify a trigger level - * that is greater than the buffer size. - * - * @return If NULL is returned, then the stream buffer cannot be created - * because there is insufficient heap memory available for FreeRTOS to allocate - * the stream buffer data structures and storage area. A non-NULL value being - * returned indicates that the stream buffer has been created successfully - - * the returned value should be stored as the handle to the created stream - * buffer. - * - * Example use: - *
- *
- * void vAFunction( void )
- * {
- * StreamBufferHandle_t xStreamBuffer;
- * const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10;
- *
- *  // Create a stream buffer that can hold 100 bytes.  The memory used to hold
- *  // both the stream buffer structure and the data in the stream buffer is
- *  // allocated dynamically.
- *  xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel );
- *
- *  if( xStreamBuffer == NULL )
- *  {
- *      // There was not enough heap memory space available to create the
- *      // stream buffer.
- *  }
- *  else
- *  {
- *      // The stream buffer was created successfully and can now be used.
- *  }
- * }
- * 
- * \defgroup xStreamBufferCreate xStreamBufferCreate - * \ingroup StreamBufferManagement - */ -#define xStreamBufferCreate( xBufferSizeBytes, xTriggerLevelBytes ) xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE ) - -/** - * stream_buffer.h - * - *
- * StreamBufferHandle_t xStreamBufferCreateStatic( size_t xBufferSizeBytes,
- *                                              size_t xTriggerLevelBytes,
- *                                              uint8_t *pucStreamBufferStorageArea,
- *                                              StaticStreamBuffer_t *pxStaticStreamBuffer );
- * 
- * Creates a new stream buffer using statically allocated memory. See - * xStreamBufferCreate() for a version that uses dynamically allocated memory. - * - * configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for - * xStreamBufferCreateStatic() to be available. - * - * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the - * pucStreamBufferStorageArea parameter. - * - * @param xTriggerLevelBytes The number of bytes that must be in the stream - * buffer before a task that is blocked on the stream buffer to wait for data is - * moved out of the blocked state. For example, if a task is blocked on a read - * of an empty stream buffer that has a trigger level of 1 then the task will be - * unblocked when a single byte is written to the buffer or the task's block - * time expires. As another example, if a task is blocked on a read of an empty - * stream buffer that has a trigger level of 10 then the task will not be - * unblocked until the stream buffer contains at least 10 bytes or the task's - * block time expires. If a reading task's block time expires before the - * trigger level is reached then the task will still receive however many bytes - * are actually available. Setting a trigger level of 0 will result in a - * trigger level of 1 being used. It is not valid to specify a trigger level - * that is greater than the buffer size. - * - * @param pucStreamBufferStorageArea Must point to a uint8_t array that is at - * least xBufferSizeBytes + 1 big. This is the array to which streams are - * copied when they are written to the stream buffer. - * - * @param pxStaticStreamBuffer Must point to a variable of type - * StaticStreamBuffer_t, which will be used to hold the stream buffer's data - * structure. - * - * @return If the stream buffer is created successfully then a handle to the - * created stream buffer is returned. If either pucStreamBufferStorageArea or - * pxStaticstreamBuffer are NULL then NULL is returned. - * - * Example use: - *
- *
- * // Used to dimension the array used to hold the streams.  The available space
- * // will actually be one less than this, so 999.
- #define STORAGE_SIZE_BYTES 1000
- *
- * // Defines the memory that will actually hold the streams within the stream
- * // buffer.
- * static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];
- *
- * // The variable used to hold the stream buffer structure.
- * StaticStreamBuffer_t xStreamBufferStruct;
- *
- * void MyFunction( void )
- * {
- * StreamBufferHandle_t xStreamBuffer;
- * const size_t xTriggerLevel = 1;
- *
- *  xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucBufferStorage ),
- *                                             xTriggerLevel,
- *                                             ucBufferStorage,
- *                                             &xStreamBufferStruct );
- *
- *  // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer
- *  // parameters were NULL, xStreamBuffer will not be NULL, and can be used to
- *  // reference the created stream buffer in other stream buffer API calls.
- *
- *  // Other code that uses the stream buffer can go here.
- * }
- *
- * 
- * \defgroup xStreamBufferCreateStatic xStreamBufferCreateStatic - * \ingroup StreamBufferManagement - */ -#define xStreamBufferCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer ) \ - xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE, pucStreamBufferStorageArea, pxStaticStreamBuffer ) - -/** - * stream_buffer.h - * - *
- * size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
- *                        const void *pvTxData,
- *                        size_t xDataLengthBytes,
- *                        TickType_t xTicksToWait );
- * 
- * - * Sends bytes to a stream buffer. The bytes are copied into the stream buffer. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xStreamBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xStreamBufferReceive()) inside a critical section and set the receive - * block time to 0. - * - * Use xStreamBufferSend() to write to a stream buffer from a task. Use - * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt - * service routine (ISR). - * - * @param xStreamBuffer The handle of the stream buffer to which a stream is - * being sent. - * - * @param pvTxData A pointer to the buffer that holds the bytes to be copied - * into the stream buffer. - * - * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData - * into the stream buffer. - * - * @param xTicksToWait The maximum amount of time the task should remain in the - * Blocked state to wait for enough space to become available in the stream - * buffer, should the stream buffer contain too little space to hold the - * another xDataLengthBytes bytes. The block time is specified in tick periods, - * so the absolute time it represents is dependent on the tick frequency. The - * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds - * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will - * cause the task to wait indefinitely (without timing out), provided - * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out - * before it can write all xDataLengthBytes into the buffer it will still write - * as many bytes as possible. A task does not use any CPU time when it is in - * the blocked state. - * - * @return The number of bytes written to the stream buffer. If a task times - * out before it can write all xDataLengthBytes into the buffer it will still - * write as many bytes as possible. - * - * Example use: - *
- * void vAFunction( StreamBufferHandle_t xStreamBuffer )
- * {
- * size_t xBytesSent;
- * uint8_t ucArrayToSend[] = { 0, 1, 2, 3 };
- * char *pcStringToSend = "String to send";
- * const TickType_t x100ms = pdMS_TO_TICKS( 100 );
- *
- *  // Send an array to the stream buffer, blocking for a maximum of 100ms to
- *  // wait for enough space to be available in the stream buffer.
- *  xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms );
- *
- *  if( xBytesSent != sizeof( ucArrayToSend ) )
- *  {
- *      // The call to xStreamBufferSend() times out before there was enough
- *      // space in the buffer for the data to be written, but it did
- *      // successfully write xBytesSent bytes.
- *  }
- *
- *  // Send the string to the stream buffer.  Return immediately if there is not
- *  // enough space in the buffer.
- *  xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 );
- *
- *  if( xBytesSent != strlen( pcStringToSend ) )
- *  {
- *      // The entire string could not be added to the stream buffer because
- *      // there was not enough free space in the buffer, but xBytesSent bytes
- *      // were sent.  Could try again to send the remaining bytes.
- *  }
- * }
- * 
- * \defgroup xStreamBufferSend xStreamBufferSend - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer,
- *                               const void *pvTxData,
- *                               size_t xDataLengthBytes,
- *                               BaseType_t *pxHigherPriorityTaskWoken );
- * 
- * - * Interrupt safe version of the API function that sends a stream of bytes to - * the stream buffer. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xStreamBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xStreamBufferReceive()) inside a critical section and set the receive - * block time to 0. - * - * Use xStreamBufferSend() to write to a stream buffer from a task. Use - * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt - * service routine (ISR). - * - * @param xStreamBuffer The handle of the stream buffer to which a stream is - * being sent. - * - * @param pvTxData A pointer to the data that is to be copied into the stream - * buffer. - * - * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData - * into the stream buffer. - * - * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will - * have a task blocked on it waiting for data. Calling - * xStreamBufferSendFromISR() can make data available, and so cause a task that - * was waiting for data to leave the Blocked state. If calling - * xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the - * unblocked task has a priority higher than the currently executing task (the - * task that was interrupted), then, internally, xStreamBufferSendFromISR() - * will set *pxHigherPriorityTaskWoken to pdTRUE. If - * xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a - * context switch should be performed before the interrupt is exited. This will - * ensure that the interrupt returns directly to the highest priority Ready - * state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it - * is passed into the function. See the example code below for an example. - * - * @return The number of bytes actually written to the stream buffer, which will - * be less than xDataLengthBytes if the stream buffer didn't have enough free - * space for all the bytes to be written. - * - * Example use: - *
- * // A stream buffer that has already been created.
- * StreamBufferHandle_t xStreamBuffer;
- *
- * void vAnInterruptServiceRoutine( void )
- * {
- * size_t xBytesSent;
- * char *pcStringToSend = "String to send";
- * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.
- *
- *  // Attempt to send the string to the stream buffer.
- *  xBytesSent = xStreamBufferSendFromISR( xStreamBuffer,
- *                                         ( void * ) pcStringToSend,
- *                                         strlen( pcStringToSend ),
- *                                         &xHigherPriorityTaskWoken );
- *
- *  if( xBytesSent != strlen( pcStringToSend ) )
- *  {
- *      // There was not enough free space in the stream buffer for the entire
- *      // string to be written, ut xBytesSent bytes were written.
- *  }
- *
- *  // If xHigherPriorityTaskWoken was set to pdTRUE inside
- *  // xStreamBufferSendFromISR() then a task that has a priority above the
- *  // priority of the currently executing task was unblocked and a context
- *  // switch should be performed to ensure the ISR returns to the unblocked
- *  // task.  In most FreeRTOS ports this is done by simply passing
- *  // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
- *  // variables value, and perform the context switch if necessary.  Check the
- *  // documentation for the port in use for port specific instructions.
- *  taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
- * }
- * 
- * \defgroup xStreamBufferSendFromISR xStreamBufferSendFromISR - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
- *                           void *pvRxData,
- *                           size_t xBufferLengthBytes,
- *                           TickType_t xTicksToWait );
- * 
- * - * Receives bytes from a stream buffer. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xStreamBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xStreamBufferReceive()) inside a critical section and set the receive - * block time to 0. - * - * Use xStreamBufferReceive() to read from a stream buffer from a task. Use - * xStreamBufferReceiveFromISR() to read from a stream buffer from an - * interrupt service routine (ISR). - * - * @param xStreamBuffer The handle of the stream buffer from which bytes are to - * be received. - * - * @param pvRxData A pointer to the buffer into which the received bytes will be - * copied. - * - * @param xBufferLengthBytes The length of the buffer pointed to by the - * pvRxData parameter. This sets the maximum number of bytes to receive in one - * call. xStreamBufferReceive will return as many bytes as possible up to a - * maximum set by xBufferLengthBytes. - * - * @param xTicksToWait The maximum amount of time the task should remain in the - * Blocked state to wait for data to become available if the stream buffer is - * empty. xStreamBufferReceive() will return immediately if xTicksToWait is - * zero. The block time is specified in tick periods, so the absolute time it - * represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can - * be used to convert a time specified in milliseconds into a time specified in - * ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait - * indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 - * in FreeRTOSConfig.h. A task does not use any CPU time when it is in the - * Blocked state. - * - * @return The number of bytes actually read from the stream buffer, which will - * be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed - * out before xBufferLengthBytes were available. - * - * Example use: - *
- * void vAFunction( StreamBuffer_t xStreamBuffer )
- * {
- * uint8_t ucRxData[ 20 ];
- * size_t xReceivedBytes;
- * const TickType_t xBlockTime = pdMS_TO_TICKS( 20 );
- *
- *  // Receive up to another sizeof( ucRxData ) bytes from the stream buffer.
- *  // Wait in the Blocked state (so not using any CPU processing time) for a
- *  // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be
- *  // available.
- *  xReceivedBytes = xStreamBufferReceive( xStreamBuffer,
- *                                         ( void * ) ucRxData,
- *                                         sizeof( ucRxData ),
- *                                         xBlockTime );
- *
- *  if( xReceivedBytes > 0 )
- *  {
- *      // A ucRxData contains another xRecievedBytes bytes of data, which can
- *      // be processed here....
- *  }
- * }
- * 
- * \defgroup xStreamBufferReceive xStreamBufferReceive - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, - void * pvRxData, - size_t xBufferLengthBytes, - TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer,
- *                                  void *pvRxData,
- *                                  size_t xBufferLengthBytes,
- *                                  BaseType_t *pxHigherPriorityTaskWoken );
- * 
- * - * An interrupt safe version of the API function that receives bytes from a - * stream buffer. - * - * Use xStreamBufferReceive() to read bytes from a stream buffer from a task. - * Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an - * interrupt service routine (ISR). - * - * @param xStreamBuffer The handle of the stream buffer from which a stream - * is being received. - * - * @param pvRxData A pointer to the buffer into which the received bytes are - * copied. - * - * @param xBufferLengthBytes The length of the buffer pointed to by the - * pvRxData parameter. This sets the maximum number of bytes to receive in one - * call. xStreamBufferReceive will return as many bytes as possible up to a - * maximum set by xBufferLengthBytes. - * - * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will - * have a task blocked on it waiting for space to become available. Calling - * xStreamBufferReceiveFromISR() can make space available, and so cause a task - * that is waiting for space to leave the Blocked state. If calling - * xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and - * the unblocked task has a priority higher than the currently executing task - * (the task that was interrupted), then, internally, - * xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. - * If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a - * context switch should be performed before the interrupt is exited. That will - * ensure the interrupt returns directly to the highest priority Ready state - * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is - * passed into the function. See the code example below for an example. - * - * @return The number of bytes read from the stream buffer, if any. - * - * Example use: - *
- * // A stream buffer that has already been created.
- * StreamBuffer_t xStreamBuffer;
- *
- * void vAnInterruptServiceRoutine( void )
- * {
- * uint8_t ucRxData[ 20 ];
- * size_t xReceivedBytes;
- * BaseType_t xHigherPriorityTaskWoken = pdFALSE;  // Initialised to pdFALSE.
- *
- *  // Receive the next stream from the stream buffer.
- *  xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer,
- *                                                ( void * ) ucRxData,
- *                                                sizeof( ucRxData ),
- *                                                &xHigherPriorityTaskWoken );
- *
- *  if( xReceivedBytes > 0 )
- *  {
- *      // ucRxData contains xReceivedBytes read from the stream buffer.
- *      // Process the stream here....
- *  }
- *
- *  // If xHigherPriorityTaskWoken was set to pdTRUE inside
- *  // xStreamBufferReceiveFromISR() then a task that has a priority above the
- *  // priority of the currently executing task was unblocked and a context
- *  // switch should be performed to ensure the ISR returns to the unblocked
- *  // task.  In most FreeRTOS ports this is done by simply passing
- *  // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
- *  // variables value, and perform the context switch if necessary.  Check the
- *  // documentation for the port in use for port specific instructions.
- *  taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
- * }
- * 
- * \defgroup xStreamBufferReceiveFromISR xStreamBufferReceiveFromISR - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, - void * pvRxData, - size_t xBufferLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer );
- * 
- * - * Deletes a stream buffer that was previously created using a call to - * xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream - * buffer was created using dynamic memory (that is, by xStreamBufferCreate()), - * then the allocated memory is freed. - * - * A stream buffer handle must not be used after the stream buffer has been - * deleted. - * - * @param xStreamBuffer The handle of the stream buffer to be deleted. - * - * \defgroup vStreamBufferDelete vStreamBufferDelete - * \ingroup StreamBufferManagement - */ -void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer );
- * 
- * - * Queries a stream buffer to see if it is full. A stream buffer is full if it - * does not have any free space, and therefore cannot accept any more data. - * - * @param xStreamBuffer The handle of the stream buffer being queried. - * - * @return If the stream buffer is full then pdTRUE is returned. Otherwise - * pdFALSE is returned. - * - * \defgroup xStreamBufferIsFull xStreamBufferIsFull - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer );
- * 
- * - * Queries a stream buffer to see if it is empty. A stream buffer is empty if - * it does not contain any data. - * - * @param xStreamBuffer The handle of the stream buffer being queried. - * - * @return If the stream buffer is empty then pdTRUE is returned. Otherwise - * pdFALSE is returned. - * - * \defgroup xStreamBufferIsEmpty xStreamBufferIsEmpty - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer );
- * 
- * - * Resets a stream buffer to its initial, empty, state. Any data that was in - * the stream buffer is discarded. A stream buffer can only be reset if there - * are no tasks blocked waiting to either send to or receive from the stream - * buffer. - * - * @param xStreamBuffer The handle of the stream buffer being reset. - * - * @return If the stream buffer is reset then pdPASS is returned. If there was - * a task blocked waiting to send to or read from the stream buffer then the - * stream buffer is not reset and pdFAIL is returned. - * - * \defgroup xStreamBufferReset xStreamBufferReset - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer );
- * 
- * - * Queries a stream buffer to see how much free space it contains, which is - * equal to the amount of data that can be sent to the stream buffer before it - * is full. - * - * @param xStreamBuffer The handle of the stream buffer being queried. - * - * @return The number of bytes that can be written to the stream buffer before - * the stream buffer would be full. - * - * \defgroup xStreamBufferSpacesAvailable xStreamBufferSpacesAvailable - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer );
- * 
- * - * Queries a stream buffer to see how much data it contains, which is equal to - * the number of bytes that can be read from the stream buffer before the stream - * buffer would be empty. - * - * @param xStreamBuffer The handle of the stream buffer being queried. - * - * @return The number of bytes that can be read from the stream buffer before - * the stream buffer would be empty. - * - * \defgroup xStreamBufferBytesAvailable xStreamBufferBytesAvailable - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel );
- * 
- * - * A stream buffer's trigger level is the number of bytes that must be in the - * stream buffer before a task that is blocked on the stream buffer to - * wait for data is moved out of the blocked state. For example, if a task is - * blocked on a read of an empty stream buffer that has a trigger level of 1 - * then the task will be unblocked when a single byte is written to the buffer - * or the task's block time expires. As another example, if a task is blocked - * on a read of an empty stream buffer that has a trigger level of 10 then the - * task will not be unblocked until the stream buffer contains at least 10 bytes - * or the task's block time expires. If a reading task's block time expires - * before the trigger level is reached then the task will still receive however - * many bytes are actually available. Setting a trigger level of 0 will result - * in a trigger level of 1 being used. It is not valid to specify a trigger - * level that is greater than the buffer size. - * - * A trigger level is set when the stream buffer is created, and can be modified - * using xStreamBufferSetTriggerLevel(). - * - * @param xStreamBuffer The handle of the stream buffer being updated. - * - * @param xTriggerLevel The new trigger level for the stream buffer. - * - * @return If xTriggerLevel was less than or equal to the stream buffer's length - * then the trigger level will be updated and pdTRUE is returned. Otherwise - * pdFALSE is returned. - * - * \defgroup xStreamBufferSetTriggerLevel xStreamBufferSetTriggerLevel - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, - size_t xTriggerLevel ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
- * 
- * - * For advanced users only. - * - * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when - * data is sent to a message buffer or stream buffer. If there was a task that - * was blocked on the message or stream buffer waiting for data to arrive then - * the sbSEND_COMPLETED() macro sends a notification to the task to remove it - * from the Blocked state. xStreamBufferSendCompletedFromISR() does the same - * thing. It is provided to enable application writers to implement their own - * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. - * - * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for - * additional information. - * - * @param xStreamBuffer The handle of the stream buffer to which data was - * written. - * - * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be - * initialised to pdFALSE before it is passed into - * xStreamBufferSendCompletedFromISR(). If calling - * xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, - * and the task has a priority above the priority of the currently running task, - * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a - * context switch should be performed before exiting the ISR. - * - * @return If a task was removed from the Blocked state then pdTRUE is returned. - * Otherwise pdFALSE is returned. - * - * \defgroup xStreamBufferSendCompletedFromISR xStreamBufferSendCompletedFromISR - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, - BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * - *
- * BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
- * 
- * - * For advanced users only. - * - * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when - * data is read out of a message buffer or stream buffer. If there was a task - * that was blocked on the message or stream buffer waiting for data to arrive - * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to - * remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() - * does the same thing. It is provided to enable application writers to - * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT - * ANY OTHER TIME. - * - * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for - * additional information. - * - * @param xStreamBuffer The handle of the stream buffer from which data was - * read. - * - * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be - * initialised to pdFALSE before it is passed into - * xStreamBufferReceiveCompletedFromISR(). If calling - * xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, - * and the task has a priority above the priority of the currently running task, - * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a - * context switch should be performed before exiting the ISR. - * - * @return If a task was removed from the Blocked state then pdTRUE is returned. - * Otherwise pdFALSE is returned. - * - * \defgroup xStreamBufferReceiveCompletedFromISR xStreamBufferReceiveCompletedFromISR - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, - BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - -/* Functions below here are not part of the public API. */ -StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION; - -StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer, - uint8_t * const pucStreamBufferStorageArea, - StaticStreamBuffer_t * const pxStaticStreamBuffer ) PRIVILEGED_FUNCTION; - -size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -#if ( configUSE_TRACE_FACILITY == 1 ) - void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, - UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION; - UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; -#endif - -/* *INDENT-OFF* */ -#if defined( __cplusplus ) - } -#endif -/* *INDENT-ON* */ - -#endif /* !defined( STREAM_BUFFER_H ) */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * Stream buffers are used to send a continuous stream of data from one task or + * interrupt to another. Their implementation is light weight, making them + * particularly suited for interrupt to task and core to core communication + * scenarios. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section section and set the + * receive block time to 0. + * + */ + +#ifndef STREAM_BUFFER_H +#define STREAM_BUFFER_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include stream_buffer.h" +#endif + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + extern "C" { +#endif +/* *INDENT-ON* */ + +/** + * Type of stream buffer. For internal use only. + */ +#define sbTYPE_STREAM_BUFFER ( ( BaseType_t ) 0 ) +#define sbTYPE_MESSAGE_BUFFER ( ( BaseType_t ) 1 ) +#define sbTYPE_STREAM_BATCHING_BUFFER ( ( BaseType_t ) 2 ) + +/** + * Type by which stream buffers are referenced. For example, a call to + * xStreamBufferCreate() returns an StreamBufferHandle_t variable that can + * then be used as a parameter to xStreamBufferSend(), xStreamBufferReceive(), + * etc. + */ +struct StreamBufferDef_t; +typedef struct StreamBufferDef_t * StreamBufferHandle_t; + +/** + * Type used as a stream buffer's optional callback. + */ +typedef void (* StreamBufferCallbackFunction_t)( StreamBufferHandle_t xStreamBuffer, + BaseType_t xIsInsideISR, + BaseType_t * const pxHigherPriorityTaskWoken ); + +/** + * stream_buffer.h + * + * @code{c} + * StreamBufferHandle_t xStreamBufferCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes ); + * @endcode + * + * Creates a new stream buffer using dynamically allocated memory. See + * xStreamBufferCreateStatic() for a version that uses statically allocated + * memory (memory that is allocated at compile time). + * + * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in + * FreeRTOSConfig.h for xStreamBufferCreate() to be available. + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferCreate() to be available. + * + * @param xBufferSizeBytes The total number of bytes the stream buffer will be + * able to hold at any one time. + * + * @param xTriggerLevelBytes The number of bytes that must be in the stream + * buffer before a task that is blocked on the stream buffer to wait for data is + * moved out of the blocked state. For example, if a task is blocked on a read + * of an empty stream buffer that has a trigger level of 1 then the task will be + * unblocked when a single byte is written to the buffer or the task's block + * time expires. As another example, if a task is blocked on a read of an empty + * stream buffer that has a trigger level of 10 then the task will not be + * unblocked until the stream buffer contains at least 10 bytes or the task's + * block time expires. If a reading task's block time expires before the + * trigger level is reached then the task will still receive however many bytes + * are actually available. Setting a trigger level of 0 will result in a + * trigger level of 1 being used. It is not valid to specify a trigger level + * that is greater than the buffer size. + * + * @param pxSendCompletedCallback Callback invoked when number of bytes at least equal to + * trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default + * implementation provided by sbSEND_COMPLETED macro. To enable the callback, + * configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. + * + * @param pxReceiveCompletedCallback Callback invoked when more than zero bytes are read from a + * stream buffer. If the parameter is NULL, it will use the default + * implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, + * configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. + * + * @return If NULL is returned, then the stream buffer cannot be created + * because there is insufficient heap memory available for FreeRTOS to allocate + * the stream buffer data structures and storage area. A non-NULL value being + * returned indicates that the stream buffer has been created successfully - + * the returned value should be stored as the handle to the created stream + * buffer. + * + * Example use: + * @code{c} + * + * void vAFunction( void ) + * { + * StreamBufferHandle_t xStreamBuffer; + * const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10; + * + * // Create a stream buffer that can hold 100 bytes. The memory used to hold + * // both the stream buffer structure and the data in the stream buffer is + * // allocated dynamically. + * xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel ); + * + * if( xStreamBuffer == NULL ) + * { + * // There was not enough heap memory space available to create the + * // stream buffer. + * } + * else + * { + * // The stream buffer was created successfully and can now be used. + * } + * } + * @endcode + * \defgroup xStreamBufferCreate xStreamBufferCreate + * \ingroup StreamBufferManagement + */ + +#define xStreamBufferCreate( xBufferSizeBytes, xTriggerLevelBytes ) \ + xStreamBufferGenericCreate( ( xBufferSizeBytes ), ( xTriggerLevelBytes ), sbTYPE_STREAM_BUFFER, NULL, NULL ) + +#if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + #define xStreamBufferCreateWithCallback( xBufferSizeBytes, xTriggerLevelBytes, pxSendCompletedCallback, pxReceiveCompletedCallback ) \ + xStreamBufferGenericCreate( ( xBufferSizeBytes ), ( xTriggerLevelBytes ), sbTYPE_STREAM_BUFFER, ( pxSendCompletedCallback ), ( pxReceiveCompletedCallback ) ) +#endif + +/** + * stream_buffer.h + * + * @code{c} + * StreamBufferHandle_t xStreamBufferCreateStatic( size_t xBufferSizeBytes, + * size_t xTriggerLevelBytes, + * uint8_t *pucStreamBufferStorageArea, + * StaticStreamBuffer_t *pxStaticStreamBuffer ); + * @endcode + * Creates a new stream buffer using statically allocated memory. See + * xStreamBufferCreate() for a version that uses dynamically allocated memory. + * + * configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for + * xStreamBufferCreateStatic() to be available. configUSE_STREAM_BUFFERS must be + * set to 1 in for FreeRTOSConfig.h for xStreamBufferCreateStatic() to be + * available. + * + * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the + * pucStreamBufferStorageArea parameter. + * + * @param xTriggerLevelBytes The number of bytes that must be in the stream + * buffer before a task that is blocked on the stream buffer to wait for data is + * moved out of the blocked state. For example, if a task is blocked on a read + * of an empty stream buffer that has a trigger level of 1 then the task will be + * unblocked when a single byte is written to the buffer or the task's block + * time expires. As another example, if a task is blocked on a read of an empty + * stream buffer that has a trigger level of 10 then the task will not be + * unblocked until the stream buffer contains at least 10 bytes or the task's + * block time expires. If a reading task's block time expires before the + * trigger level is reached then the task will still receive however many bytes + * are actually available. Setting a trigger level of 0 will result in a + * trigger level of 1 being used. It is not valid to specify a trigger level + * that is greater than the buffer size. + * + * @param pucStreamBufferStorageArea Must point to a uint8_t array that is at + * least xBufferSizeBytes big. This is the array to which streams are + * copied when they are written to the stream buffer. + * + * @param pxStaticStreamBuffer Must point to a variable of type + * StaticStreamBuffer_t, which will be used to hold the stream buffer's data + * structure. + * + * @param pxSendCompletedCallback Callback invoked when number of bytes at least equal to + * trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default + * implementation provided by sbSEND_COMPLETED macro. To enable the callback, + * configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. + * + * @param pxReceiveCompletedCallback Callback invoked when more than zero bytes are read from a + * stream buffer. If the parameter is NULL, it will use the default + * implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, + * configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. + * + * @return If the stream buffer is created successfully then a handle to the + * created stream buffer is returned. If either pucStreamBufferStorageArea or + * pxStaticstreamBuffer are NULL then NULL is returned. + * + * Example use: + * @code{c} + * + * // Used to dimension the array used to hold the streams. The available space + * // will actually be one less than this, so 999. + #define STORAGE_SIZE_BYTES 1000 + * + * // Defines the memory that will actually hold the streams within the stream + * // buffer. + * static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; + * + * // The variable used to hold the stream buffer structure. + * StaticStreamBuffer_t xStreamBufferStruct; + * + * void MyFunction( void ) + * { + * StreamBufferHandle_t xStreamBuffer; + * const size_t xTriggerLevel = 1; + * + * xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucStorageBuffer ), + * xTriggerLevel, + * ucStorageBuffer, + * &xStreamBufferStruct ); + * + * // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer + * // parameters were NULL, xStreamBuffer will not be NULL, and can be used to + * // reference the created stream buffer in other stream buffer API calls. + * + * // Other code that uses the stream buffer can go here. + * } + * + * @endcode + * \defgroup xStreamBufferCreateStatic xStreamBufferCreateStatic + * \ingroup StreamBufferManagement + */ + +#define xStreamBufferCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer ) \ + xStreamBufferGenericCreateStatic( ( xBufferSizeBytes ), ( xTriggerLevelBytes ), sbTYPE_STREAM_BUFFER, ( pucStreamBufferStorageArea ), ( pxStaticStreamBuffer ), NULL, NULL ) + +#if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + #define xStreamBufferCreateStaticWithCallback( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback ) \ + xStreamBufferGenericCreateStatic( ( xBufferSizeBytes ), ( xTriggerLevelBytes ), sbTYPE_STREAM_BUFFER, ( pucStreamBufferStorageArea ), ( pxStaticStreamBuffer ), ( pxSendCompletedCallback ), ( pxReceiveCompletedCallback ) ) +#endif + +/** + * stream_buffer.h + * + * @code{c} + * StreamBufferHandle_t xStreamBatchingBufferCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes ); + * @endcode + * + * Creates a new stream batching buffer using dynamically allocated memory. See + * xStreamBatchingBufferCreateStatic() for a version that uses statically + * allocated memory (memory that is allocated at compile time). + * + * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in + * FreeRTOSConfig.h for xStreamBatchingBufferCreate() to be available. + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBatchingBufferCreate() to be available. + * + * The difference between a stream buffer and a stream batching buffer is when + * a task performs read on a non-empty buffer: + * - The task reading from a non-empty stream buffer returns immediately + * regardless of the amount of data in the buffer. + * - The task reading from a non-empty steam batching buffer blocks until the + * amount of data in the buffer exceeds the trigger level or the block time + * expires. + * + * @param xBufferSizeBytes The total number of bytes the stream batching buffer + * will be able to hold at any one time. + * + * @param xTriggerLevelBytes The number of bytes that must be in the stream + * batching buffer to unblock a task calling xStreamBufferReceive before the + * block time expires. + * + * @param pxSendCompletedCallback Callback invoked when number of bytes at least + * equal to trigger level is sent to the stream batching buffer. If the + * parameter is NULL, it will use the default implementation provided by + * sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK + * must be set to 1 in FreeRTOSConfig.h. + * + * @param pxReceiveCompletedCallback Callback invoked when more than zero bytes + * are read from a stream batching buffer. If the parameter is NULL, it will use + * the default implementation provided by sbRECEIVE_COMPLETED macro. To enable + * the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in + * FreeRTOSConfig.h. + * + * @return If NULL is returned, then the stream batching buffer cannot be created + * because there is insufficient heap memory available for FreeRTOS to allocate + * the stream batching buffer data structures and storage area. A non-NULL value + * being returned indicates that the stream batching buffer has been created + * successfully - the returned value should be stored as the handle to the + * created stream batching buffer. + * + * Example use: + * @code{c} + * + * void vAFunction( void ) + * { + * StreamBufferHandle_t xStreamBatchingBuffer; + * const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10; + * + * // Create a stream batching buffer that can hold 100 bytes. The memory used + * // to hold both the stream batching buffer structure and the data in the stream + * // batching buffer is allocated dynamically. + * xStreamBatchingBuffer = xStreamBatchingBufferCreate( xStreamBufferSizeBytes, xTriggerLevel ); + * + * if( xStreamBatchingBuffer == NULL ) + * { + * // There was not enough heap memory space available to create the + * // stream batching buffer. + * } + * else + * { + * // The stream batching buffer was created successfully and can now be used. + * } + * } + * @endcode + * \defgroup xStreamBatchingBufferCreate xStreamBatchingBufferCreate + * \ingroup StreamBatchingBufferManagement + */ + +#define xStreamBatchingBufferCreate( xBufferSizeBytes, xTriggerLevelBytes ) \ + xStreamBufferGenericCreate( ( xBufferSizeBytes ), ( xTriggerLevelBytes ), sbTYPE_STREAM_BATCHING_BUFFER, NULL, NULL ) + +#if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + #define xStreamBatchingBufferCreateWithCallback( xBufferSizeBytes, xTriggerLevelBytes, pxSendCompletedCallback, pxReceiveCompletedCallback ) \ + xStreamBufferGenericCreate( ( xBufferSizeBytes ), ( xTriggerLevelBytes ), sbTYPE_STREAM_BATCHING_BUFFER, ( pxSendCompletedCallback ), ( pxReceiveCompletedCallback ) ) +#endif + +/** + * stream_buffer.h + * + * @code{c} + * StreamBufferHandle_t xStreamBatchingBufferCreateStatic( size_t xBufferSizeBytes, + * size_t xTriggerLevelBytes, + * uint8_t *pucStreamBufferStorageArea, + * StaticStreamBuffer_t *pxStaticStreamBuffer ); + * @endcode + * Creates a new stream batching buffer using statically allocated memory. See + * xStreamBatchingBufferCreate() for a version that uses dynamically allocated + * memory. + * + * configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for + * xStreamBatchingBufferCreateStatic() to be available. configUSE_STREAM_BUFFERS + * must be set to 1 in for FreeRTOSConfig.h for xStreamBatchingBufferCreateStatic() + * to be available. + * + * The difference between a stream buffer and a stream batching buffer is when + * a task performs read on a non-empty buffer: + * - The task reading from a non-empty stream buffer returns immediately + * regardless of the amount of data in the buffer. + * - The task reading from a non-empty steam batching buffer blocks until the + * amount of data in the buffer exceeds the trigger level or the block time + * expires. + * + * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the + * pucStreamBufferStorageArea parameter. + * + * @param xTriggerLevelBytes The number of bytes that must be in the stream + * batching buffer to unblock a task calling xStreamBufferReceive before the + * block time expires. + * + * @param pucStreamBufferStorageArea Must point to a uint8_t array that is at + * least xBufferSizeBytes big. This is the array to which streams are + * copied when they are written to the stream batching buffer. + * + * @param pxStaticStreamBuffer Must point to a variable of type + * StaticStreamBuffer_t, which will be used to hold the stream batching buffer's + * data structure. + * + * @param pxSendCompletedCallback Callback invoked when number of bytes at least + * equal to trigger level is sent to the stream batching buffer. If the parameter + * is NULL, it will use the default implementation provided by sbSEND_COMPLETED + * macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to + * 1 in FreeRTOSConfig.h. + * + * @param pxReceiveCompletedCallback Callback invoked when more than zero bytes + * are read from a stream batching buffer. If the parameter is NULL, it will use + * the default implementation provided by sbRECEIVE_COMPLETED macro. To enable + * the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in + * FreeRTOSConfig.h. + * + * @return If the stream batching buffer is created successfully then a handle + * to the created stream batching buffer is returned. If either pucStreamBufferStorageArea + * or pxStaticstreamBuffer are NULL then NULL is returned. + * + * Example use: + * @code{c} + * + * // Used to dimension the array used to hold the streams. The available space + * // will actually be one less than this, so 999. + * #define STORAGE_SIZE_BYTES 1000 + * + * // Defines the memory that will actually hold the streams within the stream + * // batching buffer. + * static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; + * + * // The variable used to hold the stream batching buffer structure. + * StaticStreamBuffer_t xStreamBufferStruct; + * + * void MyFunction( void ) + * { + * StreamBufferHandle_t xStreamBatchingBuffer; + * const size_t xTriggerLevel = 1; + * + * xStreamBatchingBuffer = xStreamBatchingBufferCreateStatic( sizeof( ucStorageBuffer ), + * xTriggerLevel, + * ucStorageBuffer, + * &xStreamBufferStruct ); + * + * // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer + * // parameters were NULL, xStreamBatchingBuffer will not be NULL, and can be + * // used to reference the created stream batching buffer in other stream + * // buffer API calls. + * + * // Other code that uses the stream batching buffer can go here. + * } + * + * @endcode + * \defgroup xStreamBatchingBufferCreateStatic xStreamBatchingBufferCreateStatic + * \ingroup StreamBatchingBufferManagement + */ + +#define xStreamBatchingBufferCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer ) \ + xStreamBufferGenericCreateStatic( ( xBufferSizeBytes ), ( xTriggerLevelBytes ), sbTYPE_STREAM_BATCHING_BUFFER, ( pucStreamBufferStorageArea ), ( pxStaticStreamBuffer ), NULL, NULL ) + +#if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + #define xStreamBatchingBufferCreateStaticWithCallback( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback ) \ + xStreamBufferGenericCreateStatic( ( xBufferSizeBytes ), ( xTriggerLevelBytes ), sbTYPE_STREAM_BATCHING_BUFFER, ( pucStreamBufferStorageArea ), ( pxStaticStreamBuffer ), ( pxSendCompletedCallback ), ( pxReceiveCompletedCallback ) ) +#endif + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferGetStaticBuffers( StreamBufferHandle_t xStreamBuffer, + * uint8_t ** ppucStreamBufferStorageArea, + * StaticStreamBuffer_t ** ppxStaticStreamBuffer ); + * @endcode + * + * Retrieve pointers to a statically created stream buffer's data structure + * buffer and storage area buffer. These are the same buffers that are supplied + * at the time of creation. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferGetStaticBuffers() to be available. + * + * @param xStreamBuffer The stream buffer for which to retrieve the buffers. + * + * @param ppucStreamBufferStorageArea Used to return a pointer to the stream + * buffer's storage area buffer. + * + * @param ppxStaticStreamBuffer Used to return a pointer to the stream + * buffer's data structure buffer. + * + * @return pdTRUE if buffers were retrieved, pdFALSE otherwise. + * + * \defgroup xStreamBufferGetStaticBuffers xStreamBufferGetStaticBuffers + * \ingroup StreamBufferManagement + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + BaseType_t xStreamBufferGetStaticBuffers( StreamBufferHandle_t xStreamBuffer, + uint8_t ** ppucStreamBufferStorageArea, + StaticStreamBuffer_t ** ppxStaticStreamBuffer ) PRIVILEGED_FUNCTION; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + * const void *pvTxData, + * size_t xDataLengthBytes, + * TickType_t xTicksToWait ); + * @endcode + * + * Sends bytes to a stream buffer. The bytes are copied into the stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferSend() to write to a stream buffer from a task. Use + * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt + * service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferSend() to be available. + * + * @param xStreamBuffer The handle of the stream buffer to which a stream is + * being sent. + * + * @param pvTxData A pointer to the buffer that holds the bytes to be copied + * into the stream buffer. + * + * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData + * into the stream buffer. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for enough space to become available in the stream + * buffer, should the stream buffer contain too little space to hold the + * another xDataLengthBytes bytes. The block time is specified in tick periods, + * so the absolute time it represents is dependent on the tick frequency. The + * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds + * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will + * cause the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out + * before it can write all xDataLengthBytes into the buffer it will still write + * as many bytes as possible. A task does not use any CPU time when it is in + * the blocked state. + * + * @return The number of bytes written to the stream buffer. If a task times + * out before it can write all xDataLengthBytes into the buffer it will still + * write as many bytes as possible. + * + * Example use: + * @code{c} + * void vAFunction( StreamBufferHandle_t xStreamBuffer ) + * { + * size_t xBytesSent; + * uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; + * char *pcStringToSend = "String to send"; + * const TickType_t x100ms = pdMS_TO_TICKS( 100 ); + * + * // Send an array to the stream buffer, blocking for a maximum of 100ms to + * // wait for enough space to be available in the stream buffer. + * xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); + * + * if( xBytesSent != sizeof( ucArrayToSend ) ) + * { + * // The call to xStreamBufferSend() times out before there was enough + * // space in the buffer for the data to be written, but it did + * // successfully write xBytesSent bytes. + * } + * + * // Send the string to the stream buffer. Return immediately if there is not + * // enough space in the buffer. + * xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // The entire string could not be added to the stream buffer because + * // there was not enough free space in the buffer, but xBytesSent bytes + * // were sent. Could try again to send the remaining bytes. + * } + * } + * @endcode + * \defgroup xStreamBufferSend xStreamBufferSend + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + * const void *pvTxData, + * size_t xDataLengthBytes, + * BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * Interrupt safe version of the API function that sends a stream of bytes to + * the stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferSend() to write to a stream buffer from a task. Use + * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt + * service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferSendFromISR() to be available. + * + * @param xStreamBuffer The handle of the stream buffer to which a stream is + * being sent. + * + * @param pvTxData A pointer to the data that is to be copied into the stream + * buffer. + * + * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData + * into the stream buffer. + * + * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will + * have a task blocked on it waiting for data. Calling + * xStreamBufferSendFromISR() can make data available, and so cause a task that + * was waiting for data to leave the Blocked state. If calling + * xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the + * unblocked task has a priority higher than the currently executing task (the + * task that was interrupted), then, internally, xStreamBufferSendFromISR() + * will set *pxHigherPriorityTaskWoken to pdTRUE. If + * xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. This will + * ensure that the interrupt returns directly to the highest priority Ready + * state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it + * is passed into the function. See the example code below for an example. + * + * @return The number of bytes actually written to the stream buffer, which will + * be less than xDataLengthBytes if the stream buffer didn't have enough free + * space for all the bytes to be written. + * + * Example use: + * @code{c} + * // A stream buffer that has already been created. + * StreamBufferHandle_t xStreamBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * size_t xBytesSent; + * char *pcStringToSend = "String to send"; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Attempt to send the string to the stream buffer. + * xBytesSent = xStreamBufferSendFromISR( xStreamBuffer, + * ( void * ) pcStringToSend, + * strlen( pcStringToSend ), + * &xHigherPriorityTaskWoken ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // There was not enough free space in the stream buffer for the entire + * // string to be written, ut xBytesSent bytes were written. + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xStreamBufferSendFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \defgroup xStreamBufferSendFromISR xStreamBufferSendFromISR + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + * void *pvRxData, + * size_t xBufferLengthBytes, + * TickType_t xTicksToWait ); + * @endcode + * + * Receives bytes from a stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferReceive() to read from a stream buffer from a task. Use + * xStreamBufferReceiveFromISR() to read from a stream buffer from an + * interrupt service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferReceive() to be available. + * + * @param xStreamBuffer The handle of the stream buffer from which bytes are to + * be received. + * + * @param pvRxData A pointer to the buffer into which the received bytes will be + * copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the + * pvRxData parameter. This sets the maximum number of bytes to receive in one + * call. xStreamBufferReceive will return as many bytes as possible up to a + * maximum set by xBufferLengthBytes. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for data to become available if the stream buffer is + * empty. xStreamBufferReceive() will return immediately if xTicksToWait is + * zero. The block time is specified in tick periods, so the absolute time it + * represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can + * be used to convert a time specified in milliseconds into a time specified in + * ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait + * indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 + * in FreeRTOSConfig.h. A task does not use any CPU time when it is in the + * Blocked state. + * + * @return The number of bytes actually read from the stream buffer, which will + * be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed + * out before xBufferLengthBytes were available. + * + * Example use: + * @code{c} + * void vAFunction( StreamBuffer_t xStreamBuffer ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); + * + * // Receive up to another sizeof( ucRxData ) bytes from the stream buffer. + * // Wait in the Blocked state (so not using any CPU processing time) for a + * // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be + * // available. + * xReceivedBytes = xStreamBufferReceive( xStreamBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * xBlockTime ); + * + * if( xReceivedBytes > 0 ) + * { + * // A ucRxData contains another xReceivedBytes bytes of data, which can + * // be processed here.... + * } + * } + * @endcode + * \defgroup xStreamBufferReceive xStreamBufferReceive + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + * void *pvRxData, + * size_t xBufferLengthBytes, + * BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * An interrupt safe version of the API function that receives bytes from a + * stream buffer. + * + * Use xStreamBufferReceive() to read bytes from a stream buffer from a task. + * Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an + * interrupt service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferReceiveFromISR() to be available. + * + * @param xStreamBuffer The handle of the stream buffer from which a stream + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received bytes are + * copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the + * pvRxData parameter. This sets the maximum number of bytes to receive in one + * call. xStreamBufferReceive will return as many bytes as possible up to a + * maximum set by xBufferLengthBytes. + * + * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will + * have a task blocked on it waiting for space to become available. Calling + * xStreamBufferReceiveFromISR() can make space available, and so cause a task + * that is waiting for space to leave the Blocked state. If calling + * xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and + * the unblocked task has a priority higher than the currently executing task + * (the task that was interrupted), then, internally, + * xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. + * If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. That will + * ensure the interrupt returns directly to the highest priority Ready state + * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is + * passed into the function. See the code example below for an example. + * + * @return The number of bytes read from the stream buffer, if any. + * + * Example use: + * @code{c} + * // A stream buffer that has already been created. + * StreamBuffer_t xStreamBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Receive the next stream from the stream buffer. + * xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * &xHigherPriorityTaskWoken ); + * + * if( xReceivedBytes > 0 ) + * { + * // ucRxData contains xReceivedBytes read from the stream buffer. + * // Process the stream here.... + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xStreamBufferReceiveFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \defgroup xStreamBufferReceiveFromISR xStreamBufferReceiveFromISR + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Deletes a stream buffer that was previously created using a call to + * xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream + * buffer was created using dynamic memory (that is, by xStreamBufferCreate()), + * then the allocated memory is freed. + * + * A stream buffer handle must not be used after the stream buffer has been + * deleted. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * vStreamBufferDelete() to be available. + * + * @param xStreamBuffer The handle of the stream buffer to be deleted. + * + * \defgroup vStreamBufferDelete vStreamBufferDelete + * \ingroup StreamBufferManagement + */ +void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Queries a stream buffer to see if it is full. A stream buffer is full if it + * does not have any free space, and therefore cannot accept any more data. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferIsFull() to be available. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return If the stream buffer is full then pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \defgroup xStreamBufferIsFull xStreamBufferIsFull + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Queries a stream buffer to see if it is empty. A stream buffer is empty if + * it does not contain any data. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferIsEmpty() to be available. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return If the stream buffer is empty then pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \defgroup xStreamBufferIsEmpty xStreamBufferIsEmpty + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Resets a stream buffer to its initial, empty, state. Any data that was in + * the stream buffer is discarded. A stream buffer can only be reset if there + * are no tasks blocked waiting to either send to or receive from the stream + * buffer. + * + * Use xStreamBufferReset() to reset a stream buffer from a task. + * Use xStreamBufferResetFromISR() to reset a stream buffer from an + * interrupt service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferReset() to be available. + * + * @param xStreamBuffer The handle of the stream buffer being reset. + * + * @return If the stream buffer is reset then pdPASS is returned. If there was + * a task blocked waiting to send to or read from the stream buffer then the + * stream buffer is not reset and pdFAIL is returned. + * + * \defgroup xStreamBufferReset xStreamBufferReset + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferResetFromISR( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * An interrupt safe version of the API function that resets the stream buffer. + * + * Resets a stream buffer to its initial, empty, state. Any data that was in + * the stream buffer is discarded. A stream buffer can only be reset if there + * are no tasks blocked waiting to either send to or receive from the stream + * buffer. + * + * Use xStreamBufferReset() to reset a stream buffer from a task. + * Use xStreamBufferResetFromISR() to reset a stream buffer from an + * interrupt service routine (ISR). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferResetFromISR() to be available. + * + * @param xStreamBuffer The handle of the stream buffer being reset. + * + * @return If the stream buffer is reset then pdPASS is returned. If there was + * a task blocked waiting to send to or read from the stream buffer then the + * stream buffer is not reset and pdFAIL is returned. + * + * \defgroup xStreamBufferResetFromISR xStreamBufferResetFromISR + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferResetFromISR( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Queries a stream buffer to see how much free space it contains, which is + * equal to the amount of data that can be sent to the stream buffer before it + * is full. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferSpacesAvailable() to be available. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return The number of bytes that can be written to the stream buffer before + * the stream buffer would be full. + * + * \defgroup xStreamBufferSpacesAvailable xStreamBufferSpacesAvailable + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Queries a stream buffer to see how much data it contains, which is equal to + * the number of bytes that can be read from the stream buffer before the stream + * buffer would be empty. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferBytesAvailable() to be available. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return The number of bytes that can be read from the stream buffer before + * the stream buffer would be empty. + * + * \defgroup xStreamBufferBytesAvailable xStreamBufferBytesAvailable + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ); + * @endcode + * + * A stream buffer's trigger level is the number of bytes that must be in the + * stream buffer before a task that is blocked on the stream buffer to + * wait for data is moved out of the blocked state. For example, if a task is + * blocked on a read of an empty stream buffer that has a trigger level of 1 + * then the task will be unblocked when a single byte is written to the buffer + * or the task's block time expires. As another example, if a task is blocked + * on a read of an empty stream buffer that has a trigger level of 10 then the + * task will not be unblocked until the stream buffer contains at least 10 bytes + * or the task's block time expires. If a reading task's block time expires + * before the trigger level is reached then the task will still receive however + * many bytes are actually available. Setting a trigger level of 0 will result + * in a trigger level of 1 being used. It is not valid to specify a trigger + * level that is greater than the buffer size. + * + * A trigger level is set when the stream buffer is created, and can be modified + * using xStreamBufferSetTriggerLevel(). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferSetTriggerLevel() to be available. + * + * @param xStreamBuffer The handle of the stream buffer being updated. + * + * @param xTriggerLevel The new trigger level for the stream buffer. + * + * @return If xTriggerLevel was less than or equal to the stream buffer's length + * then the trigger level will be updated and pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \defgroup xStreamBufferSetTriggerLevel xStreamBufferSetTriggerLevel + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, + size_t xTriggerLevel ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * For advanced users only. + * + * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is sent to a message buffer or stream buffer. If there was a task that + * was blocked on the message or stream buffer waiting for data to arrive then + * the sbSEND_COMPLETED() macro sends a notification to the task to remove it + * from the Blocked state. xStreamBufferSendCompletedFromISR() does the same + * thing. It is provided to enable application writers to implement their own + * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferSendCompletedFromISR() to be available. + * + * @param xStreamBuffer The handle of the stream buffer to which data was + * written. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xStreamBufferSendCompletedFromISR(). If calling + * xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xStreamBufferSendCompletedFromISR xStreamBufferSendCompletedFromISR + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * For advanced users only. + * + * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is read out of a message buffer or stream buffer. If there was a task + * that was blocked on the message or stream buffer waiting for data to arrive + * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to + * remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() + * does the same thing. It is provided to enable application writers to + * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT + * ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * xStreamBufferReceiveCompletedFromISR() to be available. + * + * @param xStreamBuffer The handle of the stream buffer from which data was + * read. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xStreamBufferReceiveCompletedFromISR(). If calling + * xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xStreamBufferReceiveCompletedFromISR xStreamBufferReceiveCompletedFromISR + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * UBaseType_t uxStreamBufferGetStreamBufferNotificationIndex( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Get the task notification index used for the supplied stream buffer which can + * be set using vStreamBufferSetStreamBufferNotificationIndex. If the task + * notification index for the stream buffer is not changed using + * vStreamBufferSetStreamBufferNotificationIndex, this function returns the + * default value (tskDEFAULT_INDEX_TO_NOTIFY). + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * uxStreamBufferGetStreamBufferNotificationIndex() to be available. + * + * @param xStreamBuffer The handle of the stream buffer for which the task + * notification index is retrieved. + * + * @return The task notification index for the stream buffer. + * + * \defgroup uxStreamBufferGetStreamBufferNotificationIndex uxStreamBufferGetStreamBufferNotificationIndex + * \ingroup StreamBufferManagement + */ +UBaseType_t uxStreamBufferGetStreamBufferNotificationIndex( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * void vStreamBufferSetStreamBufferNotificationIndex ( StreamBuffer_t xStreamBuffer, UBaseType_t uxNotificationIndex ); + * @endcode + * + * Set the task notification index used for the supplied stream buffer. + * Successive calls to stream buffer APIs (like xStreamBufferSend or + * xStreamBufferReceive) for this stream buffer will use this new index for + * their task notifications. + * + * If this function is not called, the default index (tskDEFAULT_INDEX_TO_NOTIFY) + * is used for task notifications. It is recommended to call this function + * before attempting to send or receive data from the stream buffer to avoid + * inconsistencies. + * + * configUSE_STREAM_BUFFERS must be set to 1 in for FreeRTOSConfig.h for + * vStreamBufferSetStreamBufferNotificationIndex() to be available. + * + * @param xStreamBuffer The handle of the stream buffer for which the task + * notification index is set. + * + * @param uxNotificationIndex The task notification index to set. + * + * \defgroup vStreamBufferSetStreamBufferNotificationIndex vStreamBufferSetStreamBufferNotificationIndex + * \ingroup StreamBufferManagement + */ +void vStreamBufferSetStreamBufferNotificationIndex( StreamBufferHandle_t xStreamBuffer, + UBaseType_t uxNotificationIndex ) PRIVILEGED_FUNCTION; + +/* Functions below here are not part of the public API. */ +StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xStreamBufferType, + StreamBufferCallbackFunction_t pxSendCompletedCallback, + StreamBufferCallbackFunction_t pxReceiveCompletedCallback ) PRIVILEGED_FUNCTION; + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xStreamBufferType, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer, + StreamBufferCallbackFunction_t pxSendCompletedCallback, + StreamBufferCallbackFunction_t pxReceiveCompletedCallback ) PRIVILEGED_FUNCTION; +#endif + +size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +#if ( configUSE_TRACE_FACILITY == 1 ) + void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, + UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; +#endif + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + } +#endif +/* *INDENT-ON* */ + +#endif /* !defined( STREAM_BUFFER_H ) */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/task.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/task.h index 730deec5a..c491625bc 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/task.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/task.h @@ -1,6 +1,8 @@ /* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in @@ -44,18 +46,30 @@ * MACROS AND DEFINITIONS *----------------------------------------------------------*/ -#define tskKERNEL_VERSION_NUMBER "V10.4.1" -#define tskKERNEL_VERSION_MAJOR 10 -#define tskKERNEL_VERSION_MINOR 4 -#define tskKERNEL_VERSION_BUILD 1 +/* + * If tskKERNEL_VERSION_NUMBER ends with + it represents the version in development + * after the numbered release. + * + * The tskKERNEL_VERSION_MAJOR, tskKERNEL_VERSION_MINOR, tskKERNEL_VERSION_BUILD + * values will reflect the last released version number. + */ +#define tskKERNEL_VERSION_NUMBER "V11.1.0" +#define tskKERNEL_VERSION_MAJOR 11 +#define tskKERNEL_VERSION_MINOR 1 +#define tskKERNEL_VERSION_BUILD 0 /* MPU region parameters passed in ulParameters * of MemoryRegion_t struct. */ -#define tskMPU_REGION_READ_ONLY ( 1UL << 0UL ) -#define tskMPU_REGION_READ_WRITE ( 1UL << 1UL ) -#define tskMPU_REGION_EXECUTE_NEVER ( 1UL << 2UL ) -#define tskMPU_REGION_NORMAL_MEMORY ( 1UL << 3UL ) -#define tskMPU_REGION_DEVICE_MEMORY ( 1UL << 4UL ) +#define tskMPU_REGION_READ_ONLY ( 1U << 0U ) +#define tskMPU_REGION_READ_WRITE ( 1U << 1U ) +#define tskMPU_REGION_EXECUTE_NEVER ( 1U << 2U ) +#define tskMPU_REGION_NORMAL_MEMORY ( 1U << 3U ) +#define tskMPU_REGION_DEVICE_MEMORY ( 1U << 4U ) + +/* MPU region permissions stored in MPU settings to + * authorize access requests. */ +#define tskMPU_READ_PERMISSION ( 1U << 0U ) +#define tskMPU_WRITE_PERMISSION ( 1U << 1U ) /* The direct to task notification feature used to have only a single notification * per task. Now there is an array of notifications per task that is dimensioned by @@ -74,34 +88,35 @@ * \defgroup TaskHandle_t TaskHandle_t * \ingroup Tasks */ -struct tskTaskControlBlock; /* The old naming convention is used to prevent breaking kernel aware debuggers. */ -typedef struct tskTaskControlBlock * TaskHandle_t; +struct tskTaskControlBlock; /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct tskTaskControlBlock * TaskHandle_t; +typedef const struct tskTaskControlBlock * ConstTaskHandle_t; /* * Defines the prototype to which the application task hook function must * conform. */ -typedef BaseType_t (* TaskHookFunction_t)( void * ); +typedef BaseType_t (* TaskHookFunction_t)( void * arg ); /* Task states returned by eTaskGetState. */ typedef enum { - eRunning = 0, /* A task is querying the state of itself, so must be running. */ - eReady, /* The task being queried is in a read or pending ready list. */ - eBlocked, /* The task being queried is in the Blocked state. */ - eSuspended, /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */ - eDeleted, /* The task being queried has been deleted, but its TCB has not yet been freed. */ - eInvalid /* Used as an 'invalid state' value. */ + eRunning = 0, /* A task is querying the state of itself, so must be running. */ + eReady, /* The task being queried is in a ready or pending ready list. */ + eBlocked, /* The task being queried is in the Blocked state. */ + eSuspended, /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */ + eDeleted, /* The task being queried has been deleted, but its TCB has not yet been freed. */ + eInvalid /* Used as an 'invalid state' value. */ } eTaskState; /* Actions that can be performed when vTaskNotify() is called. */ typedef enum { - eNoAction = 0, /* Notify the task without updating its notify value. */ - eSetBits, /* Set bits in the task's notification value. */ - eIncrement, /* Increment the task's notification value. */ - eSetValueWithOverwrite, /* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */ - eSetValueWithoutOverwrite /* Set the task's notification value if the previous value has been read by the task. */ + eNoAction = 0, /* Notify the task without updating its notify value. */ + eSetBits, /* Set bits in the task's notification value. */ + eIncrement, /* Increment the task's notification value. */ + eSetValueWithOverwrite, /* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */ + eSetValueWithoutOverwrite /* Set the task's notification value if the previous value has been read by the task. */ } eNotifyAction; /* @@ -129,7 +144,7 @@ typedef struct xMEMORY_REGION typedef struct xTASK_PARAMETERS { TaskFunction_t pvTaskCode; - const char * const pcName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const char * pcName; configSTACK_DEPTH_TYPE usStackDepth; void * pvParameters; UBaseType_t uxPriority; @@ -144,23 +159,33 @@ typedef struct xTASK_PARAMETERS * in the system. */ typedef struct xTASK_STATUS { - TaskHandle_t xHandle; /* The handle of the task to which the rest of the information in the structure relates. */ - const char * pcTaskName; /* A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - UBaseType_t xTaskNumber; /* A number unique to the task. */ - eTaskState eCurrentState; /* The state in which the task existed when the structure was populated. */ - UBaseType_t uxCurrentPriority; /* The priority at which the task was running (may be inherited) when the structure was populated. */ - UBaseType_t uxBasePriority; /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */ - uint32_t ulRunTimeCounter; /* The total run time allocated to the task so far, as defined by the run time stats clock. See https://www.FreeRTOS.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */ - StackType_t * pxStackBase; /* Points to the lowest address of the task's stack area. */ - configSTACK_DEPTH_TYPE usStackHighWaterMark; /* The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */ + TaskHandle_t xHandle; /* The handle of the task to which the rest of the information in the structure relates. */ + const char * pcTaskName; /* A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! */ + UBaseType_t xTaskNumber; /* A number unique to the task. */ + eTaskState eCurrentState; /* The state in which the task existed when the structure was populated. */ + UBaseType_t uxCurrentPriority; /* The priority at which the task was running (may be inherited) when the structure was populated. */ + UBaseType_t uxBasePriority; /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */ + configRUN_TIME_COUNTER_TYPE ulRunTimeCounter; /* The total run time allocated to the task so far, as defined by the run time stats clock. See https://www.FreeRTOS.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */ + StackType_t * pxStackBase; /* Points to the lowest address of the task's stack area. */ + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + StackType_t * pxTopOfStack; /* Points to the top address of the task's stack area. */ + StackType_t * pxEndOfStack; /* Points to the end address of the task's stack area. */ + #endif + configSTACK_DEPTH_TYPE usStackHighWaterMark; /* The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */ + #if ( ( configUSE_CORE_AFFINITY == 1 ) && ( configNUMBER_OF_CORES > 1 ) ) + UBaseType_t uxCoreAffinityMask; /* The core affinity mask for the task */ + #endif } TaskStatus_t; /* Possible return values for eTaskConfirmSleepModeStatus(). */ typedef enum { - eAbortSleep = 0, /* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */ - eStandardSleep, /* Enter a sleep mode that will not last any longer than the expected idle time. */ - eNoTasksWaitingTimeout /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */ + eAbortSleep = 0, /* A task has been made ready or a context switch pended since portSUPPRESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */ + eStandardSleep /* Enter a sleep mode that will not last any longer than the expected idle time. */ + #if ( INCLUDE_vTaskSuspend == 1 ) + , + eNoTasksWaitingTimeout /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */ + #endif /* INCLUDE_vTaskSuspend */ } eSleepModeStatus; /** @@ -170,6 +195,13 @@ typedef enum */ #define tskIDLE_PRIORITY ( ( UBaseType_t ) 0U ) +/** + * Defines affinity to all available cores. + * + * \ingroup TaskUtils + */ +#define tskNO_AFFINITY ( ( UBaseType_t ) -1 ) + /** * task. h * @@ -178,7 +210,7 @@ typedef enum * \defgroup taskYIELD taskYIELD * \ingroup SchedulerControl */ -#define taskYIELD() portYIELD() +#define taskYIELD() portYIELD() /** * task. h @@ -192,8 +224,12 @@ typedef enum * \defgroup taskENTER_CRITICAL taskENTER_CRITICAL * \ingroup SchedulerControl */ -#define taskENTER_CRITICAL() portENTER_CRITICAL() -#define taskENTER_CRITICAL_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() +#define taskENTER_CRITICAL() portENTER_CRITICAL() +#if ( configNUMBER_OF_CORES == 1 ) + #define taskENTER_CRITICAL_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() +#else + #define taskENTER_CRITICAL_FROM_ISR() portENTER_CRITICAL_FROM_ISR() +#endif /** * task. h @@ -207,8 +243,12 @@ typedef enum * \defgroup taskEXIT_CRITICAL taskEXIT_CRITICAL * \ingroup SchedulerControl */ -#define taskEXIT_CRITICAL() portEXIT_CRITICAL() -#define taskEXIT_CRITICAL_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( x ) +#define taskEXIT_CRITICAL() portEXIT_CRITICAL() +#if ( configNUMBER_OF_CORES == 1 ) + #define taskEXIT_CRITICAL_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( x ) +#else + #define taskEXIT_CRITICAL_FROM_ISR( x ) portEXIT_CRITICAL_FROM_ISR( x ) +#endif /** * task. h @@ -218,7 +258,7 @@ typedef enum * \defgroup taskDISABLE_INTERRUPTS taskDISABLE_INTERRUPTS * \ingroup SchedulerControl */ -#define taskDISABLE_INTERRUPTS() portDISABLE_INTERRUPTS() +#define taskDISABLE_INTERRUPTS() portDISABLE_INTERRUPTS() /** * task. h @@ -228,7 +268,7 @@ typedef enum * \defgroup taskENABLE_INTERRUPTS taskENABLE_INTERRUPTS * \ingroup SchedulerControl */ -#define taskENABLE_INTERRUPTS() portENABLE_INTERRUPTS() +#define taskENABLE_INTERRUPTS() portENABLE_INTERRUPTS() /* Definitions returned by xTaskGetSchedulerState(). taskSCHEDULER_SUSPENDED is * 0 to generate more optimal code when configASSERT() is defined as the constant @@ -237,6 +277,8 @@ typedef enum #define taskSCHEDULER_NOT_STARTED ( ( BaseType_t ) 1 ) #define taskSCHEDULER_RUNNING ( ( BaseType_t ) 2 ) +/* Checks if core ID is valid. */ +#define taskVALID_CORE_ID( xCoreID ) ( ( ( ( ( BaseType_t ) 0 <= ( xCoreID ) ) && ( ( xCoreID ) < ( BaseType_t ) configNUMBER_OF_CORES ) ) ) ? ( pdTRUE ) : ( pdFALSE ) ) /*----------------------------------------------------------- * TASK CREATION API @@ -244,16 +286,16 @@ typedef enum /** * task. h - *
+ * @code{c}
  * BaseType_t xTaskCreate(
- *                            TaskFunction_t pvTaskCode,
+ *                            TaskFunction_t pxTaskCode,
  *                            const char * const pcName,
- *                            configSTACK_DEPTH_TYPE usStackDepth,
+ *                            const configSTACK_DEPTH_TYPE uxStackDepth,
  *                            void *pvParameters,
  *                            UBaseType_t uxPriority,
- *                            TaskHandle_t *pvCreatedTask
+ *                            TaskHandle_t *pxCreatedTask
  *                        );
- * 
+ * @endcode * * Create a new task and add it to the list of tasks that are ready to run. * @@ -275,16 +317,16 @@ typedef enum * support can alternatively create an MPU constrained task using * xTaskCreateRestricted(). * - * @param pvTaskCode Pointer to the task entry function. Tasks + * @param pxTaskCode Pointer to the task entry function. Tasks * must be implemented to never return (i.e. continuous loop). * * @param pcName A descriptive name for the task. This is mainly used to * facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default * is 16. * - * @param usStackDepth The size of the task stack specified as the number of + * @param uxStackDepth The size of the task stack specified as the number of * variables the stack can hold - not the number of bytes. For example, if - * the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes + * the stack is 16 bits wide and uxStackDepth is defined as 100, 200 bytes * will be allocated for stack storage. * * @param pvParameters Pointer that will be used as the parameter for the task @@ -296,14 +338,14 @@ typedef enum * example, to create a privileged task at priority 2 the uxPriority parameter * should be set to ( 2 | portPRIVILEGE_BIT ). * - * @param pvCreatedTask Used to pass back a handle by which the created task + * @param pxCreatedTask Used to pass back a handle by which the created task * can be referenced. * * @return pdPASS if the task was successfully created and added to a ready * list, otherwise an error code defined in the file projdefs.h * * Example usage: - *
+ * @code{c}
  * // Task to be created.
  * void vTaskCode( void * pvParameters )
  * {
@@ -332,30 +374,40 @@ typedef enum
  *      vTaskDelete( xHandle );
  *   }
  * }
- * 
+ * @endcode * \defgroup xTaskCreate xTaskCreate * \ingroup Tasks */ #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const configSTACK_DEPTH_TYPE usStackDepth, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; #endif +#if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + BaseType_t xTaskCreateAffinitySet( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + UBaseType_t uxCoreAffinityMask, + TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif + /** * task. h - *
- * TaskHandle_t xTaskCreateStatic( TaskFunction_t pvTaskCode,
+ * @code{c}
+ * TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode,
  *                               const char * const pcName,
- *                               uint32_t ulStackDepth,
+ *                               const configSTACK_DEPTH_TYPE uxStackDepth,
  *                               void *pvParameters,
  *                               UBaseType_t uxPriority,
- *                               StackType_t *pxStackBuffer,
+ *                               StackType_t *puxStackBuffer,
  *                               StaticTask_t *pxTaskBuffer );
- * 
+ * @endcode * * Create a new task and add it to the list of tasks that are ready to run. * @@ -369,16 +421,16 @@ typedef enum * memory. xTaskCreateStatic() therefore allows a task to be created without * using any dynamic memory allocation. * - * @param pvTaskCode Pointer to the task entry function. Tasks + * @param pxTaskCode Pointer to the task entry function. Tasks * must be implemented to never return (i.e. continuous loop). * * @param pcName A descriptive name for the task. This is mainly used to * facilitate debugging. The maximum length of the string is defined by * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. * - * @param ulStackDepth The size of the task stack specified as the number of + * @param uxStackDepth The size of the task stack specified as the number of * variables the stack can hold - not the number of bytes. For example, if - * the stack is 32-bits wide and ulStackDepth is defined as 100 then 400 bytes + * the stack is 32-bits wide and uxStackDepth is defined as 100 then 400 bytes * will be allocated for stack storage. * * @param pvParameters Pointer that will be used as the parameter for the task @@ -386,23 +438,23 @@ typedef enum * * @param uxPriority The priority at which the task will run. * - * @param pxStackBuffer Must point to a StackType_t array that has at least - * ulStackDepth indexes - the array will then be used as the task's stack, + * @param puxStackBuffer Must point to a StackType_t array that has at least + * uxStackDepth indexes - the array will then be used as the task's stack, * removing the need for the stack to be allocated dynamically. * * @param pxTaskBuffer Must point to a variable of type StaticTask_t, which will * then be used to hold the task's data structures, removing the need for the * memory to be allocated dynamically. * - * @return If neither pxStackBuffer or pxTaskBuffer are NULL, then the task will - * be created and a handle to the created task is returned. If either - * pxStackBuffer or pxTaskBuffer are NULL then the task will not be created and + * @return If neither puxStackBuffer nor pxTaskBuffer are NULL, then the task + * will be created and a handle to the created task is returned. If either + * puxStackBuffer or pxTaskBuffer are NULL then the task will not be created and * NULL is returned. * * Example usage: - *
+ * @code{c}
  *
- *  // Dimensions the buffer that the task being created will use as its stack.
+ *  // Dimensions of the buffer that the task being created will use as its stack.
  *  // NOTE:  This is the number of words the stack will hold, not the number of
  *  // bytes.  For example, if each stack item is 32-bits, and this is set to 100,
  *  // then 400 bytes (100 * 32-bits) will be allocated.
@@ -421,7 +473,7 @@ typedef enum
  *  {
  *      // The parameter value is expected to be 1 as 1 is passed in the
  *      // pvParameters value in the call to xTaskCreateStatic().
- *      configASSERT( ( uint32_t ) pvParameters == 1UL );
+ *      configASSERT( ( uint32_t ) pvParameters == 1U );
  *
  *      for( ;; )
  *      {
@@ -449,25 +501,36 @@ typedef enum
  *      // to suspend the task.
  *      vTaskSuspend( xHandle );
  *  }
- * 
+ * @endcode * \defgroup xTaskCreateStatic xTaskCreateStatic * \ingroup Tasks */ #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, void * const pvParameters, UBaseType_t uxPriority, StackType_t * const puxStackBuffer, StaticTask_t * const pxTaskBuffer ) PRIVILEGED_FUNCTION; #endif /* configSUPPORT_STATIC_ALLOCATION */ +#if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + TaskHandle_t xTaskCreateStaticAffinitySet( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer, + UBaseType_t uxCoreAffinityMask ) PRIVILEGED_FUNCTION; +#endif + /** * task. h - *
+ * @code{c}
  * BaseType_t xTaskCreateRestricted( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask );
- * 
+ * @endcode * * Only available when configSUPPORT_DYNAMIC_ALLOCATION is set to 1. * @@ -493,15 +556,15 @@ typedef enum * list, otherwise an error code defined in the file projdefs.h * * Example usage: - *
+ * @code{c}
  * // Create an TaskParameters_t structure that defines the task to be created.
  * static const TaskParameters_t xCheckTaskParameters =
  * {
  *  vATask,     // pvTaskCode - the function that implements the task.
  *  "ATask",    // pcName - just a text name for the task to assist debugging.
- *  100,        // usStackDepth - the stack size DEFINED IN WORDS.
+ *  100,        // uxStackDepth - the stack size DEFINED IN WORDS.
  *  NULL,       // pvParameters - passed into the task function as the function parameters.
- *  ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state.
+ *  ( 1U | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state.
  *  cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack.
  *
  *  // xRegions - Allocate up to three separate memory regions for access by
@@ -532,7 +595,7 @@ typedef enum
  *  // and/or timer task.
  *  for( ;; );
  * }
- * 
+ * @endcode * \defgroup xTaskCreateRestricted xTaskCreateRestricted * \ingroup Tasks */ @@ -541,11 +604,17 @@ typedef enum TaskHandle_t * pxCreatedTask ) PRIVILEGED_FUNCTION; #endif +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + BaseType_t xTaskCreateRestrictedAffinitySet( const TaskParameters_t * const pxTaskDefinition, + UBaseType_t uxCoreAffinityMask, + TaskHandle_t * pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif + /** * task. h - *
+ * @code{c}
  * BaseType_t xTaskCreateRestrictedStatic( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask );
- * 
+ * @endcode * * Only available when configSUPPORT_STATIC_ALLOCATION is set to 1. * @@ -577,7 +646,7 @@ typedef enum * list, otherwise an error code defined in the file projdefs.h * * Example usage: - *
+ * @code{c}
  * // Create an TaskParameters_t structure that defines the task to be created.
  * // The StaticTask_t variable is only included in the structure when
  * // configSUPPORT_STATIC_ALLOCATION is set to 1.  The PRIVILEGED_DATA macro can
@@ -587,9 +656,9 @@ typedef enum
  * {
  *  vATask,     // pvTaskCode - the function that implements the task.
  *  "ATask",    // pcName - just a text name for the task to assist debugging.
- *  100,        // usStackDepth - the stack size DEFINED IN WORDS.
+ *  100,        // uxStackDepth - the stack size DEFINED IN WORDS.
  *  NULL,       // pvParameters - passed into the task function as the function parameters.
- *  ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state.
+ *  ( 1U | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state.
  *  cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack.
  *
  *  // xRegions - Allocate up to three separate memory regions for access by
@@ -613,7 +682,7 @@ typedef enum
  *  // Create a task from the const structure defined above.  The task handle
  *  // is requested (the second parameter is not NULL) but in this case just for
  *  // demonstration purposes as its not actually used.
- *  xTaskCreateRestricted( &xRegTest1Parameters, &xHandle );
+ *  xTaskCreateRestrictedStatic( &xRegTest1Parameters, &xHandle );
  *
  *  // Start the scheduler.
  *  vTaskStartScheduler();
@@ -622,7 +691,7 @@ typedef enum
  *  // and/or timer task.
  *  for( ;; );
  * }
- * 
+ * @endcode * \defgroup xTaskCreateRestrictedStatic xTaskCreateRestrictedStatic * \ingroup Tasks */ @@ -631,23 +700,29 @@ typedef enum TaskHandle_t * pxCreatedTask ) PRIVILEGED_FUNCTION; #endif +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + BaseType_t xTaskCreateRestrictedStaticAffinitySet( const TaskParameters_t * const pxTaskDefinition, + UBaseType_t uxCoreAffinityMask, + TaskHandle_t * pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif + /** * task. h - *
+ * @code{c}
  * void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions );
- * 
+ * @endcode * * Memory regions are assigned to a restricted task when the task is created by * a call to xTaskCreateRestricted(). These regions can be redefined using * vTaskAllocateMPURegions(). * - * @param xTask The handle of the task being updated. + * @param xTaskToModify The handle of the task being updated. * - * @param xRegions A pointer to an MemoryRegion_t structure that contains the + * @param[in] pxRegions A pointer to a MemoryRegion_t structure that contains the * new memory region definitions. * * Example usage: - *
+ * @code{c}
  * // Define an array of MemoryRegion_t structures that configures an MPU region
  * // allowing read/write access for 1024 bytes starting at the beginning of the
  * // ucOneKByte array.  The other two of the maximum 3 definable regions are
@@ -674,18 +749,20 @@ typedef enum
  *  // access its stack and the ucOneKByte array (unless any other statically
  *  // defined or shared regions have been declared elsewhere).
  * }
- * 
- * \defgroup xTaskCreateRestricted xTaskCreateRestricted + * @endcode + * \defgroup vTaskAllocateMPURegions vTaskAllocateMPURegions * \ingroup Tasks */ -void vTaskAllocateMPURegions( TaskHandle_t xTask, - const MemoryRegion_t * const pxRegions ) PRIVILEGED_FUNCTION; +#if ( portUSING_MPU_WRAPPERS == 1 ) + void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, + const MemoryRegion_t * const pxRegions ) PRIVILEGED_FUNCTION; +#endif /** * task. h - *
- * void vTaskDelete( TaskHandle_t xTask );
- * 
+ * @code{c} + * void vTaskDelete( TaskHandle_t xTaskToDelete ); + * @endcode * * INCLUDE_vTaskDelete must be defined as 1 for this function to be available. * See the configuration section for more information. @@ -703,11 +780,11 @@ void vTaskAllocateMPURegions( TaskHandle_t xTask, * See the demo application file death.c for sample code that utilises * vTaskDelete (). * - * @param xTask The handle of the task to be deleted. Passing NULL will + * @param xTaskToDelete The handle of the task to be deleted. Passing NULL will * cause the calling task to be deleted. * * Example usage: - *
+ * @code{c}
  * void vOtherFunction( void )
  * {
  * TaskHandle_t xHandle;
@@ -718,7 +795,7 @@ void vTaskAllocateMPURegions( TaskHandle_t xTask,
  *   // Use the handle to delete the task.
  *   vTaskDelete( xHandle );
  * }
- * 
+ * @endcode * \defgroup vTaskDelete vTaskDelete * \ingroup Tasks */ @@ -730,9 +807,9 @@ void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION; /** * task. h - *
+ * @code{c}
  * void vTaskDelay( const TickType_t xTicksToDelay );
- * 
+ * @endcode * * Delay a task for a given number of ticks. The actual time that the * task remains blocked depends on the tick rate. The constant @@ -748,9 +825,9 @@ void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION; * period of 100 ticks will cause the task to unblock 100 ticks after * vTaskDelay() is called. vTaskDelay() does not therefore provide a good method * of controlling the frequency of a periodic task as the path taken through the - * code, as well as other task and interrupt activity, will effect the frequency + * code, as well as other task and interrupt activity, will affect the frequency * at which vTaskDelay() gets called and therefore the time at which the task - * next executes. See vTaskDelayUntil() for an alternative API function designed + * next executes. See xTaskDelayUntil() for an alternative API function designed * to facilitate fixed frequency execution. It does this by specifying an * absolute time (rather than a relative time) at which the calling task should * unblock. @@ -780,11 +857,11 @@ void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION; /** * task. h - *
- * void vTaskDelayUntil( TickType_t *pxPreviousWakeTime, const TickType_t xTimeIncrement );
- * 
+ * @code{c} + * BaseType_t xTaskDelayUntil( TickType_t *pxPreviousWakeTime, const TickType_t xTimeIncrement ); + * @endcode * - * INCLUDE_vTaskDelayUntil must be defined as 1 for this function to be available. + * INCLUDE_xTaskDelayUntil must be defined as 1 for this function to be available. * See the configuration section for more information. * * Delay a task until a specified time. This function can be used by periodic @@ -799,52 +876,68 @@ void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION; * each time it executes]. * * Whereas vTaskDelay () specifies a wake time relative to the time at which the function - * is called, vTaskDelayUntil () specifies the absolute (exact) time at which it wishes to + * is called, xTaskDelayUntil () specifies the absolute (exact) time at which it wishes to * unblock. * - * The constant portTICK_PERIOD_MS can be used to calculate real time from the tick - * rate - with the resolution of one tick period. + * The macro pdMS_TO_TICKS() can be used to calculate the number of ticks from a + * time specified in milliseconds with a resolution of one tick period. * * @param pxPreviousWakeTime Pointer to a variable that holds the time at which the * task was last unblocked. The variable must be initialised with the current time * prior to its first use (see the example below). Following this the variable is - * automatically updated within vTaskDelayUntil (). + * automatically updated within xTaskDelayUntil (). * * @param xTimeIncrement The cycle time period. The task will be unblocked at - * time *pxPreviousWakeTime + xTimeIncrement. Calling vTaskDelayUntil with the + * time *pxPreviousWakeTime + xTimeIncrement. Calling xTaskDelayUntil with the * same xTimeIncrement parameter value will cause the task to execute with * a fixed interface period. * + * @return Value which can be used to check whether the task was actually delayed. + * Will be pdTRUE if the task way delayed and pdFALSE otherwise. A task will not + * be delayed if the next expected wake time is in the past. + * * Example usage: - *
+ * @code{c}
  * // Perform an action every 10 ticks.
  * void vTaskFunction( void * pvParameters )
  * {
  * TickType_t xLastWakeTime;
  * const TickType_t xFrequency = 10;
- *
- *   // Initialise the xLastWakeTime variable with the current time.
- *   xLastWakeTime = xTaskGetTickCount ();
- *   for( ;; )
- *   {
- *       // Wait for the next cycle.
- *       vTaskDelayUntil( &xLastWakeTime, xFrequency );
- *
- *       // Perform action here.
- *   }
+ * BaseType_t xWasDelayed;
+ *
+ *     // Initialise the xLastWakeTime variable with the current time.
+ *     xLastWakeTime = xTaskGetTickCount ();
+ *     for( ;; )
+ *     {
+ *         // Wait for the next cycle.
+ *         xWasDelayed = xTaskDelayUntil( &xLastWakeTime, xFrequency );
+ *
+ *         // Perform action here. xWasDelayed value can be used to determine
+ *         // whether a deadline was missed if the code here took too long.
+ *     }
  * }
- * 
- * \defgroup vTaskDelayUntil vTaskDelayUntil + * @endcode + * \defgroup xTaskDelayUntil xTaskDelayUntil * \ingroup TaskCtrl */ -void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, - const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION; +BaseType_t xTaskDelayUntil( TickType_t * const pxPreviousWakeTime, + const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION; + +/* + * vTaskDelayUntil() is the older version of xTaskDelayUntil() and does not + * return a value. + */ +#define vTaskDelayUntil( pxPreviousWakeTime, xTimeIncrement ) \ + do { \ + ( void ) xTaskDelayUntil( ( pxPreviousWakeTime ), ( xTimeIncrement ) ); \ + } while( 0 ) + /** * task. h - *
+ * @code{c}
  * BaseType_t xTaskAbortDelay( TaskHandle_t xTask );
- * 
+ * @endcode * * INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this * function to be available. @@ -870,13 +963,15 @@ void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, * \defgroup xTaskAbortDelay xTaskAbortDelay * \ingroup TaskCtrl */ -BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#if ( INCLUDE_xTaskAbortDelay == 1 ) + BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#endif /** * task. h - *
+ * @code{c}
  * UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask );
- * 
+ * @endcode * * INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. * See the configuration section for more information. @@ -889,7 +984,7 @@ BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; * @return The priority of xTask. * * Example usage: - *
+ * @code{c}
  * void vAFunction( void )
  * {
  * TaskHandle_t xHandle;
@@ -915,7 +1010,7 @@ BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
  *       // Our priority (obtained using NULL handle) is higher.
  *   }
  * }
- * 
+ * @endcode * \defgroup uxTaskPriorityGet uxTaskPriorityGet * \ingroup TaskCtrl */ @@ -923,9 +1018,9 @@ UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; /** * task. h - *
+ * @code{c}
  * UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask );
- * 
+ * @endcode * * A version of uxTaskPriorityGet() that can be used from an ISR. */ @@ -933,9 +1028,40 @@ UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) PRIVILEGED_FUNC /** * task. h - *
+ * @code{c}
+ * UBaseType_t uxTaskBasePriorityGet( const TaskHandle_t xTask );
+ * @endcode
+ *
+ * INCLUDE_uxTaskPriorityGet and configUSE_MUTEXES must be defined as 1 for this
+ * function to be available. See the configuration section for more information.
+ *
+ * Obtain the base priority of any task.
+ *
+ * @param xTask Handle of the task to be queried.  Passing a NULL
+ * handle results in the base priority of the calling task being returned.
+ *
+ * @return The base priority of xTask.
+ *
+ * \defgroup uxTaskPriorityGet uxTaskBasePriorityGet
+ * \ingroup TaskCtrl
+ */
+UBaseType_t uxTaskBasePriorityGet( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * @code{c}
+ * UBaseType_t uxTaskBasePriorityGetFromISR( const TaskHandle_t xTask );
+ * @endcode
+ *
+ * A version of uxTaskBasePriorityGet() that can be used from an ISR.
+ */
+UBaseType_t uxTaskBasePriorityGetFromISR( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * @code{c}
  * eTaskState eTaskGetState( TaskHandle_t xTask );
- * 
+ * @endcode * * INCLUDE_eTaskGetState must be defined as 1 for this function to be available. * See the configuration section for more information. @@ -949,13 +1075,15 @@ UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) PRIVILEGED_FUNC * state of the task might change between the function being called, and the * functions return value being tested by the calling task. */ -eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#if ( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) ) + eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#endif /** * task. h - *
+ * @code{c}
  * void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState );
- * 
+ * @endcode * * configUSE_TRACE_FACILITY must be defined as 1 for this function to be * available. See the configuration section for more information. @@ -969,7 +1097,7 @@ eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; * filled with information about the task referenced by the handle passed using * the xTask parameter. * - * @xGetFreeStackSpace The TaskStatus_t structure contains a member to report + * @param xGetFreeStackSpace The TaskStatus_t structure contains a member to report * the stack high water mark of the task being queried. Calculating the stack * high water mark takes a relatively long time, and can make the system * temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to @@ -985,7 +1113,7 @@ eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; * eState will be reported as the task state in the TaskStatus_t structure. * * Example usage: - *
+ * @code{c}
  * void vAFunction( void )
  * {
  * TaskHandle_t xHandle;
@@ -1003,20 +1131,22 @@ eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
  *                pdTRUE, // Include the high water mark in xTaskDetails.
  *                eInvalid ); // Include the task state in xTaskDetails.
  * }
- * 
+ * @endcode * \defgroup vTaskGetInfo vTaskGetInfo * \ingroup TaskCtrl */ -void vTaskGetInfo( TaskHandle_t xTask, - TaskStatus_t * pxTaskStatus, - BaseType_t xGetFreeStackSpace, - eTaskState eState ) PRIVILEGED_FUNCTION; +#if ( configUSE_TRACE_FACILITY == 1 ) + void vTaskGetInfo( TaskHandle_t xTask, + TaskStatus_t * pxTaskStatus, + BaseType_t xGetFreeStackSpace, + eTaskState eState ) PRIVILEGED_FUNCTION; +#endif /** * task. h - *
+ * @code{c}
  * void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority );
- * 
+ * @endcode * * INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. * See the configuration section for more information. @@ -1032,7 +1162,7 @@ void vTaskGetInfo( TaskHandle_t xTask, * @param uxNewPriority The priority to which the task will be set. * * Example usage: - *
+ * @code{c}
  * void vAFunction( void )
  * {
  * TaskHandle_t xHandle;
@@ -1050,7 +1180,7 @@ void vTaskGetInfo( TaskHandle_t xTask,
  *   // Use a NULL handle to raise our priority to the same value.
  *   vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 );
  * }
- * 
+ * @endcode * \defgroup vTaskPrioritySet vTaskPrioritySet * \ingroup TaskCtrl */ @@ -1059,9 +1189,9 @@ void vTaskPrioritySet( TaskHandle_t xTask, /** * task. h - *
+ * @code{c}
  * void vTaskSuspend( TaskHandle_t xTaskToSuspend );
- * 
+ * @endcode * * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. * See the configuration section for more information. @@ -1077,7 +1207,7 @@ void vTaskPrioritySet( TaskHandle_t xTask, * handle will cause the calling task to be suspended. * * Example usage: - *
+ * @code{c}
  * void vAFunction( void )
  * {
  * TaskHandle_t xHandle;
@@ -1104,7 +1234,7 @@ void vTaskPrioritySet( TaskHandle_t xTask,
  *   // We cannot get here unless another task calls vTaskResume
  *   // with our handle as the parameter.
  * }
- * 
+ * @endcode * \defgroup vTaskSuspend vTaskSuspend * \ingroup TaskCtrl */ @@ -1112,9 +1242,9 @@ void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION; /** * task. h - *
+ * @code{c}
  * void vTaskResume( TaskHandle_t xTaskToResume );
- * 
+ * @endcode * * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. * See the configuration section for more information. @@ -1128,7 +1258,7 @@ void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION; * @param xTaskToResume Handle to the task being readied. * * Example usage: - *
+ * @code{c}
  * void vAFunction( void )
  * {
  * TaskHandle_t xHandle;
@@ -1155,7 +1285,7 @@ void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION;
  *   // The created task will once again get microcontroller processing
  *   // time in accordance with its priority within the system.
  * }
- * 
+ * @endcode * \defgroup vTaskResume vTaskResume * \ingroup TaskCtrl */ @@ -1163,9 +1293,9 @@ void vTaskResume( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; /** * task. h - *
+ * @code{c}
  * void xTaskResumeFromISR( TaskHandle_t xTaskToResume );
- * 
+ * @endcode * * INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be * available. See the configuration section for more information. @@ -1192,15 +1322,173 @@ void vTaskResume( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; */ BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; +#if ( configUSE_CORE_AFFINITY == 1 ) + +/** + * @brief Sets the core affinity mask for a task. + * + * It sets the cores on which a task can run. configUSE_CORE_AFFINITY must + * be defined as 1 for this function to be available. + * + * @param xTask The handle of the task to set the core affinity mask for. + * Passing NULL will set the core affinity mask for the calling task. + * + * @param uxCoreAffinityMask A bitwise value that indicates the cores on + * which the task can run. Cores are numbered from 0 to configNUMBER_OF_CORES - 1. + * For example, to ensure that a task can run on core 0 and core 1, set + * uxCoreAffinityMask to 0x03. + * + * Example usage: + * + * // The function that creates task. + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * UBaseType_t uxCoreAffinityMask; + * + * // Create a task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &( xHandle ) ); + * + * // Define the core affinity mask such that this task can only run + * // on core 0 and core 2. + * uxCoreAffinityMask = ( ( 1 << 0 ) | ( 1 << 2 ) ); + * + * //Set the core affinity mask for the task. + * vTaskCoreAffinitySet( xHandle, uxCoreAffinityMask ); + * } + */ + void vTaskCoreAffinitySet( const TaskHandle_t xTask, + UBaseType_t uxCoreAffinityMask ); +#endif + +#if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + +/** + * @brief Gets the core affinity mask for a task. + * + * configUSE_CORE_AFFINITY must be defined as 1 for this function to be + * available. + * + * @param xTask The handle of the task to get the core affinity mask for. + * Passing NULL will get the core affinity mask for the calling task. + * + * @return The core affinity mask which is a bitwise value that indicates + * the cores on which a task can run. Cores are numbered from 0 to + * configNUMBER_OF_CORES - 1. For example, if a task can run on core 0 and core 1, + * the core affinity mask is 0x03. + * + * Example usage: + * + * // Task handle of the networking task - it is populated elsewhere. + * TaskHandle_t xNetworkingTaskHandle; + * + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * UBaseType_t uxNetworkingCoreAffinityMask; + * + * // Create a task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &( xHandle ) ); + * + * //Get the core affinity mask for the networking task. + * uxNetworkingCoreAffinityMask = vTaskCoreAffinityGet( xNetworkingTaskHandle ); + * + * // Here is a hypothetical scenario, just for the example. Assume that we + * // have 2 cores - Core 0 and core 1. We want to pin the application task to + * // the core different than the networking task to ensure that the + * // application task does not interfere with networking. + * if( ( uxNetworkingCoreAffinityMask & ( 1 << 0 ) ) != 0 ) + * { + * // The networking task can run on core 0, pin our task to core 1. + * vTaskCoreAffinitySet( xHandle, ( 1 << 1 ) ); + * } + * else + * { + * // Otherwise, pin our task to core 0. + * vTaskCoreAffinitySet( xHandle, ( 1 << 0 ) ); + * } + * } + */ + UBaseType_t vTaskCoreAffinityGet( ConstTaskHandle_t xTask ); +#endif + +#if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) + +/** + * @brief Disables preemption for a task. + * + * @param xTask The handle of the task to disable preemption. Passing NULL + * disables preemption for the calling task. + * + * Example usage: + * + * void vTaskCode( void *pvParameters ) + * { + * // Silence warnings about unused parameters. + * ( void ) pvParameters; + * + * for( ;; ) + * { + * // ... Perform some function here. + * + * // Disable preemption for this task. + * vTaskPreemptionDisable( NULL ); + * + * // The task will not be preempted when it is executing in this portion ... + * + * // ... until the preemption is enabled again. + * vTaskPreemptionEnable( NULL ); + * + * // The task can be preempted when it is executing in this portion. + * } + * } + */ + void vTaskPreemptionDisable( const TaskHandle_t xTask ); +#endif + +#if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) + +/** + * @brief Enables preemption for a task. + * + * @param xTask The handle of the task to enable preemption. Passing NULL + * enables preemption for the calling task. + * + * Example usage: + * + * void vTaskCode( void *pvParameters ) + * { + * // Silence warnings about unused parameters. + * ( void ) pvParameters; + * + * for( ;; ) + * { + * // ... Perform some function here. + * + * // Disable preemption for this task. + * vTaskPreemptionDisable( NULL ); + * + * // The task will not be preempted when it is executing in this portion ... + * + * // ... until the preemption is enabled again. + * vTaskPreemptionEnable( NULL ); + * + * // The task can be preempted when it is executing in this portion. + * } + * } + */ + void vTaskPreemptionEnable( const TaskHandle_t xTask ); +#endif + /*----------------------------------------------------------- * SCHEDULER CONTROL *----------------------------------------------------------*/ /** * task. h - *
+ * @code{c}
  * void vTaskStartScheduler( void );
- * 
+ * @endcode * * Starts the real time kernel tick processing. After calling the kernel * has control over which tasks are executed and when. @@ -1209,7 +1497,7 @@ BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; * tasks and starting the kernel. * * Example usage: - *
+ * @code{c}
  * void vAFunction( void )
  * {
  *   // Create at least one task before starting the kernel.
@@ -1220,7 +1508,7 @@ BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION;
  *
  *   // Will not get here unless a task calls vTaskEndScheduler ()
  * }
- * 
+ * @endcode * * \defgroup vTaskStartScheduler vTaskStartScheduler * \ingroup SchedulerControl @@ -1229,9 +1517,9 @@ void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION; /** * task. h - *
+ * @code{c}
  * void vTaskEndScheduler( void );
- * 
+ * @endcode * * NOTE: At the time of writing only the x86 real mode port, which runs on a PC * in place of DOS, implements this function. @@ -1253,7 +1541,7 @@ void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION; * tasks. * * Example usage: - *
+ * @code{c}
  * void vTaskCode( void * pvParameters )
  * {
  *   for( ;; )
@@ -1278,7 +1566,7 @@ void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION;
  *   // vTaskEndScheduler ().  When we get here we are back to single task
  *   // execution.
  * }
- * 
+ * @endcode * * \defgroup vTaskEndScheduler vTaskEndScheduler * \ingroup SchedulerControl @@ -1287,9 +1575,9 @@ void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION; /** * task. h - *
+ * @code{c}
  * void vTaskSuspendAll( void );
- * 
+ * @endcode * * Suspends the scheduler without disabling interrupts. Context switches will * not occur while the scheduler is suspended. @@ -1299,11 +1587,11 @@ void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION; * made. * * API functions that have the potential to cause a context switch (for example, - * vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler + * xTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler * is suspended. * * Example usage: - *
+ * @code{c}
  * void vTask1( void * pvParameters )
  * {
  *   for( ;; )
@@ -1332,7 +1620,7 @@ void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION;
  *       xTaskResumeAll ();
  *   }
  * }
- * 
+ * @endcode * \defgroup vTaskSuspendAll vTaskSuspendAll * \ingroup SchedulerControl */ @@ -1340,9 +1628,9 @@ void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION; /** * task. h - *
+ * @code{c}
  * BaseType_t xTaskResumeAll( void );
- * 
+ * @endcode * * Resumes scheduler activity after it was suspended by a call to * vTaskSuspendAll(). @@ -1354,7 +1642,7 @@ void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION; * returned, otherwise pdFALSE is returned. * * Example usage: - *
+ * @code{c}
  * void vTask1( void * pvParameters )
  * {
  *   for( ;; )
@@ -1388,7 +1676,7 @@ void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION;
  *       }
  *   }
  * }
- * 
+ * @endcode * \defgroup xTaskResumeAll xTaskResumeAll * \ingroup SchedulerControl */ @@ -1400,7 +1688,9 @@ BaseType_t xTaskResumeAll( void ) PRIVILEGED_FUNCTION; /** * task. h - *
TickType_t xTaskGetTickCount( void );
+ * @code{c} + * TickType_t xTaskGetTickCount( void ); + * @endcode * * @return The count of ticks since vTaskStartScheduler was called. * @@ -1411,7 +1701,9 @@ TickType_t xTaskGetTickCount( void ) PRIVILEGED_FUNCTION; /** * task. h - *
TickType_t xTaskGetTickCountFromISR( void );
+ * @code{c} + * TickType_t xTaskGetTickCountFromISR( void ); + * @endcode * * @return The count of ticks since vTaskStartScheduler was called. * @@ -1427,7 +1719,9 @@ TickType_t xTaskGetTickCountFromISR( void ) PRIVILEGED_FUNCTION; /** * task. h - *
uint16_t uxTaskGetNumberOfTasks( void );
+ * @code{c} + * uint16_t uxTaskGetNumberOfTasks( void ); + * @endcode * * @return The number of tasks that the real time kernel is currently managing. * This includes all ready, blocked and suspended tasks. A task that @@ -1441,7 +1735,9 @@ UBaseType_t uxTaskGetNumberOfTasks( void ) PRIVILEGED_FUNCTION; /** * task. h - *
char *pcTaskGetName( TaskHandle_t xTaskToQuery );
+ * @code{c} + * char *pcTaskGetName( TaskHandle_t xTaskToQuery ); + * @endcode * * @return The text (human readable) name of the task referenced by the handle * xTaskToQuery. A task can query its own name by either passing in its own @@ -1450,11 +1746,13 @@ UBaseType_t uxTaskGetNumberOfTasks( void ) PRIVILEGED_FUNCTION; * \defgroup pcTaskGetName pcTaskGetName * \ingroup TaskUtils */ -char * pcTaskGetName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +char * pcTaskGetName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /** * task. h - *
TaskHandle_t xTaskGetHandle( const char *pcNameToQuery );
+ * @code{c} + * TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ); + * @endcode * * NOTE: This function takes a relatively long time to complete and should be * used sparingly. @@ -1466,11 +1764,45 @@ char * pcTaskGetName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lin * \defgroup pcTaskGetHandle pcTaskGetHandle * \ingroup TaskUtils */ -TaskHandle_t xTaskGetHandle( const char * pcNameToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +#if ( INCLUDE_xTaskGetHandle == 1 ) + TaskHandle_t xTaskGetHandle( const char * pcNameToQuery ) PRIVILEGED_FUNCTION; +#endif + +/** + * task. h + * @code{c} + * BaseType_t xTaskGetStaticBuffers( TaskHandle_t xTask, + * StackType_t ** ppuxStackBuffer, + * StaticTask_t ** ppxTaskBuffer ); + * @endcode + * + * Retrieve pointers to a statically created task's data structure + * buffer and stack buffer. These are the same buffers that are supplied + * at the time of creation. + * + * @param xTask The task for which to retrieve the buffers. + * + * @param ppuxStackBuffer Used to return a pointer to the task's stack buffer. + * + * @param ppxTaskBuffer Used to return a pointer to the task's data structure + * buffer. + * + * @return pdTRUE if buffers were retrieved, pdFALSE otherwise. + * + * \defgroup xTaskGetStaticBuffers xTaskGetStaticBuffers + * \ingroup TaskUtils + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + BaseType_t xTaskGetStaticBuffers( TaskHandle_t xTask, + StackType_t ** ppuxStackBuffer, + StaticTask_t ** ppxTaskBuffer ) PRIVILEGED_FUNCTION; +#endif /* configSUPPORT_STATIC_ALLOCATION */ /** * task.h - *
UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask );
+ * @code{c} + * UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ); + * @endcode * * INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for * this function to be available. @@ -1493,11 +1825,15 @@ TaskHandle_t xTaskGetHandle( const char * pcNameToQuery ) PRIVILEGED_FUNCTION; * actual spaces on the stack rather than bytes) since the task referenced by * xTask was created. */ -UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) + UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#endif /** * task.h - *
configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask );
+ * @code{c} + * configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ); + * @endcode * * INCLUDE_uxTaskGetStackHighWaterMark2 must be set to 1 in FreeRTOSConfig.h for * this function to be available. @@ -1520,7 +1856,9 @@ UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTIO * actual spaces on the stack rather than bytes) since the task referenced by * xTask was created. */ -configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#if ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) + configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#endif /* When using trace macros it is sometimes necessary to include task.h before * FreeRTOS.h. When this is done TaskHookFunction_t will not yet have been defined, @@ -1533,9 +1871,9 @@ configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) PRIVIL /** * task.h - *
+ * @code{c}
  * void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction );
- * 
+ * @endcode * * Sets pxHookFunction to be the task hook function used by the task xTask. * Passing xTask as NULL has the effect of setting the calling tasks hook @@ -1546,9 +1884,9 @@ configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) PRIVIL /** * task.h - *
+ * @code{c}
  * void xTaskGetApplicationTaskTag( TaskHandle_t xTask );
- * 
+ * @endcode * * Returns the pxHookFunction value assigned to the task xTask. Do not * call from an interrupt service routine - call @@ -1558,9 +1896,9 @@ configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) PRIVIL /** * task.h - *
+ * @code{c}
  * void xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask );
- * 
+ * @endcode * * Returns the pxHookFunction value assigned to the task xTask. Can * be called from an interrupt service routine. @@ -1585,56 +1923,122 @@ configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) PRIVIL #endif #if ( configCHECK_FOR_STACK_OVERFLOW > 0 ) - - /** - * task.h - *
void vApplicationStackOverflowHook( TaskHandle_t xTask char *pcTaskName); 
- * - * The application stack overflow hook is called when a stack overflow is detected for a task. - * - * Details on stack overflow detection can be found here: https://www.FreeRTOS.org/Stacks-and-stack-overflow-checking.html - * - * @param xTask the task that just exceeded its stack boundaries. - * @param pcTaskName A character string containing the name of the offending task. - */ - void vApplicationStackOverflowHook( TaskHandle_t xTask, - char * pcTaskName ); - -#endif - -#if ( configUSE_TICK_HOOK > 0 ) - /** - * task.h - *
void vApplicationTickHook( void ); 
- * - * This hook function is called in the system tick handler after any OS work is completed. - */ - void vApplicationTickHook( void ); /*lint !e526 Symbol not defined as it is an application callback. */ + +/** + * task.h + * @code{c} + * void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName); + * @endcode + * + * The application stack overflow hook is called when a stack overflow is detected for a task. + * + * Details on stack overflow detection can be found here: https://www.FreeRTOS.org/Stacks-and-stack-overflow-checking.html + * + * @param xTask the task that just exceeded its stack boundaries. + * @param pcTaskName A character string containing the name of the offending task. + */ + /* MISRA Ref 8.6.1 [External linkage] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-86 */ + /* coverity[misra_c_2012_rule_8_6_violation] */ + void vApplicationStackOverflowHook( TaskHandle_t xTask, + char * pcTaskName ); + +#endif + +#if ( configUSE_IDLE_HOOK == 1 ) + +/** + * task.h + * @code{c} + * void vApplicationIdleHook( void ); + * @endcode + * + * The application idle hook is called by the idle task. + * This allows the application designer to add background functionality without + * the overhead of a separate task. + * NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, CALL A FUNCTION THAT MIGHT BLOCK. + */ + /* MISRA Ref 8.6.1 [External linkage] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-86 */ + /* coverity[misra_c_2012_rule_8_6_violation] */ + void vApplicationIdleHook( void ); + +#endif + + +#if ( configUSE_TICK_HOOK != 0 ) + +/** + * task.h + * @code{c} + * void vApplicationTickHook( void ); + * @endcode + * + * This hook function is called in the system tick handler after any OS work is completed. + */ + /* MISRA Ref 8.6.1 [External linkage] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-86 */ + /* coverity[misra_c_2012_rule_8_6_violation] */ + void vApplicationTickHook( void ); #endif #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - /** - * task.h - *
void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, StackType_t ** ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ) 
- * - * This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Idle Task TCB. This function is required when - * configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION - * - * @param ppxIdleTaskTCBBuffer A handle to a statically allocated TCB buffer - * @param ppxIdleTaskStackBuffer A handle to a statically allocated Stack buffer for thie idle task - * @param pulIdleTaskStackSize A pointer to the number of elements that will fit in the allocated stack buffer - */ + +/** + * task.h + * @code{c} + * void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, StackType_t ** ppxIdleTaskStackBuffer, configSTACK_DEPTH_TYPE * puxIdleTaskStackSize ) + * @endcode + * + * This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Idle Task TCB. This function is required when + * configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION + * + * @param ppxIdleTaskTCBBuffer A handle to a statically allocated TCB buffer + * @param ppxIdleTaskStackBuffer A handle to a statically allocated Stack buffer for the idle task + * @param puxIdleTaskStackSize A pointer to the number of elements that will fit in the allocated stack buffer + */ void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, - StackType_t ** ppxIdleTaskStackBuffer, - uint32_t * pulIdleTaskStackSize ); /*lint !e526 Symbol not defined as it is an application callback. */ -#endif + StackType_t ** ppxIdleTaskStackBuffer, + configSTACK_DEPTH_TYPE * puxIdleTaskStackSize ); + +/** + * task.h + * @code{c} + * void vApplicationGetPassiveIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, StackType_t ** ppxIdleTaskStackBuffer, configSTACK_DEPTH_TYPE * puxIdleTaskStackSize, BaseType_t xCoreID ) + * @endcode + * + * This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Idle Tasks TCB. This function is required when + * configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION + * + * In the FreeRTOS SMP, there are a total of configNUMBER_OF_CORES idle tasks: + * 1. 1 Active idle task which does all the housekeeping. + * 2. ( configNUMBER_OF_CORES - 1 ) Passive idle tasks which do nothing. + * These idle tasks are created to ensure that each core has an idle task to run when + * no other task is available to run. + * + * The function vApplicationGetPassiveIdleTaskMemory is called with passive idle + * task index 0, 1 ... ( configNUMBER_OF_CORES - 2 ) to get memory for passive idle + * tasks. + * + * @param ppxIdleTaskTCBBuffer A handle to a statically allocated TCB buffer + * @param ppxIdleTaskStackBuffer A handle to a statically allocated Stack buffer for the idle task + * @param puxIdleTaskStackSize A pointer to the number of elements that will fit in the allocated stack buffer + * @param xPassiveIdleTaskIndex The passive idle task index of the idle task buffer + */ + #if ( configNUMBER_OF_CORES > 1 ) + void vApplicationGetPassiveIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, + StackType_t ** ppxIdleTaskStackBuffer, + configSTACK_DEPTH_TYPE * puxIdleTaskStackSize, + BaseType_t xPassiveIdleTaskIndex ); + #endif /* #if ( configNUMBER_OF_CORES > 1 ) */ +#endif /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ /** * task.h - *
+ * @code{c}
  * BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter );
- * 
+ * @endcode * * Calls the hook function associated with xTask. Passing xTask as NULL has * the effect of calling the Running tasks (the calling task) hook function. @@ -1643,17 +2047,35 @@ configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) PRIVIL * wants. The return value is the value returned by the task hook function * registered by the user. */ -BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, - void * pvParameter ) PRIVILEGED_FUNCTION; +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, + void * pvParameter ) PRIVILEGED_FUNCTION; +#endif /** * xTaskGetIdleTaskHandle() is only available if * INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. * - * Simply returns the handle of the idle task. It is not valid to call - * xTaskGetIdleTaskHandle() before the scheduler has been started. + * In single-core FreeRTOS, this function simply returns the handle of the idle + * task. It is not valid to call xTaskGetIdleTaskHandle() before the scheduler + * has been started. + * + * In the FreeRTOS SMP, there are a total of configNUMBER_OF_CORES idle tasks: + * 1. 1 Active idle task which does all the housekeeping. + * 2. ( configNUMBER_OF_CORES - 1 ) Passive idle tasks which do nothing. + * These idle tasks are created to ensure that each core has an idle task to run when + * no other task is available to run. Call xTaskGetIdleTaskHandle() or + * xTaskGetIdleTaskHandleForCore() with xCoreID set to 0 to get the Active + * idle task handle. Call xTaskGetIdleTaskHandleForCore() with xCoreID set to + * 1,2 ... ( configNUMBER_OF_CORES - 1 ) to get the Passive idle task handles. */ -TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION; +#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) + #if ( configNUMBER_OF_CORES == 1 ) + TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION; + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + + TaskHandle_t xTaskGetIdleTaskHandleForCore( BaseType_t xCoreID ) PRIVILEGED_FUNCTION; +#endif /* #if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) */ /** * configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for @@ -1690,7 +2112,7 @@ TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION; * in the uxArraySize parameter was too small. * * Example usage: - *
+ * @code{c}
  *  // This example demonstrates how a human readable table of run time stats
  *  // information is generated from raw data provided by uxTaskGetSystemState().
  *  // The human readable table is written to pcWriteBuffer
@@ -1698,7 +2120,7 @@ TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION;
  *  {
  *  TaskStatus_t *pxTaskStatusArray;
  *  volatile UBaseType_t uxArraySize, x;
- *  uint32_t ulTotalRunTime, ulStatsAsPercentage;
+ *  configRUN_TIME_COUNTER_TYPE ulTotalRunTime, ulStatsAsPercentage;
  *
  *      // Make sure the write buffer does not contain a string.
  * pcWriteBuffer = 0x00;
@@ -1717,7 +2139,7 @@ TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION;
  *          uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );
  *
  *          // For percentage calculations.
- *          ulTotalRunTime /= 100UL;
+ *          ulTotalRunTime /= 100U;
  *
  *          // Avoid divide by zero errors.
  *          if( ulTotalRunTime > 0 )
@@ -1731,7 +2153,7 @@ TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION;
  *                  // ulTotalRunTimeDiv100 has already been divided by 100.
  *                  ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;
  *
- *                  if( ulStatsAsPercentage > 0UL )
+ *                  if( ulStatsAsPercentage > 0U )
  *                  {
  *                      sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
  *                  }
@@ -1750,20 +2172,85 @@ TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION;
  *          vPortFree( pxTaskStatusArray );
  *      }
  *  }
- *  
+ * @endcode + */ +#if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, + const UBaseType_t uxArraySize, + configRUN_TIME_COUNTER_TYPE * const pulTotalRunTime ) PRIVILEGED_FUNCTION; +#endif + +/** + * task. h + * @code{c} + * void vTaskListTasks( char *pcWriteBuffer, size_t uxBufferLength ); + * @endcode + * + * configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must + * both be defined as 1 for this function to be available. See the + * configuration section of the FreeRTOS.org website for more information. + * + * NOTE 1: This function will disable interrupts for its duration. It is + * not intended for normal application runtime use but as a debug aid. + * + * Lists all the current tasks, along with their current state and stack + * usage high water mark. + * + * Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or + * suspended ('S'). + * + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many of the + * demo applications. Do not consider it to be part of the scheduler. + * + * vTaskListTasks() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that displays task: + * names, states, priority, stack usage and task number. + * Stack usage specified as the number of unused StackType_t words stack can hold + * on top of stack - not the number of bytes. + * + * vTaskListTasks() has a dependency on the snprintf() C library function that might + * bloat the code size, use a lot of stack, and provide different results on + * different platforms. An alternative, tiny, third party, and limited + * functionality implementation of snprintf() is provided in many of the + * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note + * printf-stdarg.c does not provide a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly through a + * call to vTaskListTasks(). + * + * @param pcWriteBuffer A buffer into which the above mentioned details + * will be written, in ASCII form. This buffer is assumed to be large + * enough to contain the generated report. Approximately 40 bytes per + * task should be sufficient. + * + * @param uxBufferLength Length of the pcWriteBuffer. + * + * \defgroup vTaskListTasks vTaskListTasks + * \ingroup TaskUtils */ -UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, - const UBaseType_t uxArraySize, - uint32_t * const pulTotalRunTime ) PRIVILEGED_FUNCTION; +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) + void vTaskListTasks( char * pcWriteBuffer, + size_t uxBufferLength ) PRIVILEGED_FUNCTION; +#endif /** * task. h - *
void vTaskList( char *pcWriteBuffer );
+ * @code{c} + * void vTaskList( char *pcWriteBuffer ); + * @endcode * * configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must * both be defined as 1 for this function to be available. See the * configuration section of the FreeRTOS.org website for more information. * + * WARN: This function assumes that the pcWriteBuffer is of length + * configSTATS_BUFFER_MAX_LENGTH. This function is there only for + * backward compatibility. New applications are recommended to + * use vTaskListTasks and supply the length of the pcWriteBuffer explicitly. + * * NOTE 1: This function will disable interrupts for its duration. It is * not intended for normal application runtime use but as a debug aid. * @@ -1779,13 +2266,15 @@ UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, * demo applications. Do not consider it to be part of the scheduler. * * vTaskList() calls uxTaskGetSystemState(), then formats part of the - * uxTaskGetSystemState() output into a human readable table that displays task - * names, states and stack usage. + * uxTaskGetSystemState() output into a human readable table that displays task: + * names, states, priority, stack usage and task number. + * Stack usage specified as the number of unused StackType_t words stack can hold + * on top of stack - not the number of bytes. * - * vTaskList() has a dependency on the sprintf() C library function that might + * vTaskList() has a dependency on the snprintf() C library function that might * bloat the code size, use a lot of stack, and provide different results on * different platforms. An alternative, tiny, third party, and limited - * functionality implementation of sprintf() is provided in many of the + * functionality implementation of snprintf() is provided in many of the * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note * printf-stdarg.c does not provide a full snprintf() implementation!). * @@ -1801,11 +2290,13 @@ UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, * \defgroup vTaskList vTaskList * \ingroup TaskUtils */ -void vTaskList( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +#define vTaskList( pcWriteBuffer ) vTaskListTasks( ( pcWriteBuffer ), configSTATS_BUFFER_MAX_LENGTH ) /** * task. h - *
void vTaskGetRunTimeStats( char *pcWriteBuffer );
+ * @code{c} + * void vTaskGetRunTimeStatistics( char *pcWriteBuffer, size_t uxBufferLength ); + * @endcode * * configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS * must both be defined as 1 for this function to be available. The application @@ -1822,7 +2313,7 @@ void vTaskList( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unq * accumulated execution time being stored for each task. The resolution * of the accumulated time value depends on the frequency of the timer * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. - * Calling vTaskGetRunTimeStats() writes the total execution time of each + * Calling vTaskGetRunTimeStatistics() writes the total execution time of each * task into a buffer, both as an absolute count value and as a percentage * of the total system execution time. * @@ -1831,35 +2322,42 @@ void vTaskList( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unq * This function is provided for convenience only, and is used by many of the * demo applications. Do not consider it to be part of the scheduler. * - * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the - * uxTaskGetSystemState() output into a human readable table that displays the + * vTaskGetRunTimeStatistics() calls uxTaskGetSystemState(), then formats part of + * the uxTaskGetSystemState() output into a human readable table that displays the * amount of time each task has spent in the Running state in both absolute and * percentage terms. * - * vTaskGetRunTimeStats() has a dependency on the sprintf() C library function + * vTaskGetRunTimeStatistics() has a dependency on the snprintf() C library function * that might bloat the code size, use a lot of stack, and provide different * results on different platforms. An alternative, tiny, third party, and - * limited functionality implementation of sprintf() is provided in many of the + * limited functionality implementation of snprintf() is provided in many of the * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note * printf-stdarg.c does not provide a full snprintf() implementation!). * * It is recommended that production systems call uxTaskGetSystemState() directly * to get access to raw stats data, rather than indirectly through a call to - * vTaskGetRunTimeStats(). + * vTaskGetRunTimeStatistics(). * * @param pcWriteBuffer A buffer into which the execution times will be * written, in ASCII form. This buffer is assumed to be large enough to * contain the generated report. Approximately 40 bytes per task should * be sufficient. * - * \defgroup vTaskGetRunTimeStats vTaskGetRunTimeStats + * @param uxBufferLength Length of the pcWriteBuffer. + * + * \defgroup vTaskGetRunTimeStatistics vTaskGetRunTimeStatistics * \ingroup TaskUtils */ -void vTaskGetRunTimeStats( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configUSE_TRACE_FACILITY == 1 ) ) + void vTaskGetRunTimeStatistics( char * pcWriteBuffer, + size_t uxBufferLength ) PRIVILEGED_FUNCTION; +#endif /** * task. h - *
uint32_t ulTaskGetIdleRunTimeCounter( void );
+ * @code{c} + * void vTaskGetRunTimeStats( char *pcWriteBuffer ); + * @endcode * * configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS * must both be defined as 1 for this function to be available. The application @@ -1869,15 +2367,122 @@ void vTaskGetRunTimeStats( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lin * value respectively. The counter should be at least 10 times the frequency of * the tick count. * + * WARN: This function assumes that the pcWriteBuffer is of length + * configSTATS_BUFFER_MAX_LENGTH. This function is there only for + * backward compatiblity. New applications are recommended to use + * vTaskGetRunTimeStatistics and supply the length of the pcWriteBuffer + * explicitly. + * + * NOTE 1: This function will disable interrupts for its duration. It is + * not intended for normal application runtime use but as a debug aid. + * + * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total + * accumulated execution time being stored for each task. The resolution + * of the accumulated time value depends on the frequency of the timer + * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. + * Calling vTaskGetRunTimeStats() writes the total execution time of each + * task into a buffer, both as an absolute count value and as a percentage + * of the total system execution time. + * + * NOTE 2: + * + * This function is provided for convenience only, and is used by many of the + * demo applications. Do not consider it to be part of the scheduler. + * + * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that displays the + * amount of time each task has spent in the Running state in both absolute and + * percentage terms. + * + * vTaskGetRunTimeStats() has a dependency on the snprintf() C library function + * that might bloat the code size, use a lot of stack, and provide different + * results on different platforms. An alternative, tiny, third party, and + * limited functionality implementation of snprintf() is provided in many of the + * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note + * printf-stdarg.c does not provide a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() directly + * to get access to raw stats data, rather than indirectly through a call to + * vTaskGetRunTimeStats(). + * + * @param pcWriteBuffer A buffer into which the execution times will be + * written, in ASCII form. This buffer is assumed to be large enough to + * contain the generated report. Approximately 40 bytes per task should + * be sufficient. + * + * \defgroup vTaskGetRunTimeStats vTaskGetRunTimeStats + * \ingroup TaskUtils + */ +#define vTaskGetRunTimeStats( pcWriteBuffer ) vTaskGetRunTimeStatistics( ( pcWriteBuffer ), configSTATS_BUFFER_MAX_LENGTH ) + +/** + * task. h + * @code{c} + * configRUN_TIME_COUNTER_TYPE ulTaskGetRunTimeCounter( const TaskHandle_t xTask ); + * configRUN_TIME_COUNTER_TYPE ulTaskGetRunTimePercent( const TaskHandle_t xTask ); + * @endcode + * + * configGENERATE_RUN_TIME_STATS must be defined as 1 for these functions to be + * available. The application must also then provide definitions for + * portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and + * portGET_RUN_TIME_COUNTER_VALUE() to configure a peripheral timer/counter and + * return the timers current count value respectively. The counter should be + * at least 10 times the frequency of the tick count. + * + * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total + * accumulated execution time being stored for each task. The resolution + * of the accumulated time value depends on the frequency of the timer + * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. + * While uxTaskGetSystemState() and vTaskGetRunTimeStats() writes the total + * execution time of each task into a buffer, ulTaskGetRunTimeCounter() + * returns the total execution time of just one task and + * ulTaskGetRunTimePercent() returns the percentage of the CPU time used by + * just one task. + * + * @return The total run time of the given task or the percentage of the total + * run time consumed by the given task. This is the amount of time the task + * has actually been executing. The unit of time is dependent on the frequency + * configured using the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and + * portGET_RUN_TIME_COUNTER_VALUE() macros. + * + * \defgroup ulTaskGetRunTimeCounter ulTaskGetRunTimeCounter + * \ingroup TaskUtils + */ +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + configRUN_TIME_COUNTER_TYPE ulTaskGetRunTimeCounter( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + configRUN_TIME_COUNTER_TYPE ulTaskGetRunTimePercent( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#endif + +/** + * task. h + * @code{c} + * configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimeCounter( void ); + * configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimePercent( void ); + * @endcode + * + * configGENERATE_RUN_TIME_STATS must be defined as 1 for these functions to be + * available. The application must also then provide definitions for + * portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and + * portGET_RUN_TIME_COUNTER_VALUE() to configure a peripheral timer/counter and + * return the timers current count value respectively. The counter should be + * at least 10 times the frequency of the tick count. + * * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total * accumulated execution time being stored for each task. The resolution * of the accumulated time value depends on the frequency of the timer * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. * While uxTaskGetSystemState() and vTaskGetRunTimeStats() writes the total * execution time of each task into a buffer, ulTaskGetIdleRunTimeCounter() - * returns the total execution time of just the idle task. + * returns the total execution time of just the idle task and + * ulTaskGetIdleRunTimePercent() returns the percentage of the CPU time used by + * just the idle task. + * + * Note the amount of idle time is only a good measure of the slack time in a + * system if there are no other tasks executing at the idle priority, tickless + * idle is not used, and configIDLE_SHOULD_YIELD is set to 0. * - * @return The total run time of the idle task. This is the amount of time the + * @return The total run time of the idle task or the percentage of the total + * run time consumed by the idle task. This is the amount of time the * idle task has actually been executing. The unit of time is dependent on the * frequency configured using the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and * portGET_RUN_TIME_COUNTER_VALUE() macros. @@ -1885,12 +2490,17 @@ void vTaskGetRunTimeStats( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lin * \defgroup ulTaskGetIdleRunTimeCounter ulTaskGetIdleRunTimeCounter * \ingroup TaskUtils */ -uint32_t ulTaskGetIdleRunTimeCounter( void ) PRIVILEGED_FUNCTION; +#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) + configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimeCounter( void ) PRIVILEGED_FUNCTION; + configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimePercent( void ) PRIVILEGED_FUNCTION; +#endif /** * task. h - *
BaseType_t xTaskNotifyIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction );
- *
BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction );
+ * @code{c} + * BaseType_t xTaskNotifyIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction ); + * BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction ); + * @endcode * * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. * @@ -1916,9 +2526,8 @@ uint32_t ulTaskGetIdleRunTimeCounter( void ) PRIVILEGED_FUNCTION; * that way task notifications can be used to send data to a task, or be used as * light weight and fast binary or counting semaphores. * - * A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a - * notification to be pending, or ulTaskNotifyTakeIndexed() to [optionally] block - * to wait for a notification value to have a non-zero value. The task does + * A task can use xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() to + * [optionally] block to wait for a notification to be pending. The task does * not consume any CPU time while it is in the Blocked state. * * A notification sent to a task will remain pending until it is cleared by the @@ -1960,7 +2569,7 @@ uint32_t ulTaskGetIdleRunTimeCounter( void ) PRIVILEGED_FUNCTION; * * eSetBits - * The target notification value is bitwise ORed with ulValue. - * xTaskNofifyIndexed() always returns pdPASS in this case. + * xTaskNotifyIndexed() always returns pdPASS in this case. * * eIncrement - * The target notification value is incremented. ulValue is not used and @@ -2006,8 +2615,10 @@ BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, /** * task. h - *
BaseType_t xTaskNotifyAndQueryIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotifyValue );
- *
BaseType_t xTaskNotifyAndQuery( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotifyValue );
+ * @code{c} + * BaseType_t xTaskNotifyAndQueryIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotifyValue ); + * BaseType_t xTaskNotifyAndQuery( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotifyValue ); + * @endcode * * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. * @@ -2033,8 +2644,10 @@ BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, /** * task. h - *
BaseType_t xTaskNotifyIndexedFromISR( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );
- *
BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );
+ * @code{c} + * BaseType_t xTaskNotifyIndexedFromISR( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken ); + * BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode * * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. * @@ -2103,7 +2716,7 @@ BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, * value, if at all. Valid values for eAction are as follows: * * eSetBits - - * The task's notification value is bitwise ORed with ulValue. xTaskNofify() + * The task's notification value is bitwise ORed with ulValue. xTaskNotify() * always returns pdPASS in this case. * * eIncrement - @@ -2155,8 +2768,10 @@ BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, /** * task. h - *
BaseType_t xTaskNotifyAndQueryIndexedFromISR( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken );
- *
BaseType_t xTaskNotifyAndQueryFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken );
+ * @code{c} + * BaseType_t xTaskNotifyAndQueryIndexedFromISR( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ); + * BaseType_t xTaskNotifyAndQueryFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode * * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. * @@ -2182,11 +2797,11 @@ BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, /** * task. h - *
+ * @code{c}
  * BaseType_t xTaskNotifyWaitIndexed( UBaseType_t uxIndexToWaitOn, uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );
  *
  * BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );
- * 
+ * @endcode * * Waits for a direct to task notification to be pending at a given index within * an array of direct to task notifications. @@ -2248,7 +2863,7 @@ BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, * will be cleared in the calling task's notification value before the task * checks to see if any notifications are pending, and optionally blocks if no * notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if - * limits.h is included) or 0xffffffffUL (if limits.h is not included) will have + * limits.h is included) or 0xffffffffU (if limits.h is not included) will have * the effect of resetting the task's notification value to 0. Setting * ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. * @@ -2273,7 +2888,7 @@ BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, * the Blocked state for a notification to be received, should a notification * not already be pending when xTaskNotifyWait() was called. The task * will not consume any processing time while it is in the Blocked state. This - * is specified in kernel ticks, the macro pdMS_TO_TICSK( value_in_ms ) can be + * is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be * used to convert a time specified in milliseconds to a time specified in * ticks. * @@ -2296,8 +2911,10 @@ BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, /** * task. h - *
BaseType_t xTaskNotifyGiveIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify );
- *
BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify );
+ * @code{c} + * BaseType_t xTaskNotifyGiveIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify ); + * BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify ); + * @endcode * * Sends a direct to task notification to a particular index in the target * task's notification array in a manner similar to giving a counting semaphore. @@ -2331,7 +2948,7 @@ BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, * * When task notifications are being used as a binary or counting semaphore * equivalent then the task being notified should wait for the notification - * using the ulTaskNotificationTakeIndexed() API function rather than the + * using the ulTaskNotifyTakeIndexed() API function rather than the * xTaskNotifyWaitIndexed() API function. * * **NOTE** Each notification within the array operates independently - a task @@ -2371,8 +2988,10 @@ BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, /** * task. h - *
void vTaskNotifyGiveIndexedFromISR( TaskHandle_t xTaskHandle, UBaseType_t uxIndexToNotify, BaseType_t *pxHigherPriorityTaskWoken );
- *
void vTaskNotifyGiveFromISR( TaskHandle_t xTaskHandle, BaseType_t *pxHigherPriorityTaskWoken );
+ * @code{c} + * void vTaskNotifyGiveIndexedFromISR( TaskHandle_t xTaskHandle, UBaseType_t uxIndexToNotify, BaseType_t *pxHigherPriorityTaskWoken ); + * void vTaskNotifyGiveFromISR( TaskHandle_t xTaskHandle, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode * * A version of xTaskNotifyGiveIndexed() that can be called from an interrupt * service routine (ISR). @@ -2406,7 +3025,7 @@ BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, * * When task notifications are being used as a binary or counting semaphore * equivalent then the task being notified should wait for the notification - * using the ulTaskNotificationTakeIndexed() API function rather than the + * using the ulTaskNotifyTakeIndexed() API function rather than the * xTaskNotifyWaitIndexed() API function. * * **NOTE** Each notification within the array operates independently - a task @@ -2450,17 +3069,17 @@ void vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; #define vTaskNotifyGiveFromISR( xTaskToNotify, pxHigherPriorityTaskWoken ) \ - vTaskGenericNotifyGiveFromISR( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( pxHigherPriorityTaskWoken ) ); + vTaskGenericNotifyGiveFromISR( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( pxHigherPriorityTaskWoken ) ) #define vTaskNotifyGiveIndexedFromISR( xTaskToNotify, uxIndexToNotify, pxHigherPriorityTaskWoken ) \ - vTaskGenericNotifyGiveFromISR( ( xTaskToNotify ), ( uxIndexToNotify ), ( pxHigherPriorityTaskWoken ) ); + vTaskGenericNotifyGiveFromISR( ( xTaskToNotify ), ( uxIndexToNotify ), ( pxHigherPriorityTaskWoken ) ) /** * task. h - *
+ * @code{c}
  * uint32_t ulTaskNotifyTakeIndexed( UBaseType_t uxIndexToWaitOn, BaseType_t xClearCountOnExit, TickType_t xTicksToWait );
- * 
+ *
  * uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );
- * 
+ * @endcode * * Waits for a direct to task notification on a particular index in the calling * task's notification array in a manner similar to taking a counting semaphore. @@ -2504,8 +3123,8 @@ void vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify, * value acts like a counting semaphore. * * A task can use ulTaskNotifyTakeIndexed() to [optionally] block to wait for - * the task's notification value to be non-zero. The task does not consume any - * CPU time while it is in the Blocked state. + * a notification. The task does not consume any CPU time while it is in the + * Blocked state. * * Where as xTaskNotifyWaitIndexed() will return when a notification is pending, * ulTaskNotifyTakeIndexed() will return when the task's notification value is @@ -2543,7 +3162,7 @@ void vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify, * should the count not already be greater than zero when * ulTaskNotifyTake() was called. The task will not consume any processing * time while it is in the Blocked state. This is specified in kernel ticks, - * the macro pdMS_TO_TICSK( value_in_ms ) can be used to convert a time + * the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time * specified in milliseconds to a time specified in ticks. * * @return The task's notification count before it is either cleared to zero or @@ -2562,11 +3181,11 @@ uint32_t ulTaskGenericNotifyTake( UBaseType_t uxIndexToWaitOn, /** * task. h - *
+ * @code{c}
  * BaseType_t xTaskNotifyStateClearIndexed( TaskHandle_t xTask, UBaseType_t uxIndexToCLear );
- * 
+ *
  * BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask );
- * 
+ * @endcode * * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. * @@ -2626,11 +3245,11 @@ BaseType_t xTaskGenericNotifyStateClear( TaskHandle_t xTask, /** * task. h - *
+ * @code{c}
  * uint32_t ulTaskNotifyValueClearIndexed( TaskHandle_t xTask, UBaseType_t uxIndexToClear, uint32_t ulBitsToClear );
- * 
+ *
  * uint32_t ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear );
- * 
+ * @endcode * * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. * @@ -2692,9 +3311,9 @@ uint32_t ulTaskGenericNotifyValueClear( TaskHandle_t xTask, /** * task.h - *
+ * @code{c}
  * void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut );
- * 
+ * @endcode * * Capture the current time for future use with xTaskCheckForTimeOut(). * @@ -2708,9 +3327,9 @@ void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; /** * task.h - *
+ * @code{c}
  * BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait );
- * 
+ * @endcode * * Determines if pxTicksToWait ticks has passed since a time was captured * using a call to vTaskSetTimeOutState(). The captured time includes the tick @@ -2722,7 +3341,7 @@ void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; * @param pxTicksToWait The number of ticks to check for timeout i.e. if * pxTicksToWait ticks have passed since pxTimeOut was last updated (either by * vTaskSetTimeOutState() or xTaskCheckForTimeOut()), the timeout has occurred. - * If the timeout has not occurred, pxTIcksToWait is updated to reflect the + * If the timeout has not occurred, pxTicksToWait is updated to reflect the * number of remaining ticks. * * @return If timeout has occurred, pdTRUE is returned. Otherwise pdFALSE is @@ -2732,7 +3351,7 @@ void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; * @see https://www.FreeRTOS.org/xTaskCheckForTimeOut.html * * Example Usage: - *
+ * @code{c}
  *  // Driver library function used to receive uxWantedBytes from an Rx buffer
  *  // that is filled by a UART interrupt. If there are not enough bytes in the
  *  // Rx buffer then the task enters the Blocked state until it is notified that
@@ -2742,7 +3361,7 @@ void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION;
  *  // spent in the Blocked state does not exceed MAX_TIME_TO_WAIT. This
  *  // continues until either the buffer contains at least uxWantedBytes bytes,
  *  // or the total amount of time spent in the Blocked state reaches
- *  // MAX_TIME_TO_WAIT – at which point the task reads however many bytes are
+ *  // MAX_TIME_TO_WAIT - at which point the task reads however many bytes are
  *  // available up to a maximum of uxWantedBytes.
  *
  *  size_t xUART_Receive( uint8_t *pucBuffer, size_t uxWantedBytes )
@@ -2785,7 +3404,7 @@ void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION;
  *
  *      return uxReceived;
  *  }
- * 
+ * @endcode * \defgroup xTaskCheckForTimeOut xTaskCheckForTimeOut * \ingroup TaskCtrl */ @@ -2794,9 +3413,9 @@ BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, /** * task.h - *
+ * @code{c}
  * BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp );
- * 
+ * @endcode * * This function corrects the tick count value after the application code has held * interrupts disabled for an extended period resulting in tick interrupts having @@ -2820,11 +3439,31 @@ BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, */ BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) PRIVILEGED_FUNCTION; +/** + * task.h + * @code{c} + * void vTaskResetState( void ); + * @endcode + * + * This function resets the internal state of the task. It must be called by the + * application before restarting the scheduler. + * + * \defgroup vTaskResetState vTaskResetState + * \ingroup SchedulerControl + */ +void vTaskResetState( void ) PRIVILEGED_FUNCTION; + /*----------------------------------------------------------- * SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES *----------------------------------------------------------*/ +#if ( configNUMBER_OF_CORES == 1 ) + #define taskYIELD_WITHIN_API() portYIELD_WITHIN_API() +#else /* #if ( configNUMBER_OF_CORES == 1 ) */ + #define taskYIELD_WITHIN_API() vTaskYieldWithinAPI() +#endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + /* * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS @@ -2859,7 +3498,7 @@ BaseType_t xTaskIncrementTick( void ) PRIVILEGED_FUNCTION; * xItemValue value, and inserts the list item at the end of the list. * * The 'ordered' version uses the existing event list item value (which is the - * owning tasks priority) to insert the list item into the event list is task + * owning task's priority) to insert the list item into the event list in task * priority order. * * @param pxEventList The list containing tasks that are blocked waiting @@ -2869,7 +3508,7 @@ BaseType_t xTaskIncrementTick( void ) PRIVILEGED_FUNCTION; * event list is not ordered by task priority. * * @param xTicksToWait The maximum amount of time that the task should wait - * for the event to occur. This is specified in kernel ticks,the constant + * for the event to occur. This is specified in kernel ticks, the constant * portTICK_PERIOD_MS can be used to convert kernel ticks into a real time * period. */ @@ -2930,7 +3569,11 @@ void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, * Sets the pointer to the current TCB to the TCB of the highest priority task * that is ready to run. */ -portDONT_DISCARD void vTaskSwitchContext( void ) PRIVILEGED_FUNCTION; +#if ( configNUMBER_OF_CORES == 1 ) + portDONT_DISCARD void vTaskSwitchContext( void ) PRIVILEGED_FUNCTION; +#else + portDONT_DISCARD void vTaskSwitchContext( BaseType_t xCoreID ) PRIVILEGED_FUNCTION; +#endif /* * THESE FUNCTIONS MUST NOT BE USED FROM APPLICATION CODE. THEY ARE USED BY @@ -2943,6 +3586,11 @@ TickType_t uxTaskResetEventItemValue( void ) PRIVILEGED_FUNCTION; */ TaskHandle_t xTaskGetCurrentTaskHandle( void ) PRIVILEGED_FUNCTION; +/* + * Return the handle of the task running on specified core. + */ +TaskHandle_t xTaskGetCurrentTaskHandleForCore( BaseType_t xCoreID ) PRIVILEGED_FUNCTION; + /* * Shortcut used by the queue implementation to prevent unnecessary call to * taskYIELD(); @@ -2979,16 +3627,20 @@ void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask ) PRIVILEGED_FUNCTION; /* - * Get the uxTCBNumber assigned to the task referenced by the xTask parameter. + * Get the uxTaskNumber assigned to the task referenced by the xTask parameter. */ -UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +#endif /* * Set the uxTaskNumber of the task referenced by the xTask parameter to * uxHandle. */ -void vTaskSetTaskNumber( TaskHandle_t xTask, - const UBaseType_t uxHandle ) PRIVILEGED_FUNCTION; +#if ( configUSE_TRACE_FACILITY == 1 ) + void vTaskSetTaskNumber( TaskHandle_t xTask, + const UBaseType_t uxHandle ) PRIVILEGED_FUNCTION; +#endif /* * Only available when configUSE_TICKLESS_IDLE is set to 1. @@ -2998,7 +3650,9 @@ void vTaskSetTaskNumber( TaskHandle_t xTask, * to date with the actual execution time by being skipped forward by a time * equal to the idle period. */ -void vTaskStepTick( const TickType_t xTicksToJump ) PRIVILEGED_FUNCTION; +#if ( configUSE_TICKLESS_IDLE != 0 ) + void vTaskStepTick( TickType_t xTicksToJump ) PRIVILEGED_FUNCTION; +#endif /* * Only available when configUSE_TICKLESS_IDLE is set to 1. @@ -3014,7 +3668,9 @@ void vTaskStepTick( const TickType_t xTicksToJump ) PRIVILEGED_FUNCTION; * critical section between the timer being stopped and the sleep mode being * entered to ensure it is ok to proceed into the sleep mode. */ -eSleepModeStatus eTaskConfirmSleepModeStatus( void ) PRIVILEGED_FUNCTION; +#if ( configUSE_TICKLESS_IDLE != 0 ) + eSleepModeStatus eTaskConfirmSleepModeStatus( void ) PRIVILEGED_FUNCTION; +#endif /* * For internal use only. Increment the mutex held count when a mutex is @@ -3028,6 +3684,87 @@ TaskHandle_t pvTaskIncrementMutexHeldCount( void ) PRIVILEGED_FUNCTION; */ void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; +/* + * For internal use only. Same as portYIELD_WITHIN_API() in single core FreeRTOS. + * For SMP this is not defined by the port. + */ +#if ( configNUMBER_OF_CORES > 1 ) + void vTaskYieldWithinAPI( void ); +#endif + +/* + * This function is only intended for use when implementing a port of the scheduler + * and is only available when portCRITICAL_NESTING_IN_TCB is set to 1 or configNUMBER_OF_CORES + * is greater than 1. This function can be used in the implementation of portENTER_CRITICAL + * if port wants to maintain critical nesting count in TCB in single core FreeRTOS. + * It should be used in the implementation of portENTER_CRITICAL if port is running a + * multiple core FreeRTOS. + */ +#if ( ( portCRITICAL_NESTING_IN_TCB == 1 ) || ( configNUMBER_OF_CORES > 1 ) ) + void vTaskEnterCritical( void ); +#endif + +/* + * This function is only intended for use when implementing a port of the scheduler + * and is only available when portCRITICAL_NESTING_IN_TCB is set to 1 or configNUMBER_OF_CORES + * is greater than 1. This function can be used in the implementation of portEXIT_CRITICAL + * if port wants to maintain critical nesting count in TCB in single core FreeRTOS. + * It should be used in the implementation of portEXIT_CRITICAL if port is running a + * multiple core FreeRTOS. + */ +#if ( ( portCRITICAL_NESTING_IN_TCB == 1 ) || ( configNUMBER_OF_CORES > 1 ) ) + void vTaskExitCritical( void ); +#endif + +/* + * This function is only intended for use when implementing a port of the scheduler + * and is only available when configNUMBER_OF_CORES is greater than 1. This function + * should be used in the implementation of portENTER_CRITICAL_FROM_ISR if port is + * running a multiple core FreeRTOS. + */ +#if ( configNUMBER_OF_CORES > 1 ) + UBaseType_t vTaskEnterCriticalFromISR( void ); +#endif + +/* + * This function is only intended for use when implementing a port of the scheduler + * and is only available when configNUMBER_OF_CORES is greater than 1. This function + * should be used in the implementation of portEXIT_CRITICAL_FROM_ISR if port is + * running a multiple core FreeRTOS. + */ +#if ( configNUMBER_OF_CORES > 1 ) + void vTaskExitCriticalFromISR( UBaseType_t uxSavedInterruptStatus ); +#endif + +#if ( portUSING_MPU_WRAPPERS == 1 ) + +/* + * For internal use only. Get MPU settings associated with a task. + */ + xMPU_SETTINGS * xTaskGetMPUSettings( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +#endif /* portUSING_MPU_WRAPPERS */ + + +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) && ( configENABLE_ACCESS_CONTROL_LIST == 1 ) ) + +/* + * For internal use only. Grant/Revoke a task's access to a kernel object. + */ + void vGrantAccessToKernelObject( TaskHandle_t xExternalTaskHandle, + int32_t lExternalKernelObjectHandle ) PRIVILEGED_FUNCTION; + void vRevokeAccessToKernelObject( TaskHandle_t xExternalTaskHandle, + int32_t lExternalKernelObjectHandle ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Grant/Revoke a task's access to a kernel object. + */ + void vPortGrantAccessToKernelObject( TaskHandle_t xInternalTaskHandle, + int32_t lInternalIndexOfKernelObject ) PRIVILEGED_FUNCTION; + void vPortRevokeAccessToKernelObject( TaskHandle_t xInternalTaskHandle, + int32_t lInternalIndexOfKernelObject ) PRIVILEGED_FUNCTION; + +#endif /* #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) && ( configENABLE_ACCESS_CONTROL_LIST == 1 ) ) */ /* *INDENT-OFF* */ #ifdef __cplusplus diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/include/timers.h b/source/Middlewares/Third_Party/FreeRTOS/Source/include/timers.h index ba5c41326..e12a424e8 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/include/timers.h +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/include/timers.h @@ -1,6 +1,8 @@ /* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in @@ -32,10 +34,8 @@ #error "include FreeRTOS.h must appear in source files before include timers.h" #endif -/*lint -save -e537 This headers are only multiply included if the application code - * happens to also be including task.h. */ #include "task.h" -/*lint -restore */ + /* *INDENT-OFF* */ #ifdef __cplusplus @@ -86,13 +86,13 @@ typedef void (* TimerCallbackFunction_t)( TimerHandle_t xTimer ); * Defines the prototype to which functions used with the * xTimerPendFunctionCallFromISR() function must conform. */ -typedef void (* PendedFunction_t)( void *, - uint32_t ); +typedef void (* PendedFunction_t)( void * arg1, + uint32_t arg2 ); /** * TimerHandle_t xTimerCreate( const char * const pcTimerName, * TickType_t xTimerPeriodInTicks, - * UBaseType_t uxAutoReload, + * BaseType_t xAutoReload, * void * pvTimerID, * TimerCallbackFunction_t pxCallbackFunction ); * @@ -125,9 +125,9 @@ typedef void (* PendedFunction_t)( void *, * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or * equal to 1000. Time timer period must be greater than 0. * - * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * @param xAutoReload If xAutoReload is set to pdTRUE then the timer will * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. - * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and * enter the dormant state after it expires. * * @param pvTimerID An identifier that is assigned to the timer being created. @@ -190,11 +190,11 @@ typedef void (* PendedFunction_t)( void *, * // the scheduler starts. * for( x = 0; x < NUM_TIMERS; x++ ) * { - * xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. - * ( 100 * x ), // The timer period in ticks. - * pdTRUE, // The timers will auto-reload themselves when they expire. - * ( void * ) x, // Assign each timer a unique id equal to its array index. - * vTimerCallback // Each timer calls the same callback when it expires. + * xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. + * ( 100 * ( x + 1 ) ), // The timer period in ticks. + * pdTRUE, // The timers will auto-reload themselves when they expire. + * ( void * ) x, // Assign each timer a unique id equal to its array index. + * vTimerCallback // Each timer calls the same callback when it expires. * ); * * if( xTimers[ x ] == NULL ) @@ -227,9 +227,9 @@ typedef void (* PendedFunction_t)( void *, * @endverbatim */ #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + TimerHandle_t xTimerCreate( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, + const BaseType_t xAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; #endif @@ -237,7 +237,7 @@ typedef void (* PendedFunction_t)( void *, /** * TimerHandle_t xTimerCreateStatic(const char * const pcTimerName, * TickType_t xTimerPeriodInTicks, - * UBaseType_t uxAutoReload, + * BaseType_t xAutoReload, * void * pvTimerID, * TimerCallbackFunction_t pxCallbackFunction, * StaticTimer_t *pxTimerBuffer ); @@ -271,9 +271,9 @@ typedef void (* PendedFunction_t)( void *, * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or * equal to 1000. The timer period must be greater than 0. * - * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * @param xAutoReload If xAutoReload is set to pdTRUE then the timer will * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. - * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and * enter the dormant state after it expires. * * @param pvTimerID An identifier that is assigned to the timer being created. @@ -357,9 +357,9 @@ typedef void (* PendedFunction_t)( void *, * @endverbatim */ #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, + const BaseType_t xAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, StaticTimer_t * pxTimerBuffer ) PRIVILEGED_FUNCTION; @@ -1196,10 +1196,12 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; * } * @endverbatim */ -BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, - void * pvParameter1, - uint32_t ulParameter2, - BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +#if ( INCLUDE_xTimerPendFunctionCall == 1 ) + BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +#endif /** * BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, @@ -1233,10 +1235,12 @@ BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, * timer daemon task, otherwise pdFALSE is returned. * */ -BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, - void * pvParameter1, - uint32_t ulParameter2, - TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +#if ( INCLUDE_xTimerPendFunctionCall == 1 ) + BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +#endif /** * const char * const pcTimerGetName( TimerHandle_t xTimer ); @@ -1247,10 +1251,10 @@ BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, * * @return The name assigned to the timer specified by the xTimer parameter. */ -const char * pcTimerGetName( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +const char * pcTimerGetName( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; /** - * void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ); + * void vTimerSetReloadMode( TimerHandle_t xTimer, const BaseType_t xAutoReload ); * * Updates a timer to be either an auto-reload timer, in which case the timer * automatically resets itself each time it expires, or a one-shot timer, in @@ -1258,14 +1262,28 @@ const char * pcTimerGetName( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; /*lint * * @param xTimer The handle of the timer being updated. * - * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * @param xAutoReload If xAutoReload is set to pdTRUE then the timer will * expire repeatedly with a frequency set by the timer's period (see the * xTimerPeriodInTicks parameter of the xTimerCreate() API function). If - * uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * xAutoReload is set to pdFALSE then the timer will be a one-shot timer and * enter the dormant state after it expires. */ void vTimerSetReloadMode( TimerHandle_t xTimer, - const UBaseType_t uxAutoReload ) PRIVILEGED_FUNCTION; + const BaseType_t xAutoReload ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerGetReloadMode( TimerHandle_t xTimer ); + * + * Queries a timer to determine if it is an auto-reload timer, in which case the timer + * automatically resets itself each time it expires, or a one-shot timer, in + * which case the timer will only expire once unless it is manually restarted. + * + * @param xTimer The handle of the timer being queried. + * + * @return If the timer is an auto-reload timer then pdTRUE is returned, otherwise + * pdFALSE is returned. + */ +BaseType_t xTimerGetReloadMode( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; /** * UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ); @@ -1307,17 +1325,54 @@ TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; */ TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; +/** + * BaseType_t xTimerGetStaticBuffer( TimerHandle_t xTimer, + * StaticTimer_t ** ppxTimerBuffer ); + * + * Retrieve pointer to a statically created timer's data structure + * buffer. This is the same buffer that is supplied at the time of + * creation. + * + * @param xTimer The timer for which to retrieve the buffer. + * + * @param ppxTaskBuffer Used to return a pointer to the timers's data + * structure buffer. + * + * @return pdTRUE if the buffer was retrieved, pdFALSE otherwise. + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + BaseType_t xTimerGetStaticBuffer( TimerHandle_t xTimer, + StaticTimer_t ** ppxTimerBuffer ) PRIVILEGED_FUNCTION; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + /* * Functions beyond this part are not part of the public API and are intended * for use by the kernel only. */ BaseType_t xTimerCreateTimerTask( void ) PRIVILEGED_FUNCTION; -BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, - const BaseType_t xCommandID, - const TickType_t xOptionalValue, - BaseType_t * const pxHigherPriorityTaskWoken, - const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +/* + * Splitting the xTimerGenericCommand into two sub functions and making it a macro + * removes a recursion path when called from ISRs. This is primarily for the XCore + * XCC port which detects the recursion path and throws an error during compilation + * when this is not split. + */ +BaseType_t xTimerGenericCommandFromTask( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +BaseType_t xTimerGenericCommandFromISR( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +#define xTimerGenericCommand( xTimer, xCommandID, xOptionalValue, pxHigherPriorityTaskWoken, xTicksToWait ) \ + ( ( xCommandID ) < tmrFIRST_FROM_ISR_COMMAND ? \ + xTimerGenericCommandFromTask( xTimer, xCommandID, xOptionalValue, pxHigherPriorityTaskWoken, xTicksToWait ) : \ + xTimerGenericCommandFromISR( xTimer, xCommandID, xOptionalValue, pxHigherPriorityTaskWoken, xTicksToWait ) ) #if ( configUSE_TRACE_FACILITY == 1 ) void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) PRIVILEGED_FUNCTION; @@ -1326,23 +1381,48 @@ BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - /** - * task.h - *
void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer, StackType_t ** ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ) 
- * - * This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Timer Task TCB. This function is required when - * configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION - * - * @param ppxTimerTaskTCBBuffer A handle to a statically allocated TCB buffer - * @param ppxTimerTaskStackBuffer A handle to a statically allocated Stack buffer for thie idle task - * @param pulTimerTaskStackSize A pointer to the number of elements that will fit in the allocated stack buffer - */ +/** + * task.h + * @code{c} + * void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer, StackType_t ** ppxTimerTaskStackBuffer, configSTACK_DEPTH_TYPE * puxTimerTaskStackSize ) + * @endcode + * + * This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Timer Task TCB. This function is required when + * configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION + * + * @param ppxTimerTaskTCBBuffer A handle to a statically allocated TCB buffer + * @param ppxTimerTaskStackBuffer A handle to a statically allocated Stack buffer for the idle task + * @param puxTimerTaskStackSize A pointer to the number of elements that will fit in the allocated stack buffer + */ void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer, - StackType_t ** ppxTimerTaskStackBuffer, - uint32_t * pulTimerTaskStackSize ); + StackType_t ** ppxTimerTaskStackBuffer, + configSTACK_DEPTH_TYPE * puxTimerTaskStackSize ); #endif +#if ( configUSE_DAEMON_TASK_STARTUP_HOOK != 0 ) + +/** + * timers.h + * @code{c} + * void vApplicationDaemonTaskStartupHook( void ); + * @endcode + * + * This hook function is called form the timer task once when the task starts running. + */ + /* MISRA Ref 8.6.1 [External linkage] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-86 */ + /* coverity[misra_c_2012_rule_8_6_violation] */ + void vApplicationDaemonTaskStartupHook( void ); + +#endif + +/* + * This function resets the internal state of the timer module. It must be called + * by the application before restarting the scheduler. + */ +void vTimerResetState( void ) PRIVILEGED_FUNCTION; + /* *INDENT-OFF* */ #ifdef __cplusplus } diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/list.c b/source/Middlewares/Third_Party/FreeRTOS/Source/list.c index 5d1dc9e79..622710644 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/list.c +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/list.c @@ -1,210 +1,246 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - - -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining - * all the API functions to use the MPU wrappers. That should only be done when - * task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -#include "FreeRTOS.h" -#include "list.h" - -/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified - * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be - * defined for the header files above, but not in this file, in order to - * generate the correct privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ - -/*----------------------------------------------------------- -* PUBLIC LIST API documented in list.h -*----------------------------------------------------------*/ - -void vListInitialise( List_t * const pxList ) -{ - /* The list structure contains a list item which is used to mark the - * end of the list. To initialise the list the list end is inserted - * as the only list entry. */ - pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - - /* The list end value is the highest possible value in the list to - * ensure it remains at the end of the list. */ - pxList->xListEnd.xItemValue = portMAX_DELAY; - - /* The list end next and previous pointers point to itself so we know - * when the list is empty. */ - pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - - pxList->uxNumberOfItems = ( UBaseType_t ) 0U; - - /* Write known values into the list if - * configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); - listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); -} -/*-----------------------------------------------------------*/ - -void vListInitialiseItem( ListItem_t * const pxItem ) -{ - /* Make sure the list item is not recorded as being on a list. */ - pxItem->pxContainer = NULL; - - /* Write known values into the list item if - * configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); - listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); -} -/*-----------------------------------------------------------*/ - -void vListInsertEnd( List_t * const pxList, - ListItem_t * const pxNewListItem ) -{ - ListItem_t * const pxIndex = pxList->pxIndex; - - /* Only effective when configASSERT() is also defined, these tests may catch - * the list data structures being overwritten in memory. They will not catch - * data errors caused by incorrect configuration or use of FreeRTOS. */ - listTEST_LIST_INTEGRITY( pxList ); - listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); - - /* Insert a new list item into pxList, but rather than sort the list, - * makes the new list item the last item to be removed by a call to - * listGET_OWNER_OF_NEXT_ENTRY(). */ - pxNewListItem->pxNext = pxIndex; - pxNewListItem->pxPrevious = pxIndex->pxPrevious; - - /* Only used during decision coverage testing. */ - mtCOVERAGE_TEST_DELAY(); - - pxIndex->pxPrevious->pxNext = pxNewListItem; - pxIndex->pxPrevious = pxNewListItem; - - /* Remember which list the item is in. */ - pxNewListItem->pxContainer = pxList; - - ( pxList->uxNumberOfItems )++; -} -/*-----------------------------------------------------------*/ - -void vListInsert( List_t * const pxList, - ListItem_t * const pxNewListItem ) -{ - ListItem_t * pxIterator; - const TickType_t xValueOfInsertion = pxNewListItem->xItemValue; - - /* Only effective when configASSERT() is also defined, these tests may catch - * the list data structures being overwritten in memory. They will not catch - * data errors caused by incorrect configuration or use of FreeRTOS. */ - listTEST_LIST_INTEGRITY( pxList ); - listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); - - /* Insert the new list item into the list, sorted in xItemValue order. - * - * If the list already contains a list item with the same item value then the - * new list item should be placed after it. This ensures that TCBs which are - * stored in ready lists (all of which have the same xItemValue value) get a - * share of the CPU. However, if the xItemValue is the same as the back marker - * the iteration loop below will not end. Therefore the value is checked - * first, and the algorithm slightly modified if necessary. */ - if( xValueOfInsertion == portMAX_DELAY ) - { - pxIterator = pxList->xListEnd.pxPrevious; - } - else - { - /* *** NOTE *********************************************************** - * If you find your application is crashing here then likely causes are - * listed below. In addition see https://www.FreeRTOS.org/FAQHelp.html for - * more tips, and ensure configASSERT() is defined! - * https://www.FreeRTOS.org/a00110.html#configASSERT - * - * 1) Stack overflow - - * see https://www.FreeRTOS.org/Stacks-and-stack-overflow-checking.html - * 2) Incorrect interrupt priority assignment, especially on Cortex-M - * parts where numerically high priority values denote low actual - * interrupt priorities, which can seem counter intuitive. See - * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html and the definition - * of configMAX_SYSCALL_INTERRUPT_PRIORITY on - * https://www.FreeRTOS.org/a00110.html - * 3) Calling an API function from within a critical section or when - * the scheduler is suspended, or calling an API function that does - * not end in "FromISR" from an interrupt. - * 4) Using a queue or semaphore before it has been initialised or - * before the scheduler has been started (are interrupts firing - * before vTaskStartScheduler() has been called?). - **********************************************************************/ - - for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. *//*lint !e440 The iterator moves to a different value, not xValueOfInsertion. */ - { - /* There is nothing to do here, just iterating to the wanted - * insertion position. */ - } - } - - pxNewListItem->pxNext = pxIterator->pxNext; - pxNewListItem->pxNext->pxPrevious = pxNewListItem; - pxNewListItem->pxPrevious = pxIterator; - pxIterator->pxNext = pxNewListItem; - - /* Remember which list the item is in. This allows fast removal of the - * item later. */ - pxNewListItem->pxContainer = pxList; - - ( pxList->uxNumberOfItems )++; -} -/*-----------------------------------------------------------*/ - -UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) -{ -/* The list item knows which list it is in. Obtain the list from the list - * item. */ - List_t * const pxList = pxItemToRemove->pxContainer; - - pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; - pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; - - /* Only used during decision coverage testing. */ - mtCOVERAGE_TEST_DELAY(); - - /* Make sure the index is left pointing to a valid item. */ - if( pxList->pxIndex == pxItemToRemove ) - { - pxList->pxIndex = pxItemToRemove->pxPrevious; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - pxItemToRemove->pxContainer = NULL; - ( pxList->uxNumberOfItems )--; - - return pxList->uxNumberOfItems; -} -/*-----------------------------------------------------------*/ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "list.h" + +/* The MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be + * defined for the header files above, but not in this file, in order to + * generate the correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/*----------------------------------------------------------- +* PUBLIC LIST API documented in list.h +*----------------------------------------------------------*/ + +void vListInitialise( List_t * const pxList ) +{ + traceENTER_vListInitialise( pxList ); + + /* The list structure contains a list item which is used to mark the + * end of the list. To initialise the list the list end is inserted + * as the only list entry. */ + pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); + + listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( &( pxList->xListEnd ) ); + + /* The list end value is the highest possible value in the list to + * ensure it remains at the end of the list. */ + pxList->xListEnd.xItemValue = portMAX_DELAY; + + /* The list end next and previous pointers point to itself so we know + * when the list is empty. */ + pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); + pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd ); + + /* Initialize the remaining fields of xListEnd when it is a proper ListItem_t */ + #if ( configUSE_MINI_LIST_ITEM == 0 ) + { + pxList->xListEnd.pvOwner = NULL; + pxList->xListEnd.pxContainer = NULL; + listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( &( pxList->xListEnd ) ); + } + #endif + + pxList->uxNumberOfItems = ( UBaseType_t ) 0U; + + /* Write known values into the list if + * configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); + listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); + + traceRETURN_vListInitialise(); +} +/*-----------------------------------------------------------*/ + +void vListInitialiseItem( ListItem_t * const pxItem ) +{ + traceENTER_vListInitialiseItem( pxItem ); + + /* Make sure the list item is not recorded as being on a list. */ + pxItem->pxContainer = NULL; + + /* Write known values into the list item if + * configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); + listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); + + traceRETURN_vListInitialiseItem(); +} +/*-----------------------------------------------------------*/ + +void vListInsertEnd( List_t * const pxList, + ListItem_t * const pxNewListItem ) +{ + ListItem_t * const pxIndex = pxList->pxIndex; + + traceENTER_vListInsertEnd( pxList, pxNewListItem ); + + /* Only effective when configASSERT() is also defined, these tests may catch + * the list data structures being overwritten in memory. They will not catch + * data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + + /* Insert a new list item into pxList, but rather than sort the list, + * makes the new list item the last item to be removed by a call to + * listGET_OWNER_OF_NEXT_ENTRY(). */ + pxNewListItem->pxNext = pxIndex; + pxNewListItem->pxPrevious = pxIndex->pxPrevious; + + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); + + pxIndex->pxPrevious->pxNext = pxNewListItem; + pxIndex->pxPrevious = pxNewListItem; + + /* Remember which list the item is in. */ + pxNewListItem->pxContainer = pxList; + + ( pxList->uxNumberOfItems ) = ( UBaseType_t ) ( pxList->uxNumberOfItems + 1U ); + + traceRETURN_vListInsertEnd(); +} +/*-----------------------------------------------------------*/ + +void vListInsert( List_t * const pxList, + ListItem_t * const pxNewListItem ) +{ + ListItem_t * pxIterator; + const TickType_t xValueOfInsertion = pxNewListItem->xItemValue; + + traceENTER_vListInsert( pxList, pxNewListItem ); + + /* Only effective when configASSERT() is also defined, these tests may catch + * the list data structures being overwritten in memory. They will not catch + * data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + + /* Insert the new list item into the list, sorted in xItemValue order. + * + * If the list already contains a list item with the same item value then the + * new list item should be placed after it. This ensures that TCBs which are + * stored in ready lists (all of which have the same xItemValue value) get a + * share of the CPU. However, if the xItemValue is the same as the back marker + * the iteration loop below will not end. Therefore the value is checked + * first, and the algorithm slightly modified if necessary. */ + if( xValueOfInsertion == portMAX_DELAY ) + { + pxIterator = pxList->xListEnd.pxPrevious; + } + else + { + /* *** NOTE *********************************************************** + * If you find your application is crashing here then likely causes are + * listed below. In addition see https://www.FreeRTOS.org/FAQHelp.html for + * more tips, and ensure configASSERT() is defined! + * https://www.FreeRTOS.org/a00110.html#configASSERT + * + * 1) Stack overflow - + * see https://www.FreeRTOS.org/Stacks-and-stack-overflow-checking.html + * 2) Incorrect interrupt priority assignment, especially on Cortex-M + * parts where numerically high priority values denote low actual + * interrupt priorities, which can seem counter intuitive. See + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html and the definition + * of configMAX_SYSCALL_INTERRUPT_PRIORITY on + * https://www.FreeRTOS.org/a00110.html + * 3) Calling an API function from within a critical section or when + * the scheduler is suspended, or calling an API function that does + * not end in "FromISR" from an interrupt. + * 4) Using a queue or semaphore before it has been initialised or + * before the scheduler has been started (are interrupts firing + * before vTaskStartScheduler() has been called?). + * 5) If the FreeRTOS port supports interrupt nesting then ensure that + * the priority of the tick interrupt is at or below + * configMAX_SYSCALL_INTERRUPT_PRIORITY. + **********************************************************************/ + + for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) + { + /* There is nothing to do here, just iterating to the wanted + * insertion position. */ + } + } + + pxNewListItem->pxNext = pxIterator->pxNext; + pxNewListItem->pxNext->pxPrevious = pxNewListItem; + pxNewListItem->pxPrevious = pxIterator; + pxIterator->pxNext = pxNewListItem; + + /* Remember which list the item is in. This allows fast removal of the + * item later. */ + pxNewListItem->pxContainer = pxList; + + ( pxList->uxNumberOfItems ) = ( UBaseType_t ) ( pxList->uxNumberOfItems + 1U ); + + traceRETURN_vListInsert(); +} +/*-----------------------------------------------------------*/ + + +UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) +{ + /* The list item knows which list it is in. Obtain the list from the list + * item. */ + List_t * const pxList = pxItemToRemove->pxContainer; + + traceENTER_uxListRemove( pxItemToRemove ); + + pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; + pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; + + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); + + /* Make sure the index is left pointing to a valid item. */ + if( pxList->pxIndex == pxItemToRemove ) + { + pxList->pxIndex = pxItemToRemove->pxPrevious; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxItemToRemove->pxContainer = NULL; + ( pxList->uxNumberOfItems ) = ( UBaseType_t ) ( pxList->uxNumberOfItems - 1U ); + + traceRETURN_uxListRemove( pxList->uxNumberOfItems ); + + return pxList->uxNumberOfItems; +} +/*-----------------------------------------------------------*/ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/queue.c b/source/Middlewares/Third_Party/FreeRTOS/Source/queue.c index 5c9002dc9..f91841f96 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/queue.c +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/queue.c @@ -1,3013 +1,3364 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -#include -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining - * all the API functions to use the MPU wrappers. That should only be done when - * task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -#include "FreeRTOS.h" -#include "task.h" -#include "queue.h" - -#if ( configUSE_CO_ROUTINES == 1 ) - #include "croutine.h" -#endif - -/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified - * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined - * for the header files above, but not in this file, in order to generate the - * correct privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ - - -/* Constants used with the cRxLock and cTxLock structure members. */ -#define queueUNLOCKED ( ( int8_t ) -1 ) -#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) -#define queueINT8_MAX ( ( int8_t ) 127 ) - -/* When the Queue_t structure is used to represent a base queue its pcHead and - * pcTail members are used as pointers into the queue storage area. When the - * Queue_t structure is used to represent a mutex pcHead and pcTail pointers are - * not necessary, and the pcHead pointer is set to NULL to indicate that the - * structure instead holds a pointer to the mutex holder (if any). Map alternative - * names to the pcHead and structure member to ensure the readability of the code - * is maintained. The QueuePointers_t and SemaphoreData_t types are used to form - * a union as their usage is mutually exclusive dependent on what the queue is - * being used for. */ -#define uxQueueType pcHead -#define queueQUEUE_IS_MUTEX NULL - -typedef struct QueuePointers -{ - int8_t * pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ - int8_t * pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */ -} QueuePointers_t; - -typedef struct SemaphoreData -{ - TaskHandle_t xMutexHolder; /*< The handle of the task that holds the mutex. */ - UBaseType_t uxRecursiveCallCount; /*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ -} SemaphoreData_t; - -/* Semaphores do not actually store or copy data, so have an item size of - * zero. */ -#define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( UBaseType_t ) 0 ) -#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U ) - -#if ( configUSE_PREEMPTION == 0 ) - -/* If the cooperative scheduler is being used then a yield should not be - * performed just because a higher priority task has been woken. */ - #define queueYIELD_IF_USING_PREEMPTION() -#else - #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() -#endif - -/* - * Definition of the queue used by the scheduler. - * Items are queued by copy, not reference. See the following link for the - * rationale: https://www.FreeRTOS.org/Embedded-RTOS-Queues.html - */ -typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */ -{ - int8_t * pcHead; /*< Points to the beginning of the queue storage area. */ - int8_t * pcWriteTo; /*< Points to the free next place in the storage area. */ - - union - { - QueuePointers_t xQueue; /*< Data required exclusively when this structure is used as a queue. */ - SemaphoreData_t xSemaphore; /*< Data required exclusively when this structure is used as a semaphore. */ - } u; - - List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ - List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ - - volatile UBaseType_t uxMessagesWaiting; /*< The number of items currently in the queue. */ - UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ - UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */ - - volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ - volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ - - #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ - #endif - - #if ( configUSE_QUEUE_SETS == 1 ) - struct QueueDefinition * pxQueueSetContainer; - #endif - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxQueueNumber; - uint8_t ucQueueType; - #endif -} xQUEUE; - -/* The old xQUEUE name is maintained above then typedefed to the new Queue_t - * name below to enable the use of older kernel aware debuggers. */ -typedef xQUEUE Queue_t; - -/*-----------------------------------------------------------*/ - -/* - * The queue registry is just a means for kernel aware debuggers to locate - * queue structures. It has no other purpose so is an optional component. - */ -#if ( configQUEUE_REGISTRY_SIZE > 0 ) - -/* The type stored within the queue registry array. This allows a name - * to be assigned to each queue making kernel aware debugging a little - * more user friendly. */ - typedef struct QUEUE_REGISTRY_ITEM - { - const char * pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - QueueHandle_t xHandle; - } xQueueRegistryItem; - -/* The old xQueueRegistryItem name is maintained above then typedefed to the - * new xQueueRegistryItem name below to enable the use of older kernel aware - * debuggers. */ - typedef xQueueRegistryItem QueueRegistryItem_t; - -/* The queue registry is simply an array of QueueRegistryItem_t structures. - * The pcQueueName member of a structure being NULL is indicative of the - * array position being vacant. */ - PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; - -#endif /* configQUEUE_REGISTRY_SIZE */ - -/* - * Unlocks a queue locked by a call to prvLockQueue. Locking a queue does not - * prevent an ISR from adding or removing items to the queue, but does prevent - * an ISR from removing tasks from the queue event lists. If an ISR finds a - * queue is locked it will instead increment the appropriate queue lock count - * to indicate that a task may require unblocking. When the queue in unlocked - * these lock counts are inspected, and the appropriate action taken. - */ -static void prvUnlockQueue( Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; - -/* - * Uses a critical section to determine if there is any data in a queue. - * - * @return pdTRUE if the queue contains no items, otherwise pdFALSE. - */ -static BaseType_t prvIsQueueEmpty( const Queue_t * pxQueue ) PRIVILEGED_FUNCTION; - -/* - * Uses a critical section to determine if there is any space in a queue. - * - * @return pdTRUE if there is no space, otherwise pdFALSE; - */ -static BaseType_t prvIsQueueFull( const Queue_t * pxQueue ) PRIVILEGED_FUNCTION; - -/* - * Copies an item into the queue, either at the front of the queue or the - * back of the queue. - */ -static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, - const void * pvItemToQueue, - const BaseType_t xPosition ) PRIVILEGED_FUNCTION; - -/* - * Copies an item out of a queue. - */ -static void prvCopyDataFromQueue( Queue_t * const pxQueue, - void * const pvBuffer ) PRIVILEGED_FUNCTION; - -#if ( configUSE_QUEUE_SETS == 1 ) - -/* - * Checks to see if a queue is a member of a queue set, and if so, notifies - * the queue set that the queue contains data. - */ - static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; -#endif - -/* - * Called after a Queue_t structure has been allocated either statically or - * dynamically to fill in the structure's members. - */ -static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, - const UBaseType_t uxItemSize, - uint8_t * pucQueueStorage, - const uint8_t ucQueueType, - Queue_t * pxNewQueue ) PRIVILEGED_FUNCTION; - -/* - * Mutexes are a special type of queue. When a mutex is created, first the - * queue is created, then prvInitialiseMutex() is called to configure the queue - * as a mutex. - */ -#if ( configUSE_MUTEXES == 1 ) - static void prvInitialiseMutex( Queue_t * pxNewQueue ) PRIVILEGED_FUNCTION; -#endif - -#if ( configUSE_MUTEXES == 1 ) - -/* - * If a task waiting for a mutex causes the mutex holder to inherit a - * priority, but the waiting task times out, then the holder should - * disinherit the priority - but only down to the highest priority of any - * other tasks that are waiting for the same mutex. This function returns - * that priority. - */ - static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; -#endif -/*-----------------------------------------------------------*/ - -/* - * Macro to mark a queue as locked. Locking a queue prevents an ISR from - * accessing the queue event lists. - */ -#define prvLockQueue( pxQueue ) \ - taskENTER_CRITICAL(); \ - { \ - if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ - { \ - ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ - } \ - if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ - { \ - ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ - } \ - } \ - taskEXIT_CRITICAL() -/*-----------------------------------------------------------*/ - -BaseType_t xQueueGenericReset( QueueHandle_t xQueue, - BaseType_t xNewQueue ) -{ - Queue_t * const pxQueue = xQueue; - - configASSERT( pxQueue ); - - taskENTER_CRITICAL(); - { - pxQueue->u.xQueue.pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ - pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U; - pxQueue->pcWriteTo = pxQueue->pcHead; - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - 1U ) * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ - pxQueue->cRxLock = queueUNLOCKED; - pxQueue->cTxLock = queueUNLOCKED; - - if( xNewQueue == pdFALSE ) - { - /* If there are tasks blocked waiting to read from the queue, then - * the tasks will remain blocked as after this function exits the queue - * will still be empty. If there are tasks blocked waiting to write to - * the queue, then one should be unblocked as after this function exits - * it will be possible to write to it. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Ensure the event queues start in the correct state. */ - vListInitialise( &( pxQueue->xTasksWaitingToSend ) ); - vListInitialise( &( pxQueue->xTasksWaitingToReceive ) ); - } - } - taskEXIT_CRITICAL(); - - /* A value is returned for calling semantic consistency with previous - * versions. */ - return pdPASS; -} -/*-----------------------------------------------------------*/ - -#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - - QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, - const UBaseType_t uxItemSize, - uint8_t * pucQueueStorage, - StaticQueue_t * pxStaticQueue, - const uint8_t ucQueueType ) - { - Queue_t * pxNewQueue; - - configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); - - /* The StaticQueue_t structure and the queue storage area must be - * supplied. */ - configASSERT( pxStaticQueue != NULL ); - - /* A queue storage area should be provided if the item size is not 0, and - * should not be provided if the item size is 0. */ - configASSERT( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) ); - configASSERT( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0 ) ) ); - - #if ( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - * variable of type StaticQueue_t or StaticSemaphore_t equals the size of - * the real queue and semaphore structures. */ - volatile size_t xSize = sizeof( StaticQueue_t ); - configASSERT( xSize == sizeof( Queue_t ) ); - ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ - } - #endif /* configASSERT_DEFINED */ - - /* The address of a statically allocated queue was passed in, use it. - * The address of a statically allocated storage area was also passed in - * but is already set. */ - pxNewQueue = ( Queue_t * ) pxStaticQueue; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ - - if( pxNewQueue != NULL ) - { - #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Queues can be allocated wither statically or dynamically, so - * note this queue was allocated statically in case the queue is - * later deleted. */ - pxNewQueue->ucStaticallyAllocated = pdTRUE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - - prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); - } - else - { - traceQUEUE_CREATE_FAILED( ucQueueType ); - mtCOVERAGE_TEST_MARKER(); - } - - return pxNewQueue; - } - -#endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - - QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, - const UBaseType_t uxItemSize, - const uint8_t ucQueueType ) - { - Queue_t * pxNewQueue; - size_t xQueueSizeInBytes; - uint8_t * pucQueueStorage; - - configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); - - /* Allocate enough space to hold the maximum number of items that - * can be in the queue at any time. It is valid for uxItemSize to be - * zero in the case the queue is used as a semaphore. */ - xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - /* Check for multiplication overflow. */ - configASSERT( ( uxItemSize == 0 ) || ( uxQueueLength == ( xQueueSizeInBytes / uxItemSize ) ) ); - - /* Allocate the queue and storage area. Justification for MISRA - * deviation as follows: pvPortMalloc() always ensures returned memory - * blocks are aligned per the requirements of the MCU stack. In this case - * pvPortMalloc() must return a pointer that is guaranteed to meet the - * alignment requirements of the Queue_t structure - which in this case - * is an int8_t *. Therefore, whenever the stack alignment requirements - * are greater than or equal to the pointer to char requirements the cast - * is safe. In other cases alignment requirements are not strict (one or - * two bytes). */ - pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */ - - if( pxNewQueue != NULL ) - { - /* Jump past the queue structure to find the location of the queue - * storage area. */ - pucQueueStorage = ( uint8_t * ) pxNewQueue; - pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ - - #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* Queues can be created either statically or dynamically, so - * note this task was created dynamically in case it is later - * deleted. */ - pxNewQueue->ucStaticallyAllocated = pdFALSE; - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - - prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); - } - else - { - traceQUEUE_CREATE_FAILED( ucQueueType ); - mtCOVERAGE_TEST_MARKER(); - } - - return pxNewQueue; - } - -#endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, - const UBaseType_t uxItemSize, - uint8_t * pucQueueStorage, - const uint8_t ucQueueType, - Queue_t * pxNewQueue ) -{ - /* Remove compiler warnings about unused parameters should - * configUSE_TRACE_FACILITY not be set to 1. */ - ( void ) ucQueueType; - - if( uxItemSize == ( UBaseType_t ) 0 ) - { - /* No RAM was allocated for the queue storage area, but PC head cannot - * be set to NULL because NULL is used as a key to say the queue is used as - * a mutex. Therefore just set pcHead to point to the queue as a benign - * value that is known to be within the memory map. */ - pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; - } - else - { - /* Set the head to the start of the queue storage area. */ - pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; - } - - /* Initialise the queue members as described where the queue type is - * defined. */ - pxNewQueue->uxLength = uxQueueLength; - pxNewQueue->uxItemSize = uxItemSize; - ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); - - #if ( configUSE_TRACE_FACILITY == 1 ) - { - pxNewQueue->ucQueueType = ucQueueType; - } - #endif /* configUSE_TRACE_FACILITY */ - - #if ( configUSE_QUEUE_SETS == 1 ) - { - pxNewQueue->pxQueueSetContainer = NULL; - } - #endif /* configUSE_QUEUE_SETS */ - - traceQUEUE_CREATE( pxNewQueue ); -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - static void prvInitialiseMutex( Queue_t * pxNewQueue ) - { - if( pxNewQueue != NULL ) - { - /* The queue create function will set all the queue structure members - * correctly for a generic queue, but this function is creating a - * mutex. Overwrite those members that need to be set differently - - * in particular the information required for priority inheritance. */ - pxNewQueue->u.xSemaphore.xMutexHolder = NULL; - pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; - - /* In case this is a recursive mutex. */ - pxNewQueue->u.xSemaphore.uxRecursiveCallCount = 0; - - traceCREATE_MUTEX( pxNewQueue ); - - /* Start with the semaphore in the expected state. */ - ( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK ); - } - else - { - traceCREATE_MUTEX_FAILED(); - } - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) - { - QueueHandle_t xNewQueue; - const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; - - xNewQueue = xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType ); - prvInitialiseMutex( ( Queue_t * ) xNewQueue ); - - return xNewQueue; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - - QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, - StaticQueue_t * pxStaticQueue ) - { - QueueHandle_t xNewQueue; - const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; - - /* Prevent compiler warnings about unused parameters if - * configUSE_TRACE_FACILITY does not equal 1. */ - ( void ) ucQueueType; - - xNewQueue = xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType ); - prvInitialiseMutex( ( Queue_t * ) xNewQueue ); - - return xNewQueue; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) - - TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) - { - TaskHandle_t pxReturn; - Queue_t * const pxSemaphore = ( Queue_t * ) xSemaphore; - - /* This function is called by xSemaphoreGetMutexHolder(), and should not - * be called directly. Note: This is a good way of determining if the - * calling task is the mutex holder, but not a good way of determining the - * identity of the mutex holder, as the holder may change between the - * following critical section exiting and the function returning. */ - taskENTER_CRITICAL(); - { - if( pxSemaphore->uxQueueType == queueQUEUE_IS_MUTEX ) - { - pxReturn = pxSemaphore->u.xSemaphore.xMutexHolder; - } - else - { - pxReturn = NULL; - } - } - taskEXIT_CRITICAL(); - - return pxReturn; - } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ - -#endif /* if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) - - TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) - { - TaskHandle_t pxReturn; - - configASSERT( xSemaphore ); - - /* Mutexes cannot be used in interrupt service routines, so the mutex - * holder should not change in an ISR, and therefore a critical section is - * not required here. */ - if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) - { - pxReturn = ( ( Queue_t * ) xSemaphore )->u.xSemaphore.xMutexHolder; - } - else - { - pxReturn = NULL; - } - - return pxReturn; - } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ - -#endif /* if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_RECURSIVE_MUTEXES == 1 ) - - BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) - { - BaseType_t xReturn; - Queue_t * const pxMutex = ( Queue_t * ) xMutex; - - configASSERT( pxMutex ); - - /* If this is the task that holds the mutex then xMutexHolder will not - * change outside of this task. If this task does not hold the mutex then - * pxMutexHolder can never coincidentally equal the tasks handle, and as - * this is the only condition we are interested in it does not matter if - * pxMutexHolder is accessed simultaneously by another task. Therefore no - * mutual exclusion is required to test the pxMutexHolder variable. */ - if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) - { - traceGIVE_MUTEX_RECURSIVE( pxMutex ); - - /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to - * the task handle, therefore no underflow check is required. Also, - * uxRecursiveCallCount is only modified by the mutex holder, and as - * there can only be one, no mutual exclusion is required to modify the - * uxRecursiveCallCount member. */ - ( pxMutex->u.xSemaphore.uxRecursiveCallCount )--; - - /* Has the recursive call count unwound to 0? */ - if( pxMutex->u.xSemaphore.uxRecursiveCallCount == ( UBaseType_t ) 0 ) - { - /* Return the mutex. This will automatically unblock any other - * task that might be waiting to access the mutex. */ - ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xReturn = pdPASS; - } - else - { - /* The mutex cannot be given because the calling task is not the - * holder. */ - xReturn = pdFAIL; - - traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); - } - - return xReturn; - } - -#endif /* configUSE_RECURSIVE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_RECURSIVE_MUTEXES == 1 ) - - BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, - TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxMutex = ( Queue_t * ) xMutex; - - configASSERT( pxMutex ); - - /* Comments regarding mutual exclusion as per those within - * xQueueGiveMutexRecursive(). */ - - traceTAKE_MUTEX_RECURSIVE( pxMutex ); - - if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) - { - ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; - xReturn = pdPASS; - } - else - { - xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait ); - - /* pdPASS will only be returned if the mutex was successfully - * obtained. The calling task may have entered the Blocked state - * before reaching here. */ - if( xReturn != pdFAIL ) - { - ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; - } - else - { - traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); - } - } - - return xReturn; - } - -#endif /* configUSE_RECURSIVE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - - QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, - const UBaseType_t uxInitialCount, - StaticQueue_t * pxStaticQueue ) - { - QueueHandle_t xHandle; - - configASSERT( uxMaxCount != 0 ); - configASSERT( uxInitialCount <= uxMaxCount ); - - xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); - - if( xHandle != NULL ) - { - ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; - - traceCREATE_COUNTING_SEMAPHORE(); - } - else - { - traceCREATE_COUNTING_SEMAPHORE_FAILED(); - } - - return xHandle; - } - -#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, - const UBaseType_t uxInitialCount ) - { - QueueHandle_t xHandle; - - configASSERT( uxMaxCount != 0 ); - configASSERT( uxInitialCount <= uxMaxCount ); - - xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); - - if( xHandle != NULL ) - { - ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; - - traceCREATE_COUNTING_SEMAPHORE(); - } - else - { - traceCREATE_COUNTING_SEMAPHORE_FAILED(); - } - - return xHandle; - } - -#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ -/*-----------------------------------------------------------*/ - -BaseType_t xQueueGenericSend( QueueHandle_t xQueue, - const void * const pvItemToQueue, - TickType_t xTicksToWait, - const BaseType_t xCopyPosition ) -{ - BaseType_t xEntryTimeSet = pdFALSE, xYieldRequired; - TimeOut_t xTimeOut; - Queue_t * const pxQueue = xQueue; - - configASSERT( pxQueue ); - configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - /*lint -save -e904 This function relaxes the coding standard somewhat to - * allow return statements within the function itself. This is done in the - * interest of execution time efficiency. */ - for( ; ; ) - { - taskENTER_CRITICAL(); - { - /* Is there room on the queue now? The running task must be the - * highest priority task wanting to access the queue. If the head item - * in the queue is to be overwritten then it does not matter if the - * queue is full. */ - if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) - { - traceQUEUE_SEND( pxQueue ); - - #if ( configUSE_QUEUE_SETS == 1 ) - { - const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; - - xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) - { - /* Do not notify the queue set as an existing item - * was overwritten in the queue so the number of items - * in the queue has not changed. */ - mtCOVERAGE_TEST_MARKER(); - } - else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting - * to the queue set caused a higher priority task to - * unblock. A context switch is required. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* If there was a task waiting for data to arrive on the - * queue then unblock it now. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The unblocked task has a priority higher than - * our own so yield immediately. Yes it is ok to - * do this from within the critical section - the - * kernel takes care of that. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xYieldRequired != pdFALSE ) - { - /* This path is a special case that will only get - * executed if the task was holding multiple mutexes - * and the mutexes were given back in an order that is - * different to that in which they were taken. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - - /* If there was a task waiting for data to arrive on the - * queue then unblock it now. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The unblocked task has a priority higher than - * our own so yield immediately. Yes it is ok to do - * this from within the critical section - the kernel - * takes care of that. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xYieldRequired != pdFALSE ) - { - /* This path is a special case that will only get - * executed if the task was holding multiple mutexes and - * the mutexes were given back in an order that is - * different to that in which they were taken. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ - - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was full and no block time is specified (or - * the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); - - /* Return to the original privilege level before exiting - * the function. */ - traceQUEUE_SEND_FAILED( pxQueue ); - return errQUEUE_FULL; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was full and a block time was specified so - * configure the timeout structure. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); - - /* Interrupts and other tasks can send to and receive from the queue - * now the critical section has been exited. */ - - vTaskSuspendAll(); - prvLockQueue( pxQueue ); - - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - if( prvIsQueueFull( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_SEND( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); - - /* Unlocking the queue means queue events can effect the - * event list. It is possible that interrupts occurring now - * remove this task from the event list again - but as the - * scheduler is suspended the task will go onto the pending - * ready last instead of the actual ready list. */ - prvUnlockQueue( pxQueue ); - - /* Resuming the scheduler will move tasks from the pending - * ready list into the ready list - so it is feasible that this - * task is already in a ready list before it yields - in which - * case the yield will not cause a context switch unless there - * is also a higher priority task in the pending ready list. */ - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - } - else - { - /* Try again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* The timeout has expired. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - - traceQUEUE_SEND_FAILED( pxQueue ); - return errQUEUE_FULL; - } - } /*lint -restore */ -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, - const void * const pvItemToQueue, - BaseType_t * const pxHigherPriorityTaskWoken, - const BaseType_t xCopyPosition ) -{ - BaseType_t xReturn; - UBaseType_t uxSavedInterruptStatus; - Queue_t * const pxQueue = xQueue; - - configASSERT( pxQueue ); - configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); - - /* RTOS ports that support interrupt nesting have the concept of a maximum - * system call (or maximum API call) interrupt priority. Interrupts that are - * above the maximum system call priority are kept permanently enabled, even - * when the RTOS kernel is in a critical section, but cannot make any calls to - * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - * failure if a FreeRTOS API function is called from an interrupt that has been - * assigned a priority above the configured maximum system call priority. - * Only FreeRTOS functions that end in FromISR can be called from interrupts - * that have been assigned a priority at or (logically) below the maximum - * system call interrupt priority. FreeRTOS maintains a separate interrupt - * safe API to ensure interrupt entry is as fast and as simple as possible. - * More information (albeit Cortex-M specific) is provided on the following - * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - /* Similar to xQueueGenericSend, except without blocking if there is no room - * in the queue. Also don't directly wake a task that was blocked on a queue - * read, instead return a flag to say whether a context switch is required or - * not (i.e. has a task with a higher priority than us been woken by this - * post). */ - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) - { - const int8_t cTxLock = pxQueue->cTxLock; - const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; - - traceQUEUE_SEND_FROM_ISR( pxQueue ); - - /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a - * semaphore or mutex. That means prvCopyDataToQueue() cannot result - * in a task disinheriting a priority and prvCopyDataToQueue() can be - * called here even though the disinherit function does not check if - * the scheduler is suspended before accessing the ready lists. */ - ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - - /* The event list is not altered if the queue is locked. This will - * be done when the queue is unlocked later. */ - if( cTxLock == queueUNLOCKED ) - { - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) - { - /* Do not notify the queue set as an existing item - * was overwritten in the queue so the number of items - * in the queue has not changed. */ - mtCOVERAGE_TEST_MARKER(); - } - else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting - * to the queue set caused a higher priority task to - * unblock. A context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so - * record that a context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - * context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Not used in this path. */ - ( void ) uxPreviousMessagesWaiting; - } - #endif /* configUSE_QUEUE_SETS */ - } - else - { - /* Increment the lock count so the task that unlocks the queue - * knows that data was posted while it was locked. */ - configASSERT( cTxLock != queueINT8_MAX ); - - pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } - - xReturn = pdPASS; - } - else - { - traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); - xReturn = errQUEUE_FULL; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, - BaseType_t * const pxHigherPriorityTaskWoken ) -{ - BaseType_t xReturn; - UBaseType_t uxSavedInterruptStatus; - Queue_t * const pxQueue = xQueue; - - /* Similar to xQueueGenericSendFromISR() but used with semaphores where the - * item size is 0. Don't directly wake a task that was blocked on a queue - * read, instead return a flag to say whether a context switch is required or - * not (i.e. has a task with a higher priority than us been woken by this - * post). */ - - configASSERT( pxQueue ); - - /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() - * if the item size is not 0. */ - configASSERT( pxQueue->uxItemSize == 0 ); - - /* Normally a mutex would not be given from an interrupt, especially if - * there is a mutex holder, as priority inheritance makes no sense for an - * interrupts, only tasks. */ - configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) ); - - /* RTOS ports that support interrupt nesting have the concept of a maximum - * system call (or maximum API call) interrupt priority. Interrupts that are - * above the maximum system call priority are kept permanently enabled, even - * when the RTOS kernel is in a critical section, but cannot make any calls to - * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - * failure if a FreeRTOS API function is called from an interrupt that has been - * assigned a priority above the configured maximum system call priority. - * Only FreeRTOS functions that end in FromISR can be called from interrupts - * that have been assigned a priority at or (logically) below the maximum - * system call interrupt priority. FreeRTOS maintains a separate interrupt - * safe API to ensure interrupt entry is as fast and as simple as possible. - * More information (albeit Cortex-M specific) is provided on the following - * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - - /* When the queue is used to implement a semaphore no data is ever - * moved through the queue but it is still valid to see if the queue 'has - * space'. */ - if( uxMessagesWaiting < pxQueue->uxLength ) - { - const int8_t cTxLock = pxQueue->cTxLock; - - traceQUEUE_SEND_FROM_ISR( pxQueue ); - - /* A task can only have an inherited priority if it is a mutex - * holder - and if there is a mutex holder then the mutex cannot be - * given from an ISR. As this is the ISR version of the function it - * can be assumed there is no mutex holder and no need to determine if - * priority disinheritance is needed. Simply increase the count of - * messages (semaphores) available. */ - pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; - - /* The event list is not altered if the queue is locked. This will - * be done when the queue is unlocked later. */ - if( cTxLock == queueUNLOCKED ) - { - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) - { - /* The semaphore is a member of a queue set, and - * posting to the queue set caused a higher priority - * task to unblock. A context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so - * record that a context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - * context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ - } - else - { - /* Increment the lock count so the task that unlocks the queue - * knows that data was posted while it was locked. */ - configASSERT( cTxLock != queueINT8_MAX ); - - pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } - - xReturn = pdPASS; - } - else - { - traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); - xReturn = errQUEUE_FULL; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueReceive( QueueHandle_t xQueue, - void * const pvBuffer, - TickType_t xTicksToWait ) -{ - BaseType_t xEntryTimeSet = pdFALSE; - TimeOut_t xTimeOut; - Queue_t * const pxQueue = xQueue; - - /* Check the pointer is not NULL. */ - configASSERT( ( pxQueue ) ); - - /* The buffer into which data is received can only be NULL if the data size - * is zero (so no data is copied into the buffer). */ - configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); - - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - /*lint -save -e904 This function relaxes the coding standard somewhat to - * allow return statements within the function itself. This is done in the - * interest of execution time efficiency. */ - for( ; ; ) - { - taskENTER_CRITICAL(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - - /* Is there data in the queue now? To be running the calling task - * must be the highest priority task wanting to access the queue. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Data available, remove one item. */ - prvCopyDataFromQueue( pxQueue, pvBuffer ); - traceQUEUE_RECEIVE( pxQueue ); - pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; - - /* There is now space in the queue, were any tasks waiting to - * post to the queue? If so, unblock the highest priority waiting - * task. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was empty and no block time is specified (or - * the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was empty and a block time was specified so - * configure the timeout structure. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); - - /* Interrupts and other tasks can send to and receive from the queue - * now the critical section has been exited. */ - - vTaskSuspendAll(); - prvLockQueue( pxQueue ); - - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* The timeout has not expired. If the queue is still empty place - * the task on the list of tasks waiting to receive from the queue. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The queue contains data again. Loop back to try and read the - * data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* Timed out. If there is no data in the queue exit, otherwise loop - * back and attempt to read the data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } /*lint -restore */ -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, - TickType_t xTicksToWait ) -{ - BaseType_t xEntryTimeSet = pdFALSE; - TimeOut_t xTimeOut; - Queue_t * const pxQueue = xQueue; - - #if ( configUSE_MUTEXES == 1 ) - BaseType_t xInheritanceOccurred = pdFALSE; - #endif - - /* Check the queue pointer is not NULL. */ - configASSERT( ( pxQueue ) ); - - /* Check this really is a semaphore, in which case the item size will be - * 0. */ - configASSERT( pxQueue->uxItemSize == 0 ); - - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - /*lint -save -e904 This function relaxes the coding standard somewhat to allow return - * statements within the function itself. This is done in the interest - * of execution time efficiency. */ - for( ; ; ) - { - taskENTER_CRITICAL(); - { - /* Semaphores are queues with an item size of 0, and where the - * number of messages in the queue is the semaphore's count value. */ - const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; - - /* Is there data in the queue now? To be running the calling task - * must be the highest priority task wanting to access the queue. */ - if( uxSemaphoreCount > ( UBaseType_t ) 0 ) - { - traceQUEUE_RECEIVE( pxQueue ); - - /* Semaphores are queues with a data size of zero and where the - * messages waiting is the semaphore's count. Reduce the count. */ - pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( UBaseType_t ) 1; - - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - /* Record the information required to implement - * priority inheritance should it become necessary. */ - pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_MUTEXES */ - - /* Check to see if other tasks are blocked waiting to give the - * semaphore, and if so, unblock the highest priority such task. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* For inheritance to have occurred there must have been an - * initial timeout, and an adjusted timeout cannot become 0, as - * if it were 0 the function would have exited. */ - #if ( configUSE_MUTEXES == 1 ) - { - configASSERT( xInheritanceOccurred == pdFALSE ); - } - #endif /* configUSE_MUTEXES */ - - /* The semaphore count was 0 and no block time is specified - * (or the block time has expired) so exit now. */ - taskEXIT_CRITICAL(); - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The semaphore count was 0 and a block time was specified - * so configure the timeout structure ready to block. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); - - /* Interrupts and other tasks can give to and take from the semaphore - * now the critical section has been exited. */ - - vTaskSuspendAll(); - prvLockQueue( pxQueue ); - - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* A block time is specified and not expired. If the semaphore - * count is 0 then enter the Blocked state to wait for a semaphore to - * become available. As semaphores are implemented with queues the - * queue being empty is equivalent to the semaphore count being 0. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); - - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - taskENTER_CRITICAL(); - { - xInheritanceOccurred = xTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder ); - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* if ( configUSE_MUTEXES == 1 ) */ - - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* There was no timeout and the semaphore count was not 0, so - * attempt to take the semaphore again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* Timed out. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - - /* If the semaphore count is 0 exit now as the timeout has - * expired. Otherwise return to attempt to take the semaphore that is - * known to be available. As semaphores are implemented by queues the - * queue being empty is equivalent to the semaphore count being 0. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - #if ( configUSE_MUTEXES == 1 ) - { - /* xInheritanceOccurred could only have be set if - * pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to - * test the mutex type again to check it is actually a mutex. */ - if( xInheritanceOccurred != pdFALSE ) - { - taskENTER_CRITICAL(); - { - UBaseType_t uxHighestWaitingPriority; - - /* This task blocking on the mutex caused another - * task to inherit this task's priority. Now this task - * has timed out the priority should be disinherited - * again, but only as low as the next highest priority - * task that is waiting for the same mutex. */ - uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); - vTaskPriorityDisinheritAfterTimeout( pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority ); - } - taskEXIT_CRITICAL(); - } - } - #endif /* configUSE_MUTEXES */ - - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } /*lint -restore */ -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueuePeek( QueueHandle_t xQueue, - void * const pvBuffer, - TickType_t xTicksToWait ) -{ - BaseType_t xEntryTimeSet = pdFALSE; - TimeOut_t xTimeOut; - int8_t * pcOriginalReadPosition; - Queue_t * const pxQueue = xQueue; - - /* Check the pointer is not NULL. */ - configASSERT( ( pxQueue ) ); - - /* The buffer into which data is received can only be NULL if the data size - * is zero (so no data is copied into the buffer. */ - configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); - - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - /*lint -save -e904 This function relaxes the coding standard somewhat to - * allow return statements within the function itself. This is done in the - * interest of execution time efficiency. */ - for( ; ; ) - { - taskENTER_CRITICAL(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - - /* Is there data in the queue now? To be running the calling task - * must be the highest priority task wanting to access the queue. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Remember the read position so it can be reset after the data - * is read from the queue as this function is only peeking the - * data, not removing it. */ - pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; - - prvCopyDataFromQueue( pxQueue, pvBuffer ); - traceQUEUE_PEEK( pxQueue ); - - /* The data is not being removed, so reset the read pointer. */ - pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; - - /* The data is being left in the queue, so see if there are - * any other tasks waiting for the data. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority than this task. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was empty and no block time is specified (or - * the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); - traceQUEUE_PEEK_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was empty and a block time was specified so - * configure the timeout structure ready to enter the blocked - * state. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); - - /* Interrupts and other tasks can send to and receive from the queue - * now the critical section has been exited. */ - - vTaskSuspendAll(); - prvLockQueue( pxQueue ); - - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* Timeout has not expired yet, check to see if there is data in the - * queue now, and if not enter the Blocked state to wait for data. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* There is data in the queue now, so don't enter the blocked - * state, instead return to try and obtain the data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* The timeout has expired. If there is still no data in the queue - * exit, otherwise go back and try to read the data again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceQUEUE_PEEK_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } /*lint -restore */ -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, - void * const pvBuffer, - BaseType_t * const pxHigherPriorityTaskWoken ) -{ - BaseType_t xReturn; - UBaseType_t uxSavedInterruptStatus; - Queue_t * const pxQueue = xQueue; - - configASSERT( pxQueue ); - configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - - /* RTOS ports that support interrupt nesting have the concept of a maximum - * system call (or maximum API call) interrupt priority. Interrupts that are - * above the maximum system call priority are kept permanently enabled, even - * when the RTOS kernel is in a critical section, but cannot make any calls to - * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - * failure if a FreeRTOS API function is called from an interrupt that has been - * assigned a priority above the configured maximum system call priority. - * Only FreeRTOS functions that end in FromISR can be called from interrupts - * that have been assigned a priority at or (logically) below the maximum - * system call interrupt priority. FreeRTOS maintains a separate interrupt - * safe API to ensure interrupt entry is as fast and as simple as possible. - * More information (albeit Cortex-M specific) is provided on the following - * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - - /* Cannot block in an ISR, so check there is data available. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - const int8_t cRxLock = pxQueue->cRxLock; - - traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); - - prvCopyDataFromQueue( pxQueue, pvBuffer ); - pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; - - /* If the queue is locked the event list will not be modified. - * Instead update the lock count so the task that unlocks the queue - * will know that an ISR has removed data while the queue was - * locked. */ - if( cRxLock == queueUNLOCKED ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - /* The task waiting has a higher priority than us so - * force a context switch. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Increment the lock count so the task that unlocks the queue - * knows that data was removed while it was locked. */ - configASSERT( cRxLock != queueINT8_MAX ); - - pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 ); - } - - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, - void * const pvBuffer ) -{ - BaseType_t xReturn; - UBaseType_t uxSavedInterruptStatus; - int8_t * pcOriginalReadPosition; - Queue_t * const pxQueue = xQueue; - - configASSERT( pxQueue ); - configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ - - /* RTOS ports that support interrupt nesting have the concept of a maximum - * system call (or maximum API call) interrupt priority. Interrupts that are - * above the maximum system call priority are kept permanently enabled, even - * when the RTOS kernel is in a critical section, but cannot make any calls to - * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - * failure if a FreeRTOS API function is called from an interrupt that has been - * assigned a priority above the configured maximum system call priority. - * Only FreeRTOS functions that end in FromISR can be called from interrupts - * that have been assigned a priority at or (logically) below the maximum - * system call interrupt priority. FreeRTOS maintains a separate interrupt - * safe API to ensure interrupt entry is as fast and as simple as possible. - * More information (albeit Cortex-M specific) is provided on the following - * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - /* Cannot block in an ISR, so check there is data available. */ - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - traceQUEUE_PEEK_FROM_ISR( pxQueue ); - - /* Remember the read position so it can be reset as nothing is - * actually being removed from the queue. */ - pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; - prvCopyDataFromQueue( pxQueue, pvBuffer ); - pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; - - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) -{ - UBaseType_t uxReturn; - - configASSERT( xQueue ); - - taskENTER_CRITICAL(); - { - uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; - } - taskEXIT_CRITICAL(); - - return uxReturn; -} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ -/*-----------------------------------------------------------*/ - -UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) -{ - UBaseType_t uxReturn; - Queue_t * const pxQueue = xQueue; - - configASSERT( pxQueue ); - - taskENTER_CRITICAL(); - { - uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; - } - taskEXIT_CRITICAL(); - - return uxReturn; -} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ -/*-----------------------------------------------------------*/ - -UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) -{ - UBaseType_t uxReturn; - Queue_t * const pxQueue = xQueue; - - configASSERT( pxQueue ); - uxReturn = pxQueue->uxMessagesWaiting; - - return uxReturn; -} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ -/*-----------------------------------------------------------*/ - -void vQueueDelete( QueueHandle_t xQueue ) -{ - Queue_t * const pxQueue = xQueue; - - configASSERT( pxQueue ); - traceQUEUE_DELETE( pxQueue ); - - #if ( configQUEUE_REGISTRY_SIZE > 0 ) - { - vQueueUnregisterQueue( pxQueue ); - } - #endif - - #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) - { - /* The queue can only have been allocated dynamically - free it - * again. */ - vPortFree( pxQueue ); - } - #elif ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - { - /* The queue could have been allocated statically or dynamically, so - * check before attempting to free the memory. */ - if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) - { - vPortFree( pxQueue ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #else /* if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) */ - { - /* The queue must have been statically allocated, so is not going to be - * deleted. Avoid compiler warnings about the unused parameter. */ - ( void ) pxQueue; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) - { - return ( ( Queue_t * ) xQueue )->uxQueueNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - void vQueueSetQueueNumber( QueueHandle_t xQueue, - UBaseType_t uxQueueNumber ) - { - ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) - { - return ( ( Queue_t * ) xQueue )->ucQueueType; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) - { - UBaseType_t uxHighestPriorityOfWaitingTasks; - - /* If a task waiting for a mutex causes the mutex holder to inherit a - * priority, but the waiting task times out, then the holder should - * disinherit the priority - but only down to the highest priority of any - * other tasks that are waiting for the same mutex. For this purpose, - * return the priority of the highest priority task that is waiting for the - * mutex. */ - if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0U ) - { - uxHighestPriorityOfWaitingTasks = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ); - } - else - { - uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; - } - - return uxHighestPriorityOfWaitingTasks; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, - const void * pvItemToQueue, - const BaseType_t xPosition ) -{ - BaseType_t xReturn = pdFALSE; - UBaseType_t uxMessagesWaiting; - - /* This function is called from a critical section. */ - - uxMessagesWaiting = pxQueue->uxMessagesWaiting; - - if( pxQueue->uxItemSize == ( UBaseType_t ) 0 ) - { - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - /* The mutex is no longer being held. */ - xReturn = xTaskPriorityDisinherit( pxQueue->u.xSemaphore.xMutexHolder ); - pxQueue->u.xSemaphore.xMutexHolder = NULL; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_MUTEXES */ - } - else if( xPosition == queueSEND_TO_BACK ) - { - ( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ - pxQueue->pcWriteTo += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ - - if( pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ - { - pxQueue->pcWriteTo = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - ( void ) memcpy( ( void * ) pxQueue->u.xQueue.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e9087 !e418 MISRA exception as the casts are only redundant for some ports. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. Assert checks null pointer only used when length is 0. */ - pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize; - - if( pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ - { - pxQueue->u.xQueue.pcReadFrom = ( pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( xPosition == queueOVERWRITE ) - { - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* An item is not being added but overwritten, so subtract - * one from the recorded number of items in the queue so when - * one is added again below the number of recorded items remains - * correct. */ - --uxMessagesWaiting; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; - - return xReturn; -} -/*-----------------------------------------------------------*/ - -static void prvCopyDataFromQueue( Queue_t * const pxQueue, - void * const pvBuffer ) -{ - if( pxQueue->uxItemSize != ( UBaseType_t ) 0 ) - { - pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ - - if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */ - { - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ - } -} -/*-----------------------------------------------------------*/ - -static void prvUnlockQueue( Queue_t * const pxQueue ) -{ - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ - - /* The lock counts contains the number of extra data items placed or - * removed from the queue while the queue was locked. When a queue is - * locked items can be added or removed, but the event lists cannot be - * updated. */ - taskENTER_CRITICAL(); - { - int8_t cTxLock = pxQueue->cTxLock; - - /* See if data was added to the queue while it was locked. */ - while( cTxLock > queueLOCKED_UNMODIFIED ) - { - /* Data was posted while the queue was locked. Are any tasks - * blocked waiting for data to become available? */ - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting to - * the queue set caused a higher priority task to unblock. - * A context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Tasks that are removed from the event list will get - * added to the pending ready list as the scheduler is still - * suspended. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - * context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - break; - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - /* Tasks that are removed from the event list will get added to - * the pending ready list as the scheduler is still suspended. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that - * a context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - break; - } - } - #endif /* configUSE_QUEUE_SETS */ - - --cTxLock; - } - - pxQueue->cTxLock = queueUNLOCKED; - } - taskEXIT_CRITICAL(); - - /* Do the same for the Rx lock. */ - taskENTER_CRITICAL(); - { - int8_t cRxLock = pxQueue->cRxLock; - - while( cRxLock > queueLOCKED_UNMODIFIED ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - --cRxLock; - } - else - { - break; - } - } - - pxQueue->cRxLock = queueUNLOCKED; - } - taskEXIT_CRITICAL(); -} -/*-----------------------------------------------------------*/ - -static BaseType_t prvIsQueueEmpty( const Queue_t * pxQueue ) -{ - BaseType_t xReturn; - - taskENTER_CRITICAL(); - { - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - taskEXIT_CRITICAL(); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) -{ - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; - - configASSERT( pxQueue ); - - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ -/*-----------------------------------------------------------*/ - -static BaseType_t prvIsQueueFull( const Queue_t * pxQueue ) -{ - BaseType_t xReturn; - - taskENTER_CRITICAL(); - { - if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - taskEXIT_CRITICAL(); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) -{ - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; - - configASSERT( pxQueue ); - - if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_CO_ROUTINES == 1 ) - - BaseType_t xQueueCRSend( QueueHandle_t xQueue, - const void * pvItemToQueue, - TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; - - /* If the queue is already full we may have to block. A critical section - * is required to prevent an interrupt removing something from the queue - * between the check to see if the queue is full and blocking on the queue. */ - portDISABLE_INTERRUPTS(); - { - if( prvIsQueueFull( pxQueue ) != pdFALSE ) - { - /* The queue is full - do we want to block or just leave without - * posting? */ - if( xTicksToWait > ( TickType_t ) 0 ) - { - /* As this is called from a coroutine we cannot block directly, but - * return indicating that we need to block. */ - vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); - portENABLE_INTERRUPTS(); - return errQUEUE_BLOCKED; - } - else - { - portENABLE_INTERRUPTS(); - return errQUEUE_FULL; - } - } - } - portENABLE_INTERRUPTS(); - - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) - { - /* There is room in the queue, copy the data into the queue. */ - prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); - xReturn = pdPASS; - - /* Were any co-routines waiting for data to become available? */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - /* In this instance the co-routine could be placed directly - * into the ready list as we are within a critical section. - * Instead the same pending ready list mechanism is used as if - * the event were caused from within an interrupt. */ - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The co-routine waiting has a higher priority so record - * that a yield might be appropriate. */ - xReturn = errQUEUE_YIELD; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xReturn = errQUEUE_FULL; - } - } - portENABLE_INTERRUPTS(); - - return xReturn; - } - -#endif /* configUSE_CO_ROUTINES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_CO_ROUTINES == 1 ) - - BaseType_t xQueueCRReceive( QueueHandle_t xQueue, - void * pvBuffer, - TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; - - /* If the queue is already empty we may have to block. A critical section - * is required to prevent an interrupt adding something to the queue - * between the check to see if the queue is empty and blocking on the queue. */ - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - /* There are no messages in the queue, do we want to block or just - * leave with nothing? */ - if( xTicksToWait > ( TickType_t ) 0 ) - { - /* As this is a co-routine we cannot block directly, but return - * indicating that we need to block. */ - vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); - portENABLE_INTERRUPTS(); - return errQUEUE_BLOCKED; - } - else - { - portENABLE_INTERRUPTS(); - return errQUEUE_FULL; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - portENABLE_INTERRUPTS(); - - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Data is available from the queue. */ - pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; - - if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) - { - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - --( pxQueue->uxMessagesWaiting ); - ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); - - xReturn = pdPASS; - - /* Were any co-routines waiting for space to become available? */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - /* In this instance the co-routine could be placed directly - * into the ready list as we are within a critical section. - * Instead the same pending ready list mechanism is used as if - * the event were caused from within an interrupt. */ - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - xReturn = errQUEUE_YIELD; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xReturn = pdFAIL; - } - } - portENABLE_INTERRUPTS(); - - return xReturn; - } - -#endif /* configUSE_CO_ROUTINES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_CO_ROUTINES == 1 ) - - BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, - const void * pvItemToQueue, - BaseType_t xCoRoutinePreviouslyWoken ) - { - Queue_t * const pxQueue = xQueue; - - /* Cannot block within an ISR so if there is no space on the queue then - * exit without doing anything. */ - if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) - { - prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); - - /* We only want to wake one co-routine per ISR, so check that a - * co-routine has not already been woken. */ - if( xCoRoutinePreviouslyWoken == pdFALSE ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - return pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xCoRoutinePreviouslyWoken; - } - -#endif /* configUSE_CO_ROUTINES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_CO_ROUTINES == 1 ) - - BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, - void * pvBuffer, - BaseType_t * pxCoRoutineWoken ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; - - /* We cannot block from an ISR, so check there is data available. If - * not then just leave without doing anything. */ - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Copy the data from the queue. */ - pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; - - if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) - { - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - --( pxQueue->uxMessagesWaiting ); - ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); - - if( ( *pxCoRoutineWoken ) == pdFALSE ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - *pxCoRoutineWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } - - return xReturn; - } - -#endif /* configUSE_CO_ROUTINES */ -/*-----------------------------------------------------------*/ - -#if ( configQUEUE_REGISTRY_SIZE > 0 ) - - void vQueueAddToRegistry( QueueHandle_t xQueue, - const char * pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t ux; - - /* See if there is an empty space in the registry. A NULL name denotes - * a free slot. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].pcQueueName == NULL ) - { - /* Store the information on this queue. */ - xQueueRegistry[ ux ].pcQueueName = pcQueueName; - xQueueRegistry[ ux ].xHandle = xQueue; - - traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ); - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - -#endif /* configQUEUE_REGISTRY_SIZE */ -/*-----------------------------------------------------------*/ - -#if ( configQUEUE_REGISTRY_SIZE > 0 ) - - const char * pcQueueGetName( QueueHandle_t xQueue ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t ux; - const char * pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - - /* Note there is nothing here to protect against another task adding or - * removing entries from the registry while it is being searched. */ - - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].xHandle == xQueue ) - { - pcReturn = xQueueRegistry[ ux ].pcQueueName; - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - return pcReturn; - } /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */ - -#endif /* configQUEUE_REGISTRY_SIZE */ -/*-----------------------------------------------------------*/ - -#if ( configQUEUE_REGISTRY_SIZE > 0 ) - - void vQueueUnregisterQueue( QueueHandle_t xQueue ) - { - UBaseType_t ux; - - /* See if the handle of the queue being unregistered in actually in the - * registry. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].xHandle == xQueue ) - { - /* Set the name to NULL to show that this slot if free again. */ - xQueueRegistry[ ux ].pcQueueName = NULL; - - /* Set the handle to NULL to ensure the same queue handle cannot - * appear in the registry twice if it is added, removed, then - * added again. */ - xQueueRegistry[ ux ].xHandle = ( QueueHandle_t ) 0; - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ - -#endif /* configQUEUE_REGISTRY_SIZE */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TIMERS == 1 ) - - void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, - TickType_t xTicksToWait, - const BaseType_t xWaitIndefinitely ) - { - Queue_t * const pxQueue = xQueue; - - /* This function should not be called by application code hence the - * 'Restricted' in its name. It is not part of the public API. It is - * designed for use by kernel code, and has special calling requirements. - * It can result in vListInsert() being called on a list that can only - * possibly ever have one item in it, so the list will be fast, but even - * so it should be called with the scheduler locked and not from a critical - * section. */ - - /* Only do anything if there are no messages in the queue. This function - * will not actually cause the task to block, just place it on a blocked - * list. It will not block until the scheduler is unlocked - at which - * time a yield will be performed. If an item is added to the queue while - * the queue is locked, and the calling task blocks on the queue, then the - * calling task will be immediately unblocked when the queue is unlocked. */ - prvLockQueue( pxQueue ); - - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U ) - { - /* There is nothing in the queue, block for the specified period. */ - vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait, xWaitIndefinitely ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - prvUnlockQueue( pxQueue ); - } - -#endif /* configUSE_TIMERS */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) - { - QueueSetHandle_t pxQueue; - - pxQueue = xQueueGenericCreate( uxEventQueueLength, ( UBaseType_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET ); - - return pxQueue; - } - -#endif /* configUSE_QUEUE_SETS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - - BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, - QueueSetHandle_t xQueueSet ) - { - BaseType_t xReturn; - - taskENTER_CRITICAL(); - { - if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ) - { - /* Cannot add a queue/semaphore to more than one queue set. */ - xReturn = pdFAIL; - } - else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 ) - { - /* Cannot add a queue/semaphore to a queue set if there are already - * items in the queue/semaphore. */ - xReturn = pdFAIL; - } - else - { - ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet; - xReturn = pdPASS; - } - } - taskEXIT_CRITICAL(); - - return xReturn; - } - -#endif /* configUSE_QUEUE_SETS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - - BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, - QueueSetHandle_t xQueueSet ) - { - BaseType_t xReturn; - Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore; - - if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ) - { - /* The queue was not a member of the set. */ - xReturn = pdFAIL; - } - else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 ) - { - /* It is dangerous to remove a queue from a set when the queue is - * not empty because the queue set will still hold pending events for - * the queue. */ - xReturn = pdFAIL; - } - else - { - taskENTER_CRITICAL(); - { - /* The queue is no longer contained in the set. */ - pxQueueOrSemaphore->pxQueueSetContainer = NULL; - } - taskEXIT_CRITICAL(); - xReturn = pdPASS; - } - - return xReturn; - } /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */ - -#endif /* configUSE_QUEUE_SETS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - - QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, - TickType_t const xTicksToWait ) - { - QueueSetMemberHandle_t xReturn = NULL; - - ( void ) xQueueReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait ); /*lint !e961 Casting from one typedef to another is not redundant. */ - return xReturn; - } - -#endif /* configUSE_QUEUE_SETS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - - QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) - { - QueueSetMemberHandle_t xReturn = NULL; - - ( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */ - return xReturn; - } - -#endif /* configUSE_QUEUE_SETS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - - static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue ) - { - Queue_t * pxQueueSetContainer = pxQueue->pxQueueSetContainer; - BaseType_t xReturn = pdFALSE; - - /* This function must be called form a critical section. */ - - configASSERT( pxQueueSetContainer ); - configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ); - - if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ) - { - const int8_t cTxLock = pxQueueSetContainer->cTxLock; - - traceQUEUE_SET_SEND( pxQueueSetContainer ); - - /* The data copied is the handle of the queue that contains data. */ - xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, queueSEND_TO_BACK ); - - if( cTxLock == queueUNLOCKED ) - { - if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - configASSERT( cTxLock != queueINT8_MAX ); - - pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xReturn; - } - -#endif /* configUSE_QUEUE_SETS */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#include +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" + +#if ( configUSE_CO_ROUTINES == 1 ) + #include "croutine.h" +#endif + +/* The MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + + +/* Constants used with the cRxLock and cTxLock structure members. */ +#define queueUNLOCKED ( ( int8_t ) -1 ) +#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) +#define queueINT8_MAX ( ( int8_t ) 127 ) + +/* When the Queue_t structure is used to represent a base queue its pcHead and + * pcTail members are used as pointers into the queue storage area. When the + * Queue_t structure is used to represent a mutex pcHead and pcTail pointers are + * not necessary, and the pcHead pointer is set to NULL to indicate that the + * structure instead holds a pointer to the mutex holder (if any). Map alternative + * names to the pcHead and structure member to ensure the readability of the code + * is maintained. The QueuePointers_t and SemaphoreData_t types are used to form + * a union as their usage is mutually exclusive dependent on what the queue is + * being used for. */ +#define uxQueueType pcHead +#define queueQUEUE_IS_MUTEX NULL + +typedef struct QueuePointers +{ + int8_t * pcTail; /**< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ + int8_t * pcReadFrom; /**< Points to the last place that a queued item was read from when the structure is used as a queue. */ +} QueuePointers_t; + +typedef struct SemaphoreData +{ + TaskHandle_t xMutexHolder; /**< The handle of the task that holds the mutex. */ + UBaseType_t uxRecursiveCallCount; /**< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ +} SemaphoreData_t; + +/* Semaphores do not actually store or copy data, so have an item size of + * zero. */ +#define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( UBaseType_t ) 0 ) +#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U ) + +#if ( configUSE_PREEMPTION == 0 ) + +/* If the cooperative scheduler is being used then a yield should not be + * performed just because a higher priority task has been woken. */ + #define queueYIELD_IF_USING_PREEMPTION() +#else + #if ( configNUMBER_OF_CORES == 1 ) + #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + #define queueYIELD_IF_USING_PREEMPTION() vTaskYieldWithinAPI() + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ +#endif + +/* + * Definition of the queue used by the scheduler. + * Items are queued by copy, not reference. See the following link for the + * rationale: https://www.FreeRTOS.org/Embedded-RTOS-Queues.html + */ +typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +{ + int8_t * pcHead; /**< Points to the beginning of the queue storage area. */ + int8_t * pcWriteTo; /**< Points to the free next place in the storage area. */ + + union + { + QueuePointers_t xQueue; /**< Data required exclusively when this structure is used as a queue. */ + SemaphoreData_t xSemaphore; /**< Data required exclusively when this structure is used as a semaphore. */ + } u; + + List_t xTasksWaitingToSend; /**< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ + List_t xTasksWaitingToReceive; /**< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ + + volatile UBaseType_t uxMessagesWaiting; /**< The number of items currently in the queue. */ + UBaseType_t uxLength; /**< The length of the queue defined as the number of items it will hold, not the number of bytes. */ + UBaseType_t uxItemSize; /**< The size of each items that the queue will hold. */ + + volatile int8_t cRxLock; /**< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + volatile int8_t cTxLock; /**< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /**< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ + #endif + + #if ( configUSE_QUEUE_SETS == 1 ) + struct QueueDefinition * pxQueueSetContainer; + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxQueueNumber; + uint8_t ucQueueType; + #endif +} xQUEUE; + +/* The old xQUEUE name is maintained above then typedefed to the new Queue_t + * name below to enable the use of older kernel aware debuggers. */ +typedef xQUEUE Queue_t; + +/*-----------------------------------------------------------*/ + +/* + * The queue registry is just a means for kernel aware debuggers to locate + * queue structures. It has no other purpose so is an optional component. + */ +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + +/* The type stored within the queue registry array. This allows a name + * to be assigned to each queue making kernel aware debugging a little + * more user friendly. */ + typedef struct QUEUE_REGISTRY_ITEM + { + const char * pcQueueName; + QueueHandle_t xHandle; + } xQueueRegistryItem; + +/* The old xQueueRegistryItem name is maintained above then typedefed to the + * new xQueueRegistryItem name below to enable the use of older kernel aware + * debuggers. */ + typedef xQueueRegistryItem QueueRegistryItem_t; + +/* The queue registry is simply an array of QueueRegistryItem_t structures. + * The pcQueueName member of a structure being NULL is indicative of the + * array position being vacant. */ + +/* MISRA Ref 8.4.2 [Declaration shall be visible] */ +/* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-84 */ +/* coverity[misra_c_2012_rule_8_4_violation] */ + PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; + +#endif /* configQUEUE_REGISTRY_SIZE */ + +/* + * Unlocks a queue locked by a call to prvLockQueue. Locking a queue does not + * prevent an ISR from adding or removing items to the queue, but does prevent + * an ISR from removing tasks from the queue event lists. If an ISR finds a + * queue is locked it will instead increment the appropriate queue lock count + * to indicate that a task may require unblocking. When the queue in unlocked + * these lock counts are inspected, and the appropriate action taken. + */ +static void prvUnlockQueue( Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Uses a critical section to determine if there is any data in a queue. + * + * @return pdTRUE if the queue contains no items, otherwise pdFALSE. + */ +static BaseType_t prvIsQueueEmpty( const Queue_t * pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Uses a critical section to determine if there is any space in a queue. + * + * @return pdTRUE if there is no space, otherwise pdFALSE; + */ +static BaseType_t prvIsQueueFull( const Queue_t * pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Copies an item into the queue, either at the front of the queue or the + * back of the queue. + */ +static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, + const void * pvItemToQueue, + const BaseType_t xPosition ) PRIVILEGED_FUNCTION; + +/* + * Copies an item out of a queue. + */ +static void prvCopyDataFromQueue( Queue_t * const pxQueue, + void * const pvBuffer ) PRIVILEGED_FUNCTION; + +#if ( configUSE_QUEUE_SETS == 1 ) + +/* + * Checks to see if a queue is a member of a queue set, and if so, notifies + * the queue set that the queue contains data. + */ + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; +#endif + +/* + * Called after a Queue_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ +static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + const uint8_t ucQueueType, + Queue_t * pxNewQueue ) PRIVILEGED_FUNCTION; + +/* + * Mutexes are a special type of queue. When a mutex is created, first the + * queue is created, then prvInitialiseMutex() is called to configure the queue + * as a mutex. + */ +#if ( configUSE_MUTEXES == 1 ) + static void prvInitialiseMutex( Queue_t * pxNewQueue ) PRIVILEGED_FUNCTION; +#endif + +#if ( configUSE_MUTEXES == 1 ) + +/* + * If a task waiting for a mutex causes the mutex holder to inherit a + * priority, but the waiting task times out, then the holder should + * disinherit the priority - but only down to the highest priority of any + * other tasks that are waiting for the same mutex. This function returns + * that priority. + */ + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; +#endif +/*-----------------------------------------------------------*/ + +/* + * Macro to mark a queue as locked. Locking a queue prevents an ISR from + * accessing the queue event lists. + */ +#define prvLockQueue( pxQueue ) \ + taskENTER_CRITICAL(); \ + { \ + if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ + } \ + if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ + } \ + } \ + taskEXIT_CRITICAL() + +/* + * Macro to increment cTxLock member of the queue data structure. It is + * capped at the number of tasks in the system as we cannot unblock more + * tasks than the number of tasks in the system. + */ +#define prvIncrementQueueTxLock( pxQueue, cTxLock ) \ + do { \ + const UBaseType_t uxNumberOfTasks = uxTaskGetNumberOfTasks(); \ + if( ( UBaseType_t ) ( cTxLock ) < uxNumberOfTasks ) \ + { \ + configASSERT( ( cTxLock ) != queueINT8_MAX ); \ + ( pxQueue )->cTxLock = ( int8_t ) ( ( cTxLock ) + ( int8_t ) 1 ); \ + } \ + } while( 0 ) + +/* + * Macro to increment cRxLock member of the queue data structure. It is + * capped at the number of tasks in the system as we cannot unblock more + * tasks than the number of tasks in the system. + */ +#define prvIncrementQueueRxLock( pxQueue, cRxLock ) \ + do { \ + const UBaseType_t uxNumberOfTasks = uxTaskGetNumberOfTasks(); \ + if( ( UBaseType_t ) ( cRxLock ) < uxNumberOfTasks ) \ + { \ + configASSERT( ( cRxLock ) != queueINT8_MAX ); \ + ( pxQueue )->cRxLock = ( int8_t ) ( ( cRxLock ) + ( int8_t ) 1 ); \ + } \ + } while( 0 ) +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGenericReset( QueueHandle_t xQueue, + BaseType_t xNewQueue ) +{ + BaseType_t xReturn = pdPASS; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueGenericReset( xQueue, xNewQueue ); + + configASSERT( pxQueue ); + + if( ( pxQueue != NULL ) && + ( pxQueue->uxLength >= 1U ) && + /* Check for multiplication overflow. */ + ( ( SIZE_MAX / pxQueue->uxLength ) >= pxQueue->uxItemSize ) ) + { + taskENTER_CRITICAL(); + { + pxQueue->u.xQueue.pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); + pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U; + pxQueue->pcWriteTo = pxQueue->pcHead; + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - 1U ) * pxQueue->uxItemSize ); + pxQueue->cRxLock = queueUNLOCKED; + pxQueue->cTxLock = queueUNLOCKED; + + if( xNewQueue == pdFALSE ) + { + /* If there are tasks blocked waiting to read from the queue, then + * the tasks will remain blocked as after this function exits the queue + * will still be empty. If there are tasks blocked waiting to write to + * the queue, then one should be unblocked as after this function exits + * it will be possible to write to it. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Ensure the event queues start in the correct state. */ + vListInitialise( &( pxQueue->xTasksWaitingToSend ) ); + vListInitialise( &( pxQueue->xTasksWaitingToReceive ) ); + } + } + taskEXIT_CRITICAL(); + } + else + { + xReturn = pdFAIL; + } + + configASSERT( xReturn != pdFAIL ); + + /* A value is returned for calling semantic consistency with previous + * versions. */ + traceRETURN_xQueueGenericReset( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + StaticQueue_t * pxStaticQueue, + const uint8_t ucQueueType ) + { + Queue_t * pxNewQueue = NULL; + + traceENTER_xQueueGenericCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxStaticQueue, ucQueueType ); + + /* The StaticQueue_t structure and the queue storage area must be + * supplied. */ + configASSERT( pxStaticQueue ); + + if( ( uxQueueLength > ( UBaseType_t ) 0 ) && + ( pxStaticQueue != NULL ) && + + /* A queue storage area should be provided if the item size is not 0, and + * should not be provided if the item size is 0. */ + ( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0U ) ) ) && + ( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0U ) ) ) ) + { + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticQueue_t or StaticSemaphore_t equals the size of + * the real queue and semaphore structures. */ + volatile size_t xSize = sizeof( StaticQueue_t ); + + /* This assertion cannot be branch covered in unit tests */ + configASSERT( xSize == sizeof( Queue_t ) ); /* LCOV_EXCL_BR_LINE */ + ( void ) xSize; /* Prevent unused variable warning when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ + + /* The address of a statically allocated queue was passed in, use it. + * The address of a statically allocated storage area was also passed in + * but is already set. */ + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + pxNewQueue = ( Queue_t * ) pxStaticQueue; + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Queues can be allocated wither statically or dynamically, so + * note this queue was allocated statically in case the queue is + * later deleted. */ + pxNewQueue->ucStaticallyAllocated = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + + prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); + } + else + { + configASSERT( pxNewQueue ); + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xQueueGenericCreateStatic( pxNewQueue ); + + return pxNewQueue; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + BaseType_t xQueueGenericGetStaticBuffers( QueueHandle_t xQueue, + uint8_t ** ppucQueueStorage, + StaticQueue_t ** ppxStaticQueue ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueGenericGetStaticBuffers( xQueue, ppucQueueStorage, ppxStaticQueue ); + + configASSERT( pxQueue ); + configASSERT( ppxStaticQueue ); + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Check if the queue was statically allocated. */ + if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdTRUE ) + { + if( ppucQueueStorage != NULL ) + { + *ppucQueueStorage = ( uint8_t * ) pxQueue->pcHead; + } + + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + *ppxStaticQueue = ( StaticQueue_t * ) pxQueue; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + #else /* configSUPPORT_DYNAMIC_ALLOCATION */ + { + /* Queue must have been statically allocated. */ + if( ppucQueueStorage != NULL ) + { + *ppucQueueStorage = ( uint8_t * ) pxQueue->pcHead; + } + + *ppxStaticQueue = ( StaticQueue_t * ) pxQueue; + xReturn = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + + traceRETURN_xQueueGenericGetStaticBuffers( xReturn ); + + return xReturn; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + const uint8_t ucQueueType ) + { + Queue_t * pxNewQueue = NULL; + size_t xQueueSizeInBytes; + uint8_t * pucQueueStorage; + + traceENTER_xQueueGenericCreate( uxQueueLength, uxItemSize, ucQueueType ); + + if( ( uxQueueLength > ( UBaseType_t ) 0 ) && + /* Check for multiplication overflow. */ + ( ( SIZE_MAX / uxQueueLength ) >= uxItemSize ) && + /* Check for addition overflow. */ + ( ( UBaseType_t ) ( SIZE_MAX - sizeof( Queue_t ) ) >= ( uxQueueLength * uxItemSize ) ) ) + { + /* Allocate enough space to hold the maximum number of items that + * can be in the queue at any time. It is valid for uxItemSize to be + * zero in the case the queue is used as a semaphore. */ + xQueueSizeInBytes = ( size_t ) ( ( size_t ) uxQueueLength * ( size_t ) uxItemSize ); + + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); + + if( pxNewQueue != NULL ) + { + /* Jump past the queue structure to find the location of the queue + * storage area. */ + pucQueueStorage = ( uint8_t * ) pxNewQueue; + pucQueueStorage += sizeof( Queue_t ); + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Queues can be created either statically or dynamically, so + * note this task was created dynamically in case it is later + * deleted. */ + pxNewQueue->ucStaticallyAllocated = pdFALSE; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); + } + else + { + traceQUEUE_CREATE_FAILED( ucQueueType ); + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + configASSERT( pxNewQueue ); + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xQueueGenericCreate( pxNewQueue ); + + return pxNewQueue; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + const uint8_t ucQueueType, + Queue_t * pxNewQueue ) +{ + /* Remove compiler warnings about unused parameters should + * configUSE_TRACE_FACILITY not be set to 1. */ + ( void ) ucQueueType; + + if( uxItemSize == ( UBaseType_t ) 0 ) + { + /* No RAM was allocated for the queue storage area, but PC head cannot + * be set to NULL because NULL is used as a key to say the queue is used as + * a mutex. Therefore just set pcHead to point to the queue as a benign + * value that is known to be within the memory map. */ + pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; + } + else + { + /* Set the head to the start of the queue storage area. */ + pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; + } + + /* Initialise the queue members as described where the queue type is + * defined. */ + pxNewQueue->uxLength = uxQueueLength; + pxNewQueue->uxItemSize = uxItemSize; + ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + pxNewQueue->ucQueueType = ucQueueType; + } + #endif /* configUSE_TRACE_FACILITY */ + + #if ( configUSE_QUEUE_SETS == 1 ) + { + pxNewQueue->pxQueueSetContainer = NULL; + } + #endif /* configUSE_QUEUE_SETS */ + + traceQUEUE_CREATE( pxNewQueue ); +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + static void prvInitialiseMutex( Queue_t * pxNewQueue ) + { + if( pxNewQueue != NULL ) + { + /* The queue create function will set all the queue structure members + * correctly for a generic queue, but this function is creating a + * mutex. Overwrite those members that need to be set differently - + * in particular the information required for priority inheritance. */ + pxNewQueue->u.xSemaphore.xMutexHolder = NULL; + pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; + + /* In case this is a recursive mutex. */ + pxNewQueue->u.xSemaphore.uxRecursiveCallCount = 0; + + traceCREATE_MUTEX( pxNewQueue ); + + /* Start with the semaphore in the expected state. */ + ( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK ); + } + else + { + traceCREATE_MUTEX_FAILED(); + } + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) + { + QueueHandle_t xNewQueue; + const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; + + traceENTER_xQueueCreateMutex( ucQueueType ); + + xNewQueue = xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType ); + prvInitialiseMutex( ( Queue_t * ) xNewQueue ); + + traceRETURN_xQueueCreateMutex( xNewQueue ); + + return xNewQueue; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, + StaticQueue_t * pxStaticQueue ) + { + QueueHandle_t xNewQueue; + const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; + + traceENTER_xQueueCreateMutexStatic( ucQueueType, pxStaticQueue ); + + /* Prevent compiler warnings about unused parameters if + * configUSE_TRACE_FACILITY does not equal 1. */ + ( void ) ucQueueType; + + xNewQueue = xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType ); + prvInitialiseMutex( ( Queue_t * ) xNewQueue ); + + traceRETURN_xQueueCreateMutexStatic( xNewQueue ); + + return xNewQueue; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) + + TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; + Queue_t * const pxSemaphore = ( Queue_t * ) xSemaphore; + + traceENTER_xQueueGetMutexHolder( xSemaphore ); + + configASSERT( xSemaphore ); + + /* This function is called by xSemaphoreGetMutexHolder(), and should not + * be called directly. Note: This is a good way of determining if the + * calling task is the mutex holder, but not a good way of determining the + * identity of the mutex holder, as the holder may change between the + * following critical section exiting and the function returning. */ + taskENTER_CRITICAL(); + { + if( pxSemaphore->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = pxSemaphore->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } + } + taskEXIT_CRITICAL(); + + traceRETURN_xQueueGetMutexHolder( pxReturn ); + + return pxReturn; + } + +#endif /* if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) + + TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; + + traceENTER_xQueueGetMutexHolderFromISR( xSemaphore ); + + configASSERT( xSemaphore ); + + /* Mutexes cannot be used in interrupt service routines, so the mutex + * holder should not change in an ISR, and therefore a critical section is + * not required here. */ + if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = ( ( Queue_t * ) xSemaphore )->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } + + traceRETURN_xQueueGetMutexHolderFromISR( pxReturn ); + + return pxReturn; + } + +#endif /* if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + + BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; + + traceENTER_xQueueGiveMutexRecursive( xMutex ); + + configASSERT( pxMutex ); + + /* If this is the task that holds the mutex then xMutexHolder will not + * change outside of this task. If this task does not hold the mutex then + * pxMutexHolder can never coincidentally equal the tasks handle, and as + * this is the only condition we are interested in it does not matter if + * pxMutexHolder is accessed simultaneously by another task. Therefore no + * mutual exclusion is required to test the pxMutexHolder variable. */ + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + traceGIVE_MUTEX_RECURSIVE( pxMutex ); + + /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to + * the task handle, therefore no underflow check is required. Also, + * uxRecursiveCallCount is only modified by the mutex holder, and as + * there can only be one, no mutual exclusion is required to modify the + * uxRecursiveCallCount member. */ + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )--; + + /* Has the recursive call count unwound to 0? */ + if( pxMutex->u.xSemaphore.uxRecursiveCallCount == ( UBaseType_t ) 0 ) + { + /* Return the mutex. This will automatically unblock any other + * task that might be waiting to access the mutex. */ + ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = pdPASS; + } + else + { + /* The mutex cannot be given because the calling task is not the + * holder. */ + xReturn = pdFAIL; + + traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } + + traceRETURN_xQueueGiveMutexRecursive( xReturn ); + + return xReturn; + } + +#endif /* configUSE_RECURSIVE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + + BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; + + traceENTER_xQueueTakeMutexRecursive( xMutex, xTicksToWait ); + + configASSERT( pxMutex ); + + /* Comments regarding mutual exclusion as per those within + * xQueueGiveMutexRecursive(). */ + + traceTAKE_MUTEX_RECURSIVE( pxMutex ); + + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + xReturn = pdPASS; + } + else + { + xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait ); + + /* pdPASS will only be returned if the mutex was successfully + * obtained. The calling task may have entered the Blocked state + * before reaching here. */ + if( xReturn != pdFAIL ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + } + else + { + traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } + } + + traceRETURN_xQueueTakeMutexRecursive( xReturn ); + + return xReturn; + } + +#endif /* configUSE_RECURSIVE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount, + StaticQueue_t * pxStaticQueue ) + { + QueueHandle_t xHandle = NULL; + + traceENTER_xQueueCreateCountingSemaphoreStatic( uxMaxCount, uxInitialCount, pxStaticQueue ); + + if( ( uxMaxCount != 0U ) && + ( uxInitialCount <= uxMaxCount ) ) + { + xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); + + if( xHandle != NULL ) + { + ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; + + traceCREATE_COUNTING_SEMAPHORE(); + } + else + { + traceCREATE_COUNTING_SEMAPHORE_FAILED(); + } + } + else + { + configASSERT( xHandle ); + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xQueueCreateCountingSemaphoreStatic( xHandle ); + + return xHandle; + } + +#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount ) + { + QueueHandle_t xHandle = NULL; + + traceENTER_xQueueCreateCountingSemaphore( uxMaxCount, uxInitialCount ); + + if( ( uxMaxCount != 0U ) && + ( uxInitialCount <= uxMaxCount ) ) + { + xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); + + if( xHandle != NULL ) + { + ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; + + traceCREATE_COUNTING_SEMAPHORE(); + } + else + { + traceCREATE_COUNTING_SEMAPHORE_FAILED(); + } + } + else + { + configASSERT( xHandle ); + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xQueueCreateCountingSemaphore( xHandle ); + + return xHandle; + } + +#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGenericSend( QueueHandle_t xQueue, + const void * const pvItemToQueue, + TickType_t xTicksToWait, + const BaseType_t xCopyPosition ) +{ + BaseType_t xEntryTimeSet = pdFALSE, xYieldRequired; + TimeOut_t xTimeOut; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueGenericSend( xQueue, pvItemToQueue, xTicksToWait, xCopyPosition ); + + configASSERT( pxQueue ); + configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + for( ; ; ) + { + taskENTER_CRITICAL(); + { + /* Is there room on the queue now? The running task must be the + * highest priority task wanting to access the queue. If the head item + * in the queue is to be overwritten then it does not matter if the + * queue is full. */ + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + traceQUEUE_SEND( pxQueue ); + + #if ( configUSE_QUEUE_SETS == 1 ) + { + const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; + + xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) + { + /* Do not notify the queue set as an existing item + * was overwritten in the queue so the number of items + * in the queue has not changed. */ + mtCOVERAGE_TEST_MARKER(); + } + else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + * to the queue set caused a higher priority task to + * unblock. A context switch is required. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If there was a task waiting for data to arrive on the + * queue then unblock it now. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The unblocked task has a priority higher than + * our own so yield immediately. Yes it is ok to + * do this from within the critical section - the + * kernel takes care of that. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xYieldRequired != pdFALSE ) + { + /* This path is a special case that will only get + * executed if the task was holding multiple mutexes + * and the mutexes were given back in an order that is + * different to that in which they were taken. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + + /* If there was a task waiting for data to arrive on the + * queue then unblock it now. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The unblocked task has a priority higher than + * our own so yield immediately. Yes it is ok to do + * this from within the critical section - the kernel + * takes care of that. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xYieldRequired != pdFALSE ) + { + /* This path is a special case that will only get + * executed if the task was holding multiple mutexes and + * the mutexes were given back in an order that is + * different to that in which they were taken. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + + taskEXIT_CRITICAL(); + + traceRETURN_xQueueGenericSend( pdPASS ); + + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was full and no block time is specified (or + * the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + + /* Return to the original privilege level before exiting + * the function. */ + traceQUEUE_SEND_FAILED( pxQueue ); + traceRETURN_xQueueGenericSend( errQUEUE_FULL ); + + return errQUEUE_FULL; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was full and a block time was specified so + * configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + * now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_SEND( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); + + /* Unlocking the queue means queue events can effect the + * event list. It is possible that interrupts occurring now + * remove this task from the event list again - but as the + * scheduler is suspended the task will go onto the pending + * ready list instead of the actual ready list. */ + prvUnlockQueue( pxQueue ); + + /* Resuming the scheduler will move tasks from the pending + * ready list into the ready list - so it is feasible that this + * task is already in the ready list before it yields - in which + * case the yield will not cause a context switch unless there + * is also a higher priority task in the pending ready list. */ + if( xTaskResumeAll() == pdFALSE ) + { + taskYIELD_WITHIN_API(); + } + } + else + { + /* Try again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + traceQUEUE_SEND_FAILED( pxQueue ); + traceRETURN_xQueueGenericSend( errQUEUE_FULL ); + + return errQUEUE_FULL; + } + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, + const void * const pvItemToQueue, + BaseType_t * const pxHigherPriorityTaskWoken, + const BaseType_t xCopyPosition ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueGenericSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken, xCopyPosition ); + + configASSERT( pxQueue ); + configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + /* Similar to xQueueGenericSend, except without blocking if there is no room + * in the queue. Also don't directly wake a task that was blocked on a queue + * read, instead return a flag to say whether a context switch is required or + * not (i.e. has a task with a higher priority than us been woken by this + * post). */ + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = ( UBaseType_t ) taskENTER_CRITICAL_FROM_ISR(); + { + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + const int8_t cTxLock = pxQueue->cTxLock; + const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; + + traceQUEUE_SEND_FROM_ISR( pxQueue ); + + /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a + * semaphore or mutex. That means prvCopyDataToQueue() cannot result + * in a task disinheriting a priority and prvCopyDataToQueue() can be + * called here even though the disinherit function does not check if + * the scheduler is suspended before accessing the ready lists. */ + ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + + /* The event list is not altered if the queue is locked. This will + * be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) + { + /* Do not notify the queue set as an existing item + * was overwritten in the queue so the number of items + * in the queue has not changed. */ + mtCOVERAGE_TEST_MARKER(); + } + else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + * to the queue set caused a higher priority task to + * unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + * record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + * context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Not used in this path. */ + ( void ) uxPreviousMessagesWaiting; + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + * knows that data was posted while it was locked. */ + prvIncrementQueueTxLock( pxQueue, cTxLock ); + } + + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xQueueGenericSendFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueGiveFromISR( xQueue, pxHigherPriorityTaskWoken ); + + /* Similar to xQueueGenericSendFromISR() but used with semaphores where the + * item size is 0. Don't directly wake a task that was blocked on a queue + * read, instead return a flag to say whether a context switch is required or + * not (i.e. has a task with a higher priority than us been woken by this + * post). */ + + configASSERT( pxQueue ); + + /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() + * if the item size is not 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); + + /* Normally a mutex would not be given from an interrupt, especially if + * there is a mutex holder, as priority inheritance makes no sense for an + * interrupts, only tasks. */ + configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = ( UBaseType_t ) taskENTER_CRITICAL_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* When the queue is used to implement a semaphore no data is ever + * moved through the queue but it is still valid to see if the queue 'has + * space'. */ + if( uxMessagesWaiting < pxQueue->uxLength ) + { + const int8_t cTxLock = pxQueue->cTxLock; + + traceQUEUE_SEND_FROM_ISR( pxQueue ); + + /* A task can only have an inherited priority if it is a mutex + * holder - and if there is a mutex holder then the mutex cannot be + * given from an ISR. As this is the ISR version of the function it + * can be assumed there is no mutex holder and no need to determine if + * priority disinheritance is needed. Simply increase the count of + * messages (semaphores) available. */ + pxQueue->uxMessagesWaiting = ( UBaseType_t ) ( uxMessagesWaiting + ( UBaseType_t ) 1 ); + + /* The event list is not altered if the queue is locked. This will + * be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The semaphore is a member of a queue set, and + * posting to the queue set caused a higher priority + * task to unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + * record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + * context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + * knows that data was posted while it was locked. */ + prvIncrementQueueTxLock( pxQueue, cTxLock ); + } + + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xQueueGiveFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueReceive( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) +{ + BaseType_t xEntryTimeSet = pdFALSE; + TimeOut_t xTimeOut; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueReceive( xQueue, pvBuffer, xTicksToWait ); + + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* The buffer into which data is received can only be NULL if the data size + * is zero (so no data is copied into the buffer). */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + for( ; ; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + * must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data available, remove one item. */ + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_RECEIVE( pxQueue ); + pxQueue->uxMessagesWaiting = ( UBaseType_t ) ( uxMessagesWaiting - ( UBaseType_t ) 1 ); + + /* There is now space in the queue, were any tasks waiting to + * post to the queue? If so, unblock the highest priority waiting + * task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + + traceRETURN_xQueueReceive( pdPASS ); + + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + * the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + + traceQUEUE_RECEIVE_FAILED( pxQueue ); + traceRETURN_xQueueReceive( errQUEUE_EMPTY ); + + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + * configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + * now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* The timeout has not expired. If the queue is still empty place + * the task on the list of tasks waiting to receive from the queue. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + + if( xTaskResumeAll() == pdFALSE ) + { + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The queue contains data again. Loop back to try and read the + * data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. If there is no data in the queue exit, otherwise loop + * back and attempt to read the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_RECEIVE_FAILED( pxQueue ); + traceRETURN_xQueueReceive( errQUEUE_EMPTY ); + + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, + TickType_t xTicksToWait ) +{ + BaseType_t xEntryTimeSet = pdFALSE; + TimeOut_t xTimeOut; + Queue_t * const pxQueue = xQueue; + + #if ( configUSE_MUTEXES == 1 ) + BaseType_t xInheritanceOccurred = pdFALSE; + #endif + + traceENTER_xQueueSemaphoreTake( xQueue, xTicksToWait ); + + /* Check the queue pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* Check this really is a semaphore, in which case the item size will be + * 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + for( ; ; ) + { + taskENTER_CRITICAL(); + { + /* Semaphores are queues with an item size of 0, and where the + * number of messages in the queue is the semaphore's count value. */ + const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + * must be the highest priority task wanting to access the queue. */ + if( uxSemaphoreCount > ( UBaseType_t ) 0 ) + { + traceQUEUE_RECEIVE( pxQueue ); + + /* Semaphores are queues with a data size of zero and where the + * messages waiting is the semaphore's count. Reduce the count. */ + pxQueue->uxMessagesWaiting = ( UBaseType_t ) ( uxSemaphoreCount - ( UBaseType_t ) 1 ); + + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* Record the information required to implement + * priority inheritance should it become necessary. */ + pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ + + /* Check to see if other tasks are blocked waiting to give the + * semaphore, and if so, unblock the highest priority such task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + + traceRETURN_xQueueSemaphoreTake( pdPASS ); + + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The semaphore count was 0 and no block time is specified + * (or the block time has expired) so exit now. */ + taskEXIT_CRITICAL(); + + traceQUEUE_RECEIVE_FAILED( pxQueue ); + traceRETURN_xQueueSemaphoreTake( errQUEUE_EMPTY ); + + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The semaphore count was 0 and a block time was specified + * so configure the timeout structure ready to block. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can give to and take from the semaphore + * now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* A block time is specified and not expired. If the semaphore + * count is 0 then enter the Blocked state to wait for a semaphore to + * become available. As semaphores are implemented with queues the + * queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + taskENTER_CRITICAL(); + { + xInheritanceOccurred = xTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder ); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* if ( configUSE_MUTEXES == 1 ) */ + + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + + if( xTaskResumeAll() == pdFALSE ) + { + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There was no timeout and the semaphore count was not 0, so + * attempt to take the semaphore again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + /* If the semaphore count is 0 exit now as the timeout has + * expired. Otherwise return to attempt to take the semaphore that is + * known to be available. As semaphores are implemented by queues the + * queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + #if ( configUSE_MUTEXES == 1 ) + { + /* xInheritanceOccurred could only have be set if + * pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to + * test the mutex type again to check it is actually a mutex. */ + if( xInheritanceOccurred != pdFALSE ) + { + taskENTER_CRITICAL(); + { + UBaseType_t uxHighestWaitingPriority; + + /* This task blocking on the mutex caused another + * task to inherit this task's priority. Now this task + * has timed out the priority should be disinherited + * again, but only as low as the next highest priority + * task that is waiting for the same mutex. */ + uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); + + /* vTaskPriorityDisinheritAfterTimeout uses the uxHighestWaitingPriority + * parameter to index pxReadyTasksLists when adding the task holding + * mutex to the ready list for its new priority. Coverity thinks that + * it can result in out-of-bounds access which is not true because + * uxHighestWaitingPriority, as returned by prvGetDisinheritPriorityAfterTimeout, + * is capped at ( configMAX_PRIORITIES - 1 ). */ + /* coverity[overrun] */ + vTaskPriorityDisinheritAfterTimeout( pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority ); + } + taskEXIT_CRITICAL(); + } + } + #endif /* configUSE_MUTEXES */ + + traceQUEUE_RECEIVE_FAILED( pxQueue ); + traceRETURN_xQueueSemaphoreTake( errQUEUE_EMPTY ); + + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueuePeek( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) +{ + BaseType_t xEntryTimeSet = pdFALSE; + TimeOut_t xTimeOut; + int8_t * pcOriginalReadPosition; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueuePeek( xQueue, pvBuffer, xTicksToWait ); + + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* The buffer into which data is received can only be NULL if the data size + * is zero (so no data is copied into the buffer. */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + for( ; ; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + * must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Remember the read position so it can be reset after the data + * is read from the queue as this function is only peeking the + * data, not removing it. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_PEEK( pxQueue ); + + /* The data is not being removed, so reset the read pointer. */ + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + + /* The data is being left in the queue, so see if there are + * any other tasks waiting for the data. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than this task. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + + traceRETURN_xQueuePeek( pdPASS ); + + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + * the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + + traceQUEUE_PEEK_FAILED( pxQueue ); + traceRETURN_xQueuePeek( errQUEUE_EMPTY ); + + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + * configure the timeout structure ready to enter the blocked + * state. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + * now that the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* Timeout has not expired yet, check to see if there is data in the + * queue now, and if not enter the Blocked state to wait for data. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + + if( xTaskResumeAll() == pdFALSE ) + { + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There is data in the queue now, so don't enter the blocked + * state, instead return to try and obtain the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. If there is still no data in the queue + * exit, otherwise go back and try to read the data again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_PEEK_FAILED( pxQueue ); + traceRETURN_xQueuePeek( errQUEUE_EMPTY ); + + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, + void * const pvBuffer, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueReceiveFromISR( xQueue, pvBuffer, pxHigherPriorityTaskWoken ); + + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = ( UBaseType_t ) taskENTER_CRITICAL_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Cannot block in an ISR, so check there is data available. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + const int8_t cRxLock = pxQueue->cRxLock; + + traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); + + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->uxMessagesWaiting = ( UBaseType_t ) ( uxMessagesWaiting - ( UBaseType_t ) 1 ); + + /* If the queue is locked the event list will not be modified. + * Instead update the lock count so the task that unlocks the queue + * will know that an ISR has removed data while the queue was + * locked. */ + if( cRxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than us so + * force a context switch. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Increment the lock count so the task that unlocks the queue + * knows that data was removed while it was locked. */ + prvIncrementQueueRxLock( pxQueue, cRxLock ); + } + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); + } + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xQueueReceiveFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, + void * const pvBuffer ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + int8_t * pcOriginalReadPosition; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueuePeekFromISR( xQueue, pvBuffer ); + + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = ( UBaseType_t ) taskENTER_CRITICAL_FROM_ISR(); + { + /* Cannot block in an ISR, so check there is data available. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + traceQUEUE_PEEK_FROM_ISR( pxQueue ); + + /* Remember the read position so it can be reset as nothing is + * actually being removed from the queue. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); + } + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xQueuePeekFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) +{ + UBaseType_t uxReturn; + + traceENTER_uxQueueMessagesWaiting( xQueue ); + + configASSERT( xQueue ); + + taskENTER_CRITICAL(); + { + uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); + + traceRETURN_uxQueueMessagesWaiting( uxReturn ); + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) +{ + UBaseType_t uxReturn; + Queue_t * const pxQueue = xQueue; + + traceENTER_uxQueueSpacesAvailable( xQueue ); + + configASSERT( pxQueue ); + + taskENTER_CRITICAL(); + { + uxReturn = ( UBaseType_t ) ( pxQueue->uxLength - pxQueue->uxMessagesWaiting ); + } + taskEXIT_CRITICAL(); + + traceRETURN_uxQueueSpacesAvailable( uxReturn ); + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) +{ + UBaseType_t uxReturn; + Queue_t * const pxQueue = xQueue; + + traceENTER_uxQueueMessagesWaitingFromISR( xQueue ); + + configASSERT( pxQueue ); + uxReturn = pxQueue->uxMessagesWaiting; + + traceRETURN_uxQueueMessagesWaitingFromISR( uxReturn ); + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +void vQueueDelete( QueueHandle_t xQueue ) +{ + Queue_t * const pxQueue = xQueue; + + traceENTER_vQueueDelete( xQueue ); + + configASSERT( pxQueue ); + traceQUEUE_DELETE( pxQueue ); + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + vQueueUnregisterQueue( pxQueue ); + } + #endif + + #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The queue can only have been allocated dynamically - free it + * again. */ + vPortFree( pxQueue ); + } + #elif ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The queue could have been allocated statically or dynamically, so + * check before attempting to free the memory. */ + if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxQueue ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else /* if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) */ + { + /* The queue must have been statically allocated, so is not going to be + * deleted. Avoid compiler warnings about the unused parameter. */ + ( void ) pxQueue; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + + traceRETURN_vQueueDelete(); +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) + { + traceENTER_uxQueueGetQueueNumber( xQueue ); + + traceRETURN_uxQueueGetQueueNumber( ( ( Queue_t * ) xQueue )->uxQueueNumber ); + + return ( ( Queue_t * ) xQueue )->uxQueueNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vQueueSetQueueNumber( QueueHandle_t xQueue, + UBaseType_t uxQueueNumber ) + { + traceENTER_vQueueSetQueueNumber( xQueue, uxQueueNumber ); + + ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; + + traceRETURN_vQueueSetQueueNumber(); + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) + { + traceENTER_ucQueueGetQueueType( xQueue ); + + traceRETURN_ucQueueGetQueueType( ( ( Queue_t * ) xQueue )->ucQueueType ); + + return ( ( Queue_t * ) xQueue )->ucQueueType; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueGetQueueItemSize( QueueHandle_t xQueue ) /* PRIVILEGED_FUNCTION */ +{ + traceENTER_uxQueueGetQueueItemSize( xQueue ); + + traceRETURN_uxQueueGetQueueItemSize( ( ( Queue_t * ) xQueue )->uxItemSize ); + + return ( ( Queue_t * ) xQueue )->uxItemSize; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueGetQueueLength( QueueHandle_t xQueue ) /* PRIVILEGED_FUNCTION */ +{ + traceENTER_uxQueueGetQueueLength( xQueue ); + + traceRETURN_uxQueueGetQueueLength( ( ( Queue_t * ) xQueue )->uxLength ); + + return ( ( Queue_t * ) xQueue )->uxLength; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) + { + UBaseType_t uxHighestPriorityOfWaitingTasks; + + /* If a task waiting for a mutex causes the mutex holder to inherit a + * priority, but the waiting task times out, then the holder should + * disinherit the priority - but only down to the highest priority of any + * other tasks that are waiting for the same mutex. For this purpose, + * return the priority of the highest priority task that is waiting for the + * mutex. */ + if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0U ) + { + uxHighestPriorityOfWaitingTasks = ( UBaseType_t ) ( ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ) ); + } + else + { + uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; + } + + return uxHighestPriorityOfWaitingTasks; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, + const void * pvItemToQueue, + const BaseType_t xPosition ) +{ + BaseType_t xReturn = pdFALSE; + UBaseType_t uxMessagesWaiting; + + /* This function is called from a critical section. */ + + uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + if( pxQueue->uxItemSize == ( UBaseType_t ) 0 ) + { + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* The mutex is no longer being held. */ + xReturn = xTaskPriorityDisinherit( pxQueue->u.xSemaphore.xMutexHolder ); + pxQueue->u.xSemaphore.xMutexHolder = NULL; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ + } + else if( xPosition == queueSEND_TO_BACK ) + { + ( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); + pxQueue->pcWriteTo += pxQueue->uxItemSize; + + if( pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->pcWriteTo = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + ( void ) memcpy( ( void * ) pxQueue->u.xQueue.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); + pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize; + + if( pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead ) + { + pxQueue->u.xQueue.pcReadFrom = ( pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xPosition == queueOVERWRITE ) + { + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* An item is not being added but overwritten, so subtract + * one from the recorded number of items in the queue so when + * one is added again below the number of recorded items remains + * correct. */ + --uxMessagesWaiting; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + pxQueue->uxMessagesWaiting = ( UBaseType_t ) ( uxMessagesWaiting + ( UBaseType_t ) 1 ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static void prvCopyDataFromQueue( Queue_t * const pxQueue, + void * const pvBuffer ) +{ + if( pxQueue->uxItemSize != ( UBaseType_t ) 0 ) + { + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); + } +} +/*-----------------------------------------------------------*/ + +static void prvUnlockQueue( Queue_t * const pxQueue ) +{ + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ + + /* The lock counts contains the number of extra data items placed or + * removed from the queue while the queue was locked. When a queue is + * locked items can be added or removed, but the event lists cannot be + * updated. */ + taskENTER_CRITICAL(); + { + int8_t cTxLock = pxQueue->cTxLock; + + /* See if data was added to the queue while it was locked. */ + while( cTxLock > queueLOCKED_UNMODIFIED ) + { + /* Data was posted while the queue was locked. Are any tasks + * blocked waiting for data to become available? */ + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting to + * the queue set caused a higher priority task to unblock. + * A context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Tasks that are removed from the event list will get + * added to the pending ready list as the scheduler is still + * suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + * context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + /* Tasks that are removed from the event list will get added to + * the pending ready list as the scheduler is still suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that + * a context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + #endif /* configUSE_QUEUE_SETS */ + + --cTxLock; + } + + pxQueue->cTxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); + + /* Do the same for the Rx lock. */ + taskENTER_CRITICAL(); + { + int8_t cRxLock = pxQueue->cRxLock; + + while( cRxLock > queueLOCKED_UNMODIFIED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --cRxLock; + } + else + { + break; + } + } + + pxQueue->cRxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvIsQueueEmpty( const Queue_t * pxQueue ) +{ + BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) +{ + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueIsQueueEmptyFromISR( xQueue ); + + configASSERT( pxQueue ); + + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + traceRETURN_xQueueIsQueueEmptyFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvIsQueueFull( const Queue_t * pxQueue ) +{ + BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) +{ + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueIsQueueFullFromISR( xQueue ); + + configASSERT( pxQueue ); + + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + traceRETURN_xQueueIsQueueFullFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRSend( QueueHandle_t xQueue, + const void * pvItemToQueue, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueCRSend( xQueue, pvItemToQueue, xTicksToWait ); + + /* If the queue is already full we may have to block. A critical section + * is required to prevent an interrupt removing something from the queue + * between the check to see if the queue is full and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + /* The queue is full - do we want to block or just leave without + * posting? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is called from a coroutine we cannot block directly, but + * return indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + } + portENABLE_INTERRUPTS(); + + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + /* There is room in the queue, copy the data into the queue. */ + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + xReturn = pdPASS; + + /* Were any co-routines waiting for data to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + * into the ready list as we are within a critical section. + * Instead the same pending ready list mechanism is used as if + * the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The co-routine waiting has a higher priority so record + * that a yield might be appropriate. */ + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = errQUEUE_FULL; + } + } + portENABLE_INTERRUPTS(); + + traceRETURN_xQueueCRSend( xReturn ); + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRReceive( QueueHandle_t xQueue, + void * pvBuffer, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueCRReceive( xQueue, pvBuffer, xTicksToWait ); + + /* If the queue is already empty we may have to block. A critical section + * is required to prevent an interrupt adding something to the queue + * between the check to see if the queue is empty and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + /* There are no messages in the queue, do we want to block or just + * leave with nothing? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is a co-routine we cannot block directly, but return + * indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portENABLE_INTERRUPTS(); + + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data is available from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --( pxQueue->uxMessagesWaiting ); + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + + xReturn = pdPASS; + + /* Were any co-routines waiting for space to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + * into the ready list as we are within a critical section. + * Instead the same pending ready list mechanism is used as if + * the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = pdFAIL; + } + } + portENABLE_INTERRUPTS(); + + traceRETURN_xQueueCRReceive( xReturn ); + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, + const void * pvItemToQueue, + BaseType_t xCoRoutinePreviouslyWoken ) + { + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueCRSendFromISR( xQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ); + + /* Cannot block within an ISR so if there is no space on the queue then + * exit without doing anything. */ + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + + /* We only want to wake one co-routine per ISR, so check that a + * co-routine has not already been woken. */ + if( xCoRoutinePreviouslyWoken == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + return pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xQueueCRSendFromISR( xCoRoutinePreviouslyWoken ); + + return xCoRoutinePreviouslyWoken; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, + void * pvBuffer, + BaseType_t * pxCoRoutineWoken ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + traceENTER_xQueueCRReceiveFromISR( xQueue, pvBuffer, pxCoRoutineWoken ); + + /* We cannot block from an ISR, so check there is data available. If + * not then just leave without doing anything. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Copy the data from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --( pxQueue->uxMessagesWaiting ); + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + + if( ( *pxCoRoutineWoken ) == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + *pxCoRoutineWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + + traceRETURN_xQueueCRReceiveFromISR( xReturn ); + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + void vQueueAddToRegistry( QueueHandle_t xQueue, + const char * pcQueueName ) + { + UBaseType_t ux; + QueueRegistryItem_t * pxEntryToWrite = NULL; + + traceENTER_vQueueAddToRegistry( xQueue, pcQueueName ); + + configASSERT( xQueue ); + + if( pcQueueName != NULL ) + { + /* See if there is an empty space in the registry. A NULL name denotes + * a free slot. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + /* Replace an existing entry if the queue is already in the registry. */ + if( xQueue == xQueueRegistry[ ux ].xHandle ) + { + pxEntryToWrite = &( xQueueRegistry[ ux ] ); + break; + } + /* Otherwise, store in the next empty location */ + else if( ( pxEntryToWrite == NULL ) && ( xQueueRegistry[ ux ].pcQueueName == NULL ) ) + { + pxEntryToWrite = &( xQueueRegistry[ ux ] ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + + if( pxEntryToWrite != NULL ) + { + /* Store the information on this queue. */ + pxEntryToWrite->pcQueueName = pcQueueName; + pxEntryToWrite->xHandle = xQueue; + + traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ); + } + + traceRETURN_vQueueAddToRegistry(); + } + +#endif /* configQUEUE_REGISTRY_SIZE */ +/*-----------------------------------------------------------*/ + +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + const char * pcQueueGetName( QueueHandle_t xQueue ) + { + UBaseType_t ux; + const char * pcReturn = NULL; + + traceENTER_pcQueueGetName( xQueue ); + + configASSERT( xQueue ); + + /* Note there is nothing here to protect against another task adding or + * removing entries from the registry while it is being searched. */ + + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].xHandle == xQueue ) + { + pcReturn = xQueueRegistry[ ux ].pcQueueName; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + traceRETURN_pcQueueGetName( pcReturn ); + + return pcReturn; + } + +#endif /* configQUEUE_REGISTRY_SIZE */ +/*-----------------------------------------------------------*/ + +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + void vQueueUnregisterQueue( QueueHandle_t xQueue ) + { + UBaseType_t ux; + + traceENTER_vQueueUnregisterQueue( xQueue ); + + configASSERT( xQueue ); + + /* See if the handle of the queue being unregistered in actually in the + * registry. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].xHandle == xQueue ) + { + /* Set the name to NULL to show that this slot if free again. */ + xQueueRegistry[ ux ].pcQueueName = NULL; + + /* Set the handle to NULL to ensure the same queue handle cannot + * appear in the registry twice if it is added, removed, then + * added again. */ + xQueueRegistry[ ux ].xHandle = ( QueueHandle_t ) 0; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + traceRETURN_vQueueUnregisterQueue(); + } + +#endif /* configQUEUE_REGISTRY_SIZE */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TIMERS == 1 ) + + void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, + TickType_t xTicksToWait, + const BaseType_t xWaitIndefinitely ) + { + Queue_t * const pxQueue = xQueue; + + traceENTER_vQueueWaitForMessageRestricted( xQueue, xTicksToWait, xWaitIndefinitely ); + + /* This function should not be called by application code hence the + * 'Restricted' in its name. It is not part of the public API. It is + * designed for use by kernel code, and has special calling requirements. + * It can result in vListInsert() being called on a list that can only + * possibly ever have one item in it, so the list will be fast, but even + * so it should be called with the scheduler locked and not from a critical + * section. */ + + /* Only do anything if there are no messages in the queue. This function + * will not actually cause the task to block, just place it on a blocked + * list. It will not block until the scheduler is unlocked - at which + * time a yield will be performed. If an item is added to the queue while + * the queue is locked, and the calling task blocks on the queue, then the + * calling task will be immediately unblocked when the queue is unlocked. */ + prvLockQueue( pxQueue ); + + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U ) + { + /* There is nothing in the queue, block for the specified period. */ + vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait, xWaitIndefinitely ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + prvUnlockQueue( pxQueue ); + + traceRETURN_vQueueWaitForMessageRestricted(); + } + +#endif /* configUSE_TIMERS */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) + { + QueueSetHandle_t pxQueue; + + traceENTER_xQueueCreateSet( uxEventQueueLength ); + + pxQueue = xQueueGenericCreate( uxEventQueueLength, ( UBaseType_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET ); + + traceRETURN_xQueueCreateSet( pxQueue ); + + return pxQueue; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) + { + BaseType_t xReturn; + + traceENTER_xQueueAddToSet( xQueueOrSemaphore, xQueueSet ); + + taskENTER_CRITICAL(); + { + if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ) + { + /* Cannot add a queue/semaphore to more than one queue set. */ + xReturn = pdFAIL; + } + else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 ) + { + /* Cannot add a queue/semaphore to a queue set if there are already + * items in the queue/semaphore. */ + xReturn = pdFAIL; + } + else + { + ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet; + xReturn = pdPASS; + } + } + taskEXIT_CRITICAL(); + + traceRETURN_xQueueAddToSet( xReturn ); + + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) + { + BaseType_t xReturn; + Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore; + + traceENTER_xQueueRemoveFromSet( xQueueOrSemaphore, xQueueSet ); + + if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ) + { + /* The queue was not a member of the set. */ + xReturn = pdFAIL; + } + else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 ) + { + /* It is dangerous to remove a queue from a set when the queue is + * not empty because the queue set will still hold pending events for + * the queue. */ + xReturn = pdFAIL; + } + else + { + taskENTER_CRITICAL(); + { + /* The queue is no longer contained in the set. */ + pxQueueOrSemaphore->pxQueueSetContainer = NULL; + } + taskEXIT_CRITICAL(); + xReturn = pdPASS; + } + + traceRETURN_xQueueRemoveFromSet( xReturn ); + + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, + TickType_t const xTicksToWait ) + { + QueueSetMemberHandle_t xReturn = NULL; + + traceENTER_xQueueSelectFromSet( xQueueSet, xTicksToWait ); + + ( void ) xQueueReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait ); + + traceRETURN_xQueueSelectFromSet( xReturn ); + + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) + { + QueueSetMemberHandle_t xReturn = NULL; + + traceENTER_xQueueSelectFromSetFromISR( xQueueSet ); + + ( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); + + traceRETURN_xQueueSelectFromSetFromISR( xReturn ); + + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue ) + { + Queue_t * pxQueueSetContainer = pxQueue->pxQueueSetContainer; + BaseType_t xReturn = pdFALSE; + + /* This function must be called form a critical section. */ + + /* The following line is not reachable in unit tests because every call + * to prvNotifyQueueSetContainer is preceded by a check that + * pxQueueSetContainer != NULL */ + configASSERT( pxQueueSetContainer ); /* LCOV_EXCL_BR_LINE */ + configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ); + + if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ) + { + const int8_t cTxLock = pxQueueSetContainer->cTxLock; + + traceQUEUE_SET_SEND( pxQueueSetContainer ); + + /* The data copied is the handle of the queue that contains data. */ + xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, queueSEND_TO_BACK ); + + if( cTxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + prvIncrementQueueTxLock( pxQueueSetContainer, cTxLock ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/stream_buffer.c b/source/Middlewares/Third_Party/FreeRTOS/Source/stream_buffer.c index 8482e68fe..6decfed6f 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/stream_buffer.c +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/stream_buffer.c @@ -1,1326 +1,1718 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -/* Standard includes. */ -#include -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining - * all the API functions to use the MPU wrappers. That should only be done when - * task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -/* FreeRTOS includes. */ -#include "FreeRTOS.h" -#include "task.h" -#include "stream_buffer.h" - -#if ( configUSE_TASK_NOTIFICATIONS != 1 ) - #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c -#endif - -/* Lint e961, e9021 and e750 are suppressed as a MISRA exception justified - * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined - * for the header files above, but not in this file, in order to generate the - * correct privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ - -/* If the user has not provided application specific Rx notification macros, - * or #defined the notification macros away, them provide default implementations - * that uses task notifications. */ -/*lint -save -e9026 Function like macros allowed and needed here so they can be overridden. */ -#ifndef sbRECEIVE_COMPLETED - #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ - vTaskSuspendAll(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ - { \ - ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \ - ( uint32_t ) 0, \ - eNoAction ); \ - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ - } \ - } \ - ( void ) xTaskResumeAll(); -#endif /* sbRECEIVE_COMPLETED */ - -#ifndef sbRECEIVE_COMPLETED_FROM_ISR - #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ - pxHigherPriorityTaskWoken ) \ - { \ - UBaseType_t uxSavedInterruptStatus; \ - \ - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ - { \ - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ - ( uint32_t ) 0, \ - eNoAction, \ - pxHigherPriorityTaskWoken ); \ - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ - } \ - } \ - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ - } -#endif /* sbRECEIVE_COMPLETED_FROM_ISR */ - -/* If the user has not provided an application specific Tx notification macro, - * or #defined the notification macro away, them provide a default implementation - * that uses task notifications. */ -#ifndef sbSEND_COMPLETED - #define sbSEND_COMPLETED( pxStreamBuffer ) \ - vTaskSuspendAll(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ - { \ - ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \ - ( uint32_t ) 0, \ - eNoAction ); \ - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ - } \ - } \ - ( void ) xTaskResumeAll(); -#endif /* sbSEND_COMPLETED */ - -#ifndef sbSEND_COMPLETE_FROM_ISR - #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ - { \ - UBaseType_t uxSavedInterruptStatus; \ - \ - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ - { \ - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ - ( uint32_t ) 0, \ - eNoAction, \ - pxHigherPriorityTaskWoken ); \ - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ - } \ - } \ - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ - } -#endif /* sbSEND_COMPLETE_FROM_ISR */ -/*lint -restore (9026) */ - -/* The number of bytes used to hold the length of a message in the buffer. */ -#define sbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) ) - -/* Bits stored in the ucFlags field of the stream buffer. */ -#define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ -#define sbFLAGS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */ - -/*-----------------------------------------------------------*/ - -/* Structure that hold state information on the buffer. */ -typedef struct StreamBufferDef_t /*lint !e9058 Style convention uses tag. */ -{ - volatile size_t xTail; /* Index to the next item to read within the buffer. */ - volatile size_t xHead; /* Index to the next item to write within the buffer. */ - size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ - size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ - volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ - volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ - uint8_t * pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ - uint8_t ucFlags; - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */ - #endif -} StreamBuffer_t; - -/* - * The number of bytes available to be read from the buffer. - */ -static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) PRIVILEGED_FUNCTION; - -/* - * Add xCount bytes from pucData into the pxStreamBuffer message buffer. - * Returns the number of bytes written, which will either equal xCount in the - * success case, or 0 if there was not enough space in the buffer (in which case - * no data is written into the buffer). - */ -static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, - const uint8_t * pucData, - size_t xCount ) PRIVILEGED_FUNCTION; - -/* - * If the stream buffer is being used as a message buffer, then reads an entire - * message out of the buffer. If the stream buffer is being used as a stream - * buffer then read as many bytes as possible from the buffer. - * prvReadBytesFromBuffer() is called to actually extract the bytes from the - * buffer's data storage area. - */ -static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer, - void * pvRxData, - size_t xBufferLengthBytes, - size_t xBytesAvailable, - size_t xBytesToStoreMessageLength ) PRIVILEGED_FUNCTION; - -/* - * If the stream buffer is being used as a message buffer, then writes an entire - * message to the buffer. If the stream buffer is being used as a stream - * buffer then write as many bytes as possible to the buffer. - * prvWriteBytestoBuffer() is called to actually send the bytes to the buffer's - * data storage area. - */ -static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - size_t xSpace, - size_t xRequiredSpace ) PRIVILEGED_FUNCTION; - -/* - * Read xMaxCount bytes from the pxStreamBuffer message buffer and write them - * to pucData. - */ -static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer, - uint8_t * pucData, - size_t xMaxCount, - size_t xBytesAvailable ) PRIVILEGED_FUNCTION; - -/* - * Called by both pxStreamBufferCreate() and pxStreamBufferCreateStatic() to - * initialise the members of the newly created stream buffer structure. - */ -static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, - uint8_t * const pucBuffer, - size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - uint8_t ucFlags ) PRIVILEGED_FUNCTION; - -/*-----------------------------------------------------------*/ - -#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - - StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer ) - { - uint8_t * pucAllocatedMemory; - uint8_t ucFlags; - - /* In case the stream buffer is going to be used as a message buffer - * (that is, it will hold discrete messages with a little meta data that - * says how big the next message is) check the buffer will be large enough - * to hold at least one message. */ - if( xIsMessageBuffer == pdTRUE ) - { - /* Is a message buffer but not statically allocated. */ - ucFlags = sbFLAGS_IS_MESSAGE_BUFFER; - configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); - } - else - { - /* Not a message buffer and not statically allocated. */ - ucFlags = 0; - configASSERT( xBufferSizeBytes > 0 ); - } - - configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); - - /* A trigger level of 0 would cause a waiting task to unblock even when - * the buffer was empty. */ - if( xTriggerLevelBytes == ( size_t ) 0 ) - { - xTriggerLevelBytes = ( size_t ) 1; - } - - /* A stream buffer requires a StreamBuffer_t structure and a buffer. - * Both are allocated in a single call to pvPortMalloc(). The - * StreamBuffer_t structure is placed at the start of the allocated memory - * and the buffer follows immediately after. The requested size is - * incremented so the free space is returned as the user would expect - - * this is a quirk of the implementation that means otherwise the free - * space would be reported as one byte smaller than would be logically - * expected. */ - xBufferSizeBytes++; - pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ - - if( pucAllocatedMemory != NULL ) - { - prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ - pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ - xBufferSizeBytes, - xTriggerLevelBytes, - ucFlags ); - - traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); - } - else - { - traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); - } - - return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ - } - -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - - StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer, - uint8_t * const pucStreamBufferStorageArea, - StaticStreamBuffer_t * const pxStaticStreamBuffer ) - { - StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as StaticStreamBuffer_t is opaque Streambuffer_t. */ - StreamBufferHandle_t xReturn; - uint8_t ucFlags; - - configASSERT( pucStreamBufferStorageArea ); - configASSERT( pxStaticStreamBuffer ); - configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); - - /* A trigger level of 0 would cause a waiting task to unblock even when - * the buffer was empty. */ - if( xTriggerLevelBytes == ( size_t ) 0 ) - { - xTriggerLevelBytes = ( size_t ) 1; - } - - if( xIsMessageBuffer != pdFALSE ) - { - /* Statically allocated message buffer. */ - ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; - } - else - { - /* Statically allocated stream buffer. */ - ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED; - } - - /* In case the stream buffer is going to be used as a message buffer - * (that is, it will hold discrete messages with a little meta data that - * says how big the next message is) check the buffer will be large enough - * to hold at least one message. */ - configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); - - #if ( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - * variable of type StaticStreamBuffer_t equals the size of the real - * message buffer structure. */ - volatile size_t xSize = sizeof( StaticStreamBuffer_t ); - configASSERT( xSize == sizeof( StreamBuffer_t ) ); - } /*lint !e529 xSize is referenced is configASSERT() is defined. */ - #endif /* configASSERT_DEFINED */ - - if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) - { - prvInitialiseNewStreamBuffer( pxStreamBuffer, - pucStreamBufferStorageArea, - xBufferSizeBytes, - xTriggerLevelBytes, - ucFlags ); - - /* Remember this was statically allocated in case it is ever deleted - * again. */ - pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; - - traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); - - xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ - } - else - { - xReturn = NULL; - traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); - } - - return xReturn; - } - -#endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ -/*-----------------------------------------------------------*/ - -void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) -{ - StreamBuffer_t * pxStreamBuffer = xStreamBuffer; - - configASSERT( pxStreamBuffer ); - - traceSTREAM_BUFFER_DELETE( xStreamBuffer ); - - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) - { - #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Both the structure and the buffer were allocated using a single call - * to pvPortMalloc(), hence only one call to vPortFree() is required. */ - vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */ - } - #else - { - /* Should not be possible to get here, ucFlags must be corrupt. - * Force an assert. */ - configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 ); - } - #endif - } - else - { - /* The structure and buffer were not allocated dynamically and cannot be - * freed - just scrub the structure so future use will assert. */ - ( void ) memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); - } -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) -{ - StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - BaseType_t xReturn = pdFAIL; - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxStreamBufferNumber; - #endif - - configASSERT( pxStreamBuffer ); - - #if ( configUSE_TRACE_FACILITY == 1 ) - { - /* Store the stream buffer number so it can be restored after the - * reset. */ - uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; - } - #endif - - /* Can only reset a message buffer if there are no tasks blocked on it. */ - taskENTER_CRITICAL(); - { - if( pxStreamBuffer->xTaskWaitingToReceive == NULL ) - { - if( pxStreamBuffer->xTaskWaitingToSend == NULL ) - { - prvInitialiseNewStreamBuffer( pxStreamBuffer, - pxStreamBuffer->pucBuffer, - pxStreamBuffer->xLength, - pxStreamBuffer->xTriggerLevelBytes, - pxStreamBuffer->ucFlags ); - xReturn = pdPASS; - - #if ( configUSE_TRACE_FACILITY == 1 ) - { - pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; - } - #endif - - traceSTREAM_BUFFER_RESET( xStreamBuffer ); - } - } - } - taskEXIT_CRITICAL(); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, - size_t xTriggerLevel ) -{ - StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - BaseType_t xReturn; - - configASSERT( pxStreamBuffer ); - - /* It is not valid for the trigger level to be 0. */ - if( xTriggerLevel == ( size_t ) 0 ) - { - xTriggerLevel = ( size_t ) 1; - } - - /* The trigger level is the number of bytes that must be in the stream - * buffer before a task that is waiting for data is unblocked. */ - if( xTriggerLevel <= pxStreamBuffer->xLength ) - { - pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; - xReturn = pdPASS; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) -{ - const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - size_t xSpace; - - configASSERT( pxStreamBuffer ); - - xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail; - xSpace -= pxStreamBuffer->xHead; - xSpace -= ( size_t ) 1; - - if( xSpace >= pxStreamBuffer->xLength ) - { - xSpace -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xSpace; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) -{ - const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - size_t xReturn; - - configASSERT( pxStreamBuffer ); - - xReturn = prvBytesInBuffer( pxStreamBuffer ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - TickType_t xTicksToWait ) -{ - StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - size_t xReturn, xSpace = 0; - size_t xRequiredSpace = xDataLengthBytes; - TimeOut_t xTimeOut; - - /* Having a 'isFeasible' variable allows to respect the convention that there is only a return statement at the end. Othewise, return - * could be done as soon as we realise the send cannot happen. We will let the call to 'prvWriteMessageToBuffer' dealing with this scenario. */ - BaseType_t xIsFeasible; - - configASSERT( pvTxData ); - configASSERT( pxStreamBuffer ); - - /* This send function is used to write to both message buffers and stream - * buffers. If this is a message buffer then the space needed must be - * increased by the amount of bytes needed to store the length of the - * message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; - - /* Overflow? */ - configASSERT( xRequiredSpace > xDataLengthBytes ); - - /* In the case of the message buffer, one has to be able to write the complete message as opposed to - * a stream buffer for semantic reasons. Check if it is physically possible to write the message given - * the length of the buffer. */ - if( xRequiredSpace > pxStreamBuffer->xLength ) - { - /* The message could never be written because it is greater than the buffer length. - * By setting xIsFeasable to FALSE, we skip over the following do..while loop, thus avoiding - * a deadlock. The call to 'prvWriteMessageToBuffer' toward the end of this function with - * xRequiredSpace greater than xSpace will suffice in not writing anything to the internal buffer. - * Now, the function will return 0 because the message could not be written. Should an error code be - * returned instead ??? In my opinion, probably.. But the return type doesn't allow for negative - * values to be returned. A confusion could exist to the caller. Returning 0 because a timeout occurred - * and a subsequent send attempts could eventually succeed, and returning 0 because a write could never - * happen because of the size are two scenarios to me :/ */ - xIsFeasible = pdFALSE; - } - else - { - /* It is possible to write the message completely in the buffer. This is the intended route. - * Let's continue with the regular timeout logic. */ - xIsFeasible = pdTRUE; - } - } - else - { - /* In the case of the stream buffer, not being able to completely write the message in the buffer - * is an acceptable scenario, but it has to be dealt with properly */ - if( xRequiredSpace > pxStreamBuffer->xLength ) - { - /* Not enough buffer space. We will attempt to write as much as we can in this run - * so that the caller can send the remaining in subsequent calls. We avoid a deadlock by - * offering the possibility to take the 'else' branch in the 'if( xSpace < xRequiredSpace )' - * condition inside the following do..while loop */ - xRequiredSpace = pxStreamBuffer->xLength; - - /* TODO FIXME: Is there a check we should do with the xTriggerLevelBytes value ? */ - - /* With the adjustment to 'xRequiredSpace', the deadlock is avoided, thus it's now feasible. */ - xIsFeasible = pdTRUE; - } - else - { - /* It is possible to write the message completely in the buffer. */ - xIsFeasible = pdTRUE; - } - } - - /* Added check against xIsFeasible. If it's not feasible, don't even wait for notification, let the call to 'prvWriteMessageToBuffer' do nothing and return 0 */ - if( ( xTicksToWait != ( TickType_t ) 0 ) && ( xIsFeasible == pdTRUE ) ) - { - vTaskSetTimeOutState( &xTimeOut ); - - do - { - /* Wait until the required number of bytes are free in the message - * buffer. */ - taskENTER_CRITICAL(); - { - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - - if( xSpace < xRequiredSpace ) - { - /* Clear notification state as going to wait for space. */ - ( void ) xTaskNotifyStateClear( NULL ); - - /* Should only be one writer. */ - configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); - pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle(); - } - else - { - taskEXIT_CRITICAL(); - break; - } - } - taskEXIT_CRITICAL(); - - traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); - ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); - pxStreamBuffer->xTaskWaitingToSend = NULL; - } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( xSpace == ( size_t ) 0 ) - { - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); - - if( xReturn > ( size_t ) 0 ) - { - traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); - - /* Was a task waiting for the data? */ - if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) - { - sbSEND_COMPLETED( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) -{ - StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - size_t xReturn, xSpace; - size_t xRequiredSpace = xDataLengthBytes; - - configASSERT( pvTxData ); - configASSERT( pxStreamBuffer ); - - /* This send function is used to write to both message buffers and stream - * buffers. If this is a message buffer then the space needed must be - * increased by the amount of bytes needed to store the length of the - * message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); - - if( xReturn > ( size_t ) 0 ) - { - /* Was a task waiting for the data? */ - if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) - { - sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - size_t xSpace, - size_t xRequiredSpace ) -{ - BaseType_t xShouldWrite; - size_t xReturn; - - if( xSpace == ( size_t ) 0 ) - { - /* Doesn't matter if this is a stream buffer or a message buffer, there - * is no space to write. */ - xShouldWrite = pdFALSE; - } - else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) == ( uint8_t ) 0 ) - { - /* This is a stream buffer, as opposed to a message buffer, so writing a - * stream of bytes rather than discrete messages. Write as many bytes as - * possible. */ - xShouldWrite = pdTRUE; - xDataLengthBytes = configMIN( xDataLengthBytes, xSpace ); - } - else if( xSpace >= xRequiredSpace ) - { - /* This is a message buffer, as opposed to a stream buffer, and there - * is enough space to write both the message length and the message itself - * into the buffer. Start by writing the length of the data, the data - * itself will be written later in this function. */ - xShouldWrite = pdTRUE; - ( void ) prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH ); - } - else - { - /* There is space available, but not enough space. */ - xShouldWrite = pdFALSE; - } - - if( xShouldWrite != pdFALSE ) - { - /* Writes the data itself. */ - xReturn = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alignment and access. */ - } - else - { - xReturn = 0; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, - void * pvRxData, - size_t xBufferLengthBytes, - TickType_t xTicksToWait ) -{ - StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; - - configASSERT( pvRxData ); - configASSERT( pxStreamBuffer ); - - /* This receive function is used by both message buffers, which store - * discrete messages, and stream buffers, which store a continuous stream of - * bytes. Discrete messages include an additional - * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the - * message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } - - if( xTicksToWait != ( TickType_t ) 0 ) - { - /* Checking if there is data and clearing the notification state must be - * performed atomically. */ - taskENTER_CRITICAL(); - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - - /* If this function was invoked by a message buffer read then - * xBytesToStoreMessageLength holds the number of bytes used to hold - * the length of the next discrete message. If this function was - * invoked by a stream buffer read then xBytesToStoreMessageLength will - * be 0. */ - if( xBytesAvailable <= xBytesToStoreMessageLength ) - { - /* Clear notification state as going to wait for data. */ - ( void ) xTaskNotifyStateClear( NULL ); - - /* Should only be one reader. */ - configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); - pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - if( xBytesAvailable <= xBytesToStoreMessageLength ) - { - /* Wait for data to be available. */ - traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ); - ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); - pxStreamBuffer->xTaskWaitingToReceive = NULL; - - /* Recheck the data available after blocking. */ - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - } - - /* Whether receiving a discrete message (where xBytesToStoreMessageLength - * holds the number of bytes used to store the message length) or a stream of - * bytes (where xBytesToStoreMessageLength is zero), the number of bytes - * available must be greater than xBytesToStoreMessageLength to be able to - * read bytes from the buffer. */ - if( xBytesAvailable > xBytesToStoreMessageLength ) - { - xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); - - /* Was a task waiting for space in the buffer? */ - if( xReceivedLength != ( size_t ) 0 ) - { - traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ); - sbRECEIVE_COMPLETED( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ); - mtCOVERAGE_TEST_MARKER(); - } - - return xReceivedLength; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) -{ - StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - size_t xReturn, xBytesAvailable, xOriginalTail; - configMESSAGE_BUFFER_LENGTH_TYPE xTempReturn; - - configASSERT( pxStreamBuffer ); - - /* Ensure the stream buffer is being used as a message buffer. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - - if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH ) - { - /* The number of bytes available is greater than the number of bytes - * required to hold the length of the next message, so another message - * is available. Return its length without removing the length bytes - * from the buffer. A copy of the tail is stored so the buffer can be - * returned to its prior state as the message is not actually being - * removed from the buffer. */ - xOriginalTail = pxStreamBuffer->xTail; - ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, xBytesAvailable ); - xReturn = ( size_t ) xTempReturn; - pxStreamBuffer->xTail = xOriginalTail; - } - else - { - /* The minimum amount of bytes in a message buffer is - * ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is - * less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid - * value is 0. */ - configASSERT( xBytesAvailable == 0 ); - xReturn = 0; - } - } - else - { - xReturn = 0; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, - void * pvRxData, - size_t xBufferLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) -{ - StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; - - configASSERT( pvRxData ); - configASSERT( pxStreamBuffer ); - - /* This receive function is used by both message buffers, which store - * discrete messages, and stream buffers, which store a continuous stream of - * bytes. Discrete messages include an additional - * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the - * message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } - - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - - /* Whether receiving a discrete message (where xBytesToStoreMessageLength - * holds the number of bytes used to store the message length) or a stream of - * bytes (where xBytesToStoreMessageLength is zero), the number of bytes - * available must be greater than xBytesToStoreMessageLength to be able to - * read bytes from the buffer. */ - if( xBytesAvailable > xBytesToStoreMessageLength ) - { - xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); - - /* Was a task waiting for space in the buffer? */ - if( xReceivedLength != ( size_t ) 0 ) - { - sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ); - - return xReceivedLength; -} -/*-----------------------------------------------------------*/ - -static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer, - void * pvRxData, - size_t xBufferLengthBytes, - size_t xBytesAvailable, - size_t xBytesToStoreMessageLength ) -{ - size_t xOriginalTail, xReceivedLength, xNextMessageLength; - configMESSAGE_BUFFER_LENGTH_TYPE xTempNextMessageLength; - - if( xBytesToStoreMessageLength != ( size_t ) 0 ) - { - /* A discrete message is being received. First receive the length - * of the message. A copy of the tail is stored so the buffer can be - * returned to its prior state if the length of the message is too - * large for the provided buffer. */ - xOriginalTail = pxStreamBuffer->xTail; - ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, xBytesToStoreMessageLength, xBytesAvailable ); - xNextMessageLength = ( size_t ) xTempNextMessageLength; - - /* Reduce the number of bytes available by the number of bytes just - * read out. */ - xBytesAvailable -= xBytesToStoreMessageLength; - - /* Check there is enough space in the buffer provided by the - * user. */ - if( xNextMessageLength > xBufferLengthBytes ) - { - /* The user has provided insufficient space to read the message - * so return the buffer to its previous state (so the length of - * the message is in the buffer again). */ - pxStreamBuffer->xTail = xOriginalTail; - xNextMessageLength = 0; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* A stream of bytes is being received (as opposed to a discrete - * message), so read as many bytes as possible. */ - xNextMessageLength = xBufferLengthBytes; - } - - /* Read the actual data. */ - xReceivedLength = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xNextMessageLength, xBytesAvailable ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */ - - return xReceivedLength; -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) -{ - const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - BaseType_t xReturn; - size_t xTail; - - configASSERT( pxStreamBuffer ); - - /* True if no bytes are available. */ - xTail = pxStreamBuffer->xTail; - - if( pxStreamBuffer->xHead == xTail ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) -{ - BaseType_t xReturn; - size_t xBytesToStoreMessageLength; - const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - - configASSERT( pxStreamBuffer ); - - /* This generic version of the receive function is used by both message - * buffers, which store discrete messages, and stream buffers, which store a - * continuous stream of bytes. Discrete messages include an additional - * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } - - /* True if the available space equals zero. */ - if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, - BaseType_t * pxHigherPriorityTaskWoken ) -{ - StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - BaseType_t xReturn; - UBaseType_t uxSavedInterruptStatus; - - configASSERT( pxStreamBuffer ); - - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) - { - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, - ( uint32_t ) 0, - eNoAction, - pxHigherPriorityTaskWoken ); - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, - BaseType_t * pxHigherPriorityTaskWoken ) -{ - StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - BaseType_t xReturn; - UBaseType_t uxSavedInterruptStatus; - - configASSERT( pxStreamBuffer ); - - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) - { - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, - ( uint32_t ) 0, - eNoAction, - pxHigherPriorityTaskWoken ); - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, - const uint8_t * pucData, - size_t xCount ) -{ - size_t xNextHead, xFirstLength; - - configASSERT( xCount > ( size_t ) 0 ); - - xNextHead = pxStreamBuffer->xHead; - - /* Calculate the number of bytes that can be added in the first write - - * which may be less than the total number of bytes that need to be added if - * the buffer will wrap back to the beginning. */ - xFirstLength = configMIN( pxStreamBuffer->xLength - xNextHead, xCount ); - - /* Write as many bytes as can be written in the first write. */ - configASSERT( ( xNextHead + xFirstLength ) <= pxStreamBuffer->xLength ); - ( void ) memcpy( ( void * ) ( &( pxStreamBuffer->pucBuffer[ xNextHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - - /* If the number of bytes written was less than the number that could be - * written in the first write... */ - if( xCount > xFirstLength ) - { - /* ...then write the remaining bytes to the start of the buffer. */ - configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength ); - ( void ) memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xNextHead += xCount; - - if( xNextHead >= pxStreamBuffer->xLength ) - { - xNextHead -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - pxStreamBuffer->xHead = xNextHead; - - return xCount; -} -/*-----------------------------------------------------------*/ - -static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer, - uint8_t * pucData, - size_t xMaxCount, - size_t xBytesAvailable ) -{ - size_t xCount, xFirstLength, xNextTail; - - /* Use the minimum of the wanted bytes and the available bytes. */ - xCount = configMIN( xBytesAvailable, xMaxCount ); - - if( xCount > ( size_t ) 0 ) - { - xNextTail = pxStreamBuffer->xTail; - - /* Calculate the number of bytes that can be read - which may be - * less than the number wanted if the data wraps around to the start of - * the buffer. */ - xFirstLength = configMIN( pxStreamBuffer->xLength - xNextTail, xCount ); - - /* Obtain the number of bytes it is possible to obtain in the first - * read. Asserts check bounds of read and write. */ - configASSERT( xFirstLength <= xMaxCount ); - configASSERT( ( xNextTail + xFirstLength ) <= pxStreamBuffer->xLength ); - ( void ) memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xNextTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - - /* If the total number of wanted bytes is greater than the number - * that could be read in the first read... */ - if( xCount > xFirstLength ) - { - /*...then read the remaining bytes from the start of the buffer. */ - configASSERT( xCount <= xMaxCount ); - ( void ) memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Move the tail pointer to effectively remove the data read from - * the buffer. */ - xNextTail += xCount; - - if( xNextTail >= pxStreamBuffer->xLength ) - { - xNextTail -= pxStreamBuffer->xLength; - } - - pxStreamBuffer->xTail = xNextTail; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xCount; -} -/*-----------------------------------------------------------*/ - -static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) -{ -/* Returns the distance between xTail and xHead. */ - size_t xCount; - - xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead; - xCount -= pxStreamBuffer->xTail; - - if( xCount >= pxStreamBuffer->xLength ) - { - xCount -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xCount; -} -/*-----------------------------------------------------------*/ - -static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, - uint8_t * const pucBuffer, - size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - uint8_t ucFlags ) -{ - /* Assert here is deliberately writing to the entire buffer to ensure it can - * be written to without generating exceptions, and is setting the buffer to a - * known value to assist in development/debugging. */ - #if ( configASSERT_DEFINED == 1 ) - { - /* The value written just has to be identifiable when looking at the - * memory. Don't use 0xA5 as that is the stack fill value and could - * result in confusion as to what is actually being observed. */ - const BaseType_t xWriteValue = 0x55; - configASSERT( memset( pucBuffer, ( int ) xWriteValue, xBufferSizeBytes ) == pucBuffer ); - } /*lint !e529 !e438 xWriteValue is only used if configASSERT() is defined. */ - #endif - - ( void ) memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */ - pxStreamBuffer->pucBuffer = pucBuffer; - pxStreamBuffer->xLength = xBufferSizeBytes; - pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes; - pxStreamBuffer->ucFlags = ucFlags; -} - -#if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) - { - return xStreamBuffer->uxStreamBufferNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, - UBaseType_t uxStreamBufferNumber ) - { - xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) - { - return( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ); - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "stream_buffer.h" + +#if ( configUSE_TASK_NOTIFICATIONS != 1 ) + #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c +#endif + +#if ( INCLUDE_xTaskGetCurrentTaskHandle != 1 ) + #error INCLUDE_xTaskGetCurrentTaskHandle must be set to 1 to build stream_buffer.c +#endif + +/* The MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* This entire source file will be skipped if the application is not configured + * to include stream buffer functionality. This #if is closed at the very bottom + * of this file. If you want to include stream buffers then ensure + * configUSE_STREAM_BUFFERS is set to 1 in FreeRTOSConfig.h. */ +#if ( configUSE_STREAM_BUFFERS == 1 ) + +/* If the user has not provided application specific Rx notification macros, + * or #defined the notification macros away, then provide default implementations + * that uses task notifications. */ + #ifndef sbRECEIVE_COMPLETED + #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ + do \ + { \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotifyIndexed( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( pxStreamBuffer )->uxNotificationIndex, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); \ + } while( 0 ) + #endif /* sbRECEIVE_COMPLETED */ + +/* If user has provided a per-instance receive complete callback, then + * invoke the callback else use the receive complete macro which is provided by default for all instances. + */ + #if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + #define prvRECEIVE_COMPLETED( pxStreamBuffer ) \ + do { \ + if( ( pxStreamBuffer )->pxReceiveCompletedCallback != NULL ) \ + { \ + ( pxStreamBuffer )->pxReceiveCompletedCallback( ( pxStreamBuffer ), pdFALSE, NULL ); \ + } \ + else \ + { \ + sbRECEIVE_COMPLETED( ( pxStreamBuffer ) ); \ + } \ + } while( 0 ) + #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */ + #define prvRECEIVE_COMPLETED( pxStreamBuffer ) sbRECEIVE_COMPLETED( ( pxStreamBuffer ) ) + #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */ + + #ifndef sbRECEIVE_COMPLETED_FROM_ISR + #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ + pxHigherPriorityTaskWoken ) \ + do { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotifyIndexedFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( pxStreamBuffer )->uxNotificationIndex, \ + ( uint32_t ) 0, \ + eNoAction, \ + ( pxHigherPriorityTaskWoken ) ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); \ + } while( 0 ) + #endif /* sbRECEIVE_COMPLETED_FROM_ISR */ + + #if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + #define prvRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ + pxHigherPriorityTaskWoken ) \ + do { \ + if( ( pxStreamBuffer )->pxReceiveCompletedCallback != NULL ) \ + { \ + ( pxStreamBuffer )->pxReceiveCompletedCallback( ( pxStreamBuffer ), pdTRUE, ( pxHigherPriorityTaskWoken ) ); \ + } \ + else \ + { \ + sbRECEIVE_COMPLETED_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) ); \ + } \ + } while( 0 ) + #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */ + #define prvRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ + sbRECEIVE_COMPLETED_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) ) + #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */ + +/* If the user has not provided an application specific Tx notification macro, + * or #defined the notification macro away, then provide a default + * implementation that uses task notifications. + */ + #ifndef sbSEND_COMPLETED + #define sbSEND_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotifyIndexed( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( pxStreamBuffer )->uxNotificationIndex, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll() + #endif /* sbSEND_COMPLETED */ + +/* If user has provided a per-instance send completed callback, then + * invoke the callback else use the send complete macro which is provided by default for all instances. + */ + #if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + #define prvSEND_COMPLETED( pxStreamBuffer ) \ + do { \ + if( ( pxStreamBuffer )->pxSendCompletedCallback != NULL ) \ + { \ + ( pxStreamBuffer )->pxSendCompletedCallback( ( pxStreamBuffer ), pdFALSE, NULL ); \ + } \ + else \ + { \ + sbSEND_COMPLETED( ( pxStreamBuffer ) ); \ + } \ + } while( 0 ) + #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */ + #define prvSEND_COMPLETED( pxStreamBuffer ) sbSEND_COMPLETED( ( pxStreamBuffer ) ) + #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */ + + + #ifndef sbSEND_COMPLETE_FROM_ISR + #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ + do { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotifyIndexedFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( pxStreamBuffer )->uxNotificationIndex, \ + ( uint32_t ) 0, \ + eNoAction, \ + ( pxHigherPriorityTaskWoken ) ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); \ + } while( 0 ) + #endif /* sbSEND_COMPLETE_FROM_ISR */ + + + #if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + #define prvSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ + do { \ + if( ( pxStreamBuffer )->pxSendCompletedCallback != NULL ) \ + { \ + ( pxStreamBuffer )->pxSendCompletedCallback( ( pxStreamBuffer ), pdTRUE, ( pxHigherPriorityTaskWoken ) ); \ + } \ + else \ + { \ + sbSEND_COMPLETE_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) ); \ + } \ + } while( 0 ) + #else /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */ + #define prvSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ + sbSEND_COMPLETE_FROM_ISR( ( pxStreamBuffer ), ( pxHigherPriorityTaskWoken ) ) + #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */ + +/* The number of bytes used to hold the length of a message in the buffer. */ + #define sbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) ) + +/* Bits stored in the ucFlags field of the stream buffer. */ + #define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ + #define sbFLAGS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */ + #define sbFLAGS_IS_BATCHING_BUFFER ( ( uint8_t ) 4 ) /* Set if the stream buffer was created as a batching buffer, meaning the receiver task will only unblock when the trigger level exceededs. */ + +/*-----------------------------------------------------------*/ + +/* Structure that hold state information on the buffer. */ +typedef struct StreamBufferDef_t +{ + volatile size_t xTail; /* Index to the next item to read within the buffer. */ + volatile size_t xHead; /* Index to the next item to write within the buffer. */ + size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ + size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ + volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ + volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ + uint8_t * pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ + uint8_t ucFlags; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */ + #endif + + #if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + StreamBufferCallbackFunction_t pxSendCompletedCallback; /* Optional callback called on send complete. sbSEND_COMPLETED is called if this is NULL. */ + StreamBufferCallbackFunction_t pxReceiveCompletedCallback; /* Optional callback called on receive complete. sbRECEIVE_COMPLETED is called if this is NULL. */ + #endif + UBaseType_t uxNotificationIndex; /* The index we are using for notification, by default tskDEFAULT_INDEX_TO_NOTIFY. */ +} StreamBuffer_t; + +/* + * The number of bytes available to be read from the buffer. + */ +static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) PRIVILEGED_FUNCTION; + +/* + * Add xCount bytes from pucData into the pxStreamBuffer's data storage area. + * This function does not update the buffer's xHead pointer, so multiple writes + * may be chained together "atomically". This is useful for Message Buffers where + * the length and data bytes are written in two separate chunks, and we don't want + * the reader to see the buffer as having grown until after all data is copied over. + * This function takes a custom xHead value to indicate where to write to (necessary + * for chaining) and returns the the resulting xHead position. + * To mark the write as complete, manually set the buffer's xHead field with the + * returned xHead from this function. + */ +static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, + const uint8_t * pucData, + size_t xCount, + size_t xHead ) PRIVILEGED_FUNCTION; + +/* + * If the stream buffer is being used as a message buffer, then reads an entire + * message out of the buffer. If the stream buffer is being used as a stream + * buffer then read as many bytes as possible from the buffer. + * prvReadBytesFromBuffer() is called to actually extract the bytes from the + * buffer's data storage area. + */ +static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + size_t xBytesAvailable ) PRIVILEGED_FUNCTION; + +/* + * If the stream buffer is being used as a message buffer, then writes an entire + * message to the buffer. If the stream buffer is being used as a stream + * buffer then write as many bytes as possible to the buffer. + * prvWriteBytestoBuffer() is called to actually send the bytes to the buffer's + * data storage area. + */ +static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) PRIVILEGED_FUNCTION; + +/* + * Copies xCount bytes from the pxStreamBuffer's data storage area to pucData. + * This function does not update the buffer's xTail pointer, so multiple reads + * may be chained together "atomically". This is useful for Message Buffers where + * the length and data bytes are read in two separate chunks, and we don't want + * the writer to see the buffer as having more free space until after all data is + * copied over, especially if we have to abort the read due to insufficient receiving space. + * This function takes a custom xTail value to indicate where to read from (necessary + * for chaining) and returns the the resulting xTail position. + * To mark the read as complete, manually set the buffer's xTail field with the + * returned xTail from this function. + */ +static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer, + uint8_t * pucData, + size_t xCount, + size_t xTail ) PRIVILEGED_FUNCTION; + +/* + * Called by both pxStreamBufferCreate() and pxStreamBufferCreateStatic() to + * initialise the members of the newly created stream buffer structure. + */ +static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, + uint8_t * const pucBuffer, + size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t ucFlags, + StreamBufferCallbackFunction_t pxSendCompletedCallback, + StreamBufferCallbackFunction_t pxReceiveCompletedCallback ) PRIVILEGED_FUNCTION; + +/*-----------------------------------------------------------*/ + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xStreamBufferType, + StreamBufferCallbackFunction_t pxSendCompletedCallback, + StreamBufferCallbackFunction_t pxReceiveCompletedCallback ) + { + void * pvAllocatedMemory; + uint8_t ucFlags; + + traceENTER_xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, xStreamBufferType, pxSendCompletedCallback, pxReceiveCompletedCallback ); + + /* In case the stream buffer is going to be used as a message buffer + * (that is, it will hold discrete messages with a little meta data that + * says how big the next message is) check the buffer will be large enough + * to hold at least one message. */ + if( xStreamBufferType == sbTYPE_MESSAGE_BUFFER ) + { + /* Is a message buffer but not statically allocated. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER; + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + } + else if( xStreamBufferType == sbTYPE_STREAM_BATCHING_BUFFER ) + { + /* Is a batching buffer but not statically allocated. */ + ucFlags = sbFLAGS_IS_BATCHING_BUFFER; + configASSERT( xBufferSizeBytes > 0 ); + } + else + { + /* Not a message buffer and not statically allocated. */ + ucFlags = 0; + configASSERT( xBufferSizeBytes > 0 ); + } + + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + + /* A trigger level of 0 would cause a waiting task to unblock even when + * the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } + + /* A stream buffer requires a StreamBuffer_t structure and a buffer. + * Both are allocated in a single call to pvPortMalloc(). The + * StreamBuffer_t structure is placed at the start of the allocated memory + * and the buffer follows immediately after. The requested size is + * incremented so the free space is returned as the user would expect - + * this is a quirk of the implementation that means otherwise the free + * space would be reported as one byte smaller than would be logically + * expected. */ + if( xBufferSizeBytes < ( xBufferSizeBytes + 1U + sizeof( StreamBuffer_t ) ) ) + { + xBufferSizeBytes++; + pvAllocatedMemory = pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); + } + else + { + pvAllocatedMemory = NULL; + } + + if( pvAllocatedMemory != NULL ) + { + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pvAllocatedMemory, /* Structure at the start of the allocated memory. */ + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + ( ( uint8_t * ) pvAllocatedMemory ) + sizeof( StreamBuffer_t ), /* Storage area follows. */ + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags, + pxSendCompletedCallback, + pxReceiveCompletedCallback ); + + traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pvAllocatedMemory ), xStreamBufferType ); + } + else + { + traceSTREAM_BUFFER_CREATE_FAILED( xStreamBufferType ); + } + + traceRETURN_xStreamBufferGenericCreate( pvAllocatedMemory ); + + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + return ( StreamBufferHandle_t ) pvAllocatedMemory; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xStreamBufferType, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer, + StreamBufferCallbackFunction_t pxSendCompletedCallback, + StreamBufferCallbackFunction_t pxReceiveCompletedCallback ) + { + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; + StreamBufferHandle_t xReturn; + uint8_t ucFlags; + + traceENTER_xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, xStreamBufferType, pucStreamBufferStorageArea, pxStaticStreamBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback ); + + configASSERT( pucStreamBufferStorageArea ); + configASSERT( pxStaticStreamBuffer ); + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + + /* A trigger level of 0 would cause a waiting task to unblock even when + * the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } + + /* In case the stream buffer is going to be used as a message buffer + * (that is, it will hold discrete messages with a little meta data that + * says how big the next message is) check the buffer will be large enough + * to hold at least one message. */ + + if( xStreamBufferType == sbTYPE_MESSAGE_BUFFER ) + { + /* Statically allocated message buffer. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + } + else if( xStreamBufferType == sbTYPE_STREAM_BATCHING_BUFFER ) + { + /* Statically allocated batching buffer. */ + ucFlags = sbFLAGS_IS_BATCHING_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; + configASSERT( xBufferSizeBytes > 0 ); + } + else + { + /* Statically allocated stream buffer. */ + ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED; + } + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticStreamBuffer_t equals the size of the real + * message buffer structure. */ + volatile size_t xSize = sizeof( StaticStreamBuffer_t ); + configASSERT( xSize == sizeof( StreamBuffer_t ) ); + } + #endif /* configASSERT_DEFINED */ + + if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pucStreamBufferStorageArea, + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags, + pxSendCompletedCallback, + pxReceiveCompletedCallback ); + + /* Remember this was statically allocated in case it is ever deleted + * again. */ + pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; + + traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xStreamBufferType ); + + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; + } + else + { + xReturn = NULL; + traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xStreamBufferType ); + } + + traceRETURN_xStreamBufferGenericCreateStatic( xReturn ); + + return xReturn; + } + #endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + BaseType_t xStreamBufferGetStaticBuffers( StreamBufferHandle_t xStreamBuffer, + uint8_t ** ppucStreamBufferStorageArea, + StaticStreamBuffer_t ** ppxStaticStreamBuffer ) + { + BaseType_t xReturn; + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + + traceENTER_xStreamBufferGetStaticBuffers( xStreamBuffer, ppucStreamBufferStorageArea, ppxStaticStreamBuffer ); + + configASSERT( pxStreamBuffer ); + configASSERT( ppucStreamBufferStorageArea ); + configASSERT( ppxStaticStreamBuffer ); + + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) != ( uint8_t ) 0 ) + { + *ppucStreamBufferStorageArea = pxStreamBuffer->pucBuffer; + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + *ppxStaticStreamBuffer = ( StaticStreamBuffer_t * ) pxStreamBuffer; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + traceRETURN_xStreamBufferGetStaticBuffers( xReturn ); + + return xReturn; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) +{ + StreamBuffer_t * pxStreamBuffer = xStreamBuffer; + + traceENTER_vStreamBufferDelete( xStreamBuffer ); + + configASSERT( pxStreamBuffer ); + + traceSTREAM_BUFFER_DELETE( xStreamBuffer ); + + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) + { + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both the structure and the buffer were allocated using a single call + * to pvPortMalloc(), hence only one call to vPortFree() is required. */ + vPortFree( ( void * ) pxStreamBuffer ); + } + #else + { + /* Should not be possible to get here, ucFlags must be corrupt. + * Force an assert. */ + configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 ); + } + #endif + } + else + { + /* The structure and buffer were not allocated dynamically and cannot be + * freed - just scrub the structure so future use will assert. */ + ( void ) memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); + } + + traceRETURN_vStreamBufferDelete(); +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn = pdFAIL; + StreamBufferCallbackFunction_t pxSendCallback = NULL, pxReceiveCallback = NULL; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; + #endif + + traceENTER_xStreamBufferReset( xStreamBuffer ); + + configASSERT( pxStreamBuffer ); + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Store the stream buffer number so it can be restored after the + * reset. */ + uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; + } + #endif + + /* Can only reset a message buffer if there are no tasks blocked on it. */ + taskENTER_CRITICAL(); + { + if( ( pxStreamBuffer->xTaskWaitingToReceive == NULL ) && ( pxStreamBuffer->xTaskWaitingToSend == NULL ) ) + { + #if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + { + pxSendCallback = pxStreamBuffer->pxSendCompletedCallback; + pxReceiveCallback = pxStreamBuffer->pxReceiveCompletedCallback; + } + #endif + + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pxStreamBuffer->pucBuffer, + pxStreamBuffer->xLength, + pxStreamBuffer->xTriggerLevelBytes, + pxStreamBuffer->ucFlags, + pxSendCallback, + pxReceiveCallback ); + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } + #endif + + traceSTREAM_BUFFER_RESET( xStreamBuffer ); + + xReturn = pdPASS; + } + } + taskEXIT_CRITICAL(); + + traceRETURN_xStreamBufferReset( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferResetFromISR( StreamBufferHandle_t xStreamBuffer ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn = pdFAIL; + StreamBufferCallbackFunction_t pxSendCallback = NULL, pxReceiveCallback = NULL; + UBaseType_t uxSavedInterruptStatus; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; + #endif + + traceENTER_xStreamBufferResetFromISR( xStreamBuffer ); + + configASSERT( pxStreamBuffer ); + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Store the stream buffer number so it can be restored after the + * reset. */ + uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; + } + #endif + + /* Can only reset a message buffer if there are no tasks blocked on it. */ + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); + { + if( ( pxStreamBuffer->xTaskWaitingToReceive == NULL ) && ( pxStreamBuffer->xTaskWaitingToSend == NULL ) ) + { + #if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + { + pxSendCallback = pxStreamBuffer->pxSendCompletedCallback; + pxReceiveCallback = pxStreamBuffer->pxReceiveCompletedCallback; + } + #endif + + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pxStreamBuffer->pucBuffer, + pxStreamBuffer->xLength, + pxStreamBuffer->xTriggerLevelBytes, + pxStreamBuffer->ucFlags, + pxSendCallback, + pxReceiveCallback ); + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } + #endif + + traceSTREAM_BUFFER_RESET_FROM_ISR( xStreamBuffer ); + + xReturn = pdPASS; + } + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xStreamBufferResetFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, + size_t xTriggerLevel ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn; + + traceENTER_xStreamBufferSetTriggerLevel( xStreamBuffer, xTriggerLevel ); + + configASSERT( pxStreamBuffer ); + + /* It is not valid for the trigger level to be 0. */ + if( xTriggerLevel == ( size_t ) 0 ) + { + xTriggerLevel = ( size_t ) 1; + } + + /* The trigger level is the number of bytes that must be in the stream + * buffer before a task that is waiting for data is unblocked. */ + if( xTriggerLevel < pxStreamBuffer->xLength ) + { + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; + xReturn = pdPASS; + } + else + { + xReturn = pdFALSE; + } + + traceRETURN_xStreamBufferSetTriggerLevel( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) +{ + const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xSpace; + size_t xOriginalTail; + + traceENTER_xStreamBufferSpacesAvailable( xStreamBuffer ); + + configASSERT( pxStreamBuffer ); + + /* The code below reads xTail and then xHead. This is safe if the stream + * buffer is updated once between the two reads - but not if the stream buffer + * is updated more than once between the two reads - hence the loop. */ + do + { + xOriginalTail = pxStreamBuffer->xTail; + xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail; + xSpace -= pxStreamBuffer->xHead; + } while( xOriginalTail != pxStreamBuffer->xTail ); + + xSpace -= ( size_t ) 1; + + if( xSpace >= pxStreamBuffer->xLength ) + { + xSpace -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xStreamBufferSpacesAvailable( xSpace ); + + return xSpace; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) +{ + const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReturn; + + traceENTER_xStreamBufferBytesAvailable( xStreamBuffer ); + + configASSERT( pxStreamBuffer ); + + xReturn = prvBytesInBuffer( pxStreamBuffer ); + + traceRETURN_xStreamBufferBytesAvailable( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReturn, xSpace = 0; + size_t xRequiredSpace = xDataLengthBytes; + TimeOut_t xTimeOut; + size_t xMaxReportedSpace = 0; + + traceENTER_xStreamBufferSend( xStreamBuffer, pvTxData, xDataLengthBytes, xTicksToWait ); + + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); + + /* The maximum amount of space a stream buffer will ever report is its length + * minus 1. */ + xMaxReportedSpace = pxStreamBuffer->xLength - ( size_t ) 1; + + /* This send function is used to write to both message buffers and stream + * buffers. If this is a message buffer then the space needed must be + * increased by the amount of bytes needed to store the length of the + * message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + + /* Overflow? */ + configASSERT( xRequiredSpace > xDataLengthBytes ); + + /* If this is a message buffer then it must be possible to write the + * whole message. */ + if( xRequiredSpace > xMaxReportedSpace ) + { + /* The message would not fit even if the entire buffer was empty, + * so don't wait for space. */ + xTicksToWait = ( TickType_t ) 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If this is a stream buffer then it is acceptable to write only part + * of the message to the buffer. Cap the length to the total length of + * the buffer. */ + if( xRequiredSpace > xMaxReportedSpace ) + { + xRequiredSpace = xMaxReportedSpace; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + if( xTicksToWait != ( TickType_t ) 0 ) + { + vTaskSetTimeOutState( &xTimeOut ); + + do + { + /* Wait until the required number of bytes are free in the message + * buffer. */ + taskENTER_CRITICAL(); + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + + if( xSpace < xRequiredSpace ) + { + /* Clear notification state as going to wait for space. */ + ( void ) xTaskNotifyStateClearIndexed( NULL, pxStreamBuffer->uxNotificationIndex ); + + /* Should only be one writer. */ + configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); + pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle(); + } + else + { + taskEXIT_CRITICAL(); + break; + } + } + taskEXIT_CRITICAL(); + + traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); + ( void ) xTaskNotifyWaitIndexed( pxStreamBuffer->uxNotificationIndex, ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToSend = NULL; + } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xSpace == ( size_t ) 0 ) + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + + if( xReturn > ( size_t ) 0 ) + { + traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); + + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + prvSEND_COMPLETED( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); + } + + traceRETURN_xStreamBufferSend( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReturn, xSpace; + size_t xRequiredSpace = xDataLengthBytes; + + traceENTER_xStreamBufferSendFromISR( xStreamBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ); + + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); + + /* This send function is used to write to both message buffers and stream + * buffers. If this is a message buffer then the space needed must be + * increased by the amount of bytes needed to store the length of the + * message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + + if( xReturn > ( size_t ) 0 ) + { + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + prvSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); + traceRETURN_xStreamBufferSendFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) +{ + size_t xNextHead = pxStreamBuffer->xHead; + configMESSAGE_BUFFER_LENGTH_TYPE xMessageLength; + + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + /* This is a message buffer, as opposed to a stream buffer. */ + + /* Convert xDataLengthBytes to the message length type. */ + xMessageLength = ( configMESSAGE_BUFFER_LENGTH_TYPE ) xDataLengthBytes; + + /* Ensure the data length given fits within configMESSAGE_BUFFER_LENGTH_TYPE. */ + configASSERT( ( size_t ) xMessageLength == xDataLengthBytes ); + + if( xSpace >= xRequiredSpace ) + { + /* There is enough space to write both the message length and the message + * itself into the buffer. Start by writing the length of the data, the data + * itself will be written later in this function. */ + xNextHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xMessageLength ), sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextHead ); + } + else + { + /* Not enough space, so do not write data to the buffer. */ + xDataLengthBytes = 0; + } + } + else + { + /* This is a stream buffer, as opposed to a message buffer, so writing a + * stream of bytes rather than discrete messages. Plan to write as many + * bytes as possible. */ + xDataLengthBytes = configMIN( xDataLengthBytes, xSpace ); + } + + if( xDataLengthBytes != ( size_t ) 0 ) + { + /* Write the data to the buffer. */ + /* MISRA Ref 11.5.5 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxStreamBuffer->xHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes, xNextHead ); + } + + return xDataLengthBytes; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; + + traceENTER_xStreamBufferReceive( xStreamBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ); + + configASSERT( pvRxData ); + configASSERT( pxStreamBuffer ); + + /* This receive function is used by both message buffers, which store + * discrete messages, and stream buffers, which store a continuous stream of + * bytes. Discrete messages include an additional + * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the + * message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_BATCHING_BUFFER ) != ( uint8_t ) 0 ) + { + /* Force task to block if the batching buffer contains less bytes than + * the trigger level. */ + xBytesToStoreMessageLength = pxStreamBuffer->xTriggerLevelBytes; + } + else + { + xBytesToStoreMessageLength = 0; + } + + if( xTicksToWait != ( TickType_t ) 0 ) + { + /* Checking if there is data and clearing the notification state must be + * performed atomically. */ + taskENTER_CRITICAL(); + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + + /* If this function was invoked by a message buffer read then + * xBytesToStoreMessageLength holds the number of bytes used to hold + * the length of the next discrete message. If this function was + * invoked by a stream buffer read then xBytesToStoreMessageLength will + * be 0. If this function was invoked by a stream batch buffer read + * then xBytesToStoreMessageLength will be xTriggerLevelBytes value + * for the buffer.*/ + if( xBytesAvailable <= xBytesToStoreMessageLength ) + { + /* Clear notification state as going to wait for data. */ + ( void ) xTaskNotifyStateClearIndexed( NULL, pxStreamBuffer->uxNotificationIndex ); + + /* Should only be one reader. */ + configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); + pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + if( xBytesAvailable <= xBytesToStoreMessageLength ) + { + /* Wait for data to be available. */ + traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ); + ( void ) xTaskNotifyWaitIndexed( pxStreamBuffer->uxNotificationIndex, ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToReceive = NULL; + + /* Recheck the data available after blocking. */ + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + } + + /* Whether receiving a discrete message (where xBytesToStoreMessageLength + * holds the number of bytes used to store the message length) or a stream of + * bytes (where xBytesToStoreMessageLength is zero), the number of bytes + * available must be greater than xBytesToStoreMessageLength to be able to + * read bytes from the buffer. */ + if( xBytesAvailable > xBytesToStoreMessageLength ) + { + xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable ); + + /* Was a task waiting for space in the buffer? */ + if( xReceivedLength != ( size_t ) 0 ) + { + traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ); + prvRECEIVE_COMPLETED( xStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ); + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xStreamBufferReceive( xReceivedLength ); + + return xReceivedLength; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReturn, xBytesAvailable; + configMESSAGE_BUFFER_LENGTH_TYPE xTempReturn; + + traceENTER_xStreamBufferNextMessageLengthBytes( xStreamBuffer ); + + configASSERT( pxStreamBuffer ); + + /* Ensure the stream buffer is being used as a message buffer. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + + if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH ) + { + /* The number of bytes available is greater than the number of bytes + * required to hold the length of the next message, so another message + * is available. */ + ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, pxStreamBuffer->xTail ); + xReturn = ( size_t ) xTempReturn; + } + else + { + /* The minimum amount of bytes in a message buffer is + * ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is + * less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid + * value is 0. */ + configASSERT( xBytesAvailable == 0 ); + xReturn = 0; + } + } + else + { + xReturn = 0; + } + + traceRETURN_xStreamBufferNextMessageLengthBytes( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; + + traceENTER_xStreamBufferReceiveFromISR( xStreamBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ); + + configASSERT( pvRxData ); + configASSERT( pxStreamBuffer ); + + /* This receive function is used by both message buffers, which store + * discrete messages, and stream buffers, which store a continuous stream of + * bytes. Discrete messages include an additional + * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the + * message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } + + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + + /* Whether receiving a discrete message (where xBytesToStoreMessageLength + * holds the number of bytes used to store the message length) or a stream of + * bytes (where xBytesToStoreMessageLength is zero), the number of bytes + * available must be greater than xBytesToStoreMessageLength to be able to + * read bytes from the buffer. */ + if( xBytesAvailable > xBytesToStoreMessageLength ) + { + xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable ); + + /* Was a task waiting for space in the buffer? */ + if( xReceivedLength != ( size_t ) 0 ) + { + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + prvRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ); + traceRETURN_xStreamBufferReceiveFromISR( xReceivedLength ); + + return xReceivedLength; +} +/*-----------------------------------------------------------*/ + +static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + size_t xBytesAvailable ) +{ + size_t xCount, xNextMessageLength; + configMESSAGE_BUFFER_LENGTH_TYPE xTempNextMessageLength; + size_t xNextTail = pxStreamBuffer->xTail; + + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + /* A discrete message is being received. First receive the length + * of the message. */ + xNextTail = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextTail ); + xNextMessageLength = ( size_t ) xTempNextMessageLength; + + /* Reduce the number of bytes available by the number of bytes just + * read out. */ + xBytesAvailable -= sbBYTES_TO_STORE_MESSAGE_LENGTH; + + /* Check there is enough space in the buffer provided by the + * user. */ + if( xNextMessageLength > xBufferLengthBytes ) + { + /* The user has provided insufficient space to read the message. */ + xNextMessageLength = 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* A stream of bytes is being received (as opposed to a discrete + * message), so read as many bytes as possible. */ + xNextMessageLength = xBufferLengthBytes; + } + + /* Use the minimum of the wanted bytes and the available bytes. */ + xCount = configMIN( xNextMessageLength, xBytesAvailable ); + + if( xCount != ( size_t ) 0 ) + { + /* Read the actual data and update the tail to mark the data as officially consumed. */ + /* MISRA Ref 11.5.5 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxStreamBuffer->xTail = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xCount, xNextTail ); + } + + return xCount; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) +{ + const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn; + size_t xTail; + + traceENTER_xStreamBufferIsEmpty( xStreamBuffer ); + + configASSERT( pxStreamBuffer ); + + /* True if no bytes are available. */ + xTail = pxStreamBuffer->xTail; + + if( pxStreamBuffer->xHead == xTail ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + traceRETURN_xStreamBufferIsEmpty( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) +{ + BaseType_t xReturn; + size_t xBytesToStoreMessageLength; + const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + + traceENTER_xStreamBufferIsFull( xStreamBuffer ); + + configASSERT( pxStreamBuffer ); + + /* This generic version of the receive function is used by both message + * buffers, which store discrete messages, and stream buffers, which store a + * continuous stream of bytes. Discrete messages include an additional + * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } + + /* True if the available space equals zero. */ + if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + traceRETURN_xStreamBufferIsFull( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, + BaseType_t * pxHigherPriorityTaskWoken ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + + traceENTER_xStreamBufferSendCompletedFromISR( xStreamBuffer, pxHigherPriorityTaskWoken ); + + configASSERT( pxStreamBuffer ); + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); + { + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) + { + ( void ) xTaskNotifyIndexedFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, + ( pxStreamBuffer )->uxNotificationIndex, + ( uint32_t ) 0, + eNoAction, + pxHigherPriorityTaskWoken ); + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xStreamBufferSendCompletedFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, + BaseType_t * pxHigherPriorityTaskWoken ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + + traceENTER_xStreamBufferReceiveCompletedFromISR( xStreamBuffer, pxHigherPriorityTaskWoken ); + + configASSERT( pxStreamBuffer ); + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); + { + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) + { + ( void ) xTaskNotifyIndexedFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, + ( pxStreamBuffer )->uxNotificationIndex, + ( uint32_t ) 0, + eNoAction, + pxHigherPriorityTaskWoken ); + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xStreamBufferReceiveCompletedFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, + const uint8_t * pucData, + size_t xCount, + size_t xHead ) +{ + size_t xFirstLength; + + configASSERT( xCount > ( size_t ) 0 ); + + /* Calculate the number of bytes that can be added in the first write - + * which may be less than the total number of bytes that need to be added if + * the buffer will wrap back to the beginning. */ + xFirstLength = configMIN( pxStreamBuffer->xLength - xHead, xCount ); + + /* Write as many bytes as can be written in the first write. */ + configASSERT( ( xHead + xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void * ) ( &( pxStreamBuffer->pucBuffer[ xHead ] ) ), ( const void * ) pucData, xFirstLength ); + + /* If the number of bytes written was less than the number that could be + * written in the first write... */ + if( xCount > xFirstLength ) + { + /* ...then write the remaining bytes to the start of the buffer. */ + configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xHead += xCount; + + if( xHead >= pxStreamBuffer->xLength ) + { + xHead -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xHead; +} +/*-----------------------------------------------------------*/ + +static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer, + uint8_t * pucData, + size_t xCount, + size_t xTail ) +{ + size_t xFirstLength; + + configASSERT( xCount != ( size_t ) 0 ); + + /* Calculate the number of bytes that can be read - which may be + * less than the number wanted if the data wraps around to the start of + * the buffer. */ + xFirstLength = configMIN( pxStreamBuffer->xLength - xTail, xCount ); + + /* Obtain the number of bytes it is possible to obtain in the first + * read. Asserts check bounds of read and write. */ + configASSERT( xFirstLength <= xCount ); + configASSERT( ( xTail + xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xTail ] ), xFirstLength ); + + /* If the total number of wanted bytes is greater than the number + * that could be read in the first read... */ + if( xCount > xFirstLength ) + { + /* ...then read the remaining bytes from the start of the buffer. */ + ( void ) memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Move the tail pointer to effectively remove the data read from the buffer. */ + xTail += xCount; + + if( xTail >= pxStreamBuffer->xLength ) + { + xTail -= pxStreamBuffer->xLength; + } + + return xTail; +} +/*-----------------------------------------------------------*/ + +static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) +{ + /* Returns the distance between xTail and xHead. */ + size_t xCount; + + xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead; + xCount -= pxStreamBuffer->xTail; + + if( xCount >= pxStreamBuffer->xLength ) + { + xCount -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xCount; +} +/*-----------------------------------------------------------*/ + +static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, + uint8_t * const pucBuffer, + size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t ucFlags, + StreamBufferCallbackFunction_t pxSendCompletedCallback, + StreamBufferCallbackFunction_t pxReceiveCompletedCallback ) +{ + /* Assert here is deliberately writing to the entire buffer to ensure it can + * be written to without generating exceptions, and is setting the buffer to a + * known value to assist in development/debugging. */ + #if ( configASSERT_DEFINED == 1 ) + { + /* The value written just has to be identifiable when looking at the + * memory. Don't use 0xA5 as that is the stack fill value and could + * result in confusion as to what is actually being observed. */ + #define STREAM_BUFFER_BUFFER_WRITE_VALUE ( 0x55 ) + configASSERT( memset( pucBuffer, ( int ) STREAM_BUFFER_BUFFER_WRITE_VALUE, xBufferSizeBytes ) == pucBuffer ); + } + #endif + + ( void ) memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); + pxStreamBuffer->pucBuffer = pucBuffer; + pxStreamBuffer->xLength = xBufferSizeBytes; + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes; + pxStreamBuffer->ucFlags = ucFlags; + pxStreamBuffer->uxNotificationIndex = tskDEFAULT_INDEX_TO_NOTIFY; + #if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) + { + pxStreamBuffer->pxSendCompletedCallback = pxSendCompletedCallback; + pxStreamBuffer->pxReceiveCompletedCallback = pxReceiveCompletedCallback; + } + #else + { + /* MISRA Ref 11.1.1 [Object type casting] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-111 */ + /* coverity[misra_c_2012_rule_11_1_violation] */ + ( void ) pxSendCompletedCallback; + + /* MISRA Ref 11.1.1 [Object type casting] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-111 */ + /* coverity[misra_c_2012_rule_11_1_violation] */ + ( void ) pxReceiveCompletedCallback; + } + #endif /* if ( configUSE_SB_COMPLETED_CALLBACK == 1 ) */ +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxStreamBufferGetStreamBufferNotificationIndex( StreamBufferHandle_t xStreamBuffer ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + + traceENTER_uxStreamBufferGetStreamBufferNotificationIndex( xStreamBuffer ); + + configASSERT( pxStreamBuffer ); + + traceRETURN_uxStreamBufferGetStreamBufferNotificationIndex( pxStreamBuffer->uxNotificationIndex ); + + return pxStreamBuffer->uxNotificationIndex; +} +/*-----------------------------------------------------------*/ + +void vStreamBufferSetStreamBufferNotificationIndex( StreamBufferHandle_t xStreamBuffer, + UBaseType_t uxNotificationIndex ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + + traceENTER_vStreamBufferSetStreamBufferNotificationIndex( xStreamBuffer, uxNotificationIndex ); + + configASSERT( pxStreamBuffer ); + + /* There should be no task waiting otherwise we'd never resume them. */ + configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); + configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); + + /* Check that the task notification index is valid. */ + configASSERT( uxNotificationIndex < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + pxStreamBuffer->uxNotificationIndex = uxNotificationIndex; + + traceRETURN_vStreamBufferSetStreamBufferNotificationIndex(); +} +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) + { + traceENTER_uxStreamBufferGetStreamBufferNumber( xStreamBuffer ); + + traceRETURN_uxStreamBufferGetStreamBufferNumber( xStreamBuffer->uxStreamBufferNumber ); + + return xStreamBuffer->uxStreamBufferNumber; + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, + UBaseType_t uxStreamBufferNumber ) + { + traceENTER_vStreamBufferSetStreamBufferNumber( xStreamBuffer, uxStreamBufferNumber ); + + xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + + traceRETURN_vStreamBufferSetStreamBufferNumber(); + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) + { + traceENTER_ucStreamBufferGetStreamBufferType( xStreamBuffer ); + + traceRETURN_ucStreamBufferGetStreamBufferType( ( uint8_t ) ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) ); + + return( ( uint8_t ) ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) ); + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +/* This entire source file will be skipped if the application is not configured + * to include stream buffer functionality. This #if is closed at the very bottom + * of this file. If you want to include stream buffers then ensure + * configUSE_STREAM_BUFFERS is set to 1 in FreeRTOSConfig.h. */ +#endif /* configUSE_STREAM_BUFFERS == 1 */ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/tasks.c b/source/Middlewares/Third_Party/FreeRTOS/Source/tasks.c index 90811f6be..fd3bc638d 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/tasks.c +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/tasks.c @@ -1,5379 +1,8696 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -/* Standard includes. */ -#include -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining - * all the API functions to use the MPU wrappers. That should only be done when - * task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -/* FreeRTOS includes. */ -#include "FreeRTOS.h" -#include "task.h" -#include "timers.h" -#include "stack_macros.h" - -/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified - * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined - * for the header files above, but not in this file, in order to generate the - * correct privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ - -/* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting - * functions but without including stdio.h here. */ -#if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) - -/* At the bottom of this file are two optional functions that can be used - * to generate human readable text from the raw data generated by the - * uxTaskGetSystemState() function. Note the formatting functions are provided - * for convenience only, and are NOT considered part of the kernel. */ - #include -#endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */ - -#if ( configUSE_PREEMPTION == 0 ) - -/* If the cooperative scheduler is being used then a yield should not be - * performed just because a higher priority task has been woken. */ - #define taskYIELD_IF_USING_PREEMPTION() -#else - #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() -#endif - -/* Values that can be assigned to the ucNotifyState member of the TCB. */ -#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) /* Must be zero as it is the initialised value. */ -#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) -#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) - -/* - * The value used to fill the stack of a task when the task is created. This - * is used purely for checking the high water mark for tasks. - */ -#define tskSTACK_FILL_BYTE ( 0xa5U ) - -/* Bits used to recored how a task's stack and TCB were allocated. */ -#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 ) -#define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 ) -#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 ) - -/* If any of the following are set then task stacks are filled with a known - * value so the high water mark can be determined. If none of the following are - * set then don't fill the stack so there is no unnecessary dependency on memset. */ -#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) - #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1 -#else - #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0 -#endif - -/* - * Macros used by vListTask to indicate which state a task is in. - */ -#define tskRUNNING_CHAR ( 'X' ) -#define tskBLOCKED_CHAR ( 'B' ) -#define tskREADY_CHAR ( 'R' ) -#define tskDELETED_CHAR ( 'D' ) -#define tskSUSPENDED_CHAR ( 'S' ) - -/* - * Some kernel aware debuggers require the data the debugger needs access to be - * global, rather than file scope. - */ -#ifdef portREMOVE_STATIC_QUALIFIER - #define static -#endif - -/* The name allocated to the Idle task. This can be overridden by defining - * configIDLE_TASK_NAME in FreeRTOSConfig.h. */ -#ifndef configIDLE_TASK_NAME - #define configIDLE_TASK_NAME "IDLE" -#endif - -#if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) - -/* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is - * performed in a generic way that is not optimised to any particular - * microcontroller architecture. */ - -/* uxTopReadyPriority holds the priority of the highest priority ready - * state task. */ - #define taskRECORD_READY_PRIORITY( uxPriority ) \ - { \ - if( ( uxPriority ) > uxTopReadyPriority ) \ - { \ - uxTopReadyPriority = ( uxPriority ); \ - } \ - } /* taskRECORD_READY_PRIORITY */ - -/*-----------------------------------------------------------*/ - - #define taskSELECT_HIGHEST_PRIORITY_TASK() \ - { \ - UBaseType_t uxTopPriority = uxTopReadyPriority; \ - \ - /* Find the highest priority queue that contains ready tasks. */ \ - while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \ - { \ - configASSERT( uxTopPriority ); \ - --uxTopPriority; \ - } \ - \ - /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ - * the same priority get an equal share of the processor time. */ \ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ - uxTopReadyPriority = uxTopPriority; \ - } /* taskSELECT_HIGHEST_PRIORITY_TASK */ - -/*-----------------------------------------------------------*/ - -/* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as - * they are only required when a port optimised method of task selection is - * being used. */ - #define taskRESET_READY_PRIORITY( uxPriority ) - #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority ) - -#else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ - -/* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is - * performed in a way that is tailored to the particular microcontroller - * architecture being used. */ - -/* A port optimised version is provided. Call the port defined macros. */ - #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority ) - -/*-----------------------------------------------------------*/ - - #define taskSELECT_HIGHEST_PRIORITY_TASK() \ - { \ - UBaseType_t uxTopPriority; \ - \ - /* Find the highest priority list that contains ready tasks. */ \ - portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ - configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ - } /* taskSELECT_HIGHEST_PRIORITY_TASK() */ - -/*-----------------------------------------------------------*/ - -/* A port optimised version is provided, call it only if the TCB being reset - * is being referenced from a ready list. If it is referenced from a delayed - * or suspended list then it won't be in a ready list. */ - #define taskRESET_READY_PRIORITY( uxPriority ) \ - { \ - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \ - { \ - portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \ - } \ - } - -#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ - -/*-----------------------------------------------------------*/ - -/* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick - * count overflows. */ -#define taskSWITCH_DELAYED_LISTS() \ - { \ - List_t * pxTemp; \ - \ - /* The delayed tasks list should be empty when the lists are switched. */ \ - configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \ - \ - pxTemp = pxDelayedTaskList; \ - pxDelayedTaskList = pxOverflowDelayedTaskList; \ - pxOverflowDelayedTaskList = pxTemp; \ - xNumOfOverflows++; \ - prvResetNextTaskUnblockTime(); \ - } - -/*-----------------------------------------------------------*/ - -/* - * Place the task represented by pxTCB into the appropriate ready list for - * the task. It is inserted at the end of the list. - */ -#define prvAddTaskToReadyList( pxTCB ) \ - traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ - taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ - vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \ - tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) -/*-----------------------------------------------------------*/ - -/* - * Several functions take an TaskHandle_t parameter that can optionally be NULL, - * where NULL is used to indicate that the handle of the currently executing - * task should be used in place of the parameter. This macro simply checks to - * see if the parameter is NULL and returns a pointer to the appropriate TCB. - */ -#define prvGetTCBFromHandle( pxHandle ) ( ( ( pxHandle ) == NULL ) ? pxCurrentTCB : ( pxHandle ) ) - -/* The item value of the event list item is normally used to hold the priority - * of the task to which it belongs (coded to allow it to be held in reverse - * priority order). However, it is occasionally borrowed for other purposes. It - * is important its value is not updated due to a task priority change while it is - * being used for another purpose. The following bit definition is used to inform - * the scheduler that the value should not be changed - in which case it is the - * responsibility of whichever module is using the value to ensure it gets set back - * to its original value when it is released. */ -#if ( configUSE_16_BIT_TICKS == 1 ) - #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U -#else - #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL -#endif - -/* - * Task control block. A task control block (TCB) is allocated for each task, - * and stores task state information, including a pointer to the task's context - * (the task's run time environment, including register values) - */ -typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */ -{ - volatile StackType_t * pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */ - - #if ( portUSING_MPU_WRAPPERS == 1 ) - xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */ - #endif - - ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */ - ListItem_t xEventListItem; /*< Used to reference a task from an event list. */ - UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */ - StackType_t * pxStack; /*< Points to the start of the stack. */ - char pcTaskName[ configMAX_TASK_NAME_LEN ]; /*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - - #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) - StackType_t * pxEndOfStack; /*< Points to the highest valid address for the stack. */ - #endif - - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */ - #endif - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */ - UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */ - #endif - - #if ( configUSE_MUTEXES == 1 ) - UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */ - UBaseType_t uxMutexesHeld; - #endif - - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - TaskHookFunction_t pxTaskTag; - #endif - - #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - void * pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; - #endif - - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */ - #endif - - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - - /* Allocate a Newlib reent structure that is specific to this task. - * Note Newlib support has been included by popular demand, but is not - * used by the FreeRTOS maintainers themselves. FreeRTOS is not - * responsible for resulting newlib operation. User must be familiar with - * newlib and must provide system-wide implementations of the necessary - * stubs. Be warned that (at the time of writing) the current newlib design - * implements a system-wide malloc() that must be provided with locks. - * - * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html - * for additional information. */ - struct _reent xNewLib_reent; - #endif - - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - volatile uint32_t ulNotifiedValue[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; - volatile uint8_t ucNotifyState[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; - #endif - - /* See the comments in FreeRTOS.h with the definition of - * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ - #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ - #endif - - #if ( INCLUDE_xTaskAbortDelay == 1 ) - uint8_t ucDelayAborted; - #endif - - #if ( configUSE_POSIX_ERRNO == 1 ) - int iTaskErrno; - #endif -} tskTCB; - -/* The old tskTCB name is maintained above then typedefed to the new TCB_t name - * below to enable the use of older kernel aware debuggers. */ -typedef tskTCB TCB_t; - -/*lint -save -e956 A manual analysis and inspection has been used to determine - * which static variables must be declared volatile. */ -PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL; - -/* Lists for ready and blocked tasks. -------------------- - * xDelayedTaskList1 and xDelayedTaskList2 could be move to function scople but - * doing so breaks some kernel aware debuggers and debuggers that rely on removing - * the static qualifier. */ -PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ]; /*< Prioritised ready tasks. */ -PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */ -PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ -PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */ -PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ -PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */ - -#if ( INCLUDE_vTaskDelete == 1 ) - - PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */ - PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U; - -#endif - -#if ( INCLUDE_vTaskSuspend == 1 ) - - PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */ - -#endif - -/* Global POSIX errno. Its value is changed upon context switching to match - * the errno of the currently running task. */ -#if ( configUSE_POSIX_ERRNO == 1 ) - int FreeRTOS_errno = 0; -#endif - -/* Other file private variables. --------------------------------*/ -PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; -PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY; -PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE; -PRIVILEGED_DATA static volatile TickType_t xPendedTicks = ( TickType_t ) 0U; -PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE; -PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0; -PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */ -PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ - -/* Context switches are held pending while the scheduler is suspended. Also, - * interrupts must not manipulate the xStateListItem of a TCB, or any of the - * lists the xStateListItem can be referenced from, if the scheduler is suspended. - * If an interrupt needs to unblock a task while the scheduler is suspended then it - * moves the task's event list item into the xPendingReadyList, ready for the - * kernel to move the task from the pending ready list into the real ready list - * when the scheduler is unsuspended. The pending ready list itself can only be - * accessed from a critical section. */ -PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE; - -#if ( configGENERATE_RUN_TIME_STATS == 1 ) - -/* Do not move these variables to function scope as doing so prevents the - * code working with debuggers that need to remove the static qualifier. */ - PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ - PRIVILEGED_DATA static volatile uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */ - -#endif - -/*lint -restore */ - -/*-----------------------------------------------------------*/ - -/* File private functions. --------------------------------*/ - -/** - * Utility task that simply returns pdTRUE if the task referenced by xTask is - * currently in the Suspended state, or pdFALSE if the task referenced by xTask - * is in any other state. - */ -#if ( INCLUDE_vTaskSuspend == 1 ) - - static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - -#endif /* INCLUDE_vTaskSuspend */ - -/* - * Utility to ready all the lists used by the scheduler. This is called - * automatically upon the creation of the first task. - */ -static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION; - -/* - * The idle task, which as all tasks is implemented as a never ending loop. - * The idle task is automatically created and added to the ready lists upon - * creation of the first user task. - * - * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific - * language extensions. The equivalent prototype for this function is: - * - * void prvIdleTask( void *pvParameters ); - * - */ -static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ) PRIVILEGED_FUNCTION; - -/* - * Utility to free all memory allocated by the scheduler to hold a TCB, - * including the stack pointed to by the TCB. - * - * This does not free memory allocated by the task itself (i.e. memory - * allocated by calls to pvPortMalloc from within the tasks application code). - */ -#if ( INCLUDE_vTaskDelete == 1 ) - - static void prvDeleteTCB( TCB_t * pxTCB ) PRIVILEGED_FUNCTION; - -#endif - -/* - * Used only by the idle task. This checks to see if anything has been placed - * in the list of tasks waiting to be deleted. If so the task is cleaned up - * and its TCB deleted. - */ -static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION; - -/* - * The currently executing task is entering the Blocked state. Add the task to - * either the current or the overflow delayed task list. - */ -static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, - const BaseType_t xCanBlockIndefinitely ) PRIVILEGED_FUNCTION; - -/* - * Fills an TaskStatus_t structure with information on each task that is - * referenced from the pxList list (which may be a ready list, a delayed list, - * a suspended list, etc.). - * - * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM - * NORMAL APPLICATION CODE. - */ -#if ( configUSE_TRACE_FACILITY == 1 ) - - static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray, - List_t * pxList, - eTaskState eState ) PRIVILEGED_FUNCTION; - -#endif - -/* - * Searches pxList for a task with name pcNameToQuery - returning a handle to - * the task if it is found, or NULL if the task is not found. - */ -#if ( INCLUDE_xTaskGetHandle == 1 ) - - static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList, - const char pcNameToQuery[] ) PRIVILEGED_FUNCTION; - -#endif - -/* - * When a task is created, the stack of the task is filled with a known value. - * This function determines the 'high water mark' of the task stack by - * determining how much of the stack remains at the original preset value. - */ -#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) - - static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION; - -#endif - -/* - * Return the amount of time, in ticks, that will pass before the kernel will - * next move a task from the Blocked state to the Running state. - * - * This conditional compilation should use inequality to 0, not equality to 1. - * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user - * defined low power mode implementations require configUSE_TICKLESS_IDLE to be - * set to a value other than 1. - */ -#if ( configUSE_TICKLESS_IDLE != 0 ) - - static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION; - -#endif - -/* - * Set xNextTaskUnblockTime to the time at which the next Blocked state task - * will exit the Blocked state. - */ -static void prvResetNextTaskUnblockTime( void ) PRIVILEGED_FUNCTION; - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) - -/* - * Helper function used to pad task names with spaces when printing out - * human readable tables of task information. - */ - static char * prvWriteNameToBuffer( char * pcBuffer, - const char * pcTaskName ) PRIVILEGED_FUNCTION; - -#endif - -/* - * Called after a Task_t structure has been allocated either statically or - * dynamically to fill in the structure's members. - */ -static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask, - TCB_t * pxNewTCB, - const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; - -/* - * Called after a new task has been created and initialised to place the task - * under the control of the scheduler. - */ -static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) PRIVILEGED_FUNCTION; - -/* - * freertos_tasks_c_additions_init() should only be called if the user definable - * macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro - * called by the function. - */ -#ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - - static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION; - -#endif - -/*-----------------------------------------------------------*/ - -#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - - TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - StackType_t * const puxStackBuffer, - StaticTask_t * const pxTaskBuffer ) - { - TCB_t * pxNewTCB; - TaskHandle_t xReturn; - - configASSERT( puxStackBuffer != NULL ); - configASSERT( pxTaskBuffer != NULL ); - - #if ( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - * variable of type StaticTask_t equals the size of the real task - * structure. */ - volatile size_t xSize = sizeof( StaticTask_t ); - configASSERT( xSize == sizeof( TCB_t ) ); - ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */ - } - #endif /* configASSERT_DEFINED */ - - if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) ) - { - /* The memory used for the task's TCB and stack are passed into this - * function - use them. */ - pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ - pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer; - - #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ - { - /* Tasks can be created statically or dynamically, so note this - * task was created statically in case the task is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - - prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL ); - prvAddNewTaskToReadyList( pxNewTCB ); - } - else - { - xReturn = NULL; - } - - return xReturn; - } - -#endif /* SUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - - BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, - TaskHandle_t * pxCreatedTask ) - { - TCB_t * pxNewTCB; - BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - - configASSERT( pxTaskDefinition->puxStackBuffer != NULL ); - configASSERT( pxTaskDefinition->pxTaskBuffer != NULL ); - - if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) ) - { - /* Allocate space for the TCB. Where the memory comes from depends - * on the implementation of the port malloc function and whether or - * not static allocation is being used. */ - pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer; - - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; - - #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) - { - /* Tasks can be created statically or dynamically, so note this - * task was created statically in case the task is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - - prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, - pxTaskDefinition->pcName, - ( uint32_t ) pxTaskDefinition->usStackDepth, - pxTaskDefinition->pvParameters, - pxTaskDefinition->uxPriority, - pxCreatedTask, pxNewTCB, - pxTaskDefinition->xRegions ); - - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } - - return xReturn; - } - -#endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ -/*-----------------------------------------------------------*/ - -#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, - TaskHandle_t * pxCreatedTask ) - { - TCB_t * pxNewTCB; - BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - - configASSERT( pxTaskDefinition->puxStackBuffer ); - - if( pxTaskDefinition->puxStackBuffer != NULL ) - { - /* Allocate space for the TCB. Where the memory comes from depends - * on the implementation of the port malloc function and whether or - * not static allocation is being used. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); - - if( pxNewTCB != NULL ) - { - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; - - #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) - { - /* Tasks can be created statically or dynamically, so note - * this task had a statically allocated stack in case it is - * later deleted. The TCB was allocated dynamically. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - - prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, - pxTaskDefinition->pcName, - ( uint32_t ) pxTaskDefinition->usStackDepth, - pxTaskDefinition->pvParameters, - pxTaskDefinition->uxPriority, - pxCreatedTask, pxNewTCB, - pxTaskDefinition->xRegions ); - - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } - } - - return xReturn; - } - -#endif /* portUSING_MPU_WRAPPERS */ -/*-----------------------------------------------------------*/ - -#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - - BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const configSTACK_DEPTH_TYPE usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask ) - { - TCB_t * pxNewTCB; - BaseType_t xReturn; - - /* If the stack grows down then allocate the stack then the TCB so the stack - * does not grow into the TCB. Likewise if the stack grows up then allocate - * the TCB then the stack. */ - #if ( portSTACK_GROWTH > 0 ) - { - /* Allocate space for the TCB. Where the memory comes from depends on - * the implementation of the port malloc function and whether or not static - * allocation is being used. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); - - if( pxNewTCB != NULL ) - { - /* Allocate space for the stack used by the task being created. - * The base of the stack memory stored in the TCB so the task can - * be deleted later if required. */ - pxNewTCB->pxStack = ( StackType_t * ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - if( pxNewTCB->pxStack == NULL ) - { - /* Could not allocate the stack. Delete the allocated TCB. */ - vPortFree( pxNewTCB ); - pxNewTCB = NULL; - } - } - } - #else /* portSTACK_GROWTH */ - { - StackType_t * pxStack; - - /* Allocate space for the stack used by the task being created. */ - pxStack = pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation is the stack. */ - - if( pxStack != NULL ) - { - /* Allocate space for the TCB. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of TCB_t is always a pointer to the task's stack. */ - - if( pxNewTCB != NULL ) - { - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxStack; - } - else - { - /* The stack cannot be used as the TCB was not created. Free - * it again. */ - vPortFree( pxStack ); - } - } - else - { - pxNewTCB = NULL; - } - } - #endif /* portSTACK_GROWTH */ - - if( pxNewTCB != NULL ) - { - #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */ - { - /* Tasks can be created statically or dynamically, so note this - * task was created dynamically in case it is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - - prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } - else - { - xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - } - - return xReturn; - } - -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask, - TCB_t * pxNewTCB, - const MemoryRegion_t * const xRegions ) -{ - StackType_t * pxTopOfStack; - UBaseType_t x; - - #if ( portUSING_MPU_WRAPPERS == 1 ) - /* Should the task be created in privileged mode? */ - BaseType_t xRunPrivileged; - - if( ( uxPriority & portPRIVILEGE_BIT ) != 0U ) - { - xRunPrivileged = pdTRUE; - } - else - { - xRunPrivileged = pdFALSE; - } - uxPriority &= ~portPRIVILEGE_BIT; - #endif /* portUSING_MPU_WRAPPERS == 1 */ - - /* Avoid dependency on memset() if it is not required. */ - #if ( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 ) - { - /* Fill the stack with a known value to assist debugging. */ - ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) ); - } - #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */ - - /* Calculate the top of stack address. This depends on whether the stack - * grows from high memory to low (as per the 80x86) or vice versa. - * portSTACK_GROWTH is used to make the result positive or negative as required - * by the port. */ - #if ( portSTACK_GROWTH < 0 ) - { - pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 ] ); - pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 !e9033 !e9078 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. Checked by assert(). */ - - /* Check the alignment of the calculated top of stack is correct. */ - configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); - - #if ( configRECORD_STACK_HIGH_ADDRESS == 1 ) - { - /* Also record the stack's high address, which may assist - * debugging. */ - pxNewTCB->pxEndOfStack = pxTopOfStack; - } - #endif /* configRECORD_STACK_HIGH_ADDRESS */ - } - #else /* portSTACK_GROWTH */ - { - pxTopOfStack = pxNewTCB->pxStack; - - /* Check the alignment of the stack buffer is correct. */ - configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); - - /* The other extreme of the stack space is required if stack checking is - * performed. */ - pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); - } - #endif /* portSTACK_GROWTH */ - - /* Store the task name in the TCB. */ - if( pcName != NULL ) - { - for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) - { - pxNewTCB->pcTaskName[ x ] = pcName[ x ]; - - /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than - * configMAX_TASK_NAME_LEN characters just in case the memory after the - * string is not accessible (extremely unlikely). */ - if( pcName[ x ] == ( char ) 0x00 ) - { - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - /* Ensure the name string is terminated in the case that the string length - * was greater or equal to configMAX_TASK_NAME_LEN. */ - pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0'; - } - else - { - /* The task has not been given a name, so just ensure there is a NULL - * terminator when it is read out. */ - pxNewTCB->pcTaskName[ 0 ] = 0x00; - } - - /* This is used as an array index so must ensure it's not too large. First - * remove the privilege bit if one is present. */ - if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) - { - uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - pxNewTCB->uxPriority = uxPriority; - #if ( configUSE_MUTEXES == 1 ) - { - pxNewTCB->uxBasePriority = uxPriority; - pxNewTCB->uxMutexesHeld = 0; - } - #endif /* configUSE_MUTEXES */ - - vListInitialiseItem( &( pxNewTCB->xStateListItem ) ); - vListInitialiseItem( &( pxNewTCB->xEventListItem ) ); - - /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get - * back to the containing TCB from a generic item in a list. */ - listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB ); - - /* Event lists are always in priority order. */ - listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB ); - - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - { - pxNewTCB->uxCriticalNesting = ( UBaseType_t ) 0U; - } - #endif /* portCRITICAL_NESTING_IN_TCB */ - - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - { - pxNewTCB->pxTaskTag = NULL; - } - #endif /* configUSE_APPLICATION_TASK_TAG */ - - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - pxNewTCB->ulRunTimeCounter = 0UL; - } - #endif /* configGENERATE_RUN_TIME_STATS */ - - #if ( portUSING_MPU_WRAPPERS == 1 ) - { - vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth ); - } - #else - { - /* Avoid compiler warning about unreferenced parameter. */ - ( void ) xRegions; - } - #endif - - #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - { - memset( ( void * ) &( pxNewTCB->pvThreadLocalStoragePointers[ 0 ] ), 0x00, sizeof( pxNewTCB->pvThreadLocalStoragePointers ) ); - } - #endif - - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - { - memset( ( void * ) &( pxNewTCB->ulNotifiedValue[ 0 ] ), 0x00, sizeof( pxNewTCB->ulNotifiedValue ) ); - memset( ( void * ) &( pxNewTCB->ucNotifyState[ 0 ] ), 0x00, sizeof( pxNewTCB->ucNotifyState ) ); - } - #endif - - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Initialise this task's Newlib reent structure. - * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html - * for additional information. */ - _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) ); - } - #endif - - #if ( INCLUDE_xTaskAbortDelay == 1 ) - { - pxNewTCB->ucDelayAborted = pdFALSE; - } - #endif - - /* Initialize the TCB stack to look as if the task was already running, - * but had been interrupted by the scheduler. The return address is set - * to the start of the task function. Once the stack has been initialised - * the top of stack variable is updated. */ - #if ( portUSING_MPU_WRAPPERS == 1 ) - { - /* If the port has capability to detect stack overflow, - * pass the stack end address to the stack initialization - * function as well. */ - #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - { - #if ( portSTACK_GROWTH < 0 ) - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged ); - } - #else /* portSTACK_GROWTH */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged ); - } - #endif /* portSTACK_GROWTH */ - } - #else /* portHAS_STACK_OVERFLOW_CHECKING */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged ); - } - #endif /* portHAS_STACK_OVERFLOW_CHECKING */ - } - #else /* portUSING_MPU_WRAPPERS */ - { - /* If the port has capability to detect stack overflow, - * pass the stack end address to the stack initialization - * function as well. */ - #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - { - #if ( portSTACK_GROWTH < 0 ) - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters ); - } - #else /* portSTACK_GROWTH */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters ); - } - #endif /* portSTACK_GROWTH */ - } - #else /* portHAS_STACK_OVERFLOW_CHECKING */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); - } - #endif /* portHAS_STACK_OVERFLOW_CHECKING */ - } - #endif /* portUSING_MPU_WRAPPERS */ - - if( pxCreatedTask != NULL ) - { - /* Pass the handle out in an anonymous way. The handle can be used to - * change the created task's priority, delete the created task, etc.*/ - *pxCreatedTask = ( TaskHandle_t ) pxNewTCB; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } -} -/*-----------------------------------------------------------*/ - -static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) -{ - /* Ensure interrupts don't access the task lists while the lists are being - * updated. */ - taskENTER_CRITICAL(); - { - uxCurrentNumberOfTasks++; - - if( pxCurrentTCB == NULL ) - { - /* There are no other tasks, or all the other tasks are in - * the suspended state - make this the current task. */ - pxCurrentTCB = pxNewTCB; - - if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) - { - /* This is the first task to be created so do the preliminary - * initialisation required. We will not recover if this call - * fails, but we will report the failure. */ - prvInitialiseTaskLists(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* If the scheduler is not already running, make this task the - * current task if it is the highest priority task to be created - * so far. */ - if( xSchedulerRunning == pdFALSE ) - { - if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) - { - pxCurrentTCB = pxNewTCB; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - uxTaskNumber++; - - #if ( configUSE_TRACE_FACILITY == 1 ) - { - /* Add a counter into the TCB for tracing only. */ - pxNewTCB->uxTCBNumber = uxTaskNumber; - } - #endif /* configUSE_TRACE_FACILITY */ - traceTASK_CREATE( pxNewTCB ); - - prvAddTaskToReadyList( pxNewTCB ); - - portSETUP_TCB( pxNewTCB ); - } - taskEXIT_CRITICAL(); - - if( xSchedulerRunning != pdFALSE ) - { - /* If the created task is of a higher priority than the current task - * then it should run now. */ - if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority ) - { - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } -} -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelete == 1 ) - - void vTaskDelete( TaskHandle_t xTaskToDelete ) - { - TCB_t * pxTCB; - - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the calling task that is - * being deleted. */ - pxTCB = prvGetTCBFromHandle( xTaskToDelete ); - - /* Remove task from the ready/delayed list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Is the task waiting on an event also? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Increment the uxTaskNumber also so kernel aware debuggers can - * detect that the task lists need re-generating. This is done before - * portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will - * not return. */ - uxTaskNumber++; - - if( pxTCB == pxCurrentTCB ) - { - /* A task is deleting itself. This cannot complete within the - * task itself, as a context switch to another task is required. - * Place the task in the termination list. The idle task will - * check the termination list and free up any memory allocated by - * the scheduler for the TCB and stack of the deleted task. */ - vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); - - /* Increment the ucTasksDeleted variable so the idle task knows - * there is a task that has been deleted and that it should therefore - * check the xTasksWaitingTermination list. */ - ++uxDeletedTasksWaitingCleanUp; - - /* Call the delete hook before portPRE_TASK_DELETE_HOOK() as - * portPRE_TASK_DELETE_HOOK() does not return in the Win32 port. */ - traceTASK_DELETE( pxTCB ); - - /* The pre-delete hook is primarily for the Windows simulator, - * in which Windows specific clean up operations are performed, - * after which it is not possible to yield away from this task - - * hence xYieldPending is used to latch that a context switch is - * required. */ - portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); - } - else - { - --uxCurrentNumberOfTasks; - traceTASK_DELETE( pxTCB ); - prvDeleteTCB( pxTCB ); - - /* Reset the next expected unblock time in case it referred to - * the task that has just been deleted. */ - prvResetNextTaskUnblockTime(); - } - } - taskEXIT_CRITICAL(); - - /* Force a reschedule if it is the currently running task that has just - * been deleted. */ - if( xSchedulerRunning != pdFALSE ) - { - if( pxTCB == pxCurrentTCB ) - { - configASSERT( uxSchedulerSuspended == 0 ); - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - -#endif /* INCLUDE_vTaskDelete */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelayUntil == 1 ) - - void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, - const TickType_t xTimeIncrement ) - { - TickType_t xTimeToWake; - BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE; - - configASSERT( pxPreviousWakeTime ); - configASSERT( ( xTimeIncrement > 0U ) ); - configASSERT( uxSchedulerSuspended == 0 ); - - vTaskSuspendAll(); - { - /* Minor optimisation. The tick count cannot change in this - * block. */ - const TickType_t xConstTickCount = xTickCount; - - /* Generate the tick time at which the task wants to wake. */ - xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; - - if( xConstTickCount < *pxPreviousWakeTime ) - { - /* The tick count has overflowed since this function was - * lasted called. In this case the only time we should ever - * actually delay is if the wake time has also overflowed, - * and the wake time is greater than the tick time. When this - * is the case it is as if neither time had overflowed. */ - if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) ) - { - xShouldDelay = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The tick time has not overflowed. In this case we will - * delay if either the wake time has overflowed, and/or the - * tick time is less than the wake time. */ - if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) ) - { - xShouldDelay = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - /* Update the wake time ready for the next call. */ - *pxPreviousWakeTime = xTimeToWake; - - if( xShouldDelay != pdFALSE ) - { - traceTASK_DELAY_UNTIL( xTimeToWake ); - - /* prvAddCurrentTaskToDelayedList() needs the block time, not - * the time to wake, so subtract the current tick count. */ - prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - xAlreadyYielded = xTaskResumeAll(); - - /* Force a reschedule if xTaskResumeAll has not already done so, we may - * have put ourselves to sleep. */ - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* INCLUDE_vTaskDelayUntil */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelay == 1 ) - - void vTaskDelay( const TickType_t xTicksToDelay ) - { - BaseType_t xAlreadyYielded = pdFALSE; - - /* A delay time of zero just forces a reschedule. */ - if( xTicksToDelay > ( TickType_t ) 0U ) - { - configASSERT( uxSchedulerSuspended == 0 ); - vTaskSuspendAll(); - { - traceTASK_DELAY(); - - /* A task that is removed from the event list while the - * scheduler is suspended will not get placed in the ready - * list or removed from the blocked list until the scheduler - * is resumed. - * - * This task cannot be in an event list as it is the currently - * executing task. */ - prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE ); - } - xAlreadyYielded = xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Force a reschedule if xTaskResumeAll has not already done so, we may - * have put ourselves to sleep. */ - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* INCLUDE_vTaskDelay */ -/*-----------------------------------------------------------*/ - -#if ( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) ) - - eTaskState eTaskGetState( TaskHandle_t xTask ) - { - eTaskState eReturn; - List_t const * pxStateList, * pxDelayedList, * pxOverflowedDelayedList; - const TCB_t * const pxTCB = xTask; - - configASSERT( pxTCB ); - - if( pxTCB == pxCurrentTCB ) - { - /* The task calling this function is querying its own state. */ - eReturn = eRunning; - } - else - { - taskENTER_CRITICAL(); - { - pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); - pxDelayedList = pxDelayedTaskList; - pxOverflowedDelayedList = pxOverflowDelayedTaskList; - } - taskEXIT_CRITICAL(); - - if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) ) - { - /* The task being queried is referenced from one of the Blocked - * lists. */ - eReturn = eBlocked; - } - - #if ( INCLUDE_vTaskSuspend == 1 ) - else if( pxStateList == &xSuspendedTaskList ) - { - /* The task being queried is referenced from the suspended - * list. Is it genuinely suspended or is it blocked - * indefinitely? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) - { - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - { - BaseType_t x; - - /* The task does not appear on the event list item of - * and of the RTOS objects, but could still be in the - * blocked state if it is waiting on its notification - * rather than waiting on an object. If not, is - * suspended. */ - eReturn = eSuspended; - - for( x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ ) - { - if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION ) - { - eReturn = eBlocked; - break; - } - } - } - #else /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ - { - eReturn = eSuspended; - } - #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ - } - else - { - eReturn = eBlocked; - } - } - #endif /* if ( INCLUDE_vTaskSuspend == 1 ) */ - - #if ( INCLUDE_vTaskDelete == 1 ) - else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) - { - /* The task being queried is referenced from the deleted - * tasks list, or it is not referenced from any lists at - * all. */ - eReturn = eDeleted; - } - #endif - - else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */ - { - /* If the task is not in any other state, it must be in the - * Ready (including pending ready) state. */ - eReturn = eReady; - } - } - - return eReturn; - } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ - -#endif /* INCLUDE_eTaskGetState */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_uxTaskPriorityGet == 1 ) - - UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) - { - TCB_t const * pxTCB; - UBaseType_t uxReturn; - - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the priority of the task - * that called uxTaskPriorityGet() that is being queried. */ - pxTCB = prvGetTCBFromHandle( xTask ); - uxReturn = pxTCB->uxPriority; - } - taskEXIT_CRITICAL(); - - return uxReturn; - } - -#endif /* INCLUDE_uxTaskPriorityGet */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_uxTaskPriorityGet == 1 ) - - UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) - { - TCB_t const * pxTCB; - UBaseType_t uxReturn, uxSavedInterruptState; - - /* RTOS ports that support interrupt nesting have the concept of a - * maximum system call (or maximum API call) interrupt priority. - * Interrupts that are above the maximum system call priority are keep - * permanently enabled, even when the RTOS kernel is in a critical section, - * but cannot make any calls to FreeRTOS API functions. If configASSERT() - * is defined in FreeRTOSConfig.h then - * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - * failure if a FreeRTOS API function is called from an interrupt that has - * been assigned a priority above the configured maximum system call - * priority. Only FreeRTOS functions that end in FromISR can be called - * from interrupts that have been assigned a priority at or (logically) - * below the maximum system call interrupt priority. FreeRTOS maintains a - * separate interrupt safe API to ensure interrupt entry is as fast and as - * simple as possible. More information (albeit Cortex-M specific) is - * provided on the following link: - * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR(); - { - /* If null is passed in here then it is the priority of the calling - * task that is being queried. */ - pxTCB = prvGetTCBFromHandle( xTask ); - uxReturn = pxTCB->uxPriority; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState ); - - return uxReturn; - } - -#endif /* INCLUDE_uxTaskPriorityGet */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskPrioritySet == 1 ) - - void vTaskPrioritySet( TaskHandle_t xTask, - UBaseType_t uxNewPriority ) - { - TCB_t * pxTCB; - UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry; - BaseType_t xYieldRequired = pdFALSE; - - configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) ); - - /* Ensure the new priority is valid. */ - if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) - { - uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the priority of the calling - * task that is being changed. */ - pxTCB = prvGetTCBFromHandle( xTask ); - - traceTASK_PRIORITY_SET( pxTCB, uxNewPriority ); - - #if ( configUSE_MUTEXES == 1 ) - { - uxCurrentBasePriority = pxTCB->uxBasePriority; - } - #else - { - uxCurrentBasePriority = pxTCB->uxPriority; - } - #endif - - if( uxCurrentBasePriority != uxNewPriority ) - { - /* The priority change may have readied a task of higher - * priority than the calling task. */ - if( uxNewPriority > uxCurrentBasePriority ) - { - if( pxTCB != pxCurrentTCB ) - { - /* The priority of a task other than the currently - * running task is being raised. Is the priority being - * raised above that of the running task? */ - if( uxNewPriority >= pxCurrentTCB->uxPriority ) - { - xYieldRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The priority of the running task is being raised, - * but the running task must already be the highest - * priority task able to run so no yield is required. */ - } - } - else if( pxTCB == pxCurrentTCB ) - { - /* Setting the priority of the running task down means - * there may now be another task of higher priority that - * is ready to execute. */ - xYieldRequired = pdTRUE; - } - else - { - /* Setting the priority of any other task down does not - * require a yield as the running task must be above the - * new priority of the task being modified. */ - } - - /* Remember the ready list the task might be referenced from - * before its uxPriority member is changed so the - * taskRESET_READY_PRIORITY() macro can function correctly. */ - uxPriorityUsedOnEntry = pxTCB->uxPriority; - - #if ( configUSE_MUTEXES == 1 ) - { - /* Only change the priority being used if the task is not - * currently using an inherited priority. */ - if( pxTCB->uxBasePriority == pxTCB->uxPriority ) - { - pxTCB->uxPriority = uxNewPriority; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* The base priority gets set whatever. */ - pxTCB->uxBasePriority = uxNewPriority; - } - #else /* if ( configUSE_MUTEXES == 1 ) */ - { - pxTCB->uxPriority = uxNewPriority; - } - #endif /* if ( configUSE_MUTEXES == 1 ) */ - - /* Only reset the event list item value if the value is not - * being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* If the task is in the blocked or suspended list we need do - * nothing more than change its priority variable. However, if - * the task is in a ready list it needs to be removed and placed - * in the list appropriate to its new priority. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - /* The task is currently in its ready list - remove before - * adding it to it's new ready list. As we are in a critical - * section we can do this even if the scheduler is suspended. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - /* It is known that the task is in its ready list so - * there is no need to check again and the port level - * reset macro can be called directly. */ - portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - prvAddTaskToReadyList( pxTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( xYieldRequired != pdFALSE ) - { - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Remove compiler warning about unused variables when the port - * optimised task selection is not being used. */ - ( void ) uxPriorityUsedOnEntry; - } - } - taskEXIT_CRITICAL(); - } - -#endif /* INCLUDE_vTaskPrioritySet */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskSuspend == 1 ) - - void vTaskSuspend( TaskHandle_t xTaskToSuspend ) - { - TCB_t * pxTCB; - - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the running task that is - * being suspended. */ - pxTCB = prvGetTCBFromHandle( xTaskToSuspend ); - - traceTASK_SUSPEND( pxTCB ); - - /* Remove task from the ready/delayed list and place in the - * suspended list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Is the task waiting on an event also? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ); - - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - { - BaseType_t x; - - for( x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ ) - { - if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION ) - { - /* The task was blocked to wait for a notification, but is - * now suspended, so no notification was received. */ - pxTCB->ucNotifyState[ x ] = taskNOT_WAITING_NOTIFICATION; - } - } - } - #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ - } - taskEXIT_CRITICAL(); - - if( xSchedulerRunning != pdFALSE ) - { - /* Reset the next expected unblock time in case it referred to the - * task that is now in the Suspended state. */ - taskENTER_CRITICAL(); - { - prvResetNextTaskUnblockTime(); - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( pxTCB == pxCurrentTCB ) - { - if( xSchedulerRunning != pdFALSE ) - { - /* The current task has just been suspended. */ - configASSERT( uxSchedulerSuspended == 0 ); - portYIELD_WITHIN_API(); - } - else - { - /* The scheduler is not running, but the task that was pointed - * to by pxCurrentTCB has just been suspended and pxCurrentTCB - * must be adjusted to point to a different task. */ - if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */ - { - /* No other tasks are ready, so set pxCurrentTCB back to - * NULL so when the next task is created pxCurrentTCB will - * be set to point to it no matter what its relative priority - * is. */ - pxCurrentTCB = NULL; - } - else - { - vTaskSwitchContext(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* INCLUDE_vTaskSuspend */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskSuspend == 1 ) - - static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) - { - BaseType_t xReturn = pdFALSE; - const TCB_t * const pxTCB = xTask; - - /* Accesses xPendingReadyList so must be called from a critical - * section. */ - - /* It does not make sense to check if the calling task is suspended. */ - configASSERT( xTask ); - - /* Is the task being resumed actually in the suspended list? */ - if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - /* Has the task already been resumed from within an ISR? */ - if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) - { - /* Is it in the suspended list because it is in the Suspended - * state, or because is is blocked with no timeout? */ - if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */ - { - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xReturn; - } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ - -#endif /* INCLUDE_vTaskSuspend */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskSuspend == 1 ) - - void vTaskResume( TaskHandle_t xTaskToResume ) - { - TCB_t * const pxTCB = xTaskToResume; - - /* It does not make sense to resume the calling task. */ - configASSERT( xTaskToResume ); - - /* The parameter cannot be NULL as it is impossible to resume the - * currently executing task. */ - if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) ) - { - taskENTER_CRITICAL(); - { - if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) - { - traceTASK_RESUME( pxTCB ); - - /* The ready list can be accessed even if the scheduler is - * suspended because this is inside a critical section. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - - /* A higher priority task may have just been resumed. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - /* This yield may not cause the task just resumed to run, - * but will leave the lists in the correct state for the - * next yield. */ - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* INCLUDE_vTaskSuspend */ - -/*-----------------------------------------------------------*/ - -#if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) - - BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) - { - BaseType_t xYieldRequired = pdFALSE; - TCB_t * const pxTCB = xTaskToResume; - UBaseType_t uxSavedInterruptStatus; - - configASSERT( xTaskToResume ); - - /* RTOS ports that support interrupt nesting have the concept of a - * maximum system call (or maximum API call) interrupt priority. - * Interrupts that are above the maximum system call priority are keep - * permanently enabled, even when the RTOS kernel is in a critical section, - * but cannot make any calls to FreeRTOS API functions. If configASSERT() - * is defined in FreeRTOSConfig.h then - * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - * failure if a FreeRTOS API function is called from an interrupt that has - * been assigned a priority above the configured maximum system call - * priority. Only FreeRTOS functions that end in FromISR can be called - * from interrupts that have been assigned a priority at or (logically) - * below the maximum system call interrupt priority. FreeRTOS maintains a - * separate interrupt safe API to ensure interrupt entry is as fast and as - * simple as possible. More information (albeit Cortex-M specific) is - * provided on the following link: - * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) - { - traceTASK_RESUME_FROM_ISR( pxTCB ); - - /* Check the ready lists can be accessed. */ - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - /* Ready lists can be accessed so move the task from the - * suspended list to the ready list directly. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xYieldRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed or ready lists cannot be accessed so the task - * is held in the pending ready list until the scheduler is - * unsuspended. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xYieldRequired; - } - -#endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */ -/*-----------------------------------------------------------*/ - -void vTaskStartScheduler( void ) -{ - BaseType_t xReturn; - - /* Add the idle task at the lowest priority. */ - #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - StaticTask_t * pxIdleTaskTCBBuffer = NULL; - StackType_t * pxIdleTaskStackBuffer = NULL; - uint32_t ulIdleTaskStackSize; - - /* The Idle task is created using user provided RAM - obtain the - * address of the RAM then create the idle task. */ - vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); - xIdleTaskHandle = xTaskCreateStatic( prvIdleTask, - configIDLE_TASK_NAME, - ulIdleTaskStackSize, - ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ - portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ - pxIdleTaskStackBuffer, - pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ - - if( xIdleTaskHandle != NULL ) - { - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } - } - #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ - { - /* The Idle task is being created using dynamically allocated RAM. */ - xReturn = xTaskCreate( prvIdleTask, - configIDLE_TASK_NAME, - configMINIMAL_STACK_SIZE, - ( void * ) NULL, - portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ - &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - - #if ( configUSE_TIMERS == 1 ) - { - if( xReturn == pdPASS ) - { - xReturn = xTimerCreateTimerTask(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TIMERS */ - - if( xReturn == pdPASS ) - { - /* freertos_tasks_c_additions_init() should only be called if the user - * definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is - * the only macro called by the function. */ - #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - { - freertos_tasks_c_additions_init(); - } - #endif - - /* Interrupts are turned off here, to ensure a tick does not occur - * before or during the call to xPortStartScheduler(). The stacks of - * the created tasks contain a status word with interrupts switched on - * so interrupts will automatically get re-enabled when the first task - * starts to run. */ - portDISABLE_INTERRUPTS(); - - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Switch Newlib's _impure_ptr variable to point to the _reent - * structure specific to the task that will run first. - * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html - * for additional information. */ - _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ - - xNextTaskUnblockTime = portMAX_DELAY; - xSchedulerRunning = pdTRUE; - xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; - - /* If configGENERATE_RUN_TIME_STATS is defined then the following - * macro must be defined to configure the timer/counter used to generate - * the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS - * is set to 0 and the following line fails to build then ensure you do not - * have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your - * FreeRTOSConfig.h file. */ - portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); - - traceTASK_SWITCHED_IN(); - - /* Setting up the timer tick is hardware specific and thus in the - * portable interface. */ - if( xPortStartScheduler() != pdFALSE ) - { - /* Should not reach here as if the scheduler is running the - * function will not return. */ - } - else - { - /* Should only reach here if a task calls xTaskEndScheduler(). */ - } - } - else - { - /* This line will only be reached if the kernel could not be started, - * because there was not enough FreeRTOS heap to create the idle task - * or the timer task. */ - configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); - } - - /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, - * meaning xIdleTaskHandle is not used anywhere else. */ - ( void ) xIdleTaskHandle; -} -/*-----------------------------------------------------------*/ - -void vTaskEndScheduler( void ) -{ - /* Stop the scheduler interrupts and call the portable scheduler end - * routine so the original ISRs can be restored if necessary. The port - * layer must ensure interrupts enable bit is left in the correct state. */ - portDISABLE_INTERRUPTS(); - xSchedulerRunning = pdFALSE; - vPortEndScheduler(); -} -/*----------------------------------------------------------*/ - -void vTaskSuspendAll( void ) -{ - /* A critical section is not required as the variable is of type - * BaseType_t. Please read Richard Barry's reply in the following link to a - * post in the FreeRTOS support forum before reporting this as a bug! - - * http://goo.gl/wu4acr */ - - /* portSOFRWARE_BARRIER() is only implemented for emulated/simulated ports that - * do not otherwise exhibit real time behaviour. */ - portSOFTWARE_BARRIER(); - - /* The scheduler is suspended if uxSchedulerSuspended is non-zero. An increment - * is used to allow calls to vTaskSuspendAll() to nest. */ - ++uxSchedulerSuspended; - - /* Enforces ordering for ports and optimised compilers that may otherwise place - * the above increment elsewhere. */ - portMEMORY_BARRIER(); -} -/*----------------------------------------------------------*/ - -#if ( configUSE_TICKLESS_IDLE != 0 ) - - static TickType_t prvGetExpectedIdleTime( void ) - { - TickType_t xReturn; - UBaseType_t uxHigherPriorityReadyTasks = pdFALSE; - - /* uxHigherPriorityReadyTasks takes care of the case where - * configUSE_PREEMPTION is 0, so there may be tasks above the idle priority - * task that are in the Ready state, even though the idle task is - * running. */ - #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) - { - if( uxTopReadyPriority > tskIDLE_PRIORITY ) - { - uxHigherPriorityReadyTasks = pdTRUE; - } - } - #else - { - const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01; - - /* When port optimised task selection is used the uxTopReadyPriority - * variable is used as a bit map. If bits other than the least - * significant bit are set then there are tasks that have a priority - * above the idle priority that are in the Ready state. This takes - * care of the case where the co-operative scheduler is in use. */ - if( uxTopReadyPriority > uxLeastSignificantBit ) - { - uxHigherPriorityReadyTasks = pdTRUE; - } - } - #endif /* if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) */ - - if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) - { - xReturn = 0; - } - else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 ) - { - /* There are other idle priority tasks in the ready state. If - * time slicing is used then the very next tick interrupt must be - * processed. */ - xReturn = 0; - } - else if( uxHigherPriorityReadyTasks != pdFALSE ) - { - /* There are tasks in the Ready state that have a priority above the - * idle priority. This path can only be reached if - * configUSE_PREEMPTION is 0. */ - xReturn = 0; - } - else - { - xReturn = xNextTaskUnblockTime - xTickCount; - } - - return xReturn; - } - -#endif /* configUSE_TICKLESS_IDLE */ -/*----------------------------------------------------------*/ - -BaseType_t xTaskResumeAll( void ) -{ - TCB_t * pxTCB = NULL; - BaseType_t xAlreadyYielded = pdFALSE; - - /* If uxSchedulerSuspended is zero then this function does not match a - * previous call to vTaskSuspendAll(). */ - configASSERT( uxSchedulerSuspended ); - - /* It is possible that an ISR caused a task to be removed from an event - * list while the scheduler was suspended. If this was the case then the - * removed task will have been added to the xPendingReadyList. Once the - * scheduler has been resumed it is safe to move all the pending ready - * tasks from this list into their appropriate ready list. */ - taskENTER_CRITICAL(); - { - --uxSchedulerSuspended; - - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U ) - { - /* Move any readied tasks from the pending list into the - * appropriate ready list. */ - while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) - { - pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - - /* If the moved task has a priority higher than the current - * task then a yield must be performed. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - if( pxTCB != NULL ) - { - /* A task was unblocked while the scheduler was suspended, - * which may have prevented the next unblock time from being - * re-calculated, in which case re-calculate it now. Mainly - * important for low power tickless implementations, where - * this can prevent an unnecessary exit from low power - * state. */ - prvResetNextTaskUnblockTime(); - } - - /* If any ticks occurred while the scheduler was suspended then - * they should be processed now. This ensures the tick count does - * not slip, and that any delayed tasks are resumed at the correct - * time. */ - { - TickType_t xPendedCounts = xPendedTicks; /* Non-volatile copy. */ - - if( xPendedCounts > ( TickType_t ) 0U ) - { - do - { - if( xTaskIncrementTick() != pdFALSE ) - { - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - --xPendedCounts; - } while( xPendedCounts > ( TickType_t ) 0U ); - - xPendedTicks = 0; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - if( xYieldPending != pdFALSE ) - { - #if ( configUSE_PREEMPTION != 0 ) - { - xAlreadyYielded = pdTRUE; - } - #endif - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - return xAlreadyYielded; -} -/*-----------------------------------------------------------*/ - -TickType_t xTaskGetTickCount( void ) -{ - TickType_t xTicks; - - /* Critical section required if running on a 16 bit processor. */ - portTICK_TYPE_ENTER_CRITICAL(); - { - xTicks = xTickCount; - } - portTICK_TYPE_EXIT_CRITICAL(); - - return xTicks; -} -/*-----------------------------------------------------------*/ - -TickType_t xTaskGetTickCountFromISR( void ) -{ - TickType_t xReturn; - UBaseType_t uxSavedInterruptStatus; - - /* RTOS ports that support interrupt nesting have the concept of a maximum - * system call (or maximum API call) interrupt priority. Interrupts that are - * above the maximum system call priority are kept permanently enabled, even - * when the RTOS kernel is in a critical section, but cannot make any calls to - * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - * failure if a FreeRTOS API function is called from an interrupt that has been - * assigned a priority above the configured maximum system call priority. - * Only FreeRTOS functions that end in FromISR can be called from interrupts - * that have been assigned a priority at or (logically) below the maximum - * system call interrupt priority. FreeRTOS maintains a separate interrupt - * safe API to ensure interrupt entry is as fast and as simple as possible. - * More information (albeit Cortex-M specific) is provided on the following - * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR(); - { - xReturn = xTickCount; - } - portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -UBaseType_t uxTaskGetNumberOfTasks( void ) -{ - /* A critical section is not required because the variables are of type - * BaseType_t. */ - return uxCurrentNumberOfTasks; -} -/*-----------------------------------------------------------*/ - -char * pcTaskGetName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ -{ - TCB_t * pxTCB; - - /* If null is passed in here then the name of the calling task is being - * queried. */ - pxTCB = prvGetTCBFromHandle( xTaskToQuery ); - configASSERT( pxTCB ); - return &( pxTCB->pcTaskName[ 0 ] ); -} -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskGetHandle == 1 ) - - static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList, - const char pcNameToQuery[] ) - { - TCB_t * pxNextTCB, * pxFirstTCB, * pxReturn = NULL; - UBaseType_t x; - char cNextChar; - BaseType_t xBreakLoop; - - /* This function is called with the scheduler suspended. */ - - if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) - { - listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - - do - { - listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - - /* Check each character in the name looking for a match or - * mismatch. */ - xBreakLoop = pdFALSE; - - for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) - { - cNextChar = pxNextTCB->pcTaskName[ x ]; - - if( cNextChar != pcNameToQuery[ x ] ) - { - /* Characters didn't match. */ - xBreakLoop = pdTRUE; - } - else if( cNextChar == ( char ) 0x00 ) - { - /* Both strings terminated, a match must have been - * found. */ - pxReturn = pxNextTCB; - xBreakLoop = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( xBreakLoop != pdFALSE ) - { - break; - } - } - - if( pxReturn != NULL ) - { - /* The handle has been found. */ - break; - } - } while( pxNextTCB != pxFirstTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return pxReturn; - } - -#endif /* INCLUDE_xTaskGetHandle */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskGetHandle == 1 ) - - TaskHandle_t xTaskGetHandle( const char * pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t uxQueue = configMAX_PRIORITIES; - TCB_t * pxTCB; - - /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */ - configASSERT( strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN ); - - vTaskSuspendAll(); - { - /* Search the ready lists. */ - do - { - uxQueue--; - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery ); - - if( pxTCB != NULL ) - { - /* Found the handle. */ - break; - } - } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - /* Search the delayed lists. */ - if( pxTCB == NULL ) - { - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery ); - } - - if( pxTCB == NULL ) - { - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery ); - } - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - if( pxTCB == NULL ) - { - /* Search the suspended list. */ - pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery ); - } - } - #endif - - #if ( INCLUDE_vTaskDelete == 1 ) - { - if( pxTCB == NULL ) - { - /* Search the deleted list. */ - pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery ); - } - } - #endif - } - ( void ) xTaskResumeAll(); - - return pxTCB; - } - -#endif /* INCLUDE_xTaskGetHandle */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, - const UBaseType_t uxArraySize, - uint32_t * const pulTotalRunTime ) - { - UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES; - - vTaskSuspendAll(); - { - /* Is there a space in the array for each task in the system? */ - if( uxArraySize >= uxCurrentNumberOfTasks ) - { - /* Fill in an TaskStatus_t structure with information on each - * task in the Ready state. */ - do - { - uxQueue--; - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady ); - } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - /* Fill in an TaskStatus_t structure with information on each - * task in the Blocked state. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked ); - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked ); - - #if ( INCLUDE_vTaskDelete == 1 ) - { - /* Fill in an TaskStatus_t structure with information on - * each task that has been deleted but not yet cleaned up. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted ); - } - #endif - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - /* Fill in an TaskStatus_t structure with information on - * each task in the Suspended state. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended ); - } - #endif - - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - if( pulTotalRunTime != NULL ) - { - #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE - portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) ); - #else - *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); - #endif - } - } - #else /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */ - { - if( pulTotalRunTime != NULL ) - { - *pulTotalRunTime = 0; - } - } - #endif /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - ( void ) xTaskResumeAll(); - - return uxTask; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) - - TaskHandle_t xTaskGetIdleTaskHandle( void ) - { - /* If xTaskGetIdleTaskHandle() is called before the scheduler has been - * started, then xIdleTaskHandle will be NULL. */ - configASSERT( ( xIdleTaskHandle != NULL ) ); - return xIdleTaskHandle; - } - -#endif /* INCLUDE_xTaskGetIdleTaskHandle */ -/*----------------------------------------------------------*/ - -/* This conditional compilation should use inequality to 0, not equality to 1. - * This is to ensure vTaskStepTick() is available when user defined low power mode - * implementations require configUSE_TICKLESS_IDLE to be set to a value other than - * 1. */ -#if ( configUSE_TICKLESS_IDLE != 0 ) - - void vTaskStepTick( const TickType_t xTicksToJump ) - { - /* Correct the tick count value after a period during which the tick - * was suppressed. Note this does *not* call the tick hook function for - * each stepped tick. */ - configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime ); - xTickCount += xTicksToJump; - traceINCREASE_TICK_COUNT( xTicksToJump ); - } - -#endif /* configUSE_TICKLESS_IDLE */ -/*----------------------------------------------------------*/ - -BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) -{ - BaseType_t xYieldOccurred; - - /* Must not be called with the scheduler suspended as the implementation - * relies on xPendedTicks being wound down to 0 in xTaskResumeAll(). */ - configASSERT( uxSchedulerSuspended == 0 ); - - /* Use xPendedTicks to mimic xTicksToCatchUp number of ticks occurring when - * the scheduler is suspended so the ticks are executed in xTaskResumeAll(). */ - vTaskSuspendAll(); - xPendedTicks += xTicksToCatchUp; - xYieldOccurred = xTaskResumeAll(); - - return xYieldOccurred; -} -/*----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskAbortDelay == 1 ) - - BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) - { - TCB_t * pxTCB = xTask; - BaseType_t xReturn; - - configASSERT( pxTCB ); - - vTaskSuspendAll(); - { - /* A task can only be prematurely removed from the Blocked state if - * it is actually in the Blocked state. */ - if( eTaskGetState( xTask ) == eBlocked ) - { - xReturn = pdPASS; - - /* Remove the reference to the task from the blocked list. An - * interrupt won't touch the xStateListItem because the - * scheduler is suspended. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - - /* Is the task waiting on an event also? If so remove it from - * the event list too. Interrupts can touch the event list item, - * even though the scheduler is suspended, so a critical section - * is used. */ - taskENTER_CRITICAL(); - { - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - - /* This lets the task know it was forcibly removed from the - * blocked state so it should not re-evaluate its block time and - * then block again. */ - pxTCB->ucDelayAborted = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - /* Place the unblocked task into the appropriate ready list. */ - prvAddTaskToReadyList( pxTCB ); - - /* A task being unblocked cannot cause an immediate context - * switch if preemption is turned off. */ - #if ( configUSE_PREEMPTION == 1 ) - { - /* Preemption is on, but a context switch should only be - * performed if the unblocked task has a priority that is - * equal to or higher than the currently executing task. */ - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* Pend the yield to be performed when the scheduler - * is unsuspended. */ - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ - } - else - { - xReturn = pdFAIL; - } - } - ( void ) xTaskResumeAll(); - - return xReturn; - } - -#endif /* INCLUDE_xTaskAbortDelay */ -/*----------------------------------------------------------*/ - -BaseType_t xTaskIncrementTick( void ) -{ - TCB_t * pxTCB; - TickType_t xItemValue; - BaseType_t xSwitchRequired = pdFALSE; - - /* Called by the portable layer each time a tick interrupt occurs. - * Increments the tick then checks to see if the new tick value will cause any - * tasks to be unblocked. */ - traceTASK_INCREMENT_TICK( xTickCount ); - - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - /* Minor optimisation. The tick count cannot change in this - * block. */ - const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1; - - /* Increment the RTOS tick, switching the delayed and overflowed - * delayed lists if it wraps to 0. */ - xTickCount = xConstTickCount; - - if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */ - { - taskSWITCH_DELAYED_LISTS(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* See if this tick has made a timeout expire. Tasks are stored in - * the queue in the order of their wake time - meaning once one task - * has been found whose block time has not expired there is no need to - * look any further down the list. */ - if( xConstTickCount >= xNextTaskUnblockTime ) - { - for( ; ; ) - { - if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) - { - /* The delayed list is empty. Set xNextTaskUnblockTime - * to the maximum possible value so it is extremely - * unlikely that the - * if( xTickCount >= xNextTaskUnblockTime ) test will pass - * next time through. */ - xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - break; - } - else - { - /* The delayed list is not empty, get the value of the - * item at the head of the delayed list. This is the time - * at which the task at the head of the delayed list must - * be removed from the Blocked state. */ - pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); - - if( xConstTickCount < xItemValue ) - { - /* It is not time to unblock this item yet, but the - * item value is the time at which the task at the head - * of the blocked list must be removed from the Blocked - * state - so record the item value in - * xNextTaskUnblockTime. */ - xNextTaskUnblockTime = xItemValue; - break; /*lint !e9011 Code structure here is deedmed easier to understand with multiple breaks. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* It is time to remove the item from the Blocked state. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - - /* Is the task waiting on an event also? If so remove - * it from the event list. */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Place the unblocked task into the appropriate ready - * list. */ - prvAddTaskToReadyList( pxTCB ); - - /* A task being unblocked cannot cause an immediate - * context switch if preemption is turned off. */ - #if ( configUSE_PREEMPTION == 1 ) - { - /* Preemption is on, but a context switch should - * only be performed if the unblocked task has a - * priority that is equal to or higher than the - * currently executing task. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ - } - } - } - - /* Tasks of equal priority to the currently running task will share - * processing time (time slice) if preemption is on, and the application - * writer has not explicitly turned time slicing off. */ - #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) - { - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */ - - #if ( configUSE_TICK_HOOK == 1 ) - { - /* Guard against the tick hook being called when the pended tick - * count is being unwound (when the scheduler is being unlocked). */ - if( xPendedTicks == ( TickType_t ) 0 ) - { - vApplicationTickHook(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TICK_HOOK */ - - #if ( configUSE_PREEMPTION == 1 ) - { - if( xYieldPending != pdFALSE ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ - } - else - { - ++xPendedTicks; - - /* The tick hook gets called at regular intervals, even if the - * scheduler is locked. */ - #if ( configUSE_TICK_HOOK == 1 ) - { - vApplicationTickHook(); - } - #endif - } - - return xSwitchRequired; -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_APPLICATION_TASK_TAG == 1 ) - - void vTaskSetApplicationTaskTag( TaskHandle_t xTask, - TaskHookFunction_t pxHookFunction ) - { - TCB_t * xTCB; - - /* If xTask is NULL then it is the task hook of the calling task that is - * getting set. */ - if( xTask == NULL ) - { - xTCB = ( TCB_t * ) pxCurrentTCB; - } - else - { - xTCB = xTask; - } - - /* Save the hook function in the TCB. A critical section is required as - * the value can be accessed from an interrupt. */ - taskENTER_CRITICAL(); - { - xTCB->pxTaskTag = pxHookFunction; - } - taskEXIT_CRITICAL(); - } - -#endif /* configUSE_APPLICATION_TASK_TAG */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_APPLICATION_TASK_TAG == 1 ) - - TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) - { - TCB_t * pxTCB; - TaskHookFunction_t xReturn; - - /* If xTask is NULL then set the calling task's hook. */ - pxTCB = prvGetTCBFromHandle( xTask ); - - /* Save the hook function in the TCB. A critical section is required as - * the value can be accessed from an interrupt. */ - taskENTER_CRITICAL(); - { - xReturn = pxTCB->pxTaskTag; - } - taskEXIT_CRITICAL(); - - return xReturn; - } - -#endif /* configUSE_APPLICATION_TASK_TAG */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_APPLICATION_TASK_TAG == 1 ) - - TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) - { - TCB_t * pxTCB; - TaskHookFunction_t xReturn; - UBaseType_t uxSavedInterruptStatus; - - /* If xTask is NULL then set the calling task's hook. */ - pxTCB = prvGetTCBFromHandle( xTask ); - - /* Save the hook function in the TCB. A critical section is required as - * the value can be accessed from an interrupt. */ - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - xReturn = pxTCB->pxTaskTag; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; - } - -#endif /* configUSE_APPLICATION_TASK_TAG */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_APPLICATION_TASK_TAG == 1 ) - - BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, - void * pvParameter ) - { - TCB_t * xTCB; - BaseType_t xReturn; - - /* If xTask is NULL then we are calling our own task hook. */ - if( xTask == NULL ) - { - xTCB = pxCurrentTCB; - } - else - { - xTCB = xTask; - } - - if( xTCB->pxTaskTag != NULL ) - { - xReturn = xTCB->pxTaskTag( pvParameter ); - } - else - { - xReturn = pdFAIL; - } - - return xReturn; - } - -#endif /* configUSE_APPLICATION_TASK_TAG */ -/*-----------------------------------------------------------*/ - -void vTaskSwitchContext( void ) -{ - if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE ) - { - /* The scheduler is currently suspended - do not allow a context - * switch. */ - xYieldPending = pdTRUE; - } - else - { - xYieldPending = pdFALSE; - traceTASK_SWITCHED_OUT(); - - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE - portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime ); - #else - ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); - #endif - - /* Add the amount of time the task has been running to the - * accumulated time so far. The time the task started running was - * stored in ulTaskSwitchedInTime. Note that there is no overflow - * protection here so count values are only valid until the timer - * overflows. The guard against negative values is to protect - * against suspect run time stat counter implementations - which - * are provided by the application, not the kernel. */ - if( ulTotalRunTime > ulTaskSwitchedInTime ) - { - pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - ulTaskSwitchedInTime = ulTotalRunTime; - } - #endif /* configGENERATE_RUN_TIME_STATS */ - - /* Check for stack overflow, if configured. */ - taskCHECK_FOR_STACK_OVERFLOW(); - - /* Before the currently running task is switched out, save its errno. */ - #if ( configUSE_POSIX_ERRNO == 1 ) - { - pxCurrentTCB->iTaskErrno = FreeRTOS_errno; - } - #endif - - /* Select a new task to run using either the generic C or port - * optimised asm code. */ - taskSELECT_HIGHEST_PRIORITY_TASK(); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - traceTASK_SWITCHED_IN(); - - /* After the new task is switched in, update the global errno. */ - #if ( configUSE_POSIX_ERRNO == 1 ) - { - FreeRTOS_errno = pxCurrentTCB->iTaskErrno; - } - #endif - - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Switch Newlib's _impure_ptr variable to point to the _reent - * structure specific to this task. - * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html - * for additional information. */ - _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ - } -} -/*-----------------------------------------------------------*/ - -void vTaskPlaceOnEventList( List_t * const pxEventList, - const TickType_t xTicksToWait ) -{ - configASSERT( pxEventList ); - - /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE - * SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */ - - /* Place the event list item of the TCB in the appropriate event list. - * This is placed in the list in priority order so the highest priority task - * is the first to be woken by the event. The queue that contains the event - * list is locked, preventing simultaneous access from interrupts. */ - vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); -} -/*-----------------------------------------------------------*/ - -void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, - const TickType_t xItemValue, - const TickType_t xTicksToWait ) -{ - configASSERT( pxEventList ); - - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by - * the event groups implementation. */ - configASSERT( uxSchedulerSuspended != 0 ); - - /* Store the item value in the event list item. It is safe to access the - * event list item here as interrupts won't access the event list item of a - * task that is not in the Blocked state. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); - - /* Place the event list item of the TCB at the end of the appropriate event - * list. It is safe to access the event list here because it is part of an - * event group implementation - and interrupts don't access event groups - * directly (instead they access them indirectly by pending function calls to - * the task level). */ - vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_TIMERS == 1 ) - - void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, - TickType_t xTicksToWait, - const BaseType_t xWaitIndefinitely ) - { - configASSERT( pxEventList ); - - /* This function should not be called by application code hence the - * 'Restricted' in its name. It is not part of the public API. It is - * designed for use by kernel code, and has special calling requirements - - * it should be called with the scheduler suspended. */ - - - /* Place the event list item of the TCB in the appropriate event list. - * In this case it is assume that this is the only task that is going to - * be waiting on this event list, so the faster vListInsertEnd() function - * can be used in place of vListInsert. */ - vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - - /* If the task should block indefinitely then set the block time to a - * value that will be recognised as an indefinite delay inside the - * prvAddCurrentTaskToDelayedList() function. */ - if( xWaitIndefinitely != pdFALSE ) - { - xTicksToWait = portMAX_DELAY; - } - - traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) ); - prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely ); - } - -#endif /* configUSE_TIMERS */ -/*-----------------------------------------------------------*/ - -BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) -{ - TCB_t * pxUnblockedTCB; - BaseType_t xReturn; - - /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be - * called from a critical section within an ISR. */ - - /* The event list is sorted in priority order, so the first in the list can - * be removed as it is known to be the highest priority. Remove the TCB from - * the delayed list, and add it to the ready list. - * - * If an event is for a queue that is locked then this function will never - * get called - the lock count on the queue will get modified instead. This - * means exclusive access to the event list is guaranteed here. - * - * This function assumes that a check has already been made to ensure that - * pxEventList is not empty. */ - pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - configASSERT( pxUnblockedTCB ); - ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) ); - - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxUnblockedTCB ); - - #if ( configUSE_TICKLESS_IDLE != 0 ) - { - /* If a task is blocked on a kernel object then xNextTaskUnblockTime - * might be set to the blocked task's time out time. If the task is - * unblocked for a reason other than a timeout xNextTaskUnblockTime is - * normally left unchanged, because it is automatically reset to a new - * value when the tick count equals xNextTaskUnblockTime. However if - * tickless idling is used it might be more important to enter sleep mode - * at the earliest possible time - so reset xNextTaskUnblockTime here to - * ensure it is updated at the earliest possible time. */ - prvResetNextTaskUnblockTime(); - } - #endif - } - else - { - /* The delayed and ready lists cannot be accessed, so hold this task - * pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); - } - - if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* Return true if the task removed from the event list has a higher - * priority than the calling task. This allows the calling task to know if - * it should force a context switch now. */ - xReturn = pdTRUE; - - /* Mark that a yield is pending in case the user is not using the - * "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, - const TickType_t xItemValue ) -{ - TCB_t * pxUnblockedTCB; - - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by - * the event flags implementation. */ - configASSERT( uxSchedulerSuspended != pdFALSE ); - - /* Store the new item value in the event list. */ - listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); - - /* Remove the event list form the event flag. Interrupts do not access - * event flags. */ - pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - configASSERT( pxUnblockedTCB ); - ( void ) uxListRemove( pxEventListItem ); - - #if ( configUSE_TICKLESS_IDLE != 0 ) - { - /* If a task is blocked on a kernel object then xNextTaskUnblockTime - * might be set to the blocked task's time out time. If the task is - * unblocked for a reason other than a timeout xNextTaskUnblockTime is - * normally left unchanged, because it is automatically reset to a new - * value when the tick count equals xNextTaskUnblockTime. However if - * tickless idling is used it might be more important to enter sleep mode - * at the earliest possible time - so reset xNextTaskUnblockTime here to - * ensure it is updated at the earliest possible time. */ - prvResetNextTaskUnblockTime(); - } - #endif - - /* Remove the task from the delayed list and add it to the ready list. The - * scheduler is suspended so interrupts will not be accessing the ready - * lists. */ - ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxUnblockedTCB ); - - if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The unblocked task has a priority above that of the calling task, so - * a context switch is required. This function is called with the - * scheduler suspended so xYieldPending is set so the context switch - * occurs immediately that the scheduler is resumed (unsuspended). */ - xYieldPending = pdTRUE; - } -} -/*-----------------------------------------------------------*/ - -void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) -{ - configASSERT( pxTimeOut ); - taskENTER_CRITICAL(); - { - pxTimeOut->xOverflowCount = xNumOfOverflows; - pxTimeOut->xTimeOnEntering = xTickCount; - } - taskEXIT_CRITICAL(); -} -/*-----------------------------------------------------------*/ - -void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) -{ - /* For internal use only as it does not use a critical section. */ - pxTimeOut->xOverflowCount = xNumOfOverflows; - pxTimeOut->xTimeOnEntering = xTickCount; -} -/*-----------------------------------------------------------*/ - -BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, - TickType_t * const pxTicksToWait ) -{ - BaseType_t xReturn; - - configASSERT( pxTimeOut ); - configASSERT( pxTicksToWait ); - - taskENTER_CRITICAL(); - { - /* Minor optimisation. The tick count cannot change in this block. */ - const TickType_t xConstTickCount = xTickCount; - const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; - - #if ( INCLUDE_xTaskAbortDelay == 1 ) - if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE ) - { - /* The delay was aborted, which is not the same as a time out, - * but has the same result. */ - pxCurrentTCB->ucDelayAborted = pdFALSE; - xReturn = pdTRUE; - } - else - #endif - - #if ( INCLUDE_vTaskSuspend == 1 ) - if( *pxTicksToWait == portMAX_DELAY ) - { - /* If INCLUDE_vTaskSuspend is set to 1 and the block time - * specified is the maximum block time then the task should block - * indefinitely, and therefore never time out. */ - xReturn = pdFALSE; - } - else - #endif - - if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */ - { - /* The tick count is greater than the time at which - * vTaskSetTimeout() was called, but has also overflowed since - * vTaskSetTimeOut() was called. It must have wrapped all the way - * around and gone past again. This passed since vTaskSetTimeout() - * was called. */ - xReturn = pdTRUE; - *pxTicksToWait = ( TickType_t ) 0; - } - else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */ - { - /* Not a genuine timeout. Adjust parameters for time remaining. */ - *pxTicksToWait -= xElapsedTime; - vTaskInternalSetTimeOutState( pxTimeOut ); - xReturn = pdFALSE; - } - else - { - *pxTicksToWait = ( TickType_t ) 0; - xReturn = pdTRUE; - } - } - taskEXIT_CRITICAL(); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -void vTaskMissedYield( void ) -{ - xYieldPending = pdTRUE; -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) - { - UBaseType_t uxReturn; - TCB_t const * pxTCB; - - if( xTask != NULL ) - { - pxTCB = xTask; - uxReturn = pxTCB->uxTaskNumber; - } - else - { - uxReturn = 0U; - } - - return uxReturn; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - void vTaskSetTaskNumber( TaskHandle_t xTask, - const UBaseType_t uxHandle ) - { - TCB_t * pxTCB; - - if( xTask != NULL ) - { - pxTCB = xTask; - pxTCB->uxTaskNumber = uxHandle; - } - } - -#endif /* configUSE_TRACE_FACILITY */ - -/* - * ----------------------------------------------------------- - * The Idle task. - * ---------------------------------------------------------- - * - * The portTASK_FUNCTION() macro is used to allow port/compiler specific - * language extensions. The equivalent prototype for this function is: - * - * void prvIdleTask( void *pvParameters ); - * - */ -static portTASK_FUNCTION( prvIdleTask, pvParameters ) -{ - /* Stop warnings. */ - ( void ) pvParameters; - - /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE - * SCHEDULER IS STARTED. **/ - - /* In case a task that has a secure context deletes itself, in which case - * the idle task is responsible for deleting the task's secure context, if - * any. */ - portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE ); - - for( ; ; ) - { - /* See if any tasks have deleted themselves - if so then the idle task - * is responsible for freeing the deleted task's TCB and stack. */ - prvCheckTasksWaitingTermination(); - - #if ( configUSE_PREEMPTION == 0 ) - { - /* If we are not using preemption we keep forcing a task switch to - * see if any other task has become available. If we are using - * preemption we don't need to do this as any task becoming available - * will automatically get the processor anyway. */ - taskYIELD(); - } - #endif /* configUSE_PREEMPTION */ - - #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) - { - /* When using preemption tasks of equal priority will be - * timesliced. If a task that is sharing the idle priority is ready - * to run then the idle task should yield before the end of the - * timeslice. - * - * A critical region is not required here as we are just reading from - * the list, and an occasional incorrect value will not matter. If - * the ready list at the idle priority contains more than one task - * then a task other than the idle task is ready to execute. */ - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 ) - { - taskYIELD(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ - - #if ( configUSE_IDLE_HOOK == 1 ) - { - extern void vApplicationIdleHook( void ); - - /* Call the user defined function from within the idle task. This - * allows the application designer to add background functionality - * without the overhead of a separate task. - * NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, - * CALL A FUNCTION THAT MIGHT BLOCK. */ - vApplicationIdleHook(); - } - #endif /* configUSE_IDLE_HOOK */ - - /* This conditional compilation should use inequality to 0, not equality - * to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when - * user defined low power mode implementations require - * configUSE_TICKLESS_IDLE to be set to a value other than 1. */ - #if ( configUSE_TICKLESS_IDLE != 0 ) - { - TickType_t xExpectedIdleTime; - - /* It is not desirable to suspend then resume the scheduler on - * each iteration of the idle task. Therefore, a preliminary - * test of the expected idle time is performed without the - * scheduler suspended. The result here is not necessarily - * valid. */ - xExpectedIdleTime = prvGetExpectedIdleTime(); - - if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) - { - vTaskSuspendAll(); - { - /* Now the scheduler is suspended, the expected idle - * time can be sampled again, and this time its value can - * be used. */ - configASSERT( xNextTaskUnblockTime >= xTickCount ); - xExpectedIdleTime = prvGetExpectedIdleTime(); - - /* Define the following macro to set xExpectedIdleTime to 0 - * if the application does not want - * portSUPPRESS_TICKS_AND_SLEEP() to be called. */ - configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); - - if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) - { - traceLOW_POWER_IDLE_BEGIN(); - portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); - traceLOW_POWER_IDLE_END(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - ( void ) xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TICKLESS_IDLE */ - } -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_TICKLESS_IDLE != 0 ) - - eSleepModeStatus eTaskConfirmSleepModeStatus( void ) - { - /* The idle task exists in addition to the application tasks. */ - const UBaseType_t uxNonApplicationTasks = 1; - eSleepModeStatus eReturn = eStandardSleep; - - /* This function must be called from a critical section. */ - - if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 ) - { - /* A task was made ready while the scheduler was suspended. */ - eReturn = eAbortSleep; - } - else if( xYieldPending != pdFALSE ) - { - /* A yield was pended while the scheduler was suspended. */ - eReturn = eAbortSleep; - } - else if( xPendedTicks != 0 ) - { - /* A tick interrupt has already occurred but was held pending - * because the scheduler is suspended. */ - eReturn = eAbortSleep; - } - else - { - /* If all the tasks are in the suspended list (which might mean they - * have an infinite block time rather than actually being suspended) - * then it is safe to turn all clocks off and just wait for external - * interrupts. */ - if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) - { - eReturn = eNoTasksWaitingTimeout; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - return eReturn; - } - -#endif /* configUSE_TICKLESS_IDLE */ -/*-----------------------------------------------------------*/ - -#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - - void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, - BaseType_t xIndex, - void * pvValue ) - { - TCB_t * pxTCB; - - if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) - { - pxTCB = prvGetTCBFromHandle( xTaskToSet ); - configASSERT( pxTCB != NULL ); - pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; - } - } - -#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ -/*-----------------------------------------------------------*/ - -#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - - void * pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, - BaseType_t xIndex ) - { - void * pvReturn = NULL; - TCB_t * pxTCB; - - if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) - { - pxTCB = prvGetTCBFromHandle( xTaskToQuery ); - pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; - } - else - { - pvReturn = NULL; - } - - return pvReturn; - } - -#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ -/*-----------------------------------------------------------*/ - -#if ( portUSING_MPU_WRAPPERS == 1 ) - - void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, - const MemoryRegion_t * const xRegions ) - { - TCB_t * pxTCB; - - /* If null is passed in here then we are modifying the MPU settings of - * the calling task. */ - pxTCB = prvGetTCBFromHandle( xTaskToModify ); - - vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 ); - } - -#endif /* portUSING_MPU_WRAPPERS */ -/*-----------------------------------------------------------*/ - -static void prvInitialiseTaskLists( void ) -{ - UBaseType_t uxPriority; - - for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) - { - vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); - } - - vListInitialise( &xDelayedTaskList1 ); - vListInitialise( &xDelayedTaskList2 ); - vListInitialise( &xPendingReadyList ); - - #if ( INCLUDE_vTaskDelete == 1 ) - { - vListInitialise( &xTasksWaitingTermination ); - } - #endif /* INCLUDE_vTaskDelete */ - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - vListInitialise( &xSuspendedTaskList ); - } - #endif /* INCLUDE_vTaskSuspend */ - - /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList - * using list2. */ - pxDelayedTaskList = &xDelayedTaskList1; - pxOverflowDelayedTaskList = &xDelayedTaskList2; -} -/*-----------------------------------------------------------*/ - -static void prvCheckTasksWaitingTermination( void ) -{ - /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ - - #if ( INCLUDE_vTaskDelete == 1 ) - { - TCB_t * pxTCB; - - /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL() - * being called too often in the idle task. */ - while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) - { - taskENTER_CRITICAL(); - { - pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - --uxCurrentNumberOfTasks; - --uxDeletedTasksWaitingCleanUp; - } - taskEXIT_CRITICAL(); - - prvDeleteTCB( pxTCB ); - } - } - #endif /* INCLUDE_vTaskDelete */ -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - void vTaskGetInfo( TaskHandle_t xTask, - TaskStatus_t * pxTaskStatus, - BaseType_t xGetFreeStackSpace, - eTaskState eState ) - { - TCB_t * pxTCB; - - /* xTask is NULL then get the state of the calling task. */ - pxTCB = prvGetTCBFromHandle( xTask ); - - pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB; - pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName[ 0 ] ); - pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; - pxTaskStatus->pxStackBase = pxTCB->pxStack; - pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; - - #if ( configUSE_MUTEXES == 1 ) - { - pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; - } - #else - { - pxTaskStatus->uxBasePriority = 0; - } - #endif - - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; - } - #else - { - pxTaskStatus->ulRunTimeCounter = 0; - } - #endif - - /* Obtaining the task state is a little fiddly, so is only done if the - * value of eState passed into this function is eInvalid - otherwise the - * state is just set to whatever is passed in. */ - if( eState != eInvalid ) - { - if( pxTCB == pxCurrentTCB ) - { - pxTaskStatus->eCurrentState = eRunning; - } - else - { - pxTaskStatus->eCurrentState = eState; - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - /* If the task is in the suspended list then there is a - * chance it is actually just blocked indefinitely - so really - * it should be reported as being in the Blocked state. */ - if( eState == eSuspended ) - { - vTaskSuspendAll(); - { - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - pxTaskStatus->eCurrentState = eBlocked; - } - } - ( void ) xTaskResumeAll(); - } - } - #endif /* INCLUDE_vTaskSuspend */ - } - } - else - { - pxTaskStatus->eCurrentState = eTaskGetState( pxTCB ); - } - - /* Obtaining the stack space takes some time, so the xGetFreeStackSpace - * parameter is provided to allow it to be skipped. */ - if( xGetFreeStackSpace != pdFALSE ) - { - #if ( portSTACK_GROWTH > 0 ) - { - pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack ); - } - #else - { - pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack ); - } - #endif - } - else - { - pxTaskStatus->usStackHighWaterMark = 0; - } - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray, - List_t * pxList, - eTaskState eState ) - { - configLIST_VOLATILE TCB_t * pxNextTCB, * pxFirstTCB; - UBaseType_t uxTask = 0; - - if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) - { - listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - - /* Populate an TaskStatus_t structure within the - * pxTaskStatusArray array for each task that is referenced from - * pxList. See the definition of TaskStatus_t in task.h for the - * meaning of each TaskStatus_t structure member. */ - do - { - listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState ); - uxTask++; - } while( pxNextTCB != pxFirstTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return uxTask; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) - - static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) - { - uint32_t ulCount = 0U; - - while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE ) - { - pucStackByte -= portSTACK_GROWTH; - ulCount++; - } - - ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */ - - return ( configSTACK_DEPTH_TYPE ) ulCount; - } - -#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) - -/* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the - * same except for their return type. Using configSTACK_DEPTH_TYPE allows the - * user to determine the return type. It gets around the problem of the value - * overflowing on 8-bit types without breaking backward compatibility for - * applications that expect an 8-bit return type. */ - configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) - { - TCB_t * pxTCB; - uint8_t * pucEndOfStack; - configSTACK_DEPTH_TYPE uxReturn; - - /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are - * the same except for their return type. Using configSTACK_DEPTH_TYPE - * allows the user to determine the return type. It gets around the - * problem of the value overflowing on 8-bit types without breaking - * backward compatibility for applications that expect an 8-bit return - * type. */ - - pxTCB = prvGetTCBFromHandle( xTask ); - - #if portSTACK_GROWTH < 0 - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; - } - #else - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; - } - #endif - - uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack ); - - return uxReturn; - } - -#endif /* INCLUDE_uxTaskGetStackHighWaterMark2 */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) - - UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) - { - TCB_t * pxTCB; - uint8_t * pucEndOfStack; - UBaseType_t uxReturn; - - pxTCB = prvGetTCBFromHandle( xTask ); - - #if portSTACK_GROWTH < 0 - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; - } - #else - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; - } - #endif - - uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack ); - - return uxReturn; - } - -#endif /* INCLUDE_uxTaskGetStackHighWaterMark */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelete == 1 ) - - static void prvDeleteTCB( TCB_t * pxTCB ) - { - /* This call is required specifically for the TriCore port. It must be - * above the vPortFree() calls. The call is also used by ports/demos that - * want to allocate and clean RAM statically. */ - portCLEAN_UP_TCB( pxTCB ); - - /* Free up the memory allocated by the scheduler for the task. It is up - * to the task to free any memory allocated at the application level. - * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html - * for additional information. */ - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - _reclaim_reent( &( pxTCB->xNewLib_reent ) ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ - - #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) - { - /* The task can only have been allocated dynamically - free both - * the stack and TCB. */ - vPortFree( pxTCB->pxStack ); - vPortFree( pxTCB ); - } - #elif ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ - { - /* The task could have been allocated statically or dynamically, so - * check what was statically allocated before trying to free the - * memory. */ - if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ) - { - /* Both the stack and TCB were allocated dynamically, so both - * must be freed. */ - vPortFree( pxTCB->pxStack ); - vPortFree( pxTCB ); - } - else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) - { - /* Only the stack was statically allocated, so the TCB is the - * only memory that must be freed. */ - vPortFree( pxTCB ); - } - else - { - /* Neither the stack nor the TCB were allocated dynamically, so - * nothing needs to be freed. */ - configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ); - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - } - -#endif /* INCLUDE_vTaskDelete */ -/*-----------------------------------------------------------*/ - -static void prvResetNextTaskUnblockTime( void ) -{ - if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) - { - /* The new current delayed list is empty. Set xNextTaskUnblockTime to - * the maximum possible value so it is extremely unlikely that the - * if( xTickCount >= xNextTaskUnblockTime ) test will pass until - * there is an item in the delayed list. */ - xNextTaskUnblockTime = portMAX_DELAY; - } - else - { - /* The new current delayed list is not empty, get the value of - * the item at the head of the delayed list. This is the time at - * which the task at the head of the delayed list should be removed - * from the Blocked state. */ - xNextTaskUnblockTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxDelayedTaskList ); - } -} -/*-----------------------------------------------------------*/ - -#if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) - - TaskHandle_t xTaskGetCurrentTaskHandle( void ) - { - TaskHandle_t xReturn; - - /* A critical section is not required as this is not called from - * an interrupt and the current TCB will always be the same for any - * individual execution thread. */ - xReturn = pxCurrentTCB; - - return xReturn; - } - -#endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - - BaseType_t xTaskGetSchedulerState( void ) - { - BaseType_t xReturn; - - if( xSchedulerRunning == pdFALSE ) - { - xReturn = taskSCHEDULER_NOT_STARTED; - } - else - { - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - xReturn = taskSCHEDULER_RUNNING; - } - else - { - xReturn = taskSCHEDULER_SUSPENDED; - } - } - - return xReturn; - } - -#endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) - { - TCB_t * const pxMutexHolderTCB = pxMutexHolder; - BaseType_t xReturn = pdFALSE; - - /* If the mutex was given back by an interrupt while the queue was - * locked then the mutex holder might now be NULL. _RB_ Is this still - * needed as interrupts can no longer use mutexes? */ - if( pxMutexHolder != NULL ) - { - /* If the holder of the mutex has a priority below the priority of - * the task attempting to obtain the mutex then it will temporarily - * inherit the priority of the task attempting to obtain the mutex. */ - if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) - { - /* Adjust the mutex holder state to account for its new - * priority. Only reset the event list item value if the value is - * not being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* If the task being modified is in the ready state it will need - * to be moved into a new list. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) - { - if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - /* It is known that the task is in its ready list so - * there is no need to check again and the port level - * reset macro can be called directly. */ - portRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority, uxTopReadyPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Inherit the priority before being moved into the new list. */ - pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; - prvAddTaskToReadyList( pxMutexHolderTCB ); - } - else - { - /* Just inherit the priority. */ - pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; - } - - traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); - - /* Inheritance occurred. */ - xReturn = pdTRUE; - } - else - { - if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) - { - /* The base priority of the mutex holder is lower than the - * priority of the task attempting to take the mutex, but the - * current priority of the mutex holder is not lower than the - * priority of the task attempting to take the mutex. - * Therefore the mutex holder must have already inherited a - * priority, but inheritance would have occurred if that had - * not been the case. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xReturn; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) - { - TCB_t * const pxTCB = pxMutexHolder; - BaseType_t xReturn = pdFALSE; - - if( pxMutexHolder != NULL ) - { - /* A task can only have an inherited priority if it holds the mutex. - * If the mutex is held by a task then it cannot be given from an - * interrupt, and if a mutex is given by the holding task then it must - * be the running state task. */ - configASSERT( pxTCB == pxCurrentTCB ); - configASSERT( pxTCB->uxMutexesHeld ); - ( pxTCB->uxMutexesHeld )--; - - /* Has the holder of the mutex inherited the priority of another - * task? */ - if( pxTCB->uxPriority != pxTCB->uxBasePriority ) - { - /* Only disinherit if no other mutexes are held. */ - if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 ) - { - /* A task can only have an inherited priority if it holds - * the mutex. If the mutex is held by a task then it cannot be - * given from an interrupt, and if a mutex is given by the - * holding task then it must be the running state task. Remove - * the holding task from the ready list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Disinherit the priority before adding the task into the - * new ready list. */ - traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); - pxTCB->uxPriority = pxTCB->uxBasePriority; - - /* Reset the event list item value. It cannot be in use for - * any other purpose if this task is running, and it must be - * running to give back the mutex. */ - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - prvAddTaskToReadyList( pxTCB ); - - /* Return true to indicate that a context switch is required. - * This is only actually required in the corner case whereby - * multiple mutexes were held and the mutexes were given back - * in an order different to that in which they were taken. - * If a context switch did not occur when the first mutex was - * returned, even if a task was waiting on it, then a context - * switch should occur when the last mutex is returned whether - * a task is waiting on it or not. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xReturn; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, - UBaseType_t uxHighestPriorityWaitingTask ) - { - TCB_t * const pxTCB = pxMutexHolder; - UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse; - const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1; - - if( pxMutexHolder != NULL ) - { - /* If pxMutexHolder is not NULL then the holder must hold at least - * one mutex. */ - configASSERT( pxTCB->uxMutexesHeld ); - - /* Determine the priority to which the priority of the task that - * holds the mutex should be set. This will be the greater of the - * holding task's base priority and the priority of the highest - * priority task that is waiting to obtain the mutex. */ - if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) - { - uxPriorityToUse = uxHighestPriorityWaitingTask; - } - else - { - uxPriorityToUse = pxTCB->uxBasePriority; - } - - /* Does the priority need to change? */ - if( pxTCB->uxPriority != uxPriorityToUse ) - { - /* Only disinherit if no other mutexes are held. This is a - * simplification in the priority inheritance implementation. If - * the task that holds the mutex is also holding other mutexes then - * the other mutexes may have caused the priority inheritance. */ - if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) - { - /* If a task has timed out because it already holds the - * mutex it was trying to obtain then it cannot of inherited - * its own priority. */ - configASSERT( pxTCB != pxCurrentTCB ); - - /* Disinherit the priority, remembering the previous - * priority to facilitate determining the subject task's - * state. */ - traceTASK_PRIORITY_DISINHERIT( pxTCB, uxPriorityToUse ); - uxPriorityUsedOnEntry = pxTCB->uxPriority; - pxTCB->uxPriority = uxPriorityToUse; - - /* Only reset the event list item value if the value is not - * being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* If the running task is not the task that holds the mutex - * then the task that holds the mutex could be in either the - * Ready, Blocked or Suspended states. Only remove the task - * from its current state list if it is in the Ready state as - * the task's priority is going to change and there is one - * Ready list per priority. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - /* It is known that the task is in its ready list so - * there is no need to check again and the port level - * reset macro can be called directly. */ - portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - prvAddTaskToReadyList( pxTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( portCRITICAL_NESTING_IN_TCB == 1 ) - - void vTaskEnterCritical( void ) - { - portDISABLE_INTERRUPTS(); - - if( xSchedulerRunning != pdFALSE ) - { - ( pxCurrentTCB->uxCriticalNesting )++; - - /* This is not the interrupt safe version of the enter critical - * function so assert() if it is being called from an interrupt - * context. Only API functions that end in "FromISR" can be used in an - * interrupt. Only assert if the critical nesting count is 1 to - * protect against recursive calls if the assert function also uses a - * critical section. */ - if( pxCurrentTCB->uxCriticalNesting == 1 ) - { - portASSERT_IF_IN_ISR(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* portCRITICAL_NESTING_IN_TCB */ -/*-----------------------------------------------------------*/ - -#if ( portCRITICAL_NESTING_IN_TCB == 1 ) - - void vTaskExitCritical( void ) - { - if( xSchedulerRunning != pdFALSE ) - { - if( pxCurrentTCB->uxCriticalNesting > 0U ) - { - ( pxCurrentTCB->uxCriticalNesting )--; - - if( pxCurrentTCB->uxCriticalNesting == 0U ) - { - portENABLE_INTERRUPTS(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* portCRITICAL_NESTING_IN_TCB */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) - - static char * prvWriteNameToBuffer( char * pcBuffer, - const char * pcTaskName ) - { - size_t x; - - /* Start by copying the entire string. */ - strcpy( pcBuffer, pcTaskName ); - - /* Pad the end of the string with spaces to ensure columns line up when - * printed out. */ - for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ ) - { - pcBuffer[ x ] = ' '; - } - - /* Terminate. */ - pcBuffer[ x ] = ( char ) 0x00; - - /* Return the new end of string. */ - return &( pcBuffer[ x ] ); - } - -#endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - void vTaskList( char * pcWriteBuffer ) - { - TaskStatus_t * pxTaskStatusArray; - UBaseType_t uxArraySize, x; - char cStatus; - - /* - * PLEASE NOTE: - * - * This function is provided for convenience only, and is used by many - * of the demo applications. Do not consider it to be part of the - * scheduler. - * - * vTaskList() calls uxTaskGetSystemState(), then formats part of the - * uxTaskGetSystemState() output into a human readable table that - * displays task names, states and stack usage. - * - * vTaskList() has a dependency on the sprintf() C library function that - * might bloat the code size, use a lot of stack, and provide different - * results on different platforms. An alternative, tiny, third party, - * and limited functionality implementation of sprintf() is provided in - * many of the FreeRTOS/Demo sub-directories in a file called - * printf-stdarg.c (note printf-stdarg.c does not provide a full - * snprintf() implementation!). - * - * It is recommended that production systems call uxTaskGetSystemState() - * directly to get access to raw stats data, rather than indirectly - * through a call to vTaskList(). - */ - - - /* Make sure the write buffer does not contain a string. */ - *pcWriteBuffer = ( char ) 0x00; - - /* Take a snapshot of the number of tasks in case it changes while this - * function is executing. */ - uxArraySize = uxCurrentNumberOfTasks; - - /* Allocate an array index for each task. NOTE! if - * configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will - * equate to NULL. */ - pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ - - if( pxTaskStatusArray != NULL ) - { - /* Generate the (binary) data. */ - uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL ); - - /* Create a human readable table from the binary data. */ - for( x = 0; x < uxArraySize; x++ ) - { - switch( pxTaskStatusArray[ x ].eCurrentState ) - { - case eRunning: - cStatus = tskRUNNING_CHAR; - break; - - case eReady: - cStatus = tskREADY_CHAR; - break; - - case eBlocked: - cStatus = tskBLOCKED_CHAR; - break; - - case eSuspended: - cStatus = tskSUSPENDED_CHAR; - break; - - case eDeleted: - cStatus = tskDELETED_CHAR; - break; - - case eInvalid: /* Fall through. */ - default: /* Should not get here, but it is included - * to prevent static checking errors. */ - cStatus = ( char ) 0x00; - break; - } - - /* Write the task name to the string, padding with spaces so it - * can be printed in tabular form more easily. */ - pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); - - /* Write the rest of the string. */ - sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ - pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ - } - - /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION - * is 0 then vPortFree() will be #defined to nothing. */ - vPortFree( pxTaskStatusArray ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ -/*----------------------------------------------------------*/ - -#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - void vTaskGetRunTimeStats( char * pcWriteBuffer ) - { - TaskStatus_t * pxTaskStatusArray; - UBaseType_t uxArraySize, x; - uint32_t ulTotalTime, ulStatsAsPercentage; - - #if ( configUSE_TRACE_FACILITY != 1 ) - { - #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats(). - } - #endif - - /* - * PLEASE NOTE: - * - * This function is provided for convenience only, and is used by many - * of the demo applications. Do not consider it to be part of the - * scheduler. - * - * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part - * of the uxTaskGetSystemState() output into a human readable table that - * displays the amount of time each task has spent in the Running state - * in both absolute and percentage terms. - * - * vTaskGetRunTimeStats() has a dependency on the sprintf() C library - * function that might bloat the code size, use a lot of stack, and - * provide different results on different platforms. An alternative, - * tiny, third party, and limited functionality implementation of - * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in - * a file called printf-stdarg.c (note printf-stdarg.c does not provide - * a full snprintf() implementation!). - * - * It is recommended that production systems call uxTaskGetSystemState() - * directly to get access to raw stats data, rather than indirectly - * through a call to vTaskGetRunTimeStats(). - */ - - /* Make sure the write buffer does not contain a string. */ - *pcWriteBuffer = ( char ) 0x00; - - /* Take a snapshot of the number of tasks in case it changes while this - * function is executing. */ - uxArraySize = uxCurrentNumberOfTasks; - - /* Allocate an array index for each task. NOTE! If - * configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will - * equate to NULL. */ - pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ - - if( pxTaskStatusArray != NULL ) - { - /* Generate the (binary) data. */ - uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime ); - - /* For percentage calculations. */ - ulTotalTime /= 100UL; - - /* Avoid divide by zero errors. */ - if( ulTotalTime > 0UL ) - { - /* Create a human readable table from the binary data. */ - for( x = 0; x < uxArraySize; x++ ) - { - /* What percentage of the total run time has the task used? - * This will always be rounded down to the nearest integer. - * ulTotalRunTimeDiv100 has already been divided by 100. */ - ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime; - - /* Write the task name to the string, padding with - * spaces so it can be printed in tabular form more - * easily. */ - pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); - - if( ulStatsAsPercentage > 0UL ) - { - #ifdef portLU_PRINTF_SPECIFIER_REQUIRED - { - sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); - } - #else - { - /* sizeof( int ) == sizeof( long ) so a smaller - * printf() library can be used. */ - sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ - } - #endif - } - else - { - /* If the percentage is zero here then the task has - * consumed less than 1% of the total run time. */ - #ifdef portLU_PRINTF_SPECIFIER_REQUIRED - { - sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter ); - } - #else - { - /* sizeof( int ) == sizeof( long ) so a smaller - * printf() library can be used. */ - sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ - } - #endif - } - - pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION - * is 0 then vPortFree() will be #defined to nothing. */ - vPortFree( pxTaskStatusArray ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) */ -/*-----------------------------------------------------------*/ - -TickType_t uxTaskResetEventItemValue( void ) -{ - TickType_t uxReturn; - - uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) ); - - /* Reset the event list item to its normal value - so it can be used with - * queues and semaphores. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - return uxReturn; -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - TaskHandle_t pvTaskIncrementMutexHeldCount( void ) - { - /* If xSemaphoreCreateMutex() is called before any tasks have been created - * then pxCurrentTCB will be NULL. */ - if( pxCurrentTCB != NULL ) - { - ( pxCurrentTCB->uxMutexesHeld )++; - } - - return pxCurrentTCB; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TASK_NOTIFICATIONS == 1 ) - - uint32_t ulTaskGenericNotifyTake( UBaseType_t uxIndexToWait, - BaseType_t xClearCountOnExit, - TickType_t xTicksToWait ) - { - uint32_t ulReturn; - - configASSERT( uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES ); - - taskENTER_CRITICAL(); - { - /* Only block if the notification count is not already non-zero. */ - if( pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] == 0UL ) - { - /* Mark this task as waiting for a notification. */ - pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskWAITING_NOTIFICATION; - - if( xTicksToWait > ( TickType_t ) 0 ) - { - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); - traceTASK_NOTIFY_TAKE_BLOCK( uxIndexToWait ); - - /* All ports are written to allow a yield in a critical - * section (some will yield immediately, others wait until the - * critical section exits) - but it is not something that - * application code should ever do. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - taskENTER_CRITICAL(); - { - traceTASK_NOTIFY_TAKE( uxIndexToWait ); - ulReturn = pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ]; - - if( ulReturn != 0UL ) - { - if( xClearCountOnExit != pdFALSE ) - { - pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] = 0UL; - } - else - { - pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] = ulReturn - ( uint32_t ) 1; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskNOT_WAITING_NOTIFICATION; - } - taskEXIT_CRITICAL(); - - return ulReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TASK_NOTIFICATIONS == 1 ) - - BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWait, - uint32_t ulBitsToClearOnEntry, - uint32_t ulBitsToClearOnExit, - uint32_t * pulNotificationValue, - TickType_t xTicksToWait ) - { - BaseType_t xReturn; - - configASSERT( uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES ); - - taskENTER_CRITICAL(); - { - /* Only block if a notification is not already pending. */ - if( pxCurrentTCB->ucNotifyState[ uxIndexToWait ] != taskNOTIFICATION_RECEIVED ) - { - /* Clear bits in the task's notification value as bits may get - * set by the notifying task or interrupt. This can be used to - * clear the value to zero. */ - pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] &= ~ulBitsToClearOnEntry; - - /* Mark this task as waiting for a notification. */ - pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskWAITING_NOTIFICATION; - - if( xTicksToWait > ( TickType_t ) 0 ) - { - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); - traceTASK_NOTIFY_WAIT_BLOCK( uxIndexToWait ); - - /* All ports are written to allow a yield in a critical - * section (some will yield immediately, others wait until the - * critical section exits) - but it is not something that - * application code should ever do. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - taskENTER_CRITICAL(); - { - traceTASK_NOTIFY_WAIT( uxIndexToWait ); - - if( pulNotificationValue != NULL ) - { - /* Output the current notification value, which may or may not - * have changed. */ - *pulNotificationValue = pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ]; - } - - /* If ucNotifyValue is set then either the task never entered the - * blocked state (because a notification was already pending) or the - * task unblocked because of a notification. Otherwise the task - * unblocked because of a timeout. */ - if( pxCurrentTCB->ucNotifyState[ uxIndexToWait ] != taskNOTIFICATION_RECEIVED ) - { - /* A notification was not received. */ - xReturn = pdFALSE; - } - else - { - /* A notification was already pending or a notification was - * received while the task was waiting. */ - pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] &= ~ulBitsToClearOnExit; - xReturn = pdTRUE; - } - - pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskNOT_WAITING_NOTIFICATION; - } - taskEXIT_CRITICAL(); - - return xReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TASK_NOTIFICATIONS == 1 ) - - BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, - UBaseType_t uxIndexToNotify, - uint32_t ulValue, - eNotifyAction eAction, - uint32_t * pulPreviousNotificationValue ) - { - TCB_t * pxTCB; - BaseType_t xReturn = pdPASS; - uint8_t ucOriginalNotifyState; - - configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); - configASSERT( xTaskToNotify ); - pxTCB = xTaskToNotify; - - taskENTER_CRITICAL(); - { - if( pulPreviousNotificationValue != NULL ) - { - *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ]; - } - - ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; - - pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; - - switch( eAction ) - { - case eSetBits: - pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue; - break; - - case eIncrement: - ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; - break; - - case eSetValueWithOverwrite: - pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; - break; - - case eSetValueWithoutOverwrite: - - if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) - { - pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; - } - else - { - /* The value could not be written to the task. */ - xReturn = pdFAIL; - } - - break; - - case eNoAction: - - /* The task is being notified without its notify value being - * updated. */ - break; - - default: - - /* Should not get here if all enums are handled. - * Artificially force an assert by testing a value the - * compiler can't assume is const. */ - configASSERT( xTickCount == ( TickType_t ) 0 ); - - break; - } - - traceTASK_NOTIFY( uxIndexToNotify ); - - /* If the task is in the blocked state specifically to wait for a - * notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - - #if ( configUSE_TICKLESS_IDLE != 0 ) - { - /* If a task is blocked waiting for a notification then - * xNextTaskUnblockTime might be set to the blocked task's time - * out time. If the task is unblocked for a reason other than - * a timeout xNextTaskUnblockTime is normally left unchanged, - * because it will automatically get reset to a new value when - * the tick count equals xNextTaskUnblockTime. However if - * tickless idling is used it might be more important to enter - * sleep mode at the earliest possible time - so reset - * xNextTaskUnblockTime here to ensure it is updated at the - * earliest possible time. */ - prvResetNextTaskUnblockTime(); - } - #endif - - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - * executing task so a yield is required. */ - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - return xReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TASK_NOTIFICATIONS == 1 ) - - BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, - UBaseType_t uxIndexToNotify, - uint32_t ulValue, - eNotifyAction eAction, - uint32_t * pulPreviousNotificationValue, - BaseType_t * pxHigherPriorityTaskWoken ) - { - TCB_t * pxTCB; - uint8_t ucOriginalNotifyState; - BaseType_t xReturn = pdPASS; - UBaseType_t uxSavedInterruptStatus; - - configASSERT( xTaskToNotify ); - configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); - - /* RTOS ports that support interrupt nesting have the concept of a - * maximum system call (or maximum API call) interrupt priority. - * Interrupts that are above the maximum system call priority are keep - * permanently enabled, even when the RTOS kernel is in a critical section, - * but cannot make any calls to FreeRTOS API functions. If configASSERT() - * is defined in FreeRTOSConfig.h then - * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - * failure if a FreeRTOS API function is called from an interrupt that has - * been assigned a priority above the configured maximum system call - * priority. Only FreeRTOS functions that end in FromISR can be called - * from interrupts that have been assigned a priority at or (logically) - * below the maximum system call interrupt priority. FreeRTOS maintains a - * separate interrupt safe API to ensure interrupt entry is as fast and as - * simple as possible. More information (albeit Cortex-M specific) is - * provided on the following link: - * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - pxTCB = xTaskToNotify; - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( pulPreviousNotificationValue != NULL ) - { - *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ]; - } - - ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; - pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; - - switch( eAction ) - { - case eSetBits: - pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue; - break; - - case eIncrement: - ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; - break; - - case eSetValueWithOverwrite: - pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; - break; - - case eSetValueWithoutOverwrite: - - if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) - { - pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; - } - else - { - /* The value could not be written to the task. */ - xReturn = pdFAIL; - } - - break; - - case eNoAction: - - /* The task is being notified without its notify value being - * updated. */ - break; - - default: - - /* Should not get here if all enums are handled. - * Artificially force an assert by testing a value the - * compiler can't assume is const. */ - configASSERT( xTickCount == ( TickType_t ) 0 ); - break; - } - - traceTASK_NOTIFY_FROM_ISR( uxIndexToNotify ); - - /* If the task is in the blocked state specifically to wait for a - * notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed and ready lists cannot be accessed, so hold - * this task pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } - - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - * executing task so a yield is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - - /* Mark that a yield is pending in case the user is not - * using the "xHigherPriorityTaskWoken" parameter to an ISR - * safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TASK_NOTIFICATIONS == 1 ) - - void vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify, - UBaseType_t uxIndexToNotify, - BaseType_t * pxHigherPriorityTaskWoken ) - { - TCB_t * pxTCB; - uint8_t ucOriginalNotifyState; - UBaseType_t uxSavedInterruptStatus; - - configASSERT( xTaskToNotify ); - configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); - - /* RTOS ports that support interrupt nesting have the concept of a - * maximum system call (or maximum API call) interrupt priority. - * Interrupts that are above the maximum system call priority are keep - * permanently enabled, even when the RTOS kernel is in a critical section, - * but cannot make any calls to FreeRTOS API functions. If configASSERT() - * is defined in FreeRTOSConfig.h then - * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - * failure if a FreeRTOS API function is called from an interrupt that has - * been assigned a priority above the configured maximum system call - * priority. Only FreeRTOS functions that end in FromISR can be called - * from interrupts that have been assigned a priority at or (logically) - * below the maximum system call interrupt priority. FreeRTOS maintains a - * separate interrupt safe API to ensure interrupt entry is as fast and as - * simple as possible. More information (albeit Cortex-M specific) is - * provided on the following link: - * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - pxTCB = xTaskToNotify; - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; - pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; - - /* 'Giving' is equivalent to incrementing a count in a counting - * semaphore. */ - ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; - - traceTASK_NOTIFY_GIVE_FROM_ISR( uxIndexToNotify ); - - /* If the task is in the blocked state specifically to wait for a - * notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed and ready lists cannot be accessed, so hold - * this task pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } - - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - * executing task so a yield is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - - /* Mark that a yield is pending in case the user is not - * using the "xHigherPriorityTaskWoken" parameter in an ISR - * safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TASK_NOTIFICATIONS == 1 ) - - BaseType_t xTaskGenericNotifyStateClear( TaskHandle_t xTask, - UBaseType_t uxIndexToClear ) - { - TCB_t * pxTCB; - BaseType_t xReturn; - - configASSERT( uxIndexToClear < configTASK_NOTIFICATION_ARRAY_ENTRIES ); - - /* If null is passed in here then it is the calling task that is having - * its notification state cleared. */ - pxTCB = prvGetTCBFromHandle( xTask ); - - taskENTER_CRITICAL(); - { - if( pxTCB->ucNotifyState[ uxIndexToClear ] == taskNOTIFICATION_RECEIVED ) - { - pxTCB->ucNotifyState[ uxIndexToClear ] = taskNOT_WAITING_NOTIFICATION; - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } - } - taskEXIT_CRITICAL(); - - return xReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TASK_NOTIFICATIONS == 1 ) - - uint32_t ulTaskGenericNotifyValueClear( TaskHandle_t xTask, - UBaseType_t uxIndexToClear, - uint32_t ulBitsToClear ) - { - TCB_t * pxTCB; - uint32_t ulReturn; - - /* If null is passed in here then it is the calling task that is having - * its notification state cleared. */ - pxTCB = prvGetTCBFromHandle( xTask ); - - taskENTER_CRITICAL(); - { - /* Return the notification as it was before the bits were cleared, - * then clear the bit mask. */ - ulReturn = pxTCB->ulNotifiedValue[ uxIndexToClear ]; - pxTCB->ulNotifiedValue[ uxIndexToClear ] &= ~ulBitsToClear; - } - taskEXIT_CRITICAL(); - - return ulReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) - - uint32_t ulTaskGetIdleRunTimeCounter( void ) - { - return xIdleTaskHandle->ulRunTimeCounter; - } - -#endif -/*-----------------------------------------------------------*/ - -static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, - const BaseType_t xCanBlockIndefinitely ) -{ - TickType_t xTimeToWake; - const TickType_t xConstTickCount = xTickCount; - - #if ( INCLUDE_xTaskAbortDelay == 1 ) - { - /* About to enter a delayed list, so ensure the ucDelayAborted flag is - * reset to pdFALSE so it can be detected as having been set to pdTRUE - * when the task leaves the Blocked state. */ - pxCurrentTCB->ucDelayAborted = pdFALSE; - } - #endif - - /* Remove the task from the ready list before adding it to the blocked list - * as the same list item is used for both lists. */ - if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - /* The current task must be in a ready list, so there is no need to - * check, and the port reset macro can be called directly. */ - portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); /*lint !e931 pxCurrentTCB cannot change as it is the calling task. pxCurrentTCB->uxPriority and uxTopReadyPriority cannot change as called with scheduler suspended or in a critical section. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) ) - { - /* Add the task to the suspended task list instead of a delayed task - * list to ensure it is not woken by a timing event. It will block - * indefinitely. */ - vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* Calculate the time at which the task should be woken if the event - * does not occur. This may overflow but this doesn't matter, the - * kernel will manage it correctly. */ - xTimeToWake = xConstTickCount + xTicksToWait; - - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); - - if( xTimeToWake < xConstTickCount ) - { - /* Wake time has overflowed. Place this item in the overflow - * list. */ - vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* The wake time has not overflowed, so the current block list - * is used. */ - vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - - /* If the task entering the blocked state was placed at the - * head of the list of blocked tasks then xNextTaskUnblockTime - * needs to be updated too. */ - if( xTimeToWake < xNextTaskUnblockTime ) - { - xNextTaskUnblockTime = xTimeToWake; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - } - #else /* INCLUDE_vTaskSuspend */ - { - /* Calculate the time at which the task should be woken if the event - * does not occur. This may overflow but this doesn't matter, the kernel - * will manage it correctly. */ - xTimeToWake = xConstTickCount + xTicksToWait; - - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); - - if( xTimeToWake < xConstTickCount ) - { - /* Wake time has overflowed. Place this item in the overflow list. */ - vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* The wake time has not overflowed, so the current block list is used. */ - vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - - /* If the task entering the blocked state was placed at the head of the - * list of blocked tasks then xNextTaskUnblockTime needs to be updated - * too. */ - if( xTimeToWake < xNextTaskUnblockTime ) - { - xNextTaskUnblockTime = xTimeToWake; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */ - ( void ) xCanBlockIndefinitely; - } - #endif /* INCLUDE_vTaskSuspend */ -} - -/* Code below here allows additional code to be inserted into this source file, - * especially where access to file scope functions and data is needed (for example - * when performing module tests). */ - -#ifdef FREERTOS_MODULE_TEST - #include "tasks_test_access_functions.h" -#endif - - -#if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) - - #include "freertos_tasks_c_additions.h" - - #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - static void freertos_tasks_c_additions_init( void ) - { - FREERTOS_TASKS_C_ADDITIONS_INIT(); - } - #endif - -#endif /* if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" +#include "stack_macros.h" + +/* The default definitions are only available for non-MPU ports. The + * reason is that the stack alignment requirements vary for different + * architectures.*/ +#if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configKERNEL_PROVIDED_STATIC_MEMORY == 1 ) && ( portUSING_MPU_WRAPPERS != 0 ) ) + #error configKERNEL_PROVIDED_STATIC_MEMORY cannot be set to 1 when using an MPU port. The vApplicationGet*TaskMemory() functions must be provided manually. +#endif + +/* The MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting + * functions but without including stdio.h here. */ +#if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) + +/* At the bottom of this file are two optional functions that can be used + * to generate human readable text from the raw data generated by the + * uxTaskGetSystemState() function. Note the formatting functions are provided + * for convenience only, and are NOT considered part of the kernel. */ + #include +#endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */ + +#if ( configUSE_PREEMPTION == 0 ) + +/* If the cooperative scheduler is being used then a yield should not be + * performed just because a higher priority task has been woken. */ + #define taskYIELD_TASK_CORE_IF_USING_PREEMPTION( pxTCB ) + #define taskYIELD_ANY_CORE_IF_USING_PREEMPTION( pxTCB ) +#else + + #if ( configNUMBER_OF_CORES == 1 ) + +/* This macro requests the running task pxTCB to yield. In single core + * scheduler, a running task always runs on core 0 and portYIELD_WITHIN_API() + * can be used to request the task running on core 0 to yield. Therefore, pxTCB + * is not used in this macro. */ + #define taskYIELD_TASK_CORE_IF_USING_PREEMPTION( pxTCB ) \ + do { \ + ( void ) ( pxTCB ); \ + portYIELD_WITHIN_API(); \ + } while( 0 ) + + #define taskYIELD_ANY_CORE_IF_USING_PREEMPTION( pxTCB ) \ + do { \ + if( pxCurrentTCB->uxPriority < ( pxTCB )->uxPriority ) \ + { \ + portYIELD_WITHIN_API(); \ + } \ + else \ + { \ + mtCOVERAGE_TEST_MARKER(); \ + } \ + } while( 0 ) + + #else /* if ( configNUMBER_OF_CORES == 1 ) */ + +/* Yield the core on which this task is running. */ + #define taskYIELD_TASK_CORE_IF_USING_PREEMPTION( pxTCB ) prvYieldCore( ( pxTCB )->xTaskRunState ) + +/* Yield for the task if a running task has priority lower than this task. */ + #define taskYIELD_ANY_CORE_IF_USING_PREEMPTION( pxTCB ) prvYieldForTask( pxTCB ) + + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + +#endif /* if ( configUSE_PREEMPTION == 0 ) */ + +/* Values that can be assigned to the ucNotifyState member of the TCB. */ +#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) /* Must be zero as it is the initialised value. */ +#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) +#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) + +/* + * The value used to fill the stack of a task when the task is created. This + * is used purely for checking the high water mark for tasks. + */ +#define tskSTACK_FILL_BYTE ( 0xa5U ) + +/* Bits used to record how a task's stack and TCB were allocated. */ +#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 ) +#define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 ) +#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 ) + +/* If any of the following are set then task stacks are filled with a known + * value so the high water mark can be determined. If none of the following are + * set then don't fill the stack so there is no unnecessary dependency on memset. */ +#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) + #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1 +#else + #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0 +#endif + +/* + * Macros used by vListTask to indicate which state a task is in. + */ +#define tskRUNNING_CHAR ( 'X' ) +#define tskBLOCKED_CHAR ( 'B' ) +#define tskREADY_CHAR ( 'R' ) +#define tskDELETED_CHAR ( 'D' ) +#define tskSUSPENDED_CHAR ( 'S' ) + +/* + * Some kernel aware debuggers require the data the debugger needs access to be + * global, rather than file scope. + */ +#ifdef portREMOVE_STATIC_QUALIFIER + #define static +#endif + +/* The name allocated to the Idle task. This can be overridden by defining + * configIDLE_TASK_NAME in FreeRTOSConfig.h. */ +#ifndef configIDLE_TASK_NAME + #define configIDLE_TASK_NAME "IDLE" +#endif + +#if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) + +/* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is + * performed in a generic way that is not optimised to any particular + * microcontroller architecture. */ + +/* uxTopReadyPriority holds the priority of the highest priority ready + * state task. */ + #define taskRECORD_READY_PRIORITY( uxPriority ) \ + do { \ + if( ( uxPriority ) > uxTopReadyPriority ) \ + { \ + uxTopReadyPriority = ( uxPriority ); \ + } \ + } while( 0 ) /* taskRECORD_READY_PRIORITY */ + +/*-----------------------------------------------------------*/ + + #if ( configNUMBER_OF_CORES == 1 ) + #define taskSELECT_HIGHEST_PRIORITY_TASK() \ + do { \ + UBaseType_t uxTopPriority = uxTopReadyPriority; \ + \ + /* Find the highest priority queue that contains ready tasks. */ \ + while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) != pdFALSE ) \ + { \ + configASSERT( uxTopPriority ); \ + --uxTopPriority; \ + } \ + \ + /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ + * the same priority get an equal share of the processor time. */ \ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ + uxTopReadyPriority = uxTopPriority; \ + } while( 0 ) /* taskSELECT_HIGHEST_PRIORITY_TASK */ + #else /* if ( configNUMBER_OF_CORES == 1 ) */ + + #define taskSELECT_HIGHEST_PRIORITY_TASK( xCoreID ) prvSelectHighestPriorityTask( xCoreID ) + + #endif /* if ( configNUMBER_OF_CORES == 1 ) */ + +/*-----------------------------------------------------------*/ + +/* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as + * they are only required when a port optimised method of task selection is + * being used. */ + #define taskRESET_READY_PRIORITY( uxPriority ) + #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority ) + +#else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ + +/* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is + * performed in a way that is tailored to the particular microcontroller + * architecture being used. */ + +/* A port optimised version is provided. Call the port defined macros. */ + #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( ( uxPriority ), uxTopReadyPriority ) + +/*-----------------------------------------------------------*/ + + #define taskSELECT_HIGHEST_PRIORITY_TASK() \ + do { \ + UBaseType_t uxTopPriority; \ + \ + /* Find the highest priority list that contains ready tasks. */ \ + portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ + configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ + } while( 0 ) + +/*-----------------------------------------------------------*/ + +/* A port optimised version is provided, call it only if the TCB being reset + * is being referenced from a ready list. If it is referenced from a delayed + * or suspended list then it won't be in a ready list. */ + #define taskRESET_READY_PRIORITY( uxPriority ) \ + do { \ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \ + { \ + portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \ + } \ + } while( 0 ) + +#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ + +/*-----------------------------------------------------------*/ + +/* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick + * count overflows. */ +#define taskSWITCH_DELAYED_LISTS() \ + do { \ + List_t * pxTemp; \ + \ + /* The delayed tasks list should be empty when the lists are switched. */ \ + configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \ + \ + pxTemp = pxDelayedTaskList; \ + pxDelayedTaskList = pxOverflowDelayedTaskList; \ + pxOverflowDelayedTaskList = pxTemp; \ + xNumOfOverflows = ( BaseType_t ) ( xNumOfOverflows + 1 ); \ + prvResetNextTaskUnblockTime(); \ + } while( 0 ) + +/*-----------------------------------------------------------*/ + +/* + * Place the task represented by pxTCB into the appropriate ready list for + * the task. It is inserted at the end of the list. + */ +#define prvAddTaskToReadyList( pxTCB ) \ + do { \ + traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ + taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ + listINSERT_END( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \ + tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ); \ + } while( 0 ) +/*-----------------------------------------------------------*/ + +/* + * Several functions take a TaskHandle_t parameter that can optionally be NULL, + * where NULL is used to indicate that the handle of the currently executing + * task should be used in place of the parameter. This macro simply checks to + * see if the parameter is NULL and returns a pointer to the appropriate TCB. + */ +#define prvGetTCBFromHandle( pxHandle ) ( ( ( pxHandle ) == NULL ) ? pxCurrentTCB : ( pxHandle ) ) + +/* The item value of the event list item is normally used to hold the priority + * of the task to which it belongs (coded to allow it to be held in reverse + * priority order). However, it is occasionally borrowed for other purposes. It + * is important its value is not updated due to a task priority change while it is + * being used for another purpose. The following bit definition is used to inform + * the scheduler that the value should not be changed - in which case it is the + * responsibility of whichever module is using the value to ensure it gets set back + * to its original value when it is released. */ +#if ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_16_BITS ) + #define taskEVENT_LIST_ITEM_VALUE_IN_USE ( ( uint16_t ) 0x8000U ) +#elif ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_32_BITS ) + #define taskEVENT_LIST_ITEM_VALUE_IN_USE ( ( uint32_t ) 0x80000000U ) +#elif ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_64_BITS ) + #define taskEVENT_LIST_ITEM_VALUE_IN_USE ( ( uint64_t ) 0x8000000000000000U ) +#endif + +/* Indicates that the task is not actively running on any core. */ +#define taskTASK_NOT_RUNNING ( ( BaseType_t ) ( -1 ) ) + +/* Indicates that the task is actively running but scheduled to yield. */ +#define taskTASK_SCHEDULED_TO_YIELD ( ( BaseType_t ) ( -2 ) ) + +/* Returns pdTRUE if the task is actively running and not scheduled to yield. */ +#if ( configNUMBER_OF_CORES == 1 ) + #define taskTASK_IS_RUNNING( pxTCB ) ( ( ( pxTCB ) == pxCurrentTCB ) ? ( pdTRUE ) : ( pdFALSE ) ) + #define taskTASK_IS_RUNNING_OR_SCHEDULED_TO_YIELD( pxTCB ) ( ( ( pxTCB ) == pxCurrentTCB ) ? ( pdTRUE ) : ( pdFALSE ) ) +#else + #define taskTASK_IS_RUNNING( pxTCB ) ( ( ( ( pxTCB )->xTaskRunState >= ( BaseType_t ) 0 ) && ( ( pxTCB )->xTaskRunState < ( BaseType_t ) configNUMBER_OF_CORES ) ) ? ( pdTRUE ) : ( pdFALSE ) ) + #define taskTASK_IS_RUNNING_OR_SCHEDULED_TO_YIELD( pxTCB ) ( ( ( pxTCB )->xTaskRunState != taskTASK_NOT_RUNNING ) ? ( pdTRUE ) : ( pdFALSE ) ) +#endif + +/* Indicates that the task is an Idle task. */ +#define taskATTRIBUTE_IS_IDLE ( UBaseType_t ) ( 1U << 0U ) + +#if ( ( configNUMBER_OF_CORES > 1 ) && ( portCRITICAL_NESTING_IN_TCB == 1 ) ) + #define portGET_CRITICAL_NESTING_COUNT() ( pxCurrentTCBs[ portGET_CORE_ID() ]->uxCriticalNesting ) + #define portSET_CRITICAL_NESTING_COUNT( x ) ( pxCurrentTCBs[ portGET_CORE_ID() ]->uxCriticalNesting = ( x ) ) + #define portINCREMENT_CRITICAL_NESTING_COUNT() ( pxCurrentTCBs[ portGET_CORE_ID() ]->uxCriticalNesting++ ) + #define portDECREMENT_CRITICAL_NESTING_COUNT() ( pxCurrentTCBs[ portGET_CORE_ID() ]->uxCriticalNesting-- ) +#endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( portCRITICAL_NESTING_IN_TCB == 1 ) ) */ + +#define taskBITS_PER_BYTE ( ( size_t ) 8 ) + +#if ( configNUMBER_OF_CORES > 1 ) + +/* Yields the given core. This must be called from a critical section and xCoreID + * must be valid. This macro is not required in single core since there is only + * one core to yield. */ + #define prvYieldCore( xCoreID ) \ + do { \ + if( ( xCoreID ) == ( BaseType_t ) portGET_CORE_ID() ) \ + { \ + /* Pending a yield for this core since it is in the critical section. */ \ + xYieldPendings[ ( xCoreID ) ] = pdTRUE; \ + } \ + else \ + { \ + /* Request other core to yield if it is not requested before. */ \ + if( pxCurrentTCBs[ ( xCoreID ) ]->xTaskRunState != taskTASK_SCHEDULED_TO_YIELD ) \ + { \ + portYIELD_CORE( xCoreID ); \ + pxCurrentTCBs[ ( xCoreID ) ]->xTaskRunState = taskTASK_SCHEDULED_TO_YIELD; \ + } \ + } \ + } while( 0 ) +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ +/*-----------------------------------------------------------*/ + +/* + * Task control block. A task control block (TCB) is allocated for each task, + * and stores task state information, including a pointer to the task's context + * (the task's run time environment, including register values) + */ +typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +{ + volatile StackType_t * pxTopOfStack; /**< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */ + + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xMPUSettings; /**< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */ + #endif + + #if ( configUSE_CORE_AFFINITY == 1 ) && ( configNUMBER_OF_CORES > 1 ) + UBaseType_t uxCoreAffinityMask; /**< Used to link the task to certain cores. UBaseType_t must have greater than or equal to the number of bits as configNUMBER_OF_CORES. */ + #endif + + ListItem_t xStateListItem; /**< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */ + ListItem_t xEventListItem; /**< Used to reference a task from an event list. */ + UBaseType_t uxPriority; /**< The priority of the task. 0 is the lowest priority. */ + StackType_t * pxStack; /**< Points to the start of the stack. */ + #if ( configNUMBER_OF_CORES > 1 ) + volatile BaseType_t xTaskRunState; /**< Used to identify the core the task is running on, if the task is running. Otherwise, identifies the task's state - not running or yielding. */ + UBaseType_t uxTaskAttributes; /**< Task's attributes - currently used to identify the idle tasks. */ + #endif + char pcTaskName[ configMAX_TASK_NAME_LEN ]; /**< Descriptive name given to the task when created. Facilitates debugging only. */ + + #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) + BaseType_t xPreemptionDisable; /**< Used to prevent the task from being preempted. */ + #endif + + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + StackType_t * pxEndOfStack; /**< Points to the highest valid address for the stack. */ + #endif + + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxCriticalNesting; /**< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */ + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTCBNumber; /**< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */ + UBaseType_t uxTaskNumber; /**< Stores a number specifically for use by third party trace code. */ + #endif + + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxBasePriority; /**< The priority last assigned to the task - used by the priority inheritance mechanism. */ + UBaseType_t uxMutexesHeld; + #endif + + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + TaskHookFunction_t pxTaskTag; + #endif + + #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void * pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + configRUN_TIME_COUNTER_TYPE ulRunTimeCounter; /**< Stores the amount of time the task has spent in the Running state. */ + #endif + + #if ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) + configTLS_BLOCK_TYPE xTLSBlock; /**< Memory block used as Thread Local Storage (TLS) Block for the task. */ + #endif + + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + volatile uint32_t ulNotifiedValue[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + volatile uint8_t ucNotifyState[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + #endif + + /* See the comments in FreeRTOS.h with the definition of + * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + uint8_t ucStaticallyAllocated; /**< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ + #endif + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDelayAborted; + #endif + + #if ( configUSE_POSIX_ERRNO == 1 ) + int iTaskErrno; + #endif +} tskTCB; + +/* The old tskTCB name is maintained above then typedefed to the new TCB_t name + * below to enable the use of older kernel aware debuggers. */ +typedef tskTCB TCB_t; + +#if ( configNUMBER_OF_CORES == 1 ) + /* MISRA Ref 8.4.1 [Declaration shall be visible] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-84 */ + /* coverity[misra_c_2012_rule_8_4_violation] */ + portDONT_DISCARD PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL; +#else + /* MISRA Ref 8.4.1 [Declaration shall be visible] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-84 */ + /* coverity[misra_c_2012_rule_8_4_violation] */ + portDONT_DISCARD PRIVILEGED_DATA TCB_t * volatile pxCurrentTCBs[ configNUMBER_OF_CORES ]; + #define pxCurrentTCB xTaskGetCurrentTaskHandle() +#endif + +/* Lists for ready and blocked tasks. -------------------- + * xDelayedTaskList1 and xDelayedTaskList2 could be moved to function scope but + * doing so breaks some kernel aware debuggers and debuggers that rely on removing + * the static qualifier. */ +PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ]; /**< Prioritised ready tasks. */ +PRIVILEGED_DATA static List_t xDelayedTaskList1; /**< Delayed tasks. */ +PRIVILEGED_DATA static List_t xDelayedTaskList2; /**< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ +PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /**< Points to the delayed task list currently being used. */ +PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /**< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ +PRIVILEGED_DATA static List_t xPendingReadyList; /**< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */ + +#if ( INCLUDE_vTaskDelete == 1 ) + + PRIVILEGED_DATA static List_t xTasksWaitingTermination; /**< Tasks that have been deleted - but their memory not yet freed. */ + PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U; + +#endif + +#if ( INCLUDE_vTaskSuspend == 1 ) + + PRIVILEGED_DATA static List_t xSuspendedTaskList; /**< Tasks that are currently suspended. */ + +#endif + +/* Global POSIX errno. Its value is changed upon context switching to match + * the errno of the currently running task. */ +#if ( configUSE_POSIX_ERRNO == 1 ) + int FreeRTOS_errno = 0; +#endif + +/* Other file private variables. --------------------------------*/ +PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; +PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY; +PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE; +PRIVILEGED_DATA static volatile TickType_t xPendedTicks = ( TickType_t ) 0U; +PRIVILEGED_DATA static volatile BaseType_t xYieldPendings[ configNUMBER_OF_CORES ] = { pdFALSE }; +PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0; +PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */ +PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandles[ configNUMBER_OF_CORES ]; /**< Holds the handles of the idle tasks. The idle tasks are created automatically when the scheduler is started. */ + +/* Improve support for OpenOCD. The kernel tracks Ready tasks via priority lists. + * For tracking the state of remote threads, OpenOCD uses uxTopUsedPriority + * to determine the number of priority lists to read back from the remote target. */ +static const volatile UBaseType_t uxTopUsedPriority = configMAX_PRIORITIES - 1U; + +/* Context switches are held pending while the scheduler is suspended. Also, + * interrupts must not manipulate the xStateListItem of a TCB, or any of the + * lists the xStateListItem can be referenced from, if the scheduler is suspended. + * If an interrupt needs to unblock a task while the scheduler is suspended then it + * moves the task's event list item into the xPendingReadyList, ready for the + * kernel to move the task from the pending ready list into the real ready list + * when the scheduler is unsuspended. The pending ready list itself can only be + * accessed from a critical section. + * + * Updates to uxSchedulerSuspended must be protected by both the task lock and the ISR lock + * and must not be done from an ISR. Reads must be protected by either lock and may be done + * from either an ISR or a task. */ +PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) 0U; + +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + +/* Do not move these variables to function scope as doing so prevents the + * code working with debuggers that need to remove the static qualifier. */ +PRIVILEGED_DATA static configRUN_TIME_COUNTER_TYPE ulTaskSwitchedInTime[ configNUMBER_OF_CORES ] = { 0U }; /**< Holds the value of a timer/counter the last time a task was switched in. */ +PRIVILEGED_DATA static volatile configRUN_TIME_COUNTER_TYPE ulTotalRunTime[ configNUMBER_OF_CORES ] = { 0U }; /**< Holds the total amount of execution time as defined by the run time counter clock. */ + +#endif + +/*-----------------------------------------------------------*/ + +/* File private functions. --------------------------------*/ + +/* + * Creates the idle tasks during scheduler start. + */ +static BaseType_t prvCreateIdleTasks( void ); + +#if ( configNUMBER_OF_CORES > 1 ) + +/* + * Checks to see if another task moved the current task out of the ready + * list while it was waiting to enter a critical section and yields, if so. + */ + static void prvCheckForRunStateChange( void ); +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + +#if ( configNUMBER_OF_CORES > 1 ) + +/* + * Yields a core, or cores if multiple priorities are not allowed to run + * simultaneously, to allow the task pxTCB to run. + */ + static void prvYieldForTask( const TCB_t * pxTCB ); +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + +#if ( configNUMBER_OF_CORES > 1 ) + +/* + * Selects the highest priority available task for the given core. + */ + static void prvSelectHighestPriorityTask( BaseType_t xCoreID ); +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + +/** + * Utility task that simply returns pdTRUE if the task referenced by xTask is + * currently in the Suspended state, or pdFALSE if the task referenced by xTask + * is in any other state. + */ +#if ( INCLUDE_vTaskSuspend == 1 ) + + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +#endif /* INCLUDE_vTaskSuspend */ + +/* + * Utility to ready all the lists used by the scheduler. This is called + * automatically upon the creation of the first task. + */ +static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION; + +/* + * The idle task, which as all tasks is implemented as a never ending loop. + * The idle task is automatically created and added to the ready lists upon + * creation of the first user task. + * + * In the FreeRTOS SMP, configNUMBER_OF_CORES - 1 passive idle tasks are also + * created to ensure that each core has an idle task to run when no other + * task is available to run. + * + * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific + * language extensions. The equivalent prototype for these functions are: + * + * void prvIdleTask( void *pvParameters ); + * void prvPassiveIdleTask( void *pvParameters ); + * + */ +static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ) PRIVILEGED_FUNCTION; +#if ( configNUMBER_OF_CORES > 1 ) + static portTASK_FUNCTION_PROTO( prvPassiveIdleTask, pvParameters ) PRIVILEGED_FUNCTION; +#endif + +/* + * Utility to free all memory allocated by the scheduler to hold a TCB, + * including the stack pointed to by the TCB. + * + * This does not free memory allocated by the task itself (i.e. memory + * allocated by calls to pvPortMalloc from within the tasks application code). + */ +#if ( INCLUDE_vTaskDelete == 1 ) + + static void prvDeleteTCB( TCB_t * pxTCB ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Used only by the idle task. This checks to see if anything has been placed + * in the list of tasks waiting to be deleted. If so the task is cleaned up + * and its TCB deleted. + */ +static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION; + +/* + * The currently executing task is entering the Blocked state. Add the task to + * either the current or the overflow delayed task list. + */ +static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, + const BaseType_t xCanBlockIndefinitely ) PRIVILEGED_FUNCTION; + +/* + * Fills an TaskStatus_t structure with information on each task that is + * referenced from the pxList list (which may be a ready list, a delayed list, + * a suspended list, etc.). + * + * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM + * NORMAL APPLICATION CODE. + */ +#if ( configUSE_TRACE_FACILITY == 1 ) + + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray, + List_t * pxList, + eTaskState eState ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Searches pxList for a task with name pcNameToQuery - returning a handle to + * the task if it is found, or NULL if the task is not found. + */ +#if ( INCLUDE_xTaskGetHandle == 1 ) + + static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList, + const char pcNameToQuery[] ) PRIVILEGED_FUNCTION; + +#endif + +/* + * When a task is created, the stack of the task is filled with a known value. + * This function determines the 'high water mark' of the task stack by + * determining how much of the stack remains at the original preset value. + */ +#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) + + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Return the amount of time, in ticks, that will pass before the kernel will + * next move a task from the Blocked state to the Running state. + * + * This conditional compilation should use inequality to 0, not equality to 1. + * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user + * defined low power mode implementations require configUSE_TICKLESS_IDLE to be + * set to a value other than 1. + */ +#if ( configUSE_TICKLESS_IDLE != 0 ) + + static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Set xNextTaskUnblockTime to the time at which the next Blocked state task + * will exit the Blocked state. + */ +static void prvResetNextTaskUnblockTime( void ) PRIVILEGED_FUNCTION; + +#if ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) + +/* + * Helper function used to pad task names with spaces when printing out + * human readable tables of task information. + */ + static char * prvWriteNameToBuffer( char * pcBuffer, + const char * pcTaskName ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Called after a Task_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t * pxNewTCB, + const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; + +/* + * Called after a new task has been created and initialised to place the task + * under the control of the scheduler. + */ +static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) PRIVILEGED_FUNCTION; + +/* + * Create a task with static buffer for both TCB and stack. Returns a handle to + * the task if it is created successfully. Otherwise, returns NULL. + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + static TCB_t * prvCreateStaticTask( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer, + TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif /* #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + +/* + * Create a restricted task with static buffer for both TCB and stack. Returns + * a handle to the task if it is created successfully. Otherwise, returns NULL. + */ +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + static TCB_t * prvCreateRestrictedStaticTask( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif /* #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) */ + +/* + * Create a restricted task with static buffer for task stack and allocated buffer + * for TCB. Returns a handle to the task if it is created successfully. Otherwise, + * returns NULL. + */ +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + static TCB_t * prvCreateRestrictedTask( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif /* #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ + +/* + * Create a task with allocated buffer for both TCB and stack. Returns a handle to + * the task if it is created successfully. Otherwise, returns NULL. + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + static TCB_t * prvCreateTask( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif /* #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) */ + +/* + * freertos_tasks_c_additions_init() should only be called if the user definable + * macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro + * called by the function. + */ +#ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + + static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION; + +#endif + +#if ( configUSE_PASSIVE_IDLE_HOOK == 1 ) + extern void vApplicationPassiveIdleHook( void ); +#endif /* #if ( configUSE_PASSIVE_IDLE_HOOK == 1 ) */ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) + +/* + * Convert the snprintf return value to the number of characters + * written. The following are the possible cases: + * + * 1. The buffer supplied to snprintf is large enough to hold the + * generated string. The return value in this case is the number + * of characters actually written, not counting the terminating + * null character. + * 2. The buffer supplied to snprintf is NOT large enough to hold + * the generated string. The return value in this case is the + * number of characters that would have been written if the + * buffer had been sufficiently large, not counting the + * terminating null character. + * 3. Encoding error. The return value in this case is a negative + * number. + * + * From 1 and 2 above ==> Only when the return value is non-negative + * and less than the supplied buffer length, the string has been + * completely written. + */ + static size_t prvSnprintfReturnValueToCharsWritten( int iSnprintfReturnValue, + size_t n ); + +#endif /* #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configNUMBER_OF_CORES > 1 ) + static void prvCheckForRunStateChange( void ) + { + UBaseType_t uxPrevCriticalNesting; + const TCB_t * pxThisTCB; + + /* This must only be called from within a task. */ + portASSERT_IF_IN_ISR(); + + /* This function is always called with interrupts disabled + * so this is safe. */ + pxThisTCB = pxCurrentTCBs[ portGET_CORE_ID() ]; + + while( pxThisTCB->xTaskRunState == taskTASK_SCHEDULED_TO_YIELD ) + { + /* We are only here if we just entered a critical section + * or if we just suspended the scheduler, and another task + * has requested that we yield. + * + * This is slightly complicated since we need to save and restore + * the suspension and critical nesting counts, as well as release + * and reacquire the correct locks. And then, do it all over again + * if our state changed again during the reacquisition. */ + uxPrevCriticalNesting = portGET_CRITICAL_NESTING_COUNT(); + + if( uxPrevCriticalNesting > 0U ) + { + portSET_CRITICAL_NESTING_COUNT( 0U ); + portRELEASE_ISR_LOCK(); + } + else + { + /* The scheduler is suspended. uxSchedulerSuspended is updated + * only when the task is not requested to yield. */ + mtCOVERAGE_TEST_MARKER(); + } + + portRELEASE_TASK_LOCK(); + portMEMORY_BARRIER(); + configASSERT( pxThisTCB->xTaskRunState == taskTASK_SCHEDULED_TO_YIELD ); + + portENABLE_INTERRUPTS(); + + /* Enabling interrupts should cause this core to immediately + * service the pending interrupt and yield. If the run state is still + * yielding here then that is a problem. */ + configASSERT( pxThisTCB->xTaskRunState != taskTASK_SCHEDULED_TO_YIELD ); + + portDISABLE_INTERRUPTS(); + portGET_TASK_LOCK(); + portGET_ISR_LOCK(); + + portSET_CRITICAL_NESTING_COUNT( uxPrevCriticalNesting ); + + if( uxPrevCriticalNesting == 0U ) + { + portRELEASE_ISR_LOCK(); + } + } + } +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + +/*-----------------------------------------------------------*/ + +#if ( configNUMBER_OF_CORES > 1 ) + static void prvYieldForTask( const TCB_t * pxTCB ) + { + BaseType_t xLowestPriorityToPreempt; + BaseType_t xCurrentCoreTaskPriority; + BaseType_t xLowestPriorityCore = ( BaseType_t ) -1; + BaseType_t xCoreID; + + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + BaseType_t xYieldCount = 0; + #endif /* #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) */ + + /* This must be called from a critical section. */ + configASSERT( portGET_CRITICAL_NESTING_COUNT() > 0U ); + + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + + /* No task should yield for this one if it is a lower priority + * than priority level of currently ready tasks. */ + if( pxTCB->uxPriority >= uxTopReadyPriority ) + #else + /* Yield is not required for a task which is already running. */ + if( taskTASK_IS_RUNNING( pxTCB ) == pdFALSE ) + #endif + { + xLowestPriorityToPreempt = ( BaseType_t ) pxTCB->uxPriority; + + /* xLowestPriorityToPreempt will be decremented to -1 if the priority of pxTCB + * is 0. This is ok as we will give system idle tasks a priority of -1 below. */ + --xLowestPriorityToPreempt; + + for( xCoreID = ( BaseType_t ) 0; xCoreID < ( BaseType_t ) configNUMBER_OF_CORES; xCoreID++ ) + { + xCurrentCoreTaskPriority = ( BaseType_t ) pxCurrentTCBs[ xCoreID ]->uxPriority; + + /* System idle tasks are being assigned a priority of tskIDLE_PRIORITY - 1 here. */ + if( ( pxCurrentTCBs[ xCoreID ]->uxTaskAttributes & taskATTRIBUTE_IS_IDLE ) != 0U ) + { + xCurrentCoreTaskPriority = ( BaseType_t ) ( xCurrentCoreTaskPriority - 1 ); + } + + if( ( taskTASK_IS_RUNNING( pxCurrentTCBs[ xCoreID ] ) != pdFALSE ) && ( xYieldPendings[ xCoreID ] == pdFALSE ) ) + { + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + if( taskTASK_IS_RUNNING( pxTCB ) == pdFALSE ) + #endif + { + if( xCurrentCoreTaskPriority <= xLowestPriorityToPreempt ) + { + #if ( configUSE_CORE_AFFINITY == 1 ) + if( ( pxTCB->uxCoreAffinityMask & ( ( UBaseType_t ) 1U << ( UBaseType_t ) xCoreID ) ) != 0U ) + #endif + { + #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) + if( pxCurrentTCBs[ xCoreID ]->xPreemptionDisable == pdFALSE ) + #endif + { + xLowestPriorityToPreempt = xCurrentCoreTaskPriority; + xLowestPriorityCore = xCoreID; + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + { + /* Yield all currently running non-idle tasks with a priority lower than + * the task that needs to run. */ + if( ( xCurrentCoreTaskPriority > ( ( BaseType_t ) tskIDLE_PRIORITY - 1 ) ) && + ( xCurrentCoreTaskPriority < ( BaseType_t ) pxTCB->uxPriority ) ) + { + prvYieldCore( xCoreID ); + xYieldCount++; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + if( ( xYieldCount == 0 ) && ( xLowestPriorityCore >= 0 ) ) + #else /* #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) */ + if( xLowestPriorityCore >= 0 ) + #endif /* #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) */ + { + prvYieldCore( xLowestPriorityCore ); + } + + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + /* Verify that the calling core always yields to higher priority tasks. */ + if( ( ( pxCurrentTCBs[ portGET_CORE_ID() ]->uxTaskAttributes & taskATTRIBUTE_IS_IDLE ) == 0U ) && + ( pxTCB->uxPriority > pxCurrentTCBs[ portGET_CORE_ID() ]->uxPriority ) ) + { + configASSERT( ( xYieldPendings[ portGET_CORE_ID() ] == pdTRUE ) || + ( taskTASK_IS_RUNNING( pxCurrentTCBs[ portGET_CORE_ID() ] ) == pdFALSE ) ); + } + #endif + } + } +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( configNUMBER_OF_CORES > 1 ) + static void prvSelectHighestPriorityTask( BaseType_t xCoreID ) + { + UBaseType_t uxCurrentPriority = uxTopReadyPriority; + BaseType_t xTaskScheduled = pdFALSE; + BaseType_t xDecrementTopPriority = pdTRUE; + TCB_t * pxTCB = NULL; + + #if ( configUSE_CORE_AFFINITY == 1 ) + const TCB_t * pxPreviousTCB = NULL; + #endif + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + BaseType_t xPriorityDropped = pdFALSE; + #endif + + /* This function should be called when scheduler is running. */ + configASSERT( xSchedulerRunning == pdTRUE ); + + /* A new task is created and a running task with the same priority yields + * itself to run the new task. When a running task yields itself, it is still + * in the ready list. This running task will be selected before the new task + * since the new task is always added to the end of the ready list. + * The other problem is that the running task still in the same position of + * the ready list when it yields itself. It is possible that it will be selected + * earlier then other tasks which waits longer than this task. + * + * To fix these problems, the running task should be put to the end of the + * ready list before searching for the ready task in the ready list. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxCurrentTCBs[ xCoreID ]->uxPriority ] ), + &pxCurrentTCBs[ xCoreID ]->xStateListItem ) == pdTRUE ) + { + ( void ) uxListRemove( &pxCurrentTCBs[ xCoreID ]->xStateListItem ); + vListInsertEnd( &( pxReadyTasksLists[ pxCurrentTCBs[ xCoreID ]->uxPriority ] ), + &pxCurrentTCBs[ xCoreID ]->xStateListItem ); + } + + while( xTaskScheduled == pdFALSE ) + { + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + { + if( uxCurrentPriority < uxTopReadyPriority ) + { + /* We can't schedule any tasks, other than idle, that have a + * priority lower than the priority of a task currently running + * on another core. */ + uxCurrentPriority = tskIDLE_PRIORITY; + } + } + #endif + + if( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxCurrentPriority ] ) ) == pdFALSE ) + { + const List_t * const pxReadyList = &( pxReadyTasksLists[ uxCurrentPriority ] ); + const ListItem_t * pxEndMarker = listGET_END_MARKER( pxReadyList ); + ListItem_t * pxIterator; + + /* The ready task list for uxCurrentPriority is not empty, so uxTopReadyPriority + * must not be decremented any further. */ + xDecrementTopPriority = pdFALSE; + + for( pxIterator = listGET_HEAD_ENTRY( pxReadyList ); pxIterator != pxEndMarker; pxIterator = listGET_NEXT( pxIterator ) ) + { + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxTCB = ( TCB_t * ) listGET_LIST_ITEM_OWNER( pxIterator ); + + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + { + /* When falling back to the idle priority because only one priority + * level is allowed to run at a time, we should ONLY schedule the true + * idle tasks, not user tasks at the idle priority. */ + if( uxCurrentPriority < uxTopReadyPriority ) + { + if( ( pxTCB->uxTaskAttributes & taskATTRIBUTE_IS_IDLE ) == 0U ) + { + continue; + } + } + } + #endif /* #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) */ + + if( pxTCB->xTaskRunState == taskTASK_NOT_RUNNING ) + { + #if ( configUSE_CORE_AFFINITY == 1 ) + if( ( pxTCB->uxCoreAffinityMask & ( ( UBaseType_t ) 1U << ( UBaseType_t ) xCoreID ) ) != 0U ) + #endif + { + /* If the task is not being executed by any core swap it in. */ + pxCurrentTCBs[ xCoreID ]->xTaskRunState = taskTASK_NOT_RUNNING; + #if ( configUSE_CORE_AFFINITY == 1 ) + pxPreviousTCB = pxCurrentTCBs[ xCoreID ]; + #endif + pxTCB->xTaskRunState = xCoreID; + pxCurrentTCBs[ xCoreID ] = pxTCB; + xTaskScheduled = pdTRUE; + } + } + else if( pxTCB == pxCurrentTCBs[ xCoreID ] ) + { + configASSERT( ( pxTCB->xTaskRunState == xCoreID ) || ( pxTCB->xTaskRunState == taskTASK_SCHEDULED_TO_YIELD ) ); + + #if ( configUSE_CORE_AFFINITY == 1 ) + if( ( pxTCB->uxCoreAffinityMask & ( ( UBaseType_t ) 1U << ( UBaseType_t ) xCoreID ) ) != 0U ) + #endif + { + /* The task is already running on this core, mark it as scheduled. */ + pxTCB->xTaskRunState = xCoreID; + xTaskScheduled = pdTRUE; + } + } + else + { + /* This task is running on the core other than xCoreID. */ + mtCOVERAGE_TEST_MARKER(); + } + + if( xTaskScheduled != pdFALSE ) + { + /* A task has been selected to run on this core. */ + break; + } + } + } + else + { + if( xDecrementTopPriority != pdFALSE ) + { + uxTopReadyPriority--; + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + { + xPriorityDropped = pdTRUE; + } + #endif + } + } + + /* There are configNUMBER_OF_CORES Idle tasks created when scheduler started. + * The scheduler should be able to select a task to run when uxCurrentPriority + * is tskIDLE_PRIORITY. uxCurrentPriority is never decreased to value blow + * tskIDLE_PRIORITY. */ + if( uxCurrentPriority > tskIDLE_PRIORITY ) + { + uxCurrentPriority--; + } + else + { + /* This function is called when idle task is not created. Break the + * loop to prevent uxCurrentPriority overrun. */ + break; + } + } + + #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) + { + if( xTaskScheduled == pdTRUE ) + { + if( xPriorityDropped != pdFALSE ) + { + /* There may be several ready tasks that were being prevented from running because there was + * a higher priority task running. Now that the last of the higher priority tasks is no longer + * running, make sure all the other idle tasks yield. */ + BaseType_t x; + + for( x = ( BaseType_t ) 0; x < ( BaseType_t ) configNUMBER_OF_CORES; x++ ) + { + if( ( pxCurrentTCBs[ x ]->uxTaskAttributes & taskATTRIBUTE_IS_IDLE ) != 0U ) + { + prvYieldCore( x ); + } + } + } + } + } + #endif /* #if ( configRUN_MULTIPLE_PRIORITIES == 0 ) */ + + #if ( configUSE_CORE_AFFINITY == 1 ) + { + if( xTaskScheduled == pdTRUE ) + { + if( ( pxPreviousTCB != NULL ) && ( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxPreviousTCB->uxPriority ] ), &( pxPreviousTCB->xStateListItem ) ) != pdFALSE ) ) + { + /* A ready task was just evicted from this core. See if it can be + * scheduled on any other core. */ + UBaseType_t uxCoreMap = pxPreviousTCB->uxCoreAffinityMask; + BaseType_t xLowestPriority = ( BaseType_t ) pxPreviousTCB->uxPriority; + BaseType_t xLowestPriorityCore = -1; + BaseType_t x; + + if( ( pxPreviousTCB->uxTaskAttributes & taskATTRIBUTE_IS_IDLE ) != 0U ) + { + xLowestPriority = xLowestPriority - 1; + } + + if( ( uxCoreMap & ( ( UBaseType_t ) 1U << ( UBaseType_t ) xCoreID ) ) != 0U ) + { + /* pxPreviousTCB was removed from this core and this core is not excluded + * from it's core affinity mask. + * + * pxPreviousTCB is preempted by the new higher priority task + * pxCurrentTCBs[ xCoreID ]. When searching a new core for pxPreviousTCB, + * we do not need to look at the cores on which pxCurrentTCBs[ xCoreID ] + * is allowed to run. The reason is - when more than one cores are + * eligible for an incoming task, we preempt the core with the minimum + * priority task. Because this core (i.e. xCoreID) was preempted for + * pxCurrentTCBs[ xCoreID ], this means that all the others cores + * where pxCurrentTCBs[ xCoreID ] can run, are running tasks with priority + * no lower than pxPreviousTCB's priority. Therefore, the only cores where + * which can be preempted for pxPreviousTCB are the ones where + * pxCurrentTCBs[ xCoreID ] is not allowed to run (and obviously, + * pxPreviousTCB is allowed to run). + * + * This is an optimization which reduces the number of cores needed to be + * searched for pxPreviousTCB to run. */ + uxCoreMap &= ~( pxCurrentTCBs[ xCoreID ]->uxCoreAffinityMask ); + } + else + { + /* pxPreviousTCB's core affinity mask is changed and it is no longer + * allowed to run on this core. Searching all the cores in pxPreviousTCB's + * new core affinity mask to find a core on which it can run. */ + } + + uxCoreMap &= ( ( 1U << configNUMBER_OF_CORES ) - 1U ); + + for( x = ( ( BaseType_t ) configNUMBER_OF_CORES - 1 ); x >= ( BaseType_t ) 0; x-- ) + { + UBaseType_t uxCore = ( UBaseType_t ) x; + BaseType_t xTaskPriority; + + if( ( uxCoreMap & ( ( UBaseType_t ) 1U << uxCore ) ) != 0U ) + { + xTaskPriority = ( BaseType_t ) pxCurrentTCBs[ uxCore ]->uxPriority; + + if( ( pxCurrentTCBs[ uxCore ]->uxTaskAttributes & taskATTRIBUTE_IS_IDLE ) != 0U ) + { + xTaskPriority = xTaskPriority - ( BaseType_t ) 1; + } + + uxCoreMap &= ~( ( UBaseType_t ) 1U << uxCore ); + + if( ( xTaskPriority < xLowestPriority ) && + ( taskTASK_IS_RUNNING( pxCurrentTCBs[ uxCore ] ) != pdFALSE ) && + ( xYieldPendings[ uxCore ] == pdFALSE ) ) + { + #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) + if( pxCurrentTCBs[ uxCore ]->xPreemptionDisable == pdFALSE ) + #endif + { + xLowestPriority = xTaskPriority; + xLowestPriorityCore = ( BaseType_t ) uxCore; + } + } + } + } + + if( xLowestPriorityCore >= 0 ) + { + prvYieldCore( xLowestPriorityCore ); + } + } + } + } + #endif /* #if ( configUSE_CORE_AFFINITY == 1 ) */ + } + +#endif /* ( configNUMBER_OF_CORES > 1 ) */ + +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + static TCB_t * prvCreateStaticTask( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t * pxNewTCB; + + configASSERT( puxStackBuffer != NULL ); + configASSERT( pxTaskBuffer != NULL ); + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticTask_t equals the size of the real task + * structure. */ + volatile size_t xSize = sizeof( StaticTask_t ); + configASSERT( xSize == sizeof( TCB_t ) ); + ( void ) xSize; /* Prevent unused variable warning when configASSERT() is not used. */ + } + #endif /* configASSERT_DEFINED */ + + if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) ) + { + /* The memory used for the task's TCB and stack are passed into this + * function - use them. */ + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + pxNewTCB = ( TCB_t * ) pxTaskBuffer; + ( void ) memset( ( void * ) pxNewTCB, 0x00, sizeof( TCB_t ) ); + pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer; + + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note this + * task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); + } + else + { + pxNewTCB = NULL; + } + + return pxNewTCB; + } +/*-----------------------------------------------------------*/ + + TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) + { + TaskHandle_t xReturn = NULL; + TCB_t * pxNewTCB; + + traceENTER_xTaskCreateStatic( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, puxStackBuffer, pxTaskBuffer ); + + pxNewTCB = prvCreateStaticTask( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, puxStackBuffer, pxTaskBuffer, &xReturn ); + + if( pxNewTCB != NULL ) + { + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + { + /* Set the task's affinity before scheduling it. */ + pxNewTCB->uxCoreAffinityMask = configTASK_DEFAULT_CORE_AFFINITY; + } + #endif + + prvAddNewTaskToReadyList( pxNewTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xTaskCreateStatic( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + TaskHandle_t xTaskCreateStaticAffinitySet( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer, + UBaseType_t uxCoreAffinityMask ) + { + TaskHandle_t xReturn = NULL; + TCB_t * pxNewTCB; + + traceENTER_xTaskCreateStaticAffinitySet( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, puxStackBuffer, pxTaskBuffer, uxCoreAffinityMask ); + + pxNewTCB = prvCreateStaticTask( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, puxStackBuffer, pxTaskBuffer, &xReturn ); + + if( pxNewTCB != NULL ) + { + /* Set the task's affinity before scheduling it. */ + pxNewTCB->uxCoreAffinityMask = uxCoreAffinityMask; + + prvAddNewTaskToReadyList( pxNewTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xTaskCreateStaticAffinitySet( xReturn ); + + return xReturn; + } + #endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) */ + +#endif /* SUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + static TCB_t * prvCreateRestrictedStaticTask( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t * pxNewTCB; + + configASSERT( pxTaskDefinition->puxStackBuffer != NULL ); + configASSERT( pxTaskDefinition->pxTaskBuffer != NULL ); + + if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) ) + { + /* Allocate space for the TCB. Where the memory comes from depends + * on the implementation of the port malloc function and whether or + * not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer; + ( void ) memset( ( void * ) pxNewTCB, 0x00, sizeof( TCB_t ) ); + + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note this + * task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); + } + else + { + pxNewTCB = NULL; + } + + return pxNewTCB; + } +/*-----------------------------------------------------------*/ + + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn; + + traceENTER_xTaskCreateRestrictedStatic( pxTaskDefinition, pxCreatedTask ); + + configASSERT( pxTaskDefinition != NULL ); + + pxNewTCB = prvCreateRestrictedStaticTask( pxTaskDefinition, pxCreatedTask ); + + if( pxNewTCB != NULL ) + { + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + { + /* Set the task's affinity before scheduling it. */ + pxNewTCB->uxCoreAffinityMask = configTASK_DEFAULT_CORE_AFFINITY; + } + #endif + + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + traceRETURN_xTaskCreateRestrictedStatic( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + BaseType_t xTaskCreateRestrictedStaticAffinitySet( const TaskParameters_t * const pxTaskDefinition, + UBaseType_t uxCoreAffinityMask, + TaskHandle_t * pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn; + + traceENTER_xTaskCreateRestrictedStaticAffinitySet( pxTaskDefinition, uxCoreAffinityMask, pxCreatedTask ); + + configASSERT( pxTaskDefinition != NULL ); + + pxNewTCB = prvCreateRestrictedStaticTask( pxTaskDefinition, pxCreatedTask ); + + if( pxNewTCB != NULL ) + { + /* Set the task's affinity before scheduling it. */ + pxNewTCB->uxCoreAffinityMask = uxCoreAffinityMask; + + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + traceRETURN_xTaskCreateRestrictedStaticAffinitySet( xReturn ); + + return xReturn; + } + #endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) */ + +#endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + static TCB_t * prvCreateRestrictedTask( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t * pxNewTCB; + + configASSERT( pxTaskDefinition->puxStackBuffer ); + + if( pxTaskDefinition->puxStackBuffer != NULL ) + { + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + + if( pxNewTCB != NULL ) + { + ( void ) memset( ( void * ) pxNewTCB, 0x00, sizeof( TCB_t ) ); + + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note + * this task had a statically allocated stack in case it is + * later deleted. The TCB was allocated dynamically. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); + } + } + else + { + pxNewTCB = NULL; + } + + return pxNewTCB; + } +/*-----------------------------------------------------------*/ + + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn; + + traceENTER_xTaskCreateRestricted( pxTaskDefinition, pxCreatedTask ); + + pxNewTCB = prvCreateRestrictedTask( pxTaskDefinition, pxCreatedTask ); + + if( pxNewTCB != NULL ) + { + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + { + /* Set the task's affinity before scheduling it. */ + pxNewTCB->uxCoreAffinityMask = configTASK_DEFAULT_CORE_AFFINITY; + } + #endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) */ + + prvAddNewTaskToReadyList( pxNewTCB ); + + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + traceRETURN_xTaskCreateRestricted( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + BaseType_t xTaskCreateRestrictedAffinitySet( const TaskParameters_t * const pxTaskDefinition, + UBaseType_t uxCoreAffinityMask, + TaskHandle_t * pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn; + + traceENTER_xTaskCreateRestrictedAffinitySet( pxTaskDefinition, uxCoreAffinityMask, pxCreatedTask ); + + pxNewTCB = prvCreateRestrictedTask( pxTaskDefinition, pxCreatedTask ); + + if( pxNewTCB != NULL ) + { + /* Set the task's affinity before scheduling it. */ + pxNewTCB->uxCoreAffinityMask = uxCoreAffinityMask; + + prvAddNewTaskToReadyList( pxNewTCB ); + + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + traceRETURN_xTaskCreateRestrictedAffinitySet( xReturn ); + + return xReturn; + } + #endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) */ + + +#endif /* portUSING_MPU_WRAPPERS */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + static TCB_t * prvCreateTask( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t * pxNewTCB; + + /* If the stack grows down then allocate the stack then the TCB so the stack + * does not grow into the TCB. Likewise if the stack grows up then allocate + * the TCB then the stack. */ + #if ( portSTACK_GROWTH > 0 ) + { + /* Allocate space for the TCB. Where the memory comes from depends on + * the implementation of the port malloc function and whether or not static + * allocation is being used. */ + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + + if( pxNewTCB != NULL ) + { + ( void ) memset( ( void * ) pxNewTCB, 0x00, sizeof( TCB_t ) ); + + /* Allocate space for the stack used by the task being created. + * The base of the stack memory stored in the TCB so the task can + * be deleted later if required. */ + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxNewTCB->pxStack = ( StackType_t * ) pvPortMallocStack( ( ( ( size_t ) uxStackDepth ) * sizeof( StackType_t ) ) ); + + if( pxNewTCB->pxStack == NULL ) + { + /* Could not allocate the stack. Delete the allocated TCB. */ + vPortFree( pxNewTCB ); + pxNewTCB = NULL; + } + } + } + #else /* portSTACK_GROWTH */ + { + StackType_t * pxStack; + + /* Allocate space for the stack used by the task being created. */ + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxStack = pvPortMallocStack( ( ( ( size_t ) uxStackDepth ) * sizeof( StackType_t ) ) ); + + if( pxStack != NULL ) + { + /* Allocate space for the TCB. */ + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + + if( pxNewTCB != NULL ) + { + ( void ) memset( ( void * ) pxNewTCB, 0x00, sizeof( TCB_t ) ); + + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxStack; + } + else + { + /* The stack cannot be used as the TCB was not created. Free + * it again. */ + vPortFreeStack( pxStack ); + } + } + else + { + pxNewTCB = NULL; + } + } + #endif /* portSTACK_GROWTH */ + + if( pxNewTCB != NULL ) + { + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note this + * task was created dynamically in case it is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); + } + + return pxNewTCB; + } +/*-----------------------------------------------------------*/ + + BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn; + + traceENTER_xTaskCreate( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, pxCreatedTask ); + + pxNewTCB = prvCreateTask( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, pxCreatedTask ); + + if( pxNewTCB != NULL ) + { + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + { + /* Set the task's affinity before scheduling it. */ + pxNewTCB->uxCoreAffinityMask = configTASK_DEFAULT_CORE_AFFINITY; + } + #endif + + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + traceRETURN_xTaskCreate( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + BaseType_t xTaskCreateAffinitySet( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + UBaseType_t uxCoreAffinityMask, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn; + + traceENTER_xTaskCreateAffinitySet( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, uxCoreAffinityMask, pxCreatedTask ); + + pxNewTCB = prvCreateTask( pxTaskCode, pcName, uxStackDepth, pvParameters, uxPriority, pxCreatedTask ); + + if( pxNewTCB != NULL ) + { + /* Set the task's affinity before scheduling it. */ + pxNewTCB->uxCoreAffinityMask = uxCoreAffinityMask; + + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + traceRETURN_xTaskCreateAffinitySet( xReturn ); + + return xReturn; + } + #endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) */ + +#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, + const configSTACK_DEPTH_TYPE uxStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t * pxNewTCB, + const MemoryRegion_t * const xRegions ) +{ + StackType_t * pxTopOfStack; + UBaseType_t x; + + #if ( portUSING_MPU_WRAPPERS == 1 ) + /* Should the task be created in privileged mode? */ + BaseType_t xRunPrivileged; + + if( ( uxPriority & portPRIVILEGE_BIT ) != 0U ) + { + xRunPrivileged = pdTRUE; + } + else + { + xRunPrivileged = pdFALSE; + } + uxPriority &= ~portPRIVILEGE_BIT; + #endif /* portUSING_MPU_WRAPPERS == 1 */ + + /* Avoid dependency on memset() if it is not required. */ + #if ( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 ) + { + /* Fill the stack with a known value to assist debugging. */ + ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) uxStackDepth * sizeof( StackType_t ) ); + } + #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */ + + /* Calculate the top of stack address. This depends on whether the stack + * grows from high memory to low (as per the 80x86) or vice versa. + * portSTACK_GROWTH is used to make the result positive or negative as required + * by the port. */ + #if ( portSTACK_GROWTH < 0 ) + { + pxTopOfStack = &( pxNewTCB->pxStack[ uxStackDepth - ( configSTACK_DEPTH_TYPE ) 1 ] ); + pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); + + /* Check the alignment of the calculated top of stack is correct. */ + configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0U ) ); + + #if ( configRECORD_STACK_HIGH_ADDRESS == 1 ) + { + /* Also record the stack's high address, which may assist + * debugging. */ + pxNewTCB->pxEndOfStack = pxTopOfStack; + } + #endif /* configRECORD_STACK_HIGH_ADDRESS */ + } + #else /* portSTACK_GROWTH */ + { + pxTopOfStack = pxNewTCB->pxStack; + pxTopOfStack = ( StackType_t * ) ( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) + portBYTE_ALIGNMENT_MASK ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); + + /* Check the alignment of the calculated top of stack is correct. */ + configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0U ) ); + + /* The other extreme of the stack space is required if stack checking is + * performed. */ + pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( uxStackDepth - ( configSTACK_DEPTH_TYPE ) 1 ); + } + #endif /* portSTACK_GROWTH */ + + /* Store the task name in the TCB. */ + if( pcName != NULL ) + { + for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) + { + pxNewTCB->pcTaskName[ x ] = pcName[ x ]; + + /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than + * configMAX_TASK_NAME_LEN characters just in case the memory after the + * string is not accessible (extremely unlikely). */ + if( pcName[ x ] == ( char ) 0x00 ) + { + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Ensure the name string is terminated in the case that the string length + * was greater or equal to configMAX_TASK_NAME_LEN. */ + pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1U ] = '\0'; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* This is used as an array index so must ensure it's not too large. */ + configASSERT( uxPriority < configMAX_PRIORITIES ); + + if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxNewTCB->uxPriority = uxPriority; + #if ( configUSE_MUTEXES == 1 ) + { + pxNewTCB->uxBasePriority = uxPriority; + } + #endif /* configUSE_MUTEXES */ + + vListInitialiseItem( &( pxNewTCB->xStateListItem ) ); + vListInitialiseItem( &( pxNewTCB->xEventListItem ) ); + + /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get + * back to the containing TCB from a generic item in a list. */ + listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB ); + + /* Event lists are always in priority order. */ + listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); + listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB ); + + #if ( portUSING_MPU_WRAPPERS == 1 ) + { + vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, uxStackDepth ); + } + #else + { + /* Avoid compiler warning about unreferenced parameter. */ + ( void ) xRegions; + } + #endif + + #if ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) + { + /* Allocate and initialize memory for the task's TLS Block. */ + configINIT_TLS_BLOCK( pxNewTCB->xTLSBlock, pxTopOfStack ); + } + #endif + + /* Initialize the TCB stack to look as if the task was already running, + * but had been interrupted by the scheduler. The return address is set + * to the start of the task function. Once the stack has been initialised + * the top of stack variable is updated. */ + #if ( portUSING_MPU_WRAPPERS == 1 ) + { + /* If the port has capability to detect stack overflow, + * pass the stack end address to the stack initialization + * function as well. */ + #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if ( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged, &( pxNewTCB->xMPUSettings ) ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged, &( pxNewTCB->xMPUSettings ) ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged, &( pxNewTCB->xMPUSettings ) ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #else /* portUSING_MPU_WRAPPERS */ + { + /* If the port has capability to detect stack overflow, + * pass the stack end address to the stack initialization + * function as well. */ + #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if ( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #endif /* portUSING_MPU_WRAPPERS */ + + /* Initialize task state and task attributes. */ + #if ( configNUMBER_OF_CORES > 1 ) + { + pxNewTCB->xTaskRunState = taskTASK_NOT_RUNNING; + + /* Is this an idle task? */ + if( ( ( TaskFunction_t ) pxTaskCode == ( TaskFunction_t ) prvIdleTask ) || ( ( TaskFunction_t ) pxTaskCode == ( TaskFunction_t ) prvPassiveIdleTask ) ) + { + pxNewTCB->uxTaskAttributes |= taskATTRIBUTE_IS_IDLE; + } + } + #endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + + if( pxCreatedTask != NULL ) + { + /* Pass the handle out in an anonymous way. The handle can be used to + * change the created task's priority, delete the created task, etc.*/ + *pxCreatedTask = ( TaskHandle_t ) pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } +} +/*-----------------------------------------------------------*/ + +#if ( configNUMBER_OF_CORES == 1 ) + + static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) + { + /* Ensure interrupts don't access the task lists while the lists are being + * updated. */ + taskENTER_CRITICAL(); + { + uxCurrentNumberOfTasks = ( UBaseType_t ) ( uxCurrentNumberOfTasks + 1U ); + + if( pxCurrentTCB == NULL ) + { + /* There are no other tasks, or all the other tasks are in + * the suspended state - make this the current task. */ + pxCurrentTCB = pxNewTCB; + + if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) + { + /* This is the first task to be created so do the preliminary + * initialisation required. We will not recover if this call + * fails, but we will report the failure. */ + prvInitialiseTaskLists(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If the scheduler is not already running, make this task the + * current task if it is the highest priority task to be created + * so far. */ + if( xSchedulerRunning == pdFALSE ) + { + if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) + { + pxCurrentTCB = pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + uxTaskNumber++; + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Add a counter into the TCB for tracing only. */ + pxNewTCB->uxTCBNumber = uxTaskNumber; + } + #endif /* configUSE_TRACE_FACILITY */ + traceTASK_CREATE( pxNewTCB ); + + prvAddTaskToReadyList( pxNewTCB ); + + portSETUP_TCB( pxNewTCB ); + } + taskEXIT_CRITICAL(); + + if( xSchedulerRunning != pdFALSE ) + { + /* If the created task is of a higher priority than the current task + * then it should run now. */ + taskYIELD_ANY_CORE_IF_USING_PREEMPTION( pxNewTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#else /* #if ( configNUMBER_OF_CORES == 1 ) */ + + static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) + { + /* Ensure interrupts don't access the task lists while the lists are being + * updated. */ + taskENTER_CRITICAL(); + { + uxCurrentNumberOfTasks++; + + if( xSchedulerRunning == pdFALSE ) + { + if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) + { + /* This is the first task to be created so do the preliminary + * initialisation required. We will not recover if this call + * fails, but we will report the failure. */ + prvInitialiseTaskLists(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* All the cores start with idle tasks before the SMP scheduler + * is running. Idle tasks are assigned to cores when they are + * created in prvCreateIdleTasks(). */ + } + + uxTaskNumber++; + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Add a counter into the TCB for tracing only. */ + pxNewTCB->uxTCBNumber = uxTaskNumber; + } + #endif /* configUSE_TRACE_FACILITY */ + traceTASK_CREATE( pxNewTCB ); + + prvAddTaskToReadyList( pxNewTCB ); + + portSETUP_TCB( pxNewTCB ); + + if( xSchedulerRunning != pdFALSE ) + { + /* If the created task is of a higher priority than another + * currently running task and preemption is on then it should + * run now. */ + taskYIELD_ANY_CORE_IF_USING_PREEMPTION( pxNewTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } + +#endif /* #if ( configNUMBER_OF_CORES == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) + + static size_t prvSnprintfReturnValueToCharsWritten( int iSnprintfReturnValue, + size_t n ) + { + size_t uxCharsWritten; + + if( iSnprintfReturnValue < 0 ) + { + /* Encoding error - Return 0 to indicate that nothing + * was written to the buffer. */ + uxCharsWritten = 0; + } + else if( iSnprintfReturnValue >= ( int ) n ) + { + /* This is the case when the supplied buffer is not + * large to hold the generated string. Return the + * number of characters actually written without + * counting the terminating NULL character. */ + uxCharsWritten = n - 1U; + } + else + { + /* Complete string was written to the buffer. */ + uxCharsWritten = ( size_t ) iSnprintfReturnValue; + } + + return uxCharsWritten; + } + +#endif /* #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelete == 1 ) + + void vTaskDelete( TaskHandle_t xTaskToDelete ) + { + TCB_t * pxTCB; + BaseType_t xDeleteTCBInIdleTask = pdFALSE; + BaseType_t xTaskIsRunningOrYielding; + + traceENTER_vTaskDelete( xTaskToDelete ); + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the calling task that is + * being deleted. */ + pxTCB = prvGetTCBFromHandle( xTaskToDelete ); + + /* Remove task from the ready/delayed list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Increment the uxTaskNumber also so kernel aware debuggers can + * detect that the task lists need re-generating. This is done before + * portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will + * not return. */ + uxTaskNumber++; + + /* Use temp variable as distinct sequence points for reading volatile + * variables prior to a logical operator to ensure compliance with + * MISRA C 2012 Rule 13.5. */ + xTaskIsRunningOrYielding = taskTASK_IS_RUNNING_OR_SCHEDULED_TO_YIELD( pxTCB ); + + /* If the task is running (or yielding), we must add it to the + * termination list so that an idle task can delete it when it is + * no longer running. */ + if( ( xSchedulerRunning != pdFALSE ) && ( xTaskIsRunningOrYielding != pdFALSE ) ) + { + /* A running task or a task which is scheduled to yield is being + * deleted. This cannot complete when the task is still running + * on a core, as a context switch to another task is required. + * Place the task in the termination list. The idle task will check + * the termination list and free up any memory allocated by the + * scheduler for the TCB and stack of the deleted task. */ + vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); + + /* Increment the ucTasksDeleted variable so the idle task knows + * there is a task that has been deleted and that it should therefore + * check the xTasksWaitingTermination list. */ + ++uxDeletedTasksWaitingCleanUp; + + /* Call the delete hook before portPRE_TASK_DELETE_HOOK() as + * portPRE_TASK_DELETE_HOOK() does not return in the Win32 port. */ + traceTASK_DELETE( pxTCB ); + + /* Delete the task TCB in idle task. */ + xDeleteTCBInIdleTask = pdTRUE; + + /* The pre-delete hook is primarily for the Windows simulator, + * in which Windows specific clean up operations are performed, + * after which it is not possible to yield away from this task - + * hence xYieldPending is used to latch that a context switch is + * required. */ + #if ( configNUMBER_OF_CORES == 1 ) + portPRE_TASK_DELETE_HOOK( pxTCB, &( xYieldPendings[ 0 ] ) ); + #else + portPRE_TASK_DELETE_HOOK( pxTCB, &( xYieldPendings[ pxTCB->xTaskRunState ] ) ); + #endif + + /* In the case of SMP, it is possible that the task being deleted + * is running on another core. We must evict the task before + * exiting the critical section to ensure that the task cannot + * take an action which puts it back on ready/state/event list, + * thereby nullifying the delete operation. Once evicted, the + * task won't be scheduled ever as it will no longer be on the + * ready list. */ + #if ( configNUMBER_OF_CORES > 1 ) + { + if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE ) + { + if( pxTCB->xTaskRunState == ( BaseType_t ) portGET_CORE_ID() ) + { + configASSERT( uxSchedulerSuspended == 0 ); + taskYIELD_WITHIN_API(); + } + else + { + prvYieldCore( pxTCB->xTaskRunState ); + } + } + } + #endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + } + else + { + --uxCurrentNumberOfTasks; + traceTASK_DELETE( pxTCB ); + + /* Reset the next expected unblock time in case it referred to + * the task that has just been deleted. */ + prvResetNextTaskUnblockTime(); + } + } + taskEXIT_CRITICAL(); + + /* If the task is not deleting itself, call prvDeleteTCB from outside of + * critical section. If a task deletes itself, prvDeleteTCB is called + * from prvCheckTasksWaitingTermination which is called from Idle task. */ + if( xDeleteTCBInIdleTask != pdTRUE ) + { + prvDeleteTCB( pxTCB ); + } + + /* Force a reschedule if it is the currently running task that has just + * been deleted. */ + #if ( configNUMBER_OF_CORES == 1 ) + { + if( xSchedulerRunning != pdFALSE ) + { + if( pxTCB == pxCurrentTCB ) + { + configASSERT( uxSchedulerSuspended == 0 ); + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + + traceRETURN_vTaskDelete(); + } + +#endif /* INCLUDE_vTaskDelete */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskDelayUntil == 1 ) + + BaseType_t xTaskDelayUntil( TickType_t * const pxPreviousWakeTime, + const TickType_t xTimeIncrement ) + { + TickType_t xTimeToWake; + BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE; + + traceENTER_xTaskDelayUntil( pxPreviousWakeTime, xTimeIncrement ); + + configASSERT( pxPreviousWakeTime ); + configASSERT( ( xTimeIncrement > 0U ) ); + + vTaskSuspendAll(); + { + /* Minor optimisation. The tick count cannot change in this + * block. */ + const TickType_t xConstTickCount = xTickCount; + + configASSERT( uxSchedulerSuspended == 1U ); + + /* Generate the tick time at which the task wants to wake. */ + xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; + + if( xConstTickCount < *pxPreviousWakeTime ) + { + /* The tick count has overflowed since this function was + * lasted called. In this case the only time we should ever + * actually delay is if the wake time has also overflowed, + * and the wake time is greater than the tick time. When this + * is the case it is as if neither time had overflowed. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The tick time has not overflowed. In this case we will + * delay if either the wake time has overflowed, and/or the + * tick time is less than the wake time. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Update the wake time ready for the next call. */ + *pxPreviousWakeTime = xTimeToWake; + + if( xShouldDelay != pdFALSE ) + { + traceTASK_DELAY_UNTIL( xTimeToWake ); + + /* prvAddCurrentTaskToDelayedList() needs the block time, not + * the time to wake, so subtract the current tick count. */ + prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + xAlreadyYielded = xTaskResumeAll(); + + /* Force a reschedule if xTaskResumeAll has not already done so, we may + * have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xTaskDelayUntil( xShouldDelay ); + + return xShouldDelay; + } + +#endif /* INCLUDE_xTaskDelayUntil */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelay == 1 ) + + void vTaskDelay( const TickType_t xTicksToDelay ) + { + BaseType_t xAlreadyYielded = pdFALSE; + + traceENTER_vTaskDelay( xTicksToDelay ); + + /* A delay time of zero just forces a reschedule. */ + if( xTicksToDelay > ( TickType_t ) 0U ) + { + vTaskSuspendAll(); + { + configASSERT( uxSchedulerSuspended == 1U ); + + traceTASK_DELAY(); + + /* A task that is removed from the event list while the + * scheduler is suspended will not get placed in the ready + * list or removed from the blocked list until the scheduler + * is resumed. + * + * This task cannot be in an event list as it is the currently + * executing task. */ + prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE ); + } + xAlreadyYielded = xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Force a reschedule if xTaskResumeAll has not already done so, we may + * have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskDelay(); + } + +#endif /* INCLUDE_vTaskDelay */ +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) ) + + eTaskState eTaskGetState( TaskHandle_t xTask ) + { + eTaskState eReturn; + List_t const * pxStateList; + List_t const * pxEventList; + List_t const * pxDelayedList; + List_t const * pxOverflowedDelayedList; + const TCB_t * const pxTCB = xTask; + + traceENTER_eTaskGetState( xTask ); + + configASSERT( pxTCB ); + + #if ( configNUMBER_OF_CORES == 1 ) + if( pxTCB == pxCurrentTCB ) + { + /* The task calling this function is querying its own state. */ + eReturn = eRunning; + } + else + #endif + { + taskENTER_CRITICAL(); + { + pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); + pxEventList = listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ); + pxDelayedList = pxDelayedTaskList; + pxOverflowedDelayedList = pxOverflowDelayedTaskList; + } + taskEXIT_CRITICAL(); + + if( pxEventList == &xPendingReadyList ) + { + /* The task has been placed on the pending ready list, so its + * state is eReady regardless of what list the task's state list + * item is currently placed on. */ + eReturn = eReady; + } + else if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) ) + { + /* The task being queried is referenced from one of the Blocked + * lists. */ + eReturn = eBlocked; + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + else if( pxStateList == &xSuspendedTaskList ) + { + /* The task being queried is referenced from the suspended + * list. Is it genuinely suspended or is it blocked + * indefinitely? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) + { + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + BaseType_t x; + + /* The task does not appear on the event list item of + * and of the RTOS objects, but could still be in the + * blocked state if it is waiting on its notification + * rather than waiting on an object. If not, is + * suspended. */ + eReturn = eSuspended; + + for( x = ( BaseType_t ) 0; x < ( BaseType_t ) configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ ) + { + if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION ) + { + eReturn = eBlocked; + break; + } + } + } + #else /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + { + eReturn = eSuspended; + } + #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + } + else + { + eReturn = eBlocked; + } + } + #endif /* if ( INCLUDE_vTaskSuspend == 1 ) */ + + #if ( INCLUDE_vTaskDelete == 1 ) + else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) + { + /* The task being queried is referenced from the deleted + * tasks list, or it is not referenced from any lists at + * all. */ + eReturn = eDeleted; + } + #endif + + else + { + #if ( configNUMBER_OF_CORES == 1 ) + { + /* If the task is not in any other state, it must be in the + * Ready (including pending ready) state. */ + eReturn = eReady; + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE ) + { + /* Is it actively running on a core? */ + eReturn = eRunning; + } + else + { + /* If the task is not in any other state, it must be in the + * Ready (including pending ready) state. */ + eReturn = eReady; + } + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + } + } + + traceRETURN_eTaskGetState( eReturn ); + + return eReturn; + } + +#endif /* INCLUDE_eTaskGetState */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskPriorityGet == 1 ) + + UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) + { + TCB_t const * pxTCB; + UBaseType_t uxReturn; + + traceENTER_uxTaskPriorityGet( xTask ); + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the task + * that called uxTaskPriorityGet() that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + taskEXIT_CRITICAL(); + + traceRETURN_uxTaskPriorityGet( uxReturn ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskPriorityGet */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskPriorityGet == 1 ) + + UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) + { + TCB_t const * pxTCB; + UBaseType_t uxReturn; + UBaseType_t uxSavedInterruptStatus; + + traceENTER_uxTaskPriorityGetFromISR( xTask ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = ( UBaseType_t ) taskENTER_CRITICAL_FROM_ISR(); + { + /* If null is passed in here then it is the priority of the calling + * task that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_uxTaskPriorityGetFromISR( uxReturn ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskPriorityGet */ +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_uxTaskPriorityGet == 1 ) && ( configUSE_MUTEXES == 1 ) ) + + UBaseType_t uxTaskBasePriorityGet( const TaskHandle_t xTask ) + { + TCB_t const * pxTCB; + UBaseType_t uxReturn; + + traceENTER_uxTaskBasePriorityGet( xTask ); + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the base priority of the task + * that called uxTaskBasePriorityGet() that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxBasePriority; + } + taskEXIT_CRITICAL(); + + traceRETURN_uxTaskBasePriorityGet( uxReturn ); + + return uxReturn; + } + +#endif /* #if ( ( INCLUDE_uxTaskPriorityGet == 1 ) && ( configUSE_MUTEXES == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_uxTaskPriorityGet == 1 ) && ( configUSE_MUTEXES == 1 ) ) + + UBaseType_t uxTaskBasePriorityGetFromISR( const TaskHandle_t xTask ) + { + TCB_t const * pxTCB; + UBaseType_t uxReturn; + UBaseType_t uxSavedInterruptStatus; + + traceENTER_uxTaskBasePriorityGetFromISR( xTask ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = ( UBaseType_t ) taskENTER_CRITICAL_FROM_ISR(); + { + /* If null is passed in here then it is the base priority of the calling + * task that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxBasePriority; + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_uxTaskBasePriorityGetFromISR( uxReturn ); + + return uxReturn; + } + +#endif /* #if ( ( INCLUDE_uxTaskPriorityGet == 1 ) && ( configUSE_MUTEXES == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskPrioritySet == 1 ) + + void vTaskPrioritySet( TaskHandle_t xTask, + UBaseType_t uxNewPriority ) + { + TCB_t * pxTCB; + UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry; + BaseType_t xYieldRequired = pdFALSE; + + #if ( configNUMBER_OF_CORES > 1 ) + BaseType_t xYieldForTask = pdFALSE; + #endif + + traceENTER_vTaskPrioritySet( xTask, uxNewPriority ); + + configASSERT( uxNewPriority < configMAX_PRIORITIES ); + + /* Ensure the new priority is valid. */ + if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the calling + * task that is being changed. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + traceTASK_PRIORITY_SET( pxTCB, uxNewPriority ); + + #if ( configUSE_MUTEXES == 1 ) + { + uxCurrentBasePriority = pxTCB->uxBasePriority; + } + #else + { + uxCurrentBasePriority = pxTCB->uxPriority; + } + #endif + + if( uxCurrentBasePriority != uxNewPriority ) + { + /* The priority change may have readied a task of higher + * priority than a running task. */ + if( uxNewPriority > uxCurrentBasePriority ) + { + #if ( configNUMBER_OF_CORES == 1 ) + { + if( pxTCB != pxCurrentTCB ) + { + /* The priority of a task other than the currently + * running task is being raised. Is the priority being + * raised above that of the running task? */ + if( uxNewPriority > pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The priority of the running task is being raised, + * but the running task must already be the highest + * priority task able to run so no yield is required. */ + } + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + /* The priority of a task is being raised so + * perform a yield for this task later. */ + xYieldForTask = pdTRUE; + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + } + else if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE ) + { + /* Setting the priority of a running task down means + * there may now be another task of higher priority that + * is ready to execute. */ + #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) + if( pxTCB->xPreemptionDisable == pdFALSE ) + #endif + { + xYieldRequired = pdTRUE; + } + } + else + { + /* Setting the priority of any other task down does not + * require a yield as the running task must be above the + * new priority of the task being modified. */ + } + + /* Remember the ready list the task might be referenced from + * before its uxPriority member is changed so the + * taskRESET_READY_PRIORITY() macro can function correctly. */ + uxPriorityUsedOnEntry = pxTCB->uxPriority; + + #if ( configUSE_MUTEXES == 1 ) + { + /* Only change the priority being used if the task is not + * currently using an inherited priority or the new priority + * is bigger than the inherited priority. */ + if( ( pxTCB->uxBasePriority == pxTCB->uxPriority ) || ( uxNewPriority > pxTCB->uxPriority ) ) + { + pxTCB->uxPriority = uxNewPriority; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The base priority gets set whatever. */ + pxTCB->uxBasePriority = uxNewPriority; + } + #else /* if ( configUSE_MUTEXES == 1 ) */ + { + pxTCB->uxPriority = uxNewPriority; + } + #endif /* if ( configUSE_MUTEXES == 1 ) */ + + /* Only reset the event list item value if the value is not + * being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == ( ( TickType_t ) 0U ) ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the task is in the blocked or suspended list we need do + * nothing more than change its priority variable. However, if + * the task is in a ready list it needs to be removed and placed + * in the list appropriate to its new priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* The task is currently in its ready list - remove before + * adding it to its new ready list. As we are in a critical + * section we can do this even if the scheduler is suspended. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + * there is no need to check again and the port level + * reset macro can be called directly. */ + portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + prvAddTaskToReadyList( pxTCB ); + } + else + { + #if ( configNUMBER_OF_CORES == 1 ) + { + mtCOVERAGE_TEST_MARKER(); + } + #else + { + /* It's possible that xYieldForTask was already set to pdTRUE because + * its priority is being raised. However, since it is not in a ready list + * we don't actually need to yield for it. */ + xYieldForTask = pdFALSE; + } + #endif + } + + if( xYieldRequired != pdFALSE ) + { + /* The running task priority is set down. Request the task to yield. */ + taskYIELD_TASK_CORE_IF_USING_PREEMPTION( pxTCB ); + } + else + { + #if ( configNUMBER_OF_CORES > 1 ) + if( xYieldForTask != pdFALSE ) + { + /* The priority of the task is being raised. If a running + * task has priority lower than this task, it should yield + * for this task. */ + taskYIELD_ANY_CORE_IF_USING_PREEMPTION( pxTCB ); + } + else + #endif /* if ( configNUMBER_OF_CORES > 1 ) */ + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Remove compiler warning about unused variables when the port + * optimised task selection is not being used. */ + ( void ) uxPriorityUsedOnEntry; + } + } + taskEXIT_CRITICAL(); + + traceRETURN_vTaskPrioritySet(); + } + +#endif /* INCLUDE_vTaskPrioritySet */ +/*-----------------------------------------------------------*/ + +#if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + void vTaskCoreAffinitySet( const TaskHandle_t xTask, + UBaseType_t uxCoreAffinityMask ) + { + TCB_t * pxTCB; + BaseType_t xCoreID; + UBaseType_t uxPrevCoreAffinityMask; + + #if ( configUSE_PREEMPTION == 1 ) + UBaseType_t uxPrevNotAllowedCores; + #endif + + traceENTER_vTaskCoreAffinitySet( xTask, uxCoreAffinityMask ); + + taskENTER_CRITICAL(); + { + pxTCB = prvGetTCBFromHandle( xTask ); + + uxPrevCoreAffinityMask = pxTCB->uxCoreAffinityMask; + pxTCB->uxCoreAffinityMask = uxCoreAffinityMask; + + if( xSchedulerRunning != pdFALSE ) + { + if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE ) + { + xCoreID = ( BaseType_t ) pxTCB->xTaskRunState; + + /* If the task can no longer run on the core it was running, + * request the core to yield. */ + if( ( uxCoreAffinityMask & ( ( UBaseType_t ) 1U << ( UBaseType_t ) xCoreID ) ) == 0U ) + { + prvYieldCore( xCoreID ); + } + } + else + { + #if ( configUSE_PREEMPTION == 1 ) + { + /* Calculate the cores on which this task was not allowed to + * run previously. */ + uxPrevNotAllowedCores = ( ~uxPrevCoreAffinityMask ) & ( ( 1U << configNUMBER_OF_CORES ) - 1U ); + + /* Does the new core mask enables this task to run on any of the + * previously not allowed cores? If yes, check if this task can be + * scheduled on any of those cores. */ + if( ( uxPrevNotAllowedCores & uxCoreAffinityMask ) != 0U ) + { + prvYieldForTask( pxTCB ); + } + } + #else /* #if( configUSE_PREEMPTION == 1 ) */ + { + mtCOVERAGE_TEST_MARKER(); + } + #endif /* #if( configUSE_PREEMPTION == 1 ) */ + } + } + } + taskEXIT_CRITICAL(); + + traceRETURN_vTaskCoreAffinitySet(); + } +#endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + UBaseType_t vTaskCoreAffinityGet( ConstTaskHandle_t xTask ) + { + const TCB_t * pxTCB; + UBaseType_t uxCoreAffinityMask; + + traceENTER_vTaskCoreAffinityGet( xTask ); + + taskENTER_CRITICAL(); + { + pxTCB = prvGetTCBFromHandle( xTask ); + uxCoreAffinityMask = pxTCB->uxCoreAffinityMask; + } + taskEXIT_CRITICAL(); + + traceRETURN_vTaskCoreAffinityGet( uxCoreAffinityMask ); + + return uxCoreAffinityMask; + } +#endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) */ + +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) + + void vTaskPreemptionDisable( const TaskHandle_t xTask ) + { + TCB_t * pxTCB; + + traceENTER_vTaskPreemptionDisable( xTask ); + + taskENTER_CRITICAL(); + { + pxTCB = prvGetTCBFromHandle( xTask ); + + pxTCB->xPreemptionDisable = pdTRUE; + } + taskEXIT_CRITICAL(); + + traceRETURN_vTaskPreemptionDisable(); + } + +#endif /* #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) + + void vTaskPreemptionEnable( const TaskHandle_t xTask ) + { + TCB_t * pxTCB; + BaseType_t xCoreID; + + traceENTER_vTaskPreemptionEnable( xTask ); + + taskENTER_CRITICAL(); + { + pxTCB = prvGetTCBFromHandle( xTask ); + + pxTCB->xPreemptionDisable = pdFALSE; + + if( xSchedulerRunning != pdFALSE ) + { + if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE ) + { + xCoreID = ( BaseType_t ) pxTCB->xTaskRunState; + prvYieldCore( xCoreID ); + } + } + } + taskEXIT_CRITICAL(); + + traceRETURN_vTaskPreemptionEnable(); + } + +#endif /* #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + void vTaskSuspend( TaskHandle_t xTaskToSuspend ) + { + TCB_t * pxTCB; + + traceENTER_vTaskSuspend( xTaskToSuspend ); + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the running task that is + * being suspended. */ + pxTCB = prvGetTCBFromHandle( xTaskToSuspend ); + + traceTASK_SUSPEND( pxTCB ); + + /* Remove task from the ready/delayed list and place in the + * suspended list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ); + + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + BaseType_t x; + + for( x = ( BaseType_t ) 0; x < ( BaseType_t ) configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ ) + { + if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION ) + { + /* The task was blocked to wait for a notification, but is + * now suspended, so no notification was received. */ + pxTCB->ucNotifyState[ x ] = taskNOT_WAITING_NOTIFICATION; + } + } + } + #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + + /* In the case of SMP, it is possible that the task being suspended + * is running on another core. We must evict the task before + * exiting the critical section to ensure that the task cannot + * take an action which puts it back on ready/state/event list, + * thereby nullifying the suspend operation. Once evicted, the + * task won't be scheduled before it is resumed as it will no longer + * be on the ready list. */ + #if ( configNUMBER_OF_CORES > 1 ) + { + if( xSchedulerRunning != pdFALSE ) + { + /* Reset the next expected unblock time in case it referred to the + * task that is now in the Suspended state. */ + prvResetNextTaskUnblockTime(); + + if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE ) + { + if( pxTCB->xTaskRunState == ( BaseType_t ) portGET_CORE_ID() ) + { + /* The current task has just been suspended. */ + configASSERT( uxSchedulerSuspended == 0 ); + vTaskYieldWithinAPI(); + } + else + { + prvYieldCore( pxTCB->xTaskRunState ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + } + taskEXIT_CRITICAL(); + + #if ( configNUMBER_OF_CORES == 1 ) + { + UBaseType_t uxCurrentListLength; + + if( xSchedulerRunning != pdFALSE ) + { + /* Reset the next expected unblock time in case it referred to the + * task that is now in the Suspended state. */ + taskENTER_CRITICAL(); + { + prvResetNextTaskUnblockTime(); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( pxTCB == pxCurrentTCB ) + { + if( xSchedulerRunning != pdFALSE ) + { + /* The current task has just been suspended. */ + configASSERT( uxSchedulerSuspended == 0 ); + portYIELD_WITHIN_API(); + } + else + { + /* The scheduler is not running, but the task that was pointed + * to by pxCurrentTCB has just been suspended and pxCurrentTCB + * must be adjusted to point to a different task. */ + + /* Use a temp variable as a distinct sequence point for reading + * volatile variables prior to a comparison to ensure compliance + * with MISRA C 2012 Rule 13.2. */ + uxCurrentListLength = listCURRENT_LIST_LENGTH( &xSuspendedTaskList ); + + if( uxCurrentListLength == uxCurrentNumberOfTasks ) + { + /* No other tasks are ready, so set pxCurrentTCB back to + * NULL so when the next task is created pxCurrentTCB will + * be set to point to it no matter what its relative priority + * is. */ + pxCurrentTCB = NULL; + } + else + { + vTaskSwitchContext(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + + traceRETURN_vTaskSuspend(); + } + +#endif /* INCLUDE_vTaskSuspend */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) + { + BaseType_t xReturn = pdFALSE; + const TCB_t * const pxTCB = xTask; + + /* Accesses xPendingReadyList so must be called from a critical + * section. */ + + /* It does not make sense to check if the calling task is suspended. */ + configASSERT( xTask ); + + /* Is the task being resumed actually in the suspended list? */ + if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* Has the task already been resumed from within an ISR? */ + if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) + { + /* Is it in the suspended list because it is in the Suspended + * state, or because it is blocked with no timeout? */ + if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) + { + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + BaseType_t x; + + /* The task does not appear on the event list item of + * and of the RTOS objects, but could still be in the + * blocked state if it is waiting on its notification + * rather than waiting on an object. If not, is + * suspended. */ + xReturn = pdTRUE; + + for( x = ( BaseType_t ) 0; x < ( BaseType_t ) configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ ) + { + if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION ) + { + xReturn = pdFALSE; + break; + } + } + } + #else /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + { + xReturn = pdTRUE; + } + #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* INCLUDE_vTaskSuspend */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + void vTaskResume( TaskHandle_t xTaskToResume ) + { + TCB_t * const pxTCB = xTaskToResume; + + traceENTER_vTaskResume( xTaskToResume ); + + /* It does not make sense to resume the calling task. */ + configASSERT( xTaskToResume ); + + #if ( configNUMBER_OF_CORES == 1 ) + + /* The parameter cannot be NULL as it is impossible to resume the + * currently executing task. */ + if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) ) + #else + + /* The parameter cannot be NULL as it is impossible to resume the + * currently executing task. It is also impossible to resume a task + * that is actively running on another core but it is not safe + * to check their run state here. Therefore, we get into a critical + * section and check if the task is actually suspended or not. */ + if( pxTCB != NULL ) + #endif + { + taskENTER_CRITICAL(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME( pxTCB ); + + /* The ready list can be accessed even if the scheduler is + * suspended because this is inside a critical section. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + + /* This yield may not cause the task just resumed to run, + * but will leave the lists in the correct state for the + * next yield. */ + taskYIELD_ANY_CORE_IF_USING_PREEMPTION( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskResume(); + } + +#endif /* INCLUDE_vTaskSuspend */ + +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) + + BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) + { + BaseType_t xYieldRequired = pdFALSE; + TCB_t * const pxTCB = xTaskToResume; + UBaseType_t uxSavedInterruptStatus; + + traceENTER_xTaskResumeFromISR( xTaskToResume ); + + configASSERT( xTaskToResume ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME_FROM_ISR( pxTCB ); + + /* Check the ready lists can be accessed. */ + if( uxSchedulerSuspended == ( UBaseType_t ) 0U ) + { + #if ( configNUMBER_OF_CORES == 1 ) + { + /* Ready lists can be accessed so move the task from the + * suspended list to the ready list directly. */ + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + + /* Mark that a yield is pending in case the user is not + * using the return value to initiate a context switch + * from the ISR using the port specific portYIELD_FROM_ISR(). */ + xYieldPendings[ 0 ] = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed or ready lists cannot be accessed so the task + * is held in the pending ready list until the scheduler is + * unsuspended. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_PREEMPTION == 1 ) ) + { + prvYieldForTask( pxTCB ); + + if( xYieldPendings[ portGET_CORE_ID() ] != pdFALSE ) + { + xYieldRequired = pdTRUE; + } + } + #endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_PREEMPTION == 1 ) ) */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xTaskResumeFromISR( xYieldRequired ); + + return xYieldRequired; + } + +#endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */ +/*-----------------------------------------------------------*/ + +static BaseType_t prvCreateIdleTasks( void ) +{ + BaseType_t xReturn = pdPASS; + BaseType_t xCoreID; + char cIdleName[ configMAX_TASK_NAME_LEN ]; + TaskFunction_t pxIdleTaskFunction = NULL; + BaseType_t xIdleTaskNameIndex; + + for( xIdleTaskNameIndex = ( BaseType_t ) 0; xIdleTaskNameIndex < ( BaseType_t ) configMAX_TASK_NAME_LEN; xIdleTaskNameIndex++ ) + { + cIdleName[ xIdleTaskNameIndex ] = configIDLE_TASK_NAME[ xIdleTaskNameIndex ]; + + /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than + * configMAX_TASK_NAME_LEN characters just in case the memory after the + * string is not accessible (extremely unlikely). */ + if( cIdleName[ xIdleTaskNameIndex ] == ( char ) 0x00 ) + { + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Add each idle task at the lowest priority. */ + for( xCoreID = ( BaseType_t ) 0; xCoreID < ( BaseType_t ) configNUMBER_OF_CORES; xCoreID++ ) + { + #if ( configNUMBER_OF_CORES == 1 ) + { + pxIdleTaskFunction = prvIdleTask; + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + /* In the FreeRTOS SMP, configNUMBER_OF_CORES - 1 passive idle tasks + * are also created to ensure that each core has an idle task to + * run when no other task is available to run. */ + if( xCoreID == 0 ) + { + pxIdleTaskFunction = prvIdleTask; + } + else + { + pxIdleTaskFunction = prvPassiveIdleTask; + } + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + + /* Update the idle task name with suffix to differentiate the idle tasks. + * This function is not required in single core FreeRTOS since there is + * only one idle task. */ + #if ( configNUMBER_OF_CORES > 1 ) + { + /* Append the idle task number to the end of the name if there is space. */ + if( xIdleTaskNameIndex < ( BaseType_t ) configMAX_TASK_NAME_LEN ) + { + cIdleName[ xIdleTaskNameIndex ] = ( char ) ( xCoreID + '0' ); + + /* And append a null character if there is space. */ + if( ( xIdleTaskNameIndex + 1 ) < ( BaseType_t ) configMAX_TASK_NAME_LEN ) + { + cIdleName[ xIdleTaskNameIndex + 1 ] = '\0'; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* if ( configNUMBER_OF_CORES > 1 ) */ + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t * pxIdleTaskTCBBuffer = NULL; + StackType_t * pxIdleTaskStackBuffer = NULL; + configSTACK_DEPTH_TYPE uxIdleTaskStackSize; + + /* The Idle task is created using user provided RAM - obtain the + * address of the RAM then create the idle task. */ + #if ( configNUMBER_OF_CORES == 1 ) + { + vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &uxIdleTaskStackSize ); + } + #else + { + if( xCoreID == 0 ) + { + vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &uxIdleTaskStackSize ); + } + else + { + vApplicationGetPassiveIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &uxIdleTaskStackSize, ( BaseType_t ) ( xCoreID - 1 ) ); + } + } + #endif /* if ( configNUMBER_OF_CORES == 1 ) */ + xIdleTaskHandles[ xCoreID ] = xTaskCreateStatic( pxIdleTaskFunction, + cIdleName, + uxIdleTaskStackSize, + ( void * ) NULL, + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + pxIdleTaskStackBuffer, + pxIdleTaskTCBBuffer ); + + if( xIdleTaskHandles[ xCoreID ] != NULL ) + { + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + { + /* The Idle task is being created using dynamically allocated RAM. */ + xReturn = xTaskCreate( pxIdleTaskFunction, + cIdleName, + configMINIMAL_STACK_SIZE, + ( void * ) NULL, + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + &xIdleTaskHandles[ xCoreID ] ); + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + /* Break the loop if any of the idle task is failed to be created. */ + if( xReturn == pdFAIL ) + { + break; + } + else + { + #if ( configNUMBER_OF_CORES == 1 ) + { + mtCOVERAGE_TEST_MARKER(); + } + #else + { + /* Assign idle task to each core before SMP scheduler is running. */ + xIdleTaskHandles[ xCoreID ]->xTaskRunState = xCoreID; + pxCurrentTCBs[ xCoreID ] = xIdleTaskHandles[ xCoreID ]; + } + #endif + } + } + + return xReturn; +} + +/*-----------------------------------------------------------*/ + +void vTaskStartScheduler( void ) +{ + BaseType_t xReturn; + + traceENTER_vTaskStartScheduler(); + + #if ( configUSE_CORE_AFFINITY == 1 ) && ( configNUMBER_OF_CORES > 1 ) + { + /* Sanity check that the UBaseType_t must have greater than or equal to + * the number of bits as confNUMBER_OF_CORES. */ + configASSERT( ( sizeof( UBaseType_t ) * taskBITS_PER_BYTE ) >= configNUMBER_OF_CORES ); + } + #endif /* #if ( configUSE_CORE_AFFINITY == 1 ) && ( configNUMBER_OF_CORES > 1 ) */ + + xReturn = prvCreateIdleTasks(); + + #if ( configUSE_TIMERS == 1 ) + { + if( xReturn == pdPASS ) + { + xReturn = xTimerCreateTimerTask(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TIMERS */ + + if( xReturn == pdPASS ) + { + /* freertos_tasks_c_additions_init() should only be called if the user + * definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is + * the only macro called by the function. */ + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + { + freertos_tasks_c_additions_init(); + } + #endif + + /* Interrupts are turned off here, to ensure a tick does not occur + * before or during the call to xPortStartScheduler(). The stacks of + * the created tasks contain a status word with interrupts switched on + * so interrupts will automatically get re-enabled when the first task + * starts to run. */ + portDISABLE_INTERRUPTS(); + + #if ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) + { + /* Switch C-Runtime's TLS Block to point to the TLS + * block specific to the task that will run first. */ + configSET_TLS_BLOCK( pxCurrentTCB->xTLSBlock ); + } + #endif + + xNextTaskUnblockTime = portMAX_DELAY; + xSchedulerRunning = pdTRUE; + xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; + + /* If configGENERATE_RUN_TIME_STATS is defined then the following + * macro must be defined to configure the timer/counter used to generate + * the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS + * is set to 0 and the following line fails to build then ensure you do not + * have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your + * FreeRTOSConfig.h file. */ + portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); + + traceTASK_SWITCHED_IN(); + + /* Setting up the timer tick is hardware specific and thus in the + * portable interface. */ + + /* The return value for xPortStartScheduler is not required + * hence using a void datatype. */ + ( void ) xPortStartScheduler(); + + /* In most cases, xPortStartScheduler() will not return. If it + * returns pdTRUE then there was not enough heap memory available + * to create either the Idle or the Timer task. If it returned + * pdFALSE, then the application called xTaskEndScheduler(). + * Most ports don't implement xTaskEndScheduler() as there is + * nothing to return to. */ + } + else + { + /* This line will only be reached if the kernel could not be started, + * because there was not enough FreeRTOS heap to create the idle task + * or the timer task. */ + configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); + } + + /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, + * meaning xIdleTaskHandles are not used anywhere else. */ + ( void ) xIdleTaskHandles; + + /* OpenOCD makes use of uxTopUsedPriority for thread debugging. Prevent uxTopUsedPriority + * from getting optimized out as it is no longer used by the kernel. */ + ( void ) uxTopUsedPriority; + + traceRETURN_vTaskStartScheduler(); +} +/*-----------------------------------------------------------*/ + +void vTaskEndScheduler( void ) +{ + traceENTER_vTaskEndScheduler(); + + #if ( INCLUDE_vTaskDelete == 1 ) + { + BaseType_t xCoreID; + + #if ( configUSE_TIMERS == 1 ) + { + /* Delete the timer task created by the kernel. */ + vTaskDelete( xTimerGetTimerDaemonTaskHandle() ); + } + #endif /* #if ( configUSE_TIMERS == 1 ) */ + + /* Delete Idle tasks created by the kernel.*/ + for( xCoreID = 0; xCoreID < ( BaseType_t ) configNUMBER_OF_CORES; xCoreID++ ) + { + vTaskDelete( xIdleTaskHandles[ xCoreID ] ); + } + + /* Idle task is responsible for reclaiming the resources of the tasks in + * xTasksWaitingTermination list. Since the idle task is now deleted and + * no longer going to run, we need to reclaim resources of all the tasks + * in the xTasksWaitingTermination list. */ + prvCheckTasksWaitingTermination(); + } + #endif /* #if ( INCLUDE_vTaskDelete == 1 ) */ + + /* Stop the scheduler interrupts and call the portable scheduler end + * routine so the original ISRs can be restored if necessary. The port + * layer must ensure interrupts enable bit is left in the correct state. */ + portDISABLE_INTERRUPTS(); + xSchedulerRunning = pdFALSE; + + /* This function must be called from a task and the application is + * responsible for deleting that task after the scheduler is stopped. */ + vPortEndScheduler(); + + traceRETURN_vTaskEndScheduler(); +} +/*----------------------------------------------------------*/ + +void vTaskSuspendAll( void ) +{ + traceENTER_vTaskSuspendAll(); + + #if ( configNUMBER_OF_CORES == 1 ) + { + /* A critical section is not required as the variable is of type + * BaseType_t. Please read Richard Barry's reply in the following link to a + * post in the FreeRTOS support forum before reporting this as a bug! - + * https://goo.gl/wu4acr */ + + /* portSOFTWARE_BARRIER() is only implemented for emulated/simulated ports that + * do not otherwise exhibit real time behaviour. */ + portSOFTWARE_BARRIER(); + + /* The scheduler is suspended if uxSchedulerSuspended is non-zero. An increment + * is used to allow calls to vTaskSuspendAll() to nest. */ + uxSchedulerSuspended = ( UBaseType_t ) ( uxSchedulerSuspended + 1U ); + + /* Enforces ordering for ports and optimised compilers that may otherwise place + * the above increment elsewhere. */ + portMEMORY_BARRIER(); + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + UBaseType_t ulState; + + /* This must only be called from within a task. */ + portASSERT_IF_IN_ISR(); + + if( xSchedulerRunning != pdFALSE ) + { + /* Writes to uxSchedulerSuspended must be protected by both the task AND ISR locks. + * We must disable interrupts before we grab the locks in the event that this task is + * interrupted and switches context before incrementing uxSchedulerSuspended. + * It is safe to re-enable interrupts after releasing the ISR lock and incrementing + * uxSchedulerSuspended since that will prevent context switches. */ + ulState = portSET_INTERRUPT_MASK(); + + /* This must never be called from inside a critical section. */ + configASSERT( portGET_CRITICAL_NESTING_COUNT() == 0 ); + + /* portSOFRWARE_BARRIER() is only implemented for emulated/simulated ports that + * do not otherwise exhibit real time behaviour. */ + portSOFTWARE_BARRIER(); + + portGET_TASK_LOCK(); + + /* uxSchedulerSuspended is increased after prvCheckForRunStateChange. The + * purpose is to prevent altering the variable when fromISR APIs are readying + * it. */ + if( uxSchedulerSuspended == 0U ) + { + prvCheckForRunStateChange(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + portGET_ISR_LOCK(); + + /* The scheduler is suspended if uxSchedulerSuspended is non-zero. An increment + * is used to allow calls to vTaskSuspendAll() to nest. */ + ++uxSchedulerSuspended; + portRELEASE_ISR_LOCK(); + + portCLEAR_INTERRUPT_MASK( ulState ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + + traceRETURN_vTaskSuspendAll(); +} + +/*----------------------------------------------------------*/ + +#if ( configUSE_TICKLESS_IDLE != 0 ) + + static TickType_t prvGetExpectedIdleTime( void ) + { + TickType_t xReturn; + UBaseType_t uxHigherPriorityReadyTasks = pdFALSE; + + /* uxHigherPriorityReadyTasks takes care of the case where + * configUSE_PREEMPTION is 0, so there may be tasks above the idle priority + * task that are in the Ready state, even though the idle task is + * running. */ + #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) + { + if( uxTopReadyPriority > tskIDLE_PRIORITY ) + { + uxHigherPriorityReadyTasks = pdTRUE; + } + } + #else + { + const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01; + + /* When port optimised task selection is used the uxTopReadyPriority + * variable is used as a bit map. If bits other than the least + * significant bit are set then there are tasks that have a priority + * above the idle priority that are in the Ready state. This takes + * care of the case where the co-operative scheduler is in use. */ + if( uxTopReadyPriority > uxLeastSignificantBit ) + { + uxHigherPriorityReadyTasks = pdTRUE; + } + } + #endif /* if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) */ + + if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) + { + xReturn = 0; + } + else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1U ) + { + /* There are other idle priority tasks in the ready state. If + * time slicing is used then the very next tick interrupt must be + * processed. */ + xReturn = 0; + } + else if( uxHigherPriorityReadyTasks != pdFALSE ) + { + /* There are tasks in the Ready state that have a priority above the + * idle priority. This path can only be reached if + * configUSE_PREEMPTION is 0. */ + xReturn = 0; + } + else + { + xReturn = xNextTaskUnblockTime; + xReturn -= xTickCount; + } + + return xReturn; + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskResumeAll( void ) +{ + TCB_t * pxTCB = NULL; + BaseType_t xAlreadyYielded = pdFALSE; + + traceENTER_xTaskResumeAll(); + + #if ( configNUMBER_OF_CORES > 1 ) + if( xSchedulerRunning != pdFALSE ) + #endif + { + /* It is possible that an ISR caused a task to be removed from an event + * list while the scheduler was suspended. If this was the case then the + * removed task will have been added to the xPendingReadyList. Once the + * scheduler has been resumed it is safe to move all the pending ready + * tasks from this list into their appropriate ready list. */ + taskENTER_CRITICAL(); + { + BaseType_t xCoreID; + xCoreID = ( BaseType_t ) portGET_CORE_ID(); + + /* If uxSchedulerSuspended is zero then this function does not match a + * previous call to vTaskSuspendAll(). */ + configASSERT( uxSchedulerSuspended != 0U ); + + uxSchedulerSuspended = ( UBaseType_t ) ( uxSchedulerSuspended - 1U ); + portRELEASE_TASK_LOCK(); + + if( uxSchedulerSuspended == ( UBaseType_t ) 0U ) + { + if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U ) + { + /* Move any readied tasks from the pending list into the + * appropriate ready list. */ + while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) + { + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); + listREMOVE_ITEM( &( pxTCB->xEventListItem ) ); + portMEMORY_BARRIER(); + listREMOVE_ITEM( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + + #if ( configNUMBER_OF_CORES == 1 ) + { + /* If the moved task has a priority higher than the current + * task then a yield must be performed. */ + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + xYieldPendings[ xCoreID ] = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + /* All appropriate tasks yield at the moment a task is added to xPendingReadyList. + * If the current core yielded then vTaskSwitchContext() has already been called + * which sets xYieldPendings for the current core to pdTRUE. */ + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + } + + if( pxTCB != NULL ) + { + /* A task was unblocked while the scheduler was suspended, + * which may have prevented the next unblock time from being + * re-calculated, in which case re-calculate it now. Mainly + * important for low power tickless implementations, where + * this can prevent an unnecessary exit from low power + * state. */ + prvResetNextTaskUnblockTime(); + } + + /* If any ticks occurred while the scheduler was suspended then + * they should be processed now. This ensures the tick count does + * not slip, and that any delayed tasks are resumed at the correct + * time. + * + * It should be safe to call xTaskIncrementTick here from any core + * since we are in a critical section and xTaskIncrementTick itself + * protects itself within a critical section. Suspending the scheduler + * from any core causes xTaskIncrementTick to increment uxPendedCounts. */ + { + TickType_t xPendedCounts = xPendedTicks; /* Non-volatile copy. */ + + if( xPendedCounts > ( TickType_t ) 0U ) + { + do + { + if( xTaskIncrementTick() != pdFALSE ) + { + /* Other cores are interrupted from + * within xTaskIncrementTick(). */ + xYieldPendings[ xCoreID ] = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --xPendedCounts; + } while( xPendedCounts > ( TickType_t ) 0U ); + + xPendedTicks = 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + if( xYieldPendings[ xCoreID ] != pdFALSE ) + { + #if ( configUSE_PREEMPTION != 0 ) + { + xAlreadyYielded = pdTRUE; + } + #endif /* #if ( configUSE_PREEMPTION != 0 ) */ + + #if ( configNUMBER_OF_CORES == 1 ) + { + taskYIELD_TASK_CORE_IF_USING_PREEMPTION( pxCurrentTCB ); + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } + + traceRETURN_xTaskResumeAll( xAlreadyYielded ); + + return xAlreadyYielded; +} +/*-----------------------------------------------------------*/ + +TickType_t xTaskGetTickCount( void ) +{ + TickType_t xTicks; + + traceENTER_xTaskGetTickCount(); + + /* Critical section required if running on a 16 bit processor. */ + portTICK_TYPE_ENTER_CRITICAL(); + { + xTicks = xTickCount; + } + portTICK_TYPE_EXIT_CRITICAL(); + + traceRETURN_xTaskGetTickCount( xTicks ); + + return xTicks; +} +/*-----------------------------------------------------------*/ + +TickType_t xTaskGetTickCountFromISR( void ) +{ + TickType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + + traceENTER_xTaskGetTickCountFromISR(); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR(); + { + xReturn = xTickCount; + } + portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xTaskGetTickCountFromISR( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxTaskGetNumberOfTasks( void ) +{ + traceENTER_uxTaskGetNumberOfTasks(); + + /* A critical section is not required because the variables are of type + * BaseType_t. */ + traceRETURN_uxTaskGetNumberOfTasks( uxCurrentNumberOfTasks ); + + return uxCurrentNumberOfTasks; +} +/*-----------------------------------------------------------*/ + +char * pcTaskGetName( TaskHandle_t xTaskToQuery ) +{ + TCB_t * pxTCB; + + traceENTER_pcTaskGetName( xTaskToQuery ); + + /* If null is passed in here then the name of the calling task is being + * queried. */ + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + configASSERT( pxTCB ); + + traceRETURN_pcTaskGetName( &( pxTCB->pcTaskName[ 0 ] ) ); + + return &( pxTCB->pcTaskName[ 0 ] ); +} +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskGetHandle == 1 ) + static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList, + const char pcNameToQuery[] ) + { + TCB_t * pxReturn = NULL; + TCB_t * pxTCB = NULL; + UBaseType_t x; + char cNextChar; + BaseType_t xBreakLoop; + const ListItem_t * pxEndMarker = listGET_END_MARKER( pxList ); + ListItem_t * pxIterator; + + /* This function is called with the scheduler suspended. */ + + if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) + { + for( pxIterator = listGET_HEAD_ENTRY( pxList ); pxIterator != pxEndMarker; pxIterator = listGET_NEXT( pxIterator ) ) + { + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxTCB = listGET_LIST_ITEM_OWNER( pxIterator ); + + /* Check each character in the name looking for a match or + * mismatch. */ + xBreakLoop = pdFALSE; + + for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) + { + cNextChar = pxTCB->pcTaskName[ x ]; + + if( cNextChar != pcNameToQuery[ x ] ) + { + /* Characters didn't match. */ + xBreakLoop = pdTRUE; + } + else if( cNextChar == ( char ) 0x00 ) + { + /* Both strings terminated, a match must have been + * found. */ + pxReturn = pxTCB; + xBreakLoop = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xBreakLoop != pdFALSE ) + { + break; + } + } + + if( pxReturn != NULL ) + { + /* The handle has been found. */ + break; + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return pxReturn; + } + +#endif /* INCLUDE_xTaskGetHandle */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskGetHandle == 1 ) + + TaskHandle_t xTaskGetHandle( const char * pcNameToQuery ) + { + UBaseType_t uxQueue = configMAX_PRIORITIES; + TCB_t * pxTCB; + + traceENTER_xTaskGetHandle( pcNameToQuery ); + + /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */ + configASSERT( strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN ); + + vTaskSuspendAll(); + { + /* Search the ready lists. */ + do + { + uxQueue--; + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery ); + + if( pxTCB != NULL ) + { + /* Found the handle. */ + break; + } + } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); + + /* Search the delayed lists. */ + if( pxTCB == NULL ) + { + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery ); + } + + if( pxTCB == NULL ) + { + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery ); + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + if( pxTCB == NULL ) + { + /* Search the suspended list. */ + pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery ); + } + } + #endif + + #if ( INCLUDE_vTaskDelete == 1 ) + { + if( pxTCB == NULL ) + { + /* Search the deleted list. */ + pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery ); + } + } + #endif + } + ( void ) xTaskResumeAll(); + + traceRETURN_xTaskGetHandle( pxTCB ); + + return pxTCB; + } + +#endif /* INCLUDE_xTaskGetHandle */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + BaseType_t xTaskGetStaticBuffers( TaskHandle_t xTask, + StackType_t ** ppuxStackBuffer, + StaticTask_t ** ppxTaskBuffer ) + { + BaseType_t xReturn; + TCB_t * pxTCB; + + traceENTER_xTaskGetStaticBuffers( xTask, ppuxStackBuffer, ppxTaskBuffer ); + + configASSERT( ppuxStackBuffer != NULL ); + configASSERT( ppxTaskBuffer != NULL ); + + pxTCB = prvGetTCBFromHandle( xTask ); + + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE == 1 ) + { + if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ) + { + *ppuxStackBuffer = pxTCB->pxStack; + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + *ppxTaskBuffer = ( StaticTask_t * ) pxTCB; + xReturn = pdTRUE; + } + else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) + { + *ppuxStackBuffer = pxTCB->pxStack; + *ppxTaskBuffer = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + #else /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE == 1 */ + { + *ppuxStackBuffer = pxTCB->pxStack; + *ppxTaskBuffer = ( StaticTask_t * ) pxTCB; + xReturn = pdTRUE; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE == 1 */ + + traceRETURN_xTaskGetStaticBuffers( xReturn ); + + return xReturn; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, + const UBaseType_t uxArraySize, + configRUN_TIME_COUNTER_TYPE * const pulTotalRunTime ) + { + UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES; + + traceENTER_uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, pulTotalRunTime ); + + vTaskSuspendAll(); + { + /* Is there a space in the array for each task in the system? */ + if( uxArraySize >= uxCurrentNumberOfTasks ) + { + /* Fill in an TaskStatus_t structure with information on each + * task in the Ready state. */ + do + { + uxQueue--; + uxTask = ( UBaseType_t ) ( uxTask + prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady ) ); + } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); + + /* Fill in an TaskStatus_t structure with information on each + * task in the Blocked state. */ + uxTask = ( UBaseType_t ) ( uxTask + prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked ) ); + uxTask = ( UBaseType_t ) ( uxTask + prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked ) ); + + #if ( INCLUDE_vTaskDelete == 1 ) + { + /* Fill in an TaskStatus_t structure with information on + * each task that has been deleted but not yet cleaned up. */ + uxTask = ( UBaseType_t ) ( uxTask + prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted ) ); + } + #endif + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + /* Fill in an TaskStatus_t structure with information on + * each task in the Suspended state. */ + uxTask = ( UBaseType_t ) ( uxTask + prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended ) ); + } + #endif + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + if( pulTotalRunTime != NULL ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) ); + #else + *pulTotalRunTime = ( configRUN_TIME_COUNTER_TYPE ) portGET_RUN_TIME_COUNTER_VALUE(); + #endif + } + } + #else /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */ + { + if( pulTotalRunTime != NULL ) + { + *pulTotalRunTime = 0; + } + } + #endif /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); + + traceRETURN_uxTaskGetSystemState( uxTask ); + + return uxTask; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) + + #if ( configNUMBER_OF_CORES == 1 ) + TaskHandle_t xTaskGetIdleTaskHandle( void ) + { + traceENTER_xTaskGetIdleTaskHandle(); + + /* If xTaskGetIdleTaskHandle() is called before the scheduler has been + * started, then xIdleTaskHandles will be NULL. */ + configASSERT( ( xIdleTaskHandles[ 0 ] != NULL ) ); + + traceRETURN_xTaskGetIdleTaskHandle( xIdleTaskHandles[ 0 ] ); + + return xIdleTaskHandles[ 0 ]; + } + #endif /* if ( configNUMBER_OF_CORES == 1 ) */ + + TaskHandle_t xTaskGetIdleTaskHandleForCore( BaseType_t xCoreID ) + { + traceENTER_xTaskGetIdleTaskHandleForCore( xCoreID ); + + /* Ensure the core ID is valid. */ + configASSERT( taskVALID_CORE_ID( xCoreID ) == pdTRUE ); + + /* If xTaskGetIdleTaskHandle() is called before the scheduler has been + * started, then xIdleTaskHandles will be NULL. */ + configASSERT( ( xIdleTaskHandles[ xCoreID ] != NULL ) ); + + traceRETURN_xTaskGetIdleTaskHandleForCore( xIdleTaskHandles[ xCoreID ] ); + + return xIdleTaskHandles[ xCoreID ]; + } + +#endif /* INCLUDE_xTaskGetIdleTaskHandle */ +/*----------------------------------------------------------*/ + +/* This conditional compilation should use inequality to 0, not equality to 1. + * This is to ensure vTaskStepTick() is available when user defined low power mode + * implementations require configUSE_TICKLESS_IDLE to be set to a value other than + * 1. */ +#if ( configUSE_TICKLESS_IDLE != 0 ) + + void vTaskStepTick( TickType_t xTicksToJump ) + { + TickType_t xUpdatedTickCount; + + traceENTER_vTaskStepTick( xTicksToJump ); + + /* Correct the tick count value after a period during which the tick + * was suppressed. Note this does *not* call the tick hook function for + * each stepped tick. */ + xUpdatedTickCount = xTickCount + xTicksToJump; + configASSERT( xUpdatedTickCount <= xNextTaskUnblockTime ); + + if( xUpdatedTickCount == xNextTaskUnblockTime ) + { + /* Arrange for xTickCount to reach xNextTaskUnblockTime in + * xTaskIncrementTick() when the scheduler resumes. This ensures + * that any delayed tasks are resumed at the correct time. */ + configASSERT( uxSchedulerSuspended != ( UBaseType_t ) 0U ); + configASSERT( xTicksToJump != ( TickType_t ) 0 ); + + /* Prevent the tick interrupt modifying xPendedTicks simultaneously. */ + taskENTER_CRITICAL(); + { + xPendedTicks++; + } + taskEXIT_CRITICAL(); + xTicksToJump--; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xTickCount += xTicksToJump; + + traceINCREASE_TICK_COUNT( xTicksToJump ); + traceRETURN_vTaskStepTick(); + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) +{ + BaseType_t xYieldOccurred; + + traceENTER_xTaskCatchUpTicks( xTicksToCatchUp ); + + /* Must not be called with the scheduler suspended as the implementation + * relies on xPendedTicks being wound down to 0 in xTaskResumeAll(). */ + configASSERT( uxSchedulerSuspended == ( UBaseType_t ) 0U ); + + /* Use xPendedTicks to mimic xTicksToCatchUp number of ticks occurring when + * the scheduler is suspended so the ticks are executed in xTaskResumeAll(). */ + vTaskSuspendAll(); + + /* Prevent the tick interrupt modifying xPendedTicks simultaneously. */ + taskENTER_CRITICAL(); + { + xPendedTicks += xTicksToCatchUp; + } + taskEXIT_CRITICAL(); + xYieldOccurred = xTaskResumeAll(); + + traceRETURN_xTaskCatchUpTicks( xYieldOccurred ); + + return xYieldOccurred; +} +/*----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskAbortDelay == 1 ) + + BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) + { + TCB_t * pxTCB = xTask; + BaseType_t xReturn; + + traceENTER_xTaskAbortDelay( xTask ); + + configASSERT( pxTCB ); + + vTaskSuspendAll(); + { + /* A task can only be prematurely removed from the Blocked state if + * it is actually in the Blocked state. */ + if( eTaskGetState( xTask ) == eBlocked ) + { + xReturn = pdPASS; + + /* Remove the reference to the task from the blocked list. An + * interrupt won't touch the xStateListItem because the + * scheduler is suspended. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + + /* Is the task waiting on an event also? If so remove it from + * the event list too. Interrupts can touch the event list item, + * even though the scheduler is suspended, so a critical section + * is used. */ + taskENTER_CRITICAL(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + + /* This lets the task know it was forcibly removed from the + * blocked state so it should not re-evaluate its block time and + * then block again. */ + pxTCB->ucDelayAborted = ( uint8_t ) pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + /* Place the unblocked task into the appropriate ready list. */ + prvAddTaskToReadyList( pxTCB ); + + /* A task being unblocked cannot cause an immediate context + * switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + #if ( configNUMBER_OF_CORES == 1 ) + { + /* Preemption is on, but a context switch should only be + * performed if the unblocked task has a priority that is + * higher than the currently executing task. */ + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* Pend the yield to be performed when the scheduler + * is unsuspended. */ + xYieldPendings[ 0 ] = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + taskENTER_CRITICAL(); + { + prvYieldForTask( pxTCB ); + } + taskEXIT_CRITICAL(); + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + } + #endif /* #if ( configUSE_PREEMPTION == 1 ) */ + } + else + { + xReturn = pdFAIL; + } + } + ( void ) xTaskResumeAll(); + + traceRETURN_xTaskAbortDelay( xReturn ); + + return xReturn; + } + +#endif /* INCLUDE_xTaskAbortDelay */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskIncrementTick( void ) +{ + TCB_t * pxTCB; + TickType_t xItemValue; + BaseType_t xSwitchRequired = pdFALSE; + + #if ( configUSE_PREEMPTION == 1 ) && ( configNUMBER_OF_CORES > 1 ) + BaseType_t xYieldRequiredForCore[ configNUMBER_OF_CORES ] = { pdFALSE }; + #endif /* #if ( configUSE_PREEMPTION == 1 ) && ( configNUMBER_OF_CORES > 1 ) */ + + traceENTER_xTaskIncrementTick(); + + /* Called by the portable layer each time a tick interrupt occurs. + * Increments the tick then checks to see if the new tick value will cause any + * tasks to be unblocked. */ + traceTASK_INCREMENT_TICK( xTickCount ); + + /* Tick increment should occur on every kernel timer event. Core 0 has the + * responsibility to increment the tick, or increment the pended ticks if the + * scheduler is suspended. If pended ticks is greater than zero, the core that + * calls xTaskResumeAll has the responsibility to increment the tick. */ + if( uxSchedulerSuspended == ( UBaseType_t ) 0U ) + { + /* Minor optimisation. The tick count cannot change in this + * block. */ + const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1; + + /* Increment the RTOS tick, switching the delayed and overflowed + * delayed lists if it wraps to 0. */ + xTickCount = xConstTickCount; + + if( xConstTickCount == ( TickType_t ) 0U ) + { + taskSWITCH_DELAYED_LISTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* See if this tick has made a timeout expire. Tasks are stored in + * the queue in the order of their wake time - meaning once one task + * has been found whose block time has not expired there is no need to + * look any further down the list. */ + if( xConstTickCount >= xNextTaskUnblockTime ) + { + for( ; ; ) + { + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The delayed list is empty. Set xNextTaskUnblockTime + * to the maximum possible value so it is extremely + * unlikely that the + * if( xTickCount >= xNextTaskUnblockTime ) test will pass + * next time through. */ + xNextTaskUnblockTime = portMAX_DELAY; + break; + } + else + { + /* The delayed list is not empty, get the value of the + * item at the head of the delayed list. This is the time + * at which the task at the head of the delayed list must + * be removed from the Blocked state. */ + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); + xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); + + if( xConstTickCount < xItemValue ) + { + /* It is not time to unblock this item yet, but the + * item value is the time at which the task at the head + * of the blocked list must be removed from the Blocked + * state - so record the item value in + * xNextTaskUnblockTime. */ + xNextTaskUnblockTime = xItemValue; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* It is time to remove the item from the Blocked state. */ + listREMOVE_ITEM( &( pxTCB->xStateListItem ) ); + + /* Is the task waiting on an event also? If so remove + * it from the event list. */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + listREMOVE_ITEM( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Place the unblocked task into the appropriate ready + * list. */ + prvAddTaskToReadyList( pxTCB ); + + /* A task being unblocked cannot cause an immediate + * context switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + #if ( configNUMBER_OF_CORES == 1 ) + { + /* Preemption is on, but a context switch should + * only be performed if the unblocked task's + * priority is higher than the currently executing + * task. + * The case of equal priority tasks sharing + * processing time (which happens when both + * preemption and time slicing are on) is + * handled below.*/ + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else /* #if( configNUMBER_OF_CORES == 1 ) */ + { + prvYieldForTask( pxTCB ); + } + #endif /* #if( configNUMBER_OF_CORES == 1 ) */ + } + #endif /* #if ( configUSE_PREEMPTION == 1 ) */ + } + } + } + + /* Tasks of equal priority to the currently running task will share + * processing time (time slice) if preemption is on, and the application + * writer has not explicitly turned time slicing off. */ + #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) + { + #if ( configNUMBER_OF_CORES == 1 ) + { + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > 1U ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + BaseType_t xCoreID; + + for( xCoreID = 0; xCoreID < ( ( BaseType_t ) configNUMBER_OF_CORES ); xCoreID++ ) + { + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCBs[ xCoreID ]->uxPriority ] ) ) > 1U ) + { + xYieldRequiredForCore[ xCoreID ] = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + } + #endif /* #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */ + + #if ( configUSE_TICK_HOOK == 1 ) + { + /* Guard against the tick hook being called when the pended tick + * count is being unwound (when the scheduler is being unlocked). */ + if( xPendedTicks == ( TickType_t ) 0 ) + { + vApplicationTickHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICK_HOOK */ + + #if ( configUSE_PREEMPTION == 1 ) + { + #if ( configNUMBER_OF_CORES == 1 ) + { + /* For single core the core ID is always 0. */ + if( xYieldPendings[ 0 ] != pdFALSE ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + BaseType_t xCoreID, xCurrentCoreID; + xCurrentCoreID = ( BaseType_t ) portGET_CORE_ID(); + + for( xCoreID = 0; xCoreID < ( BaseType_t ) configNUMBER_OF_CORES; xCoreID++ ) + { + #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 ) + if( pxCurrentTCBs[ xCoreID ]->xPreemptionDisable == pdFALSE ) + #endif + { + if( ( xYieldRequiredForCore[ xCoreID ] != pdFALSE ) || ( xYieldPendings[ xCoreID ] != pdFALSE ) ) + { + if( xCoreID == xCurrentCoreID ) + { + xSwitchRequired = pdTRUE; + } + else + { + prvYieldCore( xCoreID ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + } + #endif /* #if ( configUSE_PREEMPTION == 1 ) */ + } + else + { + xPendedTicks += 1U; + + /* The tick hook gets called at regular intervals, even if the + * scheduler is locked. */ + #if ( configUSE_TICK_HOOK == 1 ) + { + vApplicationTickHook(); + } + #endif + } + + traceRETURN_xTaskIncrementTick( xSwitchRequired ); + + return xSwitchRequired; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + void vTaskSetApplicationTaskTag( TaskHandle_t xTask, + TaskHookFunction_t pxHookFunction ) + { + TCB_t * xTCB; + + traceENTER_vTaskSetApplicationTaskTag( xTask, pxHookFunction ); + + /* If xTask is NULL then it is the task hook of the calling task that is + * getting set. */ + if( xTask == NULL ) + { + xTCB = ( TCB_t * ) pxCurrentTCB; + } + else + { + xTCB = xTask; + } + + /* Save the hook function in the TCB. A critical section is required as + * the value can be accessed from an interrupt. */ + taskENTER_CRITICAL(); + { + xTCB->pxTaskTag = pxHookFunction; + } + taskEXIT_CRITICAL(); + + traceRETURN_vTaskSetApplicationTaskTag(); + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) + { + TCB_t * pxTCB; + TaskHookFunction_t xReturn; + + traceENTER_xTaskGetApplicationTaskTag( xTask ); + + /* If xTask is NULL then set the calling task's hook. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + /* Save the hook function in the TCB. A critical section is required as + * the value can be accessed from an interrupt. */ + taskENTER_CRITICAL(); + { + xReturn = pxTCB->pxTaskTag; + } + taskEXIT_CRITICAL(); + + traceRETURN_xTaskGetApplicationTaskTag( xReturn ); + + return xReturn; + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) + { + TCB_t * pxTCB; + TaskHookFunction_t xReturn; + UBaseType_t uxSavedInterruptStatus; + + traceENTER_xTaskGetApplicationTaskTagFromISR( xTask ); + + /* If xTask is NULL then set the calling task's hook. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + /* Save the hook function in the TCB. A critical section is required as + * the value can be accessed from an interrupt. */ + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); + { + xReturn = pxTCB->pxTaskTag; + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xTaskGetApplicationTaskTagFromISR( xReturn ); + + return xReturn; + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, + void * pvParameter ) + { + TCB_t * xTCB; + BaseType_t xReturn; + + traceENTER_xTaskCallApplicationTaskHook( xTask, pvParameter ); + + /* If xTask is NULL then we are calling our own task hook. */ + if( xTask == NULL ) + { + xTCB = pxCurrentTCB; + } + else + { + xTCB = xTask; + } + + if( xTCB->pxTaskTag != NULL ) + { + xReturn = xTCB->pxTaskTag( pvParameter ); + } + else + { + xReturn = pdFAIL; + } + + traceRETURN_xTaskCallApplicationTaskHook( xReturn ); + + return xReturn; + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +#if ( configNUMBER_OF_CORES == 1 ) + void vTaskSwitchContext( void ) + { + traceENTER_vTaskSwitchContext(); + + if( uxSchedulerSuspended != ( UBaseType_t ) 0U ) + { + /* The scheduler is currently suspended - do not allow a context + * switch. */ + xYieldPendings[ 0 ] = pdTRUE; + } + else + { + xYieldPendings[ 0 ] = pdFALSE; + traceTASK_SWITCHED_OUT(); + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime[ 0 ] ); + #else + ulTotalRunTime[ 0 ] = portGET_RUN_TIME_COUNTER_VALUE(); + #endif + + /* Add the amount of time the task has been running to the + * accumulated time so far. The time the task started running was + * stored in ulTaskSwitchedInTime. Note that there is no overflow + * protection here so count values are only valid until the timer + * overflows. The guard against negative values is to protect + * against suspect run time stat counter implementations - which + * are provided by the application, not the kernel. */ + if( ulTotalRunTime[ 0 ] > ulTaskSwitchedInTime[ 0 ] ) + { + pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime[ 0 ] - ulTaskSwitchedInTime[ 0 ] ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + ulTaskSwitchedInTime[ 0 ] = ulTotalRunTime[ 0 ]; + } + #endif /* configGENERATE_RUN_TIME_STATS */ + + /* Check for stack overflow, if configured. */ + taskCHECK_FOR_STACK_OVERFLOW(); + + /* Before the currently running task is switched out, save its errno. */ + #if ( configUSE_POSIX_ERRNO == 1 ) + { + pxCurrentTCB->iTaskErrno = FreeRTOS_errno; + } + #endif + + /* Select a new task to run using either the generic C or port + * optimised asm code. */ + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + taskSELECT_HIGHEST_PRIORITY_TASK(); + traceTASK_SWITCHED_IN(); + + /* Macro to inject port specific behaviour immediately after + * switching tasks, such as setting an end of stack watchpoint + * or reconfiguring the MPU. */ + portTASK_SWITCH_HOOK( pxCurrentTCB ); + + /* After the new task is switched in, update the global errno. */ + #if ( configUSE_POSIX_ERRNO == 1 ) + { + FreeRTOS_errno = pxCurrentTCB->iTaskErrno; + } + #endif + + #if ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) + { + /* Switch C-Runtime's TLS Block to point to the TLS + * Block specific to this task. */ + configSET_TLS_BLOCK( pxCurrentTCB->xTLSBlock ); + } + #endif + } + + traceRETURN_vTaskSwitchContext(); + } +#else /* if ( configNUMBER_OF_CORES == 1 ) */ + void vTaskSwitchContext( BaseType_t xCoreID ) + { + traceENTER_vTaskSwitchContext(); + + /* Acquire both locks: + * - The ISR lock protects the ready list from simultaneous access by + * both other ISRs and tasks. + * - We also take the task lock to pause here in case another core has + * suspended the scheduler. We don't want to simply set xYieldPending + * and move on if another core suspended the scheduler. We should only + * do that if the current core has suspended the scheduler. */ + + portGET_TASK_LOCK(); /* Must always acquire the task lock first. */ + portGET_ISR_LOCK(); + { + /* vTaskSwitchContext() must never be called from within a critical section. + * This is not necessarily true for single core FreeRTOS, but it is for this + * SMP port. */ + configASSERT( portGET_CRITICAL_NESTING_COUNT() == 0 ); + + if( uxSchedulerSuspended != ( UBaseType_t ) 0U ) + { + /* The scheduler is currently suspended - do not allow a context + * switch. */ + xYieldPendings[ xCoreID ] = pdTRUE; + } + else + { + xYieldPendings[ xCoreID ] = pdFALSE; + traceTASK_SWITCHED_OUT(); + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime[ xCoreID ] ); + #else + ulTotalRunTime[ xCoreID ] = portGET_RUN_TIME_COUNTER_VALUE(); + #endif + + /* Add the amount of time the task has been running to the + * accumulated time so far. The time the task started running was + * stored in ulTaskSwitchedInTime. Note that there is no overflow + * protection here so count values are only valid until the timer + * overflows. The guard against negative values is to protect + * against suspect run time stat counter implementations - which + * are provided by the application, not the kernel. */ + if( ulTotalRunTime[ xCoreID ] > ulTaskSwitchedInTime[ xCoreID ] ) + { + pxCurrentTCBs[ xCoreID ]->ulRunTimeCounter += ( ulTotalRunTime[ xCoreID ] - ulTaskSwitchedInTime[ xCoreID ] ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + ulTaskSwitchedInTime[ xCoreID ] = ulTotalRunTime[ xCoreID ]; + } + #endif /* configGENERATE_RUN_TIME_STATS */ + + /* Check for stack overflow, if configured. */ + taskCHECK_FOR_STACK_OVERFLOW(); + + /* Before the currently running task is switched out, save its errno. */ + #if ( configUSE_POSIX_ERRNO == 1 ) + { + pxCurrentTCBs[ xCoreID ]->iTaskErrno = FreeRTOS_errno; + } + #endif + + /* Select a new task to run. */ + taskSELECT_HIGHEST_PRIORITY_TASK( xCoreID ); + traceTASK_SWITCHED_IN(); + + /* Macro to inject port specific behaviour immediately after + * switching tasks, such as setting an end of stack watchpoint + * or reconfiguring the MPU. */ + portTASK_SWITCH_HOOK( pxCurrentTCBs[ portGET_CORE_ID() ] ); + + /* After the new task is switched in, update the global errno. */ + #if ( configUSE_POSIX_ERRNO == 1 ) + { + FreeRTOS_errno = pxCurrentTCBs[ xCoreID ]->iTaskErrno; + } + #endif + + #if ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) + { + /* Switch C-Runtime's TLS Block to point to the TLS + * Block specific to this task. */ + configSET_TLS_BLOCK( pxCurrentTCBs[ xCoreID ]->xTLSBlock ); + } + #endif + } + } + portRELEASE_ISR_LOCK(); + portRELEASE_TASK_LOCK(); + + traceRETURN_vTaskSwitchContext(); + } +#endif /* if ( configNUMBER_OF_CORES > 1 ) */ +/*-----------------------------------------------------------*/ + +void vTaskPlaceOnEventList( List_t * const pxEventList, + const TickType_t xTicksToWait ) +{ + traceENTER_vTaskPlaceOnEventList( pxEventList, xTicksToWait ); + + configASSERT( pxEventList ); + + /* THIS FUNCTION MUST BE CALLED WITH THE + * SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */ + + /* Place the event list item of the TCB in the appropriate event list. + * This is placed in the list in priority order so the highest priority task + * is the first to be woken by the event. + * + * Note: Lists are sorted in ascending order by ListItem_t.xItemValue. + * Normally, the xItemValue of a TCB's ListItem_t members is: + * xItemValue = ( configMAX_PRIORITIES - uxPriority ) + * Therefore, the event list is sorted in descending priority order. + * + * The queue that contains the event list is locked, preventing + * simultaneous access from interrupts. */ + vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + + traceRETURN_vTaskPlaceOnEventList(); +} +/*-----------------------------------------------------------*/ + +void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, + const TickType_t xItemValue, + const TickType_t xTicksToWait ) +{ + traceENTER_vTaskPlaceOnUnorderedEventList( pxEventList, xItemValue, xTicksToWait ); + + configASSERT( pxEventList ); + + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by + * the event groups implementation. */ + configASSERT( uxSchedulerSuspended != ( UBaseType_t ) 0U ); + + /* Store the item value in the event list item. It is safe to access the + * event list item here as interrupts won't access the event list item of a + * task that is not in the Blocked state. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); + + /* Place the event list item of the TCB at the end of the appropriate event + * list. It is safe to access the event list here because it is part of an + * event group implementation - and interrupts don't access event groups + * directly (instead they access them indirectly by pending function calls to + * the task level). */ + listINSERT_END( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + + traceRETURN_vTaskPlaceOnUnorderedEventList(); +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TIMERS == 1 ) + + void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, + TickType_t xTicksToWait, + const BaseType_t xWaitIndefinitely ) + { + traceENTER_vTaskPlaceOnEventListRestricted( pxEventList, xTicksToWait, xWaitIndefinitely ); + + configASSERT( pxEventList ); + + /* This function should not be called by application code hence the + * 'Restricted' in its name. It is not part of the public API. It is + * designed for use by kernel code, and has special calling requirements - + * it should be called with the scheduler suspended. */ + + + /* Place the event list item of the TCB in the appropriate event list. + * In this case it is assume that this is the only task that is going to + * be waiting on this event list, so the faster vListInsertEnd() function + * can be used in place of vListInsert. */ + listINSERT_END( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + + /* If the task should block indefinitely then set the block time to a + * value that will be recognised as an indefinite delay inside the + * prvAddCurrentTaskToDelayedList() function. */ + if( xWaitIndefinitely != pdFALSE ) + { + xTicksToWait = portMAX_DELAY; + } + + traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) ); + prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely ); + + traceRETURN_vTaskPlaceOnEventListRestricted(); + } + +#endif /* configUSE_TIMERS */ +/*-----------------------------------------------------------*/ + +BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) +{ + TCB_t * pxUnblockedTCB; + BaseType_t xReturn; + + traceENTER_xTaskRemoveFromEventList( pxEventList ); + + /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be + * called from a critical section within an ISR. */ + + /* The event list is sorted in priority order, so the first in the list can + * be removed as it is known to be the highest priority. Remove the TCB from + * the delayed list, and add it to the ready list. + * + * If an event is for a queue that is locked then this function will never + * get called - the lock count on the queue will get modified instead. This + * means exclusive access to the event list is guaranteed here. + * + * This function assumes that a check has already been made to ensure that + * pxEventList is not empty. */ + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); + configASSERT( pxUnblockedTCB ); + listREMOVE_ITEM( &( pxUnblockedTCB->xEventListItem ) ); + + if( uxSchedulerSuspended == ( UBaseType_t ) 0U ) + { + listREMOVE_ITEM( &( pxUnblockedTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxUnblockedTCB ); + + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked on a kernel object then xNextTaskUnblockTime + * might be set to the blocked task's time out time. If the task is + * unblocked for a reason other than a timeout xNextTaskUnblockTime is + * normally left unchanged, because it is automatically reset to a new + * value when the tick count equals xNextTaskUnblockTime. However if + * tickless idling is used it might be more important to enter sleep mode + * at the earliest possible time - so reset xNextTaskUnblockTime here to + * ensure it is updated at the earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + } + else + { + /* The delayed and ready lists cannot be accessed, so hold this task + * pending until the scheduler is resumed. */ + listINSERT_END( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); + } + + #if ( configNUMBER_OF_CORES == 1 ) + { + if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* Return true if the task removed from the event list has a higher + * priority than the calling task. This allows the calling task to know if + * it should force a context switch now. */ + xReturn = pdTRUE; + + /* Mark that a yield is pending in case the user is not using the + * "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ + xYieldPendings[ 0 ] = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + xReturn = pdFALSE; + + #if ( configUSE_PREEMPTION == 1 ) + { + prvYieldForTask( pxUnblockedTCB ); + + if( xYieldPendings[ portGET_CORE_ID() ] != pdFALSE ) + { + xReturn = pdTRUE; + } + } + #endif /* #if ( configUSE_PREEMPTION == 1 ) */ + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + + traceRETURN_xTaskRemoveFromEventList( xReturn ); + return xReturn; +} +/*-----------------------------------------------------------*/ + +void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, + const TickType_t xItemValue ) +{ + TCB_t * pxUnblockedTCB; + + traceENTER_vTaskRemoveFromUnorderedEventList( pxEventListItem, xItemValue ); + + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by + * the event flags implementation. */ + configASSERT( uxSchedulerSuspended != ( UBaseType_t ) 0U ); + + /* Store the new item value in the event list. */ + listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); + + /* Remove the event list form the event flag. Interrupts do not access + * event flags. */ + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); + configASSERT( pxUnblockedTCB ); + listREMOVE_ITEM( pxEventListItem ); + + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked on a kernel object then xNextTaskUnblockTime + * might be set to the blocked task's time out time. If the task is + * unblocked for a reason other than a timeout xNextTaskUnblockTime is + * normally left unchanged, because it is automatically reset to a new + * value when the tick count equals xNextTaskUnblockTime. However if + * tickless idling is used it might be more important to enter sleep mode + * at the earliest possible time - so reset xNextTaskUnblockTime here to + * ensure it is updated at the earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + + /* Remove the task from the delayed list and add it to the ready list. The + * scheduler is suspended so interrupts will not be accessing the ready + * lists. */ + listREMOVE_ITEM( &( pxUnblockedTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxUnblockedTCB ); + + #if ( configNUMBER_OF_CORES == 1 ) + { + if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The unblocked task has a priority above that of the calling task, so + * a context switch is required. This function is called with the + * scheduler suspended so xYieldPending is set so the context switch + * occurs immediately that the scheduler is resumed (unsuspended). */ + xYieldPendings[ 0 ] = pdTRUE; + } + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + #if ( configUSE_PREEMPTION == 1 ) + { + taskENTER_CRITICAL(); + { + prvYieldForTask( pxUnblockedTCB ); + } + taskEXIT_CRITICAL(); + } + #endif + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + + traceRETURN_vTaskRemoveFromUnorderedEventList(); +} +/*-----------------------------------------------------------*/ + +void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) +{ + traceENTER_vTaskSetTimeOutState( pxTimeOut ); + + configASSERT( pxTimeOut ); + taskENTER_CRITICAL(); + { + pxTimeOut->xOverflowCount = xNumOfOverflows; + pxTimeOut->xTimeOnEntering = xTickCount; + } + taskEXIT_CRITICAL(); + + traceRETURN_vTaskSetTimeOutState(); +} +/*-----------------------------------------------------------*/ + +void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) +{ + traceENTER_vTaskInternalSetTimeOutState( pxTimeOut ); + + /* For internal use only as it does not use a critical section. */ + pxTimeOut->xOverflowCount = xNumOfOverflows; + pxTimeOut->xTimeOnEntering = xTickCount; + + traceRETURN_vTaskInternalSetTimeOutState(); +} +/*-----------------------------------------------------------*/ + +BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, + TickType_t * const pxTicksToWait ) +{ + BaseType_t xReturn; + + traceENTER_xTaskCheckForTimeOut( pxTimeOut, pxTicksToWait ); + + configASSERT( pxTimeOut ); + configASSERT( pxTicksToWait ); + + taskENTER_CRITICAL(); + { + /* Minor optimisation. The tick count cannot change in this block. */ + const TickType_t xConstTickCount = xTickCount; + const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE ) + { + /* The delay was aborted, which is not the same as a time out, + * but has the same result. */ + pxCurrentTCB->ucDelayAborted = ( uint8_t ) pdFALSE; + xReturn = pdTRUE; + } + else + #endif + + #if ( INCLUDE_vTaskSuspend == 1 ) + if( *pxTicksToWait == portMAX_DELAY ) + { + /* If INCLUDE_vTaskSuspend is set to 1 and the block time + * specified is the maximum block time then the task should block + * indefinitely, and therefore never time out. */ + xReturn = pdFALSE; + } + else + #endif + + if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) + { + /* The tick count is greater than the time at which + * vTaskSetTimeout() was called, but has also overflowed since + * vTaskSetTimeOut() was called. It must have wrapped all the way + * around and gone past again. This passed since vTaskSetTimeout() + * was called. */ + xReturn = pdTRUE; + *pxTicksToWait = ( TickType_t ) 0; + } + else if( xElapsedTime < *pxTicksToWait ) + { + /* Not a genuine timeout. Adjust parameters for time remaining. */ + *pxTicksToWait -= xElapsedTime; + vTaskInternalSetTimeOutState( pxTimeOut ); + xReturn = pdFALSE; + } + else + { + *pxTicksToWait = ( TickType_t ) 0; + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); + + traceRETURN_xTaskCheckForTimeOut( xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +void vTaskMissedYield( void ) +{ + traceENTER_vTaskMissedYield(); + + /* Must be called from within a critical section. */ + xYieldPendings[ portGET_CORE_ID() ] = pdTRUE; + + traceRETURN_vTaskMissedYield(); +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) + { + UBaseType_t uxReturn; + TCB_t const * pxTCB; + + traceENTER_uxTaskGetTaskNumber( xTask ); + + if( xTask != NULL ) + { + pxTCB = xTask; + uxReturn = pxTCB->uxTaskNumber; + } + else + { + uxReturn = 0U; + } + + traceRETURN_uxTaskGetTaskNumber( uxReturn ); + + return uxReturn; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vTaskSetTaskNumber( TaskHandle_t xTask, + const UBaseType_t uxHandle ) + { + TCB_t * pxTCB; + + traceENTER_vTaskSetTaskNumber( xTask, uxHandle ); + + if( xTask != NULL ) + { + pxTCB = xTask; + pxTCB->uxTaskNumber = uxHandle; + } + + traceRETURN_vTaskSetTaskNumber(); + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +/* + * ----------------------------------------------------------- + * The passive idle task. + * ---------------------------------------------------------- + * + * The passive idle task is used for all the additional cores in a SMP + * system. There must be only 1 active idle task and the rest are passive + * idle tasks. + * + * The portTASK_FUNCTION() macro is used to allow port/compiler specific + * language extensions. The equivalent prototype for this function is: + * + * void prvPassiveIdleTask( void *pvParameters ); + */ + +#if ( configNUMBER_OF_CORES > 1 ) + static portTASK_FUNCTION( prvPassiveIdleTask, pvParameters ) + { + ( void ) pvParameters; + + taskYIELD(); + + for( ; configCONTROL_INFINITE_LOOP(); ) + { + #if ( configUSE_PREEMPTION == 0 ) + { + /* If we are not using preemption we keep forcing a task switch to + * see if any other task has become available. If we are using + * preemption we don't need to do this as any task becoming available + * will automatically get the processor anyway. */ + taskYIELD(); + } + #endif /* configUSE_PREEMPTION */ + + #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) + { + /* When using preemption tasks of equal priority will be + * timesliced. If a task that is sharing the idle priority is ready + * to run then the idle task should yield before the end of the + * timeslice. + * + * A critical region is not required here as we are just reading from + * the list, and an occasional incorrect value will not matter. If + * the ready list at the idle priority contains one more task than the + * number of idle tasks, which is equal to the configured numbers of cores + * then a task other than the idle task is ready to execute. */ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) configNUMBER_OF_CORES ) + { + taskYIELD(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ + + #if ( configUSE_PASSIVE_IDLE_HOOK == 1 ) + { + /* Call the user defined function from within the idle task. This + * allows the application designer to add background functionality + * without the overhead of a separate task. + * + * This hook is intended to manage core activity such as disabling cores that go idle. + * + * NOTE: vApplicationPassiveIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, + * CALL A FUNCTION THAT MIGHT BLOCK. */ + vApplicationPassiveIdleHook(); + } + #endif /* configUSE_PASSIVE_IDLE_HOOK */ + } + } +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + +/* + * ----------------------------------------------------------- + * The idle task. + * ---------------------------------------------------------- + * + * The portTASK_FUNCTION() macro is used to allow port/compiler specific + * language extensions. The equivalent prototype for this function is: + * + * void prvIdleTask( void *pvParameters ); + * + */ + +static portTASK_FUNCTION( prvIdleTask, pvParameters ) +{ + /* Stop warnings. */ + ( void ) pvParameters; + + /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE + * SCHEDULER IS STARTED. **/ + + /* In case a task that has a secure context deletes itself, in which case + * the idle task is responsible for deleting the task's secure context, if + * any. */ + portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE ); + + #if ( configNUMBER_OF_CORES > 1 ) + { + /* SMP all cores start up in the idle task. This initial yield gets the application + * tasks started. */ + taskYIELD(); + } + #endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + + for( ; configCONTROL_INFINITE_LOOP(); ) + { + /* See if any tasks have deleted themselves - if so then the idle task + * is responsible for freeing the deleted task's TCB and stack. */ + prvCheckTasksWaitingTermination(); + + #if ( configUSE_PREEMPTION == 0 ) + { + /* If we are not using preemption we keep forcing a task switch to + * see if any other task has become available. If we are using + * preemption we don't need to do this as any task becoming available + * will automatically get the processor anyway. */ + taskYIELD(); + } + #endif /* configUSE_PREEMPTION */ + + #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) + { + /* When using preemption tasks of equal priority will be + * timesliced. If a task that is sharing the idle priority is ready + * to run then the idle task should yield before the end of the + * timeslice. + * + * A critical region is not required here as we are just reading from + * the list, and an occasional incorrect value will not matter. If + * the ready list at the idle priority contains one more task than the + * number of idle tasks, which is equal to the configured numbers of cores + * then a task other than the idle task is ready to execute. */ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) configNUMBER_OF_CORES ) + { + taskYIELD(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ + + #if ( configUSE_IDLE_HOOK == 1 ) + { + /* Call the user defined function from within the idle task. */ + vApplicationIdleHook(); + } + #endif /* configUSE_IDLE_HOOK */ + + /* This conditional compilation should use inequality to 0, not equality + * to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when + * user defined low power mode implementations require + * configUSE_TICKLESS_IDLE to be set to a value other than 1. */ + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + TickType_t xExpectedIdleTime; + + /* It is not desirable to suspend then resume the scheduler on + * each iteration of the idle task. Therefore, a preliminary + * test of the expected idle time is performed without the + * scheduler suspended. The result here is not necessarily + * valid. */ + xExpectedIdleTime = prvGetExpectedIdleTime(); + + if( xExpectedIdleTime >= ( TickType_t ) configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + vTaskSuspendAll(); + { + /* Now the scheduler is suspended, the expected idle + * time can be sampled again, and this time its value can + * be used. */ + configASSERT( xNextTaskUnblockTime >= xTickCount ); + xExpectedIdleTime = prvGetExpectedIdleTime(); + + /* Define the following macro to set xExpectedIdleTime to 0 + * if the application does not want + * portSUPPRESS_TICKS_AND_SLEEP() to be called. */ + configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); + + if( xExpectedIdleTime >= ( TickType_t ) configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + traceLOW_POWER_IDLE_BEGIN(); + portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); + traceLOW_POWER_IDLE_END(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICKLESS_IDLE */ + + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_PASSIVE_IDLE_HOOK == 1 ) ) + { + /* Call the user defined function from within the idle task. This + * allows the application designer to add background functionality + * without the overhead of a separate task. + * + * This hook is intended to manage core activity such as disabling cores that go idle. + * + * NOTE: vApplicationPassiveIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, + * CALL A FUNCTION THAT MIGHT BLOCK. */ + vApplicationPassiveIdleHook(); + } + #endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_PASSIVE_IDLE_HOOK == 1 ) ) */ + } +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TICKLESS_IDLE != 0 ) + + eSleepModeStatus eTaskConfirmSleepModeStatus( void ) + { + #if ( INCLUDE_vTaskSuspend == 1 ) + /* The idle task exists in addition to the application tasks. */ + const UBaseType_t uxNonApplicationTasks = configNUMBER_OF_CORES; + #endif /* INCLUDE_vTaskSuspend */ + + eSleepModeStatus eReturn = eStandardSleep; + + traceENTER_eTaskConfirmSleepModeStatus(); + + /* This function must be called from a critical section. */ + + if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0U ) + { + /* A task was made ready while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else if( xYieldPendings[ portGET_CORE_ID() ] != pdFALSE ) + { + /* A yield was pended while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else if( xPendedTicks != 0U ) + { + /* A tick interrupt has already occurred but was held pending + * because the scheduler is suspended. */ + eReturn = eAbortSleep; + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + else if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) + { + /* If all the tasks are in the suspended list (which might mean they + * have an infinite block time rather than actually being suspended) + * then it is safe to turn all clocks off and just wait for external + * interrupts. */ + eReturn = eNoTasksWaitingTimeout; + } + #endif /* INCLUDE_vTaskSuspend */ + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_eTaskConfirmSleepModeStatus( eReturn ); + + return eReturn; + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*-----------------------------------------------------------*/ + +#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, + BaseType_t xIndex, + void * pvValue ) + { + TCB_t * pxTCB; + + traceENTER_vTaskSetThreadLocalStoragePointer( xTaskToSet, xIndex, pvValue ); + + if( ( xIndex >= 0 ) && + ( xIndex < ( BaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS ) ) + { + pxTCB = prvGetTCBFromHandle( xTaskToSet ); + configASSERT( pxTCB != NULL ); + pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; + } + + traceRETURN_vTaskSetThreadLocalStoragePointer(); + } + +#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ +/*-----------------------------------------------------------*/ + +#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + + void * pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, + BaseType_t xIndex ) + { + void * pvReturn = NULL; + TCB_t * pxTCB; + + traceENTER_pvTaskGetThreadLocalStoragePointer( xTaskToQuery, xIndex ); + + if( ( xIndex >= 0 ) && + ( xIndex < ( BaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS ) ) + { + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; + } + else + { + pvReturn = NULL; + } + + traceRETURN_pvTaskGetThreadLocalStoragePointer( pvReturn ); + + return pvReturn; + } + +#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ +/*-----------------------------------------------------------*/ + +#if ( portUSING_MPU_WRAPPERS == 1 ) + + void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, + const MemoryRegion_t * const pxRegions ) + { + TCB_t * pxTCB; + + traceENTER_vTaskAllocateMPURegions( xTaskToModify, pxRegions ); + + /* If null is passed in here then we are modifying the MPU settings of + * the calling task. */ + pxTCB = prvGetTCBFromHandle( xTaskToModify ); + + vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), pxRegions, NULL, 0 ); + + traceRETURN_vTaskAllocateMPURegions(); + } + +#endif /* portUSING_MPU_WRAPPERS */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseTaskLists( void ) +{ + UBaseType_t uxPriority; + + for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) + { + vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); + } + + vListInitialise( &xDelayedTaskList1 ); + vListInitialise( &xDelayedTaskList2 ); + vListInitialise( &xPendingReadyList ); + + #if ( INCLUDE_vTaskDelete == 1 ) + { + vListInitialise( &xTasksWaitingTermination ); + } + #endif /* INCLUDE_vTaskDelete */ + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + vListInitialise( &xSuspendedTaskList ); + } + #endif /* INCLUDE_vTaskSuspend */ + + /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList + * using list2. */ + pxDelayedTaskList = &xDelayedTaskList1; + pxOverflowDelayedTaskList = &xDelayedTaskList2; +} +/*-----------------------------------------------------------*/ + +static void prvCheckTasksWaitingTermination( void ) +{ + /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ + + #if ( INCLUDE_vTaskDelete == 1 ) + { + TCB_t * pxTCB; + + /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL() + * being called too often in the idle task. */ + while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) + { + #if ( configNUMBER_OF_CORES == 1 ) + { + taskENTER_CRITICAL(); + { + { + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + --uxCurrentNumberOfTasks; + --uxDeletedTasksWaitingCleanUp; + } + } + taskEXIT_CRITICAL(); + + prvDeleteTCB( pxTCB ); + } + #else /* #if( configNUMBER_OF_CORES == 1 ) */ + { + pxTCB = NULL; + + taskENTER_CRITICAL(); + { + /* For SMP, multiple idles can be running simultaneously + * and we need to check that other idles did not cleanup while we were + * waiting to enter the critical section. */ + if( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) + { + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); + + if( pxTCB->xTaskRunState == taskTASK_NOT_RUNNING ) + { + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + --uxCurrentNumberOfTasks; + --uxDeletedTasksWaitingCleanUp; + } + else + { + /* The TCB to be deleted still has not yet been switched out + * by the scheduler, so we will just exit this loop early and + * try again next time. */ + taskEXIT_CRITICAL(); + break; + } + } + } + taskEXIT_CRITICAL(); + + if( pxTCB != NULL ) + { + prvDeleteTCB( pxTCB ); + } + } + #endif /* #if( configNUMBER_OF_CORES == 1 ) */ + } + } + #endif /* INCLUDE_vTaskDelete */ +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vTaskGetInfo( TaskHandle_t xTask, + TaskStatus_t * pxTaskStatus, + BaseType_t xGetFreeStackSpace, + eTaskState eState ) + { + TCB_t * pxTCB; + + traceENTER_vTaskGetInfo( xTask, pxTaskStatus, xGetFreeStackSpace, eState ); + + /* xTask is NULL then get the state of the calling task. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + pxTaskStatus->xHandle = pxTCB; + pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName[ 0 ] ); + pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; + pxTaskStatus->pxStackBase = pxTCB->pxStack; + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + pxTaskStatus->pxTopOfStack = ( StackType_t * ) pxTCB->pxTopOfStack; + pxTaskStatus->pxEndOfStack = pxTCB->pxEndOfStack; + #endif + pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; + + #if ( ( configUSE_CORE_AFFINITY == 1 ) && ( configNUMBER_OF_CORES > 1 ) ) + { + pxTaskStatus->uxCoreAffinityMask = pxTCB->uxCoreAffinityMask; + } + #endif + + #if ( configUSE_MUTEXES == 1 ) + { + pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; + } + #else + { + pxTaskStatus->uxBasePriority = 0; + } + #endif + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; + } + #else + { + pxTaskStatus->ulRunTimeCounter = ( configRUN_TIME_COUNTER_TYPE ) 0; + } + #endif + + /* Obtaining the task state is a little fiddly, so is only done if the + * value of eState passed into this function is eInvalid - otherwise the + * state is just set to whatever is passed in. */ + if( eState != eInvalid ) + { + if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE ) + { + pxTaskStatus->eCurrentState = eRunning; + } + else + { + pxTaskStatus->eCurrentState = eState; + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + /* If the task is in the suspended list then there is a + * chance it is actually just blocked indefinitely - so really + * it should be reported as being in the Blocked state. */ + if( eState == eSuspended ) + { + vTaskSuspendAll(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + pxTaskStatus->eCurrentState = eBlocked; + } + else + { + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + BaseType_t x; + + /* The task does not appear on the event list item of + * and of the RTOS objects, but could still be in the + * blocked state if it is waiting on its notification + * rather than waiting on an object. If not, is + * suspended. */ + for( x = ( BaseType_t ) 0; x < ( BaseType_t ) configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ ) + { + if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION ) + { + pxTaskStatus->eCurrentState = eBlocked; + break; + } + } + } + #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + } + } + ( void ) xTaskResumeAll(); + } + } + #endif /* INCLUDE_vTaskSuspend */ + + /* Tasks can be in pending ready list and other state list at the + * same time. These tasks are in ready state no matter what state + * list the task is in. */ + taskENTER_CRITICAL(); + { + if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) != pdFALSE ) + { + pxTaskStatus->eCurrentState = eReady; + } + } + taskEXIT_CRITICAL(); + } + } + else + { + pxTaskStatus->eCurrentState = eTaskGetState( pxTCB ); + } + + /* Obtaining the stack space takes some time, so the xGetFreeStackSpace + * parameter is provided to allow it to be skipped. */ + if( xGetFreeStackSpace != pdFALSE ) + { + #if ( portSTACK_GROWTH > 0 ) + { + pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack ); + } + #else + { + pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack ); + } + #endif + } + else + { + pxTaskStatus->usStackHighWaterMark = 0; + } + + traceRETURN_vTaskGetInfo(); + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray, + List_t * pxList, + eTaskState eState ) + { + UBaseType_t uxTask = 0; + const ListItem_t * pxEndMarker = listGET_END_MARKER( pxList ); + ListItem_t * pxIterator; + TCB_t * pxTCB = NULL; + + if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) + { + /* Populate an TaskStatus_t structure within the + * pxTaskStatusArray array for each task that is referenced from + * pxList. See the definition of TaskStatus_t in task.h for the + * meaning of each TaskStatus_t structure member. */ + for( pxIterator = listGET_HEAD_ENTRY( pxList ); pxIterator != pxEndMarker; pxIterator = listGET_NEXT( pxIterator ) ) + { + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxTCB = listGET_LIST_ITEM_OWNER( pxIterator ); + + vTaskGetInfo( ( TaskHandle_t ) pxTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState ); + uxTask++; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return uxTask; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) + + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) + { + configSTACK_DEPTH_TYPE uxCount = 0U; + + while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE ) + { + pucStackByte -= portSTACK_GROWTH; + uxCount++; + } + + uxCount /= ( configSTACK_DEPTH_TYPE ) sizeof( StackType_t ); + + return uxCount; + } + +#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) + +/* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + * same except for their return type. Using configSTACK_DEPTH_TYPE allows the + * user to determine the return type. It gets around the problem of the value + * overflowing on 8-bit types without breaking backward compatibility for + * applications that expect an 8-bit return type. */ + configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) + { + TCB_t * pxTCB; + uint8_t * pucEndOfStack; + configSTACK_DEPTH_TYPE uxReturn; + + traceENTER_uxTaskGetStackHighWaterMark2( xTask ); + + /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are + * the same except for their return type. Using configSTACK_DEPTH_TYPE + * allows the user to determine the return type. It gets around the + * problem of the value overflowing on 8-bit types without breaking + * backward compatibility for applications that expect an 8-bit return + * type. */ + + pxTCB = prvGetTCBFromHandle( xTask ); + + #if portSTACK_GROWTH < 0 + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; + } + #else + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; + } + #endif + + uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack ); + + traceRETURN_uxTaskGetStackHighWaterMark2( uxReturn ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskGetStackHighWaterMark2 */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) + + UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) + { + TCB_t * pxTCB; + uint8_t * pucEndOfStack; + UBaseType_t uxReturn; + + traceENTER_uxTaskGetStackHighWaterMark( xTask ); + + pxTCB = prvGetTCBFromHandle( xTask ); + + #if portSTACK_GROWTH < 0 + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; + } + #else + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; + } + #endif + + uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack ); + + traceRETURN_uxTaskGetStackHighWaterMark( uxReturn ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskGetStackHighWaterMark */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelete == 1 ) + + static void prvDeleteTCB( TCB_t * pxTCB ) + { + /* This call is required specifically for the TriCore port. It must be + * above the vPortFree() calls. The call is also used by ports/demos that + * want to allocate and clean RAM statically. */ + portCLEAN_UP_TCB( pxTCB ); + + #if ( configUSE_C_RUNTIME_TLS_SUPPORT == 1 ) + { + /* Free up the memory allocated for the task's TLS Block. */ + configDEINIT_TLS_BLOCK( pxTCB->xTLSBlock ); + } + #endif + + #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) + { + /* The task can only have been allocated dynamically - free both + * the stack and TCB. */ + vPortFreeStack( pxTCB->pxStack ); + vPortFree( pxTCB ); + } + #elif ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* The task could have been allocated statically or dynamically, so + * check what was statically allocated before trying to free the + * memory. */ + if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ) + { + /* Both the stack and TCB were allocated dynamically, so both + * must be freed. */ + vPortFreeStack( pxTCB->pxStack ); + vPortFree( pxTCB ); + } + else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) + { + /* Only the stack was statically allocated, so the TCB is the + * only memory that must be freed. */ + vPortFree( pxTCB ); + } + else + { + /* Neither the stack nor the TCB were allocated dynamically, so + * nothing needs to be freed. */ + configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ); + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + } + +#endif /* INCLUDE_vTaskDelete */ +/*-----------------------------------------------------------*/ + +static void prvResetNextTaskUnblockTime( void ) +{ + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The new current delayed list is empty. Set xNextTaskUnblockTime to + * the maximum possible value so it is extremely unlikely that the + * if( xTickCount >= xNextTaskUnblockTime ) test will pass until + * there is an item in the delayed list. */ + xNextTaskUnblockTime = portMAX_DELAY; + } + else + { + /* The new current delayed list is not empty, get the value of + * the item at the head of the delayed list. This is the time at + * which the task at the head of the delayed list should be removed + * from the Blocked state. */ + xNextTaskUnblockTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxDelayedTaskList ); + } +} +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) || ( configNUMBER_OF_CORES > 1 ) + + #if ( configNUMBER_OF_CORES == 1 ) + TaskHandle_t xTaskGetCurrentTaskHandle( void ) + { + TaskHandle_t xReturn; + + traceENTER_xTaskGetCurrentTaskHandle(); + + /* A critical section is not required as this is not called from + * an interrupt and the current TCB will always be the same for any + * individual execution thread. */ + xReturn = pxCurrentTCB; + + traceRETURN_xTaskGetCurrentTaskHandle( xReturn ); + + return xReturn; + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + TaskHandle_t xTaskGetCurrentTaskHandle( void ) + { + TaskHandle_t xReturn; + UBaseType_t uxSavedInterruptStatus; + + traceENTER_xTaskGetCurrentTaskHandle(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK(); + { + xReturn = pxCurrentTCBs[ portGET_CORE_ID() ]; + } + portCLEAR_INTERRUPT_MASK( uxSavedInterruptStatus ); + + traceRETURN_xTaskGetCurrentTaskHandle( xReturn ); + + return xReturn; + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + + TaskHandle_t xTaskGetCurrentTaskHandleForCore( BaseType_t xCoreID ) + { + TaskHandle_t xReturn = NULL; + + traceENTER_xTaskGetCurrentTaskHandleForCore( xCoreID ); + + if( taskVALID_CORE_ID( xCoreID ) != pdFALSE ) + { + #if ( configNUMBER_OF_CORES == 1 ) + xReturn = pxCurrentTCB; + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + xReturn = pxCurrentTCBs[ xCoreID ]; + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + } + + traceRETURN_xTaskGetCurrentTaskHandleForCore( xReturn ); + + return xReturn; + } + +#endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + + BaseType_t xTaskGetSchedulerState( void ) + { + BaseType_t xReturn; + + traceENTER_xTaskGetSchedulerState(); + + if( xSchedulerRunning == pdFALSE ) + { + xReturn = taskSCHEDULER_NOT_STARTED; + } + else + { + #if ( configNUMBER_OF_CORES > 1 ) + taskENTER_CRITICAL(); + #endif + { + if( uxSchedulerSuspended == ( UBaseType_t ) 0U ) + { + xReturn = taskSCHEDULER_RUNNING; + } + else + { + xReturn = taskSCHEDULER_SUSPENDED; + } + } + #if ( configNUMBER_OF_CORES > 1 ) + taskEXIT_CRITICAL(); + #endif + } + + traceRETURN_xTaskGetSchedulerState( xReturn ); + + return xReturn; + } + +#endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxMutexHolderTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; + + traceENTER_xTaskPriorityInherit( pxMutexHolder ); + + /* If the mutex is taken by an interrupt, the mutex holder is NULL. Priority + * inheritance is not applied in this scenario. */ + if( pxMutexHolder != NULL ) + { + /* If the holder of the mutex has a priority below the priority of + * the task attempting to obtain the mutex then it will temporarily + * inherit the priority of the task attempting to obtain the mutex. */ + if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) + { + /* Adjust the mutex holder state to account for its new + * priority. Only reset the event list item value if the value is + * not being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == ( ( TickType_t ) 0U ) ) + { + listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the task being modified is in the ready state it will need + * to be moved into a new list. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + * there is no need to check again and the port level + * reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Inherit the priority before being moved into the new list. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + prvAddTaskToReadyList( pxMutexHolderTCB ); + #if ( configNUMBER_OF_CORES > 1 ) + { + /* The priority of the task is raised. Yield for this task + * if it is not running. */ + if( taskTASK_IS_RUNNING( pxMutexHolderTCB ) != pdTRUE ) + { + prvYieldForTask( pxMutexHolderTCB ); + } + } + #endif /* if ( configNUMBER_OF_CORES > 1 ) */ + } + else + { + /* Just inherit the priority. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + } + + traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); + + /* Inheritance occurred. */ + xReturn = pdTRUE; + } + else + { + if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) + { + /* The base priority of the mutex holder is lower than the + * priority of the task attempting to take the mutex, but the + * current priority of the mutex holder is not lower than the + * priority of the task attempting to take the mutex. + * Therefore the mutex holder must have already inherited a + * priority, but inheritance would have occurred if that had + * not been the case. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xTaskPriorityInherit( xReturn ); + + return xReturn; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; + + traceENTER_xTaskPriorityDisinherit( pxMutexHolder ); + + if( pxMutexHolder != NULL ) + { + /* A task can only have an inherited priority if it holds the mutex. + * If the mutex is held by a task then it cannot be given from an + * interrupt, and if a mutex is given by the holding task then it must + * be the running state task. */ + configASSERT( pxTCB == pxCurrentTCB ); + configASSERT( pxTCB->uxMutexesHeld ); + ( pxTCB->uxMutexesHeld )--; + + /* Has the holder of the mutex inherited the priority of another + * task? */ + if( pxTCB->uxPriority != pxTCB->uxBasePriority ) + { + /* Only disinherit if no other mutexes are held. */ + if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 ) + { + /* A task can only have an inherited priority if it holds + * the mutex. If the mutex is held by a task then it cannot be + * given from an interrupt, and if a mutex is given by the + * holding task then it must be the running state task. Remove + * the holding task from the ready list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Disinherit the priority before adding the task into the + * new ready list. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); + pxTCB->uxPriority = pxTCB->uxBasePriority; + + /* Reset the event list item value. It cannot be in use for + * any other purpose if this task is running, and it must be + * running to give back the mutex. */ + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); + prvAddTaskToReadyList( pxTCB ); + #if ( configNUMBER_OF_CORES > 1 ) + { + /* The priority of the task is dropped. Yield the core on + * which the task is running. */ + if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE ) + { + prvYieldCore( pxTCB->xTaskRunState ); + } + } + #endif /* if ( configNUMBER_OF_CORES > 1 ) */ + + /* Return true to indicate that a context switch is required. + * This is only actually required in the corner case whereby + * multiple mutexes were held and the mutexes were given back + * in an order different to that in which they were taken. + * If a context switch did not occur when the first mutex was + * returned, even if a task was waiting on it, then a context + * switch should occur when the last mutex is returned whether + * a task is waiting on it or not. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xTaskPriorityDisinherit( xReturn ); + + return xReturn; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, + UBaseType_t uxHighestPriorityWaitingTask ) + { + TCB_t * const pxTCB = pxMutexHolder; + UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse; + const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1; + + traceENTER_vTaskPriorityDisinheritAfterTimeout( pxMutexHolder, uxHighestPriorityWaitingTask ); + + if( pxMutexHolder != NULL ) + { + /* If pxMutexHolder is not NULL then the holder must hold at least + * one mutex. */ + configASSERT( pxTCB->uxMutexesHeld ); + + /* Determine the priority to which the priority of the task that + * holds the mutex should be set. This will be the greater of the + * holding task's base priority and the priority of the highest + * priority task that is waiting to obtain the mutex. */ + if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) + { + uxPriorityToUse = uxHighestPriorityWaitingTask; + } + else + { + uxPriorityToUse = pxTCB->uxBasePriority; + } + + /* Does the priority need to change? */ + if( pxTCB->uxPriority != uxPriorityToUse ) + { + /* Only disinherit if no other mutexes are held. This is a + * simplification in the priority inheritance implementation. If + * the task that holds the mutex is also holding other mutexes then + * the other mutexes may have caused the priority inheritance. */ + if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) + { + /* If a task has timed out because it already holds the + * mutex it was trying to obtain then it cannot of inherited + * its own priority. */ + configASSERT( pxTCB != pxCurrentTCB ); + + /* Disinherit the priority, remembering the previous + * priority to facilitate determining the subject task's + * state. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, uxPriorityToUse ); + uxPriorityUsedOnEntry = pxTCB->uxPriority; + pxTCB->uxPriority = uxPriorityToUse; + + /* Only reset the event list item value if the value is not + * being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == ( ( TickType_t ) 0U ) ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the running task is not the task that holds the mutex + * then the task that holds the mutex could be in either the + * Ready, Blocked or Suspended states. Only remove the task + * from its current state list if it is in the Ready state as + * the task's priority is going to change and there is one + * Ready list per priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + * there is no need to check again and the port level + * reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + prvAddTaskToReadyList( pxTCB ); + #if ( configNUMBER_OF_CORES > 1 ) + { + /* The priority of the task is dropped. Yield the core on + * which the task is running. */ + if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE ) + { + prvYieldCore( pxTCB->xTaskRunState ); + } + } + #endif /* if ( configNUMBER_OF_CORES > 1 ) */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskPriorityDisinheritAfterTimeout(); + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configNUMBER_OF_CORES > 1 ) + +/* If not in a critical section then yield immediately. + * Otherwise set xYieldPendings to true to wait to + * yield until exiting the critical section. + */ + void vTaskYieldWithinAPI( void ) + { + traceENTER_vTaskYieldWithinAPI(); + + if( portGET_CRITICAL_NESTING_COUNT() == 0U ) + { + portYIELD(); + } + else + { + xYieldPendings[ portGET_CORE_ID() ] = pdTRUE; + } + + traceRETURN_vTaskYieldWithinAPI(); + } +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + +/*-----------------------------------------------------------*/ + +#if ( ( portCRITICAL_NESTING_IN_TCB == 1 ) && ( configNUMBER_OF_CORES == 1 ) ) + + void vTaskEnterCritical( void ) + { + traceENTER_vTaskEnterCritical(); + + portDISABLE_INTERRUPTS(); + + if( xSchedulerRunning != pdFALSE ) + { + ( pxCurrentTCB->uxCriticalNesting )++; + + /* This is not the interrupt safe version of the enter critical + * function so assert() if it is being called from an interrupt + * context. Only API functions that end in "FromISR" can be used in an + * interrupt. Only assert if the critical nesting count is 1 to + * protect against recursive calls if the assert function also uses a + * critical section. */ + if( pxCurrentTCB->uxCriticalNesting == 1U ) + { + portASSERT_IF_IN_ISR(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskEnterCritical(); + } + +#endif /* #if ( ( portCRITICAL_NESTING_IN_TCB == 1 ) && ( configNUMBER_OF_CORES == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configNUMBER_OF_CORES > 1 ) + + void vTaskEnterCritical( void ) + { + traceENTER_vTaskEnterCritical(); + + portDISABLE_INTERRUPTS(); + + if( xSchedulerRunning != pdFALSE ) + { + if( portGET_CRITICAL_NESTING_COUNT() == 0U ) + { + portGET_TASK_LOCK(); + portGET_ISR_LOCK(); + } + + portINCREMENT_CRITICAL_NESTING_COUNT(); + + /* This is not the interrupt safe version of the enter critical + * function so assert() if it is being called from an interrupt + * context. Only API functions that end in "FromISR" can be used in an + * interrupt. Only assert if the critical nesting count is 1 to + * protect against recursive calls if the assert function also uses a + * critical section. */ + if( portGET_CRITICAL_NESTING_COUNT() == 1U ) + { + portASSERT_IF_IN_ISR(); + + if( uxSchedulerSuspended == 0U ) + { + /* The only time there would be a problem is if this is called + * before a context switch and vTaskExitCritical() is called + * after pxCurrentTCB changes. Therefore this should not be + * used within vTaskSwitchContext(). */ + prvCheckForRunStateChange(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskEnterCritical(); + } + +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + +/*-----------------------------------------------------------*/ + +#if ( configNUMBER_OF_CORES > 1 ) + + UBaseType_t vTaskEnterCriticalFromISR( void ) + { + UBaseType_t uxSavedInterruptStatus = 0; + + traceENTER_vTaskEnterCriticalFromISR(); + + if( xSchedulerRunning != pdFALSE ) + { + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + + if( portGET_CRITICAL_NESTING_COUNT() == 0U ) + { + portGET_ISR_LOCK(); + } + + portINCREMENT_CRITICAL_NESTING_COUNT(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskEnterCriticalFromISR( uxSavedInterruptStatus ); + + return uxSavedInterruptStatus; + } + +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( portCRITICAL_NESTING_IN_TCB == 1 ) && ( configNUMBER_OF_CORES == 1 ) ) + + void vTaskExitCritical( void ) + { + traceENTER_vTaskExitCritical(); + + if( xSchedulerRunning != pdFALSE ) + { + /* If pxCurrentTCB->uxCriticalNesting is zero then this function + * does not match a previous call to vTaskEnterCritical(). */ + configASSERT( pxCurrentTCB->uxCriticalNesting > 0U ); + + /* This function should not be called in ISR. Use vTaskExitCriticalFromISR + * to exit critical section from ISR. */ + portASSERT_IF_IN_ISR(); + + if( pxCurrentTCB->uxCriticalNesting > 0U ) + { + ( pxCurrentTCB->uxCriticalNesting )--; + + if( pxCurrentTCB->uxCriticalNesting == 0U ) + { + portENABLE_INTERRUPTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskExitCritical(); + } + +#endif /* #if ( ( portCRITICAL_NESTING_IN_TCB == 1 ) && ( configNUMBER_OF_CORES == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configNUMBER_OF_CORES > 1 ) + + void vTaskExitCritical( void ) + { + traceENTER_vTaskExitCritical(); + + if( xSchedulerRunning != pdFALSE ) + { + /* If critical nesting count is zero then this function + * does not match a previous call to vTaskEnterCritical(). */ + configASSERT( portGET_CRITICAL_NESTING_COUNT() > 0U ); + + /* This function should not be called in ISR. Use vTaskExitCriticalFromISR + * to exit critical section from ISR. */ + portASSERT_IF_IN_ISR(); + + if( portGET_CRITICAL_NESTING_COUNT() > 0U ) + { + portDECREMENT_CRITICAL_NESTING_COUNT(); + + if( portGET_CRITICAL_NESTING_COUNT() == 0U ) + { + BaseType_t xYieldCurrentTask; + + /* Get the xYieldPending stats inside the critical section. */ + xYieldCurrentTask = xYieldPendings[ portGET_CORE_ID() ]; + + portRELEASE_ISR_LOCK(); + portRELEASE_TASK_LOCK(); + portENABLE_INTERRUPTS(); + + /* When a task yields in a critical section it just sets + * xYieldPending to true. So now that we have exited the + * critical section check if xYieldPending is true, and + * if so yield. */ + if( xYieldCurrentTask != pdFALSE ) + { + portYIELD(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskExitCritical(); + } + +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( configNUMBER_OF_CORES > 1 ) + + void vTaskExitCriticalFromISR( UBaseType_t uxSavedInterruptStatus ) + { + traceENTER_vTaskExitCriticalFromISR( uxSavedInterruptStatus ); + + if( xSchedulerRunning != pdFALSE ) + { + /* If critical nesting count is zero then this function + * does not match a previous call to vTaskEnterCritical(). */ + configASSERT( portGET_CRITICAL_NESTING_COUNT() > 0U ); + + if( portGET_CRITICAL_NESTING_COUNT() > 0U ) + { + portDECREMENT_CRITICAL_NESTING_COUNT(); + + if( portGET_CRITICAL_NESTING_COUNT() == 0U ) + { + portRELEASE_ISR_LOCK(); + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskExitCriticalFromISR(); + } + +#endif /* #if ( configNUMBER_OF_CORES > 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) + + static char * prvWriteNameToBuffer( char * pcBuffer, + const char * pcTaskName ) + { + size_t x; + + /* Start by copying the entire string. */ + ( void ) strcpy( pcBuffer, pcTaskName ); + + /* Pad the end of the string with spaces to ensure columns line up when + * printed out. */ + for( x = strlen( pcBuffer ); x < ( size_t ) ( ( size_t ) configMAX_TASK_NAME_LEN - 1U ); x++ ) + { + pcBuffer[ x ] = ' '; + } + + /* Terminate. */ + pcBuffer[ x ] = ( char ) 0x00; + + /* Return the new end of string. */ + return &( pcBuffer[ x ] ); + } + +#endif /* ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) + + void vTaskListTasks( char * pcWriteBuffer, + size_t uxBufferLength ) + { + TaskStatus_t * pxTaskStatusArray; + size_t uxConsumedBufferLength = 0; + size_t uxCharsWrittenBySnprintf; + int iSnprintfReturnValue; + BaseType_t xOutputBufferFull = pdFALSE; + UBaseType_t uxArraySize, x; + char cStatus; + + traceENTER_vTaskListTasks( pcWriteBuffer, uxBufferLength ); + + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskListTasks() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that + * displays task: names, states, priority, stack usage and task number. + * Stack usage specified as the number of unused StackType_t words stack can hold + * on top of stack - not the number of bytes. + * + * vTaskListTasks() has a dependency on the snprintf() C library function that + * might bloat the code size, use a lot of stack, and provide different + * results on different platforms. An alternative, tiny, third party, + * and limited functionality implementation of snprintf() is provided in + * many of the FreeRTOS/Demo sub-directories in a file called + * printf-stdarg.c (note printf-stdarg.c does not provide a full + * snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly + * through a call to vTaskListTasks(). + */ + + + /* Make sure the write buffer does not contain a string. */ + *pcWriteBuffer = ( char ) 0x00; + + /* Take a snapshot of the number of tasks in case it changes while this + * function is executing. */ + uxArraySize = uxCurrentNumberOfTasks; + + /* Allocate an array index for each task. NOTE! if + * configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will + * equate to NULL. */ + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); + + if( pxTaskStatusArray != NULL ) + { + /* Generate the (binary) data. */ + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL ); + + /* Create a human readable table from the binary data. */ + for( x = 0; x < uxArraySize; x++ ) + { + switch( pxTaskStatusArray[ x ].eCurrentState ) + { + case eRunning: + cStatus = tskRUNNING_CHAR; + break; + + case eReady: + cStatus = tskREADY_CHAR; + break; + + case eBlocked: + cStatus = tskBLOCKED_CHAR; + break; + + case eSuspended: + cStatus = tskSUSPENDED_CHAR; + break; + + case eDeleted: + cStatus = tskDELETED_CHAR; + break; + + case eInvalid: /* Fall through. */ + default: /* Should not get here, but it is included + * to prevent static checking errors. */ + cStatus = ( char ) 0x00; + break; + } + + /* Is there enough space in the buffer to hold task name? */ + if( ( uxConsumedBufferLength + configMAX_TASK_NAME_LEN ) <= uxBufferLength ) + { + /* Write the task name to the string, padding with spaces so it + * can be printed in tabular form more easily. */ + pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); + /* Do not count the terminating null character. */ + uxConsumedBufferLength = uxConsumedBufferLength + ( configMAX_TASK_NAME_LEN - 1U ); + + /* Is there space left in the buffer? -1 is done because snprintf + * writes a terminating null character. So we are essentially + * checking if the buffer has space to write at least one non-null + * character. */ + if( uxConsumedBufferLength < ( uxBufferLength - 1U ) ) + { + /* Write the rest of the string. */ + #if ( ( configUSE_CORE_AFFINITY == 1 ) && ( configNUMBER_OF_CORES > 1 ) ) + /* MISRA Ref 21.6.1 [snprintf for utility] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-216 */ + /* coverity[misra_c_2012_rule_21_6_violation] */ + iSnprintfReturnValue = snprintf( pcWriteBuffer, + uxBufferLength - uxConsumedBufferLength, + "\t%c\t%u\t%u\t%u\t0x%x\r\n", + cStatus, + ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, + ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, + ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber, + ( unsigned int ) pxTaskStatusArray[ x ].uxCoreAffinityMask ); + #else /* ( ( configUSE_CORE_AFFINITY == 1 ) && ( configNUMBER_OF_CORES > 1 ) ) */ + /* MISRA Ref 21.6.1 [snprintf for utility] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-216 */ + /* coverity[misra_c_2012_rule_21_6_violation] */ + iSnprintfReturnValue = snprintf( pcWriteBuffer, + uxBufferLength - uxConsumedBufferLength, + "\t%c\t%u\t%u\t%u\r\n", + cStatus, + ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, + ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, + ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber ); + #endif /* ( ( configUSE_CORE_AFFINITY == 1 ) && ( configNUMBER_OF_CORES > 1 ) ) */ + uxCharsWrittenBySnprintf = prvSnprintfReturnValueToCharsWritten( iSnprintfReturnValue, uxBufferLength - uxConsumedBufferLength ); + + uxConsumedBufferLength += uxCharsWrittenBySnprintf; + pcWriteBuffer += uxCharsWrittenBySnprintf; + } + else + { + xOutputBufferFull = pdTRUE; + } + } + else + { + xOutputBufferFull = pdTRUE; + } + + if( xOutputBufferFull == pdTRUE ) + { + break; + } + } + + /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION + * is 0 then vPortFree() will be #defined to nothing. */ + vPortFree( pxTaskStatusArray ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskListTasks(); + } + +#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) */ +/*----------------------------------------------------------*/ + +#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configUSE_TRACE_FACILITY == 1 ) ) + + void vTaskGetRunTimeStatistics( char * pcWriteBuffer, + size_t uxBufferLength ) + { + TaskStatus_t * pxTaskStatusArray; + size_t uxConsumedBufferLength = 0; + size_t uxCharsWrittenBySnprintf; + int iSnprintfReturnValue; + BaseType_t xOutputBufferFull = pdFALSE; + UBaseType_t uxArraySize, x; + configRUN_TIME_COUNTER_TYPE ulTotalTime = 0; + configRUN_TIME_COUNTER_TYPE ulStatsAsPercentage; + + traceENTER_vTaskGetRunTimeStatistics( pcWriteBuffer, uxBufferLength ); + + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskGetRunTimeStatistics() calls uxTaskGetSystemState(), then formats part + * of the uxTaskGetSystemState() output into a human readable table that + * displays the amount of time each task has spent in the Running state + * in both absolute and percentage terms. + * + * vTaskGetRunTimeStatistics() has a dependency on the snprintf() C library + * function that might bloat the code size, use a lot of stack, and + * provide different results on different platforms. An alternative, + * tiny, third party, and limited functionality implementation of + * snprintf() is provided in many of the FreeRTOS/Demo sub-directories in + * a file called printf-stdarg.c (note printf-stdarg.c does not provide + * a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly + * through a call to vTaskGetRunTimeStatistics(). + */ + + /* Make sure the write buffer does not contain a string. */ + *pcWriteBuffer = ( char ) 0x00; + + /* Take a snapshot of the number of tasks in case it changes while this + * function is executing. */ + uxArraySize = uxCurrentNumberOfTasks; + + /* Allocate an array index for each task. NOTE! If + * configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will + * equate to NULL. */ + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); + + if( pxTaskStatusArray != NULL ) + { + /* Generate the (binary) data. */ + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime ); + + /* For percentage calculations. */ + ulTotalTime /= ( ( configRUN_TIME_COUNTER_TYPE ) 100U ); + + /* Avoid divide by zero errors. */ + if( ulTotalTime > 0U ) + { + /* Create a human readable table from the binary data. */ + for( x = 0; x < uxArraySize; x++ ) + { + /* What percentage of the total run time has the task used? + * This will always be rounded down to the nearest integer. + * ulTotalRunTime has already been divided by 100. */ + ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime; + + /* Is there enough space in the buffer to hold task name? */ + if( ( uxConsumedBufferLength + configMAX_TASK_NAME_LEN ) <= uxBufferLength ) + { + /* Write the task name to the string, padding with + * spaces so it can be printed in tabular form more + * easily. */ + pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); + /* Do not count the terminating null character. */ + uxConsumedBufferLength = uxConsumedBufferLength + ( configMAX_TASK_NAME_LEN - 1U ); + + /* Is there space left in the buffer? -1 is done because snprintf + * writes a terminating null character. So we are essentially + * checking if the buffer has space to write at least one non-null + * character. */ + if( uxConsumedBufferLength < ( uxBufferLength - 1U ) ) + { + if( ulStatsAsPercentage > 0U ) + { + #ifdef portLU_PRINTF_SPECIFIER_REQUIRED + { + /* MISRA Ref 21.6.1 [snprintf for utility] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-216 */ + /* coverity[misra_c_2012_rule_21_6_violation] */ + iSnprintfReturnValue = snprintf( pcWriteBuffer, + uxBufferLength - uxConsumedBufferLength, + "\t%lu\t\t%lu%%\r\n", + pxTaskStatusArray[ x ].ulRunTimeCounter, + ulStatsAsPercentage ); + } + #else /* ifdef portLU_PRINTF_SPECIFIER_REQUIRED */ + { + /* sizeof( int ) == sizeof( long ) so a smaller + * printf() library can be used. */ + /* MISRA Ref 21.6.1 [snprintf for utility] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-216 */ + /* coverity[misra_c_2012_rule_21_6_violation] */ + iSnprintfReturnValue = snprintf( pcWriteBuffer, + uxBufferLength - uxConsumedBufferLength, + "\t%u\t\t%u%%\r\n", + ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, + ( unsigned int ) ulStatsAsPercentage ); + } + #endif /* ifdef portLU_PRINTF_SPECIFIER_REQUIRED */ + } + else + { + /* If the percentage is zero here then the task has + * consumed less than 1% of the total run time. */ + #ifdef portLU_PRINTF_SPECIFIER_REQUIRED + { + /* MISRA Ref 21.6.1 [snprintf for utility] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-216 */ + /* coverity[misra_c_2012_rule_21_6_violation] */ + iSnprintfReturnValue = snprintf( pcWriteBuffer, + uxBufferLength - uxConsumedBufferLength, + "\t%lu\t\t<1%%\r\n", + pxTaskStatusArray[ x ].ulRunTimeCounter ); + } + #else + { + /* sizeof( int ) == sizeof( long ) so a smaller + * printf() library can be used. */ + /* MISRA Ref 21.6.1 [snprintf for utility] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-216 */ + /* coverity[misra_c_2012_rule_21_6_violation] */ + iSnprintfReturnValue = snprintf( pcWriteBuffer, + uxBufferLength - uxConsumedBufferLength, + "\t%u\t\t<1%%\r\n", + ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); + } + #endif /* ifdef portLU_PRINTF_SPECIFIER_REQUIRED */ + } + + uxCharsWrittenBySnprintf = prvSnprintfReturnValueToCharsWritten( iSnprintfReturnValue, uxBufferLength - uxConsumedBufferLength ); + uxConsumedBufferLength += uxCharsWrittenBySnprintf; + pcWriteBuffer += uxCharsWrittenBySnprintf; + } + else + { + xOutputBufferFull = pdTRUE; + } + } + else + { + xOutputBufferFull = pdTRUE; + } + + if( xOutputBufferFull == pdTRUE ) + { + break; + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION + * is 0 then vPortFree() will be #defined to nothing. */ + vPortFree( pxTaskStatusArray ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_vTaskGetRunTimeStatistics(); + } + +#endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) */ +/*-----------------------------------------------------------*/ + +TickType_t uxTaskResetEventItemValue( void ) +{ + TickType_t uxReturn; + + traceENTER_uxTaskResetEventItemValue(); + + uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) ); + + /* Reset the event list item to its normal value - so it can be used with + * queues and semaphores. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); + + traceRETURN_uxTaskResetEventItemValue( uxReturn ); + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + TaskHandle_t pvTaskIncrementMutexHeldCount( void ) + { + TCB_t * pxTCB; + + traceENTER_pvTaskIncrementMutexHeldCount(); + + pxTCB = pxCurrentTCB; + + /* If xSemaphoreCreateMutex() is called before any tasks have been created + * then pxCurrentTCB will be NULL. */ + if( pxTCB != NULL ) + { + ( pxTCB->uxMutexesHeld )++; + } + + traceRETURN_pvTaskIncrementMutexHeldCount( pxTCB ); + + return pxTCB; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + uint32_t ulTaskGenericNotifyTake( UBaseType_t uxIndexToWaitOn, + BaseType_t xClearCountOnExit, + TickType_t xTicksToWait ) + { + uint32_t ulReturn; + BaseType_t xAlreadyYielded, xShouldBlock = pdFALSE; + + traceENTER_ulTaskGenericNotifyTake( uxIndexToWaitOn, xClearCountOnExit, xTicksToWait ); + + configASSERT( uxIndexToWaitOn < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* We suspend the scheduler here as prvAddCurrentTaskToDelayedList is a + * non-deterministic operation. */ + vTaskSuspendAll(); + { + /* We MUST enter a critical section to atomically check if a notification + * has occurred and set the flag to indicate that we are waiting for + * a notification. If we do not do so, a notification sent from an ISR + * will get lost. */ + taskENTER_CRITICAL(); + { + /* Only block if the notification count is not already non-zero. */ + if( pxCurrentTCB->ulNotifiedValue[ uxIndexToWaitOn ] == 0U ) + { + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState[ uxIndexToWaitOn ] = taskWAITING_NOTIFICATION; + + if( xTicksToWait > ( TickType_t ) 0 ) + { + xShouldBlock = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + /* We are now out of the critical section but the scheduler is still + * suspended, so we are safe to do non-deterministic operations such + * as prvAddCurrentTaskToDelayedList. */ + if( xShouldBlock == pdTRUE ) + { + traceTASK_NOTIFY_TAKE_BLOCK( uxIndexToWaitOn ); + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + xAlreadyYielded = xTaskResumeAll(); + + /* Force a reschedule if xTaskResumeAll has not already done so. */ + if( ( xShouldBlock == pdTRUE ) && ( xAlreadyYielded == pdFALSE ) ) + { + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_TAKE( uxIndexToWaitOn ); + ulReturn = pxCurrentTCB->ulNotifiedValue[ uxIndexToWaitOn ]; + + if( ulReturn != 0U ) + { + if( xClearCountOnExit != pdFALSE ) + { + pxCurrentTCB->ulNotifiedValue[ uxIndexToWaitOn ] = ( uint32_t ) 0U; + } + else + { + pxCurrentTCB->ulNotifiedValue[ uxIndexToWaitOn ] = ulReturn - ( uint32_t ) 1; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxCurrentTCB->ucNotifyState[ uxIndexToWaitOn ] = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); + + traceRETURN_ulTaskGenericNotifyTake( ulReturn ); + + return ulReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, + uint32_t ulBitsToClearOnEntry, + uint32_t ulBitsToClearOnExit, + uint32_t * pulNotificationValue, + TickType_t xTicksToWait ) + { + BaseType_t xReturn, xAlreadyYielded, xShouldBlock = pdFALSE; + + traceENTER_xTaskGenericNotifyWait( uxIndexToWaitOn, ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait ); + + configASSERT( uxIndexToWaitOn < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* We suspend the scheduler here as prvAddCurrentTaskToDelayedList is a + * non-deterministic operation. */ + vTaskSuspendAll(); + { + /* We MUST enter a critical section to atomically check and update the + * task notification value. If we do not do so, a notification from + * an ISR will get lost. */ + taskENTER_CRITICAL(); + { + /* Only block if a notification is not already pending. */ + if( pxCurrentTCB->ucNotifyState[ uxIndexToWaitOn ] != taskNOTIFICATION_RECEIVED ) + { + /* Clear bits in the task's notification value as bits may get + * set by the notifying task or interrupt. This can be used + * to clear the value to zero. */ + pxCurrentTCB->ulNotifiedValue[ uxIndexToWaitOn ] &= ~ulBitsToClearOnEntry; + + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState[ uxIndexToWaitOn ] = taskWAITING_NOTIFICATION; + + if( xTicksToWait > ( TickType_t ) 0 ) + { + xShouldBlock = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + /* We are now out of the critical section but the scheduler is still + * suspended, so we are safe to do non-deterministic operations such + * as prvAddCurrentTaskToDelayedList. */ + if( xShouldBlock == pdTRUE ) + { + traceTASK_NOTIFY_WAIT_BLOCK( uxIndexToWaitOn ); + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + xAlreadyYielded = xTaskResumeAll(); + + /* Force a reschedule if xTaskResumeAll has not already done so. */ + if( ( xShouldBlock == pdTRUE ) && ( xAlreadyYielded == pdFALSE ) ) + { + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_WAIT( uxIndexToWaitOn ); + + if( pulNotificationValue != NULL ) + { + /* Output the current notification value, which may or may not + * have changed. */ + *pulNotificationValue = pxCurrentTCB->ulNotifiedValue[ uxIndexToWaitOn ]; + } + + /* If ucNotifyValue is set then either the task never entered the + * blocked state (because a notification was already pending) or the + * task unblocked because of a notification. Otherwise the task + * unblocked because of a timeout. */ + if( pxCurrentTCB->ucNotifyState[ uxIndexToWaitOn ] != taskNOTIFICATION_RECEIVED ) + { + /* A notification was not received. */ + xReturn = pdFALSE; + } + else + { + /* A notification was already pending or a notification was + * received while the task was waiting. */ + pxCurrentTCB->ulNotifiedValue[ uxIndexToWaitOn ] &= ~ulBitsToClearOnExit; + xReturn = pdTRUE; + } + + pxCurrentTCB->ucNotifyState[ uxIndexToWaitOn ] = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); + + traceRETURN_xTaskGenericNotifyWait( xReturn ); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue ) + { + TCB_t * pxTCB; + BaseType_t xReturn = pdPASS; + uint8_t ucOriginalNotifyState; + + traceENTER_xTaskGenericNotify( xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotificationValue ); + + configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + configASSERT( xTaskToNotify ); + pxTCB = xTaskToNotify; + + taskENTER_CRITICAL(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ]; + } + + ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; + + pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; + + switch( eAction ) + { + case eSetBits: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue; + break; + + case eIncrement: + ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; + break; + + case eSetValueWithOverwrite: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + break; + + case eSetValueWithoutOverwrite: + + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + + break; + + case eNoAction: + + /* The task is being notified without its notify value being + * updated. */ + break; + + default: + + /* Should not get here if all enums are handled. + * Artificially force an assert by testing a value the + * compiler can't assume is const. */ + configASSERT( xTickCount == ( TickType_t ) 0 ); + + break; + } + + traceTASK_NOTIFY( uxIndexToNotify ); + + /* If the task is in the blocked state specifically to wait for a + * notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + listREMOVE_ITEM( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked waiting for a notification then + * xNextTaskUnblockTime might be set to the blocked task's time + * out time. If the task is unblocked for a reason other than + * a timeout xNextTaskUnblockTime is normally left unchanged, + * because it will automatically get reset to a new value when + * the tick count equals xNextTaskUnblockTime. However if + * tickless idling is used it might be more important to enter + * sleep mode at the earliest possible time - so reset + * xNextTaskUnblockTime here to ensure it is updated at the + * earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + + /* Check if the notified task has a priority above the currently + * executing task. */ + taskYIELD_ANY_CORE_IF_USING_PREEMPTION( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + traceRETURN_xTaskGenericNotify( xReturn ); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue, + BaseType_t * pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + BaseType_t xReturn = pdPASS; + UBaseType_t uxSavedInterruptStatus; + + traceENTER_xTaskGenericNotifyFromISR( xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ); + + configASSERT( xTaskToNotify ); + configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + pxTCB = xTaskToNotify; + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = ( UBaseType_t ) taskENTER_CRITICAL_FROM_ISR(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ]; + } + + ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; + pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; + + switch( eAction ) + { + case eSetBits: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue; + break; + + case eIncrement: + ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; + break; + + case eSetValueWithOverwrite: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + break; + + case eSetValueWithoutOverwrite: + + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + + break; + + case eNoAction: + + /* The task is being notified without its notify value being + * updated. */ + break; + + default: + + /* Should not get here if all enums are handled. + * Artificially force an assert by testing a value the + * compiler can't assume is const. */ + configASSERT( xTickCount == ( TickType_t ) 0 ); + break; + } + + traceTASK_NOTIFY_FROM_ISR( uxIndexToNotify ); + + /* If the task is in the blocked state specifically to wait for a + * notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + if( uxSchedulerSuspended == ( UBaseType_t ) 0U ) + { + listREMOVE_ITEM( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed and ready lists cannot be accessed, so hold + * this task pending until the scheduler is resumed. */ + listINSERT_END( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + + #if ( configNUMBER_OF_CORES == 1 ) + { + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + * executing task so a yield is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + + /* Mark that a yield is pending in case the user is not + * using the "xHigherPriorityTaskWoken" parameter to an ISR + * safe FreeRTOS function. */ + xYieldPendings[ 0 ] = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + #if ( configUSE_PREEMPTION == 1 ) + { + prvYieldForTask( pxTCB ); + + if( xYieldPendings[ portGET_CORE_ID() ] == pdTRUE ) + { + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + } + } + #endif /* if ( configUSE_PREEMPTION == 1 ) */ + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + } + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_xTaskGenericNotifyFromISR( xReturn ); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + void vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + BaseType_t * pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + UBaseType_t uxSavedInterruptStatus; + + traceENTER_vTaskGenericNotifyGiveFromISR( xTaskToNotify, uxIndexToNotify, pxHigherPriorityTaskWoken ); + + configASSERT( xTaskToNotify ); + configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + pxTCB = xTaskToNotify; + + /* MISRA Ref 4.7.1 [Return value shall be checked] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */ + /* coverity[misra_c_2012_directive_4_7_violation] */ + uxSavedInterruptStatus = ( UBaseType_t ) taskENTER_CRITICAL_FROM_ISR(); + { + ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; + pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; + + /* 'Giving' is equivalent to incrementing a count in a counting + * semaphore. */ + ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; + + traceTASK_NOTIFY_GIVE_FROM_ISR( uxIndexToNotify ); + + /* If the task is in the blocked state specifically to wait for a + * notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + if( uxSchedulerSuspended == ( UBaseType_t ) 0U ) + { + listREMOVE_ITEM( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed and ready lists cannot be accessed, so hold + * this task pending until the scheduler is resumed. */ + listINSERT_END( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + + #if ( configNUMBER_OF_CORES == 1 ) + { + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + * executing task so a yield is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + + /* Mark that a yield is pending in case the user is not + * using the "xHigherPriorityTaskWoken" parameter in an ISR + * safe FreeRTOS function. */ + xYieldPendings[ 0 ] = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else /* #if ( configNUMBER_OF_CORES == 1 ) */ + { + #if ( configUSE_PREEMPTION == 1 ) + { + prvYieldForTask( pxTCB ); + + if( xYieldPendings[ portGET_CORE_ID() ] == pdTRUE ) + { + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + } + } + #endif /* #if ( configUSE_PREEMPTION == 1 ) */ + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + } + } + taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus ); + + traceRETURN_vTaskGenericNotifyGiveFromISR(); + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotifyStateClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear ) + { + TCB_t * pxTCB; + BaseType_t xReturn; + + traceENTER_xTaskGenericNotifyStateClear( xTask, uxIndexToClear ); + + configASSERT( uxIndexToClear < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* If null is passed in here then it is the calling task that is having + * its notification state cleared. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + taskENTER_CRITICAL(); + { + if( pxTCB->ucNotifyState[ uxIndexToClear ] == taskNOTIFICATION_RECEIVED ) + { + pxTCB->ucNotifyState[ uxIndexToClear ] = taskNOT_WAITING_NOTIFICATION; + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + taskEXIT_CRITICAL(); + + traceRETURN_xTaskGenericNotifyStateClear( xReturn ); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + uint32_t ulTaskGenericNotifyValueClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear, + uint32_t ulBitsToClear ) + { + TCB_t * pxTCB; + uint32_t ulReturn; + + traceENTER_ulTaskGenericNotifyValueClear( xTask, uxIndexToClear, ulBitsToClear ); + + configASSERT( uxIndexToClear < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* If null is passed in here then it is the calling task that is having + * its notification state cleared. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + taskENTER_CRITICAL(); + { + /* Return the notification as it was before the bits were cleared, + * then clear the bit mask. */ + ulReturn = pxTCB->ulNotifiedValue[ uxIndexToClear ]; + pxTCB->ulNotifiedValue[ uxIndexToClear ] &= ~ulBitsToClear; + } + taskEXIT_CRITICAL(); + + traceRETURN_ulTaskGenericNotifyValueClear( ulReturn ); + + return ulReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + + configRUN_TIME_COUNTER_TYPE ulTaskGetRunTimeCounter( const TaskHandle_t xTask ) + { + TCB_t * pxTCB; + + traceENTER_ulTaskGetRunTimeCounter( xTask ); + + pxTCB = prvGetTCBFromHandle( xTask ); + + traceRETURN_ulTaskGetRunTimeCounter( pxTCB->ulRunTimeCounter ); + + return pxTCB->ulRunTimeCounter; + } + +#endif /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + + configRUN_TIME_COUNTER_TYPE ulTaskGetRunTimePercent( const TaskHandle_t xTask ) + { + TCB_t * pxTCB; + configRUN_TIME_COUNTER_TYPE ulTotalTime, ulReturn; + + traceENTER_ulTaskGetRunTimePercent( xTask ); + + ulTotalTime = ( configRUN_TIME_COUNTER_TYPE ) portGET_RUN_TIME_COUNTER_VALUE(); + + /* For percentage calculations. */ + ulTotalTime /= ( configRUN_TIME_COUNTER_TYPE ) 100; + + /* Avoid divide by zero errors. */ + if( ulTotalTime > ( configRUN_TIME_COUNTER_TYPE ) 0 ) + { + pxTCB = prvGetTCBFromHandle( xTask ); + ulReturn = pxTCB->ulRunTimeCounter / ulTotalTime; + } + else + { + ulReturn = 0; + } + + traceRETURN_ulTaskGetRunTimePercent( ulReturn ); + + return ulReturn; + } + +#endif /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) + + configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimeCounter( void ) + { + configRUN_TIME_COUNTER_TYPE ulReturn = 0; + BaseType_t i; + + traceENTER_ulTaskGetIdleRunTimeCounter(); + + for( i = 0; i < ( BaseType_t ) configNUMBER_OF_CORES; i++ ) + { + ulReturn += xIdleTaskHandles[ i ]->ulRunTimeCounter; + } + + traceRETURN_ulTaskGetIdleRunTimeCounter( ulReturn ); + + return ulReturn; + } + +#endif /* if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) + + configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimePercent( void ) + { + configRUN_TIME_COUNTER_TYPE ulTotalTime, ulReturn; + configRUN_TIME_COUNTER_TYPE ulRunTimeCounter = 0; + BaseType_t i; + + traceENTER_ulTaskGetIdleRunTimePercent(); + + ulTotalTime = portGET_RUN_TIME_COUNTER_VALUE() * configNUMBER_OF_CORES; + + /* For percentage calculations. */ + ulTotalTime /= ( configRUN_TIME_COUNTER_TYPE ) 100; + + /* Avoid divide by zero errors. */ + if( ulTotalTime > ( configRUN_TIME_COUNTER_TYPE ) 0 ) + { + for( i = 0; i < ( BaseType_t ) configNUMBER_OF_CORES; i++ ) + { + ulRunTimeCounter += xIdleTaskHandles[ i ]->ulRunTimeCounter; + } + + ulReturn = ulRunTimeCounter / ulTotalTime; + } + else + { + ulReturn = 0; + } + + traceRETURN_ulTaskGetIdleRunTimePercent( ulReturn ); + + return ulReturn; + } + +#endif /* if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) */ +/*-----------------------------------------------------------*/ + +static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, + const BaseType_t xCanBlockIndefinitely ) +{ + TickType_t xTimeToWake; + const TickType_t xConstTickCount = xTickCount; + List_t * const pxDelayedList = pxDelayedTaskList; + List_t * const pxOverflowDelayedList = pxOverflowDelayedTaskList; + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + { + /* About to enter a delayed list, so ensure the ucDelayAborted flag is + * reset to pdFALSE so it can be detected as having been set to pdTRUE + * when the task leaves the Blocked state. */ + pxCurrentTCB->ucDelayAborted = ( uint8_t ) pdFALSE; + } + #endif + + /* Remove the task from the ready list before adding it to the blocked list + * as the same list item is used for both lists. */ + if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* The current task must be in a ready list, so there is no need to + * check, and the port reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) ) + { + /* Add the task to the suspended task list instead of a delayed task + * list to ensure it is not woken by a timing event. It will block + * indefinitely. */ + listINSERT_END( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* Calculate the time at which the task should be woken if the event + * does not occur. This may overflow but this doesn't matter, the + * kernel will manage it correctly. */ + xTimeToWake = xConstTickCount + xTicksToWait; + + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); + + if( xTimeToWake < xConstTickCount ) + { + /* Wake time has overflowed. Place this item in the overflow + * list. */ + traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST(); + vListInsert( pxOverflowDelayedList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* The wake time has not overflowed, so the current block list + * is used. */ + traceMOVED_TASK_TO_DELAYED_LIST(); + vListInsert( pxDelayedList, &( pxCurrentTCB->xStateListItem ) ); + + /* If the task entering the blocked state was placed at the + * head of the list of blocked tasks then xNextTaskUnblockTime + * needs to be updated too. */ + if( xTimeToWake < xNextTaskUnblockTime ) + { + xNextTaskUnblockTime = xTimeToWake; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + } + #else /* INCLUDE_vTaskSuspend */ + { + /* Calculate the time at which the task should be woken if the event + * does not occur. This may overflow but this doesn't matter, the kernel + * will manage it correctly. */ + xTimeToWake = xConstTickCount + xTicksToWait; + + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); + + if( xTimeToWake < xConstTickCount ) + { + traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST(); + /* Wake time has overflowed. Place this item in the overflow list. */ + vListInsert( pxOverflowDelayedList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + traceMOVED_TASK_TO_DELAYED_LIST(); + /* The wake time has not overflowed, so the current block list is used. */ + vListInsert( pxDelayedList, &( pxCurrentTCB->xStateListItem ) ); + + /* If the task entering the blocked state was placed at the head of the + * list of blocked tasks then xNextTaskUnblockTime needs to be updated + * too. */ + if( xTimeToWake < xNextTaskUnblockTime ) + { + xNextTaskUnblockTime = xTimeToWake; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */ + ( void ) xCanBlockIndefinitely; + } + #endif /* INCLUDE_vTaskSuspend */ +} +/*-----------------------------------------------------------*/ + +#if ( portUSING_MPU_WRAPPERS == 1 ) + + xMPU_SETTINGS * xTaskGetMPUSettings( TaskHandle_t xTask ) + { + TCB_t * pxTCB; + + traceENTER_xTaskGetMPUSettings( xTask ); + + pxTCB = prvGetTCBFromHandle( xTask ); + + traceRETURN_xTaskGetMPUSettings( &( pxTCB->xMPUSettings ) ); + + return &( pxTCB->xMPUSettings ); + } + +#endif /* portUSING_MPU_WRAPPERS */ +/*-----------------------------------------------------------*/ + +/* Code below here allows additional code to be inserted into this source file, + * especially where access to file scope functions and data is needed (for example + * when performing module tests). */ + +#ifdef FREERTOS_MODULE_TEST + #include "tasks_test_access_functions.h" +#endif + + +#if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) + + #include "freertos_tasks_c_additions.h" + + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + static void freertos_tasks_c_additions_init( void ) + { + FREERTOS_TASKS_C_ADDITIONS_INIT(); + } + #endif + +#endif /* if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configKERNEL_PROVIDED_STATIC_MEMORY == 1 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) + +/* + * This is the kernel provided implementation of vApplicationGetIdleTaskMemory() + * to provide the memory that is used by the Idle task. It is used when + * configKERNEL_PROVIDED_STATIC_MEMORY is set to 1. The application can provide + * it's own implementation of vApplicationGetIdleTaskMemory by setting + * configKERNEL_PROVIDED_STATIC_MEMORY to 0 or leaving it undefined. + */ + void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, + StackType_t ** ppxIdleTaskStackBuffer, + configSTACK_DEPTH_TYPE * puxIdleTaskStackSize ) + { + static StaticTask_t xIdleTaskTCB; + static StackType_t uxIdleTaskStack[ configMINIMAL_STACK_SIZE ]; + + *ppxIdleTaskTCBBuffer = &( xIdleTaskTCB ); + *ppxIdleTaskStackBuffer = &( uxIdleTaskStack[ 0 ] ); + *puxIdleTaskStackSize = configMINIMAL_STACK_SIZE; + } + + #if ( configNUMBER_OF_CORES > 1 ) + + void vApplicationGetPassiveIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, + StackType_t ** ppxIdleTaskStackBuffer, + configSTACK_DEPTH_TYPE * puxIdleTaskStackSize, + BaseType_t xPassiveIdleTaskIndex ) + { + static StaticTask_t xIdleTaskTCBs[ configNUMBER_OF_CORES - 1 ]; + static StackType_t uxIdleTaskStacks[ configNUMBER_OF_CORES - 1 ][ configMINIMAL_STACK_SIZE ]; + + *ppxIdleTaskTCBBuffer = &( xIdleTaskTCBs[ xPassiveIdleTaskIndex ] ); + *ppxIdleTaskStackBuffer = &( uxIdleTaskStacks[ xPassiveIdleTaskIndex ][ 0 ] ); + *puxIdleTaskStackSize = configMINIMAL_STACK_SIZE; + } + + #endif /* #if ( configNUMBER_OF_CORES > 1 ) */ + +#endif /* #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configKERNEL_PROVIDED_STATIC_MEMORY == 1 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configKERNEL_PROVIDED_STATIC_MEMORY == 1 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) + +/* + * This is the kernel provided implementation of vApplicationGetTimerTaskMemory() + * to provide the memory that is used by the Timer service task. It is used when + * configKERNEL_PROVIDED_STATIC_MEMORY is set to 1. The application can provide + * it's own implementation of vApplicationGetTimerTaskMemory by setting + * configKERNEL_PROVIDED_STATIC_MEMORY to 0 or leaving it undefined. + */ + void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer, + StackType_t ** ppxTimerTaskStackBuffer, + configSTACK_DEPTH_TYPE * puxTimerTaskStackSize ) + { + static StaticTask_t xTimerTaskTCB; + static StackType_t uxTimerTaskStack[ configTIMER_TASK_STACK_DEPTH ]; + + *ppxTimerTaskTCBBuffer = &( xTimerTaskTCB ); + *ppxTimerTaskStackBuffer = &( uxTimerTaskStack[ 0 ] ); + *puxTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH; + } + +#endif /* #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configKERNEL_PROVIDED_STATIC_MEMORY == 1 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) */ +/*-----------------------------------------------------------*/ + +/* + * Reset the state in this file. This state is normally initialized at start up. + * This function must be called by the application before restarting the + * scheduler. + */ +void vTaskResetState( void ) +{ + BaseType_t xCoreID; + + /* Task control block. */ + #if ( configNUMBER_OF_CORES == 1 ) + { + pxCurrentTCB = NULL; + } + #endif /* #if ( configNUMBER_OF_CORES == 1 ) */ + + #if ( INCLUDE_vTaskDelete == 1 ) + { + uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U; + } + #endif /* #if ( INCLUDE_vTaskDelete == 1 ) */ + + #if ( configUSE_POSIX_ERRNO == 1 ) + { + FreeRTOS_errno = 0; + } + #endif /* #if ( configUSE_POSIX_ERRNO == 1 ) */ + + /* Other file private variables. */ + uxCurrentNumberOfTasks = ( UBaseType_t ) 0U; + xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; + uxTopReadyPriority = tskIDLE_PRIORITY; + xSchedulerRunning = pdFALSE; + xPendedTicks = ( TickType_t ) 0U; + + for( xCoreID = 0; xCoreID < configNUMBER_OF_CORES; xCoreID++ ) + { + xYieldPendings[ xCoreID ] = pdFALSE; + } + + xNumOfOverflows = ( BaseType_t ) 0; + uxTaskNumber = ( UBaseType_t ) 0U; + xNextTaskUnblockTime = ( TickType_t ) 0U; + + uxSchedulerSuspended = ( UBaseType_t ) 0U; + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + for( xCoreID = 0; xCoreID < configNUMBER_OF_CORES; xCoreID++ ) + { + ulTaskSwitchedInTime[ xCoreID ] = 0U; + ulTotalRunTime[ xCoreID ] = 0U; + } + } + #endif /* #if ( configGENERATE_RUN_TIME_STATS == 1 ) */ +} +/*-----------------------------------------------------------*/ diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/timers.c b/source/Middlewares/Third_Party/FreeRTOS/Source/timers.c index d614602c2..d499db2b9 100644 --- a/source/Middlewares/Third_Party/FreeRTOS/Source/timers.c +++ b/source/Middlewares/Third_Party/FreeRTOS/Source/timers.c @@ -1,1144 +1,1340 @@ -/* - * FreeRTOS Kernel V10.4.1 - * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * https://www.FreeRTOS.org - * https://github.com/FreeRTOS - * - */ - -/* Standard includes. */ -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining - * all the API functions to use the MPU wrappers. That should only be done when - * task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -#include "FreeRTOS.h" -#include "task.h" -#include "queue.h" -#include "timers.h" - -#if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 ) - #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available. -#endif - -/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified - * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined - * for the header files above, but not in this file, in order to generate the - * correct privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e9021 !e961 !e750. */ - - -/* This entire source file will be skipped if the application is not configured - * to include software timer functionality. This #if is closed at the very bottom - * of this file. If you want to include software timer functionality then ensure - * configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ -#if ( configUSE_TIMERS == 1 ) - -/* Misc definitions. */ - #define tmrNO_DELAY ( TickType_t ) 0U - -/* The name assigned to the timer service task. This can be overridden by - * defining trmTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */ - #ifndef configTIMER_SERVICE_TASK_NAME - #define configTIMER_SERVICE_TASK_NAME "Tmr Svc" - #endif - -/* Bit definitions used in the ucStatus member of a timer structure. */ - #define tmrSTATUS_IS_ACTIVE ( ( uint8_t ) 0x01 ) - #define tmrSTATUS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 0x02 ) - #define tmrSTATUS_IS_AUTORELOAD ( ( uint8_t ) 0x04 ) - -/* The definition of the timers themselves. */ - typedef struct tmrTimerControl /* The old naming convention is used to prevent breaking kernel aware debuggers. */ - { - const char * pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */ - TickType_t xTimerPeriodInTicks; /*<< How quickly and often the timer expires. */ - void * pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ - TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */ - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */ - #endif - uint8_t ucStatus; /*<< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */ - } xTIMER; - -/* The old xTIMER name is maintained above then typedefed to the new Timer_t - * name below to enable the use of older kernel aware debuggers. */ - typedef xTIMER Timer_t; - -/* The definition of messages that can be sent and received on the timer queue. - * Two types of message can be queued - messages that manipulate a software timer, - * and messages that request the execution of a non-timer related callback. The - * two message types are defined in two separate structures, xTimerParametersType - * and xCallbackParametersType respectively. */ - typedef struct tmrTimerParameters - { - TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */ - Timer_t * pxTimer; /*<< The timer to which the command will be applied. */ - } TimerParameter_t; - - - typedef struct tmrCallbackParameters - { - PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */ - void * pvParameter1; /* << The value that will be used as the callback functions first parameter. */ - uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */ - } CallbackParameters_t; - -/* The structure that contains the two message types, along with an identifier - * that is used to determine which message type is valid. */ - typedef struct tmrTimerQueueMessage - { - BaseType_t xMessageID; /*<< The command being sent to the timer service task. */ - union - { - TimerParameter_t xTimerParameters; - - /* Don't include xCallbackParameters if it is not going to be used as - * it makes the structure (and therefore the timer queue) larger. */ - #if ( INCLUDE_xTimerPendFunctionCall == 1 ) - CallbackParameters_t xCallbackParameters; - #endif /* INCLUDE_xTimerPendFunctionCall */ - } u; - } DaemonTaskMessage_t; - -/*lint -save -e956 A manual analysis and inspection has been used to determine - * which static variables must be declared volatile. */ - -/* The list in which active timers are stored. Timers are referenced in expire - * time order, with the nearest expiry time at the front of the list. Only the - * timer service task is allowed to access these lists. - * xActiveTimerList1 and xActiveTimerList2 could be at function scope but that - * breaks some kernel aware debuggers, and debuggers that reply on removing the - * static qualifier. */ - PRIVILEGED_DATA static List_t xActiveTimerList1; - PRIVILEGED_DATA static List_t xActiveTimerList2; - PRIVILEGED_DATA static List_t * pxCurrentTimerList; - PRIVILEGED_DATA static List_t * pxOverflowTimerList; - -/* A queue that is used to send commands to the timer service task. */ - PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL; - PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL; - -/*lint -restore */ - -/*-----------------------------------------------------------*/ - -/* - * Initialise the infrastructure used by the timer service task if it has not - * been initialised already. - */ - static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION; - -/* - * The timer service task (daemon). Timer functionality is controlled by this - * task. Other tasks communicate with the timer service task using the - * xTimerQueue queue. - */ - static portTASK_FUNCTION_PROTO( prvTimerTask, pvParameters ) PRIVILEGED_FUNCTION; - -/* - * Called by the timer service task to interpret and process a command it - * received on the timer queue. - */ - static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION; - -/* - * Insert the timer into either xActiveTimerList1, or xActiveTimerList2, - * depending on if the expire time causes a timer counter overflow. - */ - static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, - const TickType_t xNextExpiryTime, - const TickType_t xTimeNow, - const TickType_t xCommandTime ) PRIVILEGED_FUNCTION; - -/* - * An active timer has reached its expire time. Reload the timer if it is an - * auto-reload timer, then call its callback. - */ - static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, - const TickType_t xTimeNow ) PRIVILEGED_FUNCTION; - -/* - * The tick count has overflowed. Switch the timer lists after ensuring the - * current timer list does not still reference some timers. - */ - static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION; - -/* - * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE - * if a tick count overflow occurred since prvSampleTimeNow() was last called. - */ - static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION; - -/* - * If the timer list contains any active timers then return the expire time of - * the timer that will expire first and set *pxListWasEmpty to false. If the - * timer list does not contain any timers then return 0 and set *pxListWasEmpty - * to pdTRUE. - */ - static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION; - -/* - * If a timer has expired, process it. Otherwise, block the timer service task - * until either a timer does expire or a command is received. - */ - static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, - BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION; - -/* - * Called after a Timer_t structure has been allocated either statically or - * dynamically to fill in the structure's members. - */ - static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - Timer_t * pxNewTimer ) PRIVILEGED_FUNCTION; -/*-----------------------------------------------------------*/ - - BaseType_t xTimerCreateTimerTask( void ) - { - BaseType_t xReturn = pdFAIL; - - /* This function is called when the scheduler is started if - * configUSE_TIMERS is set to 1. Check that the infrastructure used by the - * timer service task has been created/initialised. If timers have already - * been created then the initialisation will already have been performed. */ - prvCheckForValidListAndQueue(); - - if( xTimerQueue != NULL ) - { - #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - StaticTask_t * pxTimerTaskTCBBuffer = NULL; - StackType_t * pxTimerTaskStackBuffer = NULL; - uint32_t ulTimerTaskStackSize; - - vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize ); - xTimerTaskHandle = xTaskCreateStatic( prvTimerTask, - configTIMER_SERVICE_TASK_NAME, - ulTimerTaskStackSize, - NULL, - ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, - pxTimerTaskStackBuffer, - pxTimerTaskTCBBuffer ); - - if( xTimerTaskHandle != NULL ) - { - xReturn = pdPASS; - } - } - #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ - { - xReturn = xTaskCreate( prvTimerTask, - configTIMER_SERVICE_TASK_NAME, - configTIMER_TASK_STACK_DEPTH, - NULL, - ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, - &xTimerTaskHandle ); - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - configASSERT( xReturn ); - return xReturn; - } -/*-----------------------------------------------------------*/ - - #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - - TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction ) - { - Timer_t * pxNewTimer; - - pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of Timer_t is always a pointer to the timer's mame. */ - - if( pxNewTimer != NULL ) - { - /* Status is thus far zero as the timer is not created statically - * and has not been started. The auto-reload bit may get set in - * prvInitialiseNewTimer. */ - pxNewTimer->ucStatus = 0x00; - prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); - } - - return pxNewTimer; - } - - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - - #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - - TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - StaticTimer_t * pxTimerBuffer ) - { - Timer_t * pxNewTimer; - - #if ( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - * variable of type StaticTimer_t equals the size of the real timer - * structure. */ - volatile size_t xSize = sizeof( StaticTimer_t ); - configASSERT( xSize == sizeof( Timer_t ) ); - ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ - } - #endif /* configASSERT_DEFINED */ - - /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ - configASSERT( pxTimerBuffer ); - pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */ - - if( pxNewTimer != NULL ) - { - /* Timers can be created statically or dynamically so note this - * timer was created statically in case it is later deleted. The - * auto-reload bit may get set in prvInitialiseNewTimer(). */ - pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED; - - prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); - } - - return pxNewTimer; - } - - #endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - - static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - Timer_t * pxNewTimer ) - { - /* 0 is not a valid value for xTimerPeriodInTicks. */ - configASSERT( ( xTimerPeriodInTicks > 0 ) ); - - if( pxNewTimer != NULL ) - { - /* Ensure the infrastructure used by the timer service task has been - * created/initialised. */ - prvCheckForValidListAndQueue(); - - /* Initialise the timer structure members using the function - * parameters. */ - pxNewTimer->pcTimerName = pcTimerName; - pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; - pxNewTimer->pvTimerID = pvTimerID; - pxNewTimer->pxCallbackFunction = pxCallbackFunction; - vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); - - if( uxAutoReload != pdFALSE ) - { - pxNewTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; - } - - traceTIMER_CREATE( pxNewTimer ); - } - } -/*-----------------------------------------------------------*/ - - BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, - const BaseType_t xCommandID, - const TickType_t xOptionalValue, - BaseType_t * const pxHigherPriorityTaskWoken, - const TickType_t xTicksToWait ) - { - BaseType_t xReturn = pdFAIL; - DaemonTaskMessage_t xMessage; - - configASSERT( xTimer ); - - /* Send a message to the timer service task to perform a particular action - * on a particular timer definition. */ - if( xTimerQueue != NULL ) - { - /* Send a command to the timer service task to start the xTimer timer. */ - xMessage.xMessageID = xCommandID; - xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; - xMessage.u.xTimerParameters.pxTimer = xTimer; - - if( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) - { - if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) - { - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); - } - else - { - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY ); - } - } - else - { - xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); - } - - traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xReturn; - } -/*-----------------------------------------------------------*/ - - TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) - { - /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been - * started, then xTimerTaskHandle will be NULL. */ - configASSERT( ( xTimerTaskHandle != NULL ) ); - return xTimerTaskHandle; - } -/*-----------------------------------------------------------*/ - - TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) - { - Timer_t * pxTimer = xTimer; - - configASSERT( xTimer ); - return pxTimer->xTimerPeriodInTicks; - } -/*-----------------------------------------------------------*/ - - void vTimerSetReloadMode( TimerHandle_t xTimer, - const UBaseType_t uxAutoReload ) - { - Timer_t * pxTimer = xTimer; - - configASSERT( xTimer ); - taskENTER_CRITICAL(); - { - if( uxAutoReload != pdFALSE ) - { - pxTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; - } - else - { - pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD; - } - } - taskEXIT_CRITICAL(); - } -/*-----------------------------------------------------------*/ - - UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ) - { - Timer_t * pxTimer = xTimer; - UBaseType_t uxReturn; - - configASSERT( xTimer ); - taskENTER_CRITICAL(); - { - if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) == 0 ) - { - /* Not an auto-reload timer. */ - uxReturn = ( UBaseType_t ) pdFALSE; - } - else - { - /* Is an auto-reload timer. */ - uxReturn = ( UBaseType_t ) pdTRUE; - } - } - taskEXIT_CRITICAL(); - - return uxReturn; - } -/*-----------------------------------------------------------*/ - - TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) - { - Timer_t * pxTimer = xTimer; - TickType_t xReturn; - - configASSERT( xTimer ); - xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) ); - return xReturn; - } -/*-----------------------------------------------------------*/ - - const char * pcTimerGetName( TimerHandle_t xTimer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - Timer_t * pxTimer = xTimer; - - configASSERT( xTimer ); - return pxTimer->pcTimerName; - } -/*-----------------------------------------------------------*/ - - static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, - const TickType_t xTimeNow ) - { - BaseType_t xResult; - Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - - /* Remove the timer from the list of active timers. A check has already - * been performed to ensure the list is not empty. */ - - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - traceTIMER_EXPIRED( pxTimer ); - - /* If the timer is an auto-reload timer then calculate the next - * expiry time and re-insert the timer in the list of active timers. */ - if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) - { - /* The timer is inserted into a list using a time relative to anything - * other than the current time. It will therefore be inserted into the - * correct list relative to the time this task thinks it is now. */ - if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE ) - { - /* The timer expired before it was added to the active timer - * list. Reload it now. */ - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - mtCOVERAGE_TEST_MARKER(); - } - - /* Call the timer callback. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); - } -/*-----------------------------------------------------------*/ - - static portTASK_FUNCTION( prvTimerTask, pvParameters ) - { - TickType_t xNextExpireTime; - BaseType_t xListWasEmpty; - - /* Just to avoid compiler warnings. */ - ( void ) pvParameters; - - #if ( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 ) - { - extern void vApplicationDaemonTaskStartupHook( void ); - - /* Allow the application writer to execute some code in the context of - * this task at the point the task starts executing. This is useful if the - * application includes initialisation code that would benefit from - * executing after the scheduler has been started. */ - vApplicationDaemonTaskStartupHook(); - } - #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */ - - for( ; ; ) - { - /* Query the timers list to see if it contains any timers, and if so, - * obtain the time at which the next timer will expire. */ - xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); - - /* If a timer has expired, process it. Otherwise, block this task - * until either a timer does expire, or a command is received. */ - prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); - - /* Empty the command queue. */ - prvProcessReceivedCommands(); - } - } -/*-----------------------------------------------------------*/ - - static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, - BaseType_t xListWasEmpty ) - { - TickType_t xTimeNow; - BaseType_t xTimerListsWereSwitched; - - vTaskSuspendAll(); - { - /* Obtain the time now to make an assessment as to whether the timer - * has expired or not. If obtaining the time causes the lists to switch - * then don't process this timer as any timers that remained in the list - * when the lists were switched will have been processed within the - * prvSampleTimeNow() function. */ - xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); - - if( xTimerListsWereSwitched == pdFALSE ) - { - /* The tick count has not overflowed, has the timer expired? */ - if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) - { - ( void ) xTaskResumeAll(); - prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); - } - else - { - /* The tick count has not overflowed, and the next expire - * time has not been reached yet. This task should therefore - * block to wait for the next expire time or a command to be - * received - whichever comes first. The following line cannot - * be reached unless xNextExpireTime > xTimeNow, except in the - * case when the current timer list is empty. */ - if( xListWasEmpty != pdFALSE ) - { - /* The current timer list is empty - is the overflow list - * also empty? */ - xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList ); - } - - vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty ); - - if( xTaskResumeAll() == pdFALSE ) - { - /* Yield to wait for either a command to arrive, or the - * block time to expire. If a command arrived between the - * critical section being exited and this yield then the yield - * will not cause the task to block. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - ( void ) xTaskResumeAll(); - } - } - } -/*-----------------------------------------------------------*/ - - static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) - { - TickType_t xNextExpireTime; - - /* Timers are listed in expiry time order, with the head of the list - * referencing the task that will expire first. Obtain the time at which - * the timer with the nearest expiry time will expire. If there are no - * active timers then just set the next expire time to 0. That will cause - * this task to unblock when the tick count overflows, at which point the - * timer lists will be switched and the next expiry time can be - * re-assessed. */ - *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); - - if( *pxListWasEmpty == pdFALSE ) - { - xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); - } - else - { - /* Ensure the task unblocks when the tick count rolls over. */ - xNextExpireTime = ( TickType_t ) 0U; - } - - return xNextExpireTime; - } -/*-----------------------------------------------------------*/ - - static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) - { - TickType_t xTimeNow; - PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */ - - xTimeNow = xTaskGetTickCount(); - - if( xTimeNow < xLastTime ) - { - prvSwitchTimerLists(); - *pxTimerListsWereSwitched = pdTRUE; - } - else - { - *pxTimerListsWereSwitched = pdFALSE; - } - - xLastTime = xTimeNow; - - return xTimeNow; - } -/*-----------------------------------------------------------*/ - - static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, - const TickType_t xNextExpiryTime, - const TickType_t xTimeNow, - const TickType_t xCommandTime ) - { - BaseType_t xProcessTimerNow = pdFALSE; - - listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); - listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); - - if( xNextExpiryTime <= xTimeNow ) - { - /* Has the expiry time elapsed between the command to start/reset a - * timer was issued, and the time the command was processed? */ - if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - { - /* The time between a command being issued and the command being - * processed actually exceeds the timers period. */ - xProcessTimerNow = pdTRUE; - } - else - { - vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); - } - } - else - { - if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) - { - /* If, since the command was issued, the tick count has overflowed - * but the expiry time has not, then the timer must have already passed - * its expiry time and should be processed immediately. */ - xProcessTimerNow = pdTRUE; - } - else - { - vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); - } - } - - return xProcessTimerNow; - } -/*-----------------------------------------------------------*/ - - static void prvProcessReceivedCommands( void ) - { - DaemonTaskMessage_t xMessage; - Timer_t * pxTimer; - BaseType_t xTimerListsWereSwitched, xResult; - TickType_t xTimeNow; - - while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */ - { - #if ( INCLUDE_xTimerPendFunctionCall == 1 ) - { - /* Negative commands are pended function calls rather than timer - * commands. */ - if( xMessage.xMessageID < ( BaseType_t ) 0 ) - { - const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters ); - - /* The timer uses the xCallbackParameters member to request a - * callback be executed. Check the callback is not NULL. */ - configASSERT( pxCallback ); - - /* Call the function. */ - pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* INCLUDE_xTimerPendFunctionCall */ - - /* Commands that are positive are timer commands rather than pended - * function calls. */ - if( xMessage.xMessageID >= ( BaseType_t ) 0 ) - { - /* The messages uses the xTimerParameters member to work on a - * software timer. */ - pxTimer = xMessage.u.xTimerParameters.pxTimer; - - if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */ - { - /* The timer is in a list, remove it. */ - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue ); - - /* In this case the xTimerListsWereSwitched parameter is not used, but - * it must be present in the function call. prvSampleTimeNow() must be - * called after the message is received from xTimerQueue so there is no - * possibility of a higher priority task adding a message to the message - * queue with a time that is ahead of the timer daemon task (because it - * pre-empted the timer daemon task after the xTimeNow value was set). */ - xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); - - switch( xMessage.xMessageID ) - { - case tmrCOMMAND_START: - case tmrCOMMAND_START_FROM_ISR: - case tmrCOMMAND_RESET: - case tmrCOMMAND_RESET_FROM_ISR: - case tmrCOMMAND_START_DONT_TRACE: - /* Start or restart a timer. */ - pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; - - if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE ) - { - /* The timer expired before it was added to the active - * timer list. Process it now. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); - traceTIMER_EXPIRED( pxTimer ); - - if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) - { - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - break; - - case tmrCOMMAND_STOP: - case tmrCOMMAND_STOP_FROM_ISR: - /* The timer has already been removed from the active list. */ - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - break; - - case tmrCOMMAND_CHANGE_PERIOD: - case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR: - pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; - pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue; - configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); - - /* The new period does not really have a reference, and can - * be longer or shorter than the old one. The command time is - * therefore set to the current time, and as the period cannot - * be zero the next expiry time can only be in the future, - * meaning (unlike for the xTimerStart() case above) there is - * no fail case that needs to be handled here. */ - ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); - break; - - case tmrCOMMAND_DELETE: - #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* The timer has already been removed from the active list, - * just free up the memory if the memory was dynamically - * allocated. */ - if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 ) - { - vPortFree( pxTimer ); - } - else - { - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - } - } - #else /* if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) */ - { - /* If dynamic allocation is not enabled, the memory - * could not have been dynamically allocated. So there is - * no need to free the memory - just mark the timer as - * "not active". */ - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - break; - - default: - /* Don't expect to get here. */ - break; - } - } - } - } -/*-----------------------------------------------------------*/ - - static void prvSwitchTimerLists( void ) - { - TickType_t xNextExpireTime, xReloadTime; - List_t * pxTemp; - Timer_t * pxTimer; - BaseType_t xResult; - - /* The tick count has overflowed. The timer lists must be switched. - * If there are any timers still referenced from the current timer list - * then they must have expired and should be processed before the lists - * are switched. */ - while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) - { - xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); - - /* Remove the timer from the list. */ - pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - traceTIMER_EXPIRED( pxTimer ); - - /* Execute its callback, then send a command to restart the timer if - * it is an auto-reload timer. It cannot be restarted here as the lists - * have not yet been switched. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); - - if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) - { - /* Calculate the reload value, and if the reload value results in - * the timer going into the same timer list then it has already expired - * and the timer should be re-inserted into the current list so it is - * processed again within this loop. Otherwise a command should be sent - * to restart the timer to ensure it is only inserted into a list after - * the lists have been swapped. */ - xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ); - - if( xReloadTime > xNextExpireTime ) - { - listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime ); - listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); - vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); - } - else - { - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - pxTemp = pxCurrentTimerList; - pxCurrentTimerList = pxOverflowTimerList; - pxOverflowTimerList = pxTemp; - } -/*-----------------------------------------------------------*/ - - static void prvCheckForValidListAndQueue( void ) - { - /* Check that the list from which active timers are referenced, and the - * queue used to communicate with the timer service, have been - * initialised. */ - taskENTER_CRITICAL(); - { - if( xTimerQueue == NULL ) - { - vListInitialise( &xActiveTimerList1 ); - vListInitialise( &xActiveTimerList2 ); - pxCurrentTimerList = &xActiveTimerList1; - pxOverflowTimerList = &xActiveTimerList2; - - #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* The timer queue is allocated statically in case - * configSUPPORT_DYNAMIC_ALLOCATION is 0. */ - PRIVILEGED_DATA static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ - PRIVILEGED_DATA static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ - - xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); - } - #else - { - xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) ); - } - #endif /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ - - #if ( configQUEUE_REGISTRY_SIZE > 0 ) - { - if( xTimerQueue != NULL ) - { - vQueueAddToRegistry( xTimerQueue, "TmrQ" ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configQUEUE_REGISTRY_SIZE */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - } -/*-----------------------------------------------------------*/ - - BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) - { - BaseType_t xReturn; - Timer_t * pxTimer = xTimer; - - configASSERT( xTimer ); - - /* Is the timer in the list of active timers? */ - taskENTER_CRITICAL(); - { - if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0 ) - { - xReturn = pdFALSE; - } - else - { - xReturn = pdTRUE; - } - } - taskEXIT_CRITICAL(); - - return xReturn; - } /*lint !e818 Can't be pointer to const due to the typedef. */ -/*-----------------------------------------------------------*/ - - void * pvTimerGetTimerID( const TimerHandle_t xTimer ) - { - Timer_t * const pxTimer = xTimer; - void * pvReturn; - - configASSERT( xTimer ); - - taskENTER_CRITICAL(); - { - pvReturn = pxTimer->pvTimerID; - } - taskEXIT_CRITICAL(); - - return pvReturn; - } -/*-----------------------------------------------------------*/ - - void vTimerSetTimerID( TimerHandle_t xTimer, - void * pvNewID ) - { - Timer_t * const pxTimer = xTimer; - - configASSERT( xTimer ); - - taskENTER_CRITICAL(); - { - pxTimer->pvTimerID = pvNewID; - } - taskEXIT_CRITICAL(); - } -/*-----------------------------------------------------------*/ - - #if ( INCLUDE_xTimerPendFunctionCall == 1 ) - - BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, - void * pvParameter1, - uint32_t ulParameter2, - BaseType_t * pxHigherPriorityTaskWoken ) - { - DaemonTaskMessage_t xMessage; - BaseType_t xReturn; - - /* Complete the message with the function parameters and post it to the - * daemon task. */ - xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; - xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; - xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; - xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; - - xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); - - tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); - - return xReturn; - } - - #endif /* INCLUDE_xTimerPendFunctionCall */ -/*-----------------------------------------------------------*/ - - #if ( INCLUDE_xTimerPendFunctionCall == 1 ) - - BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, - void * pvParameter1, - uint32_t ulParameter2, - TickType_t xTicksToWait ) - { - DaemonTaskMessage_t xMessage; - BaseType_t xReturn; - - /* This function can only be called after a timer has been created or - * after the scheduler has been started because, until then, the timer - * queue does not exist. */ - configASSERT( xTimerQueue ); - - /* Complete the message with the function parameters and post it to the - * daemon task. */ - xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; - xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; - xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; - xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; - - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); - - tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); - - return xReturn; - } - - #endif /* INCLUDE_xTimerPendFunctionCall */ -/*-----------------------------------------------------------*/ - - #if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) - { - return ( ( Timer_t * ) xTimer )->uxTimerNumber; - } - - #endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - - #if ( configUSE_TRACE_FACILITY == 1 ) - - void vTimerSetTimerNumber( TimerHandle_t xTimer, - UBaseType_t uxTimerNumber ) - { - ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; - } - - #endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -/* This entire source file will be skipped if the application is not configured - * to include software timer functionality. If you want to include software timer - * functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ -#endif /* configUSE_TIMERS == 1 */ +/* + * FreeRTOS Kernel V11.1.0 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "timers.h" + +#if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 ) + #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available. +#endif + +/* The MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + + +/* This entire source file will be skipped if the application is not configured + * to include software timer functionality. This #if is closed at the very bottom + * of this file. If you want to include software timer functionality then ensure + * configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ +#if ( configUSE_TIMERS == 1 ) + +/* Misc definitions. */ + #define tmrNO_DELAY ( ( TickType_t ) 0U ) + #define tmrMAX_TIME_BEFORE_OVERFLOW ( ( TickType_t ) -1 ) + +/* The name assigned to the timer service task. This can be overridden by + * defining configTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */ + #ifndef configTIMER_SERVICE_TASK_NAME + #define configTIMER_SERVICE_TASK_NAME "Tmr Svc" + #endif + + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + +/* The core affinity assigned to the timer service task on SMP systems. + * This can be overridden by defining configTIMER_SERVICE_TASK_CORE_AFFINITY in FreeRTOSConfig.h. */ + #ifndef configTIMER_SERVICE_TASK_CORE_AFFINITY + #define configTIMER_SERVICE_TASK_CORE_AFFINITY tskNO_AFFINITY + #endif + #endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) */ + +/* Bit definitions used in the ucStatus member of a timer structure. */ + #define tmrSTATUS_IS_ACTIVE ( 0x01U ) + #define tmrSTATUS_IS_STATICALLY_ALLOCATED ( 0x02U ) + #define tmrSTATUS_IS_AUTORELOAD ( 0x04U ) + +/* The definition of the timers themselves. */ + typedef struct tmrTimerControl /* The old naming convention is used to prevent breaking kernel aware debuggers. */ + { + const char * pcTimerName; /**< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ + ListItem_t xTimerListItem; /**< Standard linked list item as used by all kernel features for event management. */ + TickType_t xTimerPeriodInTicks; /**< How quickly and often the timer expires. */ + void * pvTimerID; /**< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ + portTIMER_CALLBACK_ATTRIBUTE TimerCallbackFunction_t pxCallbackFunction; /**< The function that will be called when the timer expires. */ + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTimerNumber; /**< An ID assigned by trace tools such as FreeRTOS+Trace */ + #endif + uint8_t ucStatus; /**< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */ + } xTIMER; + +/* The old xTIMER name is maintained above then typedefed to the new Timer_t + * name below to enable the use of older kernel aware debuggers. */ + typedef xTIMER Timer_t; + +/* The definition of messages that can be sent and received on the timer queue. + * Two types of message can be queued - messages that manipulate a software timer, + * and messages that request the execution of a non-timer related callback. The + * two message types are defined in two separate structures, xTimerParametersType + * and xCallbackParametersType respectively. */ + typedef struct tmrTimerParameters + { + TickType_t xMessageValue; /**< An optional value used by a subset of commands, for example, when changing the period of a timer. */ + Timer_t * pxTimer; /**< The timer to which the command will be applied. */ + } TimerParameter_t; + + + typedef struct tmrCallbackParameters + { + portTIMER_CALLBACK_ATTRIBUTE + PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */ + void * pvParameter1; /* << The value that will be used as the callback functions first parameter. */ + uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */ + } CallbackParameters_t; + +/* The structure that contains the two message types, along with an identifier + * that is used to determine which message type is valid. */ + typedef struct tmrTimerQueueMessage + { + BaseType_t xMessageID; /**< The command being sent to the timer service task. */ + union + { + TimerParameter_t xTimerParameters; + + /* Don't include xCallbackParameters if it is not going to be used as + * it makes the structure (and therefore the timer queue) larger. */ + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + CallbackParameters_t xCallbackParameters; + #endif /* INCLUDE_xTimerPendFunctionCall */ + } u; + } DaemonTaskMessage_t; + +/* The list in which active timers are stored. Timers are referenced in expire + * time order, with the nearest expiry time at the front of the list. Only the + * timer service task is allowed to access these lists. + * xActiveTimerList1 and xActiveTimerList2 could be at function scope but that + * breaks some kernel aware debuggers, and debuggers that reply on removing the + * static qualifier. */ + PRIVILEGED_DATA static List_t xActiveTimerList1; + PRIVILEGED_DATA static List_t xActiveTimerList2; + PRIVILEGED_DATA static List_t * pxCurrentTimerList; + PRIVILEGED_DATA static List_t * pxOverflowTimerList; + +/* A queue that is used to send commands to the timer service task. */ + PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL; + PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL; + +/*-----------------------------------------------------------*/ + +/* + * Initialise the infrastructure used by the timer service task if it has not + * been initialised already. + */ + static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION; + +/* + * The timer service task (daemon). Timer functionality is controlled by this + * task. Other tasks communicate with the timer service task using the + * xTimerQueue queue. + */ + static portTASK_FUNCTION_PROTO( prvTimerTask, pvParameters ) PRIVILEGED_FUNCTION; + +/* + * Called by the timer service task to interpret and process a command it + * received on the timer queue. + */ + static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION; + +/* + * Insert the timer into either xActiveTimerList1, or xActiveTimerList2, + * depending on if the expire time causes a timer counter overflow. + */ + static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, + const TickType_t xNextExpiryTime, + const TickType_t xTimeNow, + const TickType_t xCommandTime ) PRIVILEGED_FUNCTION; + +/* + * Reload the specified auto-reload timer. If the reloading is backlogged, + * clear the backlog, calling the callback for each additional reload. When + * this function returns, the next expiry time is after xTimeNow. + */ + static void prvReloadTimer( Timer_t * const pxTimer, + TickType_t xExpiredTime, + const TickType_t xTimeNow ) PRIVILEGED_FUNCTION; + +/* + * An active timer has reached its expire time. Reload the timer if it is an + * auto-reload timer, then call its callback. + */ + static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, + const TickType_t xTimeNow ) PRIVILEGED_FUNCTION; + +/* + * The tick count has overflowed. Switch the timer lists after ensuring the + * current timer list does not still reference some timers. + */ + static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION; + +/* + * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE + * if a tick count overflow occurred since prvSampleTimeNow() was last called. + */ + static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION; + +/* + * If the timer list contains any active timers then return the expire time of + * the timer that will expire first and set *pxListWasEmpty to false. If the + * timer list does not contain any timers then return 0 and set *pxListWasEmpty + * to pdTRUE. + */ + static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION; + +/* + * If a timer has expired, process it. Otherwise, block the timer service task + * until either a timer does expire or a command is received. + */ + static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, + BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION; + +/* + * Called after a Timer_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ + static void prvInitialiseNewTimer( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const BaseType_t xAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t * pxNewTimer ) PRIVILEGED_FUNCTION; +/*-----------------------------------------------------------*/ + + BaseType_t xTimerCreateTimerTask( void ) + { + BaseType_t xReturn = pdFAIL; + + traceENTER_xTimerCreateTimerTask(); + + /* This function is called when the scheduler is started if + * configUSE_TIMERS is set to 1. Check that the infrastructure used by the + * timer service task has been created/initialised. If timers have already + * been created then the initialisation will already have been performed. */ + prvCheckForValidListAndQueue(); + + if( xTimerQueue != NULL ) + { + #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) + { + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t * pxTimerTaskTCBBuffer = NULL; + StackType_t * pxTimerTaskStackBuffer = NULL; + configSTACK_DEPTH_TYPE uxTimerTaskStackSize; + + vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &uxTimerTaskStackSize ); + xTimerTaskHandle = xTaskCreateStaticAffinitySet( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + uxTimerTaskStackSize, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + pxTimerTaskStackBuffer, + pxTimerTaskTCBBuffer, + configTIMER_SERVICE_TASK_CORE_AFFINITY ); + + if( xTimerTaskHandle != NULL ) + { + xReturn = pdPASS; + } + } + #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + { + xReturn = xTaskCreateAffinitySet( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + configTIMER_TASK_STACK_DEPTH, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + configTIMER_SERVICE_TASK_CORE_AFFINITY, + &xTimerTaskHandle ); + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + } + #else /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) */ + { + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t * pxTimerTaskTCBBuffer = NULL; + StackType_t * pxTimerTaskStackBuffer = NULL; + configSTACK_DEPTH_TYPE uxTimerTaskStackSize; + + vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &uxTimerTaskStackSize ); + xTimerTaskHandle = xTaskCreateStatic( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + uxTimerTaskStackSize, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + pxTimerTaskStackBuffer, + pxTimerTaskTCBBuffer ); + + if( xTimerTaskHandle != NULL ) + { + xReturn = pdPASS; + } + } + #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + { + xReturn = xTaskCreate( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + configTIMER_TASK_STACK_DEPTH, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + &xTimerTaskHandle ); + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + } + #endif /* #if ( ( configNUMBER_OF_CORES > 1 ) && ( configUSE_CORE_AFFINITY == 1 ) ) */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + configASSERT( xReturn ); + + traceRETURN_xTimerCreateTimerTask( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + TimerHandle_t xTimerCreate( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const BaseType_t xAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) + { + Timer_t * pxNewTimer; + + traceENTER_xTimerCreate( pcTimerName, xTimerPeriodInTicks, xAutoReload, pvTimerID, pxCallbackFunction ); + + /* MISRA Ref 11.5.1 [Malloc memory assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); + + if( pxNewTimer != NULL ) + { + /* Status is thus far zero as the timer is not created statically + * and has not been started. The auto-reload bit may get set in + * prvInitialiseNewTimer. */ + pxNewTimer->ucStatus = 0x00; + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, xAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } + + traceRETURN_xTimerCreate( pxNewTimer ); + + return pxNewTimer; + } + + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const BaseType_t xAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t * pxTimerBuffer ) + { + Timer_t * pxNewTimer; + + traceENTER_xTimerCreateStatic( pcTimerName, xTimerPeriodInTicks, xAutoReload, pvTimerID, pxCallbackFunction, pxTimerBuffer ); + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticTimer_t equals the size of the real timer + * structure. */ + volatile size_t xSize = sizeof( StaticTimer_t ); + configASSERT( xSize == sizeof( Timer_t ) ); + ( void ) xSize; /* Prevent unused variable warning when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ + + /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ + configASSERT( pxTimerBuffer ); + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + pxNewTimer = ( Timer_t * ) pxTimerBuffer; + + if( pxNewTimer != NULL ) + { + /* Timers can be created statically or dynamically so note this + * timer was created statically in case it is later deleted. The + * auto-reload bit may get set in prvInitialiseNewTimer(). */ + pxNewTimer->ucStatus = ( uint8_t ) tmrSTATUS_IS_STATICALLY_ALLOCATED; + + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, xAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } + + traceRETURN_xTimerCreateStatic( pxNewTimer ); + + return pxNewTimer; + } + + #endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + + static void prvInitialiseNewTimer( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const BaseType_t xAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t * pxNewTimer ) + { + /* 0 is not a valid value for xTimerPeriodInTicks. */ + configASSERT( ( xTimerPeriodInTicks > 0 ) ); + + /* Ensure the infrastructure used by the timer service task has been + * created/initialised. */ + prvCheckForValidListAndQueue(); + + /* Initialise the timer structure members using the function + * parameters. */ + pxNewTimer->pcTimerName = pcTimerName; + pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; + pxNewTimer->pvTimerID = pvTimerID; + pxNewTimer->pxCallbackFunction = pxCallbackFunction; + vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); + + if( xAutoReload != pdFALSE ) + { + pxNewTimer->ucStatus |= ( uint8_t ) tmrSTATUS_IS_AUTORELOAD; + } + + traceTIMER_CREATE( pxNewTimer ); + } +/*-----------------------------------------------------------*/ + + BaseType_t xTimerGenericCommandFromTask( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) + { + BaseType_t xReturn = pdFAIL; + DaemonTaskMessage_t xMessage; + + ( void ) pxHigherPriorityTaskWoken; + + traceENTER_xTimerGenericCommandFromTask( xTimer, xCommandID, xOptionalValue, pxHigherPriorityTaskWoken, xTicksToWait ); + + configASSERT( xTimer ); + + /* Send a message to the timer service task to perform a particular action + * on a particular timer definition. */ + if( xTimerQueue != NULL ) + { + /* Send a command to the timer service task to start the xTimer timer. */ + xMessage.xMessageID = xCommandID; + xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; + xMessage.u.xTimerParameters.pxTimer = xTimer; + + configASSERT( xCommandID < tmrFIRST_FROM_ISR_COMMAND ); + + if( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) + { + if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) + { + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + } + else + { + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY ); + } + } + + traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xTimerGenericCommandFromTask( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + + BaseType_t xTimerGenericCommandFromISR( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) + { + BaseType_t xReturn = pdFAIL; + DaemonTaskMessage_t xMessage; + + ( void ) xTicksToWait; + + traceENTER_xTimerGenericCommandFromISR( xTimer, xCommandID, xOptionalValue, pxHigherPriorityTaskWoken, xTicksToWait ); + + configASSERT( xTimer ); + + /* Send a message to the timer service task to perform a particular action + * on a particular timer definition. */ + if( xTimerQueue != NULL ) + { + /* Send a command to the timer service task to start the xTimer timer. */ + xMessage.xMessageID = xCommandID; + xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; + xMessage.u.xTimerParameters.pxTimer = xTimer; + + configASSERT( xCommandID >= tmrFIRST_FROM_ISR_COMMAND ); + + if( xCommandID >= tmrFIRST_FROM_ISR_COMMAND ) + { + xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + } + + traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceRETURN_xTimerGenericCommandFromISR( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + + TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) + { + traceENTER_xTimerGetTimerDaemonTaskHandle(); + + /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been + * started, then xTimerTaskHandle will be NULL. */ + configASSERT( ( xTimerTaskHandle != NULL ) ); + + traceRETURN_xTimerGetTimerDaemonTaskHandle( xTimerTaskHandle ); + + return xTimerTaskHandle; + } +/*-----------------------------------------------------------*/ + + TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) + { + Timer_t * pxTimer = xTimer; + + traceENTER_xTimerGetPeriod( xTimer ); + + configASSERT( xTimer ); + + traceRETURN_xTimerGetPeriod( pxTimer->xTimerPeriodInTicks ); + + return pxTimer->xTimerPeriodInTicks; + } +/*-----------------------------------------------------------*/ + + void vTimerSetReloadMode( TimerHandle_t xTimer, + const BaseType_t xAutoReload ) + { + Timer_t * pxTimer = xTimer; + + traceENTER_vTimerSetReloadMode( xTimer, xAutoReload ); + + configASSERT( xTimer ); + taskENTER_CRITICAL(); + { + if( xAutoReload != pdFALSE ) + { + pxTimer->ucStatus |= ( uint8_t ) tmrSTATUS_IS_AUTORELOAD; + } + else + { + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_AUTORELOAD ); + } + } + taskEXIT_CRITICAL(); + + traceRETURN_vTimerSetReloadMode(); + } +/*-----------------------------------------------------------*/ + + BaseType_t xTimerGetReloadMode( TimerHandle_t xTimer ) + { + Timer_t * pxTimer = xTimer; + BaseType_t xReturn; + + traceENTER_xTimerGetReloadMode( xTimer ); + + configASSERT( xTimer ); + taskENTER_CRITICAL(); + { + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) == 0U ) + { + /* Not an auto-reload timer. */ + xReturn = pdFALSE; + } + else + { + /* Is an auto-reload timer. */ + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); + + traceRETURN_xTimerGetReloadMode( xReturn ); + + return xReturn; + } + + UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ) + { + UBaseType_t uxReturn; + + traceENTER_uxTimerGetReloadMode( xTimer ); + + uxReturn = ( UBaseType_t ) xTimerGetReloadMode( xTimer ); + + traceRETURN_uxTimerGetReloadMode( uxReturn ); + + return uxReturn; + } +/*-----------------------------------------------------------*/ + + TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) + { + Timer_t * pxTimer = xTimer; + TickType_t xReturn; + + traceENTER_xTimerGetExpiryTime( xTimer ); + + configASSERT( xTimer ); + xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) ); + + traceRETURN_xTimerGetExpiryTime( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + BaseType_t xTimerGetStaticBuffer( TimerHandle_t xTimer, + StaticTimer_t ** ppxTimerBuffer ) + { + BaseType_t xReturn; + Timer_t * pxTimer = xTimer; + + traceENTER_xTimerGetStaticBuffer( xTimer, ppxTimerBuffer ); + + configASSERT( ppxTimerBuffer != NULL ); + + if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) != 0U ) + { + /* MISRA Ref 11.3.1 [Misaligned access] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-113 */ + /* coverity[misra_c_2012_rule_11_3_violation] */ + *ppxTimerBuffer = ( StaticTimer_t * ) pxTimer; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + traceRETURN_xTimerGetStaticBuffer( xReturn ); + + return xReturn; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + + const char * pcTimerGetName( TimerHandle_t xTimer ) + { + Timer_t * pxTimer = xTimer; + + traceENTER_pcTimerGetName( xTimer ); + + configASSERT( xTimer ); + + traceRETURN_pcTimerGetName( pxTimer->pcTimerName ); + + return pxTimer->pcTimerName; + } +/*-----------------------------------------------------------*/ + + static void prvReloadTimer( Timer_t * const pxTimer, + TickType_t xExpiredTime, + const TickType_t xTimeNow ) + { + /* Insert the timer into the appropriate list for the next expiry time. + * If the next expiry time has already passed, advance the expiry time, + * call the callback function, and try again. */ + while( prvInsertTimerInActiveList( pxTimer, ( xExpiredTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xExpiredTime ) != pdFALSE ) + { + /* Advance the expiry time. */ + xExpiredTime += pxTimer->xTimerPeriodInTicks; + + /* Call the timer callback. */ + traceTIMER_EXPIRED( pxTimer ); + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + } + } +/*-----------------------------------------------------------*/ + + static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, + const TickType_t xTimeNow ) + { + /* MISRA Ref 11.5.3 [Void pointer assignment] */ + /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */ + /* coverity[misra_c_2012_rule_11_5_violation] */ + Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); + + /* Remove the timer from the list of active timers. A check has already + * been performed to ensure the list is not empty. */ + + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + + /* If the timer is an auto-reload timer then calculate the next + * expiry time and re-insert the timer in the list of active timers. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0U ) + { + prvReloadTimer( pxTimer, xNextExpireTime, xTimeNow ); + } + else + { + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE ); + } + + /* Call the timer callback. */ + traceTIMER_EXPIRED( pxTimer ); + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + } +/*-----------------------------------------------------------*/ + + static portTASK_FUNCTION( prvTimerTask, pvParameters ) + { + TickType_t xNextExpireTime; + BaseType_t xListWasEmpty; + + /* Just to avoid compiler warnings. */ + ( void ) pvParameters; + + #if ( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 ) + { + /* Allow the application writer to execute some code in the context of + * this task at the point the task starts executing. This is useful if the + * application includes initialisation code that would benefit from + * executing after the scheduler has been started. */ + vApplicationDaemonTaskStartupHook(); + } + #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */ + + for( ; configCONTROL_INFINITE_LOOP(); ) + { + /* Query the timers list to see if it contains any timers, and if so, + * obtain the time at which the next timer will expire. */ + xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); + + /* If a timer has expired, process it. Otherwise, block this task + * until either a timer does expire, or a command is received. */ + prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); + + /* Empty the command queue. */ + prvProcessReceivedCommands(); + } + } +/*-----------------------------------------------------------*/ + + static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, + BaseType_t xListWasEmpty ) + { + TickType_t xTimeNow; + BaseType_t xTimerListsWereSwitched; + + vTaskSuspendAll(); + { + /* Obtain the time now to make an assessment as to whether the timer + * has expired or not. If obtaining the time causes the lists to switch + * then don't process this timer as any timers that remained in the list + * when the lists were switched will have been processed within the + * prvSampleTimeNow() function. */ + xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); + + if( xTimerListsWereSwitched == pdFALSE ) + { + /* The tick count has not overflowed, has the timer expired? */ + if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) + { + ( void ) xTaskResumeAll(); + prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); + } + else + { + /* The tick count has not overflowed, and the next expire + * time has not been reached yet. This task should therefore + * block to wait for the next expire time or a command to be + * received - whichever comes first. The following line cannot + * be reached unless xNextExpireTime > xTimeNow, except in the + * case when the current timer list is empty. */ + if( xListWasEmpty != pdFALSE ) + { + /* The current timer list is empty - is the overflow list + * also empty? */ + xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList ); + } + + vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty ); + + if( xTaskResumeAll() == pdFALSE ) + { + /* Yield to wait for either a command to arrive, or the + * block time to expire. If a command arrived between the + * critical section being exited and this yield then the yield + * will not cause the task to block. */ + taskYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + ( void ) xTaskResumeAll(); + } + } + } +/*-----------------------------------------------------------*/ + + static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) + { + TickType_t xNextExpireTime; + + /* Timers are listed in expiry time order, with the head of the list + * referencing the task that will expire first. Obtain the time at which + * the timer with the nearest expiry time will expire. If there are no + * active timers then just set the next expire time to 0. That will cause + * this task to unblock when the tick count overflows, at which point the + * timer lists will be switched and the next expiry time can be + * re-assessed. */ + *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); + + if( *pxListWasEmpty == pdFALSE ) + { + xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); + } + else + { + /* Ensure the task unblocks when the tick count rolls over. */ + xNextExpireTime = ( TickType_t ) 0U; + } + + return xNextExpireTime; + } +/*-----------------------------------------------------------*/ + + static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) + { + TickType_t xTimeNow; + PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; + + xTimeNow = xTaskGetTickCount(); + + if( xTimeNow < xLastTime ) + { + prvSwitchTimerLists(); + *pxTimerListsWereSwitched = pdTRUE; + } + else + { + *pxTimerListsWereSwitched = pdFALSE; + } + + xLastTime = xTimeNow; + + return xTimeNow; + } +/*-----------------------------------------------------------*/ + + static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, + const TickType_t xNextExpiryTime, + const TickType_t xTimeNow, + const TickType_t xCommandTime ) + { + BaseType_t xProcessTimerNow = pdFALSE; + + listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); + listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); + + if( xNextExpiryTime <= xTimeNow ) + { + /* Has the expiry time elapsed between the command to start/reset a + * timer was issued, and the time the command was processed? */ + if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) + { + /* The time between a command being issued and the command being + * processed actually exceeds the timers period. */ + xProcessTimerNow = pdTRUE; + } + else + { + vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); + } + } + else + { + if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) + { + /* If, since the command was issued, the tick count has overflowed + * but the expiry time has not, then the timer must have already passed + * its expiry time and should be processed immediately. */ + xProcessTimerNow = pdTRUE; + } + else + { + vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); + } + } + + return xProcessTimerNow; + } +/*-----------------------------------------------------------*/ + + static void prvProcessReceivedCommands( void ) + { + DaemonTaskMessage_t xMessage = { 0 }; + Timer_t * pxTimer; + BaseType_t xTimerListsWereSwitched; + TickType_t xTimeNow; + + while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) + { + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + { + /* Negative commands are pended function calls rather than timer + * commands. */ + if( xMessage.xMessageID < ( BaseType_t ) 0 ) + { + const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters ); + + /* The timer uses the xCallbackParameters member to request a + * callback be executed. Check the callback is not NULL. */ + configASSERT( pxCallback ); + + /* Call the function. */ + pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* INCLUDE_xTimerPendFunctionCall */ + + /* Commands that are positive are timer commands rather than pended + * function calls. */ + if( xMessage.xMessageID >= ( BaseType_t ) 0 ) + { + /* The messages uses the xTimerParameters member to work on a + * software timer. */ + pxTimer = xMessage.u.xTimerParameters.pxTimer; + + if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) + { + /* The timer is in a list, remove it. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue ); + + /* In this case the xTimerListsWereSwitched parameter is not used, but + * it must be present in the function call. prvSampleTimeNow() must be + * called after the message is received from xTimerQueue so there is no + * possibility of a higher priority task adding a message to the message + * queue with a time that is ahead of the timer daemon task (because it + * pre-empted the timer daemon task after the xTimeNow value was set). */ + xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); + + switch( xMessage.xMessageID ) + { + case tmrCOMMAND_START: + case tmrCOMMAND_START_FROM_ISR: + case tmrCOMMAND_RESET: + case tmrCOMMAND_RESET_FROM_ISR: + /* Start or restart a timer. */ + pxTimer->ucStatus |= ( uint8_t ) tmrSTATUS_IS_ACTIVE; + + if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE ) + { + /* The timer expired before it was added to the active + * timer list. Process it now. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0U ) + { + prvReloadTimer( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow ); + } + else + { + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE ); + } + + /* Call the timer callback. */ + traceTIMER_EXPIRED( pxTimer ); + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + break; + + case tmrCOMMAND_STOP: + case tmrCOMMAND_STOP_FROM_ISR: + /* The timer has already been removed from the active list. */ + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE ); + break; + + case tmrCOMMAND_CHANGE_PERIOD: + case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR: + pxTimer->ucStatus |= ( uint8_t ) tmrSTATUS_IS_ACTIVE; + pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue; + configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); + + /* The new period does not really have a reference, and can + * be longer or shorter than the old one. The command time is + * therefore set to the current time, and as the period cannot + * be zero the next expiry time can only be in the future, + * meaning (unlike for the xTimerStart() case above) there is + * no fail case that needs to be handled here. */ + ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); + break; + + case tmrCOMMAND_DELETE: + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* The timer has already been removed from the active list, + * just free up the memory if the memory was dynamically + * allocated. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 ) + { + vPortFree( pxTimer ); + } + else + { + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE ); + } + } + #else /* if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) */ + { + /* If dynamic allocation is not enabled, the memory + * could not have been dynamically allocated. So there is + * no need to free the memory - just mark the timer as + * "not active". */ + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE ); + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + break; + + default: + /* Don't expect to get here. */ + break; + } + } + } + } +/*-----------------------------------------------------------*/ + + static void prvSwitchTimerLists( void ) + { + TickType_t xNextExpireTime; + List_t * pxTemp; + + /* The tick count has overflowed. The timer lists must be switched. + * If there are any timers still referenced from the current timer list + * then they must have expired and should be processed before the lists + * are switched. */ + while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) + { + xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); + + /* Process the expired timer. For auto-reload timers, be careful to + * process only expirations that occur on the current list. Further + * expirations must wait until after the lists are switched. */ + prvProcessExpiredTimer( xNextExpireTime, tmrMAX_TIME_BEFORE_OVERFLOW ); + } + + pxTemp = pxCurrentTimerList; + pxCurrentTimerList = pxOverflowTimerList; + pxOverflowTimerList = pxTemp; + } +/*-----------------------------------------------------------*/ + + static void prvCheckForValidListAndQueue( void ) + { + /* Check that the list from which active timers are referenced, and the + * queue used to communicate with the timer service, have been + * initialised. */ + taskENTER_CRITICAL(); + { + if( xTimerQueue == NULL ) + { + vListInitialise( &xActiveTimerList1 ); + vListInitialise( &xActiveTimerList2 ); + pxCurrentTimerList = &xActiveTimerList1; + pxOverflowTimerList = &xActiveTimerList2; + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* The timer queue is allocated statically in case + * configSUPPORT_DYNAMIC_ALLOCATION is 0. */ + PRIVILEGED_DATA static StaticQueue_t xStaticTimerQueue; + PRIVILEGED_DATA static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; + + xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); + } + #else + { + xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ) ); + } + #endif /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + if( xTimerQueue != NULL ) + { + vQueueAddToRegistry( xTimerQueue, "TmrQ" ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configQUEUE_REGISTRY_SIZE */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } +/*-----------------------------------------------------------*/ + + BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) + { + BaseType_t xReturn; + Timer_t * pxTimer = xTimer; + + traceENTER_xTimerIsTimerActive( xTimer ); + + configASSERT( xTimer ); + + /* Is the timer in the list of active timers? */ + taskENTER_CRITICAL(); + { + if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0U ) + { + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); + + traceRETURN_xTimerIsTimerActive( xReturn ); + + return xReturn; + } +/*-----------------------------------------------------------*/ + + void * pvTimerGetTimerID( const TimerHandle_t xTimer ) + { + Timer_t * const pxTimer = xTimer; + void * pvReturn; + + traceENTER_pvTimerGetTimerID( xTimer ); + + configASSERT( xTimer ); + + taskENTER_CRITICAL(); + { + pvReturn = pxTimer->pvTimerID; + } + taskEXIT_CRITICAL(); + + traceRETURN_pvTimerGetTimerID( pvReturn ); + + return pvReturn; + } +/*-----------------------------------------------------------*/ + + void vTimerSetTimerID( TimerHandle_t xTimer, + void * pvNewID ) + { + Timer_t * const pxTimer = xTimer; + + traceENTER_vTimerSetTimerID( xTimer, pvNewID ); + + configASSERT( xTimer ); + + taskENTER_CRITICAL(); + { + pxTimer->pvTimerID = pvNewID; + } + taskEXIT_CRITICAL(); + + traceRETURN_vTimerSetTimerID(); + } +/*-----------------------------------------------------------*/ + + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + + BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + BaseType_t * pxHigherPriorityTaskWoken ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; + + traceENTER_xTimerPendFunctionCallFromISR( xFunctionToPend, pvParameter1, ulParameter2, pxHigherPriorityTaskWoken ); + + /* Complete the message with the function parameters and post it to the + * daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + + xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + + tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + traceRETURN_xTimerPendFunctionCallFromISR( xReturn ); + + return xReturn; + } + + #endif /* INCLUDE_xTimerPendFunctionCall */ +/*-----------------------------------------------------------*/ + + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + + BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + TickType_t xTicksToWait ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; + + traceENTER_xTimerPendFunctionCall( xFunctionToPend, pvParameter1, ulParameter2, xTicksToWait ); + + /* This function can only be called after a timer has been created or + * after the scheduler has been started because, until then, the timer + * queue does not exist. */ + configASSERT( xTimerQueue ); + + /* Complete the message with the function parameters and post it to the + * daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + + tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + traceRETURN_xTimerPendFunctionCall( xReturn ); + + return xReturn; + } + + #endif /* INCLUDE_xTimerPendFunctionCall */ +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) + { + traceENTER_uxTimerGetTimerNumber( xTimer ); + + traceRETURN_uxTimerGetTimerNumber( ( ( Timer_t * ) xTimer )->uxTimerNumber ); + + return ( ( Timer_t * ) xTimer )->uxTimerNumber; + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + void vTimerSetTimerNumber( TimerHandle_t xTimer, + UBaseType_t uxTimerNumber ) + { + traceENTER_vTimerSetTimerNumber( xTimer, uxTimerNumber ); + + ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; + + traceRETURN_vTimerSetTimerNumber(); + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +/* + * Reset the state in this file. This state is normally initialized at start up. + * This function must be called by the application before restarting the + * scheduler. + */ + void vTimerResetState( void ) + { + xTimerQueue = NULL; + xTimerTaskHandle = NULL; + } +/*-----------------------------------------------------------*/ + +/* This entire source file will be skipped if the application is not configured + * to include software timer functionality. If you want to include software timer + * functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ +#endif /* configUSE_TIMERS == 1 */ diff --git a/source/build.sh b/source/build.sh index be2841836..d831e4e57 100755 --- a/source/build.sh +++ b/source/build.sh @@ -6,8 +6,9 @@ TRANSLATION_DIR="../Translations" # AVAILABLE_LANGUAGES will be calculating according to json files in $TRANSLATION_DIR AVAILABLE_LANGUAGES=() BUILD_LANGUAGES=() -AVAILABLE_MODELS=("TS100" "TS80" "TS80P" "Pinecil" "MHP30" "Pinecilv2" "S60" "TS101") +AVAILABLE_MODELS=("TS100" "TS80" "TS80P" "Pinecil" "MHP30" "Pinecilv2" "S60" "S60P" "T55" "TS101") BUILD_MODELS=() +OPTIONS=() builder_info() { echo -e " @@ -28,17 +29,19 @@ usage() { builder_info echo -e " Usage : - $(basename "$0") [-l ] [-m ] [-h] + $(basename "$0") [-l ] [-m ] [-o ] [-h] Parameters : -l LANG_CODE : Force a specific language (${AVAILABLE_LANGUAGES[*]}) -m MODEL : Force a specific model (${AVAILABLE_MODELS[*]}) + -o key=val : Pass options to make -h : Show this help message Example : $(basename "$0") -l EN -m TS100 (Build one language and model) $(basename "$0") -l EN -m \"TS100 MHP30\" (Build one language and multi models) $(basename "$0") -l \"DE EN\" -m \"TS100 MHP30\" (Build multi languages and models) + $(basename "$0") -l EN -m Pinecilv2 -o ws2812b_enable=1 INFO : By default, without parameters, the build is for all platforms and all languages @@ -47,8 +50,8 @@ INFO : exit 1 } -StartBuild(){ - read -n 1 -r -s -p $'Press Enter to start the building process...\n' +StartBuild() { + read -n 1 -r -s -p $'Press Enter to start the building process...\n' } checkLastCommand() { @@ -84,20 +87,24 @@ isInArray() { declare -a margs=() declare -a largs=() +declare -a oargs=() -while getopts "h:l:m:" option; do +while getopts "h:l:m:o:" option; do case "${option}" in - h) - usage - ;; - l) - IFS=' ' read -r -a largs <<< "${OPTARG}" - ;; - m) - IFS=' ' read -r -a margs <<< "${OPTARG}" - ;; - *) - usage + h) + usage + ;; + l) + IFS=' ' read -r -a largs <<<"${OPTARG}" + ;; + m) + IFS=' ' read -r -a margs <<<"${OPTARG}" + ;; + o) + IFS=' ' read -r -a oargs <<< "${OPTARG}" + ;; + *) + usage ;; esac done @@ -156,6 +163,16 @@ fi echo "********************************************" +echo -n "Requested options : " +if ((${#oargs[@]})); then + for i in "${oargs[@]}"; do + echo -n "$i " + OPTIONS+=("$i") + done + echo "" +fi + +echo "********************************************" ## #StartBuild @@ -168,7 +185,7 @@ if [ ${#BUILD_LANGUAGES[@]} -gt 0 ] && [ ${#BUILD_MODELS[@]} -gt 0 ]; then for model in "${BUILD_MODELS[@]}"; do echo "Building firmware for $model in ${BUILD_LANGUAGES[*]}" - make -j"$(nproc)" model="$model" "${BUILD_LANGUAGES[@]/#/firmware-}" >/dev/null + make -j"$(nproc)" model="$model" "${BUILD_LANGUAGES[@]/#/firmware-}" "${OPTIONS[@]}" >/dev/null checkLastCommand done else diff --git a/source/dfuse-pack.py b/source/dfuse-pack.py index 71158ace5..71bdcd45f 100755 --- a/source/dfuse-pack.py +++ b/source/dfuse-pack.py @@ -256,7 +256,7 @@ def build(file, targets, name=DEFAULT_NAME, device=DEFAULT_DEVICE): sys.exit(1) for hexf in options.hexfiles: ih = IntelHex(hexf) - for (address, end) in ih.segments(): + for address, end in ih.segments(): try: address = address & 0xFFFFFFFF except ValueError: diff --git a/source/metadata.py b/source/metadata.py index 72133e5ee..9749ce95d 100755 --- a/source/metadata.py +++ b/source/metadata.py @@ -12,8 +12,12 @@ if len(sys.argv) < 2 or len(sys.argv) > 3: print("Usage: metadata.py OUTPUT_FILE [model]") - print(" OUTPUT_FILE - the name of output file in json format with meta info about binary files") - print(" model [optional] - name of the model (as for `make model=NAME`) to scan files for explicitly (all files in source/Hexfile by default otherwise)") + print( + " OUTPUT_FILE - the name of output file in json format with meta info about binary files" + ) + print( + " model [optional] - name of the model (as for `make model=NAME`) to scan files for explicitly (all files in source/Hexfile by default otherwise)" + ) exit(1) # If model is provided explicitly to scan related files only for json output, then process the argument @@ -30,16 +34,19 @@ OutputJSONPath = os.path.join(HexFileFolder, sys.argv[1]) TranslationsFilesPath = os.path.join(HERE.parent, "Translations") + def load_json(filename: str): with open(filename) as f: return json.loads(f.read()) + def read_git_tag(): if os.environ.get("GITHUB_CI_PR_SHA", "") != "": return os.environ["GITHUB_CI_PR_SHA"][:7].upper() else: return f"{subprocess.check_output(['git', 'rev-parse', '--short=7', 'HEAD']).strip().decode('ascii').upper()}" + def read_version(): with open(HERE / "version.h") as version_file: for line in version_file: @@ -49,9 +56,18 @@ def read_version(): return matches[0] raise Exception("Could not parse version") + # Fetch our file listings -translation_files = [os.path.join(TranslationsFilesPath, f) for f in os.listdir(TranslationsFilesPath) if os.path.isfile(os.path.join(TranslationsFilesPath, f)) and f.endswith(".json")] -output_files = [os.path.join(HexFileFolder, f) for f in sorted(os.listdir(HexFileFolder)) if os.path.isfile(os.path.join(HexFileFolder, f))] +translation_files = [ + os.path.join(TranslationsFilesPath, f) + for f in os.listdir(TranslationsFilesPath) + if os.path.isfile(os.path.join(TranslationsFilesPath, f)) and f.endswith(".json") +] +output_files = [ + os.path.join(HexFileFolder, f) + for f in sorted(os.listdir(HexFileFolder)) + if os.path.isfile(os.path.join(HexFileFolder, f)) +] parsed_languages = {} for path in translation_files: @@ -74,7 +90,9 @@ def read_version(): if not name.startswith(ModelName + "_"): continue # If build of interest is not multi-lang one but scanning one is not MODEL_LANG-ID here, then skip it to avoid mess in json between MODEL_LANG-ID & MODEL_multi' - if not ModelName.endswith("_multi") and not re.match(r"^" + ModelName + "_" + "([A-Z]+).*$", name): + if not ModelName.endswith("_multi") and not re.match( + r"^" + ModelName + "_" + "([A-Z]+).*$", name + ): continue matches = re.findall(r"^([a-zA-Z0-9]+)_(.+)\.(.+)$", name) if matches: @@ -86,10 +104,17 @@ def read_version(): lang_file = parsed_languages.get(lang_code, None) if lang_file is None and lang_code.startswith("multi_"): # Multi files wont match, but we fake this by just taking the filename to it - lang_file = {"languageLocalName": lang_code.replace("multi_", "").replace("compressed_", "")} + lang_file = { + "languageLocalName": lang_code.replace("multi_", "").replace( + "compressed_", "" + ) + } if lang_file is None: raise Exception(f"Could not match language code {lang_code}") - file_record = {"language_code": lang_code, "language_name": lang_file.get("languageLocalName", None)} + file_record = { + "language_code": lang_code, + "language_name": lang_file.get("languageLocalName", None), + } output_json["contents"][name] = file_record else: print(f"failed to parse {matches}") diff --git a/source/version.h b/source/version.h index 74ffad74b..c2320b9d6 100644 --- a/source/version.h +++ b/source/version.h @@ -21,4 +21,4 @@ * * BUILD_VERSION = 'v2.22' -> from stable git release: 'v2.22R.5E6F7G8H' */ -#define BUILD_VERSION "v2.22" +#define BUILD_VERSION "v2.23"