diff --git a/scripts/deploy.sh b/scripts/deploy.sh index f7964ce4..3f654266 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -91,21 +91,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}" } diff --git a/source/.clang-format b/source/.clang-format index a737f88c..a7bddf26 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 -BreakBeforeBraces: Attach -BreakBeforeInheritanceComma: false -BreakInheritanceList: BeforeColon -BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false -BreakConstructorInitializers: BeforeColon +BreakAfterAttributes: Never BreakAfterJavaFieldAnnotations: false +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +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 -SpaceInEmptyBlock: false -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 1 -SpacesInAngles: false -SpacesInConditionalStatement: false -SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false -SpacesInSquareBrackets: false SpaceBeforeSquareBrackets: false -Standard: Latest +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +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/MHP30/BSP.cpp b/source/Core/BSP/MHP30/BSP.cpp index cbf5ce79..dde331d4 100644 --- a/source/Core/BSP/MHP30/BSP.cpp +++ b/source/Core/BSP/MHP30/BSP.cpp @@ -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) { @@ -273,8 +275,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; + } } } diff --git a/source/Core/BSP/MHP30/Setup.c b/source/Core/BSP/MHP30/Setup.c index 8eaaaf35..b354c6e3 100644 --- a/source/Core/BSP/MHP30/Setup.c +++ b/source/Core/BSP/MHP30/Setup.c @@ -336,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/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/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c index f71efb0f..4f8a7576 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 bb7ac4fc..d0ea179a 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 e24c8e54..ce5414e9 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 c77c4608..f6444997 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_rcc.c b/source/Core/BSP/MHP30/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c index dfea429d..f1a5d2c3 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 d82d6fea..4051fb91 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 1990dcc5..c7e3f8cd 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 9d6123bf..87f66c3f 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/system_stm32f1xx.c b/source/Core/BSP/MHP30/system_stm32f1xx.c index 944abbcc..e9b08e10 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 */ diff --git a/source/Core/BSP/Miniware/BSP.cpp b/source/Core/BSP/Miniware/BSP.cpp index e930f682..df45516b 100644 --- a/source/Core/BSP/Miniware/BSP.cpp +++ b/source/Core/BSP/Miniware/BSP.cpp @@ -207,8 +207,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. 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 00000000..f8d1c8ed --- /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/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c index cb32ffdf..8725243a 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 f29ea6c5..19ac9e7d 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 dc2e20e8..03c947f3 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 e1f9b4e4..b973ec02 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_i2c.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c index 5dd8b7c7..2c38ddb9 100644 --- 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 @@ -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/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 e56f9cbd..56515b0b 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 d700f0ca..25e902fa 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 18e2fc37..dfa0b557 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 9d6123bf..87f66c3f 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/port.c b/source/Core/BSP/Miniware/port.c index a79eab6f..fb0e0330 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/system_stm32f1xx.c b/source/Core/BSP/Miniware/system_stm32f1xx.c index 06c843e0..4c5df9cc 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 */ diff --git a/source/Core/BSP/Pinecil/I2C_Wrapper.cpp b/source/Core/BSP/Pinecil/I2C_Wrapper.cpp index 46f33436..853f5fab 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/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 2700e660..0b61201f 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 4a7d0e9c..900a1e25 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 8b976709..a1d359bb 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 22b474c0..edb73d0f 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), - }, + *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) - }; + .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), - }, + *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) - }; + .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)}, + *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)}; + .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 9c04ec58..57f0f206 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)) { + } } /*! 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 e129f7cc..b2eebe3e 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 d1485881..436a3497 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 @@ -114,14 +114,14 @@ void exmc_norsram_init(exmc_norsram_parameter_struct *exmc_norsram_init_struct) /* 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)((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 4811ec87..3b38e5bd 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 af0b669d..231431ac 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 8a7bb21f..50d2909a 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 08192e35..652fff3f 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 c4f213d1..48618134 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 171bb151..60b09c16 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) { + } } /** diff --git a/source/Core/BSP/Pinecilv2/MemMang/heap_5.c b/source/Core/BSP/Pinecilv2/MemMang/heap_5.c index 3ee2639b..d84de815 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/Setup.cpp b/source/Core/BSP/Pinecilv2/Setup.cpp index 120ba237..7e8ea542 100644 --- a/source/Core/BSP/Pinecilv2/Setup.cpp +++ b/source/Core/BSP/Pinecilv2/Setup.cpp @@ -23,8 +23,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 @@ -86,8 +86,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[] = {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_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)); 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 47aad724..5f8cdfac 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/syscalls.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/bsp/bsp_common/platform/syscalls.c index a87c44d5..6299cad8 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 9fe57a5e..00000000 --- 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 46d5b0c2..00000000 --- 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 60dffbd0..00000000 --- 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 05c62792..28c478c0 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 e02a8371..d3dc7330 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/misc.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/common/misc/misc.c index 3292a683..92699a50 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; + * @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++; - } + while (n--) { + *q++ = *p++; + } - return dst; + 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; + * @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++; - } + while (n--) { + *q++ = *p++; + } - return dst; + 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; + * @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; + 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); + 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; + * @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; - } + while (n > 0) { + *p++ = (uint8_t)c; + --n; + } - return s; + 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; + * @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; - } + while (n--) { + *q++ = val; + } - return dst; + 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; + * @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++; + while (n--) { + d = (int)*c1++ - (int)*c2++; - if (d) { - break; - } + 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; - } + * @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; + *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 673dcbe8..a96f0b59 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 - * - *
程序如下:
- 利用基姆拉尔森计算日期公式 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;
+ 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;
+ 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;
+void unixtime2bejingtime(uint32_t unixtime, rtc_time *beijing_time) {
+ uint32_t totle_day_num;
+ uint32_t current_sec_num;
- uint16_t remain_day;
+ uint16_t remain_day;
- uint16_t temp_year;
+ uint16_t temp_year;
- uint8_t *p = NULL;
+ uint8_t *p = NULL;
- 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
+ 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
- /* 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;
+ /* 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++;
- }
+ /* 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++;
- }
+ /* 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;
+ 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)*/
+ 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;
- /*利用基姆拉尔森计算日期公式 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 ;
-
- cal_weekday(beijing_time);
+ cal_weekday(beijing_time);
}
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 238b9b20..5778665e 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,318 @@
/*****************************************************************************************
-*
-* @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 "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;
+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;
+ 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;
+ 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);
-
- if (prio) {
- bt_recv_prio(buf);
- } else {
- hci_driver_enque_recvq(buf);
+ 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;
+ }
+
+ 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;
- do {
- unsigned int lock = irq_lock();
+ uint8_t *buf_data = net_buf_tail(buf);
+ bt_buf_set_rx_adv(buf, false);
- if (k_queue_is_empty(&msg_queue)) {
- break;
- }
+ 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 (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT)
- break;
+ net_buf_add(buf, tlt_len);
- buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
- if (!buf) {
- break;
- }
-
- msg = k_fifo_get(&msg_queue, K_NO_WAIT);
-
- BT_ASSERT(msg);
-
- bl_packet_to_host(msg->pkt_type, msg->src_id, msg->param, msg->param_len, buf);
-
- irq_unlock(lock);
-
- if (msg->param) {
- k_free(msg->param);
- }
- memset(msg, 0, sizeof(struct rx_msg_struct));
-
- } while (buf);
+ if (prio) {
+ bt_recv_prio(buf);
+ } else {
+ hci_driver_enque_recvq(buf);
+ }
}
-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;
+void bl_trigger_queued_msg() {
+ struct net_buf *buf = NULL;
+ struct rx_msg_struct *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);
+ do {
+ unsigned int lock = irq_lock();
+
+ if (k_queue_is_empty(&msg_queue)) {
+ break;
+ }
+
+ if (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT) {
+ break;
+ }
+
+ buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
+ if (!buf) {
+ break;
+ }
+
+ msg = k_fifo_get(&msg_queue, K_NO_WAIT);
+
+ BT_ASSERT(msg);
+
+ bl_packet_to_host(msg->pkt_type, msg->src_id, msg->param, msg->param_len, buf);
+
+ irq_unlock(lock);
+
+ if (msg->param) {
+ k_free(msg->param);
+ }
+ memset(msg, 0, sizeof(struct rx_msg_struct));
+
+ } while (buf);
+}
+
+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;
+ } 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]);
+#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;
+ } 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_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]);
-#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;
+ }
+ }
+
+ rx_msg = bl_find_valid_data_msg();
+ }
+
+ 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);
+
+ 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));
+ }
+
+ k_queue_init(&msg_queue, DATA_MSG_CNT);
+
+ 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 {
- 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();
+ break;
}
+ } while (1);
- 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);
-
- 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));
- }
-
- k_queue_init(&msg_queue, DATA_MSG_CNT);
-
- 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);
+ k_queue_free(&msg_queue);
}
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 25c27fb6..34beb7ce 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 "bl_port.h"
#include
#include
-#include "bl_port.h"
-//#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 44bdbda0..bb3a5b54 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"
@@ -29,17 +29,16 @@
#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 +49,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
@@ -71,7 +70,7 @@ extern struct net_buf_pool acl_in_pool;
#if CONFIG_BT_ATT_PREPARE_COUNT > 0
extern struct net_buf_pool frag_pool;
#endif
-#endif //CONFIG_BT_CONN
+#endif // CONFIG_BT_CONN
#if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT)
extern struct net_buf_pool discardable_pool;
#endif
@@ -80,7 +79,7 @@ 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 +94,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,193 +107,171 @@ 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)
-void net_buf_init(struct net_buf_pool *buf_pool, u16_t buf_count, size_t data_size, destroy_cb_t destroy)
-{
- 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 *));
+void net_buf_init(struct net_buf_pool *buf_pool, u16_t buf_count, size_t data_size, destroy_cb_t destroy) {
+ 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_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;
+ 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;
#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)));
+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);
+ 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);
}
#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;
+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;
- }
+ /* 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 = {
@@ -306,35 +281,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 +317,282 @@ 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;
+ u32_t alloc_start = k_uptime_get_32();
+ struct net_buf *buf;
+ unsigned int key;
- NET_BUF_ASSERT(pool);
+ NET_BUF_ASSERT(pool);
- NET_BUF_DBG("%s():%d: pool %p size %zu timeout %d", func, line, pool,
- size, timeout);
+ 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();
+ /* 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 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--;
+ /* 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);
-
- buf = pool_get_uninit(pool, uninit_count);
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);
+ 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;
+ 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;
+ 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);
+ key = irq_lock();
+ buf = (void *)sys_slist_get(list);
+ irq_unlock(key);
+
+ 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);
- if (!buf) {
- return NULL;
- }
+ NET_BUF_ASSERT(frag->frags);
- /* 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);
+ /* The fragments flag is only for list-internal usage */
+ frag->flags &= ~NET_BUF_FRAGS;
+ }
- NET_BUF_ASSERT(frag->frags);
+ /* Mark the end of the fragment list */
+ frag->frags = NULL;
- /* The fragments flag is only for list-internal usage */
- frag->flags &= ~NET_BUF_FRAGS;
- }
-
- /* 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 +601,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;
- }
-#endif
- 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 */
-
- if (buf->__buf) {
- data_unref(buf, buf->__buf);
- buf->__buf = NULL;
- }
-
- buf->data = NULL;
- buf->frags = NULL;
-
- 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);
-#endif
-
- if (pool->destroy) {
- pool->destroy(buf);
- } else {
- net_buf_destroy(buf);
- }
-
- buf = frags;
-
-#if defined(BFLB_BLE)
- if (pool == &hci_rx_pool) {
- bl_trigger_queued_msg();
- return;
- }
-#endif
+ 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);
-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);
-
- unsigned int key = irq_lock(); /* Added by bouffalo lab, to protect ref increase */
- buf->ref++;
+ 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 */
- 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;
+ if (buf->__buf) {
+ data_unref(buf, buf->__buf);
+ buf->__buf = NULL;
+ }
- NET_BUF_ASSERT(buf);
+ buf->data = NULL;
+ buf->frags = NULL;
pool = net_buf_pool_get(buf->pool_id);
- clone = net_buf_alloc_len(pool, 0, timeout);
- if (!clone) {
- return NULL;
- }
+#if defined(CONFIG_NET_BUF_POOL_USAGE)
+ pool->avail_count++;
+ NET_BUF_ASSERT(pool->avail_count <= pool->buf_count);
+#endif
- /* 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;
+ if (pool->destroy) {
+ pool->destroy(buf);
} else {
- size_t size = buf->size;
-
- if (timeout != K_NO_WAIT && timeout != K_FOREVER) {
- u32_t diff = k_uptime_get_32() - alloc_start;
-
- timeout -= MIN(timeout, diff);
- }
-
- clone->__buf = data_alloc(clone, &size, timeout);
- if (!clone->__buf || size < buf->size) {
- net_buf_destroy(clone);
- return NULL;
- }
-
- clone->size = size;
- clone->data = clone->__buf + net_buf_headroom(buf);
- net_buf_add_mem(clone, buf->data, buf->len);
+ net_buf_destroy(buf);
}
- return clone;
+ buf = frags;
+
+#if defined(BFLB_BLE)
+ if (pool == &hci_rx_pool) {
+ bl_trigger_queued_msg();
+ return;
+ }
+#endif
+ }
}
-struct net_buf *net_buf_frag_last(struct net_buf *buf)
-{
- NET_BUF_ASSERT(buf);
+struct net_buf *net_buf_ref(struct net_buf *buf) {
+ NET_BUF_ASSERT(buf);
- while (buf->frags) {
- buf = buf->frags;
- }
+ NET_BUF_DBG("buf %p (old) ref %u pool_id %u", buf, buf->ref, buf->pool_id);
- 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;
}
-void net_buf_frag_insert(struct net_buf *parent, struct net_buf *frag)
-{
- NET_BUF_ASSERT(parent);
- NET_BUF_ASSERT(frag);
+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;
- if (parent->frags) {
- net_buf_frag_last(frag)->frags = parent->frags;
+ NET_BUF_ASSERT(buf);
+
+ 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;
+
+ if (timeout != K_NO_WAIT && timeout != K_FOREVER) {
+ u32_t diff = k_uptime_get_32() - alloc_start;
+
+ timeout -= MIN(timeout, diff);
}
- /* Take ownership of the fragment reference */
- parent->frags = frag;
+
+ clone->__buf = data_alloc(clone, &size, timeout);
+ if (!clone->__buf || size < buf->size) {
+ net_buf_destroy(clone);
+ return NULL;
+ }
+
+ 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_add(struct net_buf *head, struct net_buf *frag)
-{
- NET_BUF_ASSERT(frag);
+struct net_buf *net_buf_frag_last(struct net_buf *buf) {
+ NET_BUF_ASSERT(buf);
- if (!head) {
- return net_buf_ref(frag);
- }
+ while (buf->frags) {
+ buf = buf->frags;
+ }
- net_buf_frag_insert(net_buf_frag_last(head), frag);
+ return buf;
+}
- return head;
+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;
+}
+
+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);
+ }
+
+ net_buf_frag_insert(net_buf_frag_last(head), frag);
+
+ 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 +853,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);
+
+ NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+
+ NET_BUF_SIMPLE_ASSERT(net_buf_simple_tailroom(buf) >= len);
+
+ buf->len += len;
+ return tail;
}
-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_mem(struct net_buf_simple *buf, const void *mem, size_t len) {
+ 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);
-
- buf->len += len;
- return tail;
+ return memcpy(net_buf_simple_add(buf, len), mem, 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);
+u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val) {
+ u8_t *u8;
- return memcpy(net_buf_simple_add(buf, len), mem, len);
+ NET_BUF_SIMPLE_DBG("buf %p val 0x%02x", buf, val);
+
+ u8 = net_buf_simple_add(buf, 1);
+ *u8 = val;
+
+ return u8;
}
-u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val)
-{
- u8_t *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);
- NET_BUF_SIMPLE_DBG("buf %p val 0x%02x", buf, val);
-
- u8 = net_buf_simple_add(buf, 1);
- *u8 = val;
-
- return u8;
+ sys_put_le16(val, net_buf_simple_add(buf, sizeof(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);
+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_le16(val, net_buf_simple_add(buf, sizeof(val)));
+ sys_put_be16(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_le24(struct net_buf_simple *buf, uint32_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_le24(val, net_buf_simple_add(buf, 3));
}
-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_be24(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_be24(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_le32(struct net_buf_simple *buf, u32_t val) {
+ NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
- sys_put_be24(val, net_buf_simple_add(buf, 3));
+ sys_put_le32(val, net_buf_simple_add(buf, sizeof(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);
+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_le32(val, net_buf_simple_add(buf, sizeof(val)));
+ sys_put_be32(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_push(struct net_buf_simple *buf, size_t len) {
+ NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
- sys_put_be32(val, net_buf_simple_add(buf, sizeof(val)));
+ NET_BUF_SIMPLE_ASSERT(net_buf_simple_headroom(buf) >= len);
+
+ buf->data -= len;
+ buf->len += len;
+ return buf->data;
}
-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_le16(struct net_buf_simple *buf, u16_t val) {
+ NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
- NET_BUF_SIMPLE_ASSERT(net_buf_simple_headroom(buf) >= len);
-
- buf->data -= len;
- buf->len += len;
- return buf->data;
+ sys_put_le16(val, net_buf_simple_push(buf, sizeof(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);
+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_le16(val, net_buf_simple_push(buf, sizeof(val)));
+ sys_put_be16(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_u8(struct net_buf_simple *buf, u8_t val) {
+ u8_t *data = net_buf_simple_push(buf, 1);
- sys_put_be16(val, net_buf_simple_push(buf, sizeof(val)));
+ *data = 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_le24(struct net_buf_simple *buf, uint32_t val) {
+ NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val);
- *data = val;
+ sys_put_le24(val, net_buf_simple_push(buf, 3));
}
-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_be24(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_be24(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_pull(struct net_buf_simple *buf, size_t len) {
+ NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
- sys_put_be24(val, net_buf_simple_push(buf, 3));
+ NET_BUF_SIMPLE_ASSERT(buf->len >= len);
+
+ buf->len -= len;
+ return buf->data += len;
}
-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_mem(struct net_buf_simple *buf, size_t len) {
+ void *data = buf->data;
- NET_BUF_SIMPLE_ASSERT(buf->len >= len);
+ NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
- buf->len -= len;
- return buf->data += len;
+ NET_BUF_SIMPLE_ASSERT(buf->len >= len);
+
+ buf->len -= len;
+ buf->data += len;
+
+ return data;
}
-void *net_buf_simple_pull_mem(struct net_buf_simple *buf, size_t len)
-{
- void *data = buf->data;
+u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf) {
+ u8_t val;
- NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len);
+ val = buf->data[0];
+ net_buf_simple_pull(buf, 1);
- NET_BUF_SIMPLE_ASSERT(buf->len >= len);
-
- buf->len -= len;
- buf->data += len;
-
- return data;
+ return val;
}
-u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf)
-{
- u8_t val;
+u16_t net_buf_simple_pull_le16(struct net_buf_simple *buf) {
+ u16_t val;
- val = buf->data[0];
- net_buf_simple_pull(buf, 1);
+ val = UNALIGNED_GET((u16_t *)buf->data);
+ net_buf_simple_pull(buf, sizeof(val));
- return val;
+ return sys_le16_to_cpu(val);
}
-u16_t net_buf_simple_pull_le16(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_le16_to_cpu(val);
+ return sys_be16_to_cpu(val);
}
-u16_t net_buf_simple_pull_be16(struct net_buf_simple *buf)
-{
- u16_t val;
+u32_t net_buf_simple_pull_le32(struct net_buf_simple *buf) {
+ u32_t val;
- val = UNALIGNED_GET((u16_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_be16_to_cpu(val);
+ return sys_le32_to_cpu(val);
}
-u32_t net_buf_simple_pull_le32(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_le32_to_cpu(val);
+ return sys_be32_to_cpu(val);
}
-u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf)
-{
- u32_t val;
+size_t net_buf_simple_headroom(struct net_buf_simple *buf) { return buf->data - buf->__buf; }
- val = UNALIGNED_GET((u32_t *)buf->data);
- net_buf_simple_pull(buf, sizeof(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_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 7c7f30c0..e0fd7b79 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;
+ }
- return num_digits;
+ if (buflen) {
+ *buf = '\0';
+ }
+
+ 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 db90bb43..30184dcb 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 2d2425c0..31617020 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/log.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/log.c
index 3a579079..2f43ff2b 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[255];
#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/poll.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/poll.c
index b97a4f79..8dce95e2 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,203 @@
#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");
+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;
+ 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;
+ }
+
+ return 0;
}
-static inline void add_event(sys_dlist_t *events, struct k_poll_event *event,
- struct _poller *poller)
-{
- sys_dlist_append(events, &event->_node);
+static inline void add_event(sys_dlist_t *events, struct k_poll_event *event, struct _poller *poller) { sys_dlist_append(events, &event->_node); }
+
+/* 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 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;
- }
+static inline void clear_event_registration(struct k_poll_event *event) {
+ event->poller = NULL;
- event->poller = poller;
-
- return 0;
+ 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_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 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)
-{
- 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);
- }
- return polling;
-}
-
-int k_poll(struct k_poll_event *events, int num_events, s32_t timeout)
-{
- __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;
- }
-
- k_sem_take(&g_poll_sem, timeout);
-
- last_registered = -1;
- polling_events(events, num_events, timeout, &last_registered);
-exit:
+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();
- clear_event_registrations(events, last_registered, key);
+ }
+}
+
+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) {
+ 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);
- return 0;
+ }
+ return polling;
+}
+
+int k_poll(struct k_poll_event *events, int num_events, s32_t timeout) {
+ __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;
+ }
+
+ k_sem_take(&g_poll_sem, timeout);
+
+ last_registered = -1;
+ polling_events(events, num_events, timeout, &last_registered);
+exit:
+ 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;
- }
-
- int rc = _signal_poll_event(poll_event, K_POLL_STATE_SIGNALED,
- &must_reschedule);
-
- k_sem_give(&g_poll_sem);
+ poll_event = (struct k_poll_event *)sys_dlist_get(&signal->poll_events);
+ if (!poll_event) {
irq_unlock(key);
- return rc;
+ return 0;
+ }
+
+ int rc = _signal_poll_event(poll_event, K_POLL_STATE_SIGNALED, &must_reschedule);
+
+ 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 231ca221..ef5d96c2 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,91 @@
* 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/bluetooth/crypto.h>
+#include
+#include
+#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;
+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));
+ 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);
+ /* r' = padding || r */
+ memcpy(res, r, 3);
+ (void)memset(res + 3, 0, 13);
- err = bt_encrypt_le(irk, res, res);
- if (err) {
- return err;
- }
+ 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);
+ /* 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;
+ 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/tinycrypt/source/aes_decrypt.c b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/common/tinycrypt/source/aes_decrypt.c
index 83719acc..a0ea2b81 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
-};
+ 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);
-}
+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];
+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));
+ 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);
+ }
- (void)_copy(out, sizeof(state), state, sizeof(state));
+ inv_shift_rows(state);
+ inv_sub_bytes(state);
+ add_round_key(state, s->words);
- /*zeroing out the state buffer */
- _set(state, TC_ZERO_BYTE, sizeof(state));
+ (void)_copy(out, sizeof(state), state, sizeof(state));
- return TC_CRYPTO_SUCCESS;
+ /*zeroing out the state buffer */
+ _set(state, TC_ZERO_BYTE, sizeof(state));
+
+ 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 0cb47b84..9d20d1c2 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
-};
+ 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));
-}
+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;
+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;
+ 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 = 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;
- }
-
- 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];
+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));
+ 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;
+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;
- }
+ 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));
- 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));
- }
+ (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));
+ }
- (void)_copy(out, sizeof(state), state, sizeof(state));
+ sub_bytes(state);
+ shift_rows(state);
+ add_round_key(state, s->words + Nb * (i + 1));
- /* zeroing out the state buffer */
- _set(state, TC_ZERO_BYTE, sizeof(state));
+ (void)_copy(out, sizeof(state), state, sizeof(state));
- return TC_CRYPTO_SUCCESS;
+ /* zeroing out the state buffer */
+ _set(state, TC_ZERO_BYTE, sizeof(state));
+
+ 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 b405d7d2..8c30104f 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;
+
+ 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;
}
+ }
- /* 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;
- }
- }
-
- 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 ed94e75b..e102957e 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.*/
- }
+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;
+ c->mlen = mlen;
+ c->sched = sched;
+ c->nonce = nonce;
- return TC_CRYPTO_SUCCESS;
+ 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;
+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;
- }
+ 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);
- }
+ 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;
+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) {
+ /* 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));
+ /* update the counter */
+ ctr[14] = nonce[14];
+ ctr[15] = nonce[15];
- /* 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++;
- }
+ return TC_CRYPTO_SUCCESS;
+}
- /* update the counter */
- ctr[14] = nonce[14];
- ctr[15] = nonce[15];
+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;
-}
-
-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;
- }
+ } 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 97e7dd34..fa517db9 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);
+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;
+ /* 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;
+ 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;
+}
+
+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));
+
+ return TC_CRYPTO_SUCCESS;
+}
+
+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);
+
+ /* 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;
+
+ 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_erase(TCCmacState_t s)
-{
- if (s == (TCCmacState_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;
}
-
- /* destroy the current state */
- _set(s, 0, sizeof(*s));
-
- return TC_CRYPTO_SUCCESS;
-}
-
-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);
-
- /* and the leftover buffer is empty */
- _set(s->leftover, 0, TC_AES_BLOCK_SIZE);
+ /* 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;
- /* Set countdown to max number of calls allowed before re-keying: */
- s->countdown = MAX_CALLS;
-
- 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;
- }
-
- 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;
-
- 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;
- }
-
- 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;
-}
-
-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;
- }
-
- 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];
+ s->iv[i] ^= s->leftover[i];
}
+ tc_aes_encrypt(s->iv, s->iv, s->sched);
+ }
- tc_aes_encrypt(tag, 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;
+ }
- /* erasing state: */
- tc_cmac_erase(s);
+ 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;
+
+ /* 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;
+
+ _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);
+
+ /* erasing state: */
+ tc_cmac_erase(s);
+
+ 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 c9808338..eaa14bc5 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) {
+ /* 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));
+
+ /* 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++;
+ }
- /* copy the ctr to the nonce */
- (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce));
+ /* update the counter */
+ ctr[12] = nonce[12];
+ ctr[13] = nonce[13];
+ ctr[14] = nonce[14];
+ ctr[15] = nonce[15];
- /* 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];
-
- 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 d3410bc5..e53f550b 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;
+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 */
+ 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.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.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);
+ /* 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 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);
+ 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 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);
+ }
}
-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 };
+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);
+ if (0 != personalization) {
+ /* 10.2.1.3.1 step 1 */
+ unsigned int len = pLen;
+ if (len > sizeof personalization_buf) {
+ len = sizeof personalization_buf;
}
- 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 2 */
+ memcpy(personalization_buf, personalization, len);
+ }
- /* 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 6 */
- tc_ctr_prng_update(ctx, seed_material);
-
- /* 10.2.1.3.1 step 7 */
- ctx->reseedCount = 1U;
-
- result = TC_CRYPTO_SUCCESS;
+ 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];
}
- return result;
+
+ /* 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 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];
+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 */
+ 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.4.1 step 2 */
+ memcpy(additional_input_buf, additional_input, len);
+ }
+
+ 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.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_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.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);
- /* 10.2.1.4.1 step 4 */
- tc_ctr_prng_update(ctx, seed_material);
+ len += blocklen;
+ }
- /* 10.2.1.4.1 step 5 */
- ctx->reseedCount = 1U;
+ /* 10.2.1.5.1 step 6 */
+ tc_ctr_prng_update(ctx, additional_input_buf);
- result = TC_CRYPTO_SUCCESS;
+ /* 10.2.1.5.1 step 7 */
+ ctx->reseedCount++;
+
+ /* 10.2.1.5.1 step 8 */
+ result = TC_CRYPTO_SUCCESS;
}
- return result;
+ }
+
+ return result;
}
-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;
- }
- }
-
- 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 eb3fa223..e9281a59 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
@@ -52,10 +52,10 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include "ecc.h"
-#include "ecc_platform_specific.h"
+#include "../include/tinycrypt/ecc.h"
+#include "../include/tinycrypt/ecc_platform_specific.h"
+#include
#include
-
/* IMPORTANT: Make sure a cryptographically-secure PRNG is set and the platform
* has access to enough entropy in order to feed the PRNG regularly. */
#if default_RNG_defined
@@ -64,860 +64,735 @@ 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; }
+
+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; }
+
+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_RNG_Function uECC_get_rng(void)
-{
- return g_rng_function;
+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);
}
-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;
-}
-
-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_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;
- }
-
- digit = vli[num_digits - 1];
- for (i = 0; digit; ++i) {
- digit >>= 1;
- }
-
- 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;
-
- 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;
-
- for (i = num_words - 1; i >= 0; --i) {
- if (left[i] > right[i]) {
- return 1;
- } else if (left[i] < right[i]) {
- return -1;
- }
- }
+ 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;
+ }
+
+ return (((bitcount_t)(num_digits - 1) << uECC_WORD_BITS_SHIFT) + 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;
+void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src, wordcount_t num_words) {
+ wordcount_t i;
- for (i = num_words - 1; i >= 0; --i) {
- diff |= (left[i] ^ right[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;
+
+ for (i = num_words - 1; i >= 0; --i) {
+ if (left[i] > right[i]) {
+ return 1;
+ } else if (left[i] < right[i]) {
+ return -1;
}
- return !(diff == 0);
+ }
+ return 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 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);
}
+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;
+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);
- }
+ vli += num_words;
+ while (vli-- > end) {
+ uECC_word_t temp = *vli;
+ *vli = (temp >> 1) | carry;
+ carry = temp << (uECC_WORD_BITS - 1);
+ }
}
-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;
+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;
}
/* 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;
+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;
+ /* 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);
}
- 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[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[num_words * 2 - 1] = r0;
+ 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_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);
- }
+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;
+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);
+ /* 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);
+ 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;
+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;
- }
+ 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;
+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;
- }
+ 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(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);
+ }
+ 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;
+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;
+ 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_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_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve) { return uECC_vli_isZero(point, curve->num_words * 2); }
- 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);
-}
+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_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 */
+ 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;
- }
+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);
+ 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);
+ 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;
+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, 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_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);
+ 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;
+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(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(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_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_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);
+ 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;
+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);
+ 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);
+ 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);
+ 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);
-
- /* 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 */
-
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);
+ nb = !uECC_vli_testBit(scalar, 0);
+ XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[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 */
+
+ 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;
- }
-
- 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;
- }
- }
+ 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;
+ }
+ }
+ 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;
+}
+
+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);
+
+ if (uECC_vli_cmp_unsafe(_public, curve->G, NUM_ECC_WORDS * 2) == 0) {
+ return -4;
+ }
+
+ 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];
+
+ 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;
-}
-
-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);
-
- if (uECC_vli_cmp_unsafe(_public, curve->G, NUM_ECC_WORDS * 2) == 0) {
- return -4;
- }
-
- 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];
-
- 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;
- }
-
- 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;
- }
-
- 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;
+ }
+
+ 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;
+ }
+
+ 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 e2995ef2..e26b1526 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;
+}
+
+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);
+ /* 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);
+ /* erasing temporary buffer that stored secret: */
+ _set_secure(_private, 0, NUM_ECC_BYTES);
- return 1;
+ return 1;
}
- return 0;
+ }
+ 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;
+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];
- 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;
- }
+ 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 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));
+ /* 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);
- /* 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);
+ /* 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);
- /* erasing temporary buffer that stored secret: */
- _set_secure(_private, 0, NUM_ECC_BYTES);
-
- return 1;
- }
+ /* 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;
}
- return 0;
-}
+ initial_Z = p2[carry];
+ }
-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];
+ EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1, curve);
- 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);
-
- 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 117e3d26..6bad0933 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,209 @@ 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;
+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;
- }
+ 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);
- }
+ 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);
- }
+ /* 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;
+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;
- }
-
- /* 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 */
-
- /* 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 */
-
- 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;
-}
-
-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;
- }
- }
+ /* 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;
+ }
+
+ /* 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 */
+
+ /* 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 */
+
+ 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;
}
-static bitcount_t smax(bitcount_t a, bitcount_t b)
-{
- return (a > b ? a : b);
+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;
+ }
+ }
+ return 0;
}
-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;
+static bitcount_t smax(bitcount_t a, bitcount_t b) { return (a > b ? a : b); }
- 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);
+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;
- rx[num_n_words - 1] = 0;
- r[num_n_words - 1] = 0;
- s[num_n_words - 1] = 0;
+ 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);
- 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);
+ rx[num_n_words - 1] = 0;
+ r[num_n_words - 1] = 0;
+ s[num_n_words - 1] = 0;
- /* r, s must not be 0. */
- if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) {
- return 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;
+ }
+
+ /* 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);
}
+ }
- /* 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;
- }
+ uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
+ apply_z(rx, ry, z, curve);
- /* 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 */
+ /* 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);
+ }
- /* 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);
-
- /* 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 42dfee82..f958eb95 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,34 @@
#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 aee8a44e..287c323e 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;
+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;
- }
+ 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;
- }
+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;
+ 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;
- }
+ 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, ctx->key, TC_SHA256_BLOCK_SIZE);
+ (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;
+ 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_init(TCHmacState_t ctx) {
+ /* 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_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_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_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_final(tag, &ctx->hash_state);
+ (void)tc_sha256_update(&ctx->hash_state, data, data_length);
- (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));
-
- 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;
+ }
+
+ (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));
+
+ 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 8ef3c0c2..1c9971bd 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,137 @@ 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);
-
- (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));
-
- /* 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;
-
- /* 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));
+ 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);
+ }
+ 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));
+
+ /* 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;
+ }
+
+ /* 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);
+
+ /* 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);
+}
+
+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));
+
+ update(prng, personalization, plen, 0, 0);
+
+ /* force a reseed before allowing tc_hmac_prng_generate to succeed: */
+ prng->countdown = 0;
+
+ 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);
+ }
+ } else {
+ /* call update only for the seed */
+ update(prng, seed, seedlen, 0, 0);
+ }
+
+ /* ... and enable hmac_prng_generate */
+ prng->countdown = MAX_GENS;
+
+ 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;
+ }
+
+ prng->countdown--;
+
+ while (outlen != 0) {
/* configure the new prng key into the prng's instance of hmac */
- (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
+ tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key));
- /* use the new key to compute a new state variable v */
+ /* 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);
-}
-
-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));
-
- update(prng, personalization, plen, 0, 0);
-
- /* force a reseed before allowing tc_hmac_prng_generate to succeed: */
- prng->countdown = 0;
-
- 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);
- }
- } else {
- /* call update only for the seed */
- update(prng, seed, seedlen, 0, 0);
- }
-
- /* ... and enable hmac_prng_generate */
- prng->countdown = MAX_GENS;
-
- 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;
- }
-
- prng->countdown--;
-
- 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));
-
- /* 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);
-
- 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);
-
- return TC_CRYPTO_SUCCESS;
+
+ 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);
+
+ 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 57952104..1dab3607 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;
- }
+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;
+ /*
+ * 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;
+ 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;
}
-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->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;
- }
-
- /* 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);
+ s->leftover_offset = 0;
+ }
- /* 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);
- }
+ /* 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);
- /* destroy the current state */
- _set(s, 0, sizeof(*s));
+ /* hash the padding and length */
+ compress(s->iv, s->leftover);
- return TC_CRYPTO_SUCCESS;
+ /* 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 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 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;
+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];
+ 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 = 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);
+ 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;
- }
+ 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;
+ 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 137702a8..2cef6b05 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 bde33926..76071e3f 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;
-
- 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;
-
- 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;
- }
+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);
}
-int hex2char(uint8_t x, char *c)
-{
- if (x <= 9) {
- *c = x + '0';
- } else if (x <= 15) {
- *c = x - 10 + 'a';
- } else {
- return -1;
- }
+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);
}
-size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen)
-{
- if ((hexlen + 1) < buflen * 2) {
- 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;
+ }
- 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;
+ return 0;
}
-size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen)
-{
- uint8_t dec;
+int hex2char(uint8_t x, char *c) {
+ if (x <= 9) {
+ *c = x + '0';
+ } else if (x <= 15) {
+ *c = x - 10 + 'a';
+ } else {
+ return -1;
+ }
- 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++;
- }
-
- /* 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;
- }
-
- return hexlen / 2 + hexlen % 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;
+ }
+ }
+
+ 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;
+
+ 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++;
+ }
+
+ /* 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;
+ }
+
+ 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 f8f72ad6..86d2285c 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,295 @@ 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 defined(BFLB_BLE)
-static void work_queue_main(void *p1)
-{
- struct k_work *work;
- UNUSED(p1);
+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);
+ while (1) {
+ work = k_fifo_get(&g_work_queue_main.fifo, K_FOREVER);
- 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_init(struct k_work *work, k_work_handler_t handler)
-{
- ASSERT(work, "work is NULL");
-
- 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);
-}
-
-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;
+ if (atomic_test_and_clear_bit(work->flags, K_WORK_STATE_PENDING)) {
+ work->handler(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);
- }
+ k_yield();
+ }
}
-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);
+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_init(struct k_work *work, k_work_handler_t handler) {
+ ASSERT(work, "work is NULL");
+
+ 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); }
+
+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);
+ }
+}
+
+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;
+
+ /* 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;
+ }
+ }
+
+ 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;
+ }
-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;
- }
-
- /* Cancel if work has been submitted */
- if (work->work_q == work_q) {
- err = k_delayed_work_cancel(work);
-
- 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;
- }
-
- 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;
- }
+ if (work == NULL) {
+ return 0;
+ }
- timer = &work->timer;
- remain = timer->timeout - (k_now_ms() - timer->start_ms);
- if (remain < 0) {
- remain = 0;
- }
- return remain;
+ 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;
+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);
+ ARG_UNUSED(p2);
+ ARG_UNUSED(p3);
- while (1) {
- struct k_work *work;
- k_work_handler_t handler;
+ 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();
+ 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;
+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;
+ /* 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);
- }
-
- /* Detach from workqueue */
- work->work_q = NULL;
-
- atomic_clear_bit(work->work.flags, K_WORK_STATE_PENDING);
+ if (!work->work_q) {
irq_unlock(key);
+ return -EINVAL;
+ }
- return 0;
+ 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;
+
+ atomic_clear_bit(work->work.flags, K_WORK_STATE_PENDING);
+ irq_unlock(key);
+
+ 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 a992c5d1..47b1daf6 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,20 @@
#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,20 +32,19 @@
#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);
@@ -54,13 +53,12 @@ static K_SEM_DEFINE(sem_prio_recv, 0, BT_UINT_MAX);
K_FIFO_DEFINE(recv_fifo);
#if (BFLB_BLE_CO_THREAD)
extern struct k_sem g_poll_sem;
-static int recv_fifo_count = 0;
+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 +72,452 @@ 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;
+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))) {
+ 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;
-#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;
-#endif
- 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);
-
- 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;
-
-#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;
- }
- }
-#endif
-
- /* process regular node from radio */
- buf = encode_node(node_rx, class);
-
- 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);
- }
-
- 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);
- }
- 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);
- }
- }
- }
-
- 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);
-#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),
- };
-#endif
-
- 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);
- }
-#else
- struct radio_pdu_node_rx *node_rx = NULL;
- struct net_buf *buf = NULL;
-
- BT_DBG("blocking");
-#if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
- 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);
- }
-
- 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);
-
-#else
- 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);
- }
- }
-#endif
- 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
- }
-}
-#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);
- }
-}
-
-#if defined(CONFIG_BT_CONN)
-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);
- }
-
- return err;
-}
-#endif /* CONFIG_BT_CONN */
-#endif
-
-static int hci_driver_send(struct net_buf *buf)
-{
-#if !defined(BFLB_BLE)
- u8_t type;
-#endif
- int err;
-
- BT_DBG("enter");
-
- 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;
-#else
- type = bt_buf_get_type(buf);
- switch (type) {
-#if defined(CONFIG_BT_CONN)
- case BT_BUF_ACL_OUT:
- err = acl_handle(buf);
- break;
-#endif /* CONFIG_BT_CONN */
- case BT_BUF_CMD:
- err = cmd_handle(buf);
-
- break;
- default:
- BT_ERR("Unknown HCI type %u", type);
- return -EINVAL;
- }
-
- if (!err) {
- net_buf_unref(buf);
+ /* 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);
}
-
- BT_DBG("exit: %d", err);
+ 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;
#endif
- return err;
+ 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);
+
+ return buf;
}
-static int hci_driver_open(void)
-{
-#if !defined(BFLB_BLE)
- u32_t err;
+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;
- DEBUG_INIT();
- k_sem_init(&sem_prio_recv, 0, BT_UINT_MAX);
+#if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
+ if (hbuf_count != -1) {
+ bool pend = !sys_slist_is_empty(&hbuf_pend);
- err = ll_init(&sem_prio_recv);
-
- if (err) {
- BT_ERR("LL initialization failed: %u", err);
- return err;
+ /* 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);
+
+ 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);
+ }
+
+ 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);
+ }
+ 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);
+ }
+ }
+ }
+
+ 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);
+#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),
+ };
+#endif
+
+ 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);
+ }
+#else
+ struct radio_pdu_node_rx *node_rx = NULL;
+ struct net_buf *buf = NULL;
+
+ BT_DBG("blocking");
+#if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL)
+ 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);
+ }
+
+ 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);
+
+#else
+ 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);
+ }
+ }
+#endif
+ 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
+ }
+}
+#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);
+ }
+}
+
+#if defined(CONFIG_BT_CONN)
+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);
+ }
+
+ return err;
+}
+#endif /* CONFIG_BT_CONN */
+#endif
+
+static int hci_driver_send(struct net_buf *buf) {
+#if !defined(BFLB_BLE)
+ u8_t type;
+#endif
+ int err;
+
+ BT_DBG("enter");
+
+ 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;
+#else
+ type = bt_buf_get_type(buf);
+ switch (type) {
+#if defined(CONFIG_BT_CONN)
+ case BT_BUF_ACL_OUT:
+ err = acl_handle(buf);
+ break;
+#endif /* CONFIG_BT_CONN */
+ case BT_BUF_CMD:
+ err = cmd_handle(buf);
+
+ break;
+ default:
+ BT_ERR("Unknown HCI type %u", type);
+ return -EINVAL;
+ }
+
+ if (!err) {
+ net_buf_unref(buf);
+ } else {
+ }
+
+ BT_DBG("exit: %d", err);
+#endif
+ return err;
+}
+
+static int hci_driver_open(void) {
+#if !defined(BFLB_BLE)
+ u32_t err;
+
+ DEBUG_INIT();
+ k_sem_init(&sem_prio_recv, 0, BT_UINT_MAX);
+
+ err = ll_init(&sem_prio_recv);
+
+ 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);
+ k_fifo_init(&recv_fifo, 20);
#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));
+ 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));
+ 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);
+void hci_driver_enque_recvq(struct net_buf *buf) {
+ net_buf_put(&recv_fifo, buf);
#if (BFLB_BLE_CO_THREAD)
- recv_fifo_count++;
+ recv_fifo_count++;
#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
index 82901ed2..6a7ddc1b 100644
--- 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
@@ -8,84 +8,61 @@
* 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
#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 "a2dp_internal.h"
+#include "avdtp_internal.h"
+#include "conn_internal.h"
+#include "hci_core.h"
#include "oi_codec_sbc.h"
#define A2DP_NO_SPACE (-1)
struct bt_a2dp {
- struct bt_avdtp session;
+ 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];
+ 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_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_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"),
};
@@ -96,164 +73,131 @@ 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 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 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));
-}
+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;
+struct bt_a2dp *get_new_connection(struct bt_conn *conn) {
+ int8_t i, free;
- free = A2DP_NO_SPACE;
+ free = A2DP_NO_SPACE;
- if (!conn) {
- BT_ERR("Invalid Input (err: %d)", -EINVAL);
+ 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;
+ }
}
- /* 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 (!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;
- }
+ 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];
+ /* Clean the memory area before returning */
+ a2d_reset(&connection[free]);
+ stream_reset(&stream[free]);
+ connection[free].session.streams = &stream[free];
- return &connection[free];
+ return &connection[free];
}
-int a2dp_accept(struct bt_conn *conn, struct bt_avdtp **session)
-{
- struct bt_a2dp *a2dp_conn;
+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;
- }
+ a2dp_conn = get_new_connection(conn);
+ if (!a2dp_conn) {
+ return -ENOMEM;
+ }
- *session = &(a2dp_conn->session);
- BT_DBG("session: %p", &(a2dp_conn->session));
+ *session = &(a2dp_conn->session);
+ BT_DBG("session: %p", &(a2dp_conn->session));
- return 0;
+ 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;
- }
+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;
+ return 0;
}
#if PCM_PRINTF
-extern int16_t cool_edit[];
+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;
+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_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 (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;
+ memcpy((OI_INT8 *)cool_edit + byte_index, pcm, pcm_size);
+ byte_index += pcm_size;
#endif
- }
+ }
- return 0;
+ return 0;
}
/* Callback for incoming requests */
@@ -262,82 +206,75 @@ static struct bt_avdtp_ind_cb cb_ind = {
};
/* 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
-};
+static struct bt_avdtp_event_cb avdtp_cb = {.ind = &cb_ind, .accept = a2dp_accept};
-int bt_a2dp_init(void)
-{
- int err;
+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 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;
- }
+ /* 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;
- }
+ 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();
+ bt_a2dp_set_sbc_codec_info();
- err = a2dp_sbc_decode_init();
- if (err < 0) {
- BT_ERR("sbc codec init failed");
- return err;
- }
+ err = a2dp_sbc_decode_init();
+ if (err < 0) {
+ BT_ERR("sbc codec init failed");
+ return err;
+ }
- BT_DBG("A2DP Initialized successfully.");
- return 0;
+ BT_DBG("A2DP Initialized successfully.");
+ return 0;
}
-struct bt_a2dp *bt_a2dp_connect(struct bt_conn *conn)
-{
- struct bt_a2dp *a2dp_conn;
- int err;
+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;
- }
+ 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;
- }
+ 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;
+ 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;
+int bt_a2dp_register_endpoint(struct bt_a2dp_endpoint *endpoint, uint8_t media_type, uint8_t role) {
+ int err;
- BT_ASSERT(endpoint);
+ BT_ASSERT(endpoint);
- err = bt_avdtp_register_sep(media_type, role, &(endpoint->info));
- if (err < 0) {
- return err;
- }
+ err = bt_avdtp_register_sep(media_type, role, &(endpoint->info));
+ if (err < 0) {
+ return err;
+ }
- return 0;
+ return 0;
}
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 189ff4b2..0f1feaf4 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';
- }
-
- if (i == 0U) {
- return -ENODATA;
- }
-
- 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;
- }
-
- 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;
- }
-
- if ((!strncmp(str, "ERROR", 5)) && (at_check_byte(buf, '\n')) == 0) {
- *result = AT_RESULT_ERROR;
- return 0;
- }
-
- 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);
-
- 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);
-
- 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 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;
-
- return 0;
-}
-
-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;
-
- 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;
- }
+ 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;
+ }
+
+ next_list(at);
+ return 0;
}
-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 str_has_prefix(const char *str, const char *prefix) {
+ if (strncmp(str, prefix, strlen(prefix)) != 0) {
return false;
+ }
+
+ return true;
}
-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_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 (at->resp) {
- at->resp(at, buf);
- at->resp = NULL;
- return 0;
+ if ((!strncmp(str, "ERROR", 5)) && (at_check_byte(buf, '\n')) == 0) {
+ *result = AT_RESULT_ERROR;
+ return 0;
+ }
+
+ 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);
+
+ 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);
+
+ 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 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;
+
+ return 0;
+}
+
+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;
+
+ 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;
+}
+
+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;
+ }
+
+ 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;
+ }
+
+ 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 bool is_ring(struct at_client *at) {
+ if (strncmp(at->buf, "RING", 4) == 0) {
+ return true;
+ }
+
+ 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;
+
+ if (is_ring(at)) {
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 bool is_ring(struct at_client *at)
-{
- if (strncmp(at->buf, "RING", 4) == 0) {
- return true;
- }
-
- 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;
-
- 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);
- }
- }
-
- /* Reset the state to process unsolicited response */
- at->cmd_state = AT_CMD_START;
- at->state = AT_STATE_START;
-
- return 0;
-}
-
-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_parse_result(at->buf, buf, &result) == 0) {
if (at->finish) {
- at->finish(at, AT_RESULT_CME_ERROR, cme_err);
+ /* cme_err is 0 - Is invalid until result is
+ * AT_RESULT_CME_ERROR
+ */
+ cme_err = 0;
+ at->finish(at, result, cme_err);
}
+ }
- return 0;
+ /* Reset the state to process unsolicited response */
+ at->cmd_state = AT_CMD_START;
+ at->state = AT_STATE_START;
+
+ 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);
+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->finish) {
+ at->finish(at, AT_RESULT_CME_ERROR, cme_err);
+ }
+
+ return 0;
}
-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_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);
+}
- return -ENODATA;
+static int at_state_unsolicited_cmd(struct at_client *at, struct net_buf *buf) {
+ if (at->unsolicited) {
+ return at->unsolicited(at, buf);
+ }
+
+ 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;
+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;
- }
+ 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;
+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;
- }
+ 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;
+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;
- }
+ 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);
+
+ /* The list shall start with '(' open parenthesis */
+ if (at->buf[at->pos] != '(') {
+ return -ENODATA;
+ }
+ at->pos++;
+
+ return 0;
}
-int at_open_list(struct at_client *at)
-{
- skip_space(at);
+int at_close_list(struct at_client *at) {
+ skip_space(at);
- /* The list shall start with '(' open parenthesis */
- if (at->buf[at->pos] != '(') {
- return -ENODATA;
- }
- at->pos++;
+ if (at->buf[at->pos] != ')') {
+ return -ENODATA;
+ }
+ at->pos++;
- return 0;
+ next_list(at);
+
+ return 0;
}
-int at_close_list(struct at_client *at)
-{
- 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);
- next_list(at);
-
- return 0;
-}
-
-int at_list_get_string(struct at_client *at, char *name, uint8_t len)
-{
- int i = 0;
-
- skip_space(at);
-
- if (at->buf[at->pos] != '"') {
- return -ENODATA;
- }
- at->pos++;
-
- 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;
- }
+ name[i] = '\0';
+
+ if (at->buf[at->pos] != '"') {
+ return -ENODATA;
+ }
+ at->pos++;
+
+ skip_space(at);
+ next_list(at);
+
+ return 0;
+}
+
+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;
+ }
+
+ if (at->buf[at->pos] == '-') {
at->pos++;
+ goto out;
+ }
- skip_space(at);
- next_list(at);
-
- return 0;
-}
-
-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;
- }
-
- 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 d792f0b6..52f2ad92 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,29 +6,29 @@
* SPDX-License-Identifier: Apache-2.0
*/
-#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_ATT)
#include "log.h"
-#include "hci_core.h"
+#include "att_internal.h"
#include "conn_internal.h"
+#include "gatt_internal.h"
+#include "hci_core.h"
#include "l2cap_internal.h"
#include "smp.h"
-#include "att_internal.h"
-#include "gatt_internal.h"
#define ATT_CHAN(_ch) CONTAINER_OF(_ch, struct bt_att, chan.chan)
#define ATT_REQ(_node) CONTAINER_OF(_node, struct bt_att_req, node)
@@ -38,53 +38,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 +91,2113 @@ 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;
- }
- }
-#endif
- 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;
-
- 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);
- }
-
- if (!att_send(conn, buf, NULL, NULL)) {
- return;
- }
- }
-
- k_sem_give(&att->tx_sem);
-}
-
-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);
-
- if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
- atomic_clear_bit(att->flags, ATT_PENDING_CFM);
- }
-
- att_pdu_sent(conn, user_data);
-}
-
-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);
-
- if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
- atomic_clear_bit(att->flags, ATT_PENDING_RSP);
- }
-
- att_pdu_sent(conn, user_data);
-}
-
-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);
-
- /* 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;
- }
-}
-
-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;
-
- /* Ignore opcode 0x00 */
- if (!req) {
- return;
- }
-
- buf = bt_att_create_pdu(conn, BT_ATT_OP_ERROR_RSP, sizeof(*rsp));
- if (!buf) {
- return;
- }
-
- 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;
-
- req = (void *)buf->data;
-
- mtu_client = sys_le16_to_cpu(req->mtu);
-
- 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;
- }
-
- 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;
-
- BT_DBG("Server MTU %u", 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);
-
- /* 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);
-
-#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);
-#endif
-
- 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 int att_send_req(struct bt_att *att, struct bt_att_req *req)
-{
+ if (hdr->code == BT_ATT_OP_SIGNED_WRITE_CMD) {
int err;
- __ASSERT_NO_MSG(req);
- __ASSERT_NO_MSG(req->func);
- __ASSERT_NO_MSG(!att->req);
-
- BT_DBG("req %p", 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;
- }
-
- /* 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);
+ err = bt_smp_sign(conn, buf);
if (err) {
- net_buf_unref(req->buf);
- req->buf = NULL;
- return 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);
+}
+
+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);
+
+ 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;
+ }
+ }
+
+ k_sem_give(&att->tx_sem);
+}
+
+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);
+
+ if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
+ atomic_clear_bit(att->flags, ATT_PENDING_CFM);
+ }
+
+ att_pdu_sent(conn, user_data);
+}
+
+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);
+
+ if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) {
+ atomic_clear_bit(att->flags, ATT_PENDING_RSP);
+ }
+
+ att_pdu_sent(conn, user_data);
+}
+
+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);
+
+ /* 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;
+ }
+}
+
+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;
+
+ /* Ignore opcode 0x00 */
+ if (!req) {
+ return;
+ }
+
+ buf = bt_att_create_pdu(conn, BT_ATT_OP_ERROR_RSP, sizeof(*rsp));
+ if (!buf) {
+ return;
+ }
+
+ 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;
+
+ req = (void *)buf->data;
+
+ mtu_client = sys_le16_to_cpu(req->mtu);
+
+ 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;
+ }
+
+ 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;
+
+ BT_DBG("Server MTU %u", 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);
+
+ /* 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);
+
+#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);
+ }
+#endif
+
+ 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 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);
+
+ BT_DBG("req %p", 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;
+ }
+
+ /* 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;
+ }
+
+ 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;
- }
-
- /* 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;
- }
-
- /* Reset func so it can be reused by the callback */
- func = att->req->func;
- att->req->func = NULL;
-
- 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);
- }
+ 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;
+ }
+
+ /* 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;
+
+ 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);
+ }
+
+ 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;
}
- 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);
- /* 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;
- }
+ if (att->chan.tx.mtu - data->buf->len > sizeof(*data->info16)) {
+ return BT_GATT_ITER_CONTINUE;
}
- return BT_GATT_ITER_STOP;
+ 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;
+ }
+ }
+
+ 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;
+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));
+ (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.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);
+ 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];
+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;
+ /* 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);
}
-
- /* 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);
-
- /* 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;
- }
-
- /* 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 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);
-
- /* continue to find the end_handle */
return BT_GATT_ITER_CONTINUE;
+ }
+
+ 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;
+ }
+
+ /* 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;
+
+ 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;
+
+ /* 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;
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));
-
- 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;
-
- /* 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);
-
- /* 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;
- }
-
-#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);
-
- 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);
-
- 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));
-
- 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;
-
- BT_DBG("start_handle 0x%04x end_handle 0x%04x type %u", start_handle,
- end_handle, type);
-
- 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);
-}
-
-static u8_t err_to_att(int err)
-{
- BT_DBG("%d", err);
-
- if (err < 0 && err >= -0xff) {
- return -err;
- }
+ (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.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;
+
+ 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 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;
+ }
+
+#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);
+
+ 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);
+
+ 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));
+
+ 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;
+
+ BT_DBG("start_handle 0x%04x end_handle 0x%04x type %u", start_handle, end_handle, type);
+
+ 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);
+}
+
+static u8_t err_to_att(int err) {
+ BT_DBG("%d", err);
+
+ if (err < 0 && err >= -0xff) {
+ return -err;
+ }
+
+ 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;
+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;
+ /* 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;
+ }
- BT_DBG("handle 0x%04x", attr->handle);
+ /*
+ * 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;
- /*
- * 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;
- }
+ /* 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);
- /*
- * 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;
+ /* 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;
+ }
- /* 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);
+ 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;
+ }
- /* 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;
- }
+ net_buf_add(data->buf, read);
- 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);
-
- /* 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);
+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;
- }
+ /* Type can only be UUID16 or UUID128 */
+ if (uuid_len != 2 && uuid_len != 16) {
+ return BT_ATT_ERR_INVALID_PDU;
+ }
- req = net_buf_pull_mem(buf, sizeof(*req));
+ req = net_buf_pull_mem(buf, sizeof(*req));
- 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;
- }
+ 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;
+ }
- BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s",
- start_handle, end_handle, bt_uuid_str(&u.uuid));
+ BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", start_handle, end_handle, bt_uuid_str(&u.uuid));
- 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;
- }
+ 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);
+ 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;
+ /*
+ * 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;
- }
+ /* Check attribute permissions */
+ data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK);
+ if (data->err) {
+ return BT_GATT_ITER_STOP;
+ }
- /* 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;
- }
+ /* 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;
+ }
- net_buf_add(data->buf, read);
+ net_buf_add(data->buf, read);
- return BT_GATT_ITER_CONTINUE;
+ 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 */
+ /* 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);
+
+ /* 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);
+
+ 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;
+
+ req = (void *)buf->data;
+
+ handle = sys_le16_to_cpu(req->handle);
+
+ BT_DBG("handle 0x%04x", handle);
+
+ 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;
+
+ req = (void *)buf->data;
+
+ handle = sys_le16_to_cpu(req->handle);
+ offset = sys_le16_to_cpu(req->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);
+}
+
+#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;
+
+ (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.att = att;
+
+ while (buf->len >= sizeof(u16_t)) {
+ handle = net_buf_pull_le16(buf);
+
+ 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;
bt_gatt_foreach_attr(handle, handle, read_cb, &data);
- /* In case of error discard data and respond with an error */
+ /* Stop reading in case of 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;
+ 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;
-}
-
-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;
-
- handle = sys_le16_to_cpu(req->handle);
-
- BT_DBG("handle 0x%04x", handle);
-
- 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;
-
- req = (void *)buf->data;
-
- handle = sys_le16_to_cpu(req->handle);
- offset = sys_le16_to_cpu(req->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);
-}
-
-#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;
-
- (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.att = att;
-
- while (buf->len >= sizeof(u16_t)) {
- handle = net_buf_pull_le16(buf);
-
- 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;
-
- 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;
- }
- }
-
- (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;
+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;
+ /* 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);
}
-
- /* If Group Type don't match skip */
- if (bt_uuid_cmp(attr->uuid, data->uuid)) {
- data->group = NULL;
- return BT_GATT_ITER_CONTINUE;
- }
-
- BT_DBG("handle 0x%04x", attr->handle);
-
- /* 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;
- }
-
- /* Fast forward to next group position */
- data->group = net_buf_add(data->buf, sizeof(*data->group));
-
- /* Initialize group handle range */
- data->group->start_handle = sys_cpu_to_le16(attr->handle);
- data->group->end_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) {
- /* TODO: Handle read errors */
- return BT_GATT_ITER_STOP;
- }
-
- 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;
- }
-
- net_buf_add(data->buf, read);
-
- /* Continue to find the end handle */
return BT_GATT_ITER_CONTINUE;
+ }
+
+ /* If Group Type don't match skip */
+ if (bt_uuid_cmp(attr->uuid, data->uuid)) {
+ data->group = NULL;
+ return BT_GATT_ITER_CONTINUE;
+ }
+
+ BT_DBG("handle 0x%04x", attr->handle);
+
+ /* 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;
+ }
+
+ /* Fast forward to next group position */
+ data->group = net_buf_add(data->buf, sizeof(*data->group));
+
+ /* Initialize group handle range */
+ data->group->start_handle = sys_cpu_to_le16(attr->handle);
+ data->group->end_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) {
+ /* TODO: Handle read errors */
+ return BT_GATT_ITER_STOP;
+ }
+
+ 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;
+ }
+
+ 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);
-
- 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);
+ 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;
+ }
+
+ (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
+
+ 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);
+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;
- }
+ /* Type can only be UUID16 or UUID128 */
+ if (uuid_len != 2 && uuid_len != 16) {
+ return BT_ATT_ERR_INVALID_PDU;
+ }
- req = net_buf_pull_mem(buf, sizeof(*req));
+ req = net_buf_pull_mem(buf, sizeof(*req));
- 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);
- if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) {
- return BT_ATT_ERR_UNLIKELY;
- }
+ if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) {
+ return BT_ATT_ERR_UNLIKELY;
+ }
- BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s",
- start_handle, end_handle, bt_uuid_str(&u.uuid));
+ BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", start_handle, end_handle, bt_uuid_str(&u.uuid));
- 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;
- }
+ 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;
- }
+ /* 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;
+ }
+
+ (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;
}
+ }
- if (!handle) {
- return 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;
- (void)memset(&data, 0, sizeof(data));
+ bt_gatt_foreach_attr(handle, handle, write_cb, &data);
- /* Only allocate buf if required to respond */
+ if (data.err) {
+ /* In case of error discard data and respond with an error */
if (rsp) {
- data.buf = bt_att_create_pdu(conn, rsp, 0);
- if (!data.buf) {
- return BT_ATT_ERR_UNLIKELY;
- }
+ 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;
+ }
- data.conn = conn;
- data.req = req;
- data.offset = offset;
- data.value = value;
- data.len = len;
- data.err = BT_ATT_ERR_INVALID_HANDLE;
+ if (data.buf) {
+ (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
+ }
- 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.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);
-
- 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);
-
- /* 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;
- }
-
- 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);
+ 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;
+ }
+
+ 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);
+
+ /* 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);
+
+ (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, NULL);
+
+ 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;
+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);
+ 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);
+ 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);
+ /* 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);
+ }
}
- 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);
+ 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;
+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;
+ 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;
- }
+ 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;
- }
+ /* 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);
+ 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;
+
+ handle = net_buf_pull_le16(buf);
+
+ BT_DBG("handle 0x%04x", handle);
+
+ bt_gatt_notification(conn, handle, buf->data, buf->len);
+
+ buf = bt_att_create_pdu(conn, BT_ATT_OP_CONFIRM, 0);
+ if (!buf) {
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;
+ (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_cfm_sent, NULL);
- handle = net_buf_pull_le16(buf);
-
- BT_DBG("handle 0x%04x", handle);
-
- bt_gatt_notification(conn, handle, buf->data, buf->len);
-
- 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);
-
- 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;
- }
+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;
- }
+ if (op & ATT_CMD_MASK) {
+ return ATT_COMMAND;
+ }
- return ATT_UNKNOWN;
+ 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 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);
+ }
+
+ return 0;
}
-static struct bt_att *att_chan_get(struct bt_conn *conn)
-{
- struct bt_l2cap_chan *chan;
- struct bt_att *att;
+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;
- }
+ 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;
- }
+ 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;
- }
+ att = ATT_CHAN(chan);
+ if (atomic_test_bit(att->flags, ATT_DISCONNECTED)) {
+ BT_WARN("ATT context flagged as disconnected");
+ return NULL;
+ }
- return att;
+ 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;
+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;
- }
+ 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;
- }
+ 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);
- }
+ 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;
- }
+ 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;
+ hdr = net_buf_add(buf, sizeof(*hdr));
+ hdr->code = op;
- return buf;
+ return buf;
}
-static void att_reset(struct bt_att *att)
-{
- struct bt_att_req *req, *tmp;
- int i;
- struct net_buf *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);
+
+ /* 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);
}
- atomic_set_bit(att->flags, ATT_DISCONNECTED);
+ att_req_destroy(req);
+ }
- /* Ensure that any waiters are woken up */
- for (i = 0; i < CONFIG_BT_ATT_TX_MAX; i++) {
- k_sem_give(&att->tx_sem);
- }
+ /* Reset list */
+ sys_slist_init(&att->reqs);
- /* 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);
- }
+ if (!att->req) {
+ return;
+ }
- att_req_destroy(req);
- }
-
- /* 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;
+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);
+ 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;
- }
+ /*
+ * 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);
+ bt_gatt_encrypt_change(conn);
- if (conn->sec_level == BT_SECURITY_L1) {
- return;
- }
+ if (conn->sec_level == BT_SECURITY_L1) {
+ return;
+ }
- if (!att->req || !att->req->retrying) {
- 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;
- }
+ k_sem_take(&att->tx_sem, K_FOREVER);
+ 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;
- }
-
- (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;
-
- return 0;
+ if (att->chan.chan.conn) {
+ continue;
}
- BT_ERR("No available ATT context for conn %p", conn);
+ (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);
- return -ENOMEM;
+ *chan = &att->chan.chan;
+
+ return 0;
+ }
+
+ BT_ERR("No available ATT context for conn %p", conn);
+
+ 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);
+ net_buf_init(&prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU, NULL);
#endif
#endif
- bt_gatt_init();
+ bt_gatt_init();
}
-u16_t bt_att_get_mtu(struct bt_conn *conn)
-{
- struct bt_att *att;
-
- att = att_chan_get(conn);
- if (!att) {
- return 0;
- }
-
- /* 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;
-
- __ASSERT_NO_MSG(conn);
- __ASSERT_NO_MSG(buf);
-
- 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;
- }
- }
-
- err = att_send(conn, buf, cb, user_data);
- if (err) {
- if (!cb) {
- k_sem_give(&att->tx_sem);
- }
- return err;
- }
+u16_t bt_att_get_mtu(struct bt_conn *conn) {
+ struct bt_att *att;
+ att = att_chan_get(conn);
+ if (!att) {
return 0;
+ }
+
+ /* tx and rx MTU shall be symmetric */
+ return att->chan.tx.mtu;
}
-int bt_att_req_send(struct bt_conn *conn, struct bt_att_req *req)
-{
- struct bt_att *att;
+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;
- BT_DBG("conn %p req %p", conn, req);
+ __ASSERT_NO_MSG(conn);
+ __ASSERT_NO_MSG(buf);
- __ASSERT_NO_MSG(conn);
- __ASSERT_NO_MSG(req);
+ att = att_chan_get(conn);
+ if (!att) {
+ net_buf_unref(buf);
+ return -ENOTCONN;
+ }
- att = att_chan_get(conn);
- if (!att) {
- net_buf_unref(req->buf);
- req->buf = NULL;
- 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;
}
+ }
- /* 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;
+ err = att_send(conn, buf, cb, user_data);
+ if (err) {
+ if (!cb) {
+ k_sem_give(&att->tx_sem);
}
+ return err;
+ }
- return att_send_req(att, req);
+ return 0;
}
-void bt_att_req_cancel(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("req %p", req);
+ BT_DBG("conn %p req %p", conn, req);
- if (!conn || !req) {
- return;
- }
+ __ASSERT_NO_MSG(conn);
+ __ASSERT_NO_MSG(req);
- att = att_chan_get(conn);
- if (!att) {
- return;
- }
+ att = att_chan_get(conn);
+ if (!att) {
+ net_buf_unref(req->buf);
+ req->buf = NULL;
+ return -ENOTCONN;
+ }
- /* 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 there is a request outstanding */
+ if (att->req) {
+ /* Queue the request to be send later */
+ sys_slist_append(&att->reqs, &req->node);
+ return 0;
+ }
- att_req_destroy(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;
+
+ BT_DBG("req %p", req);
+
+ if (!conn || !req) {
+ 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);
+ }
+
+ att_req_destroy(req);
}
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att_internal.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att_internal.h
index f591a8b8..68fd8348 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att_internal.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/att_internal.h
@@ -5,7 +5,7 @@
*
* SPDX-License-Identifier: Apache-2.0
*/
-
+#include "conn_internal.h"
#define BT_ATT_DEFAULT_LE_MTU 23
#if BT_L2CAP_RX_MTU < CONFIG_BT_L2CAP_TX_MTU
diff --git a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/avdtp_internal.h b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/avdtp_internal.h
index e182689f..7825a6e4 100644
--- a/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/avdtp_internal.h
+++ b/source/Core/BSP/Pinecilv2/bl_mcu_sdk/components/ble/ble_stack/host/avdtp_internal.h
@@ -7,6 +7,9 @@
*/
#include
+#include "l2cap.h"
+#ifndef BLE_STACK_HOST_AVDTP_INTERNAL_H_
+#define BLE_STACK_HOST_AVDTP_INTERNAL_H_
/* @brief A2DP ROLE's */
#define A2DP_SRC_ROLE 0x00
@@ -173,3 +176,5 @@ int bt_avdtp_register_sep(uint8_t media_type, uint8_t role,
/* AVDTP Discover Request */
int bt_avdtp_discover(struct bt_avdtp *session,
struct bt_avdtp_discover_params *param);
+
+#endif
\ No newline at end of file
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 6644abcd..1e389fae 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,49 +6,48 @@
* 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
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_CONN)
#define LOG_MODULE_NAME bt_conn
#include "log.h"
-#include "hci_core.h"
-#include "conn_internal.h"
-#include "l2cap_internal.h"
-#include "keys.h"
-#include "smp.h"
#include "att_internal.h"
#include "gatt_internal.h"
+#include "hci_core.h"
+#include "keys.h"
+#include "l2cap_internal.h"
+#include "smp.h"
+
+#include "conn_internal.h"
#if defined(BFLB_BLE)
#include "ble_config.h"
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 +67,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 +80,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 +90,2410 @@ 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 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 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->err) {
+ bt_gatt_connected(conn);
+ }
}
-static void notify_disconnected(struct bt_conn *conn)
-{
- struct bt_conn_cb *cb;
+static 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;
+bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param) {
+ 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_param_req) {
+ continue;
+ }
+
+ if (!cb->le_param_req(conn, 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;
+ return false;
}
+ }
- for (cb = callback_list; cb; cb = cb->_next) {
- if (!cb->le_param_req) {
- continue;
- }
-
- if (!cb->le_param_req(conn, 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;
- }
- }
-
- /* Default to accepting if there's no app callback */
- return true;
+ /* Default to accepting if there's no app callback */
+ return true;
}
-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);
+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);
- /* 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;
+ /* 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;
- rc = bt_conn_le_conn_update(conn, param);
+ rc = bt_conn_le_conn_update(conn, param);
- /* store those in case of fallback to L2CAP */
- if (rc == 0) {
- conn->le.pending_latency = param->latency;
- conn->le.pending_timeout = param->timeout;
- }
-
- 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;
- }
-
- 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);
-
- /* 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);
-
- /* 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);
+ 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);
+
+ 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;
+
+ /* 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);
+ }
}
-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;
+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);
+ BT_DBG("conn %p", conn);
- if (conn->state == BT_CONN_DISCONNECTED) {
- bt_l2cap_disconnected(conn);
- notify_disconnected(conn);
+ if (conn->state == BT_CONN_DISCONNECTED) {
+ bt_l2cap_disconnected(conn);
+ notify_disconnected(conn);
- /* Release the reference we took for the very first
- * state transition.
- */
- bt_conn_unref(conn);
- 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 (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 (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);
+ /* 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);
+ 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);
- }
+ 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) {
+ size_t 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) {
+ size_t 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;
+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_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;
- }
+ conn = bt_conn_add_br(peer);
+ if (!conn) {
+ return NULL;
+ }
- buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT, sizeof(*cp));
- if (!buf) {
- bt_conn_unref(conn);
- return NULL;
- }
+ buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT, sizeof(*cp));
+ if (!buf) {
+ bt_conn_unref(conn);
+ return NULL;
+ }
- cp = net_buf_add(buf, sizeof(*cp));
+ cp = net_buf_add(buf, sizeof(*cp));
- (void)memset(cp, 0, sizeof(*cp));
+ (void)memset(cp, 0, 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 */
+ 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 */
- if (bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT, buf, NULL) < 0) {
- bt_conn_unref(conn);
- return NULL;
- }
+ if (bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT, buf, NULL) < 0) {
+ bt_conn_unref(conn);
+ return NULL;
+ }
- bt_conn_set_state(conn, BT_CONN_CONNECT);
- conn->role = BT_CONN_ROLE_MASTER;
+ bt_conn_set_state(conn, BT_CONN_CONNECT);
+ conn->role = BT_CONN_ROLE_MASTER;
- return 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;
+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;
- }
+ 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;
+ }
+ }
+
+ if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) {
+ link_type = BT_HCI_ESCO;
+ } else {
+ link_type = BT_HCI_SCO;
+ }
+
+ sco_conn = bt_conn_add_sco(peer, link_type);
+ if (!sco_conn) {
+ return NULL;
+ }
+
+ buf = bt_hci_cmd_create(BT_HCI_OP_SETUP_SYNC_CONN, sizeof(*cp));
+ if (!buf) {
+ bt_sco_cleanup(sco_conn);
+ return NULL;
+ }
+
+ cp = net_buf_add(buf, sizeof(*cp));
+
+ (void)memset(cp, 0, sizeof(*cp));
+
+ BT_ERR("handle : %x", sco_conn->sco.acl->handle);
+
+ 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;
+
+ 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;
+}
+
+struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer) {
+ size_t i;
+
+ 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 (!bt_addr_cmp(peer, &sco_conns[i].sco.acl->br.dst)) {
+ return bt_conn_ref(&sco_conns[i]);
+ }
+ }
+
+ return NULL;
+}
+
+struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer) {
+ size_t i;
+
+ 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 (!bt_addr_cmp(peer, &conns[i].br.dst)) {
+ return bt_conn_ref(&conns[i]);
+ }
+ }
+
+ 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();
+
+ if (!sco_conn) {
+ return NULL;
+ }
+
+ 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)) {
- link_type = BT_HCI_ESCO;
+ sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & ESCO_PKT_MASK);
} else {
- link_type = BT_HCI_SCO;
+ 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);
+ }
- sco_conn = bt_conn_add_sco(peer, link_type);
- if (!sco_conn) {
- return NULL;
- }
-
- buf = bt_hci_cmd_create(BT_HCI_OP_SETUP_SYNC_CONN, sizeof(*cp));
- if (!buf) {
- bt_sco_cleanup(sco_conn);
- return NULL;
- }
-
- cp = net_buf_add(buf, sizeof(*cp));
-
- (void)memset(cp, 0, sizeof(*cp));
-
- BT_ERR("handle : %x", sco_conn->sco.acl->handle);
-
- 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;
-
- 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;
-
- 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 (!bt_addr_cmp(peer, &sco_conns[i].sco.acl->br.dst)) {
- return bt_conn_ref(&sco_conns[i]);
- }
- }
+struct bt_conn *bt_conn_add_br(const bt_addr_t *peer) {
+ struct bt_conn *conn = conn_new();
+ if (!conn) {
return NULL;
+ }
+
+ bt_addr_copy(&conn->br.dst, peer);
+ conn->type = BT_CONN_TYPE_BR;
+
+ return conn;
}
-struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer)
-{
- int i;
+static int pin_code_neg_reply(const bt_addr_t *bdaddr) {
+ struct bt_hci_cp_pin_code_neg_reply *cp;
+ struct net_buf *buf;
- for (i = 0; i < ARRAY_SIZE(conns); i++) {
- if (!atomic_get(&conns[i].ref)) {
- continue;
- }
+ BT_DBG("");
- if (conns[i].type != BT_CONN_TYPE_BR) {
- continue;
- }
+ buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_NEG_REPLY, sizeof(*cp));
+ if (!buf) {
+ return -ENOBUFS;
+ }
- if (!bt_addr_cmp(peer, &conns[i].br.dst)) {
- return bt_conn_ref(&conns[i]);
- }
- }
+ cp = net_buf_add(buf, sizeof(*cp));
+ bt_addr_copy(&cp->bdaddr, bdaddr);
- return NULL;
+ return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_NEG_REPLY, buf, NULL);
}
-struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type)
-{
- struct bt_conn *sco_conn = sco_conn_new();
+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;
- if (!sco_conn) {
- return NULL;
- }
+ BT_DBG("");
- sco_conn->sco.acl = bt_conn_lookup_addr_br(peer);
- sco_conn->type = BT_CONN_TYPE_SCO;
+ buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_REPLY, sizeof(*cp));
+ if (!buf) {
+ return -ENOBUFS;
+ }
- 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);
- }
+ cp = net_buf_add(buf, sizeof(*cp));
- return sco_conn;
+ 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);
}
-struct bt_conn *bt_conn_add_br(const bt_addr_t *peer)
-{
- struct bt_conn *conn = conn_new();
+int bt_conn_auth_pincode_entry(struct bt_conn *conn, const char *pin) {
+ size_t len;
- if (!conn) {
- return NULL;
- }
+ if (!bt_auth) {
+ return -EINVAL;
+ }
- bt_addr_copy(&conn->br.dst, peer);
- conn->type = BT_CONN_TYPE_BR;
+ if (conn->type != BT_CONN_TYPE_BR) {
+ return -EINVAL;
+ }
- return conn;
+ 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;
+ }
+
+ /* 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);
+ }
+
+ return pin_code_reply(conn, pin, len);
}
-static int pin_code_neg_reply(const bt_addr_t *bdaddr)
-{
- struct bt_hci_cp_pin_code_neg_reply *cp;
- struct net_buf *buf;
+void bt_conn_pin_code_req(struct bt_conn *conn) {
+ if (bt_auth && bt_auth->pincode_entry) {
+ bool secure = false;
- BT_DBG("");
-
- buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_NEG_REPLY, sizeof(*cp));
- if (!buf) {
- return -ENOBUFS;
+ if (conn->required_sec_level == BT_SECURITY_L3) {
+ secure = true;
}
- 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);
+ 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);
+ }
}
-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("");
-
- buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_REPLY, sizeof(*cp));
- if (!buf) {
- return -ENOBUFS;
- }
-
- 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));
-
- 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;
-
- if (!bt_auth) {
- return -EINVAL;
- }
-
- if (conn->type != BT_CONN_TYPE_BR) {
- 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;
- }
-
- /* 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);
- }
-
- 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;
- }
-
- 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;
- }
-
- 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_display) {
- return BT_IO_DISPLAY_ONLY;
- }
-
+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_entry) {
+ return BT_IO_KEYBOARD_ONLY;
+ }
+
+ if (bt_auth->passkey_display) {
+ return BT_IO_DISPLAY_ONLY;
+ }
+
+ 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;
+ }
+
+ /* 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);
}
-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;
+static int ssp_confirm_reply(struct bt_conn *conn) {
+ struct bt_hci_cp_user_confirm_reply *cp;
+ struct net_buf *buf;
+
+ BT_DBG("");
+
+ 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);
+
+ 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;
+
+ BT_DBG("");
+
+ 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);
+
+ 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);
+
+ if (bt_auth && bt_auth->pairing_complete) {
+ bt_auth->pairing_complete(conn, bond);
}
-
- /* Local & remote have enough IO capabilities to get MITM protection. */
- if (ssp_pair_method(conn) > JUST_WORKS) {
- return conn->br.remote_auth | BT_MITM;
+ } else {
+ if (bt_auth && bt_auth->pairing_failed) {
+ bt_auth->pairing_failed(conn, status);
}
-
- /* 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;
+void bt_conn_ssp_auth(struct bt_conn *conn, u32_t passkey) {
+ conn->br.pairing_method = ssp_pair_method(conn);
- BT_DBG("");
-
- 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);
-
- 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;
-
- BT_DBG("");
-
- 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);
-
- 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);
-
- 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);
+ /*
+ * 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;
- }
-
- 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;
+ * 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));
-
- err = bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT_CANCEL, buf, &rsp);
- if (err) {
- return err;
- }
-
- rp = (void *)rsp->data;
-
- err = rp->status ? -EIO : 0;
-
- net_buf_unref(rsp);
+ 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;
+ }
+
+ rp = (void *)rsp->data;
+
+ err = rp->status ? -EIO : 0;
+
+ net_buf_unref(rsp);
+
+ 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;
- }
-
- 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;
-
- 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);
-
- if (bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE,
- buf, &rsp)) {
- return 0;
- }
-
- rp = (void *)rsp->data;
-
- key_size = rp->status ? 0 : rp->key_size;
-
- net_buf_unref(rsp);
-
- return key_size;
- }
-
- if (IS_ENABLED(CONFIG_BT_SMP)) {
- return conn->le.keys ? conn->le.keys->enc_size : 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 (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;
+ }
+
+ 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;
+ }
+
+ rp = (void *)rsp->data;
+
+ key_size = rp->status ? 0 : rp->key_size;
+
+ net_buf_unref(rsp);
+
+ return key_size;
+ }
+
+ if (IS_ENABLED(CONFIG_BT_SMP)) {
+ return conn->le.keys ? conn->le.keys->enc_size : 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 (bt_conn_get_io_capa() == BT_IO_NO_INPUT_OUTPUT &&
- conn->required_sec_level > BT_SECURITY_L2) {
- return -EINVAL;
- }
-
- return conn_auth(conn);
+ 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 (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;
+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);
+ /* 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;
- }
+ 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);
}
- BT_DBG("Successfully parsed %u byte L2CAP packet", buf->len);
+ conn->rx_len = (sizeof(*hdr) + len) - buf->len;
+ BT_DBG("rx_len %u", conn->rx_len);
+ if (conn->rx_len) {
+ conn->rx = buf;
+ return;
+ }
- bt_l2cap_recv(conn, buf);
+ 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;
+ }
+
+ 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 (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) {
+ struct bt_conn_tx *tx = k_fifo_get(&free_tx, K_NO_WAIT);
- if (tx) {
- return tx;
- }
-
- 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;
-
- 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_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;
- }
-
- net_buf_put(&conn->tx_queue, buf);
-#if defined(BFLB_BLE)
- k_sem_give(&g_poll_sem);
-#endif
- 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;
-
- 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);
-
- /* 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);
+ return tx;
+ }
+
+ 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;
+
+ 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_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;
+ }
+
+ net_buf_put(&conn->tx_queue, buf);
+#if defined(BFLB_BLE)
+ k_sem_give(&g_poll_sem);
+#endif
+ 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;
+
+ 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);
+
+ /* 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 {
- struct bt_conn_tx *tail_tx;
+ pending_no_cb = &conn->pending_no_cb;
+ }
- 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)++;
+ }
+ irq_unlock(key);
- (*pending_no_cb)++;
+ 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;
+ }
- 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 */
+ /* Create & enqueue first fragment */
+ frag = create_frag(conn, buf);
+ if (!frag) {
+ return false;
+ }
+
+ 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 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 void conn_cleanup(struct bt_conn *conn) {
+ struct net_buf *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);
- }
-
- 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);
- k_delayed_work_submit(&conn->update_work, K_NO_WAIT);
+ bt_conn_reset_rx_state(conn);
+
+ 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 (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;
- }
-
- 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;
+ if (!atomic_get(&conn->ref)) {
+ continue;
}
- return ev_count;
+ 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;
+ }
+
+ 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;
+ }
+
+ return ev_count;
}
-void bt_conn_process_tx(struct bt_conn *conn)
-{
- struct net_buf *buf;
+void bt_conn_process_tx(struct bt_conn *conn) {
+ 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;
- }
+ 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 */
- buf = net_buf_get(&conn->tx_queue, K_NO_WAIT);
- BT_ASSERT(buf);
- if (!send_buf(conn, buf)) {
- net_buf_unref(buf);
- }
+ /* Get next ACL packet for connection */
+ buf = net_buf_get(&conn->tx_queue, K_NO_WAIT);
+ 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;
- }
-
- node = sys_slist_get(&conn->tx_pending);
- irq_unlock(key);
-
- if (!node) {
- break;
- }
-
- 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);
-
- tx_free(tx);
-
- k_sem_give(bt_conn_get_pkts(conn));
+ 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);
+
+ if (!node) {
+ break;
+ }
+
+ 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);
+
+ tx_free(tx);
+
+ 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;
+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));
+ BT_DBG("%s -> %s", state2str(conn->state), state2str(state));
- if (conn->state == state) {
- BT_WARN("no transition");
- return;
+ 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);
}
- 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;
+ 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);
}
- /* 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);
+ break;
+ case BT_CONN_DISCONNECT:
+ break;
+ default:
+ BT_WARN("no valid (%u) state was set", state);
- 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;
- }
+ break;
+ }
}
-struct bt_conn *bt_conn_lookup_handle(u16_t handle)
-{
- int i;
+struct bt_conn *bt_conn_lookup_handle(u16_t handle) {
+ size_t i;
- 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;
- }
-
- if (conns[i].handle == handle) {
- return bt_conn_ref(&conns[i]);
- }
+ 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;
+ }
+
+ 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;
- }
-
- /* 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]);
- }
+ 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;
+ }
+
+ 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) {
+ size_t i;
- 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].id == id &&
- !bt_conn_addr_le_cmp(&conns[i], peer)) {
- return bt_conn_ref(&conns[i]);
- }
+ for (i = 0; i < ARRAY_SIZE(conns); i++) {
+ if (!atomic_get(&conns[i].ref)) {
+ continue;
}
- return NULL;
+ 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]);
+ }
+ }
+
+ 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) {
+ size_t i;
- 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 (peer && bt_conn_addr_le_cmp(&conns[i], peer)) {
- continue;
- }
-
- if (conns[i].state == state) {
- return bt_conn_ref(&conns[i]);
- }
+ for (i = 0; i < ARRAY_SIZE(conns); i++) {
+ if (!atomic_get(&conns[i].ref)) {
+ continue;
}
- return NULL;
+ if (conns[i].type != BT_CONN_TYPE_LE) {
+ continue;
+ }
+
+ if (peer && bt_conn_addr_le_cmp(&conns[i], peer)) {
+ continue;
+ }
+
+ if (conns[i].state == state) {
+ return bt_conn_ref(&conns[i]);
+ }
+ }
+
+ return NULL;
}
-void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data),
- void *data)
-{
- int i;
+void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data), void *data) {
+ size_t i;
- for (i = 0; i < ARRAY_SIZE(conns); i++) {
- if (!atomic_get(&conns[i].ref)) {
- continue;
- }
-
- if (!(conns[i].type & type)) {
- continue;
- }
-
- func(&conns[i], data);
+ for (i = 0; i < ARRAY_SIZE(conns); i++) {
+ if (!atomic_get(&conns[i].ref)) {
+ continue;
}
+
+ 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); }
+
+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));
+
+ return conn;
+}
+
+void bt_conn_unref(struct bt_conn *conn) {
+ atomic_dec(&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; }
+
+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;
}
-}
-
-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);
-
- BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref));
-
- return conn;
-}
-
-void bt_conn_unref(struct bt_conn *conn)
-{
- atomic_dec(&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;
-}
-
-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;
-#endif
- }
-
- return -EINVAL;
-}
-
-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++;
- }
-
- 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;
-
- 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;
-
- err = bt_hci_cmd_send_sync(BT_HCI_OP_DISCONNECT, buf, NULL);
- if (err) {
- return err;
- }
-
- bt_conn_set_state(conn, BT_CONN_DISCONNECT);
-
+ 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;
+#endif
+ }
+
+ return -EINVAL;
+}
+
+int bt_conn_get_remote_dev_info(struct bt_conn_info *info) {
+ int link_num = 0;
+
+ for (size_t 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;
+}
+
+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;
+ }
+
+ 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;
+ }
+
+ bt_conn_set_state(conn, BT_CONN_DISCONNECT);
+
+ 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);
+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;
+ /* 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);
}
- if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
- conn->role == BT_CONN_ROLE_MASTER) {
- 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) */
+
+ 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);
- }
+ /* User should unref connection object when receiving
+ * error in connection callback.
+ */
+ return bt_le_adv_stop();
+ }
+ return 0;
+ case BT_CONN_CONNECT:
+#if defined(CONFIG_BT_BREDR)
+ if (conn->type == BT_CONN_TYPE_BR) {
+ return bt_hci_connect_br_cancel(conn);
+ }
+#endif /* CONFIG_BT_BREDR */
- /* 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);
+ 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;
-}
-
-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:
-#if defined(CONFIG_BT_BREDR)
- 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;
- }
+ 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;
+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;
- }
+ if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
+ return NULL;
+ }
- if (!bt_le_conn_params_valid(param)) {
- return NULL;
- }
+ if (!bt_le_conn_params_valid(param)) {
+ return NULL;
+ }
- if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
- return NULL;
- }
+ if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
+ return NULL;
+ }
- if (IS_ENABLED(CONFIG_BT_WHITELIST) &&
- atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) {
- return NULL;
- }
+ if (IS_ENABLED(CONFIG_BT_WHITELIST) && atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_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;
- }
+ 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 (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;
- }
+ /* 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 (!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_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);
- }
- }
+ 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;
+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);
-
- 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);
+ 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;
}
+ }
- return conn;
+ conn = bt_conn_add_le(param->id, peer);
+ if (!conn) {
+ return NULL;
+ }
+
+start_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);
+
+ bt_conn_unref(conn);
+ return NULL;
+ }
+
+ 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;
+ }
- return buf;
+ reserve += sizeof(struct bt_hci_acl_hdr) + BT_BUF_RESERVE;
+ net_buf_reserve(buf, reserve);
+
+ 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;
- }
-
- 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 ||
-#if defined(CONFIG_BT_BREDR)
- cb->pincode_entry ||
-#endif
- cb->pairing_confirm)) {
- return -EINVAL;
- }
-
- bt_auth = cb;
+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;
+ }
+
+ /* 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 ||
+#endif
+ cb->pairing_confirm)) {
+ return -EINVAL;
+ }
+
+ 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->br.pairing_method == PASSKEY_INPUT) {
- return ssp_passkey_reply(conn, passkey);
- }
+ 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);
+ }
+ }
#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;
+ size_t 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);
+ net_buf_init(&acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), NULL);
#if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0
- net_buf_init(&frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE, NULL);
+ 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;
+#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 3e6f0fe7..180864e3 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,6 +1,9 @@
/** @file
* @brief Internal APIs for Bluetooth connection handling.
*/
+#ifndef BLE_STACK_HOST_CONN_INTERNAL_H_
+#define BLE_STACK_HOST_CONN_INTERNAL_H_
+
#include "addr.h"
#include "atomic.h"
#include "slist.h"
@@ -8,6 +11,12 @@
#include "work_q.h"
#include
#include
+#include "conn.h"
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
/*
* Copyright (c) 2015 Intel Corporation
*
@@ -324,3 +333,9 @@ void bt_conn_process_tx(struct bt_conn *conn);
*/
int bt_hci_get_conn_handle(const struct bt_conn *conn, u16_t *conn_handle);
#endif
+
+#ifdef __cplusplus
+};
+#endif
+
+#endif //BLE_STACK_HOST_CONN_INTERNAL_H_
\ No newline at end of file
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 b1eeb839..5bcf4b2e 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;
-
- 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);
-
- net_buf_unref(rsp);
- }
-
- 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;
- }
-
- return 0;
-}
-
-int prng_init(void)
-{
+ for (i = 0; i < (sizeof(seed) / 8); i++) {
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;
- }
+ struct net_buf *rsp;
ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
if (ret) {
- return ret;
+ return ret;
}
rp = (void *)rsp->data;
-
- ret = tc_hmac_prng_init(&prng, rp->rand, sizeof(rp->rand));
+ memcpy(&seed[i * 8], rp->rand, 8);
net_buf_unref(rsp);
+ }
- if (ret == TC_CRYPTO_FAIL) {
- BT_ERR("Failed to initialize PRNG");
- return -EIO;
- }
+ extra = k_uptime_get();
- /* re-seed is needed after init */
- return prng_reseed(&prng);
+ 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;
}
-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;
-#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;
- }
+int prng_init(void) {
+ struct bt_hci_rp_le_rand *rp;
+ struct net_buf *rsp;
+ int ret;
- ret = tc_hmac_prng_generate(buf, len, &prng);
- }
+ /* Check first that HCI_LE_Rand is supported */
+ if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 7)) {
+ return -ENOTSUP;
+ }
- if (ret == TC_CRYPTO_SUCCESS) {
- return 0;
- }
+ ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp);
+ if (ret) {
+ return ret;
+ }
+ rp = (void *)rsp->data;
+
+ ret = tc_hmac_prng_init(&prng, rp->rand, sizeof(rp->rand));
+
+ net_buf_unref(rsp);
+
+ if (ret == TC_CRYPTO_FAIL) {
+ BT_ERR("Failed to initialize PRNG");
return -EIO;
+ }
+
+ /* re-seed is needed after init */
+ return prng_reseed(&prng);
+}
+
+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;
+#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);
+ }
+
+ 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 70908c7f..f740dc18 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
*
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 e6ed08ae..ef9856cb 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,29 @@
* 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
-#include
-#include
#endif /* CONFIG_BT_GATT_CACHING */
-#include
#include
-#include
#include
#include
+#include
+#include
#if defined(BFLB_BLE)
#include "ble_config.h"
#include
@@ -48,14 +48,14 @@ extern u8_t event_flag;
#define LOG_MODULE_NAME bt_gatt
#include "log.h"
-#include "hci_core.h"
+#include "att_internal.h"
#include "conn_internal.h"
+#include "gatt_internal.h"
+#include "hci_core.h"
#include "keys.h"
#include "l2cap_internal.h"
-#include "att_internal.h"
-#include "smp.h"
#include "settings.h"
-#include "gatt_internal.h"
+#include "smp.h"
#define SC_TIMEOUT K_MSEC(10)
#define CCC_STORE_DELAY K_SECONDS(1)
@@ -66,8 +66,8 @@ 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)
@@ -86,91 +86,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));
+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;
+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);
+ 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));
+ 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 +161,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 +183,459 @@ 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) {
+ 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_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);
+}
+
+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 (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);
- }
+ 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_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));
+ }
}
+ }
- 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);
+ memset(cfg, 0, sizeof(*cfg));
}
-static void sc_clear(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));
- if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
- bool modified = false;
+ memset(&cfg->data, 0, sizeof(cfg->data));
- 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));
- }
- }
- }
-
- memset(cfg, 0, sizeof(*cfg));
+ if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
+ sc_store(cfg);
+ }
}
-static void sc_reset(struct gatt_sc_cfg *cfg)
-{
- BT_DBG("peer %s", bt_addr_le_str(&cfg->peer));
+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);
- memset(&cfg->data, 0, sizeof(cfg->data));
+ /* Check if inside existing range */
+ if (new_start >= *start && new_end <= *end) {
+ return false;
+ }
- if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
- sc_store(cfg);
- }
+ /* Update range */
+ if (*start > new_start) {
+ *start = new_start;
+ }
+
+ if (*end < new_end) {
+ *end = new_end;
+ }
+
+ return true;
}
-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 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;
- /* Check if inside existing range */
- if (new_start >= *start && new_end <= *end) {
- return false;
- }
+ BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(peer), start, end);
- /* Update range */
- if (*start > new_start) {
- *start = new_start;
- }
-
- if (*end < new_end) {
- *end = new_end;
- }
-
- 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;
-
- 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;
+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];
- }
+ 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;
+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;
+ /* 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;
- }
- }
+ 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;
+ }
}
+ }
- /* 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]);
- }
+ /* 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;
+ 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;
+ }
+
+ 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;
+ }
+
+ return BT_GATT_ITER_CONTINUE;
}
-static void db_hash_store(void)
-{
- int err;
+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);
- }
+ 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");
+ 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;
+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;
- }
+ if (tc_cmac_setup(&state.state, key, &sched) == TC_CRYPTO_FAIL) {
+ BT_ERR("Unable to setup AES CMAC");
+ return;
+ }
- bt_gatt_foreach_attr(0x0001, 0xffff, gen_hash_m, &state);
+ 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;
- }
+ 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));
+ /**
+ * 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)
-{
+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);
+ }
+
+ /* 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));
}
-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);
-
- 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;
-static void remove_cf_cfg(struct bt_conn *conn)
-{
- struct gatt_cf_cfg *cfg;
+ cfg = find_cf_cfg(conn);
+ if (!cfg) {
+ return;
+ }
- 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);
- }
+ /* 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 +648,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 +672,2905 @@ 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;
+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;
+ if (last_handle == 0 || svc->attrs[0].handle > last_handle) {
+ sys_slist_append(&db, &svc->node);
+ return;
+ }
+
+ /* 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;
}
- /* 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;
- }
+ 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;
+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;
- }
+ if (sys_slist_is_empty(&db)) {
+ handle = last_static_handle;
+ last_handle = 0;
+ goto populate;
+ }
- last = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node);
- handle = last->attrs[last->attr_count - 1].handle;
- last_handle = handle;
+ last = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node);
+ handle = last->attrs[last->attr_count - 1].handle;
+ last_handle = handle;
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;
- }
-
- BT_DBG("attr %p handle 0x%04x uuid %s perm 0x%02x",
- attrs, attrs->handle, bt_uuid_str(attrs->uuid),
- attrs->perm);
+ /* 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;
- }
+ if (bt_gatt_indicate(con, params)) {
+ /* No connections to indicate */
+ return;
+ }
}
#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);
+
+ 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 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;
+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;
}
-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 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];
+
+ if (!conn) {
+ continue;
}
- 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);
-
- for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) {
- struct bt_conn *conn = ccc_store->conn_list[i];
-
- 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 (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 (!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));
+ }
+ }
+ }
#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;
+ 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);
+ /* 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);
- }
+ /*
+ * 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;
-
- 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
- }
-
- 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)
-{
+ if ((attr != NULL) && (attr->read == bt_gatt_attr_read_chrc)) {
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;
+ 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
+ }
- return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
+ return handle;
}
-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;
+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;
- /* Stop if over the requested range */
- if (attr->handle > end_handle) {
- return BT_GATT_ITER_STOP;
- }
+ 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));
- /* Check if attribute handle is within range */
- if (attr->handle < start_handle) {
- return BT_GATT_ITER_CONTINUE;
- }
+ value_len = sizeof(pdu.properties) + sizeof(pdu.value_handle);
- /* Match attribute UUID if set */
- if (uuid && bt_uuid_cmp(uuid, attr->uuid)) {
- return BT_GATT_ITER_CONTINUE;
- }
+ 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;
+ }
- /* Match attribute user_data if set */
- if (attr_data && attr_data != attr->user_data) {
- return BT_GATT_ITER_CONTINUE;
- }
-
- *num_matches -= 1;
-
- result = func(attr, user_data);
-
- if (!*num_matches) {
- return BT_GATT_ITER_STOP;
- }
-
- return result;
+ return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len);
}
-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 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;
+ }
+
+ /* 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 user_data if set */
+ if (attr_data && attr_data != attr->user_data) {
+ return BT_GATT_ITER_CONTINUE;
+ }
+
+ *num_matches -= 1;
+
+ result = func(attr, user_data);
+
+ if (!*num_matches) {
+ return BT_GATT_ITER_STOP;
+ }
+
+ 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) {
#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;
- }
- }
-
- 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;
- }
- }
+ 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;
+ }
+ }
+ }
#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;
+ 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;
- }
+ 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;
+ for (i = 0; i < static_svc->attr_count; i++, handle++) {
+ struct bt_gatt_attr attr;
- memcpy(&attr, &static_svc->attrs[i],
- sizeof(attr));
+ memcpy(&attr, &static_svc->attrs[i], sizeof(attr));
- attr.handle = handle;
+ 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 (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 < 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;
}
- 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);
- }
-
- 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);
- }
+ 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;
-
- /* 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);
- }
- }
-
- /* 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;
- }
-
- conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
- if (!conn) {
- continue;
- }
-
- if (conn->state != BT_CONN_CONNECTED) {
- bt_conn_unref(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 (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);
- }
-
- bt_conn_unref(conn);
-
- if (err < 0) {
- return BT_GATT_ITER_STOP;
- }
-
- data->err = 0;
- }
+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;
+ }
+
+ 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;
+ }
+
+ conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer);
+ if (!conn) {
+ continue;
+ }
+
+ if (conn->state != BT_CONN_CONNECTED) {
+ bt_conn_unref(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 (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);
+ }
+
+ bt_conn_unref(conn);
+
+ if (err < 0) {
+ return BT_GATT_ITER_STOP;
+ }
+
+ 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;
+ attr = params->attr;
- if (conn && conn->state != BT_CONN_CONNECTED) {
- return -ENOTCONN;
+ 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;
+ }
+
+ /* Lookup UUID if it was given */
+ if (params->uuid) {
+ attr = NULL;
+
+ 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;
+ }
+ }
+
+ /* 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;
+
+ if (!(chrc->properties & BT_GATT_CHRC_NOTIFY)) {
+ return -EINVAL;
}
- /* Lookup UUID if it was given */
- if (params->uuid) {
- attr = NULL;
+ handle = bt_gatt_attr_value_handle(attr);
+ }
- 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 (conn) {
+ return gatt_notify(conn, handle, params);
+ }
- /* 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;
+ data.err = -ENOTCONN;
+ data.type = BT_GATT_CCC_NOTIFY;
+ data.nfy_params = params;
- if (!(chrc->properties & BT_GATT_CHRC_NOTIFY)) {
- return -EINVAL;
- }
+ bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, notify_cb, &data);
- handle = bt_gatt_attr_value_handle(attr);
- }
-
- if (conn) {
- return gatt_notify(conn, handle, params);
- }
-
- data.err = -ENOTCONN;
- data.type = BT_GATT_CCC_NOTIFY;
- data.nfy_params = params;
-
- bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1,
- notify_cb, &data);
-
- return data.err;
+ return data.err;
}
-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;
+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;
- __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;
+ attr = params->attr;
- if (conn && conn->state != BT_CONN_CONNECTED) {
- return -ENOTCONN;
+ 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;
+ }
+
+ /* Lookup UUID if it was given */
+ if (params->uuid) {
+ attr = NULL;
+
+ 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;
+ }
+ }
+
+ /* 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;
}
- /* Lookup UUID if it was given */
- if (params->uuid) {
- attr = NULL;
+ handle = bt_gatt_attr_value_handle(params->attr);
+ }
- 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 (conn) {
+ return gatt_indicate(conn, handle, params);
+ }
- /* 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;
+ data.err = -ENOTCONN;
+ data.type = BT_GATT_CCC_INDICATE;
+ data.ind_params = params;
- if (!(chrc->properties & BT_GATT_CHRC_INDICATE)) {
- return -EINVAL;
- }
+ bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, notify_cb, &data);
- handle = bt_gatt_attr_value_handle(params->attr);
- }
-
- if (conn) {
- return gatt_indicate(conn, handle, 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);
-
- 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;
+ }
+
+ 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_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;
- }
- }
-
- 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;
- }
-#else
- return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
-#endif /* CONFIG_BT_SMP */
+ if (!conn->encrypt) {
+ return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION;
}
+#else
+ 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;
- }
-
- 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;
- }
-
- /* 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;
- }
- }
-
- 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;
- }
- }
+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;
+ }
+
+ /* 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;
+ }
+ }
+
+ 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;
- }
-
- ccc = attr->user_data;
-
- /* If already disabled skip */
- if (!ccc->value) {
- return BT_GATT_ITER_CONTINUE;
- }
-
- /* Checking if all values are disabled */
- value_used = false;
-
- for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
- struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
-
- /* Ignore configurations with disabled value */
- if (!cfg->value) {
- continue;
- }
-
- 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);
- }
- }
- }
-
- /* 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);
- }
-
- BT_DBG("ccc %p reseted", ccc);
- }
+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;
+ }
+
+ ccc = attr->user_data;
+
+ /* If already disabled skip */
+ if (!ccc->value) {
+ return BT_GATT_ITER_CONTINUE;
+ }
+
+ /* Checking if all values are disabled */
+ value_used = false;
+
+ for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) {
+ struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i];
+
+ /* Ignore configurations with disabled value */
+ if (!cfg->value) {
+ continue;
+ }
+
+ 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);
+ }
+ }
+ }
+
+ /* 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);
+ }
+
+ BT_DBG("ccc %p reseted", ccc);
+ }
+
+ return BT_GATT_ITER_CONTINUE;
}
-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;
+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;
- __ASSERT(conn, "invalid parameter\n");
- __ASSERT(attr, "invalid parameter\n");
-
- if (conn->state != BT_CONN_CONNECTED) {
- return false;
- }
-
- /* 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;
-
- if (!(chrc->properties &
- (BT_GATT_CHRC_NOTIFY | BT_GATT_CHRC_INDICATE))) {
- /* Characteristic doesn't support subscription */
- return false;
- }
-
- attr = bt_gatt_attr_next(attr);
- }
-
- /* 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 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;
- }
- }
+ __ASSERT(conn, "invalid parameter\n");
+ __ASSERT(attr, "invalid parameter\n");
+ if (conn->state != BT_CONN_CONNECTED) {
return false;
+ }
+
+ /* 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;
+
+ if (!(chrc->properties & (BT_GATT_CHRC_NOTIFY | BT_GATT_CHRC_INDICATE))) {
+ /* Characteristic doesn't support subscription */
+ return false;
+ }
+
+ attr = bt_gatt_attr_next(attr);
+ }
+
+ /* 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 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;
}
#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;
+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);
+ 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 (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;
+ SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) {
+ if (bt_conn_addr_le_cmp(conn, ¶ms->_peer) || handle != params->value_handle) {
+ continue;
}
- /* 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);
-
- 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;
- }
-
- 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;
- }
+ if (params->notify(conn, params, data, length) == BT_GATT_ITER_STOP) {
+ bt_gatt_unsubscribe(conn, params);
}
+ }
}
-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 update_subscription(struct bt_conn *conn, struct bt_gatt_subscribe_params *params) {
+ if (params->_peer.type == BT_ADDR_LE_PUBLIC) {
+ return;
+ }
- params->func(conn, err, params);
+ /* Update address */
+ bt_addr_le_copy(¶ms->_peer, &conn->le.dst);
}
-#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;
- __ASSERT(conn, "invalid parameter\n");
- __ASSERT(params && params->func, "invalid parameters\n");
+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);
- if (conn->state != BT_CONN_CONNECTED) {
- return -ENOTCONN;
+ 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;
}
- buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req));
- if (!buf) {
- return -ENOMEM;
- }
-
- mtu = mtu_size;
-
-#if defined(CONFIG_BLE_AT_CMD)
- set_mtu_size(mtu);
-#endif
-
- BT_DBG("Client MTU %u", 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);
-}
-#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;
-
- __ASSERT(conn, "invalid parameter\n");
- __ASSERT(params && params->func, "invalid parameters\n");
-
- 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;
- }
-
- mtu = BT_ATT_MTU;
-
- BT_DBG("Client MTU %u", 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);
-}
-
-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++;
+ 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 {
- goto done;
+ update_subscription(conn, params);
+ prev = ¶ms->node;
}
+ }
+}
- /* Stop if over the range or the requests */
- if (params->start_handle > params->end_handle) {
- goto done;
- }
+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);
+}
+#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;
+
+ __ASSERT(conn, "invalid parameter\n");
+ __ASSERT(params && params->func, "invalid parameters\n");
+
+ 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;
+ }
+
+ mtu = mtu_size;
+
+#if defined(CONFIG_BLE_AT_CMD)
+ set_mtu_size(mtu);
+#endif
+
+ BT_DBG("Client MTU %u", 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);
+}
+#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;
+
+ __ASSERT(conn, "invalid parameter\n");
+ __ASSERT(params && params->func, "invalid parameters\n");
+
+ 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;
+ }
+
+ mtu = BT_ATT_MTU;
+
+ BT_DBG("Client MTU %u", 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);
+}
+
+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;
+ }
+
+ /* 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;
- }
-
-done:
- params->func(conn, NULL, params);
-}
-
-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);
-
- 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;
-
- 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);
-
- 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;
-
- attr.handle = start_handle;
- attr.user_data = &value;
-
- if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
- return;
- }
- }
-
- /* Stop if could not parse the whole PDU */
- if (length > 0) {
- goto done;
- }
-
- gatt_discover_next(conn, end_handle, params);
-
+ /* Discover next range */
+ if (!bt_gatt_discover(conn, params)) {
return;
+ }
+
done:
- params->func(conn, NULL, params);
+ params->func(conn, NULL, params);
}
-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;
+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;
- buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_REQ, sizeof(*req));
- if (!buf) {
- return -ENOMEM;
- }
+ BT_DBG("err 0x%02x", err);
- 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 (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;
+
+ 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);
if (params->type == BT_GATT_DISCOVER_PRIMARY) {
- uuid = BT_UUID_GATT_PRIMARY;
+ attr.uuid = BT_UUID_GATT_PRIMARY;
} else {
- uuid = BT_UUID_GATT_SECONDARY;
+ attr.uuid = BT_UUID_GATT_SECONDARY;
}
- req->type = sys_cpu_to_le16(BT_UUID_16(uuid)->val);
+ value.end_handle = end_handle;
+ value.uuid = params->uuid;
- BT_DBG("uuid %s start_handle 0x%04x end_handle 0x%04x",
- bt_uuid_str(params->uuid), params->start_handle,
- params->end_handle);
+ attr.handle = start_handle;
+ attr.user_data = &value;
- 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 (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
+ return;
}
+ }
- return gatt_send(conn, buf, gatt_find_type_rsp, params, NULL);
+ /* Stop if could not parse the whole PDU */
+ if (length > 0) {
+ goto done;
+ }
+
+ gatt_discover_next(conn, end_handle, params);
+
+ return;
+done:
+ params->func(conn, NULL, params);
}
-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;
+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;
- if (length != 16U) {
- BT_ERR("Invalid data len %u", length);
- params->func(conn, NULL, params);
- return;
+ 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;
+ }
+
+ return gatt_send(conn, buf, gatt_find_type_rsp, params, NULL);
+}
+
+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;
+ }
+
+ 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;
+}
+
+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;
+
+ 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->_included.start_handle);
+
+ BT_DBG("handle 0x%04x", params->_included.start_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;
+ }
+
+ /* 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;
}
- 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);
+ /* 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",
- params->_included.attr_handle,
- bt_uuid_str(&u.uuid), value.start_handle, value.end_handle);
+ 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;
+ continue;
}
- attr = (&(struct bt_gatt_attr){
- .uuid = BT_UUID_GATT_INCLUDE,
- .user_data = &value,
+ attr = (&(struct bt_gatt_attr){
+ .uuid = BT_UUID_GATT_INCLUDE,
+ .user_data = &value,
});
- attr->handle = params->_included.attr_handle;
+ attr->handle = handle;
if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) {
- return;
+ return 0;
}
-next:
- gatt_discover_next(conn, params->start_handle, 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;
-
- 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->_included.start_handle);
-
- BT_DBG("handle 0x%04x", params->_included.start_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;
- }
-
- /* 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);
-
- /* 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;
-
- 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;
}
-#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, \
- }))
+#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;
+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;
+ /* 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;
+ 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;
+ }
- 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;
- }
-
- 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;
+}
+
+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);
+
+ if (err) {
params->func(conn, NULL, params);
- return 0;
+ return;
+ }
+
+ 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;
+ }
+
+ gatt_discover_next(conn, handle, params);
}
-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 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;
- BT_DBG("err 0x%02x", err);
+ buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req));
+ if (!buf) {
+ return -ENOMEM;
+ }
- if (err) {
- params->func(conn, NULL, params);
- return;
- }
+ 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) {
- handle = parse_include(conn, pdu, params, length);
- } else {
- handle = parse_characteristic(conn, pdu, params, length);
- }
+ 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 (!handle) {
- return;
- }
+ BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, params->end_handle);
- gatt_discover_next(conn, handle, params);
+ return gatt_send(conn, buf, gatt_read_type_rsp, params, NULL);
}
-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 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;
- buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req));
- if (!buf) {
- return -ENOMEM;
+ /* 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;
+ }
+
+ /* 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;
}
- 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);
+ end_handle = sys_le16_to_cpu(data->end_handle);
+ if (!end_handle || end_handle < start_handle) {
+ goto done;
}
- 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);
-}
-
-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;
+ 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;
}
- /* 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;
- }
-
- value.end_handle = end_handle;
- value.uuid = &u.uuid;
-
- attr.handle = start_handle;
- attr.user_data = &value;
-
- if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
- return 0;
- }
- }
-
- /* Whole PDU read without error */
- if (length == 0U && end_handle) {
- return end_handle;
- }
-
-done:
- params->func(conn, NULL, params);
- return 0;
-}
-
-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;
-
- BT_DBG("err 0x%02x", err);
-
- if (err) {
- params->func(conn, NULL, params);
- return;
- }
-
- handle = parse_service(conn, pdu, params, length);
- if (!handle) {
- 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);
+ 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) {
- net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_PRIMARY)->val);
+ attr.uuid = BT_UUID_GATT_PRIMARY;
} else {
- net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_SECONDARY)->val);
+ attr.uuid = BT_UUID_GATT_SECONDARY;
}
- BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle,
- params->end_handle);
+ value.end_handle = end_handle;
+ value.uuid = &u.uuid;
- return gatt_send(conn, buf, gatt_read_group_rsp, params, NULL);
-}
+ attr.handle = start_handle;
+ attr.user_data = &value;
-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;
+ if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) {
+ return 0;
}
+ }
- /* 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;
-
- 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;
- }
- }
-
- 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;
- }
- }
-
- gatt_discover_next(conn, handle, params);
-
- return;
+ /* Whole PDU read without error */
+ if (length == 0U && end_handle) {
+ return end_handle;
+ }
done:
+ params->func(conn, NULL, params);
+ return 0;
+}
+
+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;
+
+ BT_DBG("err 0x%02x", err);
+
+ if (err) {
params->func(conn, NULL, params);
+ return;
+ }
+
+ handle = parse_service(conn, pdu, params, length);
+ if (!handle) {
+ return;
+ }
+
+ gatt_discover_next(conn, handle, params);
}
-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_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_FIND_INFO_REQ, sizeof(*req));
- if (!buf) {
- return -ENOMEM;
- }
+ 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);
+ 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);
+ 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);
+ }
- return gatt_send(conn, buf, gatt_find_info_rsp, params, NULL);
+ 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);
}
-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");
+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;
- if (conn->state != BT_CONN_CONNECTED) {
- return -ENOTCONN;
+ 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;
+
+ info.i16 = pdu;
+ handle = sys_le16_to_cpu(info.i16->handle);
+
+ if (skip) {
+ skip = false;
+ continue;
}
- 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;
- }
+ 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;
+ }
+ }
+
+ 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;
+ }
+ }
+
+ gatt_discover_next(conn, handle, params);
+
+ return;
+
+done:
+ params->func(conn, NULL, params);
+}
+
+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;
+ }
+
+ 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);
+
+ 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");
+
+ 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)
- __attribute__((fallthrough));
+ __attribute__((fallthrough));
#endif
- /* Fallthrough. */
- case BT_GATT_DISCOVER_ATTRIBUTE:
- return gatt_find_info(conn, params);
- default:
- BT_ERR("Invalid discovery type: %u", params->type);
- }
+ /* Fallthrough. */
+ case BT_GATT_DISCOVER_ATTRIBUTE:
+ return gatt_find_info(conn, params);
+ default:
+ BT_ERR("Invalid discovery type: %u", params->type);
+ }
- return -EINVAL;
+ return -EINVAL;
}
-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;
+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;
- /* 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;
+ /* 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;
- handle = sys_le16_to_cpu(data->handle);
+ handle = sys_le16_to_cpu(data->handle);
- /* Handle 0 is invalid */
- if (!handle) {
- BT_ERR("Invalid handle");
- return;
- }
-
- len = rsp->len > length ? length - 2 : rsp->len - 2;
-
- BT_DBG("handle 0x%04x len %u value %u", handle, rsp->len, len);
-
- /* Update start_handle */
- params->by_uuid.start_handle = handle;
-
- if (params->func(conn, 0, params, data->value, len) ==
- BT_GATT_ITER_STOP) {
- return;
- }
-
- /* Check if long attribute */
- if (rsp->len > length) {
- break;
- }
-
- /* 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;
- }
-
- params->by_uuid.start_handle++;
+ /* Handle 0 is invalid */
+ if (!handle) {
+ BT_ERR("Invalid handle");
+ return;
}
- /* Continue reading the attributes */
- if (bt_gatt_read(conn, params) < 0) {
- params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
+ len = rsp->len > length ? length - 2 : rsp->len - 2;
+
+ BT_DBG("handle 0x%04x len %u value %u", handle, rsp->len, len);
+
+ /* Update start_handle */
+ params->by_uuid.start_handle = handle;
+
+ if (params->func(conn, 0, params, data->value, len) == BT_GATT_ITER_STOP) {
+ return;
}
+
+ /* Check if long attribute */
+ if (rsp->len > length) {
+ break;
+ }
+
+ /* 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;
+ }
+
+ params->by_uuid.start_handle++;
+ }
+
+ /* Continue reading the attributes */
+ if (bt_gatt_read(conn, params) < 0) {
+ params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0);
+ }
}
-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;
+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;
- 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;
+ }
- if (!params->handle_count) {
- parse_read_by_uuid(conn, params, pdu, length);
- return;
- }
+ if (!params->handle_count) {
+ parse_read_by_uuid(conn, params, pdu, length);
+ return;
+ }
- if (params->func(conn, 0, params, pdu, length) == BT_GATT_ITER_STOP) {
- return;
- }
+ 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;
- }
+ /*
+ * 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;
+ }
- params->single.offset += length;
+ 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);
- }
+ /* 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)
-{
+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;
+
+ __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;
+ }
+
+ /* 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);
-}
-#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;
+ buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, sizeof(*req) + params->length);
+ if (!buf) {
+ return -ENOMEM;
+ }
- __ASSERT(conn, "invalid parameters\n");
- __ASSERT(params && params->func, "invalid parameters\n");
- __ASSERT(params->handle, "invalid parameters\n");
+ 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);
- if (conn->state != BT_CONN_CONNECTED) {
- return -ENOTCONN;
- }
+ BT_DBG("handle 0x%04x length %u", params->handle, params->length);
- /* 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;
- }
-
- 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);
-
- 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;
+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;
- }
+ 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);
+ 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);
+ BT_DBG("handle 0x%04x value 0x%04x", handle, value);
- atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
+ atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING);
- return gatt_send(conn, buf, func, params, NULL);
+ 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;
+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");
+ __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");
- if (conn->state != BT_CONN_CONNECTED) {
- return -ENOTCONN;
+ if (conn->state != BT_CONN_CONNECTED) {
+ return -ENOTCONN;
+ }
+
+ /* Lookup existing subscriptions */
+ SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, tmp, node) {
+ /* Fail if entry already exists */
+ if (tmp == params) {
+ return -EALREADY;
}
- /* Lookup existing subscriptions */
- SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, tmp, node)
- {
- /* Fail if entry already exists */
- if (tmp == params) {
- return -EALREADY;
- }
+ /* 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;
+ }
+ }
- /* 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;
- }
+ /* Skip write if already subscribed */
+ if (!has_subscription) {
+ int err;
+
+ 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;
}
- /* Skip write if already subscribed */
- if (!has_subscription) {
- int err;
-
- err = gatt_write_ccc(conn, params->ccc_handle, params->value,
- gatt_write_ccc_rsp, params);
- if (err) {
- return 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;
}
+ }
- /*
- * Add subscription before write complete as some implementation were
- * reported to send notification before reply to CCC write.
- */
- gatt_subscription_add(conn, params);
+ if (!found) {
+ return -EINVAL;
+ }
+ if (has_subscription) {
+ /* Notify with NULL data to complete unsubscribe */
+ params->notify(conn, params, NULL, 0);
return 0;
+ }
+
+ params->value = 0x0000;
+
+ return gatt_write_ccc(conn, params->ccc_handle, params->value, gatt_write_ccc_rsp, params);
}
-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;
+void bt_gatt_cancel(struct bt_conn *conn, void *params) { bt_att_req_cancel(conn, params); }
- __ASSERT(conn, "invalid parameters\n");
- __ASSERT(params, "invalid parameters\n");
+static void add_subscriptions(struct bt_conn *conn) {
+ struct bt_gatt_subscribe_params *params;
- if (conn->state != BT_CONN_CONNECTED) {
- return -ENOTCONN;
+ /* Lookup existing subscriptions */
+ SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, params, node) {
+ if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) {
+ continue;
}
- /* 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;
- }
-
- /* 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 (!found) {
- return -EINVAL;
- }
-
- if (has_subscription) {
- /* Notify with NULL data to complete unsubscribe */
- params->notify(conn, params, NULL, 0);
- return 0;
- }
-
- params->value = 0x0000;
-
- return gatt_write_ccc(conn, params->ccc_handle, params->value,
- gatt_write_ccc_rsp, params);
-}
-
-void bt_gatt_cancel(struct bt_conn *conn, void *params)
-{
- bt_att_req_cancel(conn, params);
-}
-
-static void add_subscriptions(struct bt_conn *conn)
-{
- struct bt_gatt_subscribe_params *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);
- }
+ /* 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;
+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;
+ /* Check if attribute is a CCC */
+ if (attr->write != bt_gatt_attr_write_ccc) {
+ return BT_GATT_ITER_CONTINUE;
+ }
+
+ ccc = attr->user_data;
+
+ /* 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;
+ }
- ccc = attr->user_data;
+ BT_DBG("Restoring CCC: handle 0x%04x value 0x%04x", load->entry->handle, load->entry->value);
- /* 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);
-
- 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);
-#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);
- }
-
- 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 < 0) {
- BT_ERR("Failed to decode value (err %d)", len);
- return len;
- }
-
- 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;
- }
-#endif
-
- 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));
+ err = bt_settings_get_bin(key, (u8_t *)ccc_store, CCC_STORE_MAX, &len);
+ if (err) {
+ return err;
}
- return 0;
+ 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);
+ }
+
+ 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 < 0) {
+ BT_ERR("Failed to decode value (err %d)", len);
+ return len;
+ }
+
+ 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;
+ }
+#endif
+
+ 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));
+ }
+
+ return 0;
}
#if !defined(BFLB_BLE)
@@ -3994,23 +3581,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));
+ 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;
- }
-
- 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 +3607,527 @@ 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);
+ 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);
- }
+ /* 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;
- }
-
- /* 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);
-
- return false;
-#else
+ cfg = find_cf_cfg(conn);
+ if (!cfg || !CF_ROBUST_CACHING(cfg)) {
return true;
+ }
+
+ if (atomic_test_bit(cfg->flags, CF_CHANGE_AWARE)) {
+ 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);
+
+ return false;
+#else
+ 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;
+ 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);
+ 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];
+ 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);
- }
+ 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 (!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;
-
- /* Check if attribute is a CCC */
- if (attr->write != bt_gatt_attr_write_ccc) {
- return BT_GATT_ITER_CONTINUE;
- }
-
- 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;
- }
-
- 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++;
+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;
-}
+ }
-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;
-
- bt_gatt_foreach_attr(0x0001, 0xffff, ccc_save, &save);
-
- 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);
- }
-
- 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;
- }
-
- 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;
-}
-
-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;
- }
-
- 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));
- }
+ 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;
+ }
+
+ 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++;
+
+ 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,
- };
+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;
- if (id) {
- char id_str[4];
+ save.addr_with_id.addr = addr;
+ save.addr_with_id.id = id;
+ save.count = 0;
- 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, ccc_save, &save);
+
+ 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);
+ }
+
+ 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;
+ }
+
+ 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_gatt_foreach_attr(0x0001, 0xffff, remove_peer_from_attr,
- &addr_with_id);
+ return 0;
+}
- return settings_delete(key);
+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;
+ }
+
+ 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));
+ }
+
+ 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,
+ };
+
+ 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);
+ }
+
+ bt_gatt_foreach_attr(0x0001, 0xffff, remove_peer_from_attr, &addr_with_id);
+
+ 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;
+ 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);
+ 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;
+ }
+
+ settings_name_next(name, &next);
+
+ 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;
}
- err = bt_settings_decode_key(name, &addr);
- if (err) {
- BT_ERR("Unable to decode address %s", log_strdup(name));
- return -EINVAL;
+ 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);
- settings_name_next(name, &next);
+ BT_DBG("Restored SC for %s", bt_addr_le_str(&addr));
+ } else if (cfg) {
+ /* Clear configuration */
+ memset(cfg, 0, sizeof(*cfg));
- if (!next) {
- id = BT_ID_DEFAULT;
- } else {
- id = strtol(next, NULL, 10);
- }
+ BT_DBG("Removed SC for %s", bt_addr_le_str(&addr));
+ }
- 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);
- }
-
- 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("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 +4136,97 @@ 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;
}
- 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);
+ }
- BT_DBG("Read CF: len %d", len);
- } else {
- clear_cf_cfg(cfg);
- }
+ BT_DBG("Restored CF for %s", bt_addr_le_str(&addr));
- BT_DBG("Restored CF for %s", bt_addr_le_str(&addr));
-
- return 0;
+ 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);
- }
-
- /* 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: ");
-
- /**
- * 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();
+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;
+ }
+
+ 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);
+
+ /* Hash did not match overwrite with current hash */
+ db_hash_store();
+
+ 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 */
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 f6bbf28a..bfcdc05b 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,42 +7,42 @@
* 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